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 0 unless ref($self);
54 return $self->{max_chunk_size} if (defined($self->{max_chunk_size}));
60 return 0 unless ref($self);
61 return $self->{max_chunk_count} || 0;
66 return 1 unless ref($self);
67 return $self->{api_name};
72 return 1 unless ref($self);
73 return $self->{api_level};
81 $self->{session} = $session;
83 return $self->{session};
89 $server_class = $class;
97 $thunk = $flag if (defined $flag);
101 sub application_implementation {
109 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
118 my ($self, $session, $app_msg) = @_;
124 my $app = $self->application_implementation;
126 if ($session->last_message_type eq 'REQUEST') {
128 my @p = $app_msg->params;
129 my $method_name = $app_msg->method;
130 my $method_proto = $session->last_message_api_level;
131 $log->info("CALL: $method_name [". (@p ? join(', ',@p) : '') ."]");
133 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
136 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
137 statusCode => STATUS_NOTFOUND(),
138 status => "Method [$method_name] not found for $app"));
142 unless ($session->continue_request) {
144 OpenSRF::DomainObject::oilsConnectStatus->new(
145 statusCode => STATUS_REDIRECTED(),
146 status => 'Disconnect on max requests' ) );
152 my @args = $app_msg->params;
153 my $appreq = OpenSRF::AppRequest->new( $session );
154 $appreq->max_chunk_size( $coderef->max_chunk_size );
155 $appreq->max_chunk_count( $coderef->max_chunk_count );
157 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
159 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
160 push @pending_requests, [ $appreq, \@args, $coderef ];
167 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
171 # un-if(0) this block to enable param checking based on signature and argc
172 if ($coderef->strict) {
173 if (@args < $coderef->argc) {
174 die "Not enough params passed to ".
175 $coderef->api_name." : requires ". $coderef->argc
178 my $sig = $coderef->signature;
179 if ($sig && exists $sig->{params}) {
180 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
181 my $s = $sig->{params}->[$p];
183 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
184 die "Incorrect param class at position $p : should be a '$$s{class}'";
185 } elsif ($s->{type}) {
186 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
187 die "Incorrect param type at position $p : should be an 'object'";
188 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
189 die "Incorrect param type at position $p : should be an 'array'";
190 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
191 die "Incorrect param type at position $p : should be a 'number'";
192 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
193 die "Incorrect param type at position $p : should be a 'string'";
202 $resp = $coderef->run( $appreq, @args);
203 my $time = sprintf '%.3f', time() - $start;
205 $log->debug( "Method duration for [$method_name]: ". $time );
206 $appreq->respond_complete( $resp );
210 warn "Caught error from 'run' method: $e\n";
212 if(UNIVERSAL::isa($e,"Error")) {
213 $e = $e->stringify();
215 my $sess_id = $session->session_id;
217 OpenSRF::DomainObject::oilsMethodException->new(
218 statusCode => STATUS_INTERNALSERVERERROR(),
219 status => " *** Call to [$method_name] failed for session ".
220 "[$sess_id], thread trace ".
221 "[".$appreq->threadTrace."]:\n$e\n"
228 # ----------------------------------------------
231 # XXX may need this later
232 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
236 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
238 # cycle through queued requests
239 while( my $aref = shift @pending_requests ) {
243 # un-if(0) this block to enable param checking based on signature and argc
245 if (@args < $aref->[2]->argc) {
246 die "Not enough params passed to ".
247 $aref->[2]->api_name." : requires ". $aref->[2]->argc
250 my $sig = $aref->[2]->signature;
251 if ($sig && exists $sig->{params}) {
252 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
253 my $s = $sig->{params}->[$p];
255 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
256 die "Incorrect param class at position $p : should be a '$$s{class}'";
257 } elsif ($s->{type}) {
258 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
259 die "Incorrect param type at position $p : should be an 'object'";
260 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
261 die "Incorrect param type at position $p : should be an 'array'";
262 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
263 die "Incorrect param type at position $p : should be a 'number'";
264 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
265 die "Incorrect param type at position $p : should be a 'string'";
274 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
275 my $time = sprintf '%.3f', time - $start;
276 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
278 $appreq = $aref->[0];
279 $appreq->respond_complete( $response );
280 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
284 if(UNIVERSAL::isa($e,"Error")) {
285 $e = $e->stringify();
288 OpenSRF::DomainObject::oilsMethodException->new(
289 statusCode => STATUS_INTERNALSERVERERROR(),
290 status => "Call to [".$aref->[2]->api_name."] faild: $e"
300 $log->info("Received non-REQUEST message in Application handler");
302 my $res = OpenSRF::DomainObject::oilsMethodException->new(
303 status => "Received non-REQUEST message in Application handler");
304 $session->send('ERROR', $res);
309 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
312 $session->last_message_type('');
313 $session->last_message_api_level('');
320 my $api_name = shift;
321 my $api_level = shift || 1;
322 return exists($_METHODS[$api_level]{$api_name});
326 sub normalize_whitespace {
333 $txt =~ s/\. /\. /gso;
338 sub parse_string_signature {
340 return [] unless $string;
341 my @chunks = split(/\@/smo, $string);
347 if (/^return (.+)$/so) {
348 $ret = [normalize_whitespace($1)];
349 } elsif (/^param (\w+) \b(.+)$/so) {
350 push @params, [ $1, normalize_whitespace($2) ];
352 $desc .= '@' if $desc;
357 return [normalize_whitespace($desc),\@params, $ret];
360 sub parse_array_signature {
362 my ($d,$p,$r) = @$array;
363 return {} unless ($d or $p or $r);
384 sub register_method {
386 my $app = ref($self) || $self;
390 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
392 $args{api_level} = 1 unless(defined($args{api_level}));
396 $args{package} ||= $app;
397 $args{server_class} = server_class();
398 $args{api_name} ||= $args{server_class} . '.' . $args{method};
400 # un-if(0) this block to enable signature parsing
401 if (!$args{signature}) {
402 if ($args{notes} && !ref($args{notes})) {
404 parse_array_signature( parse_string_signature( $args{notes} ) );
406 } elsif( !ref($args{signature}) ) {
408 parse_array_signature( parse_string_signature( $args{signature} ) );
409 } elsif( ref($args{signature}) eq 'ARRAY') {
411 parse_array_signature( $args{signature} );
414 unless ($args{object_hint}) {
415 ($args{object_hint} = $args{package}) =~ s/::/_/go;
418 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
420 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
422 __PACKAGE__->register_method(
425 api_name => $args{api_name}.'.atomic',
426 method => 'make_stream_atomic',
427 notes => "This is a system generated method. Please see the definition for $args{api_name}",
428 ) if ($args{stream});
431 sub retrieve_remote_apis {
433 my $session = OpenSRF::AppSession->create('router');
435 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
438 $log->debug( "Remote subrequest returned an error:\n". $e );
441 return undef unless ($session->state == $session->CONNECTED);
444 my $req = $session->request( 'opensrf.router.info.class.list' );
445 my $list = $req->recv;
447 if( UNIVERSAL::isa($list,"Error") ) {
451 my $content = $list->content;
455 $session->disconnect;
457 my %u_list = map { ($_ => 1) } @$content;
459 for my $class ( keys %u_list ) {
460 next if($class eq $server_class);
461 populate_remote_method_cache($class, $method);
465 sub populate_remote_method_cache {
469 my $session = OpenSRF::AppSession->create($class);
471 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
473 my $call = 'opensrf.system.method.all' unless (defined $meth);
474 $call = 'opensrf.system.method' if (defined $meth);
476 my $req = $session->request( $call, $meth );
478 while (my $method = $req->recv) {
479 next if (UNIVERSAL::isa($method, 'Error'));
481 $method = $method->content;
482 next if ( exists($_METHODS[$$method{api_level}]) &&
483 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
484 $method->{remote} = 1;
485 bless($method, __PACKAGE__ );
486 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
491 $session->disconnect;
495 $log->debug( "Remote subrequest returned an error:\n". $e );
504 my $no_recurse = shift || 0;
505 my $no_remote = shift || 0;
507 # this instead of " || 1;" above to allow api_level 0
508 $proto = $self->api_level unless (defined $proto);
510 my $class = ref($self) || $self;
512 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
513 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
516 if (__PACKAGE__->thunk) {
517 for my $p ( reverse(1 .. $proto) ) {
518 if (exists $_METHODS[$p]{$method}) {
519 $meth = $_METHODS[$p]{$method};
523 if (exists $_METHODS[$proto]{$method}) {
524 $meth = $_METHODS[$proto]{$method};
529 if($no_remote and $meth->{remote}) {
530 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
534 } elsif (!$no_recurse) {
535 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
536 retrieve_remote_apis($method);
537 $meth = $self->method_lookup($method,$proto,1);
550 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
551 $log->debug("Creating a SubRequest object", DEBUG);
552 unshift @params, $req;
553 $req = OpenSRF::AppSubrequest->new;
554 $req->session( $self->session ) if ($self->session);
557 $log->debug("This is a top level request", DEBUG);
560 if (!$self->{remote}) {
561 my $code = \&{$self->{package} . '::' . $self->{method}};
565 $resp = $code->($self, $req, @params);
570 if( ref($self) eq 'HASH') {
571 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
576 if(UNIVERSAL::isa($err,"Error")) {
584 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
586 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
587 $req->respond($resp) if (defined $resp);
588 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
589 return $req->responses;
591 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
595 my $session = OpenSRF::AppSession->create($self->{server_class});
597 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
598 my $remote_req = $session->request( $self->{api_name}, @params );
599 while (my $remote_resp = $remote_req->recv) {
600 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
601 if( UNIVERSAL::isa($remote_resp,"Error") ) {
604 $req->respond( $remote_resp->content );
606 $remote_req->finish();
610 $log->debug( "Remote subrequest returned an error:\n". $e );
615 $session->disconnect();
619 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
621 return $req->responses;
623 # huh? how'd we get here...
634 if ($self->api_name =~ /all$/o) {
640 my ($seen,$returned) = (0,0);
641 for my $api_level ( reverse(1 .. $#_METHODS) ) {
642 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
643 if (!$offset || $offset <= $seen) {
644 if (!$_METHODS[$api_level]{$api_name}{remote}) {
645 if (defined($method)) {
646 if ($api_name =~ $method) {
647 if (!$limit || $returned < $limit) {
648 $client->respond( $_METHODS[$api_level]{$api_name} );
653 if (!$limit || $returned < $limit) {
654 $client->respond( $_METHODS[$api_level]{$api_name} );
666 __PACKAGE__->register_method(
668 method => 'introspect',
669 api_name => 'opensrf.system.method.all',
672 desc => q/This method is used to introspect an entire OpenSRF Application/,
674 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
679 __PACKAGE__->register_method(
681 method => 'introspect',
683 api_name => 'opensrf.system.method',
686 desc => q/Use this method to get the definition of a single OpenSRF Method/,
688 { desc => q/The method to introspect/,
691 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
701 $client->respond( $_ ) for (@args);
704 __PACKAGE__->register_method(
706 method => 'echo_method',
708 api_name => 'opensrf.system.echo',
710 desc => q/A test method that will echo back it's arguments in a streaming response/,
712 { desc => q/One or more arguments to echo back/ }
714 return => { desc => q/A stream of the arguments passed/ }
719 my( $self, $conn ) = @_;
722 __PACKAGE__->register_method(
723 method => 'time_method',
725 api_name => 'opensrf.system.time',
727 desc => q/Returns the current system time as epoch seconds/,
728 return => { desc => q/epoch seconds/ }
732 sub make_stream_atomic {
737 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
738 my $m = $self->method_lookup($m_name);
740 $m->session( $req->session );
741 my @results = $m->run(@args);