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;
21 $log = 'OpenSRF::Utils::Logger';
24 our @pending_requests;
28 return 1 unless ref($self);
29 return $self->{package};
34 return 0 unless ref($self);
35 return $self->{signature};
40 return 0 unless ref($self);
41 return $self->{strict};
46 return 0 unless ref($self);
52 return 0 unless ref($self);
53 return $self->{max_chunk_size} if (defined($self->{max_chunk_size}));
59 return 0 unless ref($self);
60 return $self->{max_chunk_count} || 0;
65 return 1 unless ref($self);
66 return $self->{api_name};
71 return 1 unless ref($self);
72 return $self->{api_level};
80 $self->{session} = $session;
82 return $self->{session};
88 $server_class = $class;
96 $thunk = $flag if (defined $flag);
100 sub application_implementation {
108 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
117 my ($self, $session, $app_msg) = @_;
123 my $app = $self->application_implementation;
125 if ($session->last_message_type eq 'REQUEST') {
127 my @p = $app_msg->params;
128 my $method_name = $app_msg->method;
129 my $method_proto = $session->last_message_api_level;
130 $log->info("CALL: ".$session->service." $method_name ". (@p ? join(', ',@p) : ''));
132 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
135 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
136 statusCode => STATUS_NOTFOUND(),
137 status => "Method [$method_name] not found for $app"));
141 unless ($session->continue_request) {
143 OpenSRF::DomainObject::oilsConnectStatus->new(
144 statusCode => STATUS_REDIRECTED(),
145 status => 'Disconnect on max requests' ) );
151 my @args = $app_msg->params;
152 my $appreq = OpenSRF::AppRequest->new( $session );
153 $appreq->max_chunk_size( $coderef->max_chunk_size );
154 $appreq->max_chunk_count( $coderef->max_chunk_count );
156 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
158 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
159 push @pending_requests, [ $appreq, \@args, $coderef ];
166 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
170 # un-if(0) this block to enable param checking based on signature and argc
171 if ($coderef->strict) {
172 if (@args < $coderef->argc) {
173 die "Not enough params passed to ".
174 $coderef->api_name." : requires ". $coderef->argc
177 my $sig = $coderef->signature;
178 if ($sig && exists $sig->{params}) {
179 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
180 my $s = $sig->{params}->[$p];
182 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
183 die "Incorrect param class at position $p : should be a '$$s{class}'";
184 } elsif ($s->{type}) {
185 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
186 die "Incorrect param type at position $p : should be an 'object'";
187 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
188 die "Incorrect param type at position $p : should be an 'array'";
189 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
190 die "Incorrect param type at position $p : should be a 'number'";
191 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
192 die "Incorrect param type at position $p : should be a 'string'";
201 $resp = $coderef->run( $appreq, @args);
202 my $time = sprintf '%.3f', time() - $start;
204 $log->debug( "Method duration for [$method_name]: ". $time );
205 $appreq->respond_complete( $resp );
209 warn "Caught error from 'run' method: $e\n";
211 if(UNIVERSAL::isa($e,"Error")) {
212 $e = $e->stringify();
214 my $sess_id = $session->session_id;
216 OpenSRF::DomainObject::oilsMethodException->new(
217 statusCode => STATUS_INTERNALSERVERERROR(),
218 status => " *** Call to [$method_name] failed for session ".
219 "[$sess_id], thread trace ".
220 "[".$appreq->threadTrace."]:\n$e\n"
227 # ----------------------------------------------
230 # XXX may need this later
231 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
235 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
237 # cycle through queued requests
238 while( my $aref = shift @pending_requests ) {
242 # un-if(0) this block to enable param checking based on signature and argc
244 if (@args < $aref->[2]->argc) {
245 die "Not enough params passed to ".
246 $aref->[2]->api_name." : requires ". $aref->[2]->argc
249 my $sig = $aref->[2]->signature;
250 if ($sig && exists $sig->{params}) {
251 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
252 my $s = $sig->{params}->[$p];
254 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
255 die "Incorrect param class at position $p : should be a '$$s{class}'";
256 } elsif ($s->{type}) {
257 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
258 die "Incorrect param type at position $p : should be an 'object'";
259 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
260 die "Incorrect param type at position $p : should be an 'array'";
261 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
262 die "Incorrect param type at position $p : should be a 'number'";
263 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
264 die "Incorrect param type at position $p : should be a 'string'";
273 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
274 my $time = sprintf '%.3f', time - $start;
275 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
277 $appreq = $aref->[0];
278 $appreq->respond_complete( $response );
279 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
283 if(UNIVERSAL::isa($e,"Error")) {
284 $e = $e->stringify();
287 OpenSRF::DomainObject::oilsMethodException->new(
288 statusCode => STATUS_INTERNALSERVERERROR(),
289 status => "Call to [".$aref->[2]->api_name."] faild: $e"
299 $log->info("Received non-REQUEST message in Application handler");
301 my $res = OpenSRF::DomainObject::oilsMethodException->new(
302 status => "Received non-REQUEST message in Application handler");
303 $session->send('ERROR', $res);
308 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
311 $session->last_message_type('');
312 $session->last_message_api_level('');
319 my $api_name = shift;
320 my $api_level = shift || 1;
321 return exists($_METHODS[$api_level]{$api_name});
325 sub normalize_whitespace {
332 $txt =~ s/\. /\. /gso;
337 sub parse_string_signature {
339 return [] unless $string;
340 my @chunks = split(/\@/smo, $string);
346 if (/^return (.+)$/so) {
347 $ret = [normalize_whitespace($1)];
348 } elsif (/^param (\w+) \b(.+)$/so) {
349 push @params, [ $1, normalize_whitespace($2) ];
351 $desc .= '@' if $desc;
356 return [normalize_whitespace($desc),\@params, $ret];
359 sub parse_array_signature {
361 my ($d,$p,$r) = @$array;
362 return {} unless ($d or $p or $r);
383 sub register_method {
385 my $app = ref($self) || $self;
389 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
391 $args{api_level} = 1 unless(defined($args{api_level}));
395 $args{package} ||= $app;
396 $args{server_class} = server_class();
397 $args{api_name} ||= $args{server_class} . '.' . $args{method};
399 # un-if(0) this block to enable signature parsing
400 if (!$args{signature}) {
401 if ($args{notes} && !ref($args{notes})) {
403 parse_array_signature( parse_string_signature( $args{notes} ) );
405 } elsif( !ref($args{signature}) ) {
407 parse_array_signature( parse_string_signature( $args{signature} ) );
408 } elsif( ref($args{signature}) eq 'ARRAY') {
410 parse_array_signature( $args{signature} );
413 unless ($args{object_hint}) {
414 ($args{object_hint} = $args{package}) =~ s/::/_/go;
417 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
419 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
421 __PACKAGE__->register_method(
424 api_name => $args{api_name}.'.atomic',
425 method => 'make_stream_atomic',
426 notes => "This is a system generated method. Please see the definition for $args{api_name}",
427 ) if ($args{stream});
430 sub retrieve_remote_apis {
432 my $session = OpenSRF::AppSession->create('router');
434 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
437 $log->debug( "Remote subrequest returned an error:\n". $e );
440 return undef unless ($session->state == $session->CONNECTED);
443 my $req = $session->request( 'opensrf.router.info.class.list' );
444 my $list = $req->recv;
446 if( UNIVERSAL::isa($list,"Error") ) {
450 my $content = $list->content;
454 $session->disconnect;
456 my %u_list = map { ($_ => 1) } @$content;
458 for my $class ( keys %u_list ) {
459 next if($class eq $server_class);
460 populate_remote_method_cache($class, $method);
464 sub populate_remote_method_cache {
468 my $session = OpenSRF::AppSession->create($class);
470 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
472 my $call = 'opensrf.system.method.all' unless (defined $meth);
473 $call = 'opensrf.system.method' if (defined $meth);
475 my $req = $session->request( $call, $meth );
477 while (my $method = $req->recv) {
478 next if (UNIVERSAL::isa($method, 'Error'));
480 $method = $method->content;
481 next if ( exists($_METHODS[$$method{api_level}]) &&
482 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
483 $method->{remote} = 1;
484 bless($method, __PACKAGE__ );
485 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
490 $session->disconnect;
494 $log->debug( "Remote subrequest returned an error:\n". $e );
503 my $no_recurse = shift || 0;
504 my $no_remote = shift || 0;
506 # this instead of " || 1;" above to allow api_level 0
507 $proto = $self->api_level unless (defined $proto);
509 my $class = ref($self) || $self;
511 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
512 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
515 if (__PACKAGE__->thunk) {
516 for my $p ( reverse(1 .. $proto) ) {
517 if (exists $_METHODS[$p]{$method}) {
518 $meth = $_METHODS[$p]{$method};
522 if (exists $_METHODS[$proto]{$method}) {
523 $meth = $_METHODS[$proto]{$method};
528 if($no_remote and $meth->{remote}) {
529 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
533 } elsif (!$no_recurse) {
534 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
535 retrieve_remote_apis($method);
536 $meth = $self->method_lookup($method,$proto,1);
549 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
550 $log->debug("Creating a SubRequest object", DEBUG);
551 unshift @params, $req;
552 $req = OpenSRF::AppSubrequest->new;
553 $req->session( $self->session ) if ($self->session);
556 $log->debug("This is a top level request", DEBUG);
559 if (!$self->{remote}) {
560 my $code = \&{$self->{package} . '::' . $self->{method}};
564 $resp = $code->($self, $req, @params);
569 if( ref($self) eq 'HASH') {
570 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
575 if(UNIVERSAL::isa($err,"Error")) {
583 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
585 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
586 $req->respond($resp) if (defined $resp);
587 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
588 return $req->responses;
590 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
594 my $session = OpenSRF::AppSession->create($self->{server_class});
596 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
597 my $remote_req = $session->request( $self->{api_name}, @params );
598 while (my $remote_resp = $remote_req->recv) {
599 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
600 if( UNIVERSAL::isa($remote_resp,"Error") ) {
603 $req->respond( $remote_resp->content );
605 $remote_req->finish();
609 $log->debug( "Remote subrequest returned an error:\n". $e );
614 $session->disconnect();
618 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
620 return $req->responses;
622 # huh? how'd we get here...
633 if ($self->api_name =~ /all$/o) {
639 my ($seen,$returned) = (0,0);
640 for my $api_level ( reverse(1 .. $#_METHODS) ) {
641 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
642 if (!$offset || $offset <= $seen) {
643 if (!$_METHODS[$api_level]{$api_name}{remote}) {
644 if (defined($method)) {
645 if ($api_name =~ $method) {
646 if (!$limit || $returned < $limit) {
647 $client->respond( $_METHODS[$api_level]{$api_name} );
652 if (!$limit || $returned < $limit) {
653 $client->respond( $_METHODS[$api_level]{$api_name} );
665 __PACKAGE__->register_method(
667 method => 'introspect',
668 api_name => 'opensrf.system.method.all',
671 desc => q/This method is used to introspect an entire OpenSRF Application/,
673 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
678 __PACKAGE__->register_method(
680 method => 'introspect',
682 api_name => 'opensrf.system.method',
685 desc => q/Use this method to get the definition of a single OpenSRF Method/,
687 { desc => q/The method to introspect/,
690 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
700 $client->respond( $_ ) for (@args);
703 __PACKAGE__->register_method(
705 method => 'echo_method',
707 api_name => 'opensrf.system.echo',
709 desc => q/A test method that will echo back it's arguments in a streaming response/,
711 { desc => q/One or more arguments to echo back/ }
713 return => { desc => q/A stream of the arguments passed/ }
718 my( $self, $conn ) = @_;
721 __PACKAGE__->register_method(
722 method => 'time_method',
724 api_name => 'opensrf.system.time',
726 desc => q/Returns the current system time as epoch seconds/,
727 return => { desc => q/epoch seconds/ }
731 sub make_stream_atomic {
736 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
737 my $m = $self->method_lookup($m_name);
739 $m->session( $req->session );
740 my @results = $m->run(@args);