| 1 | package PAGI::App::Loader; | ||
| 2 | $PAGI::App::Loader::VERSION = '0.002000'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Future::AsyncAwait; | ||
| 6 | |||
| 7 | =head1 NAME | ||
| 8 | |||
| 9 | PAGI::App::Loader - Load PAGI app from file | ||
| 10 | |||
| 11 | =head1 SYNOPSIS | ||
| 12 | |||
| 13 | use PAGI::App::Loader; | ||
| 14 | |||
| 15 | my $app = PAGI::App::Loader->new( | ||
| 16 | file => 'app.pl', | ||
| 17 | )->to_app; | ||
| 18 | |||
| 19 | =cut | ||
| 20 | |||
| 21 | sub new { | ||
| 22 | my ($class, %args) = @_; | ||
| 23 | |||
| 24 | return bless { | ||
| 25 | file => $args{file}, | ||
| 26 | reload => $args{reload} // 0, | ||
| 27 | _app => undef, | ||
| 28 | _mtime => 0, | ||
| 29 | }, $class; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub to_app { | ||
| 33 | my ($self) = @_; | ||
| 34 | |||
| 35 | return async sub { | ||
| 36 | my ($scope, $receive, $send) = @_; | ||
| 37 | my $app = $self->_get_app(); | ||
| 38 | |||
| 39 | unless ($app) { | ||
| 40 | await $send->({ | ||
| 41 | type => 'http.response.start', | ||
| 42 | status => 500, | ||
| 43 | headers => [['content-type', 'text/plain']], | ||
| 44 | }); | ||
| 45 | await $send->({ type => 'http.response.body', body => 'App failed to load', more => 0 }); | ||
| 46 | return; | ||
| 47 | } | ||
| 48 | |||
| 49 | await $app->($scope, $receive, $send); | ||
| 50 | }; | ||
| 51 | } | ||
| 52 | |||
| 53 | sub _get_app { | ||
| 54 | my ($self) = @_; | ||
| 55 | |||
| 56 | my $file = $self->{file}; | ||
| 57 | |||
| 58 | # Check if reload needed | ||
| 59 | if ($self->{reload} && $self->{_app}) { | ||
| 60 | my @stat = stat($file); | ||
| 61 | if (@stat && $stat[9] > $self->{_mtime}) { | ||
| 62 | $self->{_app} = undef; | ||
| 63 | } | ||
| 64 | } | ||
| 65 | |||
| 66 | return $self->{_app} if $self->{_app}; | ||
| 67 | |||
| 68 | # Load app | ||
| 69 | my @stat = stat($file); | ||
| 70 | $self->{_mtime} = $stat[9] if @stat; | ||
| 71 | |||
| 72 | my $app = do $file; | ||
| 73 | if ($@) { | ||
| 74 | warn "Error loading $file: $@\n"; | ||
| 75 | return; | ||
| 76 | } | ||
| 77 | unless ($app) { | ||
| 78 | warn "Error loading $file: $!\n" if $!; | ||
| 79 | warn "$file did not return a coderef\n" unless $app; | ||
| 80 | return; | ||
| 81 | } | ||
| 82 | unless (ref $app eq 'CODE') { | ||
| 83 | warn "$file did not return a coderef\n"; | ||
| 84 | return; | ||
| 85 | } | ||
| 86 | |||
| 87 | $self->{_app} = $app; | ||
| 88 | return $app; | ||
| 89 | } | ||
| 90 | |||
| 91 | 1; | ||
| 92 | |||
| 93 | __END__ |