providing option to connect to memcache at general connect time
[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 my $_last_locale = 'en-US';
25
26 our %_CACHE;
27 our @_RESEND_QUEUE;
28
29 sub CONNECTING { return 3 };
30 sub INIT_CONNECTED { return 4 };
31 sub CONNECTED { return 1 };
32 sub DISCONNECTED { return 2 };
33
34 sub CLIENT { return 2 };
35 sub SERVER { return 1 };
36
37 sub find {
38         return undef unless (defined $_[1]);
39         return $_CACHE{$_[1]} if (exists($_CACHE{$_[1]}));
40 }
41
42 sub transport_connected {
43         my $self = shift;
44         if( ! exists $self->{peer_handle} || ! $self->{peer_handle} ) {
45                 return 0;
46         }
47         return $self->{peer_handle}->tcp_connected();
48 }
49
50 sub connected {
51         my $self = shift;
52         return $self->state == CONNECTED;
53 }
54 # ----------------------------------------------------------------------------
55 # Clears the transport buffers
56 # call this if you are not through with the sesssion, but you want 
57 # to have a clean slate.  You shouldn't have to call this if
58 # you are correctly 'recv'ing all of the data from a request.
59 # however, if you don't want all of the data, this will
60 # slough off any excess
61 #  * * Note: This will delete data for all sessions using this transport
62 # handle.  For example, all client sessions use the same handle.
63 # ----------------------------------------------------------------------------
64 sub buffer_reset {
65
66         my $self = shift;
67         if( ! exists $self->{peer_handle} || ! $self->{peer_handle} ) { 
68                 return 0;
69         }
70         $self->{peer_handle}->buffer_reset();
71 }
72
73
74 # when any incoming data is received, this method is called.
75 sub server_build {
76         my $class = shift;
77         $class = ref($class) || $class;
78
79         my $sess_id = shift;
80         my $remote_id = shift;
81         my $service = shift;
82
83         warn "Missing args to server_build():\n" .
84                 "sess_id: $sess_id, remote_id: $remote_id, service: $service\n" 
85                 unless ($sess_id and $remote_id and $service);
86
87         return undef unless ($sess_id and $remote_id and $service);
88
89         if ( my $thingy = $class->find($sess_id) ) {
90                 $thingy->remote_id( $remote_id );
91                 return $thingy;
92         }
93
94         if( $service eq "client" ) {
95                 #throw OpenSRF::EX::PANIC ("Attempting to build a client session as a server" .
96                 #       " Session ID [$sess_id], remote_id [$remote_id]");
97
98                 warn "Attempting to build a client session as ".
99                                 "a server Session ID [$sess_id], remote_id [$remote_id]";
100
101                 $logger->debug("Attempting to build a client session as ".
102                                 "a server Session ID [$sess_id], remote_id [$remote_id]", ERROR );
103
104                 return undef;
105         }
106
107         my $config_client = OpenSRF::Utils::SettingsClient->new();
108         my $stateless = $config_client->config_value("apps", $service, "stateless");
109
110         #my $max_requests = $conf->$service->max_requests;
111         my $max_requests        = $config_client->config_value("apps",$service,"max_requests");
112         $logger->debug( "Max Requests for $service is $max_requests", INTERNAL ) if (defined $max_requests);
113
114         $logger->transport( "AppSession creating new session: $sess_id", INTERNAL );
115
116         my $self = bless { recv_queue  => [],
117                            request_queue  => [],
118                            requests  => 0,
119                            session_data  => {},
120                            callbacks  => {},
121                            endpoint    => SERVER,
122                            state       => CONNECTING, 
123                            session_id  => $sess_id,
124                            remote_id    => $remote_id,
125                                 peer_handle => OpenSRF::Transport::PeerHandle->retrieve($service),
126                                 max_requests => $max_requests,
127                                 session_threadTrace => 0,
128                                 service => $service,
129                                 stateless => $stateless,
130                          } => $class;
131
132         return $_CACHE{$sess_id} = $self;
133 }
134
135 sub session_data {
136         my $self = shift;
137         my ($name, $datum) = @_;
138
139         $self->{session_data}->{$name} = $datum if (defined $datum);
140         return $self->{session_data}->{$name};
141 }
142
143 sub service { return shift()->{service}; }
144
145 sub continue_request {
146         my $self = shift;
147         $self->{'requests'}++;
148         return 1 if (!$self->{'max_requests'});
149         return $self->{'requests'} <= $self->{'max_requests'} ? 1 : 0;
150 }
151
152 sub last_sent_payload {
153         my( $self, $payload ) = @_;
154         if( $payload ) {
155                 return $self->{'last_sent_payload'} = $payload;
156         }
157         return $self->{'last_sent_payload'};
158 }
159
160 sub session_locale {
161         my( $self, $type ) = @_;
162         if( $type ) {
163         $_last_locale = $type if ($self->endpoint == SERVER);
164                 return $self->{'session_locale'} = $type;
165         }
166         return $self->{'session_locale'};
167 }
168
169 sub last_sent_type {
170         my( $self, $type ) = @_;
171         if( $type ) {
172                 return $self->{'last_sent_type'} = $type;
173         }
174         return $self->{'last_sent_type'};
175 }
176
177 sub get_app_targets {
178         my $app = shift;
179
180         my $conf = OpenSRF::Utils::Config->current;
181         my $router_name = $conf->bootstrap->router_name || 'router';
182         my $routers = $conf->bootstrap->domains;
183
184         unless($router_name and $routers) {
185                 throw OpenSRF::EX::Config 
186                         ("Missing router config information 'router_name' and 'routers'");
187         }
188
189         my @targets;
190         for my $router (@$routers) {
191                 push @targets, "$router_name\@$router/$app";
192         }
193
194         return @targets;
195 }
196
197 sub stateless {
198         my $self = shift;
199         my $state = shift;
200         $self->{stateless} = $state if (defined $state);
201         return $self->{stateless};
202 }
203
204 # When we're a client and we want to connect to a remote service
205 sub create {
206         my $class = shift;
207         $class = ref($class) || $class;
208
209         my $app = shift;
210         my $api_level = shift;
211         my $quiet = shift;
212         my $locale = shift || $_last_locale;
213
214         $api_level = 1 if (!defined($api_level));
215                                 
216         $logger->debug( "AppSession creating new client session for $app", DEBUG );
217
218         my $stateless = 0;
219         my $c = OpenSRF::Utils::SettingsClient->new();
220         # we can get an infinite loop if we're grabbing the settings and we
221         # need the settings to grab the settings...
222         if($app ne "opensrf.settings" || $c->has_config()) { 
223                 $stateless = $c->config_value("apps", $app, "stateless");
224         }
225
226         my $sess_id = time . rand( $$ );
227         while ( $class->find($sess_id) ) {
228                 $sess_id = time . rand( $$ );
229         }
230
231         
232         my ($r_id) = get_app_targets($app);
233
234         my $peer_handle = OpenSRF::Transport::PeerHandle->retrieve("client"); 
235         if( ! $peer_handle ) {
236                 $peer_handle = OpenSRF::Transport::PeerHandle->retrieve("system_client");
237         }
238
239         my $self = bless { app_name    => $app,
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
505         my $locale = $self->session_locale;
506                 $msg->sender_locale($locale) if ($locale);
507         
508                 push @doc, $msg;
509
510         
511                 $logger->info( "AppSession sending ".$msg->type." to ".$self->remote_id.
512                         " with threadTrace [".$msg->threadTrace."]");
513
514         }
515         
516         if ($self->endpoint == CLIENT and ! $disconnect) {
517                 $self->queue_wait(0);
518
519
520                 if($self->stateless && $self->state != CONNECTED) {
521                         $self->reset;
522                         $logger->debug("AppSession is stateless in send", INTERNAL );
523                 }
524
525                 if( !$self->stateless and $self->state != CONNECTED ) {
526
527                         $logger->debug( "Sending connect before request 1", INTERNAL );
528
529                         unless (($self->state == CONNECTING && $connecting )) {
530                                 $logger->debug( "Sending connect before request 2", INTERNAL );
531                                 my $v = $self->connect();
532                                 if( ! $v ) {
533                                         $logger->debug( "Unable to connect to remote service in AppSession::send()", ERROR );
534                                         return undef;
535                                 }
536                                 if( ref($v) and $v->can("class") and $v->class->isa( "OpenSRF::EX" ) ) {
537                                         return $v;
538                                 }
539                         }
540                 }
541
542         } 
543         my $json = OpenSRF::Utils::JSON->perl2JSON(\@doc);
544         $logger->internal("AppSession sending doc: $json");
545
546         $self->{peer_handle}->send( 
547                                         to     => $self->remote_id,
548                                    thread => $self->session_id,
549                                    body   => $json );
550
551         if( $disconnect) {
552                 $self->state( DISCONNECTED );
553         }
554
555         my $req = $self->app_request( $tT );
556         $req->{_start} = time;
557         return $req
558 }
559
560 sub app_request {
561         my $self = shift;
562         my $tT = shift;
563         
564         return undef unless (defined $tT);
565         my ($req) = grep { $_->threadTrace == $tT } @{ $self->{request_queue} };
566
567         return $req;
568 }
569
570 sub remove_app_request {
571         my $self = shift;
572         my $req = shift;
573         
574         my @list = grep { $_->threadTrace != $req->threadTrace } @{ $self->{request_queue} };
575
576         $self->{request_queue} = \@list;
577 }
578
579 sub endpoint {
580         return $_[0]->{endpoint};
581 }
582
583
584 sub session_id {
585         my $self = shift;
586         return $self->{session_id};
587 }
588
589 sub push_queue {
590         my $self = shift;
591         my $resp = shift;
592         my $req = $self->app_request($resp->[1]);
593         return $req->push_queue( $resp->[0] ) if ($req);
594         push @{ $self->{recv_queue} }, $resp->[0];
595 }
596
597 sub last_threadTrace {
598         my $self = shift;
599         my $new_last_threadTrace = shift;
600
601         my $old_last_threadTrace = $self->{last_threadTrace};
602         if (defined $new_last_threadTrace) {
603                 $self->{last_threadTrace} = $new_last_threadTrace;
604                 return $new_last_threadTrace unless ($old_last_threadTrace);
605         }
606
607         return $old_last_threadTrace;
608 }
609
610 sub session_threadTrace {
611         my $self = shift;
612         my $new_last_threadTrace = shift;
613
614         my $old_last_threadTrace = $self->{session_threadTrace};
615         if (defined $new_last_threadTrace) {
616                 $self->{session_threadTrace} = $new_last_threadTrace;
617                 return $new_last_threadTrace unless ($old_last_threadTrace);
618         }
619
620         return $old_last_threadTrace;
621 }
622
623 sub last_message_type {
624         my $self = shift;
625         my $new_last_message_type = shift;
626
627         my $old_last_message_type = $self->{last_message_type};
628         if (defined $new_last_message_type) {
629                 $self->{last_message_type} = $new_last_message_type;
630                 return $new_last_message_type unless ($old_last_message_type);
631         }
632
633         return $old_last_message_type;
634 }
635
636 sub last_message_api_level {
637         my $self = shift;
638         my $new_last_message_api_level = shift;
639
640         my $old_last_message_api_level = $self->{last_message_api_level};
641         if (defined $new_last_message_api_level) {
642                 $self->{last_message_api_level} = $new_last_message_api_level;
643                 return $new_last_message_api_level unless ($old_last_message_api_level);
644         }
645
646         return $old_last_message_api_level;
647 }
648
649 sub remote_id {
650         my $self = shift;
651         my $new_remote_id = shift;
652
653         my $old_remote_id = $self->{remote_id};
654         if (defined $new_remote_id) {
655                 $self->{remote_id} = $new_remote_id;
656                 return $new_remote_id unless ($old_remote_id);
657         }
658
659         return $old_remote_id;
660 }
661
662 sub client_auth {
663         return undef;
664         my $self = shift;
665         my $new_ua = shift;
666
667         my $old_ua = $self->{client_auth};
668         if (defined $new_ua) {
669                 $self->{client_auth} = $new_ua;
670                 return $new_ua unless ($old_ua);
671         }
672
673         return $old_ua->cloneNode(1);
674 }
675
676 sub state {
677         my $self = shift;
678         my $new_state = shift;
679
680         my $old_state = $self->{state};
681         if (defined $new_state) {
682                 $self->{state} = $new_state;
683                 return $new_state unless ($old_state);
684         }
685
686         return $old_state;
687 }
688
689 sub DESTROY {
690         my $self = shift;
691         delete $$self{$_} for keys %$self;
692         return undef;
693 }
694
695 sub recv {
696         my $self = shift;
697         my @proto_args = @_;
698         my %args;
699
700         if ( @proto_args ) {
701                 if ( !(@proto_args % 2) ) {
702                         %args = @proto_args;
703                 } elsif (@proto_args == 1) {
704                         %args = ( timeout => @proto_args );
705                 }
706         }
707
708         #$logger->debug( ref($self). " recv_queue before wait: " . $self->_print_queue(), INTERNAL );
709
710         if( exists( $args{timeout} ) ) {
711                 $args{timeout} = int($args{timeout});
712                 $self->{recv_timeout} = $args{timeout};
713         }
714
715         #$args{timeout} = 0 if ($self->complete);
716
717         if(defined($args{timeout})) {
718                 $logger->debug( ref($self) ."->recv with timeout " . $args{timeout}, INTERNAL );
719         }
720
721         my $avail = @{ $self->{recv_queue} };
722         $self->{remaining_recv_timeout} = $self->{recv_timeout};
723
724         if (!$args{count}) {
725                 if (wantarray) {
726                         $args{count} = $avail;
727                 } else {
728                         $args{count} = 1;
729                 }
730         }
731
732         while ( $self->{remaining_recv_timeout} > 0 and $avail < $args{count} ) {
733                         last if $self->complete;
734                         my $starttime = time;
735                         $self->queue_wait($self->{remaining_recv_timeout});
736                         my $endtime = time;
737                         if ($self->{timeout_reset}) {
738                                 $self->{timeout_reset} = 0;
739                         } else {
740                                 $self->{remaining_recv_timeout} -= ($endtime - $starttime)
741                         }
742                         $avail = @{ $self->{recv_queue} };
743         }
744
745
746         my @list;
747         while ( my $msg = shift @{ $self->{recv_queue} } ) {
748                 push @list, $msg;
749                 last if (scalar(@list) >= $args{count});
750         }
751
752         $logger->debug( "Number of matched responses: " . @list, DEBUG );
753         $self->queue_wait(0); # check for statuses
754         
755         return $list[0] if (!wantarray);
756         return @list;
757 }
758
759 sub push_resend {
760         my $self = shift;
761         push @OpenSRF::AppSession::_RESEND_QUEUE, @_;
762 }
763
764 sub flush_resend {
765         my $self = shift;
766         $logger->debug( "Resending..." . @_RESEND_QUEUE, INTERNAL );
767         while ( my $req = shift @OpenSRF::AppSession::_RESEND_QUEUE ) {
768                 $req->resend unless $req->complete;
769         }
770 }
771
772
773 sub queue_wait {
774         my $self = shift;
775         if( ! $self->{peer_handle} ) { return 0; }
776         my $timeout = shift || 0;
777         $logger->debug( "Calling queue_wait($timeout)" , INTERNAL );
778         my $o = $self->{peer_handle}->process($timeout);
779         $self->flush_resend;
780         return $o;
781 }
782
783 sub _print_queue {
784         my( $self ) = @_;
785         my $string = "";
786         foreach my $msg ( @{$self->{recv_queue}} ) {
787                 $string = $string . $msg->toString(1) . "\n";
788         }
789         return $string;
790 }
791
792 sub status {
793         my $self = shift;
794         return unless $self;
795         $self->send( 'STATUS', @_ );
796 }
797
798 sub reset_request_timeout {
799         my $self = shift;
800         my $tt = shift;
801         my $req = $self->app_request($tt);
802         $req->{remaining_recv_timeout} = $req->{recv_timeout};
803         $req->{timout_reset} = 1;
804 }
805
806 #-------------------------------------------------------------------------------
807
808 package OpenSRF::AppRequest;
809 use base qw/OpenSRF::AppSession/;
810 use OpenSRF::Utils::Logger qw/:level/;
811 use OpenSRF::DomainObject::oilsResponse qw/:status/;
812 use Time::HiRes qw/time usleep/;
813
814 sub new {
815         my $class = shift;
816         $class = ref($class) || $class;
817
818         my $session = shift;
819         my $threadTrace = $session->session_threadTrace || $session->last_threadTrace;
820         my $payload = shift;
821         
822         my $self = {    session                 => $session,
823                         threadTrace             => $threadTrace,
824                         payload                 => $payload,
825                         complete                => 0,
826                         timeout_reset           => 0,
827                         recv_timeout            => 30,
828                         remaining_recv_timeout  => 30,
829                         recv_queue              => [],
830         };
831
832         bless $self => $class;
833
834         push @{ $self->session->{request_queue} }, $self;
835
836         return $self;
837 }
838
839 sub recv_timeout {
840         my $self = shift;
841         my $timeout = shift;
842         if (defined $timeout) {
843                 $self->{recv_timeout} = $timeout;
844                 $self->{remaining_recv_timeout} = $timeout;
845         }
846         return $self->{recv_timeout};
847 }
848
849 sub queue_size {
850         my $size = @{$_[0]->{recv_queue}};
851         return $size;
852 }
853         
854 sub send {
855         my $self = shift;
856         return unless ($self and $self->session and !$self->complete);
857         $self->session->send(@_);
858 }
859
860 sub finish {
861         my $self = shift;
862         return unless $self->session;
863         $self->session->remove_app_request($self);
864         delete($$self{$_}) for (keys %$self);
865 }
866
867 sub session {
868         return shift()->{session};
869 }
870
871 sub complete {
872         my $self = shift;
873         my $complete = shift;
874         return $self->{complete} if ($self->{complete});
875         if (defined $complete) {
876                 $self->{complete} = $complete;
877                 $self->{_duration} = time - $self->{_start} if ($self->{complete});
878         } else {
879                 $self->session->queue_wait(0);
880         }
881         return $self->{complete};
882 }
883
884 sub duration {
885         my $self = shift;
886         $self->wait_complete;
887         return $self->{_duration};
888 }
889
890 sub wait_complete {
891         my $self = shift;
892         my $timeout = shift || 10;
893         my $time_remaining = $timeout;
894
895         while ( ! $self->complete  and $time_remaining > 0 ) {
896                 my $starttime = time;
897                 $self->queue_wait($time_remaining);
898                 my $endtime = time;
899                 $time_remaining -= ($endtime - $starttime);
900         }
901
902         return $self->complete;
903 }
904
905 sub threadTrace {
906         return shift()->{threadTrace};
907 }
908
909 sub push_queue {
910         my $self = shift;
911         my $resp = shift;
912         if( !$resp ) { return 0; }
913         if( UNIVERSAL::isa($resp, "Error")) {
914                 $self->{failed} = $resp;
915                 $self->complete(1);
916                 #return; eventually...
917         }
918         push @{ $self->{recv_queue} }, $resp;
919 }
920
921 sub failed {
922         my $self = shift;
923         return $self->{failed};
924 }
925
926 sub queue_wait {
927         my $self = shift;
928         return $self->session->queue_wait(@_)
929 }
930
931 sub payload { return shift()->{payload}; }
932
933 sub resend {
934         my $self = shift;
935         return unless ($self and $self->session and !$self->complete);
936         OpenSRF::Utils::Logger->debug( "I'm resending the request for threadTrace ". $self->threadTrace, DEBUG);
937         return $self->session->send('REQUEST', $self->payload, $self->threadTrace );
938 }
939
940 sub status {
941         my $self = shift;
942         my $msg = shift;
943         return unless ($self and $self->session and !$self->complete);
944         $self->session->send( 'STATUS',$msg, $self->threadTrace );
945 }
946
947 sub stream_push {
948         my $self = shift;
949         my $msg = shift;
950         $self->respond( $msg );
951 }
952
953 sub respond {
954         my $self = shift;
955         my $msg = shift;
956         return unless ($self and $self->session and !$self->complete);
957
958         my $response;
959         if (ref($msg) && UNIVERSAL::isa($msg, 'OpenSRF::DomainObject::oilsResult')) {
960                 $response = $msg;
961         } else {
962                 $response = new OpenSRF::DomainObject::oilsResult;
963                 $response->content($msg);
964         }
965
966         $self->session->send('RESULT', $response, $self->threadTrace);
967 }
968
969 sub respond_complete {
970         my $self = shift;
971         my $msg = shift;
972         return unless ($self and $self->session and !$self->complete);
973
974         my $response;
975         if (ref($msg) && UNIVERSAL::isa($msg, 'OpenSRF::DomainObject::oilsResult')) {
976                 $response = $msg;
977         } else {
978                 $response = new OpenSRF::DomainObject::oilsResult;
979                 $response->content($msg);
980         }
981
982         my $stat = OpenSRF::DomainObject::oilsConnectStatus->new(
983                 statusCode => STATUS_COMPLETE(),
984                 status => 'Request Complete' );
985
986
987         $self->session->send( 'RESULT' => $response, 'STATUS' => $stat, $self->threadTrace);
988         $self->complete(1);
989 }
990
991 sub register_death_callback {
992         my $self = shift;
993         my $cb = shift;
994         $self->session->register_callback( death => $cb );
995 }
996
997
998 # utility method.  checks to see of the request failed.
999 # if so, throws an OpenSRF::EX::ERROR. if everything is
1000 # ok, it returns the content of the request
1001 sub gather {
1002         my $self = shift;
1003         my $finish = shift;
1004         $self->wait_complete;
1005         my $resp = $self->recv( timeout => 60 );
1006         if( $self->failed() ) { 
1007                 throw OpenSRF::EX::ERROR
1008                         ($self->failed()->stringify());
1009         }
1010         if(!$resp) { return undef; }
1011         my $content = $resp->content;
1012         if($finish) { $self->finish();}
1013         return $content;
1014 }
1015
1016
1017 package OpenSRF::AppSubrequest;
1018
1019 sub respond {
1020         my $self = shift;
1021         my $resp = shift;
1022         push @{$$self{resp}}, $resp if (defined $resp);
1023 }
1024 sub respond_complete { respond(@_); }
1025
1026 sub new {
1027         my $class = shift;
1028         $class = ref($class) || $class;
1029         return bless({resp => [], @_}, $class);
1030 }
1031
1032 sub responses { @{$_[0]->{resp}} }
1033
1034 sub status {}
1035
1036
1037 1;
1038