1 package OpenSRF::Application;
3 use vars qw/$_app $log @_METHODS $thunk $server_class/;
6 use OpenSRF::AppSession;
7 use OpenSRF::DomainObject::oilsMethod;
8 use OpenSRF::DomainObject::oilsResponse qw/:status/;
9 use OpenSRF::Utils::Logger qw/:level $logger/;
11 use Time::HiRes qw/time/;
12 use OpenSRF::EX qw/:try/;
14 use OpenSRF::Utils::JSON;
15 #use OpenSRF::UnixServer; # to get the server class from UnixServer::App
22 $log = 'OpenSRF::Utils::Logger';
25 our @pending_requests;
29 return 1 unless ref($self);
30 return $self->{package};
35 return 0 unless ref($self);
36 return $self->{signature};
41 return 0 unless ref($self);
47 return 1 unless ref($self);
48 return $self->{api_name};
53 return 1 unless ref($self);
54 return $self->{api_level};
60 $server_class = $class;
68 $thunk = $flag if (defined $flag);
72 sub application_implementation {
80 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
89 my ($self, $session, $app_msg) = @_;
95 my $app = $self->application_implementation;
97 if ($session->last_message_type eq 'REQUEST') {
99 my @p = $app_msg->params;
100 my $method_name = $app_msg->method;
101 my $method_proto = $session->last_message_api_level;
102 $log->info("CALL: $method_name [". (@p ? join(', ',@p) : '') ."]");
104 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
107 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
108 statusCode => STATUS_NOTFOUND(),
109 status => "Method [$method_name] not found for $app"));
113 unless ($session->continue_request) {
115 OpenSRF::DomainObject::oilsConnectStatus->new(
116 statusCode => STATUS_REDIRECTED(),
117 status => 'Disconnect on max requests' ) );
123 my @args = $app_msg->params;
124 my $appreq = OpenSRF::AppRequest->new( $session );
126 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
128 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
129 push @pending_requests, [ $appreq, \@args, $coderef ];
136 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
140 # un-if(0) this block to enable param checking based on signature and argc
142 if (@args < $coderef->argc) {
143 die "Not enough params passed to ".
144 $coderef->api_name." : requires ". $coderef->argc
147 my $sig = $coderef->signature;
148 if ($sig && exists $sig->{params}) {
149 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
150 my $s = $sig->{params}->[$p];
152 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
153 die "Incorrect param class at position $p : should be a '$$s{class}'";
154 } elsif ($s->{type}) {
155 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
156 die "Incorrect param type at position $p : should be an 'object'";
157 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
158 die "Incorrect param type at position $p : should be an 'array'";
159 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
160 die "Incorrect param type at position $p : should be a 'number'";
161 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
162 die "Incorrect param type at position $p : should be a 'string'";
171 $resp = $coderef->run( $appreq, @args);
172 my $time = sprintf '%.3f', time() - $start;
174 $log->debug( "Method duration for [$method_name]: ". $time );
175 if( defined( $resp ) ) {
176 $appreq->respond_complete( $resp );
178 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
179 statusCode => STATUS_COMPLETE(),
180 status => 'Request Complete' ) );
184 warn "Caught error from 'run' method: $e\n";
186 if(UNIVERSAL::isa($e,"Error")) {
187 $e = $e->stringify();
189 my $sess_id = $session->session_id;
191 OpenSRF::DomainObject::oilsMethodException->new(
192 statusCode => STATUS_INTERNALSERVERERROR(),
193 status => " *** Call to [$method_name] failed for session ".
194 "[$sess_id], thread trace ".
195 "[".$appreq->threadTrace."]:\n$e\n"
202 # ----------------------------------------------
205 # XXX may need this later
206 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
210 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
212 # cycle through queued requests
213 while( my $aref = shift @pending_requests ) {
217 # un-if(0) this block to enable param checking based on signature and argc
219 if (@args < $aref->[2]->argc) {
220 die "Not enough params passed to ".
221 $aref->[2]->api_name." : requires ". $aref->[2]->argc
224 my $sig = $aref->[2]->signature;
225 if ($sig && exists $sig->{params}) {
226 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
227 my $s = $sig->{params}->[$p];
229 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
230 die "Incorrect param class at position $p : should be a '$$s{class}'";
231 } elsif ($s->{type}) {
232 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
233 die "Incorrect param type at position $p : should be an 'object'";
234 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
235 die "Incorrect param type at position $p : should be an 'array'";
236 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
237 die "Incorrect param type at position $p : should be a 'number'";
238 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
239 die "Incorrect param type at position $p : should be a 'string'";
248 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
249 my $time = sprintf '%.3f', time - $start;
250 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
252 $appreq = $aref->[0];
253 if( ref( $response ) ) {
254 $appreq->respond_complete( $response );
256 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
257 statusCode => STATUS_COMPLETE(),
258 status => 'Request Complete' ) );
260 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
263 if(UNIVERSAL::isa($e,"Error")) {
264 $e = $e->stringify();
267 OpenSRF::DomainObject::oilsMethodException->new(
268 statusCode => STATUS_INTERNALSERVERERROR(),
269 status => "Call to [".$aref->[2]->api_name."] faild: $e"
279 $log->info("Received non-REQUEST message in Application handler");
281 my $res = OpenSRF::DomainObject::oilsMethodException->new(
282 status => "Received non-REQUEST message in Application handler");
283 $session->send('ERROR', $res);
288 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
291 $session->last_message_type('');
292 $session->last_message_api_level('');
299 my $api_name = shift;
300 my $api_level = shift || 1;
301 return exists($_METHODS[$api_level]{$api_name});
305 sub normalize_whitespace {
312 $txt =~ s/\. /\. /gso;
317 sub parse_string_signature {
319 return [] unless $string;
320 my @chunks = split(/\@/so, $string);
326 if (/^return (.+)$/so) {
327 $ret = [normalize_whitespace($1)];
328 } elsif (/^param (\w+) \b(.+)$/so) {
329 push @params, [ $1, normalize_whitespace($2) ];
331 $desc .= '@' if $desc;
336 return [normalize_whitespace($desc),\@params, $ret];
339 sub parse_array_signature {
341 my ($d,$p,$r) = @$array;
342 return {} unless ($d or $p or $r);
363 sub register_method {
365 my $app = ref($self) || $self;
369 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
371 $args{api_level} = 1 unless(defined($args{api_level}));
375 $args{package} ||= $app;
376 $args{server_class} = server_class();
377 $args{api_name} ||= $args{server_class} . '.' . $args{method};
379 # un-if(0) this block to enable signature parsing
380 if (!$args{signature}) {
381 if ($args{notes} && !ref($args{notes})) {
383 parse_array_signature( parse_string_signature( $args{notes} ) );
385 } elsif( !ref($args{signature}) ) {
387 parse_array_signature( parse_string_signature( $args{signature} ) );
388 } elsif( ref($args{signature}) eq 'ARRAY') {
390 parse_array_signature( $args{signature} );
393 unless ($args{object_hint}) {
394 ($args{object_hint} = $args{package}) =~ s/::/_/go;
397 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
399 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
401 __PACKAGE__->register_method(
404 api_name => $args{api_name}.'.atomic',
405 method => 'make_stream_atomic',
406 notes => "This is a system generated method. Please see the definition for $args{api_name}",
407 ) if ($args{stream});
410 sub retrieve_remote_apis {
412 my $session = OpenSRF::AppSession->create('router');
414 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
417 $log->debug( "Remote subrequest returned an error:\n". $e );
420 return undef unless ($session->state == $session->CONNECTED);
423 my $req = $session->request( 'opensrf.router.info.class.list' );
424 my $list = $req->recv;
426 if( UNIVERSAL::isa($list,"Error") ) {
430 my $content = $list->content;
434 $session->disconnect;
436 my %u_list = map { ($_ => 1) } @$content;
438 for my $class ( keys %u_list ) {
439 next if($class eq $server_class);
440 populate_remote_method_cache($class, $method);
444 sub populate_remote_method_cache {
448 my $session = OpenSRF::AppSession->create($class);
450 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
452 my $call = 'opensrf.system.method.all' unless (defined $meth);
453 $call = 'opensrf.system.method' if (defined $meth);
455 my $req = $session->request( $call, $meth );
457 while (my $method = $req->recv) {
458 next if (UNIVERSAL::isa($method, 'Error'));
460 $method = $method->content;
461 next if ( exists($_METHODS[$$method{api_level}]) &&
462 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
463 $method->{remote} = 1;
464 bless($method, __PACKAGE__ );
465 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
470 $session->disconnect;
474 $log->debug( "Remote subrequest returned an error:\n". $e );
483 my $no_recurse = shift || 0;
484 my $no_remote = shift || 0;
486 # this instead of " || 1;" above to allow api_level 0
487 $proto = $self->api_level unless (defined $proto);
489 my $class = ref($self) || $self;
491 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
492 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
495 if (__PACKAGE__->thunk) {
496 for my $p ( reverse(1 .. $proto) ) {
497 if (exists $_METHODS[$p]{$method}) {
498 $meth = $_METHODS[$p]{$method};
502 if (exists $_METHODS[$proto]{$method}) {
503 $meth = $_METHODS[$proto]{$method};
508 if($no_remote and $meth->{remote}) {
509 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
513 } elsif (!$no_recurse) {
514 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
515 retrieve_remote_apis($method);
516 $meth = $self->method_lookup($method,$proto,1);
529 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
530 $log->debug("Creating a SubRequest object", DEBUG);
531 unshift @params, $req;
532 $req = OpenSRF::AppSubrequest->new;
534 $log->debug("This is a top level request", DEBUG);
537 if (!$self->{remote}) {
538 my $code = \&{$self->{package} . '::' . $self->{method}};
542 $resp = $code->($self, $req, @params);
547 if( ref($self) eq 'HASH') {
548 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
553 if(UNIVERSAL::isa($err,"Error")) {
561 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
563 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
564 $req->respond($resp) if (defined $resp);
565 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
566 return $req->responses;
568 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
572 my $session = OpenSRF::AppSession->create($self->{server_class});
574 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
575 my $remote_req = $session->request( $self->{api_name}, @params );
576 while (my $remote_resp = $remote_req->recv) {
577 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
578 if( UNIVERSAL::isa($remote_resp,"Error") ) {
581 $req->respond( $remote_resp->content );
583 $remote_req->finish();
587 $log->debug( "Remote subrequest returned an error:\n". $e );
592 $session->disconnect();
596 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
598 return $req->responses;
600 # huh? how'd we get here...
611 if ($self->api_name =~ /all$/o) {
617 my ($seen,$returned) = (0,0);
618 for my $api_level ( reverse(1 .. $#_METHODS) ) {
619 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
620 if (!$offset || $offset <= $seen) {
621 if (!$_METHODS[$api_level]{$api_name}{remote}) {
622 if (defined($method)) {
623 if ($api_name =~ $method) {
624 if (!$limit || $returned < $limit) {
625 $client->respond( $_METHODS[$api_level]{$api_name} );
630 if (!$limit || $returned < $limit) {
631 $client->respond( $_METHODS[$api_level]{$api_name} );
643 __PACKAGE__->register_method(
645 method => 'introspect',
646 api_name => 'opensrf.system.method.all',
649 desc => q/This method is used to introspect an entire OpenSRF Application/,
651 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
656 __PACKAGE__->register_method(
658 method => 'introspect',
660 api_name => 'opensrf.system.method',
663 desc => q/Use this method to get the definition of a single OpenSRF Method/,
665 { desc => q/The method to introspect/,
668 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
678 $client->respond( $_ ) for (@args);
681 __PACKAGE__->register_method(
683 method => 'echo_method',
685 api_name => 'opensrf.system.echo',
687 desc => q/A test method that will echo back it's arguments in a streaming response/,
689 { desc => q/One or more arguments to echo back/ }
691 return => { desc => q/A stream of the arguments passed/ }
696 my( $self, $conn ) = @_;
699 __PACKAGE__->register_method(
700 method => 'time_method',
702 api_name => 'opensrf.system.time',
704 desc => q/Returns the current system time as epoch seconds/,
705 return => { desc => q/epoch seconds/ }
709 sub make_stream_atomic {
714 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
715 my @results = $self->method_lookup($m_name)->run(@args);