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);
42 return $self->{strict};
47 return 0 unless ref($self);
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 # un-if(0) this block to enable param checking based on signature and argc
157 if ($coderef->strict) {
158 if (@args < $coderef->argc) {
159 die "Not enough params passed to ".
160 $coderef->api_name." : requires ". $coderef->argc
163 my $sig = $coderef->signature;
164 if ($sig && exists $sig->{params}) {
165 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
166 my $s = $sig->{params}->[$p];
168 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
169 die "Incorrect param class at position $p : should be a '$$s{class}'";
170 } elsif ($s->{type}) {
171 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
172 die "Incorrect param type at position $p : should be an 'object'";
173 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
174 die "Incorrect param type at position $p : should be an 'array'";
175 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
176 die "Incorrect param type at position $p : should be a 'number'";
177 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
178 die "Incorrect param type at position $p : should be a 'string'";
187 $resp = $coderef->run( $appreq, @args);
188 my $time = sprintf '%.3f', time() - $start;
190 $log->debug( "Method duration for [$method_name]: ". $time );
191 if( defined( $resp ) ) {
192 $appreq->respond_complete( $resp );
194 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
195 statusCode => STATUS_COMPLETE(),
196 status => 'Request Complete' ) );
200 warn "Caught error from 'run' method: $e\n";
202 if(UNIVERSAL::isa($e,"Error")) {
203 $e = $e->stringify();
205 my $sess_id = $session->session_id;
207 OpenSRF::DomainObject::oilsMethodException->new(
208 statusCode => STATUS_INTERNALSERVERERROR(),
209 status => " *** Call to [$method_name] failed for session ".
210 "[$sess_id], thread trace ".
211 "[".$appreq->threadTrace."]:\n$e\n"
218 # ----------------------------------------------
221 # XXX may need this later
222 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
226 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
228 # cycle through queued requests
229 while( my $aref = shift @pending_requests ) {
233 # un-if(0) this block to enable param checking based on signature and argc
235 if (@args < $aref->[2]->argc) {
236 die "Not enough params passed to ".
237 $aref->[2]->api_name." : requires ". $aref->[2]->argc
240 my $sig = $aref->[2]->signature;
241 if ($sig && exists $sig->{params}) {
242 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
243 my $s = $sig->{params}->[$p];
245 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
246 die "Incorrect param class at position $p : should be a '$$s{class}'";
247 } elsif ($s->{type}) {
248 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
249 die "Incorrect param type at position $p : should be an 'object'";
250 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
251 die "Incorrect param type at position $p : should be an 'array'";
252 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
253 die "Incorrect param type at position $p : should be a 'number'";
254 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
255 die "Incorrect param type at position $p : should be a 'string'";
264 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
265 my $time = sprintf '%.3f', time - $start;
266 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
268 $appreq = $aref->[0];
269 if( ref( $response ) ) {
270 $appreq->respond_complete( $response );
272 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
273 statusCode => STATUS_COMPLETE(),
274 status => 'Request Complete' ) );
276 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
279 if(UNIVERSAL::isa($e,"Error")) {
280 $e = $e->stringify();
283 OpenSRF::DomainObject::oilsMethodException->new(
284 statusCode => STATUS_INTERNALSERVERERROR(),
285 status => "Call to [".$aref->[2]->api_name."] faild: $e"
295 $log->info("Received non-REQUEST message in Application handler");
297 my $res = OpenSRF::DomainObject::oilsMethodException->new(
298 status => "Received non-REQUEST message in Application handler");
299 $session->send('ERROR', $res);
304 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
307 $session->last_message_type('');
308 $session->last_message_api_level('');
315 my $api_name = shift;
316 my $api_level = shift || 1;
317 return exists($_METHODS[$api_level]{$api_name});
321 sub normalize_whitespace {
328 $txt =~ s/\. /\. /gso;
333 sub parse_string_signature {
335 return [] unless $string;
336 my @chunks = split(/\@/smo, $string);
342 if (/^return (.+)$/so) {
343 $ret = [normalize_whitespace($1)];
344 } elsif (/^param (\w+) \b(.+)$/so) {
345 push @params, [ $1, normalize_whitespace($2) ];
347 $desc .= '@' if $desc;
352 return [normalize_whitespace($desc),\@params, $ret];
355 sub parse_array_signature {
357 my ($d,$p,$r) = @$array;
358 return {} unless ($d or $p or $r);
379 sub register_method {
381 my $app = ref($self) || $self;
385 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
387 $args{api_level} = 1 unless(defined($args{api_level}));
391 $args{package} ||= $app;
392 $args{server_class} = server_class();
393 $args{api_name} ||= $args{server_class} . '.' . $args{method};
395 # un-if(0) this block to enable signature parsing
396 if (!$args{signature}) {
397 if ($args{notes} && !ref($args{notes})) {
399 parse_array_signature( parse_string_signature( $args{notes} ) );
401 } elsif( !ref($args{signature}) ) {
403 parse_array_signature( parse_string_signature( $args{signature} ) );
404 } elsif( ref($args{signature}) eq 'ARRAY') {
406 parse_array_signature( $args{signature} );
409 unless ($args{object_hint}) {
410 ($args{object_hint} = $args{package}) =~ s/::/_/go;
413 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
415 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
417 __PACKAGE__->register_method(
420 api_name => $args{api_name}.'.atomic',
421 method => 'make_stream_atomic',
422 notes => "This is a system generated method. Please see the definition for $args{api_name}",
423 ) if ($args{stream});
426 sub retrieve_remote_apis {
428 my $session = OpenSRF::AppSession->create('router');
430 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
433 $log->debug( "Remote subrequest returned an error:\n". $e );
436 return undef unless ($session->state == $session->CONNECTED);
439 my $req = $session->request( 'opensrf.router.info.class.list' );
440 my $list = $req->recv;
442 if( UNIVERSAL::isa($list,"Error") ) {
446 my $content = $list->content;
450 $session->disconnect;
452 my %u_list = map { ($_ => 1) } @$content;
454 for my $class ( keys %u_list ) {
455 next if($class eq $server_class);
456 populate_remote_method_cache($class, $method);
460 sub populate_remote_method_cache {
464 my $session = OpenSRF::AppSession->create($class);
466 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
468 my $call = 'opensrf.system.method.all' unless (defined $meth);
469 $call = 'opensrf.system.method' if (defined $meth);
471 my $req = $session->request( $call, $meth );
473 while (my $method = $req->recv) {
474 next if (UNIVERSAL::isa($method, 'Error'));
476 $method = $method->content;
477 next if ( exists($_METHODS[$$method{api_level}]) &&
478 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
479 $method->{remote} = 1;
480 bless($method, __PACKAGE__ );
481 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
486 $session->disconnect;
490 $log->debug( "Remote subrequest returned an error:\n". $e );
499 my $no_recurse = shift || 0;
500 my $no_remote = shift || 0;
502 # this instead of " || 1;" above to allow api_level 0
503 $proto = $self->api_level unless (defined $proto);
505 my $class = ref($self) || $self;
507 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
508 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
511 if (__PACKAGE__->thunk) {
512 for my $p ( reverse(1 .. $proto) ) {
513 if (exists $_METHODS[$p]{$method}) {
514 $meth = $_METHODS[$p]{$method};
518 if (exists $_METHODS[$proto]{$method}) {
519 $meth = $_METHODS[$proto]{$method};
524 if($no_remote and $meth->{remote}) {
525 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
529 } elsif (!$no_recurse) {
530 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
531 retrieve_remote_apis($method);
532 $meth = $self->method_lookup($method,$proto,1);
545 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
546 $log->debug("Creating a SubRequest object", DEBUG);
547 unshift @params, $req;
548 $req = OpenSRF::AppSubrequest->new;
549 $req->session( $self->session ) if ($self->session);
552 $log->debug("This is a top level request", DEBUG);
555 if (!$self->{remote}) {
556 my $code = \&{$self->{package} . '::' . $self->{method}};
560 $resp = $code->($self, $req, @params);
565 if( ref($self) eq 'HASH') {
566 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
571 if(UNIVERSAL::isa($err,"Error")) {
579 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
581 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
582 $req->respond($resp) if (defined $resp);
583 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
584 return $req->responses;
586 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
590 my $session = OpenSRF::AppSession->create($self->{server_class});
592 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
593 my $remote_req = $session->request( $self->{api_name}, @params );
594 while (my $remote_resp = $remote_req->recv) {
595 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
596 if( UNIVERSAL::isa($remote_resp,"Error") ) {
599 $req->respond( $remote_resp->content );
601 $remote_req->finish();
605 $log->debug( "Remote subrequest returned an error:\n". $e );
610 $session->disconnect();
614 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
616 return $req->responses;
618 # huh? how'd we get here...
629 if ($self->api_name =~ /all$/o) {
635 my ($seen,$returned) = (0,0);
636 for my $api_level ( reverse(1 .. $#_METHODS) ) {
637 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
638 if (!$offset || $offset <= $seen) {
639 if (!$_METHODS[$api_level]{$api_name}{remote}) {
640 if (defined($method)) {
641 if ($api_name =~ $method) {
642 if (!$limit || $returned < $limit) {
643 $client->respond( $_METHODS[$api_level]{$api_name} );
648 if (!$limit || $returned < $limit) {
649 $client->respond( $_METHODS[$api_level]{$api_name} );
661 __PACKAGE__->register_method(
663 method => 'introspect',
664 api_name => 'opensrf.system.method.all',
667 desc => q/This method is used to introspect an entire OpenSRF Application/,
669 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
674 __PACKAGE__->register_method(
676 method => 'introspect',
678 api_name => 'opensrf.system.method',
681 desc => q/Use this method to get the definition of a single OpenSRF Method/,
683 { desc => q/The method to introspect/,
686 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
696 $client->respond( $_ ) for (@args);
699 __PACKAGE__->register_method(
701 method => 'echo_method',
703 api_name => 'opensrf.system.echo',
705 desc => q/A test method that will echo back it's arguments in a streaming response/,
707 { desc => q/One or more arguments to echo back/ }
709 return => { desc => q/A stream of the arguments passed/ }
714 my( $self, $conn ) = @_;
717 __PACKAGE__->register_method(
718 method => 'time_method',
720 api_name => 'opensrf.system.time',
722 desc => q/Returns the current system time as epoch seconds/,
723 return => { desc => q/epoch seconds/ }
727 sub make_stream_atomic {
732 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
733 my $m = $self->method_lookup($m_name);
735 $m->session( $req->session );
736 my @results = $m->run(@args);