a2da7059056e8ff51d34d0429ea16ca75b04c4b0
[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{package} ||= $app;                
205         $args{api_name} ||= UnixServer->app() . '.' . $args{method};
206         $args{server_class} ||= UnixServer->app();
207         $args{code} ||= \&{$app . '::' . $args{method}};
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
219 sub method_lookup {             
220         my $self = shift;
221         my $method = shift;
222         my $proto = shift;
223
224         # this instead of " || 1;" above to allow api_level 0
225         $proto = 1 unless (defined $proto);
226
227         my $class = ref($self) || $self;
228
229         $log->debug("Lookup of [$method] by [$class]", DEBUG);
230         $log->debug("Available methods\n".Dumper(\%_METHODS), INTERNAL);
231
232         my $meth;
233         if (__PACKAGE__->thunk) {
234                 for my $p ( reverse(1 .. $proto) ) {
235                         if (exists $_METHODS[$p]{$method}) {
236                                 $meth = $_METHODS[$p]{$method};
237                         }
238                 }
239         } else {
240                 if (exists $_METHODS[$proto]{$method}) {
241                         $meth = $_METHODS[$proto]{$method};
242                 }
243         }
244
245         if (defined $meth) {
246                 $log->debug("Looks like we found [$method]!", DEBUG);
247                 $log->debug("Method object is ".Dumper($meth), INTERNAL);
248         }
249
250         return $meth;
251
252 }
253
254 sub run {
255         my $self = shift;
256         my $req = shift;
257
258         if ( !ref($req) || !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
259                 $log->debug("Creating a SubRequest object", DEBUG);
260                 unshift @_, $req;
261                 $req = OpenSRF::AppSubrequest->new;
262         } else {
263                 $log->debug("This is a top level request", DEBUG);
264         }
265
266         my $resp = $self->{code}->($self, $req, @_);
267
268         if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
269                 $req->respond($resp) if ($resp);
270                 for my $r ( $req->responses ) {
271                         $log->debug("A SubRequest object is responding with $r", DEBUG);
272                 }
273                 return $req->responses;
274         } else {
275                 $log->debug("A top level Request object is responding $resp", DEBUG);
276         }
277
278         return $resp;
279 }
280
281 sub introspect {
282         my $self = shift;
283         my $client = shift;
284
285         for my $api_level ( 1 .. $#_METHODS ) {
286                 $client->respond( { $api_level => $_METHODS[$api_level] } );
287         }
288
289         return undef;
290 }
291 __PACKAGE__->register_method(
292         stream => 1,
293         method => 'introspect',
294         api_name => 'opensrf.system.method_list'
295 );
296
297 sub make_stream_atomic {
298         my $self = shift;
299         my $req = shift;
300         my @args = @_;
301
302         (my $m_name = $self->api_name) =~ s/\.atomic$//o;
303         my @results = $self->method_lookup($m_name)->run(@args);
304
305         if (@results == 1) {
306                 return $results[0];
307         }
308         return \@results;
309 }
310
311
312 1;