| 1 | package PAGI::App::Cascade; | ||
| 2 | $PAGI::App::Cascade::VERSION = '0.002001'; | ||
| 3 | use strict; | ||
| 4 | use warnings; | ||
| 5 | use Future::AsyncAwait; | ||
| 6 | use PAGI::Utils (); | ||
| 7 | |||
| 8 | =head1 NAME | ||
| 9 | |||
| 10 | PAGI::App::Cascade - Try apps in sequence until success | ||
| 11 | |||
| 12 | =head1 SYNOPSIS | ||
| 13 | |||
| 14 | use PAGI::App::Cascade; | ||
| 15 | |||
| 16 | my $app = PAGI::App::Cascade->new( | ||
| 17 | apps => [$static_app, PAGI::App::NotFound->new(body => 'nope')], | ||
| 18 | catch => [404, 405], | ||
| 19 | )->to_app; | ||
| 20 | |||
| 21 | =cut | ||
| 22 | |||
| 23 | sub new { | ||
| 24 | my ($class, %args) = @_; | ||
| 25 | |||
| 26 | return bless { | ||
| 27 | apps => [map { PAGI::Utils::to_app($_) } @{$args{apps} // []}], | ||
| 28 | catch => { map { $_ => 1 } @{$args{catch} // [404, 405]} }, | ||
| 29 | }, $class; | ||
| 30 | } | ||
| 31 | |||
| 32 | sub add { | ||
| 33 | my ($self, $app) = @_; | ||
| 34 | |||
| 35 | push @{$self->{apps}}, PAGI::Utils::to_app($app); | ||
| 36 | return $self; | ||
| 37 | } | ||
| 38 | |||
| 39 | sub to_app { | ||
| 40 | my ($self) = @_; | ||
| 41 | |||
| 42 | my @apps = @{$self->{apps}}; | ||
| 43 | my %catch = %{$self->{catch}}; | ||
| 44 | |||
| 45 | return async sub { | ||
| 46 | my ($scope, $receive, $send) = @_; | ||
| 47 | for my $i (0 .. $#apps) { | ||
| 48 | my $app = $apps[$i]; | ||
| 49 | my $is_last = ($i == $#apps); | ||
| 50 | |||
| 51 | # For non-last apps, we need to capture the response | ||
| 52 | if (!$is_last) { | ||
| 53 | my @captured_events; | ||
| 54 | my $captured_status; | ||
| 55 | |||
| 56 | my $capture_send = async sub { | ||
| 57 | my ($event) = @_; | ||
| 58 | push @captured_events, $event; | ||
| 59 | if ($event->{type} eq 'http.response.start') { | ||
| 60 | $captured_status = $event->{status}; | ||
| 61 | } | ||
| 62 | }; | ||
| 63 | |||
| 64 | await $app->($scope, $receive, $capture_send); | ||
| 65 | |||
| 66 | # Check if we should try next app | ||
| 67 | if ($captured_status && $catch{$captured_status}) { | ||
| 68 | next; # Try next app | ||
| 69 | } | ||
| 70 | |||
| 71 | # Send captured events | ||
| 72 | for my $event (@captured_events) { | ||
| 73 | await $send->($event); | ||
| 74 | } | ||
| 75 | return; | ||
| 76 | } | ||
| 77 | |||
| 78 | # Last app - send directly | ||
| 79 | await $app->($scope, $receive, $send); | ||
| 80 | return; | ||
| 81 | } | ||
| 82 | }; | ||
| 83 | } | ||
| 84 | |||
| 85 | 1; | ||
| 86 | |||
| 87 | __END__ |