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/;
10 use Time::HiRes qw/time/;
11 use OpenSRF::EX qw/:try/;
13 #use OpenSRF::UnixServer; # to get the server class from UnixServer::App
20 $log = 'OpenSRF::Utils::Logger';
23 our @pending_requests;
27 return 1 unless ref($self);
28 return $self->{package};
33 return 0 unless ref($self);
34 return $self->{signature};
39 return 0 unless ref($self);
45 return 1 unless ref($self);
46 return $self->{api_name};
51 return 1 unless ref($self);
52 return $self->{api_level};
58 $server_class = $class;
66 $thunk = $flag if (defined $flag);
70 sub application_implementation {
78 $log->error( "Error loading application_implementation: $app -> $@", ERROR);
87 my ($self, $session, $app_msg) = @_;
93 my $app = $self->application_implementation;
95 if ($session->last_message_type eq 'REQUEST') {
97 my $method_name = $app_msg->method;
98 my $method_proto = $session->last_message_api_level;
100 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
103 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
104 statusCode => STATUS_NOTFOUND(),
105 status => "Method [$method_name] not found for $app"));
109 unless ($session->continue_request) {
111 OpenSRF::DomainObject::oilsConnectStatus->new(
112 statusCode => STATUS_REDIRECTED(),
113 status => 'Disconnect on max requests' ) );
119 my @args = $app_msg->params;
120 my $appreq = OpenSRF::AppRequest->new( $session );
122 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
124 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
125 push @pending_requests, [ $appreq, \@args, $coderef ];
132 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
136 # un-if(0) this block to enable param checking based on signature and argc
138 if (@args < $coderef->argc) {
139 die "Not enough params passed to ".
140 $coderef->api_name." : requires ". $coderef->argc
143 my $sig = $coderef->signature;
144 if ($sig && exists $sig->{params}) {
145 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
146 my $s = $sig->{params}->[$p];
148 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
149 die "Incorrect param class at position $p : should be a '$$s{class}'";
150 } elsif ($s->{type}) {
151 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
152 die "Incorrect param type at position $p : should be an 'object'";
153 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
154 die "Incorrect param type at position $p : should be an 'array'";
155 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
156 die "Incorrect param type at position $p : should be a 'number'";
157 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
158 die "Incorrect param type at position $p : should be a 'string'";
167 warn "About to run...\n";
168 $resp = $coderef->run( $appreq, @args);
169 warn "Done running...\n";
170 my $time = sprintf '%.3f', time() - $start;
172 $log->debug( "Method duration for [$method_name]: ". $time );
173 if( defined( $resp ) ) {
174 $appreq->respond_complete( $resp );
176 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
177 statusCode => STATUS_COMPLETE(),
178 status => 'Request Complete' ) );
182 warn "Caught error from 'run' method: $e\n";
184 if(UNIVERSAL::isa($e,"Error")) {
185 $e = $e->stringify();
187 my $sess_id = $session->session_id;
189 OpenSRF::DomainObject::oilsMethodException->new(
190 statusCode => STATUS_INTERNALSERVERERROR(),
191 status => " *** Call to [$method_name] failed for session ".
192 "[$sess_id], thread trace ".
193 "[".$appreq->threadTrace."]:\n$e\n"
200 # ----------------------------------------------
203 # XXX may need this later
204 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
208 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
210 # cycle through queued requests
211 while( my $aref = shift @pending_requests ) {
215 # un-if(0) this block to enable param checking based on signature and argc
217 if (@args < $aref->[2]->argc) {
218 die "Not enough params passed to ".
219 $aref->[2]->api_name." : requires ". $aref->[2]->argc
222 my $sig = $aref->[2]->signature;
223 if ($sig && exists $sig->{params}) {
224 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
225 my $s = $sig->{params}->[$p];
227 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
228 die "Incorrect param class at position $p : should be a '$$s{class}'";
229 } elsif ($s->{type}) {
230 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
231 die "Incorrect param type at position $p : should be an 'object'";
232 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
233 die "Incorrect param type at position $p : should be an 'array'";
234 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
235 die "Incorrect param type at position $p : should be a 'number'";
236 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
237 die "Incorrect param type at position $p : should be a 'string'";
246 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
247 my $time = sprintf '%.3f', time - $start;
248 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
250 $appreq = $aref->[0];
251 if( ref( $response ) ) {
252 $appreq->respond_complete( $response );
254 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
255 statusCode => STATUS_COMPLETE(),
256 status => 'Request Complete' ) );
258 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
261 if(UNIVERSAL::isa($e,"Error")) {
262 $e = $e->stringify();
265 OpenSRF::DomainObject::oilsMethodException->new(
266 statusCode => STATUS_INTERNALSERVERERROR(),
267 status => "Call to [".$aref->[2]->api_name."] faild: $e"
277 $log->info("Received non-REQUEST message in Application handler");
279 my $res = OpenSRF::DomainObject::oilsMethodException->new(
280 status => "Received non-REQUEST message in Application handler");
281 $session->send('ERROR', $res);
286 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
289 $session->last_message_type('');
290 $session->last_message_api_level('');
297 my $api_name = shift;
298 my $api_level = shift || 1;
299 return exists($_METHODS[$api_level]{$api_name});
303 sub normalize_whitespace {
310 $txt =~ s/\. /\. /gso;
315 sub parse_string_signature {
317 return [] unless $string;
318 my @chunks = split(/\@/so, $string);
324 if (/^return (.+)$/so) {
325 $ret = [normalize_whitespace($1)];
326 } elsif (/^param (\w+) \b(.+)$/so) {
327 push @params, [ $1, normalize_whitespace($2) ];
329 $desc .= '@' if $desc;
334 return [normalize_whitespace($desc),\@params, $ret];
337 sub parse_array_signature {
339 my ($d,$p,$r) = @$array;
340 return {} unless ($d or $p or $r);
361 sub register_method {
363 my $app = ref($self) || $self;
367 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
369 $args{api_level} = 1 unless(defined($args{api_level}));
373 $args{package} ||= $app;
374 $args{server_class} = server_class();
375 $args{api_name} ||= $args{server_class} . '.' . $args{method};
377 # un-if(0) this block to enable signature parsing
378 if (!$args{signature}) {
379 if ($args{notes} && !ref($args{notes})) {
381 parse_array_signature( parse_string_signature( $args{notes} ) );
383 } elsif( !ref($args{signature}) ) {
385 parse_array_signature( parse_string_signature( $args{signature} ) );
386 } elsif( ref($args{signature}) eq 'ARRAY') {
388 parse_array_signature( $args{signature} );
391 unless ($args{object_hint}) {
392 ($args{object_hint} = $args{package}) =~ s/::/_/go;
395 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
397 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
399 __PACKAGE__->register_method(
402 api_name => $args{api_name}.'.atomic',
403 method => 'make_stream_atomic',
404 notes => "This is a system generated method. Please see the definition for $args{api_name}",
405 ) if ($args{stream});
408 sub retrieve_remote_apis {
410 my $session = OpenSRF::AppSession->create('router');
412 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
415 $log->debug( "Remote subrequest returned an error:\n". $e );
418 return undef unless ($session->state == $session->CONNECTED);
421 my $req = $session->request( 'opensrf.router.info.class.list' );
422 my $list = $req->recv;
424 if( UNIVERSAL::isa($list,"Error") ) {
428 my $content = $list->content;
432 $session->disconnect;
434 my %u_list = map { ($_ => 1) } @$content;
436 for my $class ( keys %u_list ) {
437 next if($class eq $server_class);
438 populate_remote_method_cache($class, $method);
442 sub populate_remote_method_cache {
446 my $session = OpenSRF::AppSession->create($class);
448 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
450 my $call = 'opensrf.system.method.all' unless (defined $meth);
451 $call = 'opensrf.system.method' if (defined $meth);
453 my $req = $session->request( $call, $meth );
455 while (my $method = $req->recv) {
456 next if (UNIVERSAL::isa($method, 'Error'));
458 $method = $method->content;
459 next if ( exists($_METHODS[$$method{api_level}]) &&
460 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
461 $method->{remote} = 1;
462 bless($method, __PACKAGE__ );
463 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
468 $session->disconnect;
472 $log->debug( "Remote subrequest returned an error:\n". $e );
481 my $no_recurse = shift || 0;
482 my $no_remote = shift || 0;
484 # this instead of " || 1;" above to allow api_level 0
485 $proto = $self->api_level unless (defined $proto);
487 my $class = ref($self) || $self;
489 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
490 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
493 if (__PACKAGE__->thunk) {
494 for my $p ( reverse(1 .. $proto) ) {
495 if (exists $_METHODS[$p]{$method}) {
496 $meth = $_METHODS[$p]{$method};
500 if (exists $_METHODS[$proto]{$method}) {
501 $meth = $_METHODS[$proto]{$method};
506 if($no_remote and $meth->{remote}) {
507 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
511 } elsif (!$no_recurse) {
512 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
513 retrieve_remote_apis($method);
514 $meth = $self->method_lookup($method,$proto,1);
527 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
528 $log->debug("Creating a SubRequest object", DEBUG);
529 unshift @params, $req;
530 $req = OpenSRF::AppSubrequest->new;
532 $log->debug("This is a top level request", DEBUG);
535 if (!$self->{remote}) {
536 my $code = \&{$self->{package} . '::' . $self->{method}};
540 $resp = $code->($self, $req, @params);
545 if( ref($self) eq 'HASH') {
546 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
551 if(UNIVERSAL::isa($err,"Error")) {
559 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
561 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
562 $req->respond($resp) if (defined $resp);
563 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
564 return $req->responses;
566 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
570 my $session = OpenSRF::AppSession->create($self->{server_class});
572 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
573 my $remote_req = $session->request( $self->{api_name}, @params );
574 while (my $remote_resp = $remote_req->recv) {
575 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
576 if( UNIVERSAL::isa($remote_resp,"Error") ) {
579 $req->respond( $remote_resp->content );
581 $remote_req->finish();
585 $log->debug( "Remote subrequest returned an error:\n". $e );
590 $session->disconnect();
594 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
596 return $req->responses;
598 # huh? how'd we get here...
609 if ($self->api_name =~ /all$/o) {
615 my ($seen,$returned) = (0,0);
616 for my $api_level ( reverse(1 .. $#_METHODS) ) {
617 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
618 if (!$offset || $offset <= $seen) {
619 if (!$_METHODS[$api_level]{$api_name}{remote}) {
620 if (defined($method)) {
621 if ($api_name =~ $method) {
622 if (!$limit || $returned < $limit) {
623 $client->respond( $_METHODS[$api_level]{$api_name} );
628 if (!$limit || $returned < $limit) {
629 $client->respond( $_METHODS[$api_level]{$api_name} );
641 __PACKAGE__->register_method(
643 method => 'introspect',
644 api_name => 'opensrf.system.method.all',
647 desc => q/This method is used to introspect an entire OpenSRF Application/,
649 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
654 __PACKAGE__->register_method(
656 method => 'introspect',
658 api_name => 'opensrf.system.method',
661 desc => q/Use this method to get the definition of a single OpenSRF Method/,
663 { desc => q/The method to introspect/,
666 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
676 $client->respond( $_ ) for (@args);
679 __PACKAGE__->register_method(
681 method => 'echo_method',
683 api_name => 'opensrf.system.echo',
685 desc => q/A test method that will echo back it's arguments in a streaming response/,
687 { desc => q/One or more arguments to echo back/ }
689 return => { desc => q/A stream of the arguments passed/ }
694 my( $self, $conn ) = @_;
697 __PACKAGE__->register_method(
698 method => 'time_method',
700 api_name => 'opensrf.system.time',
702 desc => q/Returns the current system time as epoch seconds/,
703 return => { desc => q/epoch seconds/ }
707 sub make_stream_atomic {
712 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
713 my @results = $self->method_lookup($m_name)->run(@args);