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/;
13 #use OpenSRF::UnixServer; # to get the server class from UnixServer::App
20 $log = 'OpenSRF::Utils::Logger';
23 our @pending_requests;
27 return $self->{api_name};
32 return $self->{api_name};
37 return $self->{api_name};
43 $server_class = $class;
51 $thunk = $flag if (defined $flag);
55 sub application_implementation {
63 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
72 my ($self, $session, $app_msg) = @_;
78 $log->debug( "In Application::handler()", DEBUG );
80 my $app = $self->application_implementation;
83 $log->debug( "Application is $app", DEBUG);
85 $log->debug( "Message is ".$app_msg->toString(1), INTERNAL);
88 if ($session->last_message_type eq 'REQUEST') {
89 $log->debug( "We got a REQUEST: ". $app_msg->method, INFO );
91 my $method_name = $app_msg->method;
92 $log->debug( " * Looking up $method_name inside $app", DEBUG);
94 my $method_proto = $session->last_message_api_level;
95 $log->debug( " * Method API Level [$method_proto]", DEBUG);
97 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
100 $session->status( OpenSRF::DomainObject::oilsMethodException->new() );
104 $log->debug( " (we got coderef $coderef", DEBUG);
106 unless ($session->continue_request) {
108 OpenSRF::DomainObject::oilsConnectStatus->new(
109 statusCode => STATUS_REDIRECTED(),
110 status => 'Disconnect on max requests' ) );
116 my @args = $app_msg->params;
117 my $appreq = OpenSRF::AppRequest->new( $session );
119 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
121 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
122 push @pending_requests, [ $appreq, \@args, $coderef ];
129 $log->debug( "Executing coderef for {$method_name -> ".join(', ', @args)."}", INTERNAL );
134 $resp = $coderef->run( $appreq, @args);
135 my $time = sprintf '%.3f', time() - $start;
136 $log->debug( "Method duration for {$method_name -> ".join(', ', @args)."}: ". $time, DEBUG );
137 if( defined( $resp ) ) {
138 #$log->debug( "Calling respond_complete: ". $resp->toString(), INTERNAL );
139 $appreq->respond_complete( $resp );
141 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
142 statusCode => STATUS_COMPLETE(),
143 status => 'Request Complete' ) );
147 $e = $e->{-text} || $e->message if (ref $e);
148 my $sess_id = $session->session_id;
150 OpenSRF::DomainObject::oilsMethodException->new(
151 statusCode => STATUS_INTERNALSERVERERROR(),
152 status => " *** Call to [$method_name] failed for session ".
153 "[$sess_id], thread trace [".$appreq->threadTrace."]:\n$e"
160 # ----------------------------------------------
163 # XXX may need this later
164 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
168 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
170 # cycle through queued requests
171 while( my $aref = shift @pending_requests ) {
176 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
177 my $time = sprintf '%.3f', time - $start;
178 $log->debug( "Method duration for {[".$aref->[2]->name." -> ".join(', ',@{$aref->[1]}).'}: '.$time, DEBUG );
180 $appreq = $aref->[0];
181 if( ref( $response ) ) {
182 $log->debug( "Calling respond_complete: ". $response->toString(), INTERNAL );
183 $appreq->respond_complete( $response );
185 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
186 statusCode => STATUS_COMPLETE(),
187 status => 'Request Complete' ) );
189 $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
193 OpenSRF::DomainObject::oilsMethodException->new(
194 statusCode => STATUS_INTERNALSERVERERROR(),
195 status => "Call to [".$aref->[2]->name."] faild: ".$e->{-text}
204 my $res = OpenSRF::DomainObject::oilsMethodException->new;
205 $session->send('ERROR', $res);
210 $log->debug( "Pushing ". $app_msg->toString ." onto queue", INTERNAL );
211 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
214 $session->last_message_type('');
215 $session->last_message_api_level('');
222 my $api_name = shift;
223 my $api_level = shift || 1;
224 return exists($_METHODS[$api_level]{$api_name});
227 sub register_method {
229 my $app = ref($self) || $self;
233 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
235 $args{api_level} ||= 1;
238 $args{package} = $app;
239 $args{server_class} = server_class();
240 $args{api_name} ||= $args{server_class} . '.' . $args{method};
242 unless ($args{object_hint}) {
243 ($args{object_hint} = $args{package}) =~ s/::/_/go;
246 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
248 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
250 __PACKAGE__->register_method(
252 api_name => $args{api_name}.'.atomic',
253 method => 'make_stream_atomic'
254 ) if ($args{stream});
257 sub retrieve_remote_apis {
258 my $session = OpenSRF::AppSession->create('router');
260 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
263 $log->debug( "Remote subrequest returned an error:\n". $e );
266 return undef unless ($session->state == $session->CONNECTED);
269 my $req = $session->request( 'opensrf.router.info.class.list' );
270 my $list = $req->recv;
272 if( UNIVERSAL::isa($list,"Error") ) {
276 my $content = $list->content;
280 $session->disconnect;
282 my %u_list = map { ($_ => 1) } @$content;
284 for my $class ( keys %u_list ) {
285 next if($class eq $server_class);
286 populate_remote_method_cache($class);
290 sub populate_remote_method_cache {
293 my $session = OpenSRF::AppSession->create($class);
295 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
297 my $req = $session->request( 'opensrf.system.method.all' );
299 while (my $method = $req->recv) {
300 next if (UNIVERSAL::isa($method, 'Error'));
302 $method = $method->content;
303 next if ( exists($_METHODS[$$method{api_level}]) &&
304 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
305 $method->{remote} = 1;
306 bless($method, __PACKAGE__ );
307 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
312 $session->disconnect;
316 $log->debug( "Remote subrequest returned an error:\n". $e );
325 my $no_recurse = shift || 0;
326 my $no_remote = shift || 0;
328 # this instead of " || 1;" above to allow api_level 0
329 $proto = $self->api_level unless (defined $proto);
331 my $class = ref($self) || $self;
333 $log->debug("Lookup of [$method] by [$class]", DEBUG);
334 $log->debug("Available methods\n".Dumper(\@_METHODS), INTERNAL);
337 if (__PACKAGE__->thunk) {
338 for my $p ( reverse(1 .. $proto) ) {
339 if (exists $_METHODS[$p]{$method}) {
340 $meth = $_METHODS[$p]{$method};
344 if (exists $_METHODS[$proto]{$method}) {
345 $meth = $_METHODS[$proto]{$method};
350 $log->debug("Looks like we found [$method]!", DEBUG);
351 $log->debug("Method object is ".Dumper($meth), INTERNAL);
352 if($no_remote and $meth->{remote}) {
353 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
357 } elsif (!$no_recurse) {
358 retrieve_remote_apis();
359 $meth = $self->method_lookup($method,$proto,1);
372 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
373 $log->debug("Creating a SubRequest object", DEBUG);
374 unshift @params, $req;
375 $req = OpenSRF::AppSubrequest->new;
377 $log->debug("This is a top level request", DEBUG);
380 if (!$self->{remote}) {
381 my $code ||= \&{$self->{package} . '::' . $self->{method}};
382 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
384 $resp = $code->($self, $req, @params);
387 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n".Carp::longmess(), ERROR);
391 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
393 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
394 $log->debug("A SubRequest object is responding", DEBUG);
395 $req->respond($resp) if (defined $resp);
396 $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
397 return $req->responses;
399 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
403 my $session = OpenSRF::AppSession->create($self->{server_class});
405 $session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
406 my $remote_req = $session->request( $self->{api_name}, @params );
407 while (my $remote_resp = $remote_req->recv) {
408 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
409 if( UNIVERSAL::isa($remote_resp,"Error") ) {
412 $req->respond( $remote_resp->content );
414 $remote_req->finish();
419 $log->debug( "Remote subrequest returned an error:\n". $e );
423 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
425 return $req->responses;
427 # huh? how'd we get here...
436 $method = undef if ($self->api_name =~ /all$/o);
438 for my $api_level ( reverse(1 .. $#_METHODS) ) {
439 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
440 if (!$_METHODS[$api_level]{$api_name}{remote}) {
441 if (defined($method)) {
442 if ($api_name eq $method) {
443 $client->respond( $_METHODS[$api_level]{$api_name} );
446 $log->debug( "Returning definition for method [$api_name]", INTERNAL );
447 $client->respond( $_METHODS[$api_level]{$api_name} );
448 $log->debug( "responed with definition for method [$api_name]", INTERNAL );
456 __PACKAGE__->register_method(
458 method => 'introspect',
459 api_name => 'opensrf.system.method.all'
462 __PACKAGE__->register_method(
464 method => 'introspect',
466 api_name => 'opensrf.system.method'
469 sub make_stream_atomic {
474 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
475 my @results = $self->method_lookup($m_name)->run(@args);