« blib/lib/WebDyne/Cloudflare/Hyperdrive/Error.pm
↑ Summary
blib/lib/WebDyne/Cloudflare/R2/Error.pm »
| 1 | package WebDyne::Cloudflare::DurableObject::Handler; | ||
| 2 | |||
| 3 | use 5.020; | ||
| 4 | use strict; | ||
| 5 | use warnings; | ||
| 6 | use Future::AsyncAwait; | ||
| 7 | use Scalar::Util qw(blessed); | ||
| 8 | use WebDyne::Cloudflare::DurableObject; | ||
| 9 | use WebDyne::Cloudflare::DurableObject::Context; | ||
| 10 | our $VERSION='0.001'; | ||
| 11 | |||
| 12 | # The hosting wrapper supplies the package and an allowlisted method. Each | ||
| 13 | # finite event has a fresh context and yields exactly one structured result. | ||
| 14 | # | ||
| 15 | async sub application { | ||
| 16 | my ($scope_hr, $receive_cr, $send_cr)=@_; | ||
| 17 | my $response_hr; | ||
| 18 | my $ok=eval { | ||
| 19 | my $package=$scope_hr->{'package'}; | ||
| 20 | my $method=$scope_hr->{'method'}; | ||
| 21 | die "Invalid handler package or method\n" | ||
| 22 | unless (defined($package)&&($package=~/\A[A-Za-z_]\w*(?:::[A-Za-z_]\w*)*\z/) | ||
| 23 | &&defined($method)&&($method=~/\A[A-Za-z]\w*\z/)); | ||
| 24 | my $module_fn=$package; | ||
| 25 | $module_fn=~s{::}{/}g; | ||
| 26 | require "$module_fn.pm"; | ||
| 27 | my $handler_cr=$package->can($method) or die "Handler $package\::$method is not defined\n"; | ||
| 28 | my $context_or=WebDyne::Cloudflare::DurableObject::Context->new($scope_hr); | ||
| 29 | my $args_ar=WebDyne::Cloudflare::DurableObject::decode_value($scope_hr->{'args'}); | ||
| 30 | die "Handler arguments must be an array\n" unless (ref($args_ar) eq 'ARRAY'); | ||
| 31 | my $result_ref=$handler_cr->($context_or, @{$args_ar}); | ||
| 32 | $result_ref=await $result_ref if (blessed($result_ref)&&$result_ref->isa('Future')); | ||
| 33 | $response_hr={ok => JSON::PP::true, result => WebDyne::Cloudflare::DurableObject::encode_value($result_ref)}; | ||
| 34 | 1; | ||
| 35 | }; | ||
| 36 | unless ($ok) { | ||
| 37 | my $error_ref=$@; | ||
| 38 | my %error=(name => 'DURABLE_OBJECT_ERROR', message => substr("$error_ref", 0, 4096)); | ||
| 39 | if (blessed($error_ref)&&$error_ref->isa('WebDyne::Cloudflare::DurableObject::Error')) { | ||
| 40 | $error{'name'}=substr($error_ref->name(), 0, 128); | ||
| 41 | $error{'message'}=substr($error_ref->message(), 0, 4096); | ||
| 42 | $error{'code'}=substr($error_ref->code(), 0, 128) if defined($error_ref->code()); | ||
| 43 | } | ||
| 44 | $response_hr={ok => JSON::PP::false, error => \%error}; | ||
| 45 | } | ||
| 46 | await $send_cr->({type => 'invocation.result', value => $response_hr}); | ||
| 47 | return; | ||
| 48 | } | ||
| 49 | |||
| 50 | 1; |