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