« lib/Beekeeper/Service/Sinkhole/Worker.pm
↑ Summary
blib/lib/auto/share/dist/Beekeeper/scraper/lib/MyApp/Service/Scraper/Worker.pm »
| 1 | package MyApp::Service::Calculator::Worker; | ||
| 2 | |||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | |||
| 6 | use Beekeeper::Worker ':log'; | ||
| 7 | use base 'Beekeeper::Worker'; | ||
| 8 | |||
| 9 | |||
| 10 | sub authorize_request { | ||
| 11 | my ($self, $req) = @_; | ||
| 12 | |||
| 13 | return BKPR_REQUEST_AUTHORIZED; | ||
| 14 | } | ||
| 15 | |||
| 16 | sub on_startup { | ||
| 17 | my $self = shift; | ||
| 18 | |||
| 19 | $self->accept_remote_calls( | ||
| 20 | 'myapp.calculator.eval_expr' => 'eval_expr', | ||
| 21 | ); | ||
| 22 | |||
| 23 | log_info "Ready"; | ||
| 24 | } | ||
| 25 | |||
| 26 | sub on_shutdown { | ||
| 27 | my $self = shift; | ||
| 28 | |||
| 29 | log_info "Stopped"; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub eval_expr { | ||
| 33 | my ($self, $params) = @_; | ||
| 34 | |||
| 35 | my $expr = $params->{"expr"}; | ||
| 36 | |||
| 37 | unless (defined $expr) { | ||
| 38 | # Explicit error response. It will be not logged | ||
| 39 | return Beekeeper::JSONRPC->error( message => 'No expression given' ); | ||
| 40 | } | ||
| 41 | |||
| 42 | ($expr) = $expr =~ m/^([ \d \. \+\-\*\/ ]*)$/x; | ||
| 43 | |||
| 44 | unless (defined $expr) { | ||
| 45 | # Throw a handled exception. It will be not logged | ||
| 46 | die Beekeeper::JSONRPC->error( message => 'Invalid expression' ); | ||
| 47 | } | ||
| 48 | |||
| 49 | my $result = eval $expr; | ||
| 50 | |||
| 51 | if ($@) { | ||
| 52 | # Throw an unhandled exception which will be automatically logged | ||
| 53 | # The client will receive a generic error response (try division by zero) | ||
| 54 | die "Died while processing '$expr': $@"; | ||
| 55 | } | ||
| 56 | |||
| 57 | return $result; | ||
| 58 | } | ||
| 59 | |||
| 60 | 1; |