1 package OpenSRF::Application;
2 use vars qw/$_app $log @_METHODS $thunk $server_class/;
5 use OpenSRF::AppSession;
6 use OpenSRF::DomainObject::oilsMethod;
7 use OpenSRF::DomainObject::oilsResponse qw/:status/;
8 use OpenSRF::Utils::Logger qw/:level $logger/;
10 use Time::HiRes qw/time/;
11 use OpenSRF::EX qw/:try/;
14 #use OpenSRF::UnixServer; # to get the server class from UnixServer::App
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);
46 return 1 unless ref($self);
47 return $self->{api_name};
52 return 1 unless ref($self);
53 return $self->{api_level};
59 $server_class = $class;
67 $thunk = $flag if (defined $flag);
71 sub application_implementation {
79 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
88 my ($self, $session, $app_msg) = @_;
94 my $app = $self->application_implementation;
96 if ($session->last_message_type eq 'REQUEST') {
98 my @p = $app_msg->params;
99 my $method_name = $app_msg->method;
100 my $method_proto = $session->last_message_api_level;
101 $logger->info("CALL: $method_name [".join(', ',@p)."]");
103 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
106 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
107 statusCode => STATUS_NOTFOUND(),
108 status => "Method [$method_name] not found for $app"));
112 unless ($session->continue_request) {
114 OpenSRF::DomainObject::oilsConnectStatus->new(
115 statusCode => STATUS_REDIRECTED(),
116 status => 'Disconnect on max requests' ) );
122 my @args = $app_msg->params;
123 my $appreq = OpenSRF::AppRequest->new( $session );
125 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
127 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
128 push @pending_requests, [ $appreq, \@args, $coderef ];
135 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
139 # un-if(0) this block to enable param checking based on signature and argc
141 if (@args < $coderef->argc) {
142 die "Not enough params passed to ".
143 $coderef->api_name." : requires ". $coderef->argc
146 my $sig = $coderef->signature;
147 if ($sig && exists $sig->{params}) {
148 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
149 my $s = $sig->{params}->[$p];
151 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
152 die "Incorrect param class at position $p : should be a '$$s{class}'";
153 } elsif ($s->{type}) {
154 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
155 die "Incorrect param type at position $p : should be an 'object'";
156 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
157 die "Incorrect param type at position $p : should be an 'array'";
158 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
159 die "Incorrect param type at position $p : should be a 'number'";
160 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
161 die "Incorrect param type at position $p : should be a 'string'";
170 $resp = $coderef->run( $appreq, @args);
171 my $time = sprintf '%.3f', time() - $start;
173 $log->debug( "Method duration for [$method_name]: ". $time );
174 if( defined( $resp ) ) {
175 $appreq->respond_complete( $resp );
177 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
178 statusCode => STATUS_COMPLETE(),
179 status => 'Request Complete' ) );
183 warn "Caught error from 'run' method: $e\n";
185 if(UNIVERSAL::isa($e,"Error")) {
186 $e = $e->stringify();
188 my $sess_id = $session->session_id;
190 OpenSRF::DomainObject::oilsMethodException->new(
191 statusCode => STATUS_INTERNALSERVERERROR(),
192 status => " *** Call to [$method_name] failed for session ".
193 "[$sess_id], thread trace ".
194 "[".$appreq->threadTrace."]:\n$e\n"
201 # ----------------------------------------------
204 # XXX may need this later
205 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
209 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
211 # cycle through queued requests
212 while( my $aref = shift @pending_requests ) {
216 # un-if(0) this block to enable param checking based on signature and argc
218 if (@args < $aref->[2]->argc) {
219 die "Not enough params passed to ".
220 $aref->[2]->api_name." : requires ". $aref->[2]->argc
223 my $sig = $aref->[2]->signature;
224 if ($sig && exists $sig->{params}) {
225 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
226 my $s = $sig->{params}->[$p];
228 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
229 die "Incorrect param class at position $p : should be a '$$s{class}'";
230 } elsif ($s->{type}) {
231 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
232 die "Incorrect param type at position $p : should be an 'object'";
233 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
234 die "Incorrect param type at position $p : should be an 'array'";
235 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
236 die "Incorrect param type at position $p : should be a 'number'";
237 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
238 die "Incorrect param type at position $p : should be a 'string'";
247 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
248 my $time = sprintf '%.3f', time - $start;
249 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
251 $appreq = $aref->[0];
252 if( ref( $response ) ) {
253 $appreq->respond_complete( $response );
255 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
256 statusCode => STATUS_COMPLETE(),
257 status => 'Request Complete' ) );
259 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
262 if(UNIVERSAL::isa($e,"Error")) {
263 $e = $e->stringify();
266 OpenSRF::DomainObject::oilsMethodException->new(
267 statusCode => STATUS_INTERNALSERVERERROR(),
268 status => "Call to [".$aref->[2]->api_name."] faild: $e"
278 $log->info("Received non-REQUEST message in Application handler");
280 my $res = OpenSRF::DomainObject::oilsMethodException->new(
281 status => "Received non-REQUEST message in Application handler");
282 $session->send('ERROR', $res);
287 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
290 $session->last_message_type('');
291 $session->last_message_api_level('');
298 my $api_name = shift;
299 my $api_level = shift || 1;
300 return exists($_METHODS[$api_level]{$api_name});
304 sub normalize_whitespace {
311 $txt =~ s/\. /\. /gso;
316 sub parse_string_signature {
318 return [] unless $string;
319 my @chunks = split(/\@/so, $string);
325 if (/^return (.+)$/so) {
326 $ret = [normalize_whitespace($1)];
327 } elsif (/^param (\w+) \b(.+)$/so) {
328 push @params, [ $1, normalize_whitespace($2) ];
330 $desc .= '@' if $desc;
335 return [normalize_whitespace($desc),\@params, $ret];
338 sub parse_array_signature {
340 my ($d,$p,$r) = @$array;
341 return {} unless ($d or $p or $r);
362 sub register_method {
364 my $app = ref($self) || $self;
368 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
370 $args{api_level} = 1 unless(defined($args{api_level}));
374 $args{package} ||= $app;
375 $args{server_class} = server_class();
376 $args{api_name} ||= $args{server_class} . '.' . $args{method};
378 # un-if(0) this block to enable signature parsing
379 if (!$args{signature}) {
380 if ($args{notes} && !ref($args{notes})) {
382 parse_array_signature( parse_string_signature( $args{notes} ) );
384 } elsif( !ref($args{signature}) ) {
386 parse_array_signature( parse_string_signature( $args{signature} ) );
387 } elsif( ref($args{signature}) eq 'ARRAY') {
389 parse_array_signature( $args{signature} );
392 unless ($args{object_hint}) {
393 ($args{object_hint} = $args{package}) =~ s/::/_/go;
396 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
398 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
400 __PACKAGE__->register_method(
403 api_name => $args{api_name}.'.atomic',
404 method => 'make_stream_atomic',
405 notes => "This is a system generated method. Please see the definition for $args{api_name}",
406 ) if ($args{stream});
409 sub retrieve_remote_apis {
411 my $session = OpenSRF::AppSession->create('router');
413 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
416 $log->debug( "Remote subrequest returned an error:\n". $e );
419 return undef unless ($session->state == $session->CONNECTED);
422 my $req = $session->request( 'opensrf.router.info.class.list' );
423 my $list = $req->recv;
425 if( UNIVERSAL::isa($list,"Error") ) {
429 my $content = $list->content;
433 $session->disconnect;
435 my %u_list = map { ($_ => 1) } @$content;
437 for my $class ( keys %u_list ) {
438 next if($class eq $server_class);
439 populate_remote_method_cache($class, $method);
443 sub populate_remote_method_cache {
447 my $session = OpenSRF::AppSession->create($class);
449 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
451 my $call = 'opensrf.system.method.all' unless (defined $meth);
452 $call = 'opensrf.system.method' if (defined $meth);
454 my $req = $session->request( $call, $meth );
456 while (my $method = $req->recv) {
457 next if (UNIVERSAL::isa($method, 'Error'));
459 $method = $method->content;
460 next if ( exists($_METHODS[$$method{api_level}]) &&
461 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
462 $method->{remote} = 1;
463 bless($method, __PACKAGE__ );
464 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
469 $session->disconnect;
473 $log->debug( "Remote subrequest returned an error:\n". $e );
482 my $no_recurse = shift || 0;
483 my $no_remote = shift || 0;
485 # this instead of " || 1;" above to allow api_level 0
486 $proto = $self->api_level unless (defined $proto);
488 my $class = ref($self) || $self;
490 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
491 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
494 if (__PACKAGE__->thunk) {
495 for my $p ( reverse(1 .. $proto) ) {
496 if (exists $_METHODS[$p]{$method}) {
497 $meth = $_METHODS[$p]{$method};
501 if (exists $_METHODS[$proto]{$method}) {
502 $meth = $_METHODS[$proto]{$method};
507 if($no_remote and $meth->{remote}) {
508 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
512 } elsif (!$no_recurse) {
513 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
514 retrieve_remote_apis($method);
515 $meth = $self->method_lookup($method,$proto,1);
528 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
529 $log->debug("Creating a SubRequest object", DEBUG);
530 unshift @params, $req;
531 $req = OpenSRF::AppSubrequest->new;
533 $log->debug("This is a top level request", DEBUG);
536 if (!$self->{remote}) {
537 my $code = \&{$self->{package} . '::' . $self->{method}};
541 $resp = $code->($self, $req, @params);
546 if( ref($self) eq 'HASH') {
547 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
552 if(UNIVERSAL::isa($err,"Error")) {
560 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
562 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
563 $req->respond($resp) if (defined $resp);
564 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
565 return $req->responses;
567 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
571 my $session = OpenSRF::AppSession->create($self->{server_class});
573 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
574 my $remote_req = $session->request( $self->{api_name}, @params );
575 while (my $remote_resp = $remote_req->recv) {
576 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
577 if( UNIVERSAL::isa($remote_resp,"Error") ) {
580 $req->respond( $remote_resp->content );
582 $remote_req->finish();
586 $log->debug( "Remote subrequest returned an error:\n". $e );
591 $session->disconnect();
595 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
597 return $req->responses;
599 # huh? how'd we get here...
610 if ($self->api_name =~ /all$/o) {
616 my ($seen,$returned) = (0,0);
617 for my $api_level ( reverse(1 .. $#_METHODS) ) {
618 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
619 if (!$offset || $offset <= $seen) {
620 if (!$_METHODS[$api_level]{$api_name}{remote}) {
621 if (defined($method)) {
622 if ($api_name =~ $method) {
623 if (!$limit || $returned < $limit) {
624 $client->respond( $_METHODS[$api_level]{$api_name} );
629 if (!$limit || $returned < $limit) {
630 $client->respond( $_METHODS[$api_level]{$api_name} );
642 __PACKAGE__->register_method(
644 method => 'introspect',
645 api_name => 'opensrf.system.method.all',
648 desc => q/This method is used to introspect an entire OpenSRF Application/,
650 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
655 __PACKAGE__->register_method(
657 method => 'introspect',
659 api_name => 'opensrf.system.method',
662 desc => q/Use this method to get the definition of a single OpenSRF Method/,
664 { desc => q/The method to introspect/,
667 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
677 $client->respond( $_ ) for (@args);
680 __PACKAGE__->register_method(
682 method => 'echo_method',
684 api_name => 'opensrf.system.echo',
686 desc => q/A test method that will echo back it's arguments in a streaming response/,
688 { desc => q/One or more arguments to echo back/ }
690 return => { desc => q/A stream of the arguments passed/ }
695 my( $self, $conn ) = @_;
698 __PACKAGE__->register_method(
699 method => 'time_method',
701 api_name => 'opensrf.system.time',
703 desc => q/Returns the current system time as epoch seconds/,
704 return => { desc => q/epoch seconds/ }
708 sub make_stream_atomic {
713 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
714 my @results = $self->method_lookup($m_name)->run(@args);