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 0 unless ref($self);
48 return $self->{strict};
53 return 1 unless ref($self);
54 return $self->{api_name};
59 return 1 unless ref($self);
60 return $self->{api_level};
68 $self->{session} = $session;
70 return $self->{session};
76 $server_class = $class;
84 $thunk = $flag if (defined $flag);
88 sub application_implementation {
96 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
105 my ($self, $session, $app_msg) = @_;
111 my $app = $self->application_implementation;
113 if ($session->last_message_type eq 'REQUEST') {
115 my @p = $app_msg->params;
116 my $method_name = $app_msg->method;
117 my $method_proto = $session->last_message_api_level;
118 $log->info("CALL: $method_name [". (@p ? join(', ',@p) : '') ."]");
120 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
123 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
124 statusCode => STATUS_NOTFOUND(),
125 status => "Method [$method_name] not found for $app"));
129 unless ($session->continue_request) {
131 OpenSRF::DomainObject::oilsConnectStatus->new(
132 statusCode => STATUS_REDIRECTED(),
133 status => 'Disconnect on max requests' ) );
139 my @args = $app_msg->params;
140 my $appreq = OpenSRF::AppRequest->new( $session );
142 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
144 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
145 push @pending_requests, [ $appreq, \@args, $coderef ];
152 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
156 if ($coderef->strict) {
157 if (@args < $coderef->argc) {
158 die "Not enough params passed to ".
159 $coderef->api_name." : requires ". $coderef->argc
162 my $sig = $coderef->signature;
163 if ($sig && exists $sig->{params}) {
164 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
165 my $s = $sig->{params}->[$p];
167 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
168 die "Incorrect param class at position $p : should be a '$$s{class}'";
169 } elsif ($s->{type}) {
170 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
171 die "Incorrect param type at position $p : should be an 'object'";
172 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
173 die "Incorrect param type at position $p : should be an 'array'";
174 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
175 die "Incorrect param type at position $p : should be a 'number'";
176 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
177 die "Incorrect param type at position $p : should be a 'string'";
186 $resp = $coderef->run( $appreq, @args);
187 my $time = sprintf '%.3f', time() - $start;
189 $log->debug( "Method duration for [$method_name]: ". $time );
190 if( defined( $resp ) ) {
191 $appreq->respond_complete( $resp );
193 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
194 statusCode => STATUS_COMPLETE(),
195 status => 'Request Complete' ) );
199 warn "Caught error from 'run' method: $e\n";
201 if(UNIVERSAL::isa($e,"Error")) {
202 $e = $e->stringify();
204 my $sess_id = $session->session_id;
206 OpenSRF::DomainObject::oilsMethodException->new(
207 statusCode => STATUS_INTERNALSERVERERROR(),
208 status => " *** Call to [$method_name] failed for session ".
209 "[$sess_id], thread trace ".
210 "[".$appreq->threadTrace."]:\n$e\n"
217 # ----------------------------------------------
220 # XXX may need this later
221 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
225 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
227 # cycle through queued requests
228 while( my $aref = shift @pending_requests ) {
232 # un-if(0) this block to enable param checking based on signature and argc
234 if (@args < $aref->[2]->argc) {
235 die "Not enough params passed to ".
236 $aref->[2]->api_name." : requires ". $aref->[2]->argc
239 my $sig = $aref->[2]->signature;
240 if ($sig && exists $sig->{params}) {
241 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
242 my $s = $sig->{params}->[$p];
244 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
245 die "Incorrect param class at position $p : should be a '$$s{class}'";
246 } elsif ($s->{type}) {
247 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
248 die "Incorrect param type at position $p : should be an 'object'";
249 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
250 die "Incorrect param type at position $p : should be an 'array'";
251 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
252 die "Incorrect param type at position $p : should be a 'number'";
253 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
254 die "Incorrect param type at position $p : should be a 'string'";
263 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
264 my $time = sprintf '%.3f', time - $start;
265 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
267 $appreq = $aref->[0];
268 if( ref( $response ) ) {
269 $appreq->respond_complete( $response );
271 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
272 statusCode => STATUS_COMPLETE(),
273 status => 'Request Complete' ) );
275 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
278 if(UNIVERSAL::isa($e,"Error")) {
279 $e = $e->stringify();
282 OpenSRF::DomainObject::oilsMethodException->new(
283 statusCode => STATUS_INTERNALSERVERERROR(),
284 status => "Call to [".$aref->[2]->api_name."] faild: $e"
294 $log->info("Received non-REQUEST message in Application handler");
296 my $res = OpenSRF::DomainObject::oilsMethodException->new(
297 status => "Received non-REQUEST message in Application handler");
298 $session->send('ERROR', $res);
303 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
306 $session->last_message_type('');
307 $session->last_message_api_level('');
314 my $api_name = shift;
315 my $api_level = shift || 1;
316 return exists($_METHODS[$api_level]{$api_name});
320 sub normalize_whitespace {
327 $txt =~ s/\. /\. /gso;
332 sub parse_string_signature {
334 return [] unless $string;
335 my @chunks = split(/\@/sog, $string);
341 if (/^return (.+)$/so) {
342 $ret = [normalize_whitespace($1)];
343 } elsif (/^param (\w+) \b(.+)$/so) {
344 push @params, [ $1, normalize_whitespace($2) ];
346 $desc .= '@' if $desc;
351 return [normalize_whitespace($desc),\@params, $ret];
354 sub parse_array_signature {
356 my ($d,$p,$r) = @$array;
357 return {} unless ($d or $p or $r);
378 sub register_method {
380 my $app = ref($self) || $self;
384 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
386 $args{api_level} = 1 unless(defined($args{api_level}));
390 $args{package} ||= $app;
391 $args{server_class} = server_class();
392 $args{api_name} ||= $args{server_class} . '.' . $args{method};
394 # un-if(0) this block to enable signature parsing
395 if (!$args{signature}) {
396 if ($args{notes} && !ref($args{notes})) {
398 parse_array_signature( parse_string_signature( $args{notes} ) );
400 } elsif( !ref($args{signature}) ) {
402 parse_array_signature( parse_string_signature( $args{signature} ) );
403 } elsif( ref($args{signature}) eq 'ARRAY') {
405 parse_array_signature( $args{signature} );
408 unless ($args{object_hint}) {
409 ($args{object_hint} = $args{package}) =~ s/::/_/go;
412 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
414 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
416 __PACKAGE__->register_method(
419 api_name => $args{api_name}.'.atomic',
420 method => 'make_stream_atomic',
421 notes => "This is a system generated method. Please see the definition for $args{api_name}",
422 ) if ($args{stream});
425 sub retrieve_remote_apis {
427 my $session = OpenSRF::AppSession->create('router');
429 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
432 $log->debug( "Remote subrequest returned an error:\n". $e );
435 return undef unless ($session->state == $session->CONNECTED);
438 my $req = $session->request( 'opensrf.router.info.class.list' );
439 my $list = $req->recv;
441 if( UNIVERSAL::isa($list,"Error") ) {
445 my $content = $list->content;
449 $session->disconnect;
451 my %u_list = map { ($_ => 1) } @$content;
453 for my $class ( keys %u_list ) {
454 next if($class eq $server_class);
455 populate_remote_method_cache($class, $method);
459 sub populate_remote_method_cache {
463 my $session = OpenSRF::AppSession->create($class);
465 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
467 my $call = 'opensrf.system.method.all' unless (defined $meth);
468 $call = 'opensrf.system.method' if (defined $meth);
470 my $req = $session->request( $call, $meth );
472 while (my $method = $req->recv) {
473 next if (UNIVERSAL::isa($method, 'Error'));
475 $method = $method->content;
476 next if ( exists($_METHODS[$$method{api_level}]) &&
477 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
478 $method->{remote} = 1;
479 bless($method, __PACKAGE__ );
480 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
485 $session->disconnect;
489 $log->debug( "Remote subrequest returned an error:\n". $e );
498 my $no_recurse = shift || 0;
499 my $no_remote = shift || 0;
501 # this instead of " || 1;" above to allow api_level 0
502 $proto = $self->api_level unless (defined $proto);
504 my $class = ref($self) || $self;
506 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
507 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
510 if (__PACKAGE__->thunk) {
511 for my $p ( reverse(1 .. $proto) ) {
512 if (exists $_METHODS[$p]{$method}) {
513 $meth = $_METHODS[$p]{$method};
517 if (exists $_METHODS[$proto]{$method}) {
518 $meth = $_METHODS[$proto]{$method};
523 if($no_remote and $meth->{remote}) {
524 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
528 } elsif (!$no_recurse) {
529 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
530 retrieve_remote_apis($method);
531 $meth = $self->method_lookup($method,$proto,1);
544 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
545 $log->debug("Creating a SubRequest object", DEBUG);
546 unshift @params, $req;
547 $req = OpenSRF::AppSubrequest->new;
548 $req->session( $self->session ) if ($self->session);
551 $log->debug("This is a top level request", DEBUG);
554 if (!$self->{remote}) {
555 my $code = \&{$self->{package} . '::' . $self->{method}};
559 $resp = $code->($self, $req, @params);
564 if( ref($self) eq 'HASH') {
565 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
570 if(UNIVERSAL::isa($err,"Error")) {
578 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
580 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
581 $req->respond($resp) if (defined $resp);
582 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
583 return $req->responses;
585 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
589 my $session = OpenSRF::AppSession->create($self->{server_class});
591 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
592 my $remote_req = $session->request( $self->{api_name}, @params );
593 while (my $remote_resp = $remote_req->recv) {
594 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
595 if( UNIVERSAL::isa($remote_resp,"Error") ) {
598 $req->respond( $remote_resp->content );
600 $remote_req->finish();
604 $log->debug( "Remote subrequest returned an error:\n". $e );
609 $session->disconnect();
613 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
615 return $req->responses;
617 # huh? how'd we get here...
628 if ($self->api_name =~ /all$/o) {
634 my ($seen,$returned) = (0,0);
635 for my $api_level ( reverse(1 .. $#_METHODS) ) {
636 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
637 if (!$offset || $offset <= $seen) {
638 if (!$_METHODS[$api_level]{$api_name}{remote}) {
639 if (defined($method)) {
640 if ($api_name =~ $method) {
641 if (!$limit || $returned < $limit) {
642 $client->respond( $_METHODS[$api_level]{$api_name} );
647 if (!$limit || $returned < $limit) {
648 $client->respond( $_METHODS[$api_level]{$api_name} );
660 __PACKAGE__->register_method(
662 method => 'introspect',
663 api_name => 'opensrf.system.method.all',
666 desc => q/This method is used to introspect an entire OpenSRF Application/,
668 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
673 __PACKAGE__->register_method(
675 method => 'introspect',
677 api_name => 'opensrf.system.method',
680 desc => q/Use this method to get the definition of a single OpenSRF Method/,
682 { desc => q/The method to introspect/,
685 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
695 $client->respond( $_ ) for (@args);
698 __PACKAGE__->register_method(
700 method => 'echo_method',
702 api_name => 'opensrf.system.echo',
704 desc => q/A test method that will echo back it's arguments in a streaming response/,
706 { desc => q/One or more arguments to echo back/ }
708 return => { desc => q/A stream of the arguments passed/ }
713 my( $self, $conn ) = @_;
716 __PACKAGE__->register_method(
717 method => 'time_method',
719 api_name => 'opensrf.system.time',
721 desc => q/Returns the current system time as epoch seconds/,
722 return => { desc => q/epoch seconds/ }
726 sub make_stream_atomic {
731 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
732 my $m = $self->method_lookup($m_name);
734 $m->session( $req->session );
735 my @results = $m->run(@args);