adding the transparent subrequest logic, it will be enabled when the Settings server...
[OpenSRF.git] / src / perlmods / OpenSRF / Application.pm
1 package OpenSRF::Application;
2 use vars qw/$_app $log @_METHODS $thunk//;
3
4 use base qw/OpenSRF/;
5 use OpenSRF::AppSession;
6 use OpenSRF::DomainObject::oilsMethod;
7 use OpenSRF::DomainObject::oilsResponse qw/:status/;
8 use OpenSRF::Utils::Logger qw/:level/;
9 use Data::Dumper;
10 use Time::HiRes qw/time/;
11 use OpenSRF::EX qw/:try/;
12 use OpenSRF::UnixServer;  # to get the server class from UnixServer::App
13
14 use strict;
15 use warnings;
16
17 $log = 'OpenSRF::Utils::Logger';
18
19 our $in_request = 0;
20 our @pending_requests;
21
22 sub thunk {
23         my $self = shift;
24         my $flag = shift;
25         $thunk = $flag if (defined $flag);
26         return $thunk;
27 }
28
29 sub application_implementation {
30         my $self = shift;
31         my $app = shift;
32
33         if (defined $app) {
34                 $_app = $app;
35                 eval "use $_app;";
36                 if( $@ ) {
37                         $log->error( "Error loading application_implementation: $app -> $@", ERROR);
38                 }
39
40         }
41
42         return $_app;
43 }
44
45 sub handler {
46         my ($self, $session, $app_msg) = @_;
47
48         if( ! $app_msg ) {
49                 return 0;  # error?
50         }
51
52         $log->debug( "In Application::handler()", DEBUG );
53
54         my $app = $self->application_implementation;
55
56         if( $app ) {
57                 $log->debug( "Application is $app", DEBUG);
58         }
59         $log->debug( "Message is ".$app_msg->toString(1), INTERNAL);
60
61
62         if ($session->last_message_type eq 'REQUEST') {
63                 $log->debug( "We got a REQUEST: ". $app_msg->method, INFO );
64
65                 my $method_name = $app_msg->method;
66                 $log->debug( " * Looking up $method_name inside $app", DEBUG);
67
68                 my $method_proto = $session->last_message_api_level;
69                 $log->debug( " * Method API Level [$method_proto]", DEBUG);
70
71                 my $coderef = $app->method_lookup( $method_name, $method_proto );
72
73                 unless ($coderef) {
74                         $session->status( OpenSRF::DomainObject::oilsMethodException->new() );
75                         return 1;
76                 }
77
78                 $log->debug( " (we got coderef $coderef", DEBUG);
79
80                 unless ($session->continue_request) {
81                         $session->status(
82                                 OpenSRF::DomainObject::oilsConnectStatus->new(
83                                                 statusCode => STATUS_REDIRECTED(),
84                                                 status => 'Disconnect on max requests' ) );
85                         $session->kill_me;
86                         return 1;
87                 }
88
89                 if (ref $coderef) {
90                         my @args = $app_msg->params;
91                         my $appreq = OpenSRF::AppRequest->new( $session );
92
93                         $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
94                         if( $in_request ) {
95                                 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
96                                 push @pending_requests, [ $appreq, \@args, $coderef ]; 
97                                 return 1;
98                         }
99
100
101                         $in_request++;
102
103                         $log->debug( "Executing coderef for {$method_name -> ".join(', ', @args)."}", INTERNAL );
104
105                         my $resp;
106                         try {
107                                 my $start = time();
108                                 $resp = $coderef->run( $appreq, @args); 
109                                 my $time = sprintf '%.3f', time() - $start;
110                                 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}:  ". $time, DEBUG );
111                                 if( ref( $resp ) ) {
112                                         $log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
113                                         $appreq->respond_complete( $resp );
114                                 } else {
115                                         $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
116                                                                 statusCode => STATUS_COMPLETE(),
117                                                                 status => 'Request Complete' ) );
118                                 }
119                         } catch Error with {
120                                 my $e = shift;
121                                 $e = $e->{-text} || $e->message if (ref $e);
122                                 my $sess_id = $session->session_id;
123                                 $session->status(
124                                         OpenSRF::DomainObject::oilsMethodException->new(
125                                                         statusCode      => STATUS_INTERNALSERVERERROR(),
126                                                         status          => " *** Call to [$method_name] failed for session ".
127                                                                            "[$sess_id], thread trace [".$appreq->threadTrace."]:\n".$e
128                                         )
129                                 );
130                         };
131
132
133
134                         # ----------------------------------------------
135
136
137                         # XXX may need this later
138                         # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
139
140                         $in_request--;
141
142                         $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
143
144                         # cycle through queued requests
145                         while( my $aref = shift @pending_requests ) {
146                                 $in_request++;
147                                 my $resp;
148                                 try {
149                                         my $start = time;
150                                         my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
151                                         my $time = sprintf '%.3f', time - $start;
152                                         $log->debug( "Method duration for {[".$aref->[2]->name." -> ".join(', ',@{$aref->[1]}).'}:  '.$time, DEBUG );
153
154                                         $appreq = $aref->[0];   
155                                         if( ref( $response ) ) {
156                                                 $log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
157                                                 $appreq->respond_complete( $response );
158                                         } else {
159                                                 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
160                                                                         statusCode => STATUS_COMPLETE(),
161                                                                         status => 'Request Complete' ) );
162                                         }
163                                         $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
164                                 } catch Error with {
165                                         my $e = shift;
166                                         $session->status(
167                                                 OpenSRF::DomainObject::oilsMethodException->new(
168                                                                 statusCode => STATUS_INTERNALSERVERERROR(),
169                                                                 status => "Call to [".$aref->[2]->name."] faild:  ".$e->{-text}
170                                                 )
171                                         );
172                                 };
173                                 $in_request--;
174                         }
175
176                         return 1;
177                 } 
178                 my $res = OpenSRF::DomainObject::oilsMethodException->new;
179                 $session->send('ERROR', $res);
180                 $session->kill_me;
181                 return 1;
182
183         } else {
184                 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
185                 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
186         }
187
188         $session->last_message_type('');
189         $session->last_message_api_level('');
190
191         return 1;
192 }
193
194 sub register_method {
195         my $self = shift;
196         my $app = ref($self) || $self;
197         my %args = @_;
198
199
200         throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
201
202         $args{api_level} ||= 1;
203         $args{stream} ||= 0;
204         $args{remote} ||= 0;
205         $args{package} ||= $app;                
206         $args{api_name} ||= UnixServer->app() . '.' . $args{method};
207         $args{server_class} ||= UnixServer->app();
208
209         $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
210
211         __PACKAGE__->register_method(
212                 stream => 0,
213                 api_name => $args{api_name}.'.atomic',
214                 method => 'make_stream_atomic'
215         ) if ($stream);
216 }
217
218 sub retrieve_remote_apis {
219         my $session = AppSession->create('settings');
220         try {
221                 $session->connect;
222         } catch ERROR with {
223                 my $e = shift;
224                 $log->debug( "Remote subrequest returned an error:\n". $e );
225                 return undef;
226         } finally {
227                 return undef unless ($session->state == $session->CONNECTED);
228         }
229
230         my $req = $session->request( 'opensrf.settings.xpath.get' );
231         my $list = $req->recv->content;
232         $req->finish;
233         $session->finish;
234         $session->disconnect;
235
236         my %u_list = map { ($_ => 1) } @$list;
237
238         for my $class ( keys %u_list ) {
239                 populate_remote_method_cache($class);
240         }
241 }
242
243 sub populate_remote_method_cache {
244         my $class = shift;
245
246         my $session = AppSession->create($class);
247         try {
248                 $session->connect;
249         } catch ERROR with {
250                 my $e = shift;
251                 $log->debug( "Remote subrequest returned an error:\n". $e );
252                 return undef;
253         } finally {
254                 return undef unless ($session->state == $session->CONNECTED);
255         }
256
257         my $req = $session->request( 'opensrf.settings.xpath.get' );
258
259         while (my $method = $req->recv->content) {
260                 $method->{remote} = 1;
261                 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
262         }
263
264         $req->finish;
265         $session->finish;
266         $session->disconnect;
267 }
268
269 sub method_lookup {             
270         my $self = shift;
271         my $method = shift;
272         my $proto = shift;
273         my $no_recurse = shift || 0;
274
275         # this instead of " || 1;" above to allow api_level 0
276         $proto = 1 unless (defined $proto);
277
278         my $class = ref($self) || $self;
279
280         $log->debug("Lookup of [$method] by [$class]", DEBUG);
281         $log->debug("Available methods\n".Dumper(\%_METHODS), INTERNAL);
282
283         my $meth;
284         if (__PACKAGE__->thunk) {
285                 for my $p ( reverse(1 .. $proto) ) {
286                         if (exists $_METHODS[$p]{$method}) {
287                                 $meth = $_METHODS[$p]{$method};
288                         }
289                 }
290         } else {
291                 if (exists $_METHODS[$proto]{$method}) {
292                         $meth = $_METHODS[$proto]{$method};
293                 }
294         }
295
296         if (defined $meth) {
297                 $log->debug("Looks like we found [$method]!", DEBUG);
298                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
299         } elsif (!$no_recurse) {
300
301                 # XXX Remvoe this to activate the magic!
302                 return $meth;
303                 # XXX Remvoe this to activate the magic!
304                 
305                 retrieve_remote_apis();
306                 $self->method_lookup($method,$proto,1);
307         }
308
309         return $meth;
310 }
311
312 sub run {
313         my $self = shift;
314         my $req = shift;
315
316         my $resp;
317
318         if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
319                 $log->debug("Creating a SubRequest object", DEBUG);
320                 unshift @_, $req;
321                 $req = OpenSRF::AppSubrequest->new;
322         } else {
323                 $log->debug("This is a top level request", DEBUG);
324         }
325
326         if (!$self->{remote}) {
327                 my $code ||= \&{$app . '::' . $self->{method}};
328                 $resp = $code->($self, $req, @_);
329
330                 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
331                         $req->respond($resp) if (defined $resp);
332                         return $req->responses;
333                 } else {
334                         $log->debug("A top level Request object is responding $resp", DEBUG);
335                         return $resp;
336                 }
337         } else {
338                 my $session = AppSession->create($self->{server_class});
339                 try {
340                         $session->connect;
341                 } catch ERROR with {
342                         my $e = shift;
343                         $log->debug( "Remote subrequest returned an error:\n". $e );
344                         return undef;
345                 } finally {
346                         return undef unless ($session->state == $session->CONNECTED);
347                 }
348
349                 my $remote_req = $session->request( $self->{api_name}, @_ );
350                 while (my $remote_resp = $remote_req->recv) {
351                         $req->respond( $remote_resp );
352                 }
353                 return $req->responses;
354         }
355         # huh? how'd we get here...
356         return undef;
357 }
358
359 sub introspect {
360         my $self = shift;
361         my $client = shift;
362
363         for my $api_level ( 1 .. $#_METHODS ) {
364                 $client->respond( { $api_level => $_METHODS[$api_level] } );
365         }
366
367         return undef;
368 }
369 __PACKAGE__->register_method(
370         stream => 1,
371         method => 'introspect',
372         api_name => 'opensrf.system.method_list'
373 );
374
375 sub make_stream_atomic {
376         my $self = shift;
377         my $req = shift;
378         my @args = @_;
379
380         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
381         my @results = $self->method_lookup($m_name)->run(@args);
382
383         if (@results == 1) {
384                 return $results[0];
385         }
386         return \@results;
387 }
388
389
390 1;