]> git.evergreen-ils.org Git - OpenSRF.git/blob - src/perlmods/OpenSRF/AppSession.pm
adding full_request (not sure if we need this) and fixing thinko on disconnect
[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 (defined $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  => {},
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
198 # When we're a client and we want to connect to a remote service
199 # create( $app, username => $user, secret => $passwd );
200 #    OR
201 # create( $app, sysname => $user, secret => $shared_secret );
202 sub create {
203         my $class = shift;
204         $class = ref($class) || $class;
205
206         my $app = shift;
207
208         if( my $thingy = OpenSRF::AppSession->find_client( $app ) ) {
209                         $logger->debug( "AppSession returning existing client session for $app", DEBUG );
210                         return $thingy;
211         } else {
212                 $logger->debug( "AppSession creating new client session for $app", DEBUG );
213         }
214
215
216         my $sess_id = time . rand( $$ );
217         while ( $class->find($sess_id) ) {
218                 $sess_id = time . rand( $$ );
219         }
220
221         my ($r_id) = get_app_targets($app);
222
223         my $peer_handle = OpenSRF::Transport::PeerHandle->retrieve("client"); 
224         if( ! $peer_handle ) {
225                 $peer_handle = OpenSRF::Transport::PeerHandle->retrieve("system_client");
226         }
227
228         my $self = bless { app_name    => $app,
229                                 #client_auth => $auth,
230                            #recv_queue  => [],
231                            request_queue  => [],
232                            endpoint    => CLIENT,
233                            state       => DISCONNECTED,#since we're init'ing
234                            session_id  => $sess_id,
235                            remote_id   => $r_id,
236                            api_level   => 1,
237                            orig_remote_id   => $r_id,
238                                 peer_handle => $peer_handle,
239                                 session_threadTrace => 0,
240                          } => $class;
241
242         $self->client_cache();
243         $_CACHE{$sess_id} = $self;
244         return $self->find_client( $app );
245 }
246
247 sub api_level {
248         return shift()->{api_level};
249 }
250
251 sub app {
252         return shift()->{app_name};
253 }
254
255 sub reset {
256         my $self = shift;
257         $self->remote_id($$self{orig_remote_id});
258 }
259
260 # 'connect' can be used as a constructor if called as a class method,
261 # or used to connect a session that has disconnectd if called against
262 # an existing session that seems to be disconnected, or was just built
263 # using 'create' above.
264
265 # connect( $app, username => $user, secret => $passwd );
266 #    OR
267 # connect( $app, sysname => $user, secret => $shared_secret );
268
269 # --- Returns undef if the connect attempt times out.
270 # --- Returns the OpenSRF::EX object if one is returned by the server
271 # --- Returns self if connected
272 sub connect {
273         my $self = shift;
274         my $class = ref($self) || $self;
275
276         if ( ref( $self ) and  $self->state && $self->state == CONNECTED  ) {
277                 $logger->transport("ABC AppSession already connected", DEBUG );
278         } else {
279                 $logger->transport("ABC AppSession not connected, connecting..", DEBUG );
280         }
281         return $self if ( ref( $self ) and  $self->state && $self->state == CONNECTED  );
282
283         my $app = shift;
284         my $api_level = shift;
285         $api_level = 1 unless (defined $api_level);
286
287         $self = $class->create($app, @_) if (!ref($self));
288         return undef unless ($self);
289
290         $self->{api_level} = $api_level;
291
292         $self->reset;
293         $self->state(CONNECTING);
294         $self->send('CONNECT', "");
295
296         # if we want to connect to settings, we may not have 
297         # any data for the settings client to work with...
298         # just using a default for now XXX
299
300         my $time_remaining = 5;
301         
302 =head blah
303         my $client = OpenSRF::Utils::SettingsClient->new();
304         my $trans = $client->config_value("client_connection","transport_host");
305
306         if(!ref($trans)) {
307                 $time_remaining = $trans->{connect_timeout};
308         } else {
309                 # XXX for now, just use the first
310                 $time_remaining = $trans->[0]->{connect_timeout};
311         }
312 =cut
313
314         while ( $self->state != CONNECTED  and $time_remaining > 0 ) {
315                 my $starttime = time;
316                 $self->queue_wait($time_remaining);
317                 my $endtime = time;
318                 $time_remaining -= ($endtime - $starttime);
319         }
320
321         return undef unless($self->state == CONNECTED);
322
323         return $self;
324 }
325
326 sub finish {
327         my $self = shift;
328         if( ! $self->session_id ) {
329                 return 0;
330         }
331         #$self->disconnect if ($self->endpoint == CLIENT);
332         for my $ses ( @_CLIENT_CACHE ) {
333                 if ($ses->[2]->session_id eq $self->session_id) {
334                         $ses->[1] = 1;
335                 }
336         }
337 }
338
339 sub unregister_callback {
340         my $self = shift;
341         my $type = shift;
342         my $cb = shift;
343         if (exists $self->{callbacks}{$type}) {
344                 delete $self->{callbacks}{$type}{$cb};
345                 return $cb;
346         }
347         return undef;
348 }
349
350 sub register_callback {
351         my $self = shift;
352         my $type = shift;
353         my $cb = shift;
354         my $cb_key = "$cb";
355         $self->{callbacks}{$type}{$cb_key} = $cb;
356         return $cb_key;
357 }
358
359 sub kill_me {
360         my $self = shift;
361         if( ! $self->session_id ) { return 0; }
362
363         # run each 'death' callback;
364         if (exists $self->{callbacks}{death}) {
365                 for my $sub (values %{$self->{callbacks}{death}}) {
366                         $sub->($self);
367                 }
368         }
369
370         $self->disconnect;
371         $logger->transport( "AppSession killing self: " . $self->session_id(), DEBUG );
372         my @a;
373         for my $ses ( @_CLIENT_CACHE ) {
374                 push @a, $ses 
375                         if ($ses->[2]->session_id ne $self->session_id);
376         }
377         @_CLIENT_CACHE = @a;
378         delete $_CACHE{$self->session_id};
379         delete($$self{$_}) for (keys %$self);
380 }
381
382 sub disconnect {
383         my $self = shift;
384
385         # run each 'disconnect' callback;
386         if (exists $self->{callbacks}{disconnect}) {
387                 for my $sub (values %{$self->{callbacks}{disconnect}}) {
388                         $sub->($self);
389                 }
390         }
391
392         unless( $self->state == DISCONNECTED ) {
393                 $self->send('DISCONNECT', "") if ($self->endpoint == CLIENT);;
394                 $self->state( DISCONNECTED ); 
395         }
396
397         $self->reset;
398 }
399
400 sub request {
401         my $self = shift;
402         my $meth = shift;
403         return unless $self;
404
405         my $method;
406         if (!ref $meth) {
407                 $method = new OpenSRF::DomainObject::oilsMethod ( method => $meth );
408         } else {
409                 $method = $meth;
410         }
411         
412         $method->params( @_ );
413
414         $self->send('REQUEST',$method);
415 }
416
417 sub full_request {
418         my $self = shift;
419         my $meth = shift;
420
421         my $method;
422         if (!ref $meth) {
423                 $method = new OpenSRF::DomainObject::oilsMethod ( method => $meth );
424         } else {
425                 $method = $meth;
426         }
427         
428         $method->params( @_ );
429
430         $self->send(CONNECT => '', REQUEST => $method, DISCONNECT => '');
431 }
432
433 sub send {
434         my $self = shift;
435         my @payload_list = @_; # this is a Domain Object
436
437
438         return unless ($self and $self->{peer_handle});
439
440         $logger->debug( "In send", INTERNAL );
441         
442         my $tT;
443
444         if( @payload_list % 2 ) { $tT = pop @payload_list; }
445
446         if( ! @payload_list ) {
447                 $logger->debug( "payload_list param is incomplete in AppSession::send()", ERROR );
448                 return undef; 
449         }
450
451         my $doc = OpenSRF::DOM->createDocument();
452
453         $logger->debug( "In send2", INTERNAL );
454
455         my $disconnect = 0;
456         my $connecting = 0;
457
458         while( @payload_list ) {
459
460                 my ($msg_type, $payload) = ( shift(@payload_list), shift(@payload_list) ); 
461
462                 if ($msg_type eq 'DISCONNECT' ) {
463                         $disconnect++;
464                         if( $self->state == DISCONNECTED && !$connecting) {
465                                 next;
466                         }
467                 }
468
469                 if( $msg_type eq "CONNECT" ) { $connecting++; }
470
471
472                 if( $payload ) {
473                         $logger->debug( "Payload is ".$payload->toString, INTERNAL );
474                 }
475         
476         
477                 my $msg = OpenSRF::DomainObject::oilsMessage->new();
478                 $logger->debug( "AppSession after creating oilsMessage $msg", INTERNAL );
479                 
480                 $msg->type($msg_type);
481                 $logger->debug( "AppSession after adding type" . $msg->toString(), INTERNAL );
482         
483                 #$msg->userAuth($self->client_auth) if ($self->endpoint == CLIENT && $msg_type eq 'CONNECT');
484         
485                 no warnings;
486                 $msg->threadTrace( $tT || int($self->session_threadTrace) || int($self->last_threadTrace) );
487                 use warnings;
488         
489                 if ($msg->type eq 'REQUEST') {
490                         if ( !defined($tT) || $self->last_threadTrace != $tT ) {
491                                 $msg->update_threadTrace;
492                                 $self->session_threadTrace( $msg->threadTrace );
493                                 $tT = $self->session_threadTrace;
494                                 OpenSRF::AppRequest->new($self, $payload);
495                         }
496                 }
497         
498                 $msg->api_level($self->api_level);
499                 $msg->payload($payload) if $payload;
500         
501                 $doc->documentElement->appendChild( $msg );
502
503         
504                 $logger->debug( "AppSession sending ".$msg->type." to ".$self->remote_id.
505                         " with threadTrace [".$msg->threadTrace."]", INFO );
506
507         }
508         
509         if ($self->endpoint == CLIENT and ! $disconnect) {
510                 $self->queue_wait(0);
511                 unless ($self->state == CONNECTED || ($self->state == CONNECTING && $connecting )) {
512                         my $v = $self->connect();
513                         if( ! $v ) {
514                                 $logger->debug( "Unable to connect to remote service in AppSession::send()", ERROR );
515                                 return undef;
516                         }
517                         if( ref($v) and $v->can("class") and $v->class->isa( "OpenSRF::EX" ) ) {
518                                 return $v;
519                         }
520                 }
521         } 
522         $logger->debug( "AppSession sending doc: " . $doc->toString(), INTERNAL );
523
524
525         $self->{peer_handle}->send( 
526                                         to     => $self->remote_id,
527                                    thread => $self->session_id,
528                                    body   => $doc->toString );
529
530         if( $disconnect) {
531                 $self->state( DISCONNECTED );
532         }
533
534         return $self->app_request( $tT );
535 }
536
537 sub app_request {
538         my $self = shift;
539         my $tT = shift;
540         
541         return undef unless (defined $tT);
542         my ($req) = grep { $_->threadTrace == $tT } @{ $self->{request_queue} };
543
544         return $req;
545 }
546
547 sub remove_app_request {
548         my $self = shift;
549         my $req = shift;
550         
551         my @list = grep { $_->threadTrace != $req->threadTrace } @{ $self->{request_queue} };
552
553         $self->{request_queue} = \@list;
554 }
555
556 sub endpoint {
557         return $_[0]->{endpoint};
558 }
559
560
561 sub session_id {
562         my $self = shift;
563         return $self->{session_id};
564 }
565
566 sub push_queue {
567         my $self = shift;
568         my $resp = shift;
569         my $req = $self->app_request($resp->[1]);
570         return $req->push_queue( $resp->[0] ) if ($req);
571         push @{ $self->{recv_queue} }, $resp->[0];
572 }
573
574 sub last_threadTrace {
575         my $self = shift;
576         my $new_last_threadTrace = shift;
577
578         my $old_last_threadTrace = $self->{last_threadTrace};
579         if (defined $new_last_threadTrace) {
580                 $self->{last_threadTrace} = $new_last_threadTrace;
581                 return $new_last_threadTrace unless ($old_last_threadTrace);
582         }
583
584         return $old_last_threadTrace;
585 }
586
587 sub session_threadTrace {
588         my $self = shift;
589         my $new_last_threadTrace = shift;
590
591         my $old_last_threadTrace = $self->{session_threadTrace};
592         if (defined $new_last_threadTrace) {
593                 $self->{session_threadTrace} = $new_last_threadTrace;
594                 return $new_last_threadTrace unless ($old_last_threadTrace);
595         }
596
597         return $old_last_threadTrace;
598 }
599
600 sub last_message_type {
601         my $self = shift;
602         my $new_last_message_type = shift;
603
604         my $old_last_message_type = $self->{last_message_type};
605         if (defined $new_last_message_type) {
606                 $self->{last_message_type} = $new_last_message_type;
607                 return $new_last_message_type unless ($old_last_message_type);
608         }
609
610         return $old_last_message_type;
611 }
612
613 sub last_message_api_level {
614         my $self = shift;
615         my $new_last_message_api_level = shift;
616
617         my $old_last_message_api_level = $self->{last_message_api_level};
618         if (defined $new_last_message_api_level) {
619                 $self->{last_message_api_level} = $new_last_message_api_level;
620                 return $new_last_message_api_level unless ($old_last_message_api_level);
621         }
622
623         return $old_last_message_api_level;
624 }
625
626 sub remote_id {
627         my $self = shift;
628         my $new_remote_id = shift;
629
630         my $old_remote_id = $self->{remote_id};
631         if (defined $new_remote_id) {
632                 $self->{remote_id} = $new_remote_id;
633                 return $new_remote_id unless ($old_remote_id);
634         }
635
636         return $old_remote_id;
637 }
638
639 sub client_auth {
640         return undef;
641         my $self = shift;
642         my $new_ua = shift;
643
644         my $old_ua = $self->{client_auth};
645         if (defined $new_ua) {
646                 $self->{client_auth} = $new_ua;
647                 return $new_ua unless ($old_ua);
648         }
649
650         return $old_ua->cloneNode(1);
651 }
652
653 sub state {
654         my $self = shift;
655         my $new_state = shift;
656
657         my $old_state = $self->{state};
658         if (defined $new_state) {
659                 $self->{state} = $new_state;
660                 return $new_state unless ($old_state);
661         }
662
663         return $old_state;
664 }
665
666 sub DESTROY {
667         my $self = shift;
668         delete $$self{$_} for keys %$self;
669         return undef;
670 }
671
672 sub recv {
673         my $self = shift;
674         my @proto_args = @_;
675         my %args;
676
677         if ( @proto_args ) {
678                 if ( !(@proto_args % 2) ) {
679                         %args = @proto_args;
680                 } elsif (@proto_args == 1) {
681                         %args = ( timeout => @proto_args );
682                 }
683         }
684
685         #$logger->debug( ref($self). " recv_queue before wait: " . $self->_print_queue(), INTERNAL );
686
687         if( exists( $args{timeout} ) ) {
688                 $args{timeout} = int($args{timeout});
689         } else {
690                 $args{timeout} = 10;
691         }
692
693         #$args{timeout} = 0 if ($self->complete);
694
695         $logger->debug( ref($self) ."->recv with timeout " . $args{timeout}, INTERNAL );
696
697         $args{count} ||= 1;
698
699         my $avail = @{ $self->{recv_queue} };
700         my $time_remaining = $args{timeout};
701
702         while ( $avail < $args{count} and $time_remaining > 0 ) {
703                 last if $self->complete;
704                 my $starttime = time;
705                 $self->queue_wait($time_remaining);
706                 my $endtime = time;
707                 $time_remaining -= ($endtime - $starttime);
708                 $avail = @{ $self->{recv_queue} };
709         }
710
711         #$logger->debug( ref($self)." queue after wait: " . $self->_print_queue(), INTERNAL );
712                 
713         my @list;
714         while ( my $msg = shift @{ $self->{recv_queue} } ) {
715                 push @list, $msg;
716                 last if (scalar(@list) >= $args{count});
717         }
718
719 #       $self->{recv_queue} = [@unlist, @{ $self->{recv_queue} }];
720         $logger->debug( "Number of matched responses: " . @list, DEBUG );
721
722         $self->queue_wait(0); # check for statuses
723         
724         return $list[0] unless (wantarray);
725         return @list;
726 }
727
728 sub push_resend {
729         my $self = shift;
730         push @OpenSRF::AppSession::_RESEND_QUEUE, @_;
731 }
732
733 sub flush_resend {
734         my $self = shift;
735         $logger->debug( "Resending..." . @_RESEND_QUEUE, DEBUG );
736         while ( my $req = shift @OpenSRF::AppSession::_RESEND_QUEUE ) {
737                 $req->resend unless $req->complete;
738         }
739 }
740
741
742 sub queue_wait {
743         my $self = shift;
744         if( ! $self->{peer_handle} ) { return 0; }
745         my $timeout = shift || 0;
746         $logger->debug( "Calling queue_wait($timeout)" , DEBUG );
747         $logger->debug( "Timestamp before process($timeout) : " . $logger->format_time(), INTERNAL );
748         my $o = $self->{peer_handle}->process($timeout);
749         $logger->debug( "Timestamp after  process($timeout) : " . $logger->format_time(), INTERNAL );
750         $self->flush_resend;
751         return $o;
752 }
753
754 sub _print_queue {
755         my( $self ) = @_;
756         my $string = "";
757         foreach my $msg ( @{$self->{recv_queue}} ) {
758                 $string = $string . $msg->toString(1) . "\n";
759         }
760         return $string;
761 }
762
763 sub status {
764         my $self = shift;
765         return unless $self;
766         $self->send( 'STATUS', @_ );
767 }
768
769 #-------------------------------------------------------------------------------
770
771 package OpenSRF::AppRequest;
772 use base qw/OpenSRF::AppSession/;
773 use OpenSRF::Utils::Logger qw/:level/;
774 use OpenSRF::DomainObject::oilsResponse qw/:status/;
775
776 sub new {
777         my $class = shift;
778         $class = ref($class) || $class;
779
780         my $session = shift;
781         my $threadTrace = $session->session_threadTrace || $session->last_threadTrace;
782         my $payload = shift;
783         
784         my $self = {    session     => $session,
785                         threadTrace => $threadTrace,
786                         payload     => $payload,
787                         complete    => 0,
788                         recv_queue  => [],
789         };
790
791         bless $self => $class;
792
793         push @{ $self->session->{request_queue} }, $self;
794
795         return $self;
796 }
797
798 sub queue_size {
799         my $size = @{$_[0]->{recv_queue}};
800         return $size;
801 }
802         
803 sub send {
804         my $self = shift;
805         return unless ($self and $self->session);
806         $self->session->send(@_);
807 }
808
809 sub finish {
810         my $self = shift;
811         $self->session->remove_app_request($self);
812         delete($$self{$_}) for (keys %$self);
813 }
814
815 sub session {
816         return shift()->{session};
817 }
818
819 sub complete {
820         my $self = shift;
821         my $complete = shift;
822         return $self->{complete} if ($self->{complete});
823         if (defined $complete) {
824                 $self->{complete} = $complete;
825         } else {
826                 $self->session->queue_wait(0);
827         }
828         return $self->{complete};
829 }
830
831 sub wait_complete {
832         my $self = shift;
833         my $timeout = shift || 1;
834         my $time_remaining = $timeout;
835
836         while ( ! $self->complete  and $time_remaining > 0 ) {
837                 my $starttime = time;
838                 $self->queue_wait($time_remaining);
839                 my $endtime = time;
840                 $time_remaining -= ($endtime - $starttime);
841         }
842
843         return $self->complete;
844 }
845
846 sub threadTrace {
847         return shift()->{threadTrace};
848 }
849
850 sub push_queue {
851         my $self = shift;
852         my $resp = shift;
853         if( !$resp ) { return 0; }
854         push @{ $self->{recv_queue} }, $resp;
855         OpenSRF::Utils::Logger->debug( "AppRequest pushed ".$resp->toString(), INTERNAL );
856 }
857
858 sub queue_wait {
859         my $self = shift;
860         OpenSRF::Utils::Logger->debug( "Calling queue_wait(@_)", DEBUG );
861         return $self->session->queue_wait(@_)
862 }
863
864 sub payload { return shift()->{payload}; }
865
866 sub resend {
867         my $self = shift;
868         return unless ($self and $self->session);
869         OpenSRF::Utils::Logger->debug(
870                 "I'm resending the request for threadTrace ". $self->threadTrace, DEBUG);
871         if($self->payload) {
872                 OpenSRF::Utils::Logger->debug($self->payload->toString,INTERNAL);
873         }
874         return $self->session->send('REQUEST', $self->payload, $self->threadTrace );
875 }
876
877 sub status {
878         my $self = shift;
879         my $msg = shift;
880         return unless ($self and $self->session);
881         $self->session->send( 'STATUS',$msg, $self->threadTrace );
882 }
883
884 sub respond {
885         my $self = shift;
886         my $msg = shift;
887         return unless ($self and $self->session);
888
889         my $response;
890         if (ref($msg) && UNIVERSAL::can($msg, 'getAttribute') && $msg->getAttribute('name') =~ /oilsResult/) {
891                 $response = $msg;
892         } else {
893                 $response = new OpenSRF::DomainObject::oilsResult;
894                 $response->content($msg);
895         }
896
897         $self->session->send('RESULT', $response, $self->threadTrace);
898 }
899
900 sub respond_complete {
901         my $self = shift;
902         my $msg = shift;
903
904         my $response;
905         if (ref($msg) && UNIVERSAL::can($msg, 'getAttribute') && $msg->getAttribute('name') =~ /oilsResult/) {
906                 $response = $msg;
907         } else {
908                 $response = new OpenSRF::DomainObject::oilsResult;
909                 $response->content($msg);
910         }
911
912         my $stat = OpenSRF::DomainObject::oilsConnectStatus->new(
913                 statusCode => STATUS_COMPLETE(),
914                 status => 'Request Complete' );
915
916         return unless ($self and $self->session);
917         $self->session->send( 'RESULT' => $response, 'STATUS' => $stat, $self->threadTrace);
918
919 }
920
921 sub register_death_callback {
922         my $self = shift;
923         my $cb = shift;
924         $self->session->register_callback( death => $cb );
925 }
926
927 package OpenSRF::AppSubrequest;
928
929 sub respond {
930         my $self = shift;
931         my $resp = shift;
932         push @{$$self{resp}}, $resp if (defined $resp);
933 }
934
935 sub new {
936         return bless({resp => []}, 'OpenSRF::AppSubrequest');
937 }
938
939 sub responses { @{$_[0]->{resp}} }
940
941 sub status {}
942
943
944 1;
945