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/;
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 $method_name = $app_msg->method;
99 my $method_proto = $session->last_message_api_level;
101 my $coderef = $app->method_lookup( $method_name, $method_proto, 1, 1 );
104 $session->status( OpenSRF::DomainObject::oilsMethodException->new(
105 statusCode => STATUS_NOTFOUND(),
106 status => "Method [$method_name] not found for $app"));
110 unless ($session->continue_request) {
112 OpenSRF::DomainObject::oilsConnectStatus->new(
113 statusCode => STATUS_REDIRECTED(),
114 status => 'Disconnect on max requests' ) );
120 my @args = $app_msg->params;
121 my $appreq = OpenSRF::AppRequest->new( $session );
123 $log->debug( "in_request = $in_request : [" . $appreq->threadTrace."]", INTERNAL );
125 $log->debug( "Pushing onto pending requests: " . $appreq->threadTrace, DEBUG );
126 push @pending_requests, [ $appreq, \@args, $coderef ];
133 $log->debug( "Executing coderef for {$method_name}", INTERNAL );
137 # un-if(0) this block to enable param checking based on signature and argc
139 if (@args < $coderef->argc) {
140 die "Not enough params passed to ".
141 $coderef->api_name." : requires ". $coderef->argc
144 my $sig = $coderef->signature;
145 if ($sig && exists $sig->{params}) {
146 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
147 my $s = $sig->{params}->[$p];
149 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
150 die "Incorrect param class at position $p : should be a '$$s{class}'";
151 } elsif ($s->{type}) {
152 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
153 die "Incorrect param type at position $p : should be an 'object'";
154 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
155 die "Incorrect param type at position $p : should be an 'array'";
156 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
157 die "Incorrect param type at position $p : should be a 'number'";
158 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
159 die "Incorrect param type at position $p : should be a 'string'";
168 $resp = $coderef->run( $appreq, @args);
169 my $time = sprintf '%.3f', time() - $start;
171 $log->debug( "Method duration for [$method_name]: ". $time );
172 if( defined( $resp ) ) {
173 $appreq->respond_complete( $resp );
175 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
176 statusCode => STATUS_COMPLETE(),
177 status => 'Request Complete' ) );
181 warn "Caught error from 'run' method: $e\n";
183 if(UNIVERSAL::isa($e,"Error")) {
184 $e = $e->stringify();
186 my $sess_id = $session->session_id;
188 OpenSRF::DomainObject::oilsMethodException->new(
189 statusCode => STATUS_INTERNALSERVERERROR(),
190 status => " *** Call to [$method_name] failed for session ".
191 "[$sess_id], thread trace ".
192 "[".$appreq->threadTrace."]:\n$e\n"
199 # ----------------------------------------------
202 # XXX may need this later
203 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
207 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
209 # cycle through queued requests
210 while( my $aref = shift @pending_requests ) {
214 # un-if(0) this block to enable param checking based on signature and argc
216 if (@args < $aref->[2]->argc) {
217 die "Not enough params passed to ".
218 $aref->[2]->api_name." : requires ". $aref->[2]->argc
221 my $sig = $aref->[2]->signature;
222 if ($sig && exists $sig->{params}) {
223 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
224 my $s = $sig->{params}->[$p];
226 if ($s->{class} && JSON->lookup_hint(ref $a) ne $s->{class}) {
227 die "Incorrect param class at position $p : should be a '$$s{class}'";
228 } elsif ($s->{type}) {
229 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
230 die "Incorrect param type at position $p : should be an 'object'";
231 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
232 die "Incorrect param type at position $p : should be an 'array'";
233 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
234 die "Incorrect param type at position $p : should be a 'number'";
235 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
236 die "Incorrect param type at position $p : should be a 'string'";
245 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
246 my $time = sprintf '%.3f', time - $start;
247 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
249 $appreq = $aref->[0];
250 if( ref( $response ) ) {
251 $appreq->respond_complete( $response );
253 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
254 statusCode => STATUS_COMPLETE(),
255 status => 'Request Complete' ) );
257 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
260 if(UNIVERSAL::isa($e,"Error")) {
261 $e = $e->stringify();
264 OpenSRF::DomainObject::oilsMethodException->new(
265 statusCode => STATUS_INTERNALSERVERERROR(),
266 status => "Call to [".$aref->[2]->api_name."] faild: $e"
276 $log->info("Received non-REQUEST message in Application handler");
278 my $res = OpenSRF::DomainObject::oilsMethodException->new(
279 status => "Received non-REQUEST message in Application handler");
280 $session->send('ERROR', $res);
285 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
288 $session->last_message_type('');
289 $session->last_message_api_level('');
296 my $api_name = shift;
297 my $api_level = shift || 1;
298 return exists($_METHODS[$api_level]{$api_name});
302 sub normalize_whitespace {
309 $txt =~ s/\. /\. /gso;
314 sub parse_string_signature {
316 return [] unless $string;
317 my @chunks = split(/\@/so, $string);
323 if (/^return (.+)$/so) {
324 $ret = [normalize_whitespace($1)];
325 } elsif (/^param (\w+) \b(.+)$/so) {
326 push @params, [ $1, normalize_whitespace($2) ];
328 $desc .= '@' if $desc;
333 return [normalize_whitespace($desc),\@params, $ret];
336 sub parse_array_signature {
338 my ($d,$p,$r) = @$array;
339 return {} unless ($d or $p or $r);
360 sub register_method {
362 my $app = ref($self) || $self;
366 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
368 $args{api_level} = 1 unless(defined($args{api_level}));
372 $args{package} ||= $app;
373 $args{server_class} = server_class();
374 $args{api_name} ||= $args{server_class} . '.' . $args{method};
376 # un-if(0) this block to enable signature parsing
377 if (!$args{signature}) {
378 if ($args{notes} && !ref($args{notes})) {
380 parse_array_signature( parse_string_signature( $args{notes} ) );
382 } elsif( !ref($args{signature}) ) {
384 parse_array_signature( parse_string_signature( $args{signature} ) );
385 } elsif( ref($args{signature}) eq 'ARRAY') {
387 parse_array_signature( $args{signature} );
390 unless ($args{object_hint}) {
391 ($args{object_hint} = $args{package}) =~ s/::/_/go;
394 JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
396 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
398 __PACKAGE__->register_method(
401 api_name => $args{api_name}.'.atomic',
402 method => 'make_stream_atomic',
403 notes => "This is a system generated method. Please see the definition for $args{api_name}",
404 ) if ($args{stream});
407 sub retrieve_remote_apis {
409 my $session = OpenSRF::AppSession->create('router');
411 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
414 $log->debug( "Remote subrequest returned an error:\n". $e );
417 return undef unless ($session->state == $session->CONNECTED);
420 my $req = $session->request( 'opensrf.router.info.class.list' );
421 my $list = $req->recv;
423 if( UNIVERSAL::isa($list,"Error") ) {
427 my $content = $list->content;
431 $session->disconnect;
433 my %u_list = map { ($_ => 1) } @$content;
435 for my $class ( keys %u_list ) {
436 next if($class eq $server_class);
437 populate_remote_method_cache($class, $method);
441 sub populate_remote_method_cache {
445 my $session = OpenSRF::AppSession->create($class);
447 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
449 my $call = 'opensrf.system.method.all' unless (defined $meth);
450 $call = 'opensrf.system.method' if (defined $meth);
452 my $req = $session->request( $call, $meth );
454 while (my $method = $req->recv) {
455 next if (UNIVERSAL::isa($method, 'Error'));
457 $method = $method->content;
458 next if ( exists($_METHODS[$$method{api_level}]) &&
459 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
460 $method->{remote} = 1;
461 bless($method, __PACKAGE__ );
462 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
467 $session->disconnect;
471 $log->debug( "Remote subrequest returned an error:\n". $e );
480 my $no_recurse = shift || 0;
481 my $no_remote = shift || 0;
483 # this instead of " || 1;" above to allow api_level 0
484 $proto = $self->api_level unless (defined $proto);
486 my $class = ref($self) || $self;
488 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
489 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
492 if (__PACKAGE__->thunk) {
493 for my $p ( reverse(1 .. $proto) ) {
494 if (exists $_METHODS[$p]{$method}) {
495 $meth = $_METHODS[$p]{$method};
499 if (exists $_METHODS[$proto]{$method}) {
500 $meth = $_METHODS[$proto]{$method};
505 if($no_remote and $meth->{remote}) {
506 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
510 } elsif (!$no_recurse) {
511 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
512 retrieve_remote_apis($method);
513 $meth = $self->method_lookup($method,$proto,1);
526 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
527 $log->debug("Creating a SubRequest object", DEBUG);
528 unshift @params, $req;
529 $req = OpenSRF::AppSubrequest->new;
531 $log->debug("This is a top level request", DEBUG);
534 if (!$self->{remote}) {
535 my $code = \&{$self->{package} . '::' . $self->{method}};
539 $resp = $code->($self, $req, @params);
544 if( ref($self) eq 'HASH') {
545 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
550 if(UNIVERSAL::isa($err,"Error")) {
558 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
560 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
561 $req->respond($resp) if (defined $resp);
562 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
563 return $req->responses;
565 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
569 my $session = OpenSRF::AppSession->create($self->{server_class});
571 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
572 my $remote_req = $session->request( $self->{api_name}, @params );
573 while (my $remote_resp = $remote_req->recv) {
574 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
575 if( UNIVERSAL::isa($remote_resp,"Error") ) {
578 $req->respond( $remote_resp->content );
580 $remote_req->finish();
584 $log->debug( "Remote subrequest returned an error:\n". $e );
589 $session->disconnect();
593 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
595 return $req->responses;
597 # huh? how'd we get here...
608 if ($self->api_name =~ /all$/o) {
614 my ($seen,$returned) = (0,0);
615 for my $api_level ( reverse(1 .. $#_METHODS) ) {
616 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
617 if (!$offset || $offset <= $seen) {
618 if (!$_METHODS[$api_level]{$api_name}{remote}) {
619 if (defined($method)) {
620 if ($api_name =~ $method) {
621 if (!$limit || $returned < $limit) {
622 $client->respond( $_METHODS[$api_level]{$api_name} );
627 if (!$limit || $returned < $limit) {
628 $client->respond( $_METHODS[$api_level]{$api_name} );
640 __PACKAGE__->register_method(
642 method => 'introspect',
643 api_name => 'opensrf.system.method.all',
646 desc => q/This method is used to introspect an entire OpenSRF Application/,
648 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
653 __PACKAGE__->register_method(
655 method => 'introspect',
657 api_name => 'opensrf.system.method',
660 desc => q/Use this method to get the definition of a single OpenSRF Method/,
662 { desc => q/The method to introspect/,
665 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
675 $client->respond( $_ ) for (@args);
678 __PACKAGE__->register_method(
680 method => 'echo_method',
682 api_name => 'opensrf.system.echo',
684 desc => q/A test method that will echo back it's arguments in a streaming response/,
686 { desc => q/One or more arguments to echo back/ }
688 return => { desc => q/A stream of the arguments passed/ }
693 my( $self, $conn ) = @_;
696 __PACKAGE__->register_method(
697 method => 'time_method',
699 api_name => 'opensrf.system.time',
701 desc => q/Returns the current system time as epoch seconds/,
702 return => { desc => q/epoch seconds/ }
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);