initial sender_locale support ... probably going to break stuff; also, patch from...
[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                                 #client_auth => $auth,
239                            #recv_queue  => [],
240                            request_queue  => [],
241                            endpoint    => CLIENT,
242                            state       => DISCONNECTED,#since we're init'ing
243                            session_id  => $sess_id,
244                            remote_id   => $r_id,
245                            raise_error   => $quiet ? 0 : 1,
246                            session_locale   => $locale,
247                            api_level   => $api_level,
248                            orig_remote_id   => $r_id,
249                                 peer_handle => $peer_handle,
250                                 session_threadTrace => 0,
251                                 stateless               => $stateless,
252                          } => $class;
253
254         $logger->debug( "Created new client session $app : $sess_id" );
255
256         return $_CACHE{$sess_id} = $self;
257 }
258
259 sub raise_remote_errors {
260         my $self = shift;
261         my $err = shift;
262         $self->{raise_error} = $err if (defined $err);
263         return $self->{raise_error};
264 }
265
266 sub api_level {
267         return shift()->{api_level};
268 }
269
270 sub app {
271         return shift()->{app_name};
272 }
273
274 sub reset {
275         my $self = shift;
276         $self->remote_id($$self{orig_remote_id});
277 }
278
279 # 'connect' can be used as a constructor if called as a class method,
280 # or used to connect a session that has disconnectd if called against
281 # an existing session that seems to be disconnected, or was just built
282 # using 'create' above.
283
284 # connect( $app, username => $user, secret => $passwd );
285 #    OR
286 # connect( $app, sysname => $user, secret => $shared_secret );
287
288 # --- Returns undef if the connect attempt times out.
289 # --- Returns the OpenSRF::EX object if one is returned by the server
290 # --- Returns self if connected
291 sub connect {
292         my $self = shift;
293         my $class = ref($self) || $self;
294
295
296         if ( ref( $self ) and  $self->state && $self->state == CONNECTED  ) {
297                 $logger->transport("AppSession already connected", DEBUG );
298         } else {
299                 $logger->transport("AppSession not connected, connecting..", DEBUG );
300         }
301         return $self if ( ref( $self ) and  $self->state && $self->state == CONNECTED  );
302
303
304         my $app = shift;
305         my $api_level = shift;
306         $api_level = 1 unless (defined $api_level);
307
308         $self = $class->create($app, @_) if (!ref($self));
309
310         return undef unless ($self);
311
312         $self->{api_level} = $api_level;
313
314         $self->reset;
315         $self->state(CONNECTING);
316         $self->send('CONNECT', "");
317
318
319         # if we want to connect to settings, we may not have 
320         # any data for the settings client to work with...
321         # just using a default for now XXX
322
323         my $time_remaining = 5;
324         
325 =head blah
326         my $client = OpenSRF::Utils::SettingsClient->new();
327         my $trans = $client->config_value("client_connection","transport_host");
328
329         if(!ref($trans)) {
330                 $time_remaining = $trans->{connect_timeout};
331         } else {
332                 # XXX for now, just use the first
333                 $time_remaining = $trans->[0]->{connect_timeout};
334         }
335 =cut
336
337         while ( $self->state != CONNECTED  and $time_remaining > 0 ) {
338                 my $starttime = time;
339                 $self->queue_wait($time_remaining);
340                 my $endtime = time;
341                 $time_remaining -= ($endtime - $starttime);
342         }
343
344         return undef unless($self->state == CONNECTED);
345
346         $self->stateless(0);
347
348         return $self;
349 }
350
351 sub finish {
352         my $self = shift;
353         if( ! $self->session_id ) {
354                 return 0;
355         }
356 }
357
358 sub unregister_callback {
359         my $self = shift;
360         my $type = shift;
361         my $cb = shift;
362         if (exists $self->{callbacks}{$type}) {
363                 delete $self->{callbacks}{$type}{$cb};
364                 return $cb;
365         }
366         return undef;
367 }
368
369 sub register_callback {
370         my $self = shift;
371         my $type = shift;
372         my $cb = shift;
373         my $cb_key = "$cb";
374         $self->{callbacks}{$type}{$cb_key} = $cb;
375         return $cb_key;
376 }
377
378 sub kill_me {
379         my $self = shift;
380         if( ! $self->session_id ) { return 0; }
381
382         # run each 'death' callback;
383         if (exists $self->{callbacks}{death}) {
384                 for my $sub (values %{$self->{callbacks}{death}}) {
385                         $sub->($self);
386                 }
387         }
388
389         $self->disconnect;
390         $logger->transport( "AppSession killing self: " . $self->session_id(), DEBUG );
391         delete $_CACHE{$self->session_id};
392         delete($$self{$_}) for (keys %$self);
393 }
394
395 sub disconnect {
396         my $self = shift;
397
398         # run each 'disconnect' callback;
399         if (exists $self->{callbacks}{disconnect}) {
400                 for my $sub (values %{$self->{callbacks}{disconnect}}) {
401                         $sub->($self);
402                 }
403         }
404
405         if ( !$self->stateless and $self->state != DISCONNECTED ) {
406                 $self->send('DISCONNECT', "") if ($self->endpoint == CLIENT);
407                 $self->state( DISCONNECTED ); 
408         }
409
410         $self->reset;
411 }
412
413 sub request {
414         my $self = shift;
415         my $meth = shift;
416         return unless $self;
417
418    # tell the logger to create a new xid - the logger will decide if it's really necessary
419    $logger->mk_osrf_xid;
420
421         my $method;
422         if (!ref $meth) {
423                 $method = new OpenSRF::DomainObject::oilsMethod ( method => $meth );
424         } else {
425                 $method = $meth;
426         }
427         
428         $method->params( @_ );
429
430         $self->send('REQUEST',$method);
431 }
432
433 sub full_request {
434         my $self = shift;
435         my $meth = shift;
436
437         my $method;
438         if (!ref $meth) {
439                 $method = new OpenSRF::DomainObject::oilsMethod ( method => $meth );
440         } else {
441                 $method = $meth;
442         }
443         
444         $method->params( @_ );
445
446         $self->send(CONNECT => '', REQUEST => $method, DISCONNECT => '');
447 }
448
449 sub send {
450         my $self = shift;
451         my @payload_list = @_; # this is a Domain Object
452
453         return unless ($self and $self->{peer_handle});
454
455         $logger->debug( "In send", INTERNAL );
456         
457         my $tT;
458
459         if( @payload_list % 2 ) { $tT = pop @payload_list; }
460
461         if( ! @payload_list ) {
462                 $logger->debug( "payload_list param is incomplete in AppSession::send()", ERROR );
463                 return undef; 
464         }
465
466         my @doc = ();
467
468         my $disconnect = 0;
469         my $connecting = 0;
470
471         while( @payload_list ) {
472
473                 my ($msg_type, $payload) = ( shift(@payload_list), shift(@payload_list) ); 
474
475                 if ($msg_type eq 'DISCONNECT' ) {
476                         $disconnect++;
477                         if( $self->state == DISCONNECTED && !$connecting) {
478                                 next;
479                         }
480                 }
481
482                 if( $msg_type eq "CONNECT" ) { 
483                         $connecting++; 
484                 }
485
486                 my $msg = OpenSRF::DomainObject::oilsMessage->new();
487                 $msg->type($msg_type);
488         
489                 no warnings;
490                 $msg->threadTrace( $tT || int($self->session_threadTrace) || int($self->last_threadTrace) );
491                 use warnings;
492         
493                 if ($msg->type eq 'REQUEST') {
494                         if ( !defined($tT) || $self->last_threadTrace != $tT ) {
495                                 $msg->update_threadTrace;
496                                 $self->session_threadTrace( $msg->threadTrace );
497                                 $tT = $self->session_threadTrace;
498                                 OpenSRF::AppRequest->new($self, $payload);
499                         }
500                 }
501         
502                 $msg->api_level($self->api_level);
503                 $msg->payload($payload) if $payload;
504                 $msg->sender_locale($self->session_locale) if $self->session_locale;
505         
506                 push @doc, $msg;
507
508         
509                 $logger->info( "AppSession sending ".$msg->type." to ".$self->remote_id.
510                         " with threadTrace [".$msg->threadTrace."]" );
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         if (!wantarray) {
754                 $self->session_locale( $list[0]->sender_locale );
755                 return $list[0];
756         } else {
757                 $self->session_locale( $list[-1]->sender_locale );
758         }
759
760         return @list;
761 }
762
763 sub push_resend {
764         my $self = shift;
765         push @OpenSRF::AppSession::_RESEND_QUEUE, @_;
766 }
767
768 sub flush_resend {
769         my $self = shift;
770         $logger->debug( "Resending..." . @_RESEND_QUEUE, INTERNAL );
771         while ( my $req = shift @OpenSRF::AppSession::_RESEND_QUEUE ) {
772                 $req->resend unless $req->complete;
773         }
774 }
775
776
777 sub queue_wait {
778         my $self = shift;
779         if( ! $self->{peer_handle} ) { return 0; }
780         my $timeout = shift || 0;
781         $logger->debug( "Calling queue_wait($timeout)" , INTERNAL );
782         my $o = $self->{peer_handle}->process($timeout);
783         $self->flush_resend;
784         return $o;
785 }
786
787 sub _print_queue {
788         my( $self ) = @_;
789         my $string = "";
790         foreach my $msg ( @{$self->{recv_queue}} ) {
791                 $string = $string . $msg->toString(1) . "\n";
792         }
793         return $string;
794 }
795
796 sub status {
797         my $self = shift;
798         return unless $self;
799         $self->send( 'STATUS', @_ );
800 }
801
802 sub reset_request_timeout {
803         my $self = shift;
804         my $tt = shift;
805         my $req = $self->app_request($tt);
806         $req->{remaining_recv_timeout} = $req->{recv_timeout};
807         $req->{timout_reset} = 1;
808 }
809
810 #-------------------------------------------------------------------------------
811
812 package OpenSRF::AppRequest;
813 use base qw/OpenSRF::AppSession/;
814 use OpenSRF::Utils::Logger qw/:level/;
815 use OpenSRF::DomainObject::oilsResponse qw/:status/;
816 use Time::HiRes qw/time usleep/;
817
818 sub new {
819         my $class = shift;
820         $class = ref($class) || $class;
821
822         my $session = shift;
823         my $threadTrace = $session->session_threadTrace || $session->last_threadTrace;
824         my $payload = shift;
825         
826         my $self = {    session                 => $session,
827                         threadTrace             => $threadTrace,
828                         payload                 => $payload,
829                         complete                => 0,
830                         timeout_reset           => 0,
831                         recv_timeout            => 30,
832                         remaining_recv_timeout  => 30,
833                         recv_queue              => [],
834         };
835
836         bless $self => $class;
837
838         push @{ $self->session->{request_queue} }, $self;
839
840         return $self;
841 }
842
843 sub recv_timeout {
844         my $self = shift;
845         my $timeout = shift;
846         if (defined $timeout) {
847                 $self->{recv_timeout} = $timeout;
848                 $self->{remaining_recv_timeout} = $timeout;
849         }
850         return $self->{recv_timeout};
851 }
852
853 sub queue_size {
854         my $size = @{$_[0]->{recv_queue}};
855         return $size;
856 }
857         
858 sub send {
859         my $self = shift;
860         return unless ($self and $self->session and !$self->complete);
861         $self->session->send(@_);
862 }
863
864 sub finish {
865         my $self = shift;
866         return unless $self->session;
867         $self->session->remove_app_request($self);
868         delete($$self{$_}) for (keys %$self);
869 }
870
871 sub session {
872         return shift()->{session};
873 }
874
875 sub complete {
876         my $self = shift;
877         my $complete = shift;
878         return $self->{complete} if ($self->{complete});
879         if (defined $complete) {
880                 $self->{complete} = $complete;
881                 $self->{_duration} = time - $self->{_start} if ($self->{complete});
882         } else {
883                 $self->session->queue_wait(0);
884         }
885         return $self->{complete};
886 }
887
888 sub duration {
889         my $self = shift;
890         $self->wait_complete;
891         return $self->{_duration};
892 }
893
894 sub wait_complete {
895         my $self = shift;
896         my $timeout = shift || 10;
897         my $time_remaining = $timeout;
898
899         while ( ! $self->complete  and $time_remaining > 0 ) {
900                 my $starttime = time;
901                 $self->queue_wait($time_remaining);
902                 my $endtime = time;
903                 $time_remaining -= ($endtime - $starttime);
904         }
905
906         return $self->complete;
907 }
908
909 sub threadTrace {
910         return shift()->{threadTrace};
911 }
912
913 sub push_queue {
914         my $self = shift;
915         my $resp = shift;
916         if( !$resp ) { return 0; }
917         if( UNIVERSAL::isa($resp, "Error")) {
918                 $self->{failed} = $resp;
919                 $self->complete(1);
920                 #return; eventually...
921         }
922         push @{ $self->{recv_queue} }, $resp;
923 }
924
925 sub failed {
926         my $self = shift;
927         return $self->{failed};
928 }
929
930 sub queue_wait {
931         my $self = shift;
932         return $self->session->queue_wait(@_)
933 }
934
935 sub payload { return shift()->{payload}; }
936
937 sub resend {
938         my $self = shift;
939         return unless ($self and $self->session and !$self->complete);
940         OpenSRF::Utils::Logger->debug( "I'm resending the request for threadTrace ". $self->threadTrace, DEBUG);
941         return $self->session->send('REQUEST', $self->payload, $self->threadTrace );
942 }
943
944 sub status {
945         my $self = shift;
946         my $msg = shift;
947         return unless ($self and $self->session and !$self->complete);
948         $self->session->send( 'STATUS',$msg, $self->threadTrace );
949 }
950
951 sub stream_push {
952         my $self = shift;
953         my $msg = shift;
954         $self->respond( $msg );
955 }
956
957 sub respond {
958         my $self = shift;
959         my $msg = shift;
960         return unless ($self and $self->session and !$self->complete);
961
962         my $response;
963         if (ref($msg) && UNIVERSAL::isa($msg, 'OpenSRF::DomainObject::oilsResult')) {
964                 $response = $msg;
965         } else {
966                 $response = new OpenSRF::DomainObject::oilsResult;
967                 $response->content($msg);
968         }
969
970         $self->session->send('RESULT', $response, $self->threadTrace);
971 }
972
973 sub respond_complete {
974         my $self = shift;
975         my $msg = shift;
976         return unless ($self and $self->session and !$self->complete);
977
978         my $response;
979         if (ref($msg) && UNIVERSAL::isa($msg, 'OpenSRF::DomainObject::oilsResult')) {
980                 $response = $msg;
981         } else {
982                 $response = new OpenSRF::DomainObject::oilsResult;
983                 $response->content($msg);
984         }
985
986         my $stat = OpenSRF::DomainObject::oilsConnectStatus->new(
987                 statusCode => STATUS_COMPLETE(),
988                 status => 'Request Complete' );
989
990
991         $self->session->send( 'RESULT' => $response, 'STATUS' => $stat, $self->threadTrace);
992         $self->complete(1);
993 }
994
995 sub register_death_callback {
996         my $self = shift;
997         my $cb = shift;
998         $self->session->register_callback( death => $cb );
999 }
1000
1001
1002 # utility method.  checks to see of the request failed.
1003 # if so, throws an OpenSRF::EX::ERROR. if everything is
1004 # ok, it returns the content of the request
1005 sub gather {
1006         my $self = shift;
1007         my $finish = shift;
1008         $self->wait_complete;
1009         my $resp = $self->recv( timeout => 60 );
1010         if( $self->failed() ) { 
1011                 throw OpenSRF::EX::ERROR
1012                         ($self->failed()->stringify());
1013         }
1014         if(!$resp) { return undef; }
1015         my $content = $resp->content;
1016         if($finish) { $self->finish();}
1017         return $content;
1018 }
1019
1020
1021 package OpenSRF::AppSubrequest;
1022
1023 sub respond {
1024         my $self = shift;
1025         my $resp = shift;
1026         push @{$$self{resp}}, $resp if (defined $resp);
1027 }
1028 sub respond_complete { respond(@_); }
1029
1030 sub new {
1031         my $class = shift;
1032         $class = ref($class) || $class;
1033         return bless({resp => [], @_}, $class);
1034 }
1035
1036 sub responses { @{$_[0]->{resp}} }
1037
1038 sub status {}
1039
1040
1041 1;
1042