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 if( defined( $resp ) ) {
207 $appreq->respond_complete( $resp );
209 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
210 statusCode => STATUS_COMPLETE(),
211 status => 'Request Complete' ) );
215 warn "Caught error from 'run' method: $e\n";
217 if(UNIVERSAL::isa($e,"Error")) {
218 $e = $e->stringify();
220 my $sess_id = $session->session_id;
222 OpenSRF::DomainObject::oilsMethodException->new(
223 statusCode => STATUS_INTERNALSERVERERROR(),
224 status => " *** Call to [$method_name] failed for session ".
225 "[$sess_id], thread trace ".
226 "[".$appreq->threadTrace."]:\n$e\n"
233 # ----------------------------------------------
236 # XXX may need this later
237 # $_->[1] = 1 for (@OpenSRF::AppSession::_CLIENT_CACHE);
241 $log->debug( "Pending Requests: " . scalar(@pending_requests), INTERNAL );
243 # cycle through queued requests
244 while( my $aref = shift @pending_requests ) {
248 # un-if(0) this block to enable param checking based on signature and argc
250 if (@args < $aref->[2]->argc) {
251 die "Not enough params passed to ".
252 $aref->[2]->api_name." : requires ". $aref->[2]->argc
255 my $sig = $aref->[2]->signature;
256 if ($sig && exists $sig->{params}) {
257 for my $p (0 .. scalar(@{ $sig->{params} }) - 1 ) {
258 my $s = $sig->{params}->[$p];
260 if ($s->{class} && OpenSRF::Utils::JSON->lookup_hint(ref $a) ne $s->{class}) {
261 die "Incorrect param class at position $p : should be a '$$s{class}'";
262 } elsif ($s->{type}) {
263 if (lc($s->{type}) eq 'object' && $a !~ /HASH/o) {
264 die "Incorrect param type at position $p : should be an 'object'";
265 } elsif (lc($s->{type}) eq 'array' && $a !~ /ARRAY/o) {
266 die "Incorrect param type at position $p : should be an 'array'";
267 } elsif (lc($s->{type}) eq 'number' && (ref($a) || $a !~ /^-?\d+(?:\.\d+)?$/o)) {
268 die "Incorrect param type at position $p : should be a 'number'";
269 } elsif (lc($s->{type}) eq 'string' && ref($a)) {
270 die "Incorrect param type at position $p : should be a 'string'";
279 my $response = $aref->[2]->run( $aref->[0], @{$aref->[1]} );
280 my $time = sprintf '%.3f', time - $start;
281 $log->debug( "Method duration for [".$aref->[2]->api_name." -> ".join(', ',@{$aref->[1]}).']: '.$time, DEBUG );
283 $appreq = $aref->[0];
284 if( ref( $response ) ) {
285 $appreq->respond_complete( $response );
287 $appreq->status( OpenSRF::DomainObject::oilsConnectStatus->new(
288 statusCode => STATUS_COMPLETE(),
289 status => 'Request Complete' ) );
291 $log->debug( "Executed: " . $appreq->threadTrace, INTERNAL );
294 if(UNIVERSAL::isa($e,"Error")) {
295 $e = $e->stringify();
298 OpenSRF::DomainObject::oilsMethodException->new(
299 statusCode => STATUS_INTERNALSERVERERROR(),
300 status => "Call to [".$aref->[2]->api_name."] faild: $e"
310 $log->info("Received non-REQUEST message in Application handler");
312 my $res = OpenSRF::DomainObject::oilsMethodException->new(
313 status => "Received non-REQUEST message in Application handler");
314 $session->send('ERROR', $res);
319 $session->push_queue([ $app_msg, $session->last_threadTrace ]);
322 $session->last_message_type('');
323 $session->last_message_api_level('');
330 my $api_name = shift;
331 my $api_level = shift || 1;
332 return exists($_METHODS[$api_level]{$api_name});
336 sub normalize_whitespace {
343 $txt =~ s/\. /\. /gso;
348 sub parse_string_signature {
350 return [] unless $string;
351 my @chunks = split(/\@/smo, $string);
357 if (/^return (.+)$/so) {
358 $ret = [normalize_whitespace($1)];
359 } elsif (/^param (\w+) \b(.+)$/so) {
360 push @params, [ $1, normalize_whitespace($2) ];
362 $desc .= '@' if $desc;
367 return [normalize_whitespace($desc),\@params, $ret];
370 sub parse_array_signature {
372 my ($d,$p,$r) = @$array;
373 return {} unless ($d or $p or $r);
394 sub register_method {
396 my $app = ref($self) || $self;
400 throw OpenSRF::DomainObject::oilsMethodException unless ($args{method});
402 $args{api_level} = 1 unless(defined($args{api_level}));
406 $args{package} ||= $app;
407 $args{server_class} = server_class();
408 $args{api_name} ||= $args{server_class} . '.' . $args{method};
410 # un-if(0) this block to enable signature parsing
411 if (!$args{signature}) {
412 if ($args{notes} && !ref($args{notes})) {
414 parse_array_signature( parse_string_signature( $args{notes} ) );
416 } elsif( !ref($args{signature}) ) {
418 parse_array_signature( parse_string_signature( $args{signature} ) );
419 } elsif( ref($args{signature}) eq 'ARRAY') {
421 parse_array_signature( $args{signature} );
424 unless ($args{object_hint}) {
425 ($args{object_hint} = $args{package}) =~ s/::/_/go;
428 OpenSRF::Utils::JSON->register_class_hint( name => $args{package}, hint => $args{object_hint}, type => "hash" );
430 $_METHODS[$args{api_level}]{$args{api_name}} = bless \%args => $app;
432 __PACKAGE__->register_method(
435 api_name => $args{api_name}.'.atomic',
436 method => 'make_stream_atomic',
437 notes => "This is a system generated method. Please see the definition for $args{api_name}",
438 ) if ($args{stream});
441 sub retrieve_remote_apis {
443 my $session = OpenSRF::AppSession->create('router');
445 $session->connect or OpenSRF::EX::WARN->throw("Connection to router timed out");
448 $log->debug( "Remote subrequest returned an error:\n". $e );
451 return undef unless ($session->state == $session->CONNECTED);
454 my $req = $session->request( 'opensrf.router.info.class.list' );
455 my $list = $req->recv;
457 if( UNIVERSAL::isa($list,"Error") ) {
461 my $content = $list->content;
465 $session->disconnect;
467 my %u_list = map { ($_ => 1) } @$content;
469 for my $class ( keys %u_list ) {
470 next if($class eq $server_class);
471 populate_remote_method_cache($class, $method);
475 sub populate_remote_method_cache {
479 my $session = OpenSRF::AppSession->create($class);
481 $session->connect or OpenSRF::EX::WARN->throw("Connection to $class timed out");
483 my $call = 'opensrf.system.method.all' unless (defined $meth);
484 $call = 'opensrf.system.method' if (defined $meth);
486 my $req = $session->request( $call, $meth );
488 while (my $method = $req->recv) {
489 next if (UNIVERSAL::isa($method, 'Error'));
491 $method = $method->content;
492 next if ( exists($_METHODS[$$method{api_level}]) &&
493 exists($_METHODS[$$method{api_level}]{$$method{api_name}}) );
494 $method->{remote} = 1;
495 bless($method, __PACKAGE__ );
496 $_METHODS[$$method{api_level}]{$$method{api_name}} = $method;
501 $session->disconnect;
505 $log->debug( "Remote subrequest returned an error:\n". $e );
514 my $no_recurse = shift || 0;
515 my $no_remote = shift || 0;
517 # this instead of " || 1;" above to allow api_level 0
518 $proto = $self->api_level unless (defined $proto);
520 my $class = ref($self) || $self;
522 $log->debug("Lookup of [$method] by [$class] in api_level [$proto]", DEBUG);
523 $log->debug("Available methods\n\t".join("\n\t", keys %{ $_METHODS[$proto] }), INTERNAL);
526 if (__PACKAGE__->thunk) {
527 for my $p ( reverse(1 .. $proto) ) {
528 if (exists $_METHODS[$p]{$method}) {
529 $meth = $_METHODS[$p]{$method};
533 if (exists $_METHODS[$proto]{$method}) {
534 $meth = $_METHODS[$proto]{$method};
539 if($no_remote and $meth->{remote}) {
540 $log->debug("OH CRAP We're not supposed to return remote methods", WARN);
544 } elsif (!$no_recurse) {
545 $log->debug("We didn't find [$method], asking everyone else.", DEBUG);
546 retrieve_remote_apis($method);
547 $meth = $self->method_lookup($method,$proto,1);
560 if ( !UNIVERSAL::isa($req, 'OpenSRF::AppRequest') ) {
561 $log->debug("Creating a SubRequest object", DEBUG);
562 unshift @params, $req;
563 $req = OpenSRF::AppSubrequest->new;
564 $req->session( $self->session ) if ($self->session);
567 $log->debug("This is a top level request", DEBUG);
570 if (!$self->{remote}) {
571 my $code = \&{$self->{package} . '::' . $self->{method}};
575 $resp = $code->($self, $req, @params);
580 if( ref($self) eq 'HASH') {
581 $log->error("Sub $$self{package}::$$self{method} DIED!!!\n\t$err\n", ERROR);
586 if(UNIVERSAL::isa($err,"Error")) {
594 $log->debug("Coderef for [$$self{package}::$$self{method}] has been run", DEBUG);
596 if ( ref($req) and UNIVERSAL::isa($req, 'OpenSRF::AppSubrequest') ) {
597 $req->respond($resp) if (defined $resp);
598 $log->debug("SubRequest object is responding with : " . join(" ",$req->responses), DEBUG);
599 return $req->responses;
601 $log->debug("A top level Request object is responding $resp", DEBUG) if (defined $resp);
605 my $session = OpenSRF::AppSession->create($self->{server_class});
607 #$session->connect or OpenSRF::EX::WARN->throw("Connection to [$$self{server_class}] timed out");
608 my $remote_req = $session->request( $self->{api_name}, @params );
609 while (my $remote_resp = $remote_req->recv) {
610 OpenSRF::Utils::Logger->debug("Remote Subrequest Received " . $remote_resp, INTERNAL );
611 if( UNIVERSAL::isa($remote_resp,"Error") ) {
614 $req->respond( $remote_resp->content );
616 $remote_req->finish();
620 $log->debug( "Remote subrequest returned an error:\n". $e );
625 $session->disconnect();
629 $log->debug( "Remote Subrequest Responses " . join(" ", $req->responses), INTERNAL );
631 return $req->responses;
633 # huh? how'd we get here...
644 if ($self->api_name =~ /all$/o) {
650 my ($seen,$returned) = (0,0);
651 for my $api_level ( reverse(1 .. $#_METHODS) ) {
652 for my $api_name ( sort keys %{$_METHODS[$api_level]} ) {
653 if (!$offset || $offset <= $seen) {
654 if (!$_METHODS[$api_level]{$api_name}{remote}) {
655 if (defined($method)) {
656 if ($api_name =~ $method) {
657 if (!$limit || $returned < $limit) {
658 $client->respond( $_METHODS[$api_level]{$api_name} );
663 if (!$limit || $returned < $limit) {
664 $client->respond( $_METHODS[$api_level]{$api_name} );
676 __PACKAGE__->register_method(
678 method => 'introspect',
679 api_name => 'opensrf.system.method.all',
682 desc => q/This method is used to introspect an entire OpenSRF Application/,
684 desc => q/A stream of objects describing the methods available via this OpenSRF Application/,
689 __PACKAGE__->register_method(
691 method => 'introspect',
693 api_name => 'opensrf.system.method',
696 desc => q/Use this method to get the definition of a single OpenSRF Method/,
698 { desc => q/The method to introspect/,
701 return => { desc => q/An object describing the method requested, or an error if it can't be found/,
711 $client->respond( $_ ) for (@args);
714 __PACKAGE__->register_method(
716 method => 'echo_method',
718 api_name => 'opensrf.system.echo',
720 desc => q/A test method that will echo back it's arguments in a streaming response/,
722 { desc => q/One or more arguments to echo back/ }
724 return => { desc => q/A stream of the arguments passed/ }
729 my( $self, $conn ) = @_;
732 __PACKAGE__->register_method(
733 method => 'time_method',
735 api_name => 'opensrf.system.time',
737 desc => q/Returns the current system time as epoch seconds/,
738 return => { desc => q/epoch seconds/ }
742 sub make_stream_atomic {
747 (my $m_name = $self->api_name) =~ s/\.atomic$//o;
748 my $m = $self->method_lookup($m_name);
750 $m->session( $req->session );
751 my @results = $m->run(@args);