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 1 unless ref($self);
28 return $self->{package};
33 return 0 unless ref($self);
34 return $self->{signature};
39 return 0 unless ref($self);
45 return 1 unless ref($self);
46 return $self->{api_name};
51 return 1 unless ref($self);
52 return $self->{api_level};
58 $server_class = $class;
66 $thunk = $flag if (defined $flag);
70 sub application_implementation {
78 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
87 my ($self, $session, $app_msg) = @_;
93 $log->debug( "In Application::handler()", DEBUG );
95 my $app = $self->application_implementation;
98 $log->debug( "Application is $app", DEBUG);
101 if ($session->last_message_type eq 'REQUEST') {
102 $log->debug( "We got a REQUEST: ". $app_msg->method);
104 my $method_name = $app_msg->method;
105 $log->debug( " * Looking up $method_name inside $app", DEBUG);
107 my $method_proto = $session->last_message_api_level;
108 $log->debug( " * Method API Level [$method_proto]", DEBUG);
110 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
113 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
114 statusCode => STATUS_NOTFOUND(),
115 status => "Method [$method_name] not found for $app"));
119 $log->debug( " (we got coderef $coderef", DEBUG);
121 unless ($session->continue_request) {
123 OpenSRF::DomainObject::oilsConnectStatus->new(
124 statusCode => STATUS_REDIRECTED(),
125 status => 'Disconnect on max requests' ) );
131 my @args = $app_msg->params;
132 my $appreq = OpenSRF::AppRequest->new( $session );
134 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
136 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
137 push @pending_requests, [ $appreq, \@args, $coderef ];
144 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
148 # un-if(0) this block to enable param checking based on signature and argc
150 if (@args <= $self->argc) {
151 die "Not enough params passed to ".
152 $self->api_name." : requires ". $self->argc
155 if (exists $self->signature->{params}) {
156 for my $p (0 .. scalar(@{ $self->signature->{params} }) - 1 ) {
157 my $s = $self->signature->{params}->[$p];
159 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
160 die "Incorrect param class at position $p : should be a '$$s{class}'";
161 } elsif ($s->{type}) {
162 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
163 die "Incorrect param type at position $p : should be an 'object'";
164 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
165 die "Incorrect param type at position $p : should be an 'array'";
166 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
167 die "Incorrect param type at position $p : should be a 'number'";
168 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
169 die "Incorrect param type at position $p : should be a 'string'";
178 warn "About to run...\n";
179 $resp = $coderef->run( $appreq, @args);
180 warn "Done running...\n";
181 my $time = sprintf '%.3f', time() - $start;
183 $log->debug( "Method duration for {$method_name}: ". $time, INFO );
184 if( defined( $resp ) ) {
185 $appreq->respond_complete( $resp );
187 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
188 statusCode => STATUS_COMPLETE(),
189 status => 'Request Complete' ) );
193 warn "Caught error from 'run' method: $e\n";
195 if(UNIVERSAL::isa($e,"Error")) {
196 $e = $e->stringify();
198 my $sess_id = $session->session_id;
200 OpenSRF::DomainObject::oilsMethodException->new(
201 statusCode => STATUS_INTERNALSERVERERROR(),
202 status => " *** Call to [$method_name] failed for session ".
203 "[$sess_id], thread trace ".
204 "[".$appreq->threadTrace."]:\n$e\n"
211 # ----------------------------------------------
214 # XXX may need this later
215 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
219 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
221 # cycle through queued requests
222 while( my $aref = shift @pending_requests ) {
227 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
228 my $time = sprintf '%.3f', time - $start;
229 $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}: '.$time, DEBUG );
231 $appreq = $aref->[0];
232 if( ref( $response ) ) {
233 $appreq->respond_complete( $response );
235 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
236 statusCode => STATUS_COMPLETE(),
237 status => 'Request Complete' ) );
239 $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
242 if(UNIVERSAL::isa($e,"Error")) {
243 $e = $e->stringify();
246 OpenSRF::DomainObject::oilsMethodException->new(
247 statusCode => STATUS_INTERNALSERVERERROR(),
248 status => "Call to [".$aref->[2]->api_name."] faild: $e"
258 my $res = OpenSRF::DomainObject::oilsMethodException->new(
259 status => "Received non-REQUEST message in Application handler");
260 $session->send('ERROR', $res);
265 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
268 $session->last_message_type('');
269 $session->last_message_api_level('');
276 my $api_name = shift;
277 my $api_level = shift || 1;
278 return exists($_METHODS[$api_level]{$api_name});
281 sub parse_notes_signature {
283 my @lines = split(/\n/so, $string);
289 if (/^\s*\@return (.+)$/) {
291 } elsif (/^\s*\@param (\w+) \b(.+)$/) {
292 push @params, [ $1, $2 ];
298 return [$desc,\@params, $ret];
301 sub parse_array_signature {
303 my ($d,$p,$r) = @$array;
324 sub register_method {
326 my $app = ref($self) || $self;
330 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
332 $args{api_level} = 1 unless(defined($args{api_level}));
336 $args{package} ||= $app;
337 $args{server_class} = server_class();
338 $args{api_name} ||= $args{server_class} . '.' . $args{method};
340 # un-if(0) this block to enable signature parsing
342 if (!$args{signature}) {
343 if ($args{notes} && !ref($args{notes})) {
345 parse_array_signature( parse_notes_signature( $args{notes} ) );
347 } elsif( ref($args{signature}) eq 'ARRAY') {
349 parse_array_signature( $args{signature} );
353 unless ($args{object_hint}) {
354 ($args{object_hint} = $args{package}) =~ s/::/_/go;
357 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
359 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
361 __PACKAGE__->register_method(
363 api_name => $args{api_name}.'.atomic',
364 method => 'make_stream_atomic'
365 ) if ($args{stream});
368 sub retrieve_remote_apis {
370 my $session = OpenSRF::AppSession->create('router');
372 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
375 $log->debug( "Remote subrequest returned an error:\n". $e );
378 return undef unless ($session->state == $session->CONNECTED);
381 my $req = $session->request( 'opensrf.router.info.class.list' );
382 my $list = $req->recv;
384 if( UNIVERSAL::isa($list,"Error") ) {
388 my $content = $list->content;
392 $session->disconnect;
394 my %u_list = map { ($_ => 1) } @$content;
396 for my $class ( keys %u_list ) {
397 next if($class eq $server_class);
398 populate_remote_method_cache($class, $method);
402 sub populate_remote_method_cache {
406 my $session = OpenSRF::AppSession->create($class);
408 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
410 my $call = 'opensrf.system.method.all' unless (defined $meth);
411 $call = 'opensrf.system.method' if (defined $meth);
413 my $req = $session->request( $call, $meth );
415 while (my $method = $req->recv) {
416 next if (UNIVERSAL::isa($method, 'Error'));
418 $method = $method->content;
419 next if ( exists($_METHODS[$$method{api_level}]) &&
420 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
421 $method->{remote} = 1;
422 bless($method, __PACKAGE__ );
423 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
428 $session->disconnect;
432 $log->debug( "Remote subrequest returned an error:\n". $e );
441 my $no_recurse = shift || 0;
442 my $no_remote = shift || 0;
444 # this instead of " || 1;" above to allow api_level 0
445 $proto = $self->api_level unless (defined $proto);
447 my $class = ref($self) || $self;
449 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
450 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
453 if (__PACKAGE__->thunk) {
454 for my $p ( reverse(1 .. $proto) ) {
455 if (exists $_METHODS[$p]{$method}) {
456 $meth = $_METHODS[$p]{$method};
460 if (exists $_METHODS[$proto]{$method}) {
461 $meth = $_METHODS[$proto]{$method};
466 $log->debug("Looks like we found [$method]!", DEBUG);
467 $log->debug("Method object is ".Dumper($meth), INTERNAL);
468 if($no_remote and $meth->{remote}) {
469 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
473 } elsif (!$no_recurse) {
474 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
475 retrieve_remote_apis($method);
476 $meth = $self->method_lookup($method,$proto,1);
489 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
490 $log->debug("Creating a SubRequest object", DEBUG);
491 unshift @params, $req;
492 $req = OpenSRF::AppSubrequest->new;
494 $log->debug("This is a top level request", DEBUG);
497 if (!$self->{remote}) {
498 my $code ||= \&{$self->{package} . '::' . $self->{method}};
499 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
503 $resp = $code->($self, $req, @params);
508 warn "Method 'run' catching error: $e\n";
510 if( ref($self) eq 'HASH') {
511 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
516 if(UNIVERSAL::isa($err,"Error")) {
517 warn "Throwing from method run:\n$err\n------------------\n";
525 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
527 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
528 $log->debug("A SubRequest object is responding", DEBUG);
529 $req->respond($resp) if (defined $resp);
530 $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
531 return $req->responses;
533 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
537 my $session = OpenSRF::AppSession->create($self->{server_class});
539 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
540 my $remote_req = $session->request( $self->{api_name}, @params );
541 while (my $remote_resp = $remote_req->recv) {
542 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
543 if( UNIVERSAL::isa($remote_resp,"Error") ) {
546 $req->respond( $remote_resp->content );
548 $remote_req->finish();
552 $log->debug( "Remote subrequest returned an error:\n". $e );
557 $session->disconnect();
561 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
563 return $req->responses;
565 # huh? how'd we get here...
574 $method = undef if ($self->api_name =~ /all$/o);
576 for my $api_level ( reverse(1 .. $#_METHODS) ) {
577 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
578 if (!$_METHODS[$api_level]{$api_name}{remote}) {
579 if (defined($method)) {
580 if ($api_name =~ $method) {
581 $client->respond( $_METHODS[$api_level]{$api_name} );
584 $log->debug( "Returning definition for method [$api_name]", INTERNAL );
585 $client->respond( $_METHODS[$api_level]{$api_name} );
586 $log->debug( "responed with definition for method [$api_name]", INTERNAL );
594 __PACKAGE__->register_method(
596 method => 'introspect',
597 api_name => 'opensrf.system.method.all'
599 __PACKAGE__->register_method(
601 method => 'introspect',
603 api_name => 'opensrf.system.method'
611 $client->respond( $_ ) for (@args);
614 __PACKAGE__->register_method(
616 method => 'echo_method',
618 api_name => 'opensrf.system.echo'
621 sub make_stream_atomic {
626 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
627 my @results = $self->method_lookup($m_name)->run(@args);