FastAPI.pm

filter: Statementstmt 90.8% 419 / 461 Branchbran 70.4% 124 / 176 Conditioncond 55.2% 79 / 143 MC/DCmcdc 30.3% 24 / 79 Subroutinesub 87.0% 47 / 54 Podpod 100% 18 / 18 totaltotal 76.3% 711 / 931 CC 168 SCAR 33.7
CC
168
Cov
80%
__ANON__
60.8
_register_route
42.7
_parse_multipart_form_data
31.1
CRAP 29.2
↑ Summary FastAPI/BotProtection/ProofOfWork.pm »
1 package PAGI::FastAPI;
2  
3 21 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 21 ▶use experimental qw/class try for_list/;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 21 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 21 our $VERSION = qv('v1.7.1');
8 21 our $AUTHORITY = 'cpan:MANWAR';
9  
10 21 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 21 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 21 ▶use JSON::PP qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 21 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
14 21 ▶use PAGI::App::URLMap;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 21 ▶use PAGI::Context;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 21 ▶use PAGI::WebSocket;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 21 ▶use PAGI::Middleware::CORS;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 21 ▶use PAGI::FastAPI::Context;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 21 ▶use PAGI::FastAPI::Depends qw(Depends);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 21 ▶use PAGI::FastAPI::Middleware::RateLimit;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 21 class PAGI::FastAPI {
23 21 field $title :param = 'PAGI::FastAPI Application';
24 21 field $version :param = "$VERSION";
25 21 field $secret :param = undef;
26 21 field $routes = [];
27 21 field $middlewares = [];
28 21 field $pagi_middlewares = [];
29 21 field $mounts = [];
30 21 field $cors_options = undef;
31 21 field $event_handlers = undef;
32 21 field $openapi = undef;
33 21 field $background_futures = [];
34 21 field $swagger_ui_css_url :param = 'https://unpkg.com/swagger-ui-dist@5/swagger-ui.css';
35 21 field $swagger_ui_bundle_url :param = 'https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js';
36 21 field $swagger_ui_parameters :param = { operationsSorter => 'method', tagsSorter => 'alpha', };
37  
38 ADJUST {
39 36 ▶ $event_handlers = {
Subroutine __ANON__: called CC=1 SCAR=0.0
40 startup => [],
41 shutdown => [],
42 };
43 36 $openapi = {
44 openapi => '3.1.0',
45 info => {
46 title => $title,
47 version => $version,
48 },
49 paths => {},
50 };
51 }
52  
53 ▶ method mount ($path, $app) {
Subroutine mount: not called CC=3 SCAR=24.8
Pod documented
54 0 ▶ $path = "/$path" unless $path =~ m{^/};
Branch: 1 branch
BranchTrueFalseTotal
unless $path =~ m[^/]u 0 0 0
55 0 ▶ $path =~ s{/$}{} unless $path eq '/';
Branch: 1 branch
BranchTrueFalseTotal
unless $path eq "/" 0 0 0
56  
57 0 push @$mounts, {
58 prefix => $path,
59 app => $app,
60 };
61  
62 0 return $self;
63 21 }
64  
65 35 ▶ method get ($path, %opts) { $self->_register_route('GET', $path, \%opts) }
Subroutine get: called CC=1 SCAR=0.0
Pod documented
66 11 ▶ method post ($path, %opts) { $self->_register_route('POST', $path, \%opts) }
Subroutine post: called CC=1 SCAR=0.0
Pod documented
67 0 ▶ method put ($path, %opts) { $self->_register_route('PUT', $path, \%opts) }
Subroutine put: not called CC=1 SCAR=1.2
Pod documented
68 0 ▶ method patch ($path, %opts) { $self->_register_route('PATCH', $path, \%opts) }
Subroutine patch: not called CC=1 SCAR=1.2
Pod documented
69 0 ▶ method delete ($path, %opts) { $self->_register_route('DELETE', $path, \%opts) }
Subroutine delete: not called CC=1 SCAR=1.2
Pod documented
70  
71 ▶ method on_event ($event_type, $code) {
Subroutine on_event: called CC=3 SCAR=11.4
Pod documented
72 6 ▶ die "Event type must be 'startup' or 'shutdown'"
Branch: 1 branch
BranchTrueFalseTotal
unless $event_type =~ /^(?:startup|shutdown)$/u 0 6 6
73 unless $event_type =~ /^(?:startup|shutdown)$/;
74 6 ▶ die "Event handler must be a CODE reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 0 6 6
75 unless ref $code eq 'CODE';
76 6 push @{$event_handlers->{$event_type}}, $code;
77 21 }
78  
79 4 ▶ method on_startup ($code) { $self->on_event('startup', $code) }
Subroutine on_startup: called CC=1 SCAR=0.0
Pod documented
80 2 ▶ method on_shutdown ($code) { $self->on_event('shutdown', $code) }
Subroutine on_shutdown: called CC=1 SCAR=0.0
Pod documented
81  
82 ▶ method add_middleware ($mw, %opts) {
Subroutine add_middleware: called CC=7 SCAR=20.8
Pod documented
83 12 ▶ if (!ref $mw) {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $mw) 3 9 12
84 3 ▶ eval "require $mw;" or die $@;
Branch: 1 branch
BranchTrueFalseTotal
eval "require $mw;" or die $@ 0 3 3
85 3 $mw = $mw->new(%opts);
86 }
87  
88 12 ▶ if (blessed($mw) && ($mw->can('wrap') || $mw->can('to_app') || $mw->can('call'))) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($mw) and $mw->can('wrap') || $mw->can('to_app') || $mw->can('call')) { } 7 5 12
Condition44%4/9
builtin::blessed($mw) and $mw->can("wrap") || $mw->can("to_app") || $mw->can("call")
!ll&&!rl&&r
507
$mw->can("wrap") or $mw->can("to_app") or $mw->can("call")
l!l&&r!l&&!r
700
$mw->can("wrap") or $mw->can("to_app")
l!l&&r!l&&!r
700
MC/DC25%1/4
builtin::blessed($mw) and $mw->can("wrap") || $mw->can("to_app") || $mw->can("call")
builtin::blessed($mw) $mw->can("wrap") $mw->can("to_app") $mw->can("call")
Truth table40%2/5
A and B or C or D
A= builtin::blessed($mw)B= $mw->can("wrap")C= $mw->can("to_app")D= $mw->can("call")
ABCDresult
0XXX0
10000
11XX1
101X1
10011
89 7 push @$pagi_middlewares, $mw;
90 }
91 else {
92 5 push @$middlewares, $mw;
93 }
94  
95 12 return $self;
96 21 }
97  
98 ▶ method enable_csrf (%opts) {
Subroutine enable_csrf: called CC=3 SCAR=11.0
Pod documented
99 4 require PAGI::Middleware::CSRF;
100 4 ▶ my $csrf_secret = delete $opts{secret} // $secret
Condition100%5/5
(delete $opts{"secret"} // $secret) // die("CSRF middleware requires 'secret' option")
l!l
31
delete $opts{"secret"} // $secret
l!l&&r!l&&!r
211
MC/DC100%2/2
(delete $opts{"secret"} // $secret) // die("CSRF middleware requires 'secret' option")
delete $opts{"secret"} $secret
Truth table100%3/3
A // B
A= delete $opts{"secret"}B= $secret
ABresult
1X1
011
000
101 // die "CSRF middleware requires 'secret' option";
102  
103 3 my $mw = PAGI::Middleware::CSRF->new(
104 secret => $csrf_secret,
105 enforce => 'header',
106 secure => 0,
107 %opts,
108 );
109  
110 3 return $self->add_middleware($mw);
111 21 }
112  
113 ▶ method add_cors (%opts) {
Subroutine add_cors: called CC=1 SCAR=0.0
Pod documented
114 1 $cors_options = \%opts;
115 21 }
116  
117 ▶ method websocket ($path, %args) {
Subroutine websocket: called CC=3 SCAR=11.2
Pod documented
118 2 my $handler = delete $args{handler};
119 2 ▶ my $deps = delete $args{dependencies} // [];
Condition50%1/2
delete $args{"dependencies"} // []
l!l
02
MC/DC0%0/1
delete $args{"dependencies"} // []
delete $args{"dependencies"}
Truth table50%1/2
A
A= delete $args{"dependencies"}
Aresult
11
00
120  
121 2 ▶ die "Route 'WEBSOCKET $path' requires a 'handler' async coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $handler eq "CODE" 0 2 2
122 unless ref $handler eq 'CODE';
123  
124 2 my %opts = (
125 dependencies => $deps,
126 handler => $handler,
127 %args,
128 );
129  
130 2 $self->_register_route('WEBSOCKET', $path, \%opts);
131  
132 2 return $self;
133 21 }
134  
135 ▶ method add_rate_limit (%opts) {
Subroutine add_rate_limit: called CC=1 SCAR=0.0
Pod documented
136 1 my $limiter = PAGI::FastAPI::Middleware::RateLimit->new(%opts);
137 5 ▶ $self->add_middleware(async sub ($c, $next) {
Subroutine __ANON__: called CC=1 SCAR=0.0
138 5 return await $limiter->handle($c, $next);
139 1 });
140 1 return $self;
141 21 }
142  
143 ▶ method add_bot_protection (%opts) {
Subroutine add_bot_protection: not called CC=1 SCAR=2.6
Pod documented
144 21 ▶ use PAGI::FastAPI::Middleware::BotProtection;
Subroutine BEGIN: called CC=1 SCAR=0.0
145 0 my $guard = PAGI::FastAPI::Middleware::BotProtection->new(%opts);
146  
147 0 ▶ $self->add_middleware(async sub ($c, $next) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
148 0 return await $guard->handle($c, $next);
149 0 });
150  
151 0 return $self;
152 21 }
153  
154 ▶ method sse ($generator, %opts) {
Subroutine sse: not called CC=3 SCAR=16.5
Pod documented
155 21 ▶ use PAGI::FastAPI::Response::SSE;
Subroutine BEGIN: called CC=1 SCAR=0.0
156 return PAGI::FastAPI::Response::SSE->new(
157 generator => $generator,
158 headers => $opts{headers} // [],
159 0 ▶ status => $opts{status} // 200,
Condition0%0/4
$opts{"headers"} // []
l!l
00
$opts{"status"} // 200
l!l
00
MC/DC0%0/1
$opts{"headers"} // []
$opts{"headers"}
MC/DC0%0/1
$opts{"status"} // 200
$opts{"status"}
Truth table0%0/2
A
A= $opts{"headers"}
Aresult
11
00
Truth table0%0/2
A
A= $opts{"status"}
Aresult
11
00
160 );
161 21 }
162  
163 ▶ method to_pagi () {
Subroutine to_pagi: called CC=1 SCAR=0.0
Pod documented
164 # Delegate directly to to_app to ensure identical pipeline execution
165 # and eliminate double-wrapping.
166 5 return $self->to_app();
167 21 }
168  
169 method to_app {
170 39 ▶ my $fastapi_app = $self->_build_pagi_app;
Subroutine to_app: called CC=10 SCAR=33.2
Pod documented
171  
172 39 my $final_app = $fastapi_app;
173  
174 39 ▶ if (@$mounts) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$mounts) 0 39 39
175 0 my $urlmap = PAGI::App::URLMap->new;
176  
177 0 for my $m (@$mounts) {
178 0 $urlmap->mount($m->{prefix} => $m->{app});
179 }
180  
181 0 $urlmap->mount('/' => $fastapi_app);
182  
183 0 $final_app = $urlmap->to_app;
184 }
185  
186 39 ▶ if ($cors_options) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cors_options) 2 37 39
187 2 $final_app = PAGI::Middleware::CORS->new(%$cors_options)
188 ->wrap($final_app);
189 }
190  
191 # Wrap PAGI middleware objects in reverse (LIFO order)
192 # Outermost layer wrapping around mounts and CORS
193 39 for my $mw (reverse @$pagi_middlewares) {
194 10 ▶ if (blessed($mw) && $mw->can('wrap')) {
Branch: 3 branches
BranchTrueFalseTotal
if (builtin::blessed($mw) and $mw->can('wrap')) { } 10 0 10
elsif (builtin::blessed($mw) and $mw->can('to_app')) { } 0 0 0
elsif (ref $mw eq 'CODE') { } 0 0 0
Condition33%1/3
builtin::blessed($mw) and $mw->can("wrap")
!ll&&!rl&&r
0010
MC/DC0%0/2
builtin::blessed($mw) and $mw->can("wrap")
builtin::blessed($mw) $mw->can("wrap")
Truth table33%1/3
A and B
A= builtin::blessed($mw)B= $mw->can("wrap")
ABresult
0X0
100
111
195 10 $final_app = $mw->wrap($final_app);
196 }
197 ▶ elsif (blessed($mw) && $mw->can('to_app')) {
Condition0%0/3
builtin::blessed($mw) and $mw->can("to_app")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($mw) and $mw->can("to_app")
builtin::blessed($mw) $mw->can("to_app")
Truth table0%0/3
A and B
A= builtin::blessed($mw)B= $mw->can("to_app")
ABresult
0X0
100
111
198 0 $final_app = $mw->to_app($final_app);
199 }
200 elsif (ref $mw eq 'CODE') {
201 0 $final_app = $mw->($final_app);
202 }
203 }
204  
205 39 return $final_app;
206 21 }
207  
208 method _build_pagi_app {
209 80 ▶ return async sub ($scope, $receive, $send) {
Subroutine __ANON__: called CC=48 SCAR=41.1
210 80 ▶ if ($scope->{type} eq 'websocket') {
Branch: 2 branches
BranchTrueFalseTotal
if ($scope->{'type'} eq 'websocket') { } 3 77 80
elsif ($scope->{'type'} eq 'lifespan') { } 5 72 77
211 3 return await $self->_handle_websocket($scope, $receive, $send);
212 } elsif ($scope->{type} eq 'lifespan') {
213 5 while (1) {
214 9 my $event = await $receive->();
215 9 ▶ if ($event->{type} eq 'lifespan.startup') {
Branch: 2 branches
BranchTrueFalseTotal
if ($event->{'type'} eq 'lifespan.startup') { } 5 4 9
elsif ($event->{'type'} eq 'lifespan.shutdown') { } 4 0 4
216 5 try {
217 5 for my $cb (@{$event_handlers->{startup}}) {
218 5 await $cb->();
219 }
220 4 await $send->({ type => 'lifespan.startup.complete' });
221 }
222 catch ($err) {
223 1 await $send->({ type => 'lifespan.startup.failed', message => "$err" });
224 1 return;
225 }
226 }
227 elsif ($event->{type} eq 'lifespan.shutdown') {
228 4 try {
229 4 ▶ if (@$background_futures) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$background_futures) 0 4 4
230 0 my @pending = @$background_futures;
231 0 await Future->wait_all(@pending);
232 }
233 4 for my $cb (@{$event_handlers->{shutdown}}) {
234 3 await $cb->();
235 }
236 4 await $send->({ type => 'lifespan.shutdown.complete' });
237 }
238 catch ($err) {
239 0 await $send->({ type => 'lifespan.shutdown.failed', message => "$err" });
240 }
241 4 last;
242 }
243 }
244 4 return;
245 }
246  
247 72 ▶ die "Unsupported type: $scope->{type}" unless $scope->{type} =~ /^(?:http|sse|websocket)$/;
Branch: 1 branch
BranchTrueFalseTotal
unless $scope->{"type"} =~ /^(?:http|sse|websocket)$/u 0 72 72
248  
249 72 ▶ my $path = $scope->{path} // '/';
Condition50%1/2
$scope->{"path"} // "/"
l!l
720
MC/DC0%0/1
$scope->{"path"} // "/"
$scope->{"path"}
Truth table50%1/2
A
A= $scope->{"path"}
Aresult
11
00
250 72 ▶ my $method = uc($scope->{method} // 'GET');
Condition50%1/2
$scope->{"method"} // "GET"
l!l
720
MC/DC0%0/1
$scope->{"method"} // "GET"
$scope->{"method"}
Truth table50%1/2
A
A= $scope->{"method"}
Aresult
11
00
251  
252 72 ▶ if ($path eq '/docs') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/docs") 1 71 72
253 1 await $send->({ type => 'http.response.start', status => 200, headers => [['content-type', 'text/html; charset=utf-8']] });
254 1 await $send->({ type => 'http.response.body', body => $self->_swagger_ui_html });
255 1 return;
256 }
257  
258 71 ▶ if ($path eq '/openapi.json') {
Branch: 1 branch
BranchTrueFalseTotal
if ($path eq "/openapi.json") 6 65 71
259 6 await $send->({ type => 'http.response.start', status => 200, headers => [['content-type', 'application/json']] });
260 6 await $send->({ type => 'http.response.body', body => encode_json($openapi) });
261 6 return;
262 }
263  
264 65 my %query_params;
265 65 ▶ if (defined $scope->{query_string} && length $scope->{query_string}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $scope->{"query_string"} and length $scope->{"query_string"}) 3 62 65
Condition100%3/3
defined $scope->{"query_string"} and length $scope->{"query_string"}
!ll&&!rl&&r
35273
MC/DC100%2/2
defined $scope->{"query_string"} and length $scope->{"query_string"}
defined $scope->{"query_string"} length $scope->{"query_string"}
Truth table100%3/3
A and B
A= defined $scope->{"query_string"}B= length $scope->{"query_string"}
ABresult
0X0
100
111
266 3 for my $pair (split '&', $scope->{query_string}) {
267 3 my ($k, $v) = split '=', $pair, 2;
268 3 ▶ $query_params{_uri_unescape($k)} = _uri_unescape($v // '');
Condition50%1/2
$v // ""
l!l
30
MC/DC0%0/1
$v // ""
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
269 }
270 }
271  
272 65 my $body_data;
273 my $form_data;
274 65 my $uploaded_files = {};
275  
276 65 ▶ if ($method eq 'POST' || $method eq 'PUT' || $method eq 'PATCH') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method eq "POST" or $method eq "PUT" or $method eq "PATCH") 0 45 45
Condition66%4/6
$method eq "POST" or $method eq "PUT" or $method eq "PATCH"
l!l&&r!l&&!r
20045
$method eq "POST" or $method eq "PUT"
l!l&&r!l&&!r
20045
MC/DC33%1/3
$method eq "POST" or $method eq "PUT" or $method eq "PATCH"
$method eq "POST" $method eq "PUT" $method eq "PATCH"
Truth table50%2/4
A or B or C
A= $method eq "POST"B= $method eq "PUT"C= $method eq "PATCH"
ABCresult
1XX1
01X1
0011
0000
277 20 my $raw_body = '';
278 20 while (1) {
279 20 my $event = await $receive->();
280 20 ▶ if ($event->{type} eq 'http.request') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->{'type'} eq 'http.request') { } 19 1 20
281 19 ▶ $raw_body .= $event->{body} // '';
Condition100%2/2
$event->{"body"} // ""
l!l
181
MC/DC100%1/1
$event->{"body"} // ""
$event->{"body"}
Truth table100%2/2
A
A= $event->{"body"}
Aresult
11
00
282 19 ▶ last unless $event->{more_body};
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"more_body"} 19 0 19
283 }
284 else {
285 1 last;
286 }
287 }
288  
289 20 ▶ if (length $raw_body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $raw_body) 15 5 20
290 15 my $content_type = '';
291 15 ▶ for my $h (@{ $scope->{headers} // [] }) {
Condition100%2/2
$scope->{"headers"} // []
l!l
114
MC/DC100%1/1
$scope->{"headers"} // []
$scope->{"headers"}
Truth table100%2/2
A
A= $scope->{"headers"}
Aresult
11
00
292 10 ▶ if (lc($h->[0]) eq 'content-type') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-type") 10 0 10
293 10 ▶ $content_type = $h->[1] // '';
Condition50%1/2
$h->[1] // ""
l!l
100
MC/DC0%0/1
$h->[1] // ""
$h->[1]
Truth table50%1/2
A
A= $h->[1]
Aresult
11
00
294 10 last;
295 }
296 }
297 15 my $content_type_lc = lc($content_type);
298  
299 15 ▶ if (index($content_type_lc, 'application/x-www-form-urlencoded') == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if (index($content_type_lc, 'application/x-www-form-urlencoded') == 0) { } 3 12 15
elsif (index($content_type_lc, 'multipart/form-data') == 0) { } 4 8 12
300 3 my %form;
301 3 for my $pair (split '&', $raw_body) {
302 5 my ($k, $v) = split '=', $pair, 2;
303 5 ▶ next unless defined $k && length $k;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $k and length $k 0 5 5
Condition33%1/3
defined $k and length $k
!ll&&!rl&&r
005
MC/DC0%0/2
defined $k and length $k
defined $k length $k
Truth table33%1/3
A and B
A= defined $kB= length $k
ABresult
0X0
100
111
304 5 ▶ $form{_uri_unescape($k)} = _uri_unescape($v // '');
Condition50%1/2
$v // ""
l!l
50
MC/DC0%0/1
$v // ""
$v
Truth table50%1/2
A
A= $v
Aresult
11
00
305 }
306 3 $body_data = \%form;
307 3 $form_data = \%form;
308 }
309 elsif (index($content_type_lc, 'multipart/form-data') == 0) {
310 4 my ($b1, $b2) = $content_type =~ /boundary=(?:"([^"]+)"|([^;\s]+))/i;
311 4 ▶ my $boundary = $b1 // $b2 // '';
Condition60%3/5
($b1 // $b2) // ""
l!l
40
$b1 // $b2
l!l&&r!l&&!r
130
MC/DC0%0/2
($b1 // $b2) // ""
$b1 $b2
Truth table66%2/3
A // B
A= $b1B= $b2
ABresult
1X1
011
000
312 4 my ($fields, $files) = _parse_multipart_form_data($raw_body, $boundary);
313 4 $body_data = $fields;
314 4 $form_data = $fields;
315 4 $uploaded_files = $files;
316 }
317 else {
318 8 try {
319 8 $body_data = decode_json($raw_body);
320 }
321 catch ($err) {
322 2 await $send->({ type => 'http.response.start', status => 422, headers => [['content-type', 'application/json']] });
323 2 await $send->({ type => 'http.response.body', body => encode_json({ detail => 'Invalid JSON body payload' }) });
324 2 return;
325 }
326 }
327 }
328 }
329  
330 63 my $pagi_context = PAGI::Context->new($scope, $receive, $send);
331 ▶ my $ctx = PAGI::FastAPI::Context->new(
Subroutine __ANON__: called CC=1 SCAR=0.0
332 query_params => \%query_params,
333 body => $body_data,
334 form_data => $form_data,
335 uploaded_files => $uploaded_files,
336 scope => $scope,
337 pagi_context => $pagi_context,
338 3 background_registrar => sub ($future) { $self->_retain_background($future) },
339 63 );
340  
341 61 ▶ my $dispatcher = async sub ($c) {
Subroutine __ANON__: called CC=23 SCAR=31.9
342 61 for my $route (@$routes) {
343 83 ▶ next unless $route->{method} eq $method;
Branch: 1 branch
BranchTrueFalseTotal
unless $route->{"method"} eq $method 3 80 83
344  
345 80 ▶ if (my @captures = ($path =~ $route->{regex})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@captures) = $path =~ /$route->{"regex"}/u) 59 21 80
346 59 my %path_params;
347 my %query_params_validated;
348  
349 59 for my $i (0 .. $#{$route->{path_params}}) {
350 6 $path_params{$route->{path_params}[$i]} = _uri_unescape($captures[$i]);
351 }
352  
353 # Store extracted path parameters via Context's constructor state
354 59 my $p_params = $c->path_params;
355 59 %$p_params = %path_params;
356  
357 59 for my ($param, $type) (%{$route->{query_types}}) {
358 3 my $val = $query_params{$param};
359 3 ▶ if (my $err = $type->validate($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $type->validate($val)) 1 2 3
360 1 $c->status(422);
361 1 return { detail => "Query param '$param' invalid: $err" };
362 }
363 2 ▶ my $t_name = eval { $type->name } // '';
Condition50%1/2
eval { do { $type->name } } // ""
l!l
20
MC/DC0%0/1
eval { do { $type->name } } // ""
eval { do { $type->name } }
Truth table50%1/2
A
A= eval { do { $type->name } }
Aresult
11
00
364 2 ▶ $query_params_validated{$param} = $type->has_coercion ? $type->coerce($val) : (($t_name eq 'Int') ? $val + 0 : $val);
Branch: 2 branches
BranchTrueFalseTotal
$type->has_coercion ? : 0 2 2
$t_name eq 'Int' ? : 1 1 2
365 }
366  
367 58 my $q_params = $c->query_params;
368 58 %$q_params = %query_params_validated;
369  
370 58 ▶ if (defined $route->{body_spec}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $route->{"body_spec"}) 8 50 58
371 8 my $spec = $route->{body_spec};
372  
373 8 ▶ if (blessed($spec) && $spec->can('validate')) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($spec) and $spec->can('validate')) { } 1 7 8
elsif (ref $spec eq 'HASH') { } 7 0 7
Condition66%2/3
builtin::blessed($spec) and $spec->can("validate")
!ll&&!rl&&r
701
MC/DC50%1/2
builtin::blessed($spec) and $spec->can("validate")
builtin::blessed($spec) $spec->can("validate")
Truth table66%2/3
A and B
A= builtin::blessed($spec)B= $spec->can("validate")
ABresult
0X0
100
111
374 1 ▶ if (my $err = $spec->validate($c->body)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $spec->validate($c->body)) 0 1 1
375 0 $c->status(422);
376 0 return { detail => "Body validation failed: $err" };
377 }
378 }
379 elsif (ref $spec eq 'HASH') {
380 7 ▶ unless (ref $c->body eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
unless (ref $c->body eq "HASH") 0 7 7
381 0 $c->status(422);
382 0 return { detail => 'Expected a JSON object in request body' };
383 }
384  
385 7 for my ($field, $type) (%$spec) {
386 12 my $val = $c->body($field);
387 12 ▶ if (my $err = $type->validate($val)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $type->validate($val)) 2 10 12
388 2 $c->status(422);
389 2 return { detail => "Body field '$field' invalid: $err" };
390 }
391 }
392 }
393 }
394  
395 56 for my $dep (@{$route->{dependencies}}) {
396 9 my $dep_res = await $dep->{code}->($c);
397  
398 9 ▶ if ($c->status >= 400) {
Branch: 1 branch
BranchTrueFalseTotal
if ($c->status >= 400) 2 7 9
399 2 ▶ return $dep_res // { detail => 'Dependency execution failed' };
Condition50%1/2
$dep_res // {"detail", "Dependency execution failed"}
l!l
20
MC/DC0%0/1
$dep_res // {"detail", "Dependency execution failed"}
$dep_res
Truth table50%1/2
A
A= $dep_res
Aresult
11
00
400 }
401  
402 7 ▶ if (defined $dep->{key} && defined $dep_res) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dep->{"key"} and defined $dep_res) 5 2 7
Condition100%3/3
defined $dep->{"key"} and defined $dep_res
!ll&&!rl&&r
115
MC/DC100%2/2
defined $dep->{"key"} and defined $dep_res
defined $dep->{"key"} defined $dep_res
Truth table100%3/3
A and B
A= defined $dep->{"key"}B= defined $dep_res
ABresult
0X0
100
111
403 5 $c->stash->{$dep->{key}} = $dep_res;
404 }
405 }
406  
407 54 return await $route->{handler}->($c);
408 }
409 }
410  
411 2 $c->status(404);
412 2 return { detail => 'Not Found' };
413 63 };
414  
415 63 my $pipeline = $dispatcher;
416 63 for my $mw (reverse @$middlewares) {
417 23 my $next_stage = $pipeline;
418 23 ▶ $pipeline = async sub ($c) {
Subroutine __ANON__: called CC=1 SCAR=0.0
419 23 return await $mw->($c, $next_stage);
420 23 };
421 }
422  
423 63 my $res = await $pipeline->($ctx);
424  
425 # 1. Check if response is an SSE / Streaming object that handles its own send lifecycle
426 63 ▶ if (Scalar::Util::blessed($res) && $res->can('dispatch')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($res) and $res->can("dispatch")) 0 63 63
Condition66%2/3
builtin::blessed($res) and $res->can("dispatch")
!ll&&!rl&&r
5940
MC/DC0%0/2
builtin::blessed($res) and $res->can("dispatch")
builtin::blessed($res) $res->can("dispatch")
Truth table66%2/3
A and B
A= builtin::blessed($res)B= $res->can("dispatch")
ABresult
0X0
100
111
427 0 return await $res->dispatch($scope, $receive, $send);
428 }
429  
430 # 2. Response objects (HTML, Custom Response, etc.)
431 63 ▶ if (Scalar::Util::blessed($res) && $res->isa('PAGI::FastAPI::Response')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($res) and $res->isa("PAGI::FastAPI::Response")) 4 59 63
Condition66%2/3
builtin::blessed($res) and $res->isa("PAGI::FastAPI::Response")
!ll&&!rl&&r
5904
MC/DC50%1/2
builtin::blessed($res) and $res->isa("PAGI::FastAPI::Response")
builtin::blessed($res) $res->isa("PAGI::FastAPI::Response")
Truth table66%2/3
A and B
A= builtin::blessed($res)B= $res->isa("PAGI::FastAPI::Response")
ABresult
0X0
100
111
432 4 $res->prepare_headers($ctx);
433  
434 4 await $send->({
435 type => 'http.response.start',
436 status => $ctx->status,
437 headers => $ctx->res_headers,
438 });
439  
440 4 await $send->({
441 type => 'http.response.body',
442 body => $res->body,
443 });
444  
445 4 return;
446 }
447  
448 # 3. Standard HASH/ARRAY data structures -> JSON
449 # 4. Standard unblessed scalars -> Plain text / String output
450 59 my $response_body_str = '';
451 59 my $is_json = 0;
452  
453 59 ▶ if (defined $res) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $res) 59 0 59
454 59 my $reftype = ref $res;
455 59 ▶ if ($reftype eq 'HASH' || $reftype eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if ($reftype eq 'HASH' or $reftype eq 'ARRAY') { } 59 0 59
elsif (builtin::blessed($res) and $res->can('TO_JSON')) { } 0 0 0
Condition33%1/3
$reftype eq "HASH" or $reftype eq "ARRAY"
l!l&&r!l&&!r
5900
MC/DC0%0/2
$reftype eq "HASH" or $reftype eq "ARRAY"
$reftype eq "HASH" $reftype eq "ARRAY"
Truth table33%1/3
A or B
A= $reftype eq "HASH"B= $reftype eq "ARRAY"
ABresult
1X1
011
000
456 59 $response_body_str = encode_json($res);
457 59 $is_json = 1;
458 }
459 ▶ elsif (Scalar::Util::blessed($res) && $res->can('TO_JSON')) {
Condition0%0/3
builtin::blessed($res) and $res->can("TO_JSON")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($res) and $res->can("TO_JSON")
builtin::blessed($res) $res->can("TO_JSON")
Truth table0%0/3
A and B
A= builtin::blessed($res)B= $res->can("TO_JSON")
ABresult
0X0
100
111
460 0 $response_body_str = encode_json($res);
461 0 $is_json = 1;
462 }
463 else {
464 0 $response_body_str = "$res";
465 }
466 }
467  
468 59 my $has_content_type = grep { lc($_->[0]) eq 'content-type' } @{$ctx->res_headers};
469  
470 my @res_headers = (
471 ($is_json && !$has_content_type ? (['content-type', 'application/json']) : ()),
472 59 ▶ @{$ctx->res_headers}
Branch: 1 branch
BranchTrueFalseTotal
$is_json && !$has_content_type ? : 59 0 59
Condition33%1/3
$is_json and not $has_content_type
!ll&&!rl&&r
0059
MC/DC0%0/2
$is_json and not $has_content_type
$is_json not $has_content_type
Truth table33%1/3
A and not(B)
A= $is_jsonB= not $has_content_type
ABresult
0X0
100
111
473 );
474  
475 59 await $send->({
476 type => 'http.response.start',
477 status => $ctx->status,
478 headers => \@res_headers,
479 });
480  
481 59 await $send->({
482 type => 'http.response.body',
483 body => $response_body_str,
484 });
485 39 ▶ };
Subroutine _build_pagi_app: called CC=1 SCAR=0.0
486 21 }
487  
488 ▶ sub _uri_unescape ($str) {
Subroutine _uri_unescape: called CC=2 SCAR=7.0
489 23 ▶ return $str unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 23 23
490 23 $str =~ tr/+/ /;
491 23 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
492 23 return $str;
493 }
494  
495 # Parses a 'multipart/form-data' request body per RFC 7578. Returns two
496 # HashRefs: (\%form_data, \%uploaded_files).
497 #
498 # %form_data mirrors the shape of application/x-www-form-urlencoded
499 # parsing, one scalar string value per field name (last value wins on
500 # a repeated name, matching the existing urlencoded behavior above).
501 #
502 # %uploaded_files is keyed by field name; each value is always an
503 # ArrayRef of { filename, content_type, content, size } HashRefs,
504 # even for a single file, so a field using <input type="file" multiple>
505 # and one using a plain single-file input have the same shape to consume.
506 ▶ sub _parse_multipart_form_data ($raw_body, $boundary) {
Subroutine _parse_multipart_form_data: called CC=19 SCAR=34.4
507 4 my %form_data;
508 my %uploaded_files;
509  
510 4 ▶ return (\%form_data, \%uploaded_files)
Branch: 1 branch
BranchTrueFalseTotal
unless defined $raw_body and length $raw_body and defined $boundary and length $boundary 0 4 4
Condition33%3/9
defined $raw_body and length $raw_body and defined $boundary and length $boundary
!ll&&!rl&&r
004
defined $raw_body and length $raw_body and defined $boundary
!ll&&!rl&&r
004
defined $raw_body and length $raw_body
!ll&&!rl&&r
004
MC/DC0%0/4
defined $raw_body and length $raw_body and defined $boundary and length $boundary
defined $raw_body length $raw_body defined $boundary length $boundary
Truth table20%1/5
A and B and C and D
A= defined $raw_bodyB= length $raw_bodyC= defined $boundaryD= length $boundary
ABCDresult
0XXX0
10XX0
110X0
11100
11111
511 unless defined $raw_body && length $raw_body
512 && defined $boundary && length $boundary;
513  
514 # Normalise newlines and trim final boundary trailing dashes
515 4 $raw_body =~ s/--\Q$boundary\E--\s*\z//;
516  
517 4 my @chunks = split /--\Q$boundary\E\r?\n?/, $raw_body;
518 4 ▶ shift @chunks if @chunks && $chunks[0] !~ /Content-Disposition/i;
Branch: 1 branch
BranchTrueFalseTotal
if @chunks and not $chunks[0] =~ /Content-Disposition/iu 4 0 4
Condition33%1/3
@chunks and not $chunks[0] =~ /Content-Disposition/iu
!ll&&!rl&&r
004
MC/DC0%0/2
@chunks and not $chunks[0] =~ /Content-Disposition/iu
@chunks not $chunks[0] =~ /Content-Disposition/iu
Truth table33%1/3
A and not(B)
A= @chunksB= not $chunks[0] =~ /Content-Disposition/iu
ABresult
0X0
100
111
519  
520 4 for my $chunk (@chunks) {
521 6 ▶ next unless length $chunk;
Branch: 1 branch
BranchTrueFalseTotal
unless length $chunk 0 6 6
522 6 $chunk =~ s/\r?\n\z//;
523  
524 6 my ($header_block, $part_body) = split /\r?\n\r?\n/, $chunk, 2;
525 6 ▶ next unless defined $part_body;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $part_body 0 6 6
526  
527 6 my %headers;
528 6 for my $line (split /\r?\n/, $header_block) {
529 9 ▶ $headers{lc $1} = $2 if $line =~ /^([^:]+):\s*(.*)\z/;
Branch: 1 branch
BranchTrueFalseTotal
if $line =~ /^([^:]+):\s*(.*)\z/u 9 0 9
530 }
531  
532 6 ▶ my $disposition = $headers{'content-disposition'} // '';
Condition50%1/2
$headers{"content-disposition"} // ""
l!l
60
MC/DC0%0/1
$headers{"content-disposition"} // ""
$headers{"content-disposition"}
Truth table50%1/2
A
A= $headers{"content-disposition"}
Aresult
11
00
533 6 my ($name) = $disposition =~ /\bname="([^"]*)"/;
534 6 ▶ next unless defined $name && length $name;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $name and length $name 0 6 6
Condition33%1/3
defined $name and length $name
!ll&&!rl&&r
006
MC/DC0%0/2
defined $name and length $name
defined $name length $name
Truth table33%1/3
A and B
A= defined $nameB= length $name
ABresult
0X0
100
111
535  
536 6 my ($filename_star) = $disposition =~ /\bfilename\*\s*=\s*UTF-8''([^;]+)/i;
537 6 my ($filename) = $disposition =~ /\bfilename="([^"]*)"/;
538 6 ▶ $filename = _uri_unescape($filename_star) if defined $filename_star;
Branch: 1 branch
BranchTrueFalseTotal
if defined $filename_star 0 6 6
539  
540 6 ▶ if (defined $filename && length $filename) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $filename and length $filename) { } 3 3 6
Condition66%2/3
defined $filename and length $filename
!ll&&!rl&&r
303
MC/DC50%1/2
defined $filename and length $filename
defined $filename length $filename
Truth table66%2/3
A and B
A= defined $filenameB= length $filename
ABresult
0X0
100
111
541 3 ▶ push @{ $uploaded_files{$name} }, {
Condition50%1/2
$headers{"content-type"} // "application/octet-stream"
l!l
30
MC/DC0%0/1
$headers{"content-type"} // "application/octet-stream"
$headers{"content-type"}
Truth table50%1/2
A
A= $headers{"content-type"}
Aresult
11
00
542 filename => $filename,
543 3 content_type => $headers{'content-type'} // 'application/octet-stream',
544 content => $part_body,
545 size => length $part_body,
546 };
547 }
548 else {
549 3 $form_data{$name} = $part_body;
550 }
551 }
552  
553 4 return (\%form_data, \%uploaded_files);
554 }
555  
556 # Derives a stable, unique-by-construction OpenAPI operationId from a
557 # route's method and path, e.g. GET /widgets/{id} -> "get_widgets_id".
558 # Unique because method+path is already unique per registered route
559 # (two routes can't share both). Callers can override this default via
560 # the 'operation_id' route option, e.g. when a path changes but external
561 # tooling (codegen, OpenAPI `links`, ...) depends on the ID being
562 # stable.
563 ▶ sub _operation_id_for ($method, $path) {
Subroutine _operation_id_for: called CC=2 SCAR=7.0
564 41 my $slug = lc($path);
565 41 $slug =~ s/[{}]//g;
566 41 $slug =~ s{/}{_}g;
567 41 $slug =~ s/[^a-z0-9_]/_/g;
568 41 $slug =~ s/^_+|_+$//g;
569 41 ▶ $slug = 'root' unless length $slug;
Branch: 1 branch
BranchTrueFalseTotal
unless length $slug 0 41 41
570 41 return lc($method) . '_' . $slug;
571 }
572  
573 # Retains a fire-and-forget Future so it isn't garbage-collected or
574 # cancelled before it completes, and removes it from the retention
575 # list once it settles. Owned at the application-instance level (not
576 # per-request), since the whole point is the task keeps running after
577 # its originating request/response has already finished.
578 ▶ method _retain_background ($future) {
Subroutine _retain_background: called CC=1 SCAR=0.0
579 3 push @$background_futures, $future;
580  
581 $future->on_ready(sub {
582 3 ▶ @$background_futures = grep { $_ != $future } @$background_futures;
Subroutine __ANON__: called CC=1 SCAR=0.0
583 3 });
584  
585 # A background task is deliberately fire-and-forget: nobody else
586 # ever calls ->get/->failure on it. Without an on_fail handler,
587 # Future.pm would emit its "lost future" leak warning if the task
588 # dies. Log it instead of letting it surface as a leak.
589 ▶ $future->on_fail(sub ($err) {
Subroutine __ANON__: called CC=1 SCAR=0.0
590 1 warn "[PAGI::FastAPI] background task failed: $err";
591 3 });
592  
593 3 return $future;
594 21 }
595  
596 3 ▶ async method _handle_websocket ($scope, $receive, $send) {
Subroutine _handle_websocket: called CC=9 SCAR=28.0
597 3 ▶ my $raw_path = $scope->{path} // '/';
Condition50%1/2
$scope->{"path"} // "/"
l!l
30
MC/DC0%0/1
$scope->{"path"} // "/"
$scope->{"path"}
Truth table50%1/2
A
A= $scope->{"path"}
Aresult
11
00
598 3 my ($route, $path_params) = $self->_match_route('WEBSOCKET', $raw_path);
599  
600 3 ▶ unless ($route) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($route) 1 2 3
601 1 $scope->{path_params} = {};
602 1 my $ws = PAGI::WebSocket->new($scope, $receive, $send);
603 1 await $ws->close(4004, "Not Found");
604 1 return;
605 }
606  
607 2 ▶ $scope->{path_params} = $path_params // {};
Condition50%1/2
$path_params // {}
l!l
20
MC/DC0%0/1
$path_params // {}
$path_params
Truth table50%1/2
A
A= $path_params
Aresult
11
00
608 2 my $ws = PAGI::WebSocket->new($scope, $receive, $send);
609  
610 2 my $resolved_deps = {};
611 2 ▶ if ($route->{dependencies} && @{$route->{dependencies}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($route->{"dependencies"} and @{$route->{"dependencies"};}) 0 2 2
Condition33%1/3
$route->{"dependencies"} and @{$route->{"dependencies"};}
!ll&&!rl&&r
020
MC/DC0%0/2
$route->{"dependencies"} and @{$route->{"dependencies"};}
$route->{"dependencies"} @{$route->{"dependencies"};}
Truth table33%1/3
A and B
A= $route->{"dependencies"}B= @{$route->{"dependencies"};}
ABresult
0X0
100
111
612 0 try {
613 0 for my $dep (@{$route->{dependencies}}) {
614 0 my $res = await $dep->{code}->($ws);
615 0 ▶ if (defined $dep->{key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $dep->{"key"}) 0 0 0
616 0 $resolved_deps->{$dep->{key}} = $res;
617 }
618 }
619 }
620 catch ($err) {
621 0 await $ws->close(1008, "Unauthorized: $err");
622 0 return;
623 }
624 }
625  
626 2 my $handler = $route->{handler};
627 2 try {
628 2 await $handler->($ws, $resolved_deps);
629 }
630 catch ($err) {
631 0 ▶ if (!$ws->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $ws->is_closed) 0 0 0
632 0 await $ws->close(1011, "Internal Server Error");
633 }
634 }
635 21 }
636  
637 ▶ method _match_route ($method, $path) {
Subroutine _match_route: called CC=5 SCAR=16.1
638 3 for my $route (@$routes) {
639 5 ▶ next unless $route->{method} eq $method;
Branch: 1 branch
BranchTrueFalseTotal
unless $route->{"method"} eq $method 0 5 5
640  
641 5 ▶ if (my @captures = ($path =~ $route->{regex})) {
Branch: 1 branch
BranchTrueFalseTotal
if (my(@captures) = $path =~ /$route->{"regex"}/u) 2 3 5
642 2 my %path_params;
643 2 for my $i (0 .. $#{$route->{path_params}}) {
644 1 $path_params{$route->{path_params}[$i]} = _uri_unescape($captures[$i]);
645 }
646 2 return ($route, \%path_params);
647 }
648 }
649 1 return (undef, {});
650 21 }
651  
652 ▶ method _register_route ($method, $path, $opts) {
Subroutine _register_route: called CC=41 SCAR=37.5
653 48 ▶ my $query_types = $opts->{query} // {};
Condition100%2/2
$opts->{"query"} // {}
l!l
444
MC/DC100%1/1
$opts->{"query"} // {}
$opts->{"query"}
Truth table100%2/2
A
A= $opts->{"query"}
Aresult
11
00
654 48 my $body_spec = $opts->{body};
655 48 ▶ my $raw_deps = $opts->{dependencies} // [];
Condition100%2/2
$opts->{"dependencies"} // []
l!l
939
MC/DC100%1/1
$opts->{"dependencies"} // []
$opts->{"dependencies"}
Truth table100%2/2
A
A= $opts->{"dependencies"}
Aresult
11
00
656 48 my $handler = $opts->{handler};
657 48 my $rl_opts = $opts->{rate_limit};
658  
659 48 ▶ die "Route '$method $path' requires a 'handler' async coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $handler eq "CODE" 1 47 48
660 unless ref $handler eq 'CODE';
661  
662 die "Route '$method $path' 'tags' must be an ArrayRef"
663 47 ▶ if exists $opts->{tags} && ref $opts->{tags} ne 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"tags"} and ref $opts->{"tags"} ne "ARRAY" 1 46 47
Condition100%3/3
exists $opts->{"tags"} and ref $opts->{"tags"} ne "ARRAY"
!ll&&!rl&&r
4511
MC/DC100%2/2
exists $opts->{"tags"} and ref $opts->{"tags"} ne "ARRAY"
exists $opts->{"tags"} ref $opts->{"tags"} ne "ARRAY"
Truth table100%3/3
A and B
A= exists $opts->{"tags"}B= ref $opts->{"tags"} ne "ARRAY"
ABresult
0X0
100
111
664  
665 die "Route '$method $path' 'responses' must be a HashRef"
666 46 ▶ if exists $opts->{responses} && ref $opts->{responses} ne 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"responses"} and ref $opts->{"responses"} ne "HASH" 1 45 46
Condition100%3/3
exists $opts->{"responses"} and ref $opts->{"responses"} ne "HASH"
!ll&&!rl&&r
4321
MC/DC100%2/2
exists $opts->{"responses"} and ref $opts->{"responses"} ne "HASH"
exists $opts->{"responses"} ref $opts->{"responses"} ne "HASH"
Truth table100%3/3
A and B
A= exists $opts->{"responses"}B= ref $opts->{"responses"} ne "HASH"
ABresult
0X0
100
111
667  
668 die "Route '$method $path' 'operation_id' must be a non-empty string"
669 45 ▶ if exists $opts->{operation_id} && !length($opts->{operation_id} // '');
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"operation_id"} and not length($opts->{"operation_id"} // "") 0 45 45
Condition20%1/5
exists $opts->{"operation_id"} and not length($opts->{"operation_id"} // "")
!ll&&!rl&&r
4500
$opts->{"operation_id"} // ""
l!l
00
MC/DC0%0/2
exists $opts->{"operation_id"} and not length($opts->{"operation_id"} // "")
exists $opts->{"operation_id"} $opts->{"operation_id"}
Truth table33%1/3
A and not(B)
A= exists $opts->{"operation_id"}B= $opts->{"operation_id"}
ABresult
0X0
110
101
670  
671 45 ▶ if ($rl_opts) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rl_opts) 1 44 45
672 1 ▶ my $limiter = PAGI::FastAPI::Middleware::RateLimit->new(
Branch: 1 branch
BranchTrueFalseTotal
ref $rl_opts eq 'HASH' ? : 1 0 1
673 ref $rl_opts eq 'HASH' ? %$rl_opts : ()
674 );
675 1 my $inner_handler = $handler;
676 9 ▶ $handler = async sub ($c) {
Subroutine __ANON__: called CC=1 SCAR=0.0
677 6 ▶ return await $limiter->handle($c, async sub ($ctx) {
Subroutine __ANON__: called CC=1 SCAR=0.0
678 6 return await $inner_handler->($ctx);
679 9 });
680 1 };
681 }
682  
683 45 ▶ die "Route '$method $path' 'dependencies' must be a HashRef or ArrayRef"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $raw_deps eq "HASH" or ref $raw_deps eq "ARRAY" 1 44 45
Condition100%3/3
ref $raw_deps eq "HASH" or ref $raw_deps eq "ARRAY"
l!l&&r!l&&!r
2421
MC/DC100%2/2
ref $raw_deps eq "HASH" or ref $raw_deps eq "ARRAY"
ref $raw_deps eq "HASH" ref $raw_deps eq "ARRAY"
Truth table100%3/3
A or B
A= ref $raw_deps eq "HASH"B= ref $raw_deps eq "ARRAY"
ABresult
1X1
011
000
684 unless ref $raw_deps eq 'HASH' || ref $raw_deps eq 'ARRAY';
685  
686 44 my @dependencies;
687 44 ▶ if (ref $raw_deps eq 'HASH') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $raw_deps eq 'HASH') { } 2 42 44
elsif (ref $raw_deps eq 'ARRAY') { } 42 0 42
688 2 for my ($key, $code) (%$raw_deps) {
689 3 ▶ die "Route '$method $path' dependency '$key' must be a CODE reference"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $code eq "CODE" 0 3 3
690 unless ref $code eq 'CODE';
691 3 push @dependencies, { key => $key, code => $code };
692 }
693 } elsif (ref $raw_deps eq 'ARRAY') {
694 42 for my $dep (@$raw_deps) {
695 5 ▶ if (blessed($dep) && $dep->isa('PAGI::FastAPI::Depends')) {
Branch: 2 branches
BranchTrueFalseTotal
if (builtin::blessed($dep) and $dep->isa('PAGI::FastAPI::Depends')) { } 3 2 5
elsif (ref $dep eq 'CODE') { } 1 1 2
Condition66%2/3
builtin::blessed($dep) and $dep->isa("PAGI::FastAPI::Depends")
!ll&&!rl&&r
203
MC/DC50%1/2
builtin::blessed($dep) and $dep->isa("PAGI::FastAPI::Depends")
builtin::blessed($dep) $dep->isa("PAGI::FastAPI::Depends")
Truth table66%2/3
A and B
A= builtin::blessed($dep)B= $dep->isa("PAGI::FastAPI::Depends")
ABresult
0X0
100
111
696 3 push @dependencies, { key => $dep->key, code => $dep->code };
697 } elsif (ref $dep eq 'CODE') {
698 1 push @dependencies, { key => undef, code => $dep };
699 } else {
700 1 die "Route '$method $path' has an unrecognized dependency entry "
701 . "(expected CODE ref or PAGI::FastAPI::Depends instance)";
702 }
703 }
704 }
705  
706 43 my @path_params;
707 43 my $regex_path = '';
708 43 my $last_pos = 0;
709 43 ▶ while ($path =~ /\{([a-zA-Z_]\w*)\}/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /\{([a-zA-Z_]\w*)\}/gu) 8 43 51
710 8 push @path_params, $1;
711 8 $regex_path .= quotemeta(substr($path, $last_pos, $-[0] - $last_pos));
712 8 $regex_path .= '([^/]+)';
713 8 $last_pos = $+[0];
714 }
715 43 $regex_path .= quotemeta(substr($path, $last_pos));
716 43 $regex_path = "^$regex_path\$";
717  
718 43 ▶ if ($method ne 'WEBSOCKET') {
Branch: 1 branch
BranchTrueFalseTotal
if ($method ne "WEBSOCKET") 41 2 43
719 41 my @parameters;
720 41 for my $param (@path_params) {
721 7 push @parameters, {
722 name => $param,
723 in => 'path',
724 required => \1,
725 schema => { type => 'string' }
726 };
727 }
728 41 for my ($param, $type) (%$query_types) {
729 4 ▶ my $t_name = eval { $type->name } // '';
Condition50%1/2
eval { do { $type->name } } // ""
l!l
40
MC/DC0%0/1
eval { do { $type->name } } // ""
eval { do { $type->name } }
Truth table50%1/2
A
A= eval { do { $type->name } }
Aresult
11
00
730 4 ▶ push @parameters, {
Branch: 1 branch
BranchTrueFalseTotal
$t_name eq 'Int' ? : 3 1 4
731 name => $param,
732 in => 'query',
733 required => \1,
734 schema => { type => ($t_name eq 'Int' ? 'integer' : 'string') }
735 };
736 }
737  
738 my $route_doc = {
739 operationId => $opts->{operation_id} // _operation_id_for($method, $path),
740 summary => $opts->{summary} // "$method $path",
741 parameters => \@parameters,
742 responses => {
743 200 => { description => "Successful Response" },
744 422 => { description => "Validation Error" },
745 41 ▶ %{ $opts->{responses} // {} },
Condition71%5/7
$opts->{"operation_id"} // _operation_id_for($method, $path)
l!l&&r!l&&!r
0410
$opts->{"summary"} // "$method $path"
l!l
140
$opts->{"responses"} // {}
l!l
239
MC/DC0%0/2
$opts->{"operation_id"} // _operation_id_for($method, $path)
$opts->{"operation_id"} _operation_id_for($method, $path)
MC/DC100%1/1
$opts->{"summary"} // "$method $path"
$opts->{"summary"}
MC/DC100%1/1
$opts->{"responses"} // {}
$opts->{"responses"}
Truth table33%1/3
A // B
A= $opts->{"operation_id"}B= _operation_id_for($method, $path)
ABresult
1X1
011
000
Truth table100%2/2
A
A= $opts->{"summary"}
Aresult
11
00
Truth table100%2/2
A
A= $opts->{"responses"}
Aresult
11
00
746 },
747 };
748  
749 41 ▶ $route_doc->{tags} = $opts->{tags} if exists $opts->{tags};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"tags"} 1 40 41
750 41 ▶ $route_doc->{description} = $opts->{description} if exists $opts->{description};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts->{"description"} 1 40 41
751 41 ▶ $route_doc->{deprecated} = $opts->{deprecated} ? \1 : \0 if exists $opts->{deprecated};
Branch: 2 branches
BranchTrueFalseTotal
if exists $opts->{"deprecated"} 1 40 41
$opts->{'deprecated'} ? : 1 0 1
752  
753 41 ▶ if ($body_spec) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body_spec) 3 38 41
754 3 my $properties = {};
755 3 ▶ if (ref $body_spec eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $body_spec eq "HASH") 2 1 3
756 2 for my ($k, $t) (%$body_spec) {
757 4 ▶ my $t_name = eval { $t->name } // '';
Condition50%1/2
eval { do { $t->name } } // ""
l!l
40
MC/DC0%0/1
eval { do { $t->name } } // ""
eval { do { $t->name } }
Truth table50%1/2
A
A= eval { do { $t->name } }
Aresult
11
00
758 4 ▶ $properties->{$k} = { type => ($t_name eq 'Int' ? 'integer' : 'string') };
Branch: 1 branch
BranchTrueFalseTotal
$t_name eq 'Int' ? : 1 3 4
759 }
760 }
761 $route_doc->{requestBody} = {
762 3 required => \1,
763 content => {
764 'application/json' => {
765 schema => {
766 type => 'object',
767 properties => $properties,
768 }
769 }
770 }
771 };
772 }
773  
774 41 $openapi->{paths}{$path}{lc($method)} = $route_doc;
775 }
776  
777 43 push @$routes, {
778 method => $method,
779 path => $path,
780 regex => qr/$regex_path/,
781 path_params => \@path_params,
782 query_types => $query_types,
783 body_spec => $body_spec,
784 dependencies => \@dependencies,
785 handler => $handler,
786 };
787 21 }
788  
789 method _swagger_ui_html {
790 1 ▶ my $json = encode_json($swagger_ui_parameters);
Subroutine _swagger_ui_html: called CC=2 SCAR=7.0
791  
792 # Strip opening '{' and closing '}' to inject properties directly
793 1 $json =~ s/^\s*\{|\}\s*$//g;
794  
795 # Add a comma prefix if options are present
796 1 ▶ my $extra_opts = length($json) ? ",\n $json" : "";
Branch: 1 branch
BranchTrueFalseTotal
length $json ? : 1 0 1
797  
798 1 return <<"HTML";
799 <!DOCTYPE html>
800 <html>
801 <head>
802 <title>$title - Swagger UI</title>
803 <link rel="stylesheet" href="$swagger_ui_css_url" />
804 </head>
805 <body>
806 <div id="swagger-ui"></div>
807 <script src="$swagger_ui_bundle_url"></script>
808 <script>
809 SwaggerUIBundle({
810 url: '/openapi.json',
811 dom_id: '#swagger-ui'$extra_opts
812 });
813 </script>
814 </body>
815 </html>
816 HTML
817 21 }
818 }
819  
820 =encoding utf-8
821  
822 =head1 NAME
823  
824 PAGI::FastAPI - Asynchronous, Type-Safe Micro-Framework with Dependency Injection and OpenAPI & Swagger UI
825  
826 =head1 VERSION
827  
828 Version v1.7.1
829  
830 =head1 SYNOPSIS
831  
832 use v5.38;
833 use PAGI::FastAPI;
834 use PAGI::FastAPI::Depends qw(Depends);
835 use Types::Standard qw(Int Str);
836 use Future::AsyncAwait;
837  
838 my $app = PAGI::FastAPI->new(
839 title => 'Store Microservice',
840 version => '1.0.0',
841 );
842  
843 # 1. Add CORS Support (delegates to PAGI::Middleware::CORS from PAGI::Tools)
844 $app->add_cors(
845 origins => ['https://example.com'],
846 methods => ['GET', 'POST'],
847 );
848  
849 # 2. Add Authentication Middleware Hook
850 # (hand-rolled here for illustration only, for ready-made schemes,
851 # including proper 401 challenges, see PAGI::FastAPI::Security)
852 $app->add_middleware(async sub ($c, $next) {
853 my $auth = $c->header('Authorization') // '';
854 if ($auth ne 'Bearer secret_token') {
855 $c->status(401);
856 return { detail => 'Unauthorized' };
857 }
858 $c->stash->{user_id} = 42;
859 return await $next->($c);
860 });
861  
862 # 3. Register Lifespan Handlers
863 $app->on_startup(async sub {
864 warn "Connecting to database connection pool...\n";
865 });
866  
867 $app->on_shutdown(async sub {
868 warn "Closing database connections...\n";
869 });
870  
871 # 4. Declare Async Dependencies
872 my $get_db = async sub ($c) {
873 return { db_name => 'production_db' };
874 };
875  
876 my $get_current_user = async sub ($c) {
877 my $token = $c->header('Authorization') // '';
878 unless ($token eq 'Bearer secret_token') {
879 $c->status(401);
880 return { detail => 'Invalid credentials' };
881 }
882 return { user_id => 42, role => 'admin' };
883 };
884  
885 # 5. Route using HashRef Dependency Map
886 $app->get('/profile',
887 dependencies => {
888 db => $get_db,
889 user => $get_current_user,
890 },
891 handler => async sub ($c) {
892 my $db = $c->stash->{db};
893 my $user = $c->stash->{user};
894 return { user => $user, db => $db->{db_name} };
895 }
896 );
897  
898 # 6. Route using Depends() Array Spec
899 $app->get('/admin',
900 dependencies => [
901 Depends($get_current_user, key => 'user'),
902 async sub ($c) {
903 if ($c->stash->{user}{role} ne 'admin') {
904 $c->status(403);
905 return { detail => 'Admin privileges required' };
906 }
907 }
908 ],
909 handler => async sub ($c) {
910 return { message => 'Welcome to admin panel' };
911 }
912 );
913  
914 # 7. Non-blocking GET route with path parameter & query validation
915 $app->get('/items/{id}',
916 query => { limit => Int },
917 handler => async sub ($c) {
918 return {
919 item_id => $c->param('id'),
920 limit => $c->param('limit'),
921 status => 'active',
922 };
923 }
924 );
925  
926 # 8. Non-blocking POST route with JSON payload validation
927 $app->post('/items',
928 body => { name => Str, price => Int },
929 handler => async sub ($c) {
930 return {
931 created => 1,
932 name => $c->body('name'),
933 price => $c->body('price'),
934 };
935 }
936 );
937  
938 # 9. Non-blocking WebSocket Endpoint
939 # $ws is a PAGI::WebSocket (from PAGI::Tools), so on_close/each_json/
940 # try_send_json/keepalive and more are all built in.
941 $app->websocket('/ws', handler => async sub ($ws, $deps) {
942 await $ws->accept;
943  
944 $ws->on_close(async sub {
945 my ($code, $reason) = @_;
946 # runs on every disconnect path, not just a clean loop exit
947 });
948  
949 await $ws->each_json(async sub {
950 my ($data) = @_;
951 await $ws->send_json({ echo => $data });
952 });
953 });
954  
955 # 10. Authentication via the companion PAGI::FastAPI::Security distribution
956 # (extraction only, you supply the verification logic)
957 #
958 # use PAGI::FastAPI::Security::HTTPBearer;
959 # my $bearer = PAGI::FastAPI::Security::HTTPBearer->new;
960 # $app->get('/secure',
961 # dependencies => [ $bearer->depends(key => 'token') ],
962 # handler => async sub ($c) {
963 # return { token => $c->stash->{token} };
964 # }
965 # );
966 #
967 # See L<PAGI::FastAPI::Security> for HTTP Basic, API Key
968 # (header/query/cookie), and OAuth2 password-bearer schemes.
969  
970 my $pagi_app = $app->to_app;
971  
972 =head1 DESCRIPTION
973  
974 C<PAGI::FastAPI> is an asynchronous micro-framework for modern Perl (5.36+) inspired by Python's FastAPI.
975  
976 It combines non-blocking async execution via L<Future::AsyncAwait> on the
977 L<PAGI> (Perl Asynchronous Gateway Interface) specification with request
978 parameter validation via L<Type::Tiny> and automatic interactive
979 documentation generation.
980  
981 =head2 Key Features
982  
983 =over 4
984  
985 =item * B<PAGI Protocol Engine:> Asynchronous and non-blocking natively,
986 built for scalable web applications.
987  
988 =item * B<Sub-App & Static Mounting:> Mount external PAGI applications, file
989 drivers, or sub-routers using L<mount()|/"C<mount($path_prefix, $pagi_app)>">.
990  
991 =item * B<WebSocket Support:> Full non-blocking WebSocket handshake and frame
992 streaming via L<PAGI::WebSocket>.
993  
994 =item * B<CORS:> C<add_cors> delegates to L<PAGI::Middleware::CORS> (from
995 L<PAGI::Tools>) rather than a separate implementation.
996  
997 =item * B<Automatic Type Validation:> Request query parameters and JSON
998 payloads are checked against L<Type::Tiny> constraints before reaching route
999 handlers.
1000  
1001 =item * B<Automatic Interactive Docs:> Serves an interactive Swagger UI
1002 interface at C</docs> and machine-readable OpenAPI 3.1 JSON at C</openapi.json>.
1003  
1004 =item * B<HTTP 422 Interception:> Automatically intercepts invalid or missing
1005 parameters and returns formatted JSON errors with an
1006 C<HTTP 422 Unprocessable Entity> status code.
1007  
1008 =item * B<Pluggable Authentication:> Authentication is implemented as ordinary
1009 dependencies and middleware, with no framework lock-in. For ready-made schemes
1010 (HTTP Bearer, HTTP Basic, API Key, OAuth2 password bearer), see the companion
1011 distribution L<PAGI::FastAPI::Security>, see L</AUTHENTICATION AND SECURITY>
1012 below.
1013  
1014 =item * B<Rate Limiting:> C<add_rate_limit> and the per-route C<rate_limit>
1015 option provide fixed-window request throttling with pluggable storage
1016 drivers, see L<PAGI::FastAPI::Middleware::RateLimit>.
1017  
1018 =item * B<Bot Protection:> C<add_bot_protection> enforces a stateless,
1019 cryptographic proof-of-work challenge/response flow on unauthenticated
1020 requests, see L<PAGI::FastAPI::Middleware::BotProtection>.
1021  
1022 =item * B<File Uploads:> C<multipart/form-data> request bodies are parsed
1023 automatically, see L</FILE UPLOADS>.
1024  
1025 =item * B<Background Tasks:> C<< $c->background(async sub {...}) >> for
1026 fire-and-forget work that outlives the request, see L</BACKGROUND TASKS>.
1027  
1028 =item * B<Server-Sent Events:> C<< $c->sse >> streams production-grade SSE
1029 responses with keepalives and auto-JSON serialisation, see
1030 L<PAGI::FastAPI::Response::SSE>.
1031  
1032 =item * B<CSRF Protection:> C<enable_csrf>, plus C<< $c->csrf_token >> and
1033 C<< $c->csrf_verify >>, for form and session-based CSRF defence.
1034  
1035 =item * B<Async Message Queue Facade:> L<PAGI::FastAPI::Queue> offers a
1036 pluggable, topic-based C<push>/C<pop>/C<size> queue for use as an ordinary
1037 dependency via C<< $queue->dep >>.
1038  
1039 =item * B<Typed Path Parameters:> C<TypedPath()> from
1040 L<PAGI::FastAPI::TypedPath> validates and (optionally) coerces path
1041 parameters via L<Type::Tiny>, the same way C<query>/C<body> already are,
1042 through the existing C<Depends()> mechanism, automatically returning
1043 C<HTTP 422> for a non-matching path segment instead of handing your handler
1044 an unchecked string.
1045  
1046 =item * B<Response Shape Filtering:> C<with_response_model()> from
1047 L<PAGI::FastAPI::ResponseModel> validates a handler's return value against
1048 a declared L<Type::Tiny> schema and, for a HashRef-of-fields schema, filters
1049 the output to just the declared fields, so an accidental extra column
1050 from a database row (e.g. a password hash) doesn't leak to the client.
1051  
1052 =item * B<Typed Exception Dispatch:> L<PAGI::FastAPI::Middleware::ExceptionHandler>
1053 routes a C<die>-thrown exception to a handler registered for its class,
1054 with a configurable fallback, for the case where an exception escapes a
1055 handler rather than following the C<< $c->status(...) >>-and-return
1056 convention described in L</ERROR HANDLING>.
1057  
1058 =item * B<Redirect & File Responses:> L<PAGI::FastAPI::Response::Redirect>
1059 (C<redirect_to()>) and L<PAGI::FastAPI::Response::File> (C<file_response()>)
1060 extend the base L<PAGI::FastAPI::Response> contract for HTTP redirects and
1061 file-download responses, with automatic content-type guessing and
1062 C<Content-Disposition> handling for the latter.
1063  
1064 =item * B<Cookie Parsing:> L<PAGI::FastAPI::Cookies> parses the request
1065 C<Cookie> header into a plain HashRef (C<parse_cookies()>, C<cookie()>).
1066 Setting response cookies needs no extra module, C<< $c->add_header('set-cookie' => ...) >>
1067 already works.
1068  
1069 =back
1070  
1071 =head1 METHODS
1072  
1073 =head2 C<new(%options)>
1074  
1075 my $app = PAGI::FastAPI->new(
1076 title => 'My API',
1077 version => '1.2.3',
1078 );
1079  
1080 Instantiates a new C<PAGI::FastAPI> instance. Acceptable named arguments:
1081  
1082 =over 4
1083  
1084 =item * C<title> - (Optional) Title string for the application and OpenAPI
1085 specification. Default: C<'PAGI::FastAPI Application'>.
1086  
1087 =item * C<version> - (Optional) Version string for the OpenAPI specification.
1088 Default: C<'$VERSION'>.
1089  
1090 =item * C<secret> - (Optional) Application-level secret scalar. Currently used
1091 as the default C<secret> for L</enable_csrf> when no C<secret> is passed to
1092 that call directly. Storing an app-wide secret here lets you avoid repeating
1093 it at every call site that needs it.
1094  
1095 =back
1096  
1097 =head2 C<get($path, %options)>, C<post($path, %options)>, C<put($path, %options)>, C<patch($path, %options)>, C<delete($path, %options)>
1098  
1099 Registers a route for the specified HTTP verb. Options include:
1100  
1101 =over 4
1102  
1103 =item * C<query> - (Optional) HashRef mapping query string keys to
1104 L<Type::Tiny> type constraints.
1105  
1106 =item * C<body> - (Optional) HashRef mapping request body keys to
1107 L<Type::Tiny> type constraints. The request body is parsed as JSON by
1108 default; if the C<Content-Type> header is C<application/x-www-form-urlencoded>
1109 or C<multipart/form-data>, it is parsed as form fields instead (see
1110 L</FILE UPLOADS> for the C<multipart/form-data> case specifically). Either
1111 way, the same type constraints and validation apply to the parsed field
1112 values.
1113  
1114 =item * C<dependencies> - (Optional) HashRef or ArrayRef of dependency code
1115 blocks or L<PAGI::FastAPI::Depends> specs.
1116  
1117 =item * C<handler> - (Required) An C<async sub ($c)> code reference executing
1118 business logic. Receives a L<PAGI::FastAPI::Context> instance.
1119  
1120 =item * C<tags> - (Optional) ArrayRef of strings, included verbatim in this
1121 route's generated OpenAPI document (C<< $openapi->{paths}{$path}{$method}{tags} >>).
1122 Swagger UI (served at C</docs>) groups routes by tag.
1123  
1124 =item * C<operation_id> - (Optional) String, used as this route's OpenAPI
1125 C<operationId> instead of the auto-generated default (see below). Useful
1126 when you want a stable ID that survives the route's path changing, since
1127 external tooling (client codegen, OpenAPI C<responses/*/links>, etc.) that
1128 references an C<operationId> breaks if that ID changes later.
1129  
1130 Every route gets an C<operationId> in its generated OpenAPI document,
1131 whether or not this option is given, when omitted, one is derived
1132 deterministically from the method and path (e.g. C<GET /widgets/{id}>
1133 becomes C<get_widgets_id>), which is guaranteed unique since no two
1134 routes share the same method and path.
1135  
1136 =item * C<summary> - (Optional) String, used as this route's OpenAPI
1137 C<summary>. Defaults to C<"$method $path"> (e.g. C<"GET /widgets/{id}">)
1138 when omitted, exactly as in earlier versions.
1139  
1140 =item * C<description> - (Optional) String, included as this route's
1141 OpenAPI C<description> when supplied. Omitted from the generated document
1142 entirely (not even an empty string) when not given.
1143  
1144 =item * C<deprecated> - (Optional) Boolean. When true, marks this route
1145 C<deprecated> in the generated OpenAPI document, which Swagger UI renders
1146 with a strikethrough. Omitted from the document when not given.
1147  
1148 =item * C<responses> - (Optional) HashRef mapping HTTP status codes to
1149 OpenAPI Response Object HashRefs, merged I<on top of> the default C<200>/
1150 C<422> entries every route already documents. Add an entry for a status
1151 code your handler can actually return (C<201>, C<404>, etc.), or supply
1152 your own C<200>/C<422> key to override the default wording for that
1153 route.
1154  
1155 Each response HashRef is passed through to the generated document
1156 untouched, so any valid OpenAPI Response Object key is accepted, not just
1157 C<description>, for example C<links>, to point Swagger UI/tooling at a
1158 I<different> operation worth calling next (referencing that operation's
1159 C<operationId>, per above):
1160  
1161 $app->get('/activity-log', handler => async sub ($c) { ... });
1162  
1163 $app->post('/widgets',
1164 tags => ['Widgets'],
1165 summary => 'Create a widget',
1166 description => 'Creates a new widget and returns its ID.',
1167 responses => {
1168 201 => {
1169 description => 'Widget created',
1170 links => {
1171 CheckActivityLog => {
1172 operationId => 'get_activity_log',
1173 description => 'See recent activity for this widget',
1174 },
1175 },
1176 },
1177 409 => { description => 'A widget with that name already exists' },
1178 },
1179 handler => async sub ($c) {
1180 $c->status(201);
1181 return { id => 42 };
1182 },
1183 );
1184  
1185 =back
1186  
1187 =head2 C<mount($path_prefix, $pagi_app)>
1188  
1189 $app->mount('/css', PAGI::App::File->new(root => './public/css')->to_app);
1190 $app->mount('/api/v2', $v2_sub_app);
1191  
1192 Mounts a standalone PAGI application closure or sub-application under the
1193 given path prefix. Under the hood, C<to_app()> composes mounted applications
1194 using L<PAGI::App::URLMap>.
1195  
1196 =head2 C<on_startup($code_ref)>, C<on_shutdown($code_ref)>, C<on_event($event_type, $code_ref)>
1197  
1198 Registers async callbacks for PAGI Lifespan Protocol events (C<'startup'> or
1199 C<'shutdown'>).
1200  
1201 =head2 C<add_middleware>
1202  
1203 $app->add_middleware($middleware, %opts);
1204  
1205 Appends a middleware component to the application's middleware execution stack.
1206  
1207 The C<$middleware> parameter can be passed as a class name or an instantiated
1208 object:
1209  
1210 =over 4
1211  
1212 =item * B<Class Name (String):> Automatically loads the class via C<require>
1213 (dying on load failure) and instantiates it by calling C<< $middleware->new(%opts) >>.
1214  
1215 =item * B<Object Instance:> Attached directly. If the object implements PAGI
1216 wrapper interfaces (e.g., C<wrap>, C<to_app>, or C<call>), it is placed into
1217 the PAGI middleware stack; otherwise, it is routed to the legacy/internal
1218 middleware stack.
1219  
1220 =back
1221  
1222 Returns C<$self> to allow method chaining.
1223  
1224 B<Example Usage:>
1225  
1226 # Pass class name with constructor options:
1227 $app->add_middleware('PAGI::Middleware::Session', secret => 'my-secret');
1228  
1229 # Pass an instantiated middleware object:
1230 my $mw = PAGI::Middleware::Logger->new(level => 'debug');
1231 $app->add_middleware($mw);
1232  
1233 =head2 C<enable_csrf>
1234  
1235 $app->enable_csrf(%options);
1236  
1237 Enables Cross-Site Request Forgery (CSRF) protection on the application by
1238 instantiating and attaching L<PAGI::Middleware::CSRF>.
1239  
1240 By default, the middleware is configured with C<enforce =E<gt> 'header'> and
1241 C<secure =E<gt> 0>. Any passed C<%options> override these defaults.
1242  
1243 =over 4
1244  
1245 =item * C<secret> (Scalar, optional)
1246  
1247 The cryptographic secret key used to sign and verify CSRF tokens. If omitted
1248 from C<%options>, it falls back to the application-level C<secret> attribute
1249 set during L<PAGI::FastAPI> instantiation. Dies if no secret can be resolved
1250 from either location.
1251  
1252 =item * C<%options> (Hash, optional)
1253  
1254 Additional configuration arguments passed directly to L<PAGI::Middleware::CSRF/new>
1255 (such as C<cookie_name>, C<token_length>, or C<secure>).
1256  
1257 =back
1258  
1259 Returns C<$self> to allow method chaining.
1260  
1261 B<Example Usage:>
1262  
1263 # Uses application-level default secret:
1264 my $app = PAGI::FastAPI->new(secret => 'master-app-secret');
1265 $app->enable_csrf();
1266  
1267 # Custom secret and production settings:
1268 $app->enable_csrf(
1269 secret => 'csrf-specific-secret',
1270 secure => 1,
1271 );
1272  
1273 =head2 C<add_cors(%options)>
1274  
1275 Enables Cross-Origin Resource Sharing (CORS), including automatic handling
1276 of C<OPTIONS> preflight requests, by delegating to L<PAGI::Middleware::CORS>
1277 (from L<PAGI::Tools>) rather than a hand-rolled implementation, see that
1278 module's own documentation for the authoritative behaviour.
1279 Options (matching L<PAGI::Middleware::CORS>'s own names exactly, so they
1280 mean the same thing here as anywhere else in the PAGI ecosystem):
1281  
1282 =over 4
1283  
1284 =item * C<origins> - ArrayRef of allowed origins (default: C<['*']>).
1285  
1286 =item * C<methods> - ArrayRef of allowed HTTP methods
1287 (default: C<['GET','POST','PUT','DELETE','PATCH','OPTIONS']>).
1288  
1289 =item * C<headers> - ArrayRef of allowed request headers
1290 (default: C<['Content-Type','Authorization','X-Requested-With']>).
1291  
1292 =item * C<expose_headers> - ArrayRef of headers to expose to the client
1293 (default: C<[]>).
1294  
1295 =item * C<credentials> - Boolean enabling credentials support (default: C<0>).
1296  
1297 =item * C<max_age> - Preflight cache max age in seconds (default: C<86400>).
1298  
1299 =back
1300  
1301 B<Changed in v0.1.0>: previously this took C<allow_origins>/C<allow_methods>/
1302 C<allow_headers>/C<allow_credentials> and implemented CORS handling directly
1303 in C<PAGI::FastAPI>. It's now a thin wrapper that hands your options straight
1304 to L<PAGI::Middleware::CORS>, so the option names above match that module's
1305 exactly.
1306  
1307 =head2 C<websocket($path, %options)>
1308  
1309 $app->websocket('/ws/{room}',
1310 handler => async sub ($ws, $deps) {
1311 await $ws->accept;
1312 while (defined(my $msg = await $ws->receive_text)) {
1313 await $ws->send_text("Room $ws->path_params->{room}: $msg");
1314 }
1315 }
1316 );
1317  
1318 Registers a WebSocket endpoint at C<$path>. The C<handler> receives a
1319 L<PAGI::WebSocket> instance and an optional HashRef of resolved dependencies.
1320  
1321 =head2 C<add_rate_limit(%options)>
1322  
1323 $app->add_rate_limit(
1324 requests => 100,
1325 window => 60, # 100 requests per 60s
1326 key_cb => sub ($c) { $c->header('X-API-Key') // '127.0.0.1' },
1327 );
1328  
1329 Registers application-wide rate limiting middleware.
1330  
1331 =head2 C<add_bot_protection(%options)>
1332  
1333 $app->add_bot_protection(
1334 difficulty => 3,
1335 secret => $ENV{BOT_PROTECTION_SECRET},
1336 ttl => 300,
1337 );
1338  
1339 Enables Proof-of-Work (PoW) bot protection middleware globally across the
1340 application.
1341  
1342 When configured, incoming requests lacking valid C<x-bot-challenge> and
1343 C<x-bot-nonce> headers are intercepted and rejected with an HTTP
1344 C<401 Unauthorized> response containing a signed challenge token.
1345 Legitimate client browsers solve the cryptographic puzzle in JavaScript and
1346 retry the request automatically.
1347  
1348 Accepts the following named options:
1349  
1350 =over 4
1351  
1352 =item * C<difficulty> (Optional)
1353  
1354 Integer specifying the number of leading zeros required in the calculated
1355 SHA-256 hash collision. Higher values exponentially increase CPU effort for
1356 client devices while keeping server verification costs near-instant.
1357 Defaults to C<3>.
1358  
1359 =item * C<secret> (Optional)
1360  
1361 A secret seed scalar used to generate HMAC signatures for challenges.
1362 B<Must be customised in production environments> to prevent challenge
1363 tampering or forgery. Defaults to C<'change_me_in_production'>.
1364  
1365 =item * C<ttl> (Optional)
1366  
1367 Integer specifying the validity duration of generated challenges in seconds.
1368 Defaults to C<300> (5 minutes).
1369  
1370 =back
1371  
1372 Returns C<$self> to support method chaining.
1373  
1374 =head2 C<sse($generator, %options)>
1375  
1376 $app->get('/api/v1/llm-stream', sub ($c) {
1377 return $c->sse(async sub ($sse) {
1378 await $sse->keepalive(15);
1379  
1380 for my $token ("Hello", " world!", " SSE!") {
1381 await $sse->send_json({ token => $token });
1382 await $c->sleep(0.1);
1383 }
1384  
1385 await $sse->close;
1386 });
1387 });
1388  
1389 Returns a C<PAGI::FastAPI::Response::SSE> response object for real-time
1390 Server-Sent Events (SSE) streaming.
1391  
1392 Accepts an asynchronous code reference C<$generator> receiving a
1393 L<PAGI::SSE> instance, followed by optional named arguments:
1394  
1395 =over 4
1396  
1397 =item * C<headers> (Optional)
1398  
1399 ArrayRef of additional HTTP headers to include in the handshake response
1400 (e.g., C<< headers => [ ['X-Stream-ID' => '123'] ] >>).
1401  
1402 =item * C<status> (Optional)
1403  
1404 Integer status code for the initial HTTP handshake response. Defaults to C<200>.
1405  
1406 =back
1407  
1408 Inside the generator callback, use C<$sse> methods such as C<send_event()>,
1409 C<send_json()>, C<send()>, C<keepalive()>, and C<close()>.
1410  
1411 Returns an instance of L<PAGI::FastAPI::Response::SSE>.
1412  
1413 =head2 C<to_pagi>
1414  
1415 my $pagi_app = $app->to_pagi();
1416  
1417 Compiles the application into a single, executable PAGI-compliant async code
1418 reference ready to be served by an ASGI/PAGI application server (such as
1419 L<PAGI::Server>) or wrapped by L<PAGI::Test::Client>.
1420  
1421 This method:
1422  
1423 =over 4
1424  
1425 =item 1. Builds the core route handling application via C<< $self->to_app() >>.
1426  
1427 =item 2. Wraps the application in reverse order (LIFO - Last-In, First-Out)
1428 with all registered PAGI middleware components so that the first added
1429 middleware is executed first on incoming HTTP requests.
1430  
1431 =back
1432  
1433 Middleware objects are wrapped based on their supported interface:
1434  
1435 =over 4
1436  
1437 =item * B<Objects with C<wrap>:> Invokes C<< $mw->wrap($app) >>.
1438  
1439 =item * B<Objects with C<to_app>:> Invokes C<< $mw->to_app($app) >>.
1440  
1441 =item * B<Code references:> Invokes C<< $mw->($app) >>.
1442  
1443 =back
1444  
1445 Returns an async C<CODEREF> matching the PAGI interface C<< async sub ($scope, $receive, $send) >>.
1446  
1447 B<Example Usage:>
1448  
1449 my $app = PAGI::FastAPI->new();
1450 $app->enable_csrf(secret => 'my-secret');
1451 $app->get('/health', handler => async sub ($c) { { status => 'ok' } });
1452  
1453 # Compile for server deployment or test runner
1454 my $pagi_app = $app->to_pagi();
1455  
1456 =head2 C<to_app()>
1457  
1458 my $pagi_closure = $app->to_app;
1459  
1460 Generates and returns an asynchronous code reference conforming to the PAGI
1461 protocol specification. If sub-applications were registered via
1462 L<mount()|/"C<mount($path_prefix, $pagi_app)>">, C<to_app()> automatically
1463 wraps the routes using L<PAGI::App::URLMap>.
1464  
1465 =head1 AUTO-GENERATED ENDPOINTS
1466  
1467 C<PAGI::FastAPI> automatically registers the following system endpoints:
1468  
1469 =over 4
1470  
1471 =item * C<GET /docs> - Serves an interactive Swagger UI web viewer in the browser.
1472  
1473 =item * C<GET /openapi.json> - Serves the generated OpenAPI 3.1 schema.
1474  
1475 =back
1476  
1477 =head1 FILE UPLOADS
1478  
1479 A request body with a C<Content-Type> of C<multipart/form-data> is parsed
1480 per RFC 7578 and made available through L<PAGI::FastAPI::Context>, the
1481 same way an C<application/x-www-form-urlencoded> body already is:
1482  
1483 =over 4
1484  
1485 =item * L<PAGI::FastAPI::Context/form_data> - the plain text fields.
1486  
1487 =item * L<PAGI::FastAPI::Context/uploaded_files>, L<PAGI::FastAPI::Context/uploaded_file> - the uploaded file parts.
1488  
1489 =back
1490  
1491 $app->post('/profile/avatar', handler => async sub ($c) {
1492 my $caption = $c->form_data('caption');
1493 my $avatar = $c->uploaded_file('avatar');
1494  
1495 unless ($avatar) {
1496 $c->status(422);
1497 return { detail => "Missing 'avatar' file" };
1498 }
1499  
1500 open my $fh, '>:raw', "/var/uploads/$avatar->{filename}" or die $!;
1501 print {$fh} $avatar->{content};
1502 close $fh;
1503  
1504 return { filename => $avatar->{filename}, size => $avatar->{size} };
1505 });
1506  
1507 As with C<application/x-www-form-urlencoded>, C<$c-E<gt>body> and
1508 C<$c-E<gt>param> also see the plain text fields from a multipart body (not
1509 the file parts), C<form_data> exists as a clearer-named alias for that
1510 same data, specifically for form-sourced bodies.
1511  
1512 File contents are currently read fully into memory for the duration of
1513 the request; there is no streaming or on-disk spooling for large uploads,
1514 so plan request body size limits (at your reverse proxy or C<PAGI::Server>
1515 configuration, whichever applies) accordingly.
1516  
1517 =head1 ERROR HANDLING
1518  
1519 When a request fails parameter validation (either query string or JSON/form-urlencoded body),
1520 C<PAGI::FastAPI> short-circuits handler execution and returns C<HTTP 422 Unprocessable Entity>
1521 with a JSON body:
1522  
1523 {
1524 "detail": "Query param 'priority' invalid: Undef did not pass type constraint"
1525 }
1526  
1527 Unmatched routes return C<HTTP 404 Not Found> with C<{"detail": "Not Found"}>.
1528  
1529 The two cases above, and a dependency's own C<< $c->status(...) >>-and-return
1530 convention (see L</AUTHENTICATION AND SECURITY>), cover I<expected> failure
1531 paths. For the separate case of an actual Perl exception (C<die>) escaping
1532 a handler or dependency, e.g. from a database layer or a third-party
1533 module you're calling into, see
1534 L<PAGI::FastAPI::Middleware::ExceptionHandler>, which lets you register a
1535 handler per exception class via C<add_middleware>, with a configurable
1536 fallback for anything unregistered.
1537  
1538 =head1 BACKGROUND TASKS
1539  
1540 For fire-and-forget work that shouldn't make the caller wait, sending a
1541 notification email, writing an audit log entry, warming a cache, use
1542 L<PAGI::FastAPI::Context/background>:
1543  
1544 $app->post('/signup', handler => async sub ($c) {
1545 my $email = $c->body('email');
1546  
1547 $c->background(async sub {
1548 await send_welcome_email($email);
1549 });
1550  
1551 return { status => 'account created' };
1552 });
1553  
1554 The response is sent as soon as the handler returns; the scheduled task
1555 keeps running afterward. Retention is owned by the application, not by
1556 C<$c> or the request: a background task won't be garbage-collected or
1557 dropped before it completes just because the request that scheduled it
1558 has finished, and any still-pending tasks are awaited during PAGI Lifespan
1559 C<shutdown> (before your own C<on_shutdown> callbacks run), so normal
1560 process shutdown doesn't kill one mid-flight. A task that dies is logged
1561 via C<warn> rather than crashing the request that scheduled it or any
1562 other in-flight request.
1563  
1564 See L<PAGI::FastAPI::Context/background> for full details, including how
1565 argument validation works and what a misuse error looks like.
1566  
1567 =head1 EVENT LOOPS: FUTURE::IO IS THE GOAL, IO::ASYNC IS AN IMPLEMENTATION DETAIL
1568  
1569 The PAGI protocol is deliberately silent on which event loop drives it,
1570 that's meant to be an implementation detail of whichever server runs your
1571 app, not part of the application-level contract. L<PAGI::Server>, the
1572 reference server, happens to use L<IO::Async> today, but don't write your
1573 own application code as if that's guaranteed or load-bearing. Prefer
1574 L<Future::IO> for anything loop-driven you write yourself (timers, delays,
1575 periodic tasks) and it keeps working regardless of which backend a given
1576 PAGI server chooses, now or in the future.
1577  
1578 For a periodic task (a heartbeat or a cache sweep, anything you'd otherwise
1579 reach for a timer object for), prefer a self-rescheduling coroutine over
1580 constructing an C<IO::Async::Timer::Periodic> (or any other loop-specific
1581 timer class) directly:
1582  
1583 use Future::AsyncAwait;
1584 use Future::IO;
1585  
1586 async sub heartbeat {
1587 while (1) {
1588 await Future::IO->sleep(30);
1589 ...
1590 }
1591 }
1592 heartbeat()->retain;
1593  
1594 No loop object of your own to construct or own, C<< Future::IO->sleep >>
1595 delegates to whatever backend is already configured in the process, whatever
1596 that turns out to be.
1597  
1598 B<Why "prefer" and not "always," then?> Pragmatically, the L<Future::IO>
1599 ecosystem is still growing, and not every library has caught up to it yet.
1600 You'll sometimes still need a loop-specific integration for a particular
1601 dependency, most commonly L<Mojo::Pg> or anything else built directly on
1602 L<Mojo::IOLoop>, which predates L<Future::IO> and doesn't use it. Treat the
1603 rest of this section as a workaround for that specific, narrower situation,
1604 not as a description of how C<PAGI::FastAPI> itself works, which it doesn't
1605 depend on.
1606  
1607 =head2 Fallback: bridging a Mojo::IOLoop-based dependency
1608  
1609 If your handlers depend on a library on a I<different> event loop from
1610 whatever the PAGI server ends up using, concretely, L<Mojo::Pg> or anything
1611 else on L<Mojo::IOLoop>, calling that library's non-blocking/callback API
1612 will do nothing: separate reactors by default don't service each other. The
1613 symptom is a request or C<on_startup>/C<on_shutdown> handler that just hangs
1614 (and, under L<PAGI::Server>, eventually fails with a lifespan-timeout error)
1615 even though the call you're C<await>-ing looks correct.
1616  
1617 Conversely, calling that library in blocking mode instead (e.g. plain
1618 C<< $pg->db->query(...) >> with no callback) does fire promptly, but freezes
1619 the I<entire> process, every other in-flight request and WebSocket
1620 connection, for the duration of that call, since it's a real synchronous
1621 call with nothing cooperative about it. This is easy to end up with by
1622 accident: the blocking form is the default/simplest way to call most of
1623 these libraries, and it will work correctly in every manual test with one
1624 client before degrading badly under concurrent load.
1625  
1626 The fix, when C<PAGI::Server> happens to be running on L<IO::Async> (which,
1627 again, is an implementation detail you shouldn't assume, but is true of the
1628 reference server today): get L<IO::Async> and the other library's loop onto
1629 the I<same> underlying reactor, so a single running loop drives both.
1630  
1631 =over 4
1632  
1633 =item 1.
1634  
1635 To make L<IO::Async> work with the reactor, one must install the
1636 L<IO::Async::Loop::EV> because it is the one used when one installs L<EV>,
1637 which is done by L<Mojo::IOLoop> automatically. Note that installing plain
1638 L<EV> will not work: the constructor used for L<IO::Async::Loop> will not
1639 automatically prefer C<EV> even if it has been installed.
1640  
1641 =item 2.
1642  
1643 Establish the C<IO_ASYNC_LOOP=EV> variable for the entire process prior to
1644 starting the loop. This is necessary even when the L<IO::Async::Loop> is
1645 created by someone else’s code, for instance, C<pagi-server>.
1646  
1647 IO_ASYNC_LOOP=EV pagi-server your_app.pl
1648  
1649 =item 3.
1650  
1651 Throughout the whole task, utilise the callback/non-blocking variant of the
1652 API from another library (for example, the command C<< $pg->db->query($sql, @binds, $cb) >>),
1653 using a C<Future> to wrap up every call so that it can be executed using
1654 C<await>-ed like any other command. Consult the information available in the
1655 L<Future::AsyncAwait> regarding the routine C<< Future->new >>/C<< $f->done >>/C<< $f->fail >>
1656 for more information.
1657  
1658 =back
1659  
1660 Without both (1) and (2), the two reactors remain separate no matter how
1661 correctly you use C<await> on your side.
1662  
1663 =head1 AUTHENTICATION AND SECURITY
1664  
1665 C<PAGI::FastAPI> has no authentication built in by design, auth needs vary
1666 too much between applications to standardise, so the framework gives you two
1667 general-purpose building blocks instead:
1668  
1669 =over 4
1670  
1671 =item * B<Middleware> (C<add_middleware>), runs for every request, good
1672 for a single global auth check.
1673  
1674 =item * B<Dependencies> (the C<dependencies> route option, or
1675 L<PAGI::FastAPI::Depends>), runs per-route, good for auth that varies
1676 by endpoint (e.g. some routes public, some requiring a token, some
1677 requiring a specific role).
1678  
1679 =back
1680  
1681 A dependency signals an auth failure the same way any other dependency
1682 signals failure: by calling C<< $c->status($code) >> with a code E<gt>=
1683 400 and returning a body HashRef, which short-circuits the route handler
1684 before it runs:
1685  
1686 my $get_current_user = async sub ($c) {
1687 my $token = $c->header('Authorization') // '';
1688 unless ($token eq 'Bearer secret_token') {
1689 $c->status(401);
1690 return { detail => 'Invalid credentials' };
1691 }
1692 return { user_id => 42, role => 'admin' };
1693 };
1694  
1695 Note that a dependency must signal failure this way, not by C<die>ing,
1696 dependency execution is not wrapped in an C<eval>, so a dying dependency
1697 propagates as an uncaught exception instead of a clean HTTP response.
1698  
1699 =head2 Ready-made schemes: PAGI::FastAPI::Security
1700  
1701 Writing the token-extraction and 401/403-response boilerplate above by
1702 hand for every scheme gets repetitive. The companion distribution
1703 L<PAGI::FastAPI::Security> provides ready-made, C<Depends()>-compatible
1704 classes for the common HTTP authentication schemes, modelled on Python
1705 FastAPI's C<fastapi.security> module:
1706  
1707 =over 4
1708  
1709 =item * L<PAGI::FastAPI::Security::HTTPBearer> - C<Authorization: Bearer E<lt>tokenE<gt>>, with a proper C<401> + C<WWW-Authenticate: Bearer> challenge on failure.
1710  
1711 =item * L<PAGI::FastAPI::Security::HTTPBasic> - C<Authorization: Basic E<lt>base64E<gt>>, with a C<401> + C<WWW-Authenticate: Basic realm="...">> challenge.
1712  
1713 =item * L<PAGI::FastAPI::Security::APIKey> - an API key read from a header, query string parameter, or cookie, with a C<403> on failure.
1714  
1715 =item * L<PAGI::FastAPI::Security::OAuth2::PasswordBearer> - OAuth2 bearer-token extraction plus C<token_url>/C<scopes> metadata for future OpenAPI C<securitySchemes> generation.
1716  
1717 =back
1718  
1719 Each scheme only I<extracts> the credential, it deliberately does not
1720 verify it, so you aren't locked into one JWT library, password-hashing
1721 scheme, or identity provider. Pair it with your own verification as a
1722 second dependency:
1723  
1724 use PAGI::FastAPI::Security::HTTPBearer;
1725 use PAGI::FastAPI::Depends qw(Depends);
1726  
1727 my $bearer = PAGI::FastAPI::Security::HTTPBearer->new;
1728  
1729 $app->get('/items',
1730 dependencies => [
1731 $bearer->depends(key => 'token'),
1732 Depends(async sub ($c) {
1733 my $claims = eval { verify_jwt($c->stash->{token}) };
1734 unless ($claims) {
1735 $c->status(401);
1736 return { detail => 'Invalid or expired token' };
1737 }
1738 return $claims;
1739 }, key => 'claims'),
1740 ],
1741 handler => async sub ($c) {
1742 return { user_id => $c->stash->{claims}{sub} };
1743 },
1744 );
1745  
1746 Every scheme also accepts C<auto_error =E<gt> 0>, resolving to C<undef>
1747 instead of short-circuiting, for routes that behave differently for
1748 authenticated vs. anonymous requests. See L<PAGI::FastAPI::Security> for
1749 the full documentation and an end-to-end JWT-verification example.
1750  
1751 =head1 SEE ALSO
1752  
1753 =over 4
1754  
1755 =item * L<PAGI> - Perl Asynchronous Gateway Interface specification.
1756  
1757 =item * L<PAGI::App::URLMap> - Routing middleware for prefix-matching PAGI applications.
1758  
1759 =item * L<PAGI::WebSocket> - Asynchronous WebSocket connection object (from PAGI::Tools) used by C<websocket()> handlers.
1760  
1761 =item * L<PAGI::Middleware::CORS> - CORS middleware (from PAGI::Tools) used by C<add_cors>.
1762  
1763 =item * L<Future::IO> - Loop-agnostic async I/O primitives; see L</EVENT LOOPS: FUTURE::IO IS THE GOAL, IO::ASYNC IS AN IMPLEMENTATION DETAIL>.
1764  
1765 =item * L<PAGI::FastAPI::Context> - Context object passed to route handlers.
1766  
1767 =item * L<PAGI::FastAPI::Depends> - Dependency injection helper.
1768  
1769 =item * L<PAGI::FastAPI::Security> - Ready-made authentication schemes (HTTP Bearer, HTTP Basic, API Key, OAuth2 password bearer) for C<dependencies>.
1770  
1771 =item * L<DBIx::Class::Async> - Async DBIx::Class integration; see F<eg/dbic_async_integration.pl> for a worked example with this framework.
1772  
1773 =item * L<Type::Tiny> - Efficient Perl type constraint system.
1774  
1775 =item * L<Future::AsyncAwait> - Async/Await syntax for Perl.
1776  
1777 =item * L<PAGI::FastAPI::Middleware::BotProtection>
1778  
1779 =item * L<PAGI::FastAPI::BotProtection::ProofOfWork>
1780  
1781 =item * L<PAGI::FastAPI::Response::SSE>
1782  
1783 =item * L<PAGI::SSE>
1784  
1785 =item * L<PAGI::FastAPI::Middleware::RateLimit> - App-level and per-route rate limiting.
1786  
1787 =item * L<PAGI::FastAPI::RateLimit::Driver>, L<PAGI::FastAPI::RateLimit::Driver::Memory> - Pluggable rate-limit storage drivers.
1788  
1789 =item * L<PAGI::FastAPI::Queue> - Pluggable async message queue facade.
1790  
1791 =item * L<PAGI::FastAPI::Queue::Driver>, L<PAGI::FastAPI::Queue::Driver::Memory> - Pluggable queue storage drivers.
1792  
1793 =item * L<PAGI::FastAPI::TypedPath> - Path parameter validation/coercion via C<Depends()>.
1794  
1795 =item * L<PAGI::FastAPI::ResponseModel> - Response shape validation and field filtering.
1796  
1797 =item * L<PAGI::FastAPI::Middleware::ExceptionHandler> - Typed exception-to-handler dispatch.
1798  
1799 =item * L<PAGI::FastAPI::Response::Redirect> - HTTP redirect responses.
1800  
1801 =item * L<PAGI::FastAPI::Response::File> - File-download responses.
1802  
1803 =item * L<PAGI::FastAPI::Cookies> - Request cookie parsing.
1804  
1805 =item * L</FILE UPLOADS> - Parsing C<multipart/form-data> request bodies.
1806  
1807 =item * L</BACKGROUND TASKS> - Fire-and-forget work via C<< $c->background >>.
1808  
1809 =back
1810  
1811 =head1 AUTHOR
1812  
1813 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
1814  
1815 =head1 REPOSITORY
1816  
1817 L<https://github.com/manwar/PAGI-FastAPI>
1818  
1819 =head1 BUGS
1820  
1821 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>.
1822 I will be notified and then you'll automatically be notified of progress on your
1823 bug as I make changes.
1824  
1825 =head1 SUPPORT
1826  
1827 You can find documentation for this module with the perldoc command.
1828  
1829 perldoc PAGI::FastAPI
1830  
1831 You can also look for information at:
1832  
1833 =over 4
1834  
1835 =item * BUG Report
1836  
1837 L<https://github.com/manwar/PAGI-FastAPI/issues>
1838  
1839 =item * Search MetaCPAN
1840  
1841 L<https://metacpan.org/dist/PAGI-FastAPI/>
1842  
1843 =back
1844  
1845 =head1 LICENSE AND COPYRIGHT
1846  
1847 Copyright (C) 2026 Mohammad Sajid Anwar.
1848  
1849 This program is free software; you can redistribute it and/or modify it under
1850 the terms of the Artistic License (2.0).
1851  
1852 =cut
1853  
1854 21 1; # End of PAGI::FastAPI
↑ Summary FastAPI/BotProtection/ProofOfWork.pm »