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