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