76f6c090ef9f259e2c281b986f020e9d92cea20b
[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                                    locale => $self->session_locale,
548                                    body   => $json );
549
550         if( $disconnect) {
551                 $self->state( DISCONNECTED );
552         }
553
554         my $req = $self->app_request( $tT );
555         $req->{_start} = time;
556         return $req
557 }
558
559 sub app_request {
560         my $self = shift;
561         my $tT = shift;
562         
563         return undef unless (defined $tT);
564         my ($req) = grep { $_->threadTrace == $tT } @{ $self->{request_queue} };
565
566         return $req;
567 }
568
569 sub remove_app_request {
570         my $self = shift;
571         my $req = shift;
572         
573         my @list = grep { $_->threadTrace != $req->threadTrace } @{ $self->{request_queue} };
574
575         $self->{request_queue} = \@list;
576 }
577
578 sub endpoint {
579         return $_[0]->{endpoint};
580 }
581
582
583 sub session_id {
584         my $self = shift;
585         return $self->{session_id};
586 }
587
588 sub push_queue {
589         my $self = shift;
590         my $resp = shift;
591         my $req = $self->app_request($resp->[1]);
592         return $req->push_queue( $resp->[0] ) if ($req);
593         push @{ $self->{recv_queue} }, $resp->[0];
594 }
595
596 sub last_threadTrace {
597         my $self = shift;
598         my $new_last_threadTrace = shift;
599
600         my $old_last_threadTrace = $self->{last_threadTrace};
601         if (defined $new_last_threadTrace) {
602                 $self->{last_threadTrace} = $new_last_threadTrace;
603                 return $new_last_threadTrace unless ($old_last_threadTrace);
604         }
605
606         return $old_last_threadTrace;
607 }
608
609 sub session_threadTrace {
610         my $self = shift;
611         my $new_last_threadTrace = shift;
612
613         my $old_last_threadTrace = $self->{session_threadTrace};
614         if (defined $new_last_threadTrace) {
615                 $self->{session_threadTrace} = $new_last_threadTrace;
616                 return $new_last_threadTrace unless ($old_last_threadTrace);
617         }
618
619         return $old_last_threadTrace;
620 }
621
622 sub last_message_type {
623         my $self = shift;
624         my $new_last_message_type = shift;
625
626         my $old_last_message_type = $self->{last_message_type};
627         if (defined $new_last_message_type) {
628                 $self->{last_message_type} = $new_last_message_type;
629                 return $new_last_message_type unless ($old_last_message_type);
630         }
631
632         return $old_last_message_type;
633 }
634
635 sub last_message_api_level {
636         my $self = shift;
637         my $new_last_message_api_level = shift;
638
639         my $old_last_message_api_level = $self->{last_message_api_level};
640         if (defined $new_last_message_api_level) {
641                 $self->{last_message_api_level} = $new_last_message_api_level;
642                 return $new_last_message_api_level unless ($old_last_message_api_level);
643         }
644
645         return $old_last_message_api_level;
646 }
647
648 sub remote_id {
649         my $self = shift;
650         my $new_remote_id = shift;
651
652         my $old_remote_id = $self->{remote_id};
653         if (defined $new_remote_id) {
654                 $self->{remote_id} = $new_remote_id;
655                 return $new_remote_id unless ($old_remote_id);
656         }
657
658         return $old_remote_id;
659 }
660
661 sub client_auth {
662         return undef;
663         my $self = shift;
664         my $new_ua = shift;
665
666         my $old_ua = $self->{client_auth};
667         if (defined $new_ua) {
668                 $self->{client_auth} = $new_ua;
669                 return $new_ua unless ($old_ua);
670         }
671
672         return $old_ua->cloneNode(1);
673 }
674
675 sub state {
676         my $self = shift;
677         my $new_state = shift;
678
679         my $old_state = $self->{state};
680         if (defined $new_state) {
681                 $self->{state} = $new_state;
682                 return $new_state unless ($old_state);
683         }
684
685         return $old_state;
686 }
687
688 sub DESTROY {
689         my $self = shift;
690         delete $$self{$_} for keys %$self;
691         return undef;
692 }
693
694 sub recv {
695         my $self = shift;
696         my @proto_args = @_;
697         my %args;
698
699         if ( @proto_args ) {
700                 if ( !(@proto_args % 2) ) {
701                         %args = @proto_args;
702                 } elsif (@proto_args == 1) {
703                         %args = ( timeout => @proto_args );
704                 }
705         }
706
707         #$logger->debug( ref($self). " recv_queue before wait: " . $self->_print_queue(), INTERNAL );
708
709         if( exists( $args{timeout} ) ) {
710                 $args{timeout} = int($args{timeout});
711                 $self->{recv_timeout} = $args{timeout};
712         }
713
714         #$args{timeout} = 0 if ($self->complete);
715
716         if(defined($args{timeout})) {
717                 $logger->debug( ref($self) ."->recv with timeout " . $args{timeout}, INTERNAL );
718         }
719
720         my $avail = @{ $self->{recv_queue} };
721         $self->{remaining_recv_timeout} = $self->{recv_timeout};
722
723         if (!$args{count}) {
724                 if (wantarray) {
725                         $args{count} = $avail;
726                 } else {
727                         $args{count} = 1;
728                 }
729         }
730
731         while ( $self->{remaining_recv_timeout} > 0 and $avail < $args{count} ) {
732                         last if $self->complete;
733                         my $starttime = time;
734                         $self->queue_wait($self->{remaining_recv_timeout});
735                         my $endtime = time;
736                         if ($self->{timeout_reset}) {
737                                 $self->{timeout_reset} = 0;
738                         } else {
739                                 $self->{remaining_recv_timeout} -= ($endtime - $starttime)
740                         }
741                         $avail = @{ $self->{recv_queue} };
742         }
743
744
745         my @list;
746         while ( my $msg = shift @{ $self->{recv_queue} } ) {
747                 push @list, $msg;
748                 last if (scalar(@list) >= $args{count});
749         }
750
751         $logger->debug( "Number of matched responses: " . @list, DEBUG );
752         $self->queue_wait(0); # check for statuses
753         
754         return $list[0] if (!wantarray);
755         return @list;
756 }
757
758 sub push_resend {
759         my $self = shift;
760         push @OpenSRF::AppSession::_RESEND_QUEUE, @_;
761 }
762
763 sub flush_resend {
764         my $self = shift;
765         $logger->debug( "Resending..." . @_RESEND_QUEUE, INTERNAL );
766         while ( my $req = shift @OpenSRF::AppSession::_RESEND_QUEUE ) {
767                 $req->resend unless $req->complete;
768         }
769 }
770
771
772 sub queue_wait {
773         my $self = shift;
774         if( ! $self->{peer_handle} ) { return 0; }
775         my $timeout = shift || 0;
776         $logger->debug( "Calling queue_wait($timeout)" , INTERNAL );
777         my $o = $self->{peer_handle}->process($timeout);
778         $self->flush_resend;
779         return $o;
780 }
781
782 sub _print_queue {
783         my( $self ) = @_;
784         my $string = "";
785         foreach my $msg ( @{$self->{recv_queue}} ) {
786                 $string = $string . $msg->toString(1) . "\n";
787         }
788         return $string;
789 }
790
791 sub status {
792         my $self = shift;
793         return unless $self;
794         $self->send( 'STATUS', @_ );
795 }
796
797 sub reset_request_timeout {
798         my $self = shift;
799         my $tt = shift;
800         my $req = $self->app_request($tt);
801         $req->{remaining_recv_timeout} = $req->{recv_timeout};
802         $req->{timout_reset} = 1;
803 }
804
805 #-------------------------------------------------------------------------------
806
807 package OpenSRF::AppRequest;
808 use base qw/OpenSRF::AppSession/;
809 use OpenSRF::Utils::Logger qw/:level/;
810 use OpenSRF::DomainObject::oilsResponse qw/:status/;
811 use Time::HiRes qw/time usleep/;
812
813 sub new {
814         my $class = shift;
815         $class = ref($class) || $class;
816
817         my $session = shift;
818         my $threadTrace = $session->session_threadTrace || $session->last_threadTrace;
819         my $payload = shift;
820         
821         my $self = {    session                 => $session,
822                         threadTrace             => $threadTrace,
823                         payload                 => $payload,
824                         complete                => 0,
825                         timeout_reset           => 0,
826                         recv_timeout            => 30,
827                         remaining_recv_timeout  => 30,
828                         recv_queue              => [],
829         };
830
831         bless $self => $class;
832
833         push @{ $self->session->{request_queue} }, $self;
834
835         return $self;
836 }
837
838 sub recv_timeout {
839         my $self = shift;
840         my $timeout = shift;
841         if (defined $timeout) {
842                 $self->{recv_timeout} = $timeout;
843                 $self->{remaining_recv_timeout} = $timeout;
844         }
845         return $self->{recv_timeout};
846 }
847
848 sub queue_size {
849         my $size = @{$_[0]->{recv_queue}};
850         return $size;
851 }
852         
853 sub send {
854         my $self = shift;
855         return unless ($self and $self->session and !$self->complete);
856         $self->session->send(@_);
857 }
858
859 sub finish {
860         my $self = shift;
861         return unless $self->session;
862         $self->session->remove_app_request($self);
863         delete($$self{$_}) for (keys %$self);
864 }
865
866 sub session {
867         return shift()->{session};
868 }
869
870 sub complete {
871         my $self = shift;
872         my $complete = shift;
873         return $self->{complete} if ($self->{complete});
874         if (defined $complete) {
875                 $self->{complete} = $complete;
876                 $self->{_duration} = time - $self->{_start} if ($self->{complete});
877         } else {
878                 $self->session->queue_wait(0);
879         }
880         return $self->{complete};
881 }
882
883 sub duration {
884         my $self = shift;
885         $self->wait_complete;
886         return $self->{_duration};
887 }
888
889 sub wait_complete {
890         my $self = shift;
891         my $timeout = shift || 10;
892         my $time_remaining = $timeout;
893
894         while ( ! $self->complete  and $time_remaining > 0 ) {
895                 my $starttime = time;
896                 $self->queue_wait($time_remaining);
897                 my $endtime = time;
898                 $time_remaining -= ($endtime - $starttime);
899         }
900
901         return $self->complete;
902 }
903
904 sub threadTrace {
905         return shift()->{threadTrace};
906 }
907
908 sub push_queue {
909         my $self = shift;
910         my $resp = shift;
911         if( !$resp ) { return 0; }
912         if( UNIVERSAL::isa($resp, "Error")) {
913                 $self->{failed} = $resp;
914                 $self->complete(1);
915                 #return; eventually...
916         }
917         push @{ $self->{recv_queue} }, $resp;
918 }
919
920 sub failed {
921         my $self = shift;
922         return $self->{failed};
923 }
924
925 sub queue_wait {
926         my $self = shift;
927         return $self->session->queue_wait(@_)
928 }
929
930 sub payload { return shift()->{payload}; }
931
932 sub resend {
933         my $self = shift;
934         return unless ($self and $self->session and !$self->complete);
935         OpenSRF::Utils::Logger->debug( "I'm resending the request for threadTrace ". $self->threadTrace, DEBUG);
936         return $self->session->send('REQUEST', $self->payload, $self->threadTrace );
937 }
938
939 sub status {
940         my $self = shift;
941         my $msg = shift;
942         return unless ($self and $self->session and !$self->complete);
943         $self->session->send( 'STATUS',$msg, $self->threadTrace );
944 }
945
946 sub stream_push {
947         my $self = shift;
948         my $msg = shift;
949         $self->respond( $msg );
950 }
951
952 sub respond {
953         my $self = shift;
954         my $msg = shift;
955         return unless ($self and $self->session and !$self->complete);
956
957         my $response;
958         if (ref($msg) && UNIVERSAL::isa($msg, 'OpenSRF::DomainObject::oilsResult')) {
959                 $response = $msg;
960         } else {
961                 $response = new OpenSRF::DomainObject::oilsResult;
962                 $response->content($msg);
963         }
964
965         $self->session->send('RESULT', $response, $self->threadTrace);
966 }
967
968 sub respond_complete {
969         my $self = shift;
970         my $msg = shift;
971         return unless ($self and $self->session and !$self->complete);
972
973         my $response;
974         if (ref($msg) && UNIVERSAL::isa($msg, 'OpenSRF::DomainObject::oilsResult')) {
975                 $response = $msg;
976         } else {
977                 $response = new OpenSRF::DomainObject::oilsResult;
978                 $response->content($msg);
979         }
980
981         my $stat = OpenSRF::DomainObject::oilsConnectStatus->new(
982                 statusCode => STATUS_COMPLETE(),
983                 status => 'Request Complete' );
984
985
986         $self->session->send( 'RESULT' => $response, 'STATUS' => $stat, $self->threadTrace);
987         $self->complete(1);
988 }
989
990 sub register_death_callback {
991         my $self = shift;
992         my $cb = shift;
993         $self->session->register_callback( death => $cb );
994 }
995
996
997 # utility method.  checks to see of the request failed.
998 # if so, throws an OpenSRF::EX::ERROR. if everything is
999 # ok, it returns the content of the request
1000 sub gather {
1001         my $self = shift;
1002         my $finish = shift;
1003         $self->wait_complete;
1004         my $resp = $self->recv( timeout => 60 );
1005         if( $self->failed() ) { 
1006                 throw OpenSRF::EX::ERROR
1007                         ($self->failed()->stringify());
1008         }
1009         if(!$resp) { return undef; }
1010         my $content = $resp->content;
1011         if($finish) { $self->finish();}
1012         return $content;
1013 }
1014
1015
1016 package OpenSRF::AppSubrequest;
1017
1018 sub respond {
1019         my $self = shift;
1020         my $resp = shift;
1021         push @{$$self{resp}}, $resp if (defined $resp);
1022 }
1023 sub respond_complete { respond(@_); }
1024
1025 sub new {
1026         my $class = shift;
1027         $class = ref($class) || $class;
1028         return bless({resp => [], @_}, $class);
1029 }
1030
1031 sub responses { @{$_[0]->{resp}} }
1032
1033 sub status {}
1034
1035
1036 1;
1037