1 package OpenSRF::Application;
2 use vars qw/$_app $log @_METHODS $thunk $server_class/;
5 use OpenSRF::AppSession;
6 use OpenSRF::DomainObject::oilsMethod;
7 use OpenSRF::DomainObject::oilsResponse qw/:status/;
8 use OpenSRF::Utils::Logger qw/:level/;
10 use Time::HiRes qw/time/;
11 use OpenSRF::EX qw/:try/;
12 #use OpenSRF::UnixServer; # to get the server class from UnixServer::App
19 $log = 'OpenSRF::Utils::Logger';
22 our @pending_requests;
26 return $self->{api_name};
32 $server_class = $class;
40 $thunk = $flag if (defined $flag);
44 sub application_implementation {
52 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
61 my ($self, $session, $app_msg) = @_;
67 $log->debug( "In Application::handler()", DEBUG );
69 my $app = $self->application_implementation;
72 $log->debug( "Application is $app", DEBUG);
74 $log->debug( "Message is ".$app_msg->toString(1), INTERNAL);
77 if ($session->last_message_type eq 'REQUEST') {
78 $log->debug( "We got a REQUEST: ". $app_msg->method, INFO );
80 my $method_name = $app_msg->method;
81 $log->debug( " * Looking up $method_name inside $app", DEBUG);
83 my $method_proto = $session->last_message_api_level;
84 $log->debug( " * Method API Level [$method_proto]", DEBUG);
86 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
89 $session->status( OpenSRF::DomainObject::oilsMethodException->new() );
93 $log->debug( " (we got coderef $coderef", DEBUG);
95 unless ($session->continue_request) {
97 OpenSRF::DomainObject::oilsConnectStatus->new(
98 statusCode => STATUS_REDIRECTED(),
99 status => 'Disconnect on max requests' ) );
105 my @args = $app_msg->params;
106 my $appreq = OpenSRF::AppRequest->new( $session );
108 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
110 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
111 push @pending_requests, [ $appreq, \@args, $coderef ];
118 $log->debug( "Executing coderef for {$method_name -> ".join(', ', @args)."}", INTERNAL );
123 $resp = $coderef->run( $appreq, @args);
124 my $time = sprintf '%.3f', time() - $start;
125 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}: ". $time, DEBUG );
126 if( defined( $resp ) ) {
127 #$log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
128 $appreq->respond_complete( $resp );
130 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
131 statusCode => STATUS_COMPLETE(),
132 status => 'Request Complete' ) );
136 $e = $e->{-text} || $e->message if (ref $e);
137 my $sess_id = $session->session_id;
139 OpenSRF::DomainObject::oilsMethodException->new(
140 statusCode => STATUS_INTERNALSERVERERROR(),
141 status => " *** Call to [$method_name] failed for session ".
142 "[$sess_id], thread trace [".$appreq->threadTrace."]:\n".$e
149 # ----------------------------------------------
152 # XXX may need this later
153 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
157 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
159 # cycle through queued requests
160 while( my $aref = shift @pending_requests ) {
165 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
166 my $time = sprintf '%.3f', time - $start;
167 $log->debug( "Method duration for {[".$aref->[2]->name." -> ".join(', ',@{$aref->[1]}).'}: '.$time, DEBUG );
169 $appreq = $aref->[0];
170 if( ref( $response ) ) {
171 $log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
172 $appreq->respond_complete( $response );
174 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
175 statusCode => STATUS_COMPLETE(),
176 status => 'Request Complete' ) );
178 $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
182 OpenSRF::DomainObject::oilsMethodException->new(
183 statusCode => STATUS_INTERNALSERVERERROR(),
184 status => "Call to [".$aref->[2]->name."] faild: ".$e->{-text}
193 my $res = OpenSRF::DomainObject::oilsMethodException->new;
194 $session->send('ERROR', $res);
199 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
200 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
203 $session->last_message_type('');
204 $session->last_message_api_level('');
209 sub register_method {
211 my $app = ref($self) || $self;
215 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
217 $args{api_level} ||= 1;
220 $args{package} = $app;
221 $args{object_hint} ||= '';
222 $args{server_class} = server_class();
223 $args{api_name} ||= $args{server_class} . '.' . $args{method};
225 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
227 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
229 __PACKAGE__->register_method(
231 api_name => $args{api_name}.'.atomic',
232 method => 'make_stream_atomic'
233 ) if ($args{stream});
236 sub retrieve_remote_apis {
237 my $session = OpenSRF::AppSession->create('router');
239 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
242 $log->debug( "Remote subrequest returned an error:\n". $e );
245 return undef unless ($session->state == $session->CONNECTED);
248 my $req = $session->request( 'opensrf.router.info.class.list' );
249 my $list = $req->recv;
251 if( UNIVERSAL::isa($list,"Error") ) {
255 my $content = $list->content;
259 $session->disconnect;
261 my %u_list = map { ($_ => 1) } @$content;
263 for my $class ( keys %u_list ) {
264 next if($class eq $server_class);
265 populate_remote_method_cache($class);
269 sub populate_remote_method_cache {
272 my $session = OpenSRF::AppSession->create($class);
274 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
276 my $req = $session->request( 'opensrf.system.method.all' );
278 while (my $method = $req->recv) {
279 next if (UNIVERSAL::isa($method, 'Error'));
281 $method = $method->content;
282 next if ( exists($_METHODS[$$method{api_level}]) &&
283 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
284 $method->{remote} = 1;
285 bless($method, __PACKAGE__ );
286 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
291 $session->disconnect;
295 $log->debug( "Remote subrequest returned an error:\n". $e );
304 my $no_recurse = shift || 0;
305 my $no_remote = shift || 0;
307 # this instead of " || 1;" above to allow api_level 0
308 $proto = 1 unless (defined $proto);
310 my $class = ref($self) || $self;
312 $log->debug("Lookup of [$method] by [$class]", DEBUG);
313 $log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
316 if (__PACKAGE__->thunk) {
317 for my $p ( reverse(1 .. $proto) ) {
318 if (exists $_METHODS[$p]{$method}) {
319 $meth = $_METHODS[$p]{$method};
323 if (exists $_METHODS[$proto]{$method}) {
324 $meth = $_METHODS[$proto]{$method};
329 $log->debug("Looks like we found [$method]!", DEBUG);
330 $log->debug("Method object is ".Dumper($meth), INTERNAL);
331 if($no_remote and $meth->{remote}) {
332 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
336 } elsif (!$no_recurse) {
337 retrieve_remote_apis();
338 $meth = $self->method_lookup($method,$proto,1);
351 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
352 $log->debug("Creating a SubRequest object", DEBUG);
353 unshift @params, $req;
354 $req = OpenSRF::AppSubrequest->new;
356 $log->debug("This is a top level request", DEBUG);
359 if (!$self->{remote}) {
360 my $code ||= \&{$self->{package} . '::' . $self->{method}};
361 $resp = $code->($self, $req, @params);
363 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
364 $req->respond($resp) if (defined $resp);
365 $log->debug("A SubRequest object is responding " . join(" ",$req->responses), DEBUG);
366 return $req->responses;
368 $log->debug("A top level Request object is responding $resp", DEBUG);
372 my $session = OpenSRF::AppSession->create($self->{server_class});
374 $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
375 my $remote_req = $session->request( $self->{api_name}, @params );
376 while (my $remote_resp = $remote_req->recv) {
377 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
378 if( UNIVERSAL::isa($remote_resp,"Error") ) {
381 $req->respond( $remote_resp->content );
383 $remote_req->finish();
388 $log->debug( "Remote subrequest returned an error:\n". $e );
392 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
394 return $req->responses;
396 # huh? how'd we get here...
405 $method = undef if ($self->{api_name} =~ /all$/o);
407 for my $api_level ( reverse(1 .. $#_METHODS) ) {
408 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
409 if (!$_METHODS[$api_level]{$api_name}{remote}) {
410 if (defined($method)) {
411 if ($api_name eq $method) {
412 $client->respond( $_METHODS[$api_level]{$api_name} );
415 $client->respond( $_METHODS[$api_level]{$api_name} );
423 __PACKAGE__->register_method(
425 method => 'introspect',
426 api_name => 'opensrf.system.method.all'
429 __PACKAGE__->register_method(
431 method => 'introspect',
433 api_name => 'opensrf.system.method'
436 sub make_stream_atomic {
441 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
442 my @results = $self->method_lookup($m_name)->run(@args);