]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/AppSession.pm
allow max_requests to be infinite on the server side
[OpenSRF.git] / src / perlmods / OpenSRF / AppSession.pm
1 package OpenSRF::AppSession;
2 use OpenSRF::DOM;
3 #use OpenSRF::DOM::Element::userAuth;
4 use OpenSRF::DomainObject::oilsMessage;
5 use OpenSRF::DomainObject::oilsMethod;
6 use OpenSRF::DomainObject::oilsResponse qw/:status/;
7 use OpenSRF::Transport::PeerHandle;
8 use OpenSRF::Utils::Logger qw(:level);
9 use OpenSRF::Utils::SettingsClient;
10 use OpenSRF::Utils::Config;
11 use OpenSRF::EX;
12 use OpenSRF;
13 use Exporter;
14 use base qw/Exporter OpenSRF/;
15 use Time::HiRes qw( time usleep );
16 use warnings;
17 use strict;
18
19 our @EXPORT_OK = qw/CONNECTING INIT_CONNECTED CONNECTED DISCONNECTED CLIENT SERVER/;
20 our %EXPORT_TAGS = ( state => [ qw/CONNECTING INIT_CONNECTED CONNECTED DISCONNECTED/ ],
21                  endpoint => [ qw/CLIENT SERVER/ ],
22 );
23
24 my $logger = "OpenSRF::Utils::Logger";
25
26 our %_CACHE;
27 our @_CLIENT_CACHE;
28 our @_RESEND_QUEUE;
29
30 sub kill_client_session_cache {
31         for my $session ( @_CLIENT_CACHE ) {
32                 $session->kill_me;
33         }
34 }
35
36 sub CONNECTING { return 3 };
37 sub INIT_CONNECTED { return 4 };
38 sub CONNECTED { return 1 };
39 sub DISCONNECTED { return 2 };
40
41 sub CLIENT { return 2 };
42 sub SERVER { return 1 };
43
44 sub find {
45         return undef unless (defined $_[1]);
46         return $_CACHE{$_[1]} if (exists($_CACHE{$_[1]}));
47 }
48
49 sub find_client {
50         my( $self, $app ) = @_;
51         $logger->debug( "Client Cache contains: " .scalar(@_CLIENT_CACHE), INTERNAL );
52         my ($client) = grep { $_->[0] eq $app and $_->[1] == 1 } @_CLIENT_CACHE;
53         $client->[1] = 0;
54         return $client->[2];
55 }
56
57 sub transport_connected {
58         my $self = shift;
59         if( ! exists $self->{peer_handle} || ! $self->{peer_handle} ) {
60                 return 0;
61         }
62         return $self->{peer_handle}->tcp_connected();
63 }
64
65 # ----------------------------------------------------------------------------
66 # Clears the transport buffers
67 # call this if you are not through with the sesssion, but you want 
68 # to have a clean slate.  You shouldn't have to call this if
69 # you are correctly 'recv'ing all of the data from a request.
70 # however, if you don't want all of the data, this will
71 # slough off any excess
72 #  * * Note: This will delete data for all sessions using this transport
73 # handle.  For example, all client sessions use the same handle.
74 # ----------------------------------------------------------------------------
75 sub buffer_reset {
76
77         my $self = shift;
78         if( ! exists $self->{peer_handle} || ! $self->{peer_handle} ) { 
79                 return 0;
80         }
81         $self->{peer_handle}->buffer_reset();
82 }
83
84
85 sub client_cache {
86         my $self = shift;
87         push @_CLIENT_CACHE, [ $self->app, 1, $self ];
88 }
89
90 # when any incoming data is received, this method is called.
91 sub server_build {
92         my $class = shift;
93         $class = ref($class) || $class;
94
95         my $sess_id = shift;
96         my $remote_id = shift;
97         my $service = shift;
98
99         return undef unless ($sess_id and $remote_id and $service);
100
101         my $config_client = OpenSRF::Utils::SettingsClient->new();
102         
103         if ( my $thingy = $class->find($sess_id) ) {
104                 $thingy->remote_id( $remote_id );
105                 $logger->debug( "AppSession returning existing session $sess_id", DEBUG );
106                 return $thingy;
107         } else {
108                 $logger->debug( "AppSession building new server session $sess_id", DEBUG );
109         }
110
111         if( $service eq "client" ) {
112                 #throw OpenSRF::EX::PANIC ("Attempting to build a client session as a server" .
113                 #       " Session ID [$sess_id], remote_id [$remote_id]");
114                 $logger->debug("Attempting to build a client session as ".
115                                 "a server Session ID [$sess_id], remote_id [$remote_id]", ERROR );
116         }
117
118
119         #my $max_requests = $conf->$service->max_requests;
120         my $max_requests        = $config_client->config_value("apps",$service,"max_requests");
121         $logger->debug( "Max Requests for $service is $max_requests", INTERNAL );# if $max_requests;
122
123         $logger->transport( "AppSession creating new session: $sess_id", INTERNAL );
124
125         my $self = bless { recv_queue  => [],
126                            request_queue  => [],
127                            requests  => 0,
128                            session_data  => {},
129                            callbacks  => { death => [], disconnect => [] },
130                            endpoint    => SERVER,
131                            state       => CONNECTING, 
132                            session_id  => $sess_id,
133                            remote_id    => $remote_id,
134                                 peer_handle => OpenSRF::Transport::PeerHandle->retrieve($service),
135                                 max_requests => $max_requests,
136                                 session_threadTrace => 0,
137                                 service => $service,
138                          } => $class;
139
140         return $_CACHE{$sess_id} = $self;
141 }
142
143 sub session_data {
144         my $self = shift;
145         my ($name, $datum) = @_;
146
147         $self->{session_data}->{$name} = $datum if (defined $datum);
148         return $self->{session_data}->{$name};
149 }
150
151 sub service { return shift()->{service}; }
152
153 sub continue_request {
154         my $self = shift;
155         $self->{'requests'}++;
156         return 1 if (!$self->{'max_requests'});
157         return $self->{'requests'} <= $self->{'max_requests'} ? 1 : 0;
158 }
159
160 sub last_sent_payload {
161         my( $self, $payload ) = @_;
162         if( $payload ) {
163                 return $self->{'last_sent_payload'} = $payload;
164         }
165         return $self->{'last_sent_payload'};
166 }
167
168 sub last_sent_type {
169         my( $self, $type ) = @_;
170         if( $type ) {
171                 return $self->{'last_sent_type'} = $type;
172         }
173         return $self->{'last_sent_type'};
174 }
175
176 sub get_app_targets {
177         my $app = shift;
178
179 #       my $config_client = OpenSRF::Utils::SettingsClient->new();
180
181         my $conf = OpenSRF::Utils::Config->current;
182         my $router_name = $conf->bootstrap->router_name;
183         my $routers = $conf->bootstrap->domains;
184
185         unless($router_name and $routers) {
186                 throw OpenSRF::EX::Config 
187                         ("Missing router config information 'router_name' and 'routers'");
188         }
189
190         my @targets;
191         for my $router (@$routers) {
192                 push @targets, "$router_name\@$router/$app";
193         }
194
195         return @targets;
196
197 =head comment
198         if( $app eq "settings" ) { # we have to load from the bootstrap config file
199
200                 if(!$conf) { die("No transport target for $app!"); }
201                 $targets = $conf->targets->$app || die("No transport target for $app!");
202
203         } else {
204                 $targets =  $config_client->config_value("apps",$app,"transport_targets", "router_target");
205                 if( !ref($targets) ) { $targets = [ $targets ]; }
206         }
207
208         return @$targets;
209 =cut
210 }
211
212 # When we're a client and we want to connect to a remote service
213 # create( $app, username => $user, secret => $passwd );
214 #    OR
215 # create( $app, sysname => $user, secret => $shared_secret );
216 sub create {
217         my $class = shift;
218         $class = ref($class) || $class;
219
220         my $app = shift;
221
222         if( my $thingy = OpenSRF::AppSession->find_client( $app ) ) {
223                         $logger->debug( "AppSession returning existing client session for $app", DEBUG );
224                         return $thingy;
225         } else {
226                 $logger->debug( "AppSession creating new client session for $app", DEBUG );
227         }
228
229
230         my $sess_id = time . rand( $$ );
231         while ( $class->find($sess_id) ) {
232                 $sess_id = time . rand( $$ );
233         }
234
235         my ($r_id) = get_app_targets($app);
236
237         my $peer_handle = OpenSRF::Transport::PeerHandle->retrieve("client"); 
238         if( ! $peer_handle ) {
239                 $peer_handle = OpenSRF::Transport::PeerHandle->retrieve("system_client");
240         }
241
242         my $self = bless { app_name    => $app,
243                                 #client_auth => $auth,
244                            #recv_queue  => [],
245                            request_queue  => [],
246                            endpoint    => CLIENT,
247                            state       => DISCONNECTED,#since we're init'ing
248                            session_id  => $sess_id,
249                            remote_id   => $r_id,
250                            api_level   => 1,
251                            orig_remote_id   => $r_id,
252                                 peer_handle => $peer_handle,
253                                 session_threadTrace => 0,
254                          } => $class;
255
256         $self->client_cache();
257         $_CACHE{$sess_id} = $self;
258         return $self->find_client( $app );
259 }
260
261 sub api_level {
262         return shift()->{api_level};
263 }
264
265 sub app {
266         return shift()->{app_name};
267 }
268
269 sub reset {
270         my $self = shift;
271         $self->remote_id($$self{orig_remote_id});
272 }
273
274 # 'connect' can be used as a constructor if called as a class method,
275 # or used to connect a session that has disconnectd if called against
276 # an existing session that seems to be disconnected, or was just built
277 # using 'create' above.
278
279 # connect( $app, username => $user, secret => $passwd );
280 #    OR
281 # connect( $app, sysname => $user, secret => $shared_secret );
282
283 # --- Returns undef if the connect attempt times out.
284 # --- Returns the OpenSRF::EX object if one is returned by the server
285 # --- Returns self if connected
286 sub connect {
287         my $self = shift;
288         my $class = ref($self) || $self;
289
290         if ( ref( $self ) and  $self->state && $self->state == CONNECTED  ) {
291                 $logger->transport("ABC AppSession already connected", DEBUG );
292         } else {
293                 $logger->transport("ABC AppSession not connected, connecting..", DEBUG );
294         }
295         return $self if ( ref( $self ) and  $self->state && $self->state == CONNECTED  );
296
297         my $app = shift;
298         my $api_level = shift;
299         $api_level = 1 unless (defined $api_level);
300
301         $self = $class->create($app, @_) if (!ref($self));
302         return undef unless ($self);
303
304         $self->{api_level} = $api_level;
305
306         $self->reset;
307         $self->state(CONNECTING);
308         $self->send('CONNECT', "");
309
310         # if we want to connect to settings, we may not have 
311         # any data for the settings client to work with...
312         # just using a default for now XXX
313
314         my $time_remaining = 5;
315         
316 =head blah
317         my $client = OpenSRF::Utils::SettingsClient->new();
318         my $trans = $client->config_value("client_connection","transport_host");
319
320         if(!ref($trans)) {
321                 $time_remaining = $trans->{connect_timeout};
322         } else {
323                 # XXX for now, just use the first
324                 $time_remaining = $trans->[0]->{connect_timeout};
325         }
326 =cut
327
328         while ( $self->state != CONNECTED  and $time_remaining > 0 ) {
329                 my $starttime = time;
330                 $self->queue_wait($time_remaining);
331                 my $endtime = time;
332                 $time_remaining -= ($endtime - $starttime);
333         }
334
335         return undef unless($self->state == CONNECTED);
336
337         return $self;
338 }
339
340 sub finish {
341         my $self = shift;
342         if( ! $self->session_id ) {
343                 return 0;
344         }
345         #$self->disconnect if ($self->endpoint == CLIENT);
346         for my $ses ( @_CLIENT_CACHE ) {
347                 if ($ses->[2]->session_id eq $self->session_id) {
348                         $ses->[1] = 1;
349                 }
350         }
351 }
352
353 sub register_callback {
354         my $self = shift;
355         my $type = shift;
356         my $cb = shift;
357         push @{ $self->{callbacks}{$type} }, $cb;
358 }
359
360 sub kill_me {
361         my $self = shift;
362         if( ! $self->session_id ) { return 0; }
363
364         # run each 'kill_me' callback;
365         for my $sub (@{$self->{callbacks}{death}}) {
366                 $sub->($self);
367         }
368
369         $self->disconnect;
370         $logger->transport( "AppSession killing self: " . $self->session_id(), DEBUG );
371         my @a;
372         for my $ses ( @_CLIENT_CACHE ) {
373                 push @a, $ses 
374                         if ($ses->[2]->session_id ne $self->session_id);
375         }
376         @_CLIENT_CACHE = @a;
377         delete $_CACHE{$self->session_id};
378         delete($$self{$_}) for (keys %$self);
379 }
380
381 sub disconnect {
382         my $self = shift;
383         unless( $self->state == DISCONNECTED ) {
384                 $self->send('DISCONNECT', "") if ($self->endpoint == CLIENT);;
385                 $self->state( DISCONNECTED ); 
386         }
387         # run each 'disconnect' callback;
388         for my $sub (@{$self->{callbacks}{disconnect}}) {
389                 $sub->($self);
390         }
391
392         $self->reset;
393 }
394
395 sub request {
396         my $self = shift;
397         my $meth = shift;
398
399         my $method;
400         if (!ref $meth) {
401                 $method = new OpenSRF::DomainObject::oilsMethod ( method => $meth );
402         } else {
403                 $method = $meth;
404         }
405         
406         $method->params( @_ );
407
408         $self->send('REQUEST',$method);
409 }
410
411
412 sub send {
413         my $self = shift;
414         my @payload_list = @_; # this is a Domain Object
415
416
417         $logger->debug( "In send", INTERNAL );
418         
419         my $tT;
420
421         if( @payload_list % 2 ) { $tT = pop @payload_list; }
422
423         if( ! @payload_list ) {
424                 $logger->debug( "payload_list param is incomplete in AppSession::send()", ERROR );
425                 return undef; 
426         }
427
428         my $doc = OpenSRF::DOM->createDocument();
429
430         $logger->debug( "In send2", INTERNAL );
431
432         my $disconnect = 0;
433         my $connecting = 0;
434
435         while( @payload_list ) {
436
437                 my ($msg_type, $payload) = ( shift(@payload_list), shift(@payload_list) ); 
438
439                 if ($msg_type eq 'DISCONNECT' ) {
440                         $disconnect++;
441                         if( $self->state == DISCONNECTED) {
442                                 next;
443                         }
444                 }
445
446                 if( $msg_type eq "CONNECT" ) { $connecting++; }
447
448
449                 if( $payload ) {
450                         $logger->debug( "Payload is ".$payload->toString, INTERNAL );
451                 }
452         
453         
454                 my $msg = OpenSRF::DomainObject::oilsMessage->new();
455                 $logger->debug( "AppSession after creating oilsMessage $msg", INTERNAL );
456                 
457                 $msg->type($msg_type);
458                 $logger->debug( "AppSession after adding type" . $msg->toString(), INTERNAL );
459         
460                 #$msg->userAuth($self->client_auth) if ($self->endpoint == CLIENT && $msg_type eq 'CONNECT');
461         
462                 no warnings;
463                 $msg->threadTrace( $tT || int($self->session_threadTrace) || int($self->last_threadTrace) );
464                 use warnings;
465         
466                 if ($msg->type eq 'REQUEST') {
467                         if ( !defined($tT) || $self->last_threadTrace != $tT ) {
468                                 $msg->update_threadTrace;
469                                 $self->session_threadTrace( $msg->threadTrace );
470                                 $tT = $self->session_threadTrace;
471                                 OpenSRF::AppRequest->new($self, $payload);
472                         }
473                 }
474         
475                 $msg->api_level($self->api_level);
476                 $msg->payload($payload) if $payload;
477         
478                 $doc->documentElement->appendChild( $msg );
479
480         
481                 $logger->debug( "AppSession sending ".$msg->type." to ".$self->remote_id.
482                         " with threadTrace [".$msg->threadTrace."]", INFO );
483
484         }
485         
486         if ($self->endpoint == CLIENT and ! $disconnect) {
487                 $self->queue_wait(0);
488                 unless ($self->state == CONNECTED || ($self->state == CONNECTING && $connecting )) {
489                         my $v = $self->connect();
490                         if( ! $v ) {
491                                 $logger->debug( "Unable to connect to remote service in AppSession::send()", ERROR );
492                                 return undef;
493                         }
494                         if( ref($v) and $v->can("class") and $v->class->isa( "OpenSRF::EX" ) ) {
495                                 return $v;
496                         }
497                 }
498         } 
499
500         $logger->debug( "AppSession sending doc: " . $doc->toString(), INTERNAL );
501
502
503         $self->{peer_handle}->send( 
504                                         to     => $self->remote_id,
505                                    thread => $self->session_id,
506                                    body   => $doc->toString );
507
508         return $self->app_request( $tT );
509 }
510
511 sub app_request {
512         my $self = shift;
513         my $tT = shift;
514         
515         return undef unless (defined $tT);
516         my ($req) = grep { $_->threadTrace == $tT } @{ $self->{request_queue} };
517
518         return $req;
519 }
520
521 sub remove_app_request {
522         my $self = shift;
523         my $req = shift;
524         
525         my @list = grep { $_->threadTrace != $req->threadTrace } @{ $self->{request_queue} };
526
527         $self->{request_queue} = \@list;
528 }
529
530 sub endpoint {
531         return $_[0]->{endpoint};
532 }
533
534
535 sub session_id {
536         my $self = shift;
537         return $self->{session_id};
538 }
539
540 sub push_queue {
541         my $self = shift;
542         my $resp = shift;
543         my $req = $self->app_request($resp->[1]);
544         return $req->push_queue( $resp->[0] ) if ($req);
545         push @{ $self->{recv_queue} }, $resp->[0];
546 }
547
548 sub last_threadTrace {
549         my $self = shift;
550         my $new_last_threadTrace = shift;
551
552         my $old_last_threadTrace = $self->{last_threadTrace};
553         if (defined $new_last_threadTrace) {
554                 $self->{last_threadTrace} = $new_last_threadTrace;
555                 return $new_last_threadTrace unless ($old_last_threadTrace);
556         }
557
558         return $old_last_threadTrace;
559 }
560
561 sub session_threadTrace {
562         my $self = shift;
563         my $new_last_threadTrace = shift;
564
565         my $old_last_threadTrace = $self->{session_threadTrace};
566         if (defined $new_last_threadTrace) {
567                 $self->{session_threadTrace} = $new_last_threadTrace;
568                 return $new_last_threadTrace unless ($old_last_threadTrace);
569         }
570
571         return $old_last_threadTrace;
572 }
573
574 sub last_message_type {
575         my $self = shift;
576         my $new_last_message_type = shift;
577
578         my $old_last_message_type = $self->{last_message_type};
579         if (defined $new_last_message_type) {
580                 $self->{last_message_type} = $new_last_message_type;
581                 return $new_last_message_type unless ($old_last_message_type);
582         }
583
584         return $old_last_message_type;
585 }
586
587 sub last_message_api_level {
588         my $self = shift;
589         my $new_last_message_api_level = shift;
590
591         my $old_last_message_api_level = $self->{last_message_api_level};
592         if (defined $new_last_message_api_level) {
593                 $self->{last_message_api_level} = $new_last_message_api_level;
594                 return $new_last_message_api_level unless ($old_last_message_api_level);
595         }
596
597         return $old_last_message_api_level;
598 }
599
600 sub remote_id {
601         my $self = shift;
602         my $new_remote_id = shift;
603
604         my $old_remote_id = $self->{remote_id};
605         if (defined $new_remote_id) {
606                 $self->{remote_id} = $new_remote_id;
607                 return $new_remote_id unless ($old_remote_id);
608         }
609
610         return $old_remote_id;
611 }
612
613 sub client_auth {
614         return undef;
615         my $self = shift;
616         my $new_ua = shift;
617
618         my $old_ua = $self->{client_auth};
619         if (defined $new_ua) {
620                 $self->{client_auth} = $new_ua;
621                 return $new_ua unless ($old_ua);
622         }
623
624         return $old_ua->cloneNode(1);
625 }
626
627 sub state {
628         my $self = shift;
629         my $new_state = shift;
630
631         my $old_state = $self->{state};
632         if (defined $new_state) {
633                 $self->{state} = $new_state;
634                 return $new_state unless ($old_state);
635         }
636
637         return $old_state;
638 }
639
640 sub DESTROY {
641         my $self = shift;
642         delete $$self{$_} for keys %$self;
643         return undef;
644 }
645
646 sub recv {
647         my $self = shift;
648         my @proto_args = @_;
649         my %args;
650
651         if ( @proto_args ) {
652                 if ( !(@proto_args % 2) ) {
653                         %args = @proto_args;
654                 } elsif (@proto_args == 1) {
655                         %args = ( timeout => @proto_args );
656                 }
657         }
658
659         #$logger->debug( ref($self). " recv_queue before wait: " . $self->_print_queue(), INTERNAL );
660
661         if( exists( $args{timeout} ) ) {
662                 $args{timeout} = int($args{timeout});
663         } else {
664                 $args{timeout} = 10;
665         }
666
667         #$args{timeout} = 0 if ($self->complete);
668
669         $logger->debug( ref($self) ."->recv with timeout " . $args{timeout}, INTERNAL );
670
671         $args{count} ||= 1;
672
673         my $avail = @{ $self->{recv_queue} };
674         my $time_remaining = $args{timeout};
675
676         while ( $avail < $args{count} and $time_remaining > 0 ) {
677                 last if $self->complete;
678                 my $starttime = time;
679                 $self->queue_wait($time_remaining);
680                 my $endtime = time;
681                 $time_remaining -= ($endtime - $starttime);
682                 $avail = @{ $self->{recv_queue} };
683         }
684
685         #$logger->debug( ref($self)." queue after wait: " . $self->_print_queue(), INTERNAL );
686                 
687         my @list;
688         while ( my $msg = shift @{ $self->{recv_queue} } ) {
689                 push @list, $msg;
690                 last if (scalar(@list) >= $args{count});
691         }
692
693 #       $self->{recv_queue} = [@unlist, @{ $self->{recv_queue} }];
694         $logger->debug( "Number of matched responses: " . @list, DEBUG );
695
696         $self->queue_wait(0); # check for statuses
697         
698         return $list[0] unless (wantarray);
699         return @list;
700 }
701
702 sub push_resend {
703         my $self = shift;
704         push @OpenSRF::AppSession::_RESEND_QUEUE, @_;
705 }
706
707 sub flush_resend {
708         my $self = shift;
709         $logger->debug( "Resending..." . @_RESEND_QUEUE, DEBUG );
710         while ( my $req = shift @OpenSRF::AppSession::_RESEND_QUEUE ) {
711                 $req->resend;
712         }
713 }
714
715
716 sub queue_wait {
717         my $self = shift;
718         if( ! $self->{peer_handle} ) { return 0; }
719         my $timeout = shift || 0;
720         $logger->debug( "Calling queue_wait($timeout)" , DEBUG );
721         $logger->debug( "Timestamp before process($timeout) : " . $logger->format_time(), INTERNAL );
722         my $o = $self->{peer_handle}->process($timeout);
723         $logger->debug( "Timestamp after  process($timeout) : " . $logger->format_time(), INTERNAL );
724         $self->flush_resend;
725         return $o;
726 }
727
728 sub _print_queue {
729         my( $self ) = @_;
730         my $string = "";
731         foreach my $msg ( @{$self->{recv_queue}} ) {
732                 $string = $string . $msg->toString(1) . "\n";
733         }
734         return $string;
735 }
736
737 sub status {
738         my $self = shift;
739         $self->send( 'STATUS', @_ );
740 }
741
742 #-------------------------------------------------------------------------------
743
744 package OpenSRF::AppRequest;
745 use base qw/OpenSRF::AppSession/;
746 use OpenSRF::Utils::Logger qw/:level/;
747 use OpenSRF::DomainObject::oilsResponse qw/:status/;
748
749 sub new {
750         my $class = shift;
751         $class = ref($class) || $class;
752
753         my $session = shift;
754         my $threadTrace = $session->session_threadTrace || $session->last_threadTrace;
755         my $payload = shift;
756         
757         my $self = {    session     => $session,
758                         threadTrace => $threadTrace,
759                         payload     => $payload,
760                         complete    => 0,
761                         recv_queue  => [],
762         };
763
764         bless $self => $class;
765
766         push @{ $self->session->{request_queue} }, $self;
767
768         return $self;
769 }
770
771 sub queue_size {
772         my $size = @{$_[0]->{recv_queue}};
773         return $size;
774 }
775         
776 sub send {
777         shift()->session->send(@_);
778 }
779
780 sub finish {
781         my $self = shift;
782         $self->session->remove_app_request($self);
783         delete($$self{$_}) for (keys %$self);
784 }
785
786 sub session {
787         return shift()->{session};
788 }
789
790 sub complete {
791         my $self = shift;
792         my $complete = shift;
793         return $self->{complete} if ($self->{complete});
794         if (defined $complete) {
795                 $self->{complete} = $complete;
796         } else {
797                 $self->session->queue_wait(0);
798         }
799         return $self->{complete};
800 }
801
802 sub wait_complete {
803         my $self = shift;
804         my $timeout = shift || 1;
805         my $time_remaining = $timeout;
806
807         while ( ! $self->complete  and $time_remaining > 0 ) {
808                 my $starttime = time;
809                 $self->queue_wait($time_remaining);
810                 my $endtime = time;
811                 $time_remaining -= ($endtime - $starttime);
812         }
813
814         return $self->complete;
815 }
816
817 sub threadTrace {
818         return shift()->{threadTrace};
819 }
820
821 sub push_queue {
822         my $self = shift;
823         my $resp = shift;
824         if( !$resp ) { return 0; }
825         push @{ $self->{recv_queue} }, $resp;
826         OpenSRF::Utils::Logger->debug( "AppRequest pushed ".$resp->toString(), INTERNAL );
827 }
828
829 sub queue_wait {
830         my $self = shift;
831         OpenSRF::Utils::Logger->debug( "Calling queue_wait(@_)", DEBUG );
832         return $self->session->queue_wait(@_)
833 }
834
835 sub payload { return shift()->{payload}; }
836
837 sub resend {
838         my $self = shift;
839         OpenSRF::Utils::Logger->debug(
840                 "I'm resending the request for threadTrace ". $self->threadTrace, DEBUG);
841         if($self->payload) {
842                 OpenSRF::Utils::Logger->debug($self->payload->toString,INTERNAL);
843         }
844         return $self->session->send('REQUEST', $self->payload, $self->threadTrace );
845 }
846
847 sub status {
848         my $self = shift;
849         my $msg = shift;
850         $self->session->send( 'STATUS',$msg, $self->threadTrace );
851 }
852
853 sub respond {
854         my $self = shift;
855         my $msg = shift;
856
857         my $response;
858         if (ref($msg) && UNIVERSAL::can($msg, 'getAttribute') && $msg->getAttribute('name') =~ /oilsResult/) {
859                 $response = $msg;
860         } else {
861                 $response = new OpenSRF::DomainObject::oilsResult;
862                 $response->content($msg);
863         }
864
865         $self->session->send('RESULT', $response, $self->threadTrace);
866 }
867
868 sub respond_complete {
869         my $self = shift;
870         my $msg = shift;
871
872         my $response;
873         if (ref($msg) && UNIVERSAL::can($msg, 'getAttribute') && $msg->getAttribute('name') =~ /oilsResult/) {
874                 $response = $msg;
875         } else {
876                 $response = new OpenSRF::DomainObject::oilsResult;
877                 $response->content($msg);
878         }
879
880         my $stat = OpenSRF::DomainObject::oilsConnectStatus->new(
881                 statusCode => STATUS_COMPLETE(),
882                 status => 'Request Complete' );
883
884         $self->session->send( 'RESULT' => $response, 'STATUS' => $stat, $self->threadTrace);
885
886 }
887
888 sub register_death_callback {
889         my $self = shift;
890         my $cb = shift;
891         $self->session->register_callback( death => $cb );
892 }
893
894 package OpenSRF::AppSubrequest;
895
896 sub respond {
897         my $self = shift;
898         my $resp = shift;
899         push @{$$self{resp}}, $resp;
900 }
901
902 sub new {
903         return bless({resp => []}, 'OpenSRF::AppSubrequest');
904 }
905
906 sub responses { @{$_[0]->{resp}} }
907
908 sub status {}
909
910
911 1;
912