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 $log->debug( "In Application::handler()", DEBUG );
95 my $app = $self->application_implementation;
98 $log->debug( "Application is $app", DEBUG);
101 if ($session->last_message_type eq 'REQUEST') {
102 $log->debug( "We got a REQUEST: ". $app_msg->method);
104 my $method_name = $app_msg->method;
105 $log->debug( " * Looking up $method_name inside $app", DEBUG);
107 my $method_proto = $session->last_message_api_level;
108 $log->debug( " * Method API Level [$method_proto]", DEBUG);
110 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
113 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
114 statusCode => STATUS_NOTFOUND(),
115 status => "Method [$method_name] not found for $app"));
119 $log->debug( " (we got coderef $coderef", DEBUG);
121 unless ($session->continue_request) {
123 OpenSRF::DomainObject::oilsConnectStatus->new(
124 statusCode => STATUS_REDIRECTED(),
125 status => 'Disconnect on max requests' ) );
131 my @args = $app_msg->params;
132 my $appreq = OpenSRF::AppRequest->new( $session );
134 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", DEBUG );
136 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
137 push @pending_requests, [ $appreq, \@args, $coderef ];
144 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
148 # un-if(0) this block to enable param checking based on signature and argc
150 if (@args < $coderef->argc) {
151 die "Not enough params passed to ".
152 $coderef->api_name." : requires ". $coderef->argc
155 my $sig = $coderef->signature;
156 if ($sig && exists $sig->{params}) {
157 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
158 my $s = $sig->{params}->[$p];
160 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
161 die "Incorrect param class at position $p : should be a '$$s{class}'";
162 } elsif ($s->{type}) {
163 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
164 die "Incorrect param type at position $p : should be an 'object'";
165 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
166 die "Incorrect param type at position $p : should be an 'array'";
167 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
168 die "Incorrect param type at position $p : should be a 'number'";
169 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
170 die "Incorrect param type at position $p : should be a 'string'";
179 warn "About to run...\n";
180 $resp = $coderef->run( $appreq, @args);
181 warn "Done running...\n";
182 my $time = sprintf '%.3f', time() - $start;
184 $log->debug( "Method duration for {$method_name}: ". $time );
185 if( defined( $resp ) ) {
186 $appreq->respond_complete( $resp );
188 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
189 statusCode => STATUS_COMPLETE(),
190 status => 'Request Complete' ) );
194 warn "Caught error from 'run' method: $e\n";
196 if(UNIVERSAL::isa($e,"Error")) {
197 $e = $e->stringify();
199 my $sess_id = $session->session_id;
201 OpenSRF::DomainObject::oilsMethodException->new(
202 statusCode => STATUS_INTERNALSERVERERROR(),
203 status => " *** Call to [$method_name] failed for session ".
204 "[$sess_id], thread trace ".
205 "[".$appreq->threadTrace."]:\n$e\n"
212 # ----------------------------------------------
215 # XXX may need this later
216 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
220 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
222 # cycle through queued requests
223 while( my $aref = shift @pending_requests ) {
227 # un-if(0) this block to enable param checking based on signature and argc
229 if (@args < $aref->[2]->argc) {
230 die "Not enough params passed to ".
231 $aref->[2]->api_name." : requires ". $aref->[2]->argc
234 my $sig = $aref->[2]->signature;
235 if ($sig && exists $sig->{params}) {
236 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
237 my $s = $sig->{params}->[$p];
239 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
240 die "Incorrect param class at position $p : should be a '$$s{class}'";
241 } elsif ($s->{type}) {
242 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
243 die "Incorrect param type at position $p : should be an 'object'";
244 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
245 die "Incorrect param type at position $p : should be an 'array'";
246 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
247 die "Incorrect param type at position $p : should be a 'number'";
248 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
249 die "Incorrect param type at position $p : should be a 'string'";
258 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
259 my $time = sprintf '%.3f', time - $start;
260 $log->debug( "Method duration for {[".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).'}: '.$time, DEBUG );
262 $appreq = $aref->[0];
263 if( ref( $response ) ) {
264 $appreq->respond_complete( $response );
266 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
267 statusCode => STATUS_COMPLETE(),
268 status => 'Request Complete' ) );
270 $log->debug( "Executed: " . $appreq->threadTrace, DEBUG );
273 if(UNIVERSAL::isa($e,"Error")) {
274 $e = $e->stringify();
277 OpenSRF::DomainObject::oilsMethodException->new(
278 statusCode => STATUS_INTERNALSERVERERROR(),
279 status => "Call to [".$aref->[2]->api_name."] faild: $e"
289 my $res = OpenSRF::DomainObject::oilsMethodException->new(
290 status => "Received non-REQUEST message in Application handler");
291 $session->send('ERROR', $res);
296 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
299 $session->last_message_type('');
300 $session->last_message_api_level('');
307 my $api_name = shift;
308 my $api_level = shift || 1;
309 return exists($_METHODS[$api_level]{$api_name});
313 sub normalize_whitespace {
320 $txt =~ s/\. /\. /gso;
325 sub parse_string_signature {
327 return [] unless $string;
328 my @chunks = split(/\@/so, $string);
334 if (/^return (.+)$/so) {
335 $ret = [normalize_whitespace($1)];
336 } elsif (/^param (\w+) \b(.+)$/so) {
337 push @params, [ $1, normalize_whitespace($2) ];
339 $desc .= '@' if $desc;
344 return [normalize_whitespace($desc),\@params, $ret];
347 sub parse_array_signature {
349 my ($d,$p,$r) = @$array;
350 return {} unless ($d or $p or $r);
371 sub register_method {
373 my $app = ref($self) || $self;
377 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
379 $args{api_level} = 1 unless(defined($args{api_level}));
383 $args{package} ||= $app;
384 $args{server_class} = server_class();
385 $args{api_name} ||= $args{server_class} . '.' . $args{method};
387 # un-if(0) this block to enable signature parsing
388 if (!$args{signature}) {
389 if ($args{notes} && !ref($args{notes})) {
391 parse_array_signature( parse_string_signature( $args{notes} ) );
393 } elsif( !ref($args{signature}) ) {
395 parse_array_signature( parse_string_signature( $args{notes} ) );
396 } elsif( ref($args{signature}) eq 'ARRAY') {
398 parse_array_signature( $args{signature} );
401 unless ($args{object_hint}) {
402 ($args{object_hint} = $args{package}) =~ s/::/_/go;
405 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
407 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
409 __PACKAGE__->register_method(
412 api_name => $args{api_name}.'.atomic',
413 method => 'make_stream_atomic',
414 notes => "This is a system generated method. Please see the definition for $args{api_name}",
415 ) if ($args{stream});
418 sub retrieve_remote_apis {
420 my $session = OpenSRF::AppSession->create('router');
422 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
425 $log->debug( "Remote subrequest returned an error:\n". $e );
428 return undef unless ($session->state == $session->CONNECTED);
431 my $req = $session->request( 'opensrf.router.info.class.list' );
432 my $list = $req->recv;
434 if( UNIVERSAL::isa($list,"Error") ) {
438 my $content = $list->content;
442 $session->disconnect;
444 my %u_list = map { ($_ => 1) } @$content;
446 for my $class ( keys %u_list ) {
447 next if($class eq $server_class);
448 populate_remote_method_cache($class, $method);
452 sub populate_remote_method_cache {
456 my $session = OpenSRF::AppSession->create($class);
458 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
460 my $call = 'opensrf.system.method.all' unless (defined $meth);
461 $call = 'opensrf.system.method' if (defined $meth);
463 my $req = $session->request( $call, $meth );
465 while (my $method = $req->recv) {
466 next if (UNIVERSAL::isa($method, 'Error'));
468 $method = $method->content;
469 next if ( exists($_METHODS[$$method{api_level}]) &&
470 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
471 $method->{remote} = 1;
472 bless($method, __PACKAGE__ );
473 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
478 $session->disconnect;
482 $log->debug( "Remote subrequest returned an error:\n". $e );
491 my $no_recurse = shift || 0;
492 my $no_remote = shift || 0;
494 # this instead of " || 1;" above to allow api_level 0
495 $proto = $self->api_level unless (defined $proto);
497 my $class = ref($self) || $self;
499 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
500 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
503 if (__PACKAGE__->thunk) {
504 for my $p ( reverse(1 .. $proto) ) {
505 if (exists $_METHODS[$p]{$method}) {
506 $meth = $_METHODS[$p]{$method};
510 if (exists $_METHODS[$proto]{$method}) {
511 $meth = $_METHODS[$proto]{$method};
516 $log->debug("Looks like we found [$method]!", DEBUG);
517 $log->debug("Method object is ".Dumper($meth), INTERNAL);
518 if($no_remote and $meth->{remote}) {
519 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
523 } elsif (!$no_recurse) {
524 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
525 retrieve_remote_apis($method);
526 $meth = $self->method_lookup($method,$proto,1);
539 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
540 $log->debug("Creating a SubRequest object", DEBUG);
541 unshift @params, $req;
542 $req = OpenSRF::AppSubrequest->new;
544 $log->debug("This is a top level request", DEBUG);
547 if (!$self->{remote}) {
548 my $code ||= \&{$self->{package} . '::' . $self->{method}};
549 $log->debug("Created coderef [$code] for $$self{package}::$$self{method}",DEBUG);
553 $resp = $code->($self, $req, @params);
558 warn "Method 'run' catching error: $e\n";
560 if( ref($self) eq 'HASH') {
561 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$e\n", ERROR);
566 if(UNIVERSAL::isa($err,"Error")) {
567 warn "Throwing from method run:\n$err\n------------------\n";
575 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
577 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
578 $log->debug("A SubRequest object is responding", DEBUG);
579 $req->respond($resp) if (defined $resp);
580 $log->debug("... Responding with : " . join(" ",$req->responses), DEBUG);
581 return $req->responses;
583 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
587 my $session = OpenSRF::AppSession->create($self->{server_class});
589 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
590 my $remote_req = $session->request( $self->{api_name}, @params );
591 while (my $remote_resp = $remote_req->recv) {
592 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
593 if( UNIVERSAL::isa($remote_resp,"Error") ) {
596 $req->respond( $remote_resp->content );
598 $remote_req->finish();
602 $log->debug( "Remote subrequest returned an error:\n". $e );
607 $session->disconnect();
611 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
613 return $req->responses;
615 # huh? how'd we get here...
626 $method = undef if ($self->api_name =~ /all$/o);
628 my ($seen,$returned) = (0,0);
629 for my $api_level ( reverse(1 .. $#_METHODS) ) {
630 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
631 if (!$offset || $offset < $seen) {
632 if (!$_METHODS[$api_level]{$api_name}{remote}) {
633 if (defined($method)) {
634 if ($api_name =~ $method) {
635 if (!$limit || $returned < $limit) {
636 $client->respond( $_METHODS[$api_level]{$api_name} );
641 if (!$limit || $returned < $limit) {
642 $client->respond( $_METHODS[$api_level]{$api_name} );
654 __PACKAGE__->register_method(
656 method => 'introspect',
657 api_name => 'opensrf.system.method.all',
660 desc => q/This method is used to introspect an entire OpenSRF Application/,
662 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
667 __PACKAGE__->register_method(
669 method => 'introspect',
671 api_name => 'opensrf.system.method',
674 desc => q/Use this method to get the definition of a single OpenSRF Method/,
676 { desc => q/The method to introspect/,
679 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
689 $client->respond( $_ ) for (@args);
692 __PACKAGE__->register_method(
694 method => 'echo_method',
696 api_name => 'opensrf.system.echo',
698 desc => q/A test method that will echo back it's arguments in a streaming response/,
700 { desc => q/One or more arguments to echo back/ }
702 return => { desc => q/A stream of the arguments passed/ }
706 sub make_stream_atomic {
711 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
712 my @results = $self->method_lookup($m_name)->run(@args);