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