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