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