blib/lib/PAGI/Nano.pm

filter: Statementstmt 99.3% 326 / 328 Branchbran 84.9% 124 / 146 Conditioncond 74.6% 53 / 71 MC/DCmcdc 51.2% 21 / 41 Subroutinesub 100% 77 / 77 Podpod 100% 22 / 22 totaltotal 90.9% 623 / 685 CC 105 SCAR 16.2
CC
105
Cov
92%
_assemble
12.1
__ANON__
11.8
_parse_route_args
11.2
CRAP 5.0
« blib/lib/PAGI/Nano/Context.pm ↑ Summary examples/game-of-life/app.pl »
1 package PAGI::Nano;
2  
3 11 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 11 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 11 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 11 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 11 ▶use Scalar::Util ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 11 ▶use Carp ();
Subroutine BEGIN: called CC=1 SCAR=0.0
9 11 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 11 ▶use PAGI::App::Router;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 11 ▶use PAGI::Response;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 11 ▶use PAGI::Context;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 11 ▶use PAGI::Nano::Context::HTTP;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 11 ▶use PAGI::Nano::Context::WebSocket;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 11 ▶use PAGI::Nano::Context::SSE;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 11 ▶use PAGI::Nano::ServiceRegistry;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 11 our $VERSION = '0.001001';
19  
20 11 ▶use Exporter 'import';
Subroutine BEGIN: called CC=1 SCAR=0.0
21 11 our @EXPORT = qw(
22 app
23 get post put patch del any raw
24 group mount enable
25 startup shutdown
26 static not_found
27 websocket sse
28 name middleware
29 service factory
30 );
31  
32 # Per-route attribute markers. Both sit in the arrow chain between the path and
33 # the handler, in any order; an arrayref is shorthand for middleware().
34 12 ▶sub name { my ($n) = @_; bless { name => $n }, 'PAGI::Nano::Marker::Name' }
Subroutine name: called CC=1 SCAR=0.0
Pod documented
35 4 ▶sub middleware { bless { list => [@_] }, 'PAGI::Nano::Marker::Middleware' }
Subroutine middleware: called CC=1 SCAR=0.0
Pod documented
36  
37 # A unique, immutable token used to ask an assembled Nano app for its flat
38 # name->path table. A parent's mount needs a mounted Nano app's named routes,
39 # but the app is an opaque coderef; calling it with this token alone (instead of
40 # a real ($scope,$receive,$send) triple) returns the table. This is a constant
41 # probe key, not shared mutable state — no per-app registry accumulates, so
42 # building apps leaves nothing behind.
43 11 my $ROUTES_PROBE = \do { my $unused };
44  
45 # A sibling probe token: ask an assembled Nano app whether it declared any
46 # services (true/false), the same way $ROUTES_PROBE asks for the named-route
47 # table. mount() uses this to refuse mounting an app that declared services --
48 # the outermost app owns lifecycle (see mount's shared-state limitation in the
49 # POD), so a mounted app's own services would never get built.
50 11 my $SERVICES_PROBE = \do { my $unused };
51  
52 # A two-argument probe token: ask an assembled Nano app to resolve one named
53 # app-scoped service from its retained registry, without issuing a request.
54 # The registry the startup hook builds is the same object this outer wrapper
55 # closes over, so once lifespan startup has run its values are reachable here.
56 # resolve_service() (a test seam) sends this; a real request is always a
57 # three-element ($scope, $receive, $send) triple, so the two-arg shape never
58 # collides with one.
59 11 my $SERVICE_RESOLVE_PROBE = \do { my $unused };
60  
61 # The dynamically-scoped current collector. app { } localizes this to a fresh
62 # collector for the duration of the block; the verbs register into it. No package
63 # globals leak between app { } invocations, so apps are values: composable,
64 # nestable, testable, many-per-process. This is the same local-scoped technique
65 # PAGI::Middleware::Builder's builder { } uses.
66 11 our $COLLECTOR;
67  
68 # --- the collector ----------------------------------------------------------
69  
70 90 ▶sub app (&) {
Subroutine app: called CC=1 SCAR=0.0
Pod documented
71 90 my ($block) = @_;
72 90 local $COLLECTOR = {
73 router => PAGI::App::Router->new,
74 app_mw => [],
75 startup => [],
76 shutdown => [],
77 named => {}, # name => full path (own routes, group prefixes applied)
78 nano_mounts => [], # { prefix => ..., app => <Nano app coderef> }
79 prefix_stack => [], # active group prefixes, for naming
80 services => [], # [name, builder] pairs, in declaration order
81 };
82 90 $block->();
83 86 return _assemble($COLLECTOR);
84 }
85  
86 86 ▶sub _assemble {
Subroutine _assemble: called CC=12 SCAR=24.9
87 86 my ($collector) = @_;
88 86 my $app = $collector->{router}->to_app;
89  
90 $app = _wrap_with_middleware($app, $collector->{app_mw})
91 86 ▶ if @{$collector->{app_mw}};
Branch: 1 branch
BranchTrueFalseTotal
if @{$collector->{"app_mw"};} 12 74 86
92  
93 86 ▶ my $registry = @{$collector->{services}}
Branch: 1 branch
BranchTrueFalseTotal
@{$collector->{'services'};} ? : 17 69 86
94 ? PAGI::Nano::ServiceRegistry->new
95 : undef;
96  
97 86 ▶ if (@{$collector->{startup}} || @{$collector->{shutdown}} || $registry) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$collector->{"startup"};} or @{$collector->{"shutdown"};} or $registry) 31 55 86
Condition83%5/6
@{$collector->{"startup"};} or @{$collector->{"shutdown"};} or $registry
l!l&&r!l&&!r
151655
@{$collector->{"startup"};} or @{$collector->{"shutdown"};}
l!l&&r!l&&!r
15071
MC/DC66%2/3
@{$collector->{"startup"};} or @{$collector->{"shutdown"};} or $registry
@{$collector->{"startup"};} @{$collector->{"shutdown"};} $registry
Truth table75%3/4
A or B or C
A= @{$collector->{"startup"};}B= @{$collector->{"shutdown"};}C= $registry
ABCresult
1XX1
01X1
0011
0000
98 31 require PAGI::Lifespan;
99 31 my $lifespan = PAGI::Lifespan->new(app => $app);
100 31 ▶ $lifespan->on_startup(_service_startup_hook($registry, $collector->{services}))
Branch: 1 branch
BranchTrueFalseTotal
if $registry 17 14 31
101 if $registry;
102 31 $lifespan->on_startup($_) for @{$collector->{startup}};
103 31 $lifespan->on_shutdown($_) for @{$collector->{shutdown}};
104 31 $app = $lifespan->to_app;
105 }
106  
107 86 ▶ $app = _wrap_with_services($app, $registry) if $registry;
Branch: 1 branch
BranchTrueFalseTotal
if $registry 17 69 86
108  
109 # Flat name -> absolute-path registry: this app's own named routes plus those
110 # of any mounted Nano app (prefixed, recursively via their stored tables).
111 86 my $flat = _build_flat_routes($collector);
112  
113 # Nothing to expose or introspect -> no wrapper needed. A services-only app
114 # (no named routes) still needs one, purely so mount() can probe it and
115 # refuse to mount it (see $SERVICES_PROBE).
116 86 ▶ return $app unless %$flat || $registry;
Branch: 1 branch
BranchTrueFalseTotal
unless %$flat or $registry 59 27 86
Condition100%3/3
%$flat or $registry
l!l&&r!l&&!r
101759
MC/DC100%2/2
%$flat or $registry
%$flat $registry
Truth table100%3/3
A or B
A= %$flatB= $registry
ABresult
1X1
011
000
117  
118 # Outermost wrapper: inject the registry on each request so $c->uri_for can
119 # resolve any name from anywhere. The outermost app wins (//=), so a mounted
120 # app sees the parent's fuller, mount-prefixed registry.
121 27 my $inner = $app;
122 57 ▶ my $wrapped = sub {
Subroutine __ANON__: called CC=11 SCAR=24.7
123 # Introspection: called with a probe token alone, answer it directly (this
124 # is how mount() inspects an opaque mounted app's coderef -- for its named
125 # routes, and for whether it declared services at all). A real request is
126 # always a ($scope, $receive, $send) triple.
127 57 ▶ if (@_ == 1 && ref $_[0]) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 1 and ref $_[0]) 10 47 57
Condition66%2/3
@_ == 1 and ref $_[0]
!ll&&!rl&&r
47010
MC/DC50%1/2
@_ == 1 and ref $_[0]
@_ == 1 ref $_[0]
Truth table66%2/3
A and B
A= @_ == 1B= ref $_[0]
ABresult
0X0
100
111
128 10 ▶ return $flat if $_[0] == $ROUTES_PROBE;
Branch: 1 branch
BranchTrueFalseTotal
if $_[0] == $ROUTES_PROBE 3 7 10
129 7 ▶ return $registry ? 1 : 0 if $_[0] == $SERVICES_PROBE;
Branch: 2 branches
BranchTrueFalseTotal
if $_[0] == $SERVICES_PROBE 7 0 7
$registry ? : 4 3 7
130 }
131 # The service-resolve probe (a test seam) carries the service name as a
132 # second argument. resolve_service only sends it after confirming via
133 # $SERVICES_PROBE that the app declared services, so $registry is defined
134 # here; the registry croaks, naming the service, on an unknown name.
135 47 ▶ if (@_ == 2 && ref $_[0] && $_[0] == $SERVICE_RESOLVE_PROBE) {
Branch: 1 branch
BranchTrueFalseTotal
if (@_ == 2 and ref $_[0] and $_[0] == $SERVICE_RESOLVE_PROBE) 3 44 47
Condition66%4/6
@_ == 2 and ref $_[0] and $_[0] == $SERVICE_RESOLVE_PROBE
!ll&&!rl&&r
4403
@_ == 2 and ref $_[0]
!ll&&!rl&&r
4403
MC/DC33%1/3
@_ == 2 and ref $_[0] and $_[0] == $SERVICE_RESOLVE_PROBE
@_ == 2 ref $_[0] $_[0] == $SERVICE_RESOLVE_PROBE
Truth table50%2/4
A and B and C
A= @_ == 2B= ref $_[0]C= $_[0] == $SERVICE_RESOLVE_PROBE
ABCresult
0XX0
10X0
1100
1111
136 3 return $registry->service($_[1]);
137 }
138 44 my ($scope, $receive, $send) = @_;
139 44 ▶ $scope->{'pagi.nano.routes'} //= $flat if ref $scope eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $scope eq "HASH" 44 0 44
Condition66%2/3
$scope->{"pagi.nano.routes"} //= $flat
l!l&&r!l&&!r
2420
MC/DC0%0/2
$scope->{"pagi.nano.routes"} //= $flat
$scope->{"pagi.nano.routes"} $flat
Truth table66%2/3
A //= B
A= $scope->{"pagi.nano.routes"}B= $flat
ABresult
1X1
011
000
140 44 return $inner->($scope, $receive, $send);
141 27 };
142 27 return $wrapped;
143 }
144  
145 # Ask an opaque app coderef a probe question by calling it with a single
146 # sentinel token instead of a real ($scope, $receive, $send) triple, and
147 # return whatever it answers. A non-Nano app (a plain coderef, a PSGI bridge)
148 # or a Nano app with no probe-answering wrapper either isn't a coderef, dies
149 # outright (caught below), or -- since it IS a coderef, called with one
150 # unexpected scalar arg -- ends up treating the token as a malformed scope and
151 # returns an unready or failed Future; settle that Future here so it isn't
152 # reported destroyed-unhandled, and answer undef either way. This is the one
153 # place that Future-lifecycle handling lives; callers each do their own
154 # one-line coercion of a real answer.
155 21 ▶sub _probe {
Subroutine _probe: called CC=7 SCAR=20.2
156 21 my ($app, $token) = @_;
157 21 ▶ return undef unless ref $app eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $app eq "CODE" 2 19 21
158 19 my $answer = eval { $app->($token) };
159 19 ▶ if (Scalar::Util::blessed($answer) && $answer->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($answer) and $answer->isa("Future")) 9 10 19
Condition66%2/3
builtin::blessed($answer) and $answer->isa("Future")
!ll&&!rl&&r
1009
MC/DC50%1/2
builtin::blessed($answer) and $answer->isa("Future")
builtin::blessed($answer) $answer->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($answer)B= $answer->isa("Future")
ABresult
0X0
100
111
160 9 ▶ $answer->cancel unless $answer->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $answer->is_ready 0 9 9
161 9 ▶ $answer->failure if $answer->is_ready && $answer->is_failed;
Branch: 1 branch
BranchTrueFalseTotal
if $answer->is_ready and $answer->is_failed 9 0 9
Condition33%1/3
$answer->is_ready and $answer->is_failed
!ll&&!rl&&r
009
MC/DC0%0/2
$answer->is_ready and $answer->is_failed
$answer->is_ready $answer->is_failed
Truth table33%1/3
A and B
A= $answer->is_readyB= $answer->is_failed
ABresult
0X0
100
111
162 9 return undef;
163 }
164 10 return $answer;
165 }
166  
167 # Ask an app for its flat Nano name->path table. A Nano app with named routes
168 # answers the probe token with its table; anything else is reported as nameless.
169 8 ▶sub _nano_flat_routes {
Subroutine _nano_flat_routes: called CC=2 SCAR=6.9
170 8 my ($app) = @_;
171 8 my $flat = _probe($app, $ROUTES_PROBE);
172 8 ▶ return ref $flat eq 'HASH' ? $flat : undef;
Branch: 1 branch
BranchTrueFalseTotal
ref $flat eq 'HASH' ? : 3 5 8
173 }
174  
175 # Ask an app whether it declared any services.
176 13 ▶sub _nano_has_services {
Subroutine _nano_has_services: called CC=2 SCAR=6.9
177 13 my ($app) = @_;
178 13 ▶ return _probe($app, $SERVICES_PROBE) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
_probe($app, $SERVICES_PROBE) ? : 4 9 13
179 }
180  
181 # A test seam: resolve one app-scoped service from an assembled Nano app after
182 # lifespan startup, without issuing a request. Given the app coderef and a
183 # service name, it sends the two-argument service-resolve probe and returns the
184 # built value. Only app-scoped services (a plain value or a blessed
185 # non-factory object) fully resolve without a request; a per-request maker or a
186 # factory needs a request context, so for those this returns the raw maker
187 # coderef / factory marker unchanged -- a test needing the per-request value
188 # must drive a request. Croaks if $app is not a coderef or declared no
189 # services, and (via the registry) if the name is unknown.
190 4 ▶sub resolve_service {
Subroutine resolve_service: called CC=3 SCAR=11.0
Pod documented
191 4 my ($app, $name) = @_;
192 4 ▶ Carp::croak('resolve_service: expected an assembled Nano app coderef')
Branch: 1 branch
BranchTrueFalseTotal
unless ref $app eq "CODE" 0 4 4
193 unless ref $app eq 'CODE';
194 4 ▶ Carp::croak('resolve_service: this app declares no services')
Branch: 1 branch
BranchTrueFalseTotal
unless _nano_has_services($app) 1 3 4
195 unless _nano_has_services($app);
196 3 return $app->($SERVICE_RESOLVE_PROBE, $name);
197 }
198  
199 86 ▶sub _build_flat_routes {
Subroutine _build_flat_routes: called CC=4 SCAR=13.9
200 86 my ($collector) = @_;
201 86 my %flat = %{ $collector->{named} };
202 86 for my $m (@{ $collector->{nano_mounts} }) {
203 3 for my $nm (keys %{ $m->{flat} }) {
204 3 ▶ Carp::croak("Duplicate route name '$nm'") if exists $flat{$nm};
Branch: 1 branch
BranchTrueFalseTotal
if exists $flat{$nm} 0 3 3
205 3 $flat{$nm} = $m->{prefix} . $m->{flat}{$nm};
206 }
207 }
208 86 return \%flat;
209 }
210  
211 # Wrap $app in app-wide middleware, mirroring PAGI::App::Router's event-layer
212 # chain (coderef with a $next, or an object with ->wrap).
213 12 ▶sub _wrap_with_middleware {
Subroutine _wrap_with_middleware: called CC=3 SCAR=11.0
214 12 my ($app, $mws) = @_;
215 12 my $chain = $app;
216 12 for my $mw (reverse @$mws) {
217 12 my $next = $chain;
218 12 ▶ if (ref($mw) eq 'CODE') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $mw eq 'CODE') { } 4 8 12
219 17 ▶ $chain = async sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
220 17 my ($scope, $receive, $send) = @_;
221 17 ▶ await $mw->($scope, $receive, $send, async sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
222 # Forward a transformed channel when the middleware passes
223 # one; otherwise continue with the inherited triple. Matches
224 # PAGI::App::Router so app-wide and route/group coderef
225 # middleware behave the same.
226 17 ▶ my ($s, $r, $sd) = @_ ? @_ : ($scope, $receive, $send);
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 7 10 17
227 17 await $next->($s, $r, $sd);
228 17 });
229 4 };
230 }
231 else {
232 # PAGI::Middleware contract: wrap($app) returns the composed app.
233 8 $chain = $mw->wrap($next);
234 }
235 }
236 12 return $chain;
237 }
238  
239 # The lifespan startup hook that eagerly instantiates every declared service,
240 # in declaration order. Wrapped in async sub (rather than run synchronously
241 # during app { }) so a builder's die becomes a failed Future that
242 # PAGI::Lifespan awaits inside its own eval, turning it into
243 # lifespan.startup.failed -- the worker fails at boot, not on a request.
244 17 ▶sub _service_startup_hook {
Subroutine _service_startup_hook: called CC=1 SCAR=0.0
245 17 my ($registry, $services) = @_;
246 17 ▶ return async sub { $registry->_build_all($services) };
Subroutine __ANON__: called CC=1 SCAR=0.0
247 }
248  
249 # Inject the registry onto every request's scope (plain assignment, not //=,
250 # per the design: a mounted Nano app's own services must win for requests
251 # routed into it).
252 17 ▶sub _wrap_with_services {
Subroutine _wrap_with_services: called CC=1 SCAR=0.0
253 17 my ($app, $registry) = @_;
254 33 ▶ return sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
255 33 my ($scope, $receive, $send) = @_;
256 33 ▶ $scope->{'pagi.nano.services'} = $registry if ref $scope eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $scope eq "HASH" 33 0 33
257 33 return $app->($scope, $receive, $send);
258 17 };
259 }
260  
261 # --- HTTP verbs -------------------------------------------------------------
262  
263 87 ▶sub get { _add_route('GET', @_) }
Subroutine get: called CC=1 SCAR=0.0
Pod documented
264 20 ▶sub post { _add_route('POST', @_) }
Subroutine post: called CC=1 SCAR=0.0
Pod documented
265 1 ▶sub put { _add_route('PUT', @_) }
Subroutine put: called CC=1 SCAR=0.0
Pod documented
266 1 ▶sub patch { _add_route('PATCH', @_) }
Subroutine patch: called CC=1 SCAR=0.0
Pod documented
267 2 ▶sub del { _add_route('DELETE', @_) }
Subroutine del: called CC=1 SCAR=0.0
Pod documented
268  
269 1 ▶sub any {
Subroutine any: called CC=3 SCAR=11.3
Pod documented
270 1 my ($path, @rest) = @_;
271 1 my ($mw, $handler, $name) = _parse_route_args(@rest);
272 1 my $wrapped = _wrap_http($handler, $path);
273 1 ▶ $COLLECTOR->{router}->any($path, ($mw ? (_to_router_middleware($mw)) : ()), $wrapped);
Branch: 1 branch
BranchTrueFalseTotal
$mw ? : 0 1 1
274 1 ▶ _register_name($name, $path) if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 0 1 1
275 }
276  
277 111 ▶sub _add_route {
Subroutine _add_route: called CC=3 SCAR=11.0
278 111 my ($method, $path, @rest) = @_;
279 111 my ($mw, $handler, $name) = _parse_route_args(@rest);
280 111 my $wrapped = _wrap_http($handler, $path);
281 110 ▶ $COLLECTOR->{router}->route($method, $path, ($mw ? (_to_router_middleware($mw)) : ()), $wrapped);
Branch: 1 branch
BranchTrueFalseTotal
$mw ? : 4 106 110
282 110 ▶ _register_name($name, $path) if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 12 98 110
283 }
284  
285 # An imperative HTTP route (the escape hatch): the handler gets $c, owns its own
286 # response (no return-value coercion), matches any method, and can drop fully to
287 # raw PAGI via $c->scope / $c->receive / $c->send.
288 5 ▶sub raw {
Subroutine raw: called CC=3 SCAR=11.0
Pod documented
289 5 my ($path, @rest) = @_;
290 5 my ($mw, $handler, $name) = _parse_route_args(@rest);
291 5 my $wrapped = _wrap_raw($handler, $path);
292 5 ▶ $COLLECTOR->{router}->any($path, ($mw ? (_to_router_middleware($mw)) : ()), $wrapped);
Branch: 1 branch
BranchTrueFalseTotal
$mw ? : 1 4 5
293 5 ▶ _register_name($name, $path) if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 0 5 5
294 }
295  
296 # --- grouping, mounting, static --------------------------------------------
297  
298 1 ▶sub group {
Subroutine group: called CC=2 SCAR=7.0
Pod documented
299 1 my ($prefix, @rest) = @_;
300 1 my ($mw, $block) = _parse_route_args(@rest);
301 # The router manages the prefix/middleware stack; our verbs register into the
302 # same router during the block, so they are prefixed and branch-wrapped. We
303 # track the prefix in parallel so named routes record their full path.
304 1 push @{ $COLLECTOR->{prefix_stack} }, $prefix;
305 1 ▶ $COLLECTOR->{router}->group($prefix, ($mw ? (_to_router_middleware($mw)) : ()), sub { $block->() });
Subroutine __ANON__: called CC=1 SCAR=0.2
Branch: 1 branch
BranchTrueFalseTotal
$mw ? : 1 0 1
306 1 pop @{ $COLLECTOR->{prefix_stack} };
307 }
308  
309 9 ▶sub mount {
Subroutine mount: called CC=3 SCAR=11.0
Pod documented
310 9 my ($prefix, $app) = @_;
311 # The outermost app owns lifecycle (the router never forwards lifespan
312 # events into a mount, so a mounted app's own startup/shutdown never run --
313 # see mount's POD); a mounted app that declared services would silently
314 # never build them, so refuse it loudly instead. A service-less mounted
315 # Nano app is fine: it has no registry of its own, so requests routed into
316 # it simply see whatever the outermost app injected onto the scope.
317 9 ▶ Carp::croak("mount '$prefix': a mounted Nano app cannot declare services -- "
Branch: 1 branch
BranchTrueFalseTotal
if _nano_has_services($app) 1 8 9
318 . 'the outermost app owns lifecycle (see "mount" in the PAGI::Nano POD)')
319 if _nano_has_services($app);
320  
321 # Fold a mounted Nano app's named routes into this app's flat registry
322 # (prefixed) so links resolve across the mount. We ask the app for its names
323 # via the probe; non-Nano mounts (PSGI bridges, file servers) report none.
324 8 ▶ if (my $flat = _nano_flat_routes($app)) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $flat = _nano_flat_routes($app)) 3 5 8
325 3 push @{ $COLLECTOR->{nano_mounts} }, { prefix => $prefix, flat => $flat };
326 }
327 8 $COLLECTOR->{router}->mount($prefix, $app);
328 }
329  
330 3 ▶sub static {
Subroutine static: called CC=1 SCAR=0.0
Pod documented
331 3 my ($url, $dir) = @_;
332 3 require PAGI::App::File;
333 3 $COLLECTOR->{router}->mount($url, PAGI::App::File->new(root => $dir));
334 }
335  
336 # --- middleware, lifecycle, 404 --------------------------------------------
337  
338 12 ▶sub enable {
Subroutine enable: called CC=1 SCAR=0.0
Pod documented
339 12 my ($spec, %args) = @_;
340 12 push @{$COLLECTOR->{app_mw}}, _normalize_middleware($spec, %args);
341 }
342  
343 15 ▶sub startup { push @{$COLLECTOR->{startup}}, $_[0] }
Subroutine startup: called CC=1 SCAR=0.0
Pod documented
344 5 ▶sub shutdown { push @{$COLLECTOR->{shutdown}}, $_[0] }
Subroutine shutdown: called CC=1 SCAR=0.0
Pod documented
345  
346 24 ▶sub service {
Subroutine service: called CC=3 SCAR=11.0
Pod documented
347 24 my ($name, $builder) = @_;
348 24 ▶ Carp::croak("service '$name' declared outside an app { } block")
Branch: 1 branch
BranchTrueFalseTotal
unless $PAGI::Nano::COLLECTOR 1 23 24
349 unless $COLLECTOR;
350 Carp::croak("Duplicate service '$name'")
351 23 ▶ if grep { $_->[0] eq $name } @{$COLLECTOR->{services}};
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_->[0] eq $name;} @{$$PAGI::Nano::COLLECTOR{"services"};} 1 22 23
352 22 push @{$COLLECTOR->{services}}, [$name, $builder];
353 }
354  
355 # Marks a service builder's returned coderef as a per-call maker: every
356 # $c->service access invokes it fresh, nothing is memoized. Without this a
357 # returned coderef is a per-request maker (memoized for the request instead).
358 2 ▶sub factory {
Subroutine factory: called CC=2 SCAR=6.9
Pod documented
359 2 my ($cb) = @_;
360 2 ▶ Carp::croak('factory: expected a coderef') unless ref $cb eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $cb eq "CODE" 1 1 2
361 1 return bless $cb, 'PAGI::Nano::Marker::Factory';
362 }
363  
364 11 ▶sub not_found {
Subroutine not_found: called CC=1 SCAR=0.0
Pod documented
365 11 my ($handler) = @_;
366 11 my $http_handler = _wrap_http($handler, '');
367  
368 15 ▶ $COLLECTOR->{router}{not_found} = sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
369 15 my ($scope, $receive, $send) = @_;
370 15 ▶ my $type = $scope->{type} // 'http';
Condition50%1/2
$scope->{"type"} // "http"
l!l
150
MC/DC0%0/1
$scope->{"type"} // "http"
$scope->{"type"}
Truth table50%1/2
A
A= $scope->{"type"}
Aresult
11
00
371  
372 15 ▶ return $http_handler->($scope, $receive, $send)
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "http" 4 11 15
373 if $type eq 'http';
374  
375 11 ▶ Carp::croak("not_found cannot decline unsupported scope type '$type'")
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "sse" or $type eq "websocket" 1 10 11
Condition100%3/3
$type eq "sse" or $type eq "websocket"
l!l&&r!l&&!r
461
MC/DC100%2/2
$type eq "sse" or $type eq "websocket"
$type eq "sse" $type eq "websocket"
Truth table100%3/3
A or B
A= $type eq "sse"B= $type eq "websocket"
ABresult
1X1
011
000
376 unless $type eq 'sse' || $type eq 'websocket';
377  
378 10 ▶ if ($type eq 'websocket'
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "websocket" and not exists +($scope->{"extensions"} // {})->{"websocket.http.response"}) 1 9 10
Condition100%5/5
$type eq "websocket" and not exists +($scope->{"extensions"} // {})->{"websocket.http.response"}
!ll&&!rl&&r
451
$scope->{"extensions"} // {}
l!l
51
MC/DC100%2/2
$type eq "websocket" and not exists +($scope->{"extensions"} // {})->{"websocket.http.response"}
$type eq "websocket" $scope->{"extensions"}
Truth table100%3/3
A and not(B)
A= $type eq "websocket"B= $scope->{"extensions"}
ABresult
0X0
110
101
379 && !exists(($scope->{extensions} // {})->{'websocket.http.response'})) {
380 1 return $send->({ type => 'websocket.close' });
381 }
382  
383 9 ▶ my $prefix = $type eq 'sse'
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'sse' ? : 4 5 9
384 ? 'sse.http.response'
385 : 'websocket.http.response';
386 9 my $adapted_send = _translate_not_found_send(
387 $send,
388 $prefix,
389 body_only_protocol => $type,
390 );
391 9 return $http_handler->($scope, $receive, $adapted_send);
392 11 };
393 }
394  
395 9 ▶sub _translate_not_found_send {
Subroutine _translate_not_found_send: called CC=1 SCAR=0.0
396 9 my ($send, $prefix, %opts) = @_;
397 20 ▶ return sub {
Subroutine __ANON__: called CC=8 SCAR=21.1
398 20 my ($event) = @_;
399 20 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
200
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
400 20 ▶ Carp::croak("not_found emitted unsupported event '$type'")
Branch: 1 branch
BranchTrueFalseTotal
unless $type eq "http.response.start" or $type eq "http.response.body" 0 20 20
Condition66%2/3
$type eq "http.response.start" or $type eq "http.response.body"
l!l&&r!l&&!r
9110
MC/DC0%0/2
$type eq "http.response.start" or $type eq "http.response.body"
$type eq "http.response.start" $type eq "http.response.body"
Truth table66%2/3
A or B
A= $type eq "http.response.start"B= $type eq "http.response.body"
ABresult
1X1
011
000
401 unless $type eq 'http.response.start'
402 || $type eq 'http.response.body';
403  
404 20 ▶ if ($opts{body_only_protocol} && $type eq 'http.response.body'
Branch: 1 branch
BranchTrueFalseTotal
if ($opts{"body_only_protocol"} and $type eq "http.response.body" and exists $event->{"file"} || exists $event->{"fh"}) 4 16 20
Condition88%8/9
$opts{"body_only_protocol"} and $type eq "http.response.body" and exists $event->{"file"} || exists $event->{"fh"}
!ll&&!rl&&r
974
$opts{"body_only_protocol"} and $type eq "http.response.body"
!ll&&!rl&&r
0911
exists $event->{"file"} or exists $event->{"fh"}
l!l&&r!l&&!r
227
MC/DC75%3/4
$opts{"body_only_protocol"} and $type eq "http.response.body" and exists $event->{"file"} || exists $event->{"fh"}
$opts{"body_only_protocol"} $type eq "http.response.body" exists $event->{"file"} exists $event->{"fh"}
Truth table80%4/5
A and B and C or D
A= $opts{"body_only_protocol"}B= $type eq "http.response.body"C= exists $event->{"file"}D= exists $event->{"fh"}
ABCDresult
0XXX0
10XX0
11000
111X1
11011
405 && (exists $event->{file} || exists $event->{fh})) {
406 4 Carp::croak("$opts{body_only_protocol} not_found responses support "
407 . 'body bytes, not file/fh bodies');
408 }
409  
410 16 my %translated = %$event;
411 16 $translated{type} =~ s/^http\.response/$prefix/;
412 16 return $send->(\%translated);
413 9 };
414 }
415  
416 # --- WebSocket / SSE (imperative; not coerced) ------------------------------
417  
418 8 ▶sub websocket {
Subroutine websocket: called CC=3 SCAR=11.3
Pod documented
419 8 my ($path, @rest) = @_;
420 8 my ($mw, $handler, $name) = _parse_route_args(@rest);
421 8 my $wrapped = _wrap_socket($handler, $path);
422 8 ▶ $COLLECTOR->{router}->websocket($path, ($mw ? (_to_router_middleware($mw)) : ()), $wrapped);
Branch: 1 branch
BranchTrueFalseTotal
$mw ? : 0 8 8
423 8 ▶ _register_name($name, $path) if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 0 8 8
424 }
425  
426 11 ▶sub sse {
Subroutine sse: called CC=3 SCAR=11.0
Pod documented
427 11 my ($path, @rest) = @_;
428 11 my ($mw, $handler, $name) = _parse_route_args(@rest);
429 11 my $wrapped = _wrap_socket($handler, $path);
430 11 ▶ $COLLECTOR->{router}->sse($path, ($mw ? (_to_router_middleware($mw)) : ()), $wrapped);
Branch: 1 branch
BranchTrueFalseTotal
$mw ? : 1 10 11
431 11 ▶ _register_name($name, $path) if defined $name;
Branch: 1 branch
BranchTrueFalseTotal
if defined $name 0 11 11
432 }
433  
434 12 ▶sub _register_name {
Subroutine _register_name: called CC=2 SCAR=6.9
435 12 my ($name, $path) = @_;
436 12 my $full = join('', @{ $COLLECTOR->{prefix_stack} }, $path);
437 Carp::croak("Duplicate route name '$name'")
438 12 ▶ if exists $COLLECTOR->{named}{$name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $PAGI::Nano::COLLECTOR->{"named"}{$name} 1 11 12
439 11 $COLLECTOR->{named}{$name} = $full;
440 }
441  
442 # --- handler wrapping -------------------------------------------------------
443  
444 # Extract a route's :placeholder names in path order so they can be passed to the
445 # handler signature after $c. Supports :name, {name}, {name:regex}, and *splat.
446 146 ▶sub _placeholder_names {
Subroutine _placeholder_names: called CC=4 SCAR=14.1
447 146 my ($path) = @_;
448 146 my @names;
449 146 ▶ while ($path =~ /\{(\w+)(?::[^}]+)?\}|\*(\w+)|:(\w+)/g) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path =~ /\{(\w+)(?::[^}]+)?\}|\*(\w+)|:(\w+)/g) 27 146 173
450 27 ▶ push @names, defined $1 ? $1 : defined $2 ? $2 : $3;
Branch: 2 branches
BranchTrueFalseTotal
defined $1 ? : 0 27 27
defined $2 ? : 0 27 27
451 }
452 146 return @names;
453 }
454  
455 # A route declared without a handler coderef is a loud build-time error (caught
456 # while app { } runs) rather than a "Not a CODE reference" 500 at first request.
457 147 ▶sub _assert_handler {
Subroutine _assert_handler: called CC=2 SCAR=6.9
458 147 my ($handler, $path) = @_;
459 147 ▶ Carp::croak("route '$path' is missing a handler (expected a coderef)")
Branch: 1 branch
BranchTrueFalseTotal
unless ref $handler eq "CODE" 1 146 147
460 unless ref $handler eq 'CODE';
461 }
462  
463 # Error handling uses Future combinators rather than try/catch so the core runs
464 # on Perl back to 5.18. A die in the ->then callback (e.g. an uncoercible return)
465 # becomes a failed Future and is handled by ->else.
466 123 ▶sub _wrap_http {
Subroutine _wrap_http: called CC=1 SCAR=0.0
467 123 my ($handler, $path) = @_;
468 123 _assert_handler($handler, $path);
469 122 my @names = _placeholder_names($path);
470 120 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
471 120 my ($scope, $receive, $send) = @_;
472 120 my $c = PAGI::Nano::Context::HTTP->new($scope, $receive, $send);
473 120 my @params = map { $scope->{path_params}{$_} } @names;
474  
475 112 ▶ return _invoke_handler($handler, $c, \@params)->then(sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
476 112 my ($res) = @_;
477 112 return $c->respond(_coerce($res));
478 15 ▶ })->else(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
479 15 my ($err) = @_;
480 # The "featherweight die-a-respond-able" escape hatch: a thrown
481 # respond-able value is sent as-is; anything else propagates and
482 # becomes a 500 (rendered by enable 'ErrorHandler' or the server).
483 15 ▶ return $c->respond($err)
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($err) and $err->can("respond") 5 10 15
Condition66%2/3
builtin::blessed($err) and $err->can("respond")
!ll&&!rl&&r
1005
MC/DC50%1/2
builtin::blessed($err) and $err->can("respond")
builtin::blessed($err) $err->can("respond")
Truth table66%2/3
A and B
A= builtin::blessed($err)B= $err->can("respond")
ABresult
0X0
100
111
484 if Scalar::Util::blessed($err) && $err->can('respond');
485 10 return Future->fail($err);
486 120 });
487 122 };
488 }
489  
490 # Imperative handler wrapping: build the context, pass the ordered path params,
491 # and return the handler's future as-is — no return-value coercion. Shared by the
492 # WebSocket/SSE verbs and the raw escape hatch; they differ only in which context
493 # they vend.
494 24 ▶sub _wrap_imperative {
Subroutine _wrap_imperative: called CC=1 SCAR=0.0
495 24 my ($handler, $path, $make_context) = @_;
496 24 _assert_handler($handler, $path);
497 24 my @names = _placeholder_names($path);
498 21 ▶ return sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
499 21 my ($scope, $receive, $send) = @_;
500 21 my $c = $make_context->($scope, $receive, $send);
501 21 my @params = map { $scope->{path_params}{$_} } @names;
502 21 return _invoke_handler($handler, $c, \@params);
503 24 };
504 }
505  
506 19 ▶sub _wrap_socket {
Subroutine _wrap_socket: called CC=1 SCAR=0.0
507 19 my ($handler, $path) = @_;
508 19 return _wrap_imperative($handler, $path, \&_socket_context);
509 }
510  
511 5 ▶sub _wrap_raw {
Subroutine _wrap_raw: called CC=1 SCAR=0.0
512 5 my ($handler, $path) = @_;
513 6 ▶ return _wrap_imperative($handler, $path, sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
514 6 PAGI::Nano::Context::HTTP->new(@_);
515 5 });
516 }
517  
518 # Vend the Nano WebSocket/SSE context (which carries uri_for) by scope type,
519 # falling back to the stock polymorphic context for anything else.
520 15 ▶sub _socket_context {
Subroutine _socket_context: called CC=4 SCAR=14.6
521 15 my ($scope, $receive, $send) = @_;
522 15 ▶ my $type = $scope->{type} // '';
Condition50%1/2
$scope->{"type"} // ""
l!l
150
MC/DC0%0/1
$scope->{"type"} // ""
$scope->{"type"}
Truth table50%1/2
A
A= $scope->{"type"}
Aresult
11
00
523 15 ▶ return PAGI::Nano::Context::WebSocket->new($scope, $receive, $send)
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "websocket" 7 8 15
524 if $type eq 'websocket';
525 8 ▶ return PAGI::Nano::Context::SSE->new($scope, $receive, $send)
Branch: 1 branch
BranchTrueFalseTotal
if $type eq "sse" 8 0 8
526 if $type eq 'sse';
527 0 return PAGI::Context->new($scope, $receive, $send);
528 }
529  
530 # Call a handler and normalize its result to a Future, capturing a synchronous
531 # die from a non-async handler as a failed Future.
532 141 ▶sub _invoke_handler {
Subroutine _invoke_handler: called CC=4 SCAR=13.9
533 141 my ($handler, $c, $params) = @_;
534 141 my $res = eval { $handler->($c, @$params) };
535 141 ▶ return Future->fail($@) if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 5 136 141
536 136 ▶ return $res if Scalar::Util::blessed($res) && $res->isa('Future');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($res) and $res->isa("Future") 42 94 136
Condition100%3/3
builtin::blessed($res) and $res->isa("Future")
!ll&&!rl&&r
712342
MC/DC100%2/2
builtin::blessed($res) and $res->isa("Future")
builtin::blessed($res) $res->isa("Future")
Truth table100%3/3
A and B
A= builtin::blessed($res)B= $res->isa("Future")
ABresult
0X0
100
111
537 94 return Future->done($res);
538 }
539  
540 # JSON encoder for coerced bodies. convert_blessed lets any object with a
541 # TO_JSON method serialize itself (e.g. a domain value nested in the response).
542 11 my $JSON = JSON::MaybeXS->new(utf8 => 1, canonical => 1, convert_blessed => 1);
543  
544 # The coercion table.
545 112 ▶sub _coerce {
Subroutine _coerce: called CC=7 SCAR=19.5
546 112 my ($res) = @_;
547 112 ▶ if (Scalar::Util::blessed($res)) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($res)) 38 74 112
548 38 ▶ return $res if $res->can('respond'); # a PAGI::Response (sent as-is)
Branch: 1 branch
BranchTrueFalseTotal
if $res->can("respond") 37 1 38
549 1 Carp::croak('PAGI::Nano handler returned an uncoercible '
550 . ref($res) . ' object');
551 }
552  
553 74 my $ref = ref $res;
554 74 ▶ if ($ref eq 'HASH' || $ref eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ref eq "HASH" or $ref eq "ARRAY") 66 8 74
Condition100%3/3
$ref eq "HASH" or $ref eq "ARRAY"
l!l&&r!l&&!r
5978
MC/DC100%2/2
$ref eq "HASH" or $ref eq "ARRAY"
$ref eq "HASH" $ref eq "ARRAY"
Truth table100%3/3
A or B
A= $ref eq "HASH"B= $ref eq "ARRAY"
ABresult
1X1
011
000
555 66 return PAGI::Response->send_raw(
556 $JSON->encode($res),
557 content_type => 'application/json; charset=utf-8',
558 );
559 }
560  
561 8 ▶ Carp::croak("PAGI::Nano handler returned an uncoercible $ref reference")
Branch: 1 branch
BranchTrueFalseTotal
if $ref 1 7 8
562 if $ref;
563  
564 7 ▶ Carp::croak('PAGI::Nano handler returned no response '
Branch: 1 branch
BranchTrueFalseTotal
unless defined $res 1 6 7
565 . '(did the handler forget to return a value?)')
566 unless defined $res;
567  
568 6 return PAGI::Response->text($res);
569 }
570  
571 # --- middleware normalization ----------------------------------------------
572  
573 # Turn a middleware spec (name string, instance, or coderef) into something the
574 # router/chain accepts: a coderef ($scope,$receive,$send,$next) or an object
575 # with ->wrap. Names are resolved the way `enable` resolves them.
576 19 ▶sub _normalize_middleware {
Subroutine _normalize_middleware: called CC=6 SCAR=18.0
577 19 my ($spec, %args) = @_;
578 19 ▶ return $spec if ref($spec) eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
if ref $spec eq "CODE" 10 9 19
579 9 ▶ return $spec if Scalar::Util::blessed($spec) && $spec->can('wrap');
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($spec) and $spec->can("wrap") 1 8 9
Condition66%2/3
builtin::blessed($spec) and $spec->can("wrap")
!ll&&!rl&&r
801
MC/DC50%1/2
builtin::blessed($spec) and $spec->can("wrap")
builtin::blessed($spec) $spec->can("wrap")
Truth table66%2/3
A and B
A= builtin::blessed($spec)B= $spec->can("wrap")
ABresult
0X0
100
111
580  
581 8 ▶ Carp::croak('Invalid middleware: expected a name, instance, or coderef')
Branch: 1 branch
BranchTrueFalseTotal
if ref $spec 0 8 8
582 if ref $spec;
583  
584 # A leading ^ escapes the default prefix: use the rest of the name verbatim.
585 8 ▶ my $class = $spec =~ /^\^/ ? substr($spec, 1) : "PAGI::Middleware::$spec";
Branch: 1 branch
BranchTrueFalseTotal
$spec =~ /^\^/ ? : 2 6 8
586 8 my $file = ($class =~ s{::}{/}gr) . '.pm';
587 8 require $file;
588 8 return $class->new(%args);
589 }
590  
591 # Adapt middleware for PAGI::App::Router, whose contract is a factory coderef
592 # ($factory->($app) returns the wrapped app) or an object with ->wrap. Nano's
593 # coderef middleware shape is ($scope, $receive, $send, $next); wrap each in a
594 # factory preserving those semantics (including transformed-channel forwarding).
595 7 ▶sub _to_router_middleware {
Subroutine _to_router_middleware: called CC=2 SCAR=6.9
596 7 my ($mws) = @_;
597 return [ map {
598 7 my $mw = $_;
599 ref($mw) eq 'CODE'
600 6 ▶ ? sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
601 6 my ($app) = @_;
602 6 ▶ return async sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
603 6 my ($scope, $receive, $send) = @_;
604 6 ▶ await $mw->($scope, $receive, $send, async sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
605 6 ▶ my ($s, $r, $sd) = @_ ? @_ : ($scope, $receive, $send);
Branch: 1 branch
BranchTrueFalseTotal
@_ ? : 4 2 6
606 6 await $app->($s, $r, $sd);
607 6 });
608 6 };
609 }
610 7 ▶ : $mw
Branch: 1 branch
BranchTrueFalseTotal
ref $mw eq 'CODE' ? : 6 1 7
611 } @$mws ];
612 }
613  
614 7 ▶sub _normalize_middleware_list {
Subroutine _normalize_middleware_list: called CC=1 SCAR=0.0
615 7 my ($specs) = @_;
616 7 return [ map { _normalize_middleware($_) } @$specs ];
617 }
618  
619 # Parse the arguments between a verb's path and its handler: an arrayref or a
620 # middleware() marker contributes middleware; a name() marker names the route;
621 # the bare trailing coderef is the handler. Markers may appear in any order.
622 # Returns (\@normalized_middleware | undef, $handler, $name | undef).
623 137 ▶sub _parse_route_args {
Subroutine _parse_route_args: called CC=10 SCAR=24.1
624 137 my @args = @_;
625 137 my ($handler, $name, @mw);
626 137 for my $arg (@args) {
627 155 my $ref = ref $arg;
628 155 ▶ if ($ref eq 'CODE') {
Branch: 4 branches
BranchTrueFalseTotal
if ($ref eq 'CODE') { } 136 19 155
elsif ($ref eq 'ARRAY') { } 3 16 19
elsif (builtin::blessed($arg) and $arg->isa('PAGI::Nano::Marker::Middleware')) { } 4 12 16
elsif (builtin::blessed($arg) and $arg->isa('PAGI::Nano::Marker::Name')) { } 12 0 12
629 136 $handler = $arg;
630 }
631 elsif ($ref eq 'ARRAY') {
632 3 push @mw, @$arg;
633 }
634 ▶ elsif (Scalar::Util::blessed($arg)
Condition66%2/3
builtin::blessed($arg) and $arg->isa("PAGI::Nano::Marker::Middleware")
!ll&&!rl&&r
0124
MC/DC50%1/2
builtin::blessed($arg) and $arg->isa("PAGI::Nano::Marker::Middleware")
builtin::blessed($arg) $arg->isa("PAGI::Nano::Marker::Middleware")
Truth table66%2/3
A and B
A= builtin::blessed($arg)B= $arg->isa("PAGI::Nano::Marker::Middleware")
ABresult
0X0
100
111
635 && $arg->isa('PAGI::Nano::Marker::Middleware')) {
636 4 push @mw, @{ $arg->{list} };
637 }
638 ▶ elsif (Scalar::Util::blessed($arg)
Condition33%1/3
builtin::blessed($arg) and $arg->isa("PAGI::Nano::Marker::Name")
!ll&&!rl&&r
0012
MC/DC0%0/2
builtin::blessed($arg) and $arg->isa("PAGI::Nano::Marker::Name")
builtin::blessed($arg) $arg->isa("PAGI::Nano::Marker::Name")
Truth table33%1/3
A and B
A= builtin::blessed($arg)B= $arg->isa("PAGI::Nano::Marker::Name")
ABresult
0X0
100
111
639 && $arg->isa('PAGI::Nano::Marker::Name')) {
640 12 $name = $arg->{name};
641 }
642 else {
643 0 ▶ Carp::croak('Unexpected route argument: '
Branch: 1 branch
BranchTrueFalseTotal
defined $arg ? : 0 0 0
644 . (defined $arg ? $arg : 'undef'));
645 }
646 }
647 137 ▶ my $mw = @mw ? _normalize_middleware_list(\@mw) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@mw ? : 7 130 137
648 137 return ($mw, $handler, $name);
649 }
650  
651 11 1;
652  
653 =encoding utf8
654  
655 =head1 NAME
656  
657 PAGI::Nano - A compact micro-framework front door over PAGI-Tools
658  
659 =head1 SYNOPSIS
660  
661 use v5.40;
662 use experimental 'signatures';
663 use PAGI::Nano;
664  
665 my $app = app {
666 startup async sub ($state) { $state->{tasks} = [] };
667 shutdown async sub ($state) { warn "served " . @{$state->{tasks}} . " tasks\n" };
668  
669 enable 'GZip';
670 static '/assets' => 'public/';
671  
672 get '/' => sub ($c) { 'PAGI::Nano' }; # String -> text/plain
673 any '/health' => sub ($c) { { ok => 1 } }; # hashref -> JSON
674  
675 group '/api' => ['RateLimit'] => sub {
676 get '/tasks' => sub ($c) { $c->state->{tasks} };
677 get '/tasks/:id' => sub ($c, $id) {
678 $c->state->{tasks}[$id - 1] // $c->json({ error => 'not found' }, status => 404);
679 };
680 post '/tasks' => async sub ($c) {
681 my $attrs = await $c->params->required(
682 'title', +{ tags => [] },
683 sub ($c, $missing) { $c->json({ error => 'missing', fields => $missing }, status => 400) },
684 );
685 my $tasks = $c->state->{tasks};
686 push @$tasks, { id => @$tasks + 1, %$attrs };
687 $c->json($tasks->[-1], status => 201);
688 };
689 };
690  
691 sse '/events' => async sub ($c) {
692 my $s = $c->sse;
693 for my $n (1 .. 5) { await $s->send("tick $n") }
694 };
695  
696 not_found sub ($c) { $c->json({ error => 'no such route' }, status => 404) };
697 };
698  
699 $app; # run: pagi-server app.pl
700  
701 =head1 DESCRIPTION
702  
703 C<PAGI::Nano> is a compact micro-framework for demos and small apps (roughly
704 under 20 endpoints). "Nano" means I<compact>, not I<few features>: routing,
705 middleware, lifecycle, static files, streaming, WebSocket, SSE, and request
706 shaping are all in scope. The win is that a whole small app fits on one screen
707 and reads top-to-bottom.
708  
709 Three principles shape it:
710  
711 =over 4
712  
713 =item * B<The DSL produces a value, not global state.> C<app { ... }> runs a
714 block-scoped collector (the same C<local>-scoped technique
715 L<PAGI::Middleware::Builder>'s C<builder { }> uses) and I<returns> an assembled
716 PAGI app. The result is composable (C<mount> it), nestable, testable, and
717 many-per-process.
718  
719 =item * B<No silo, no cliff.> The DSL is thin sugar over the exact PAGI objects
720 you would use by hand — L<PAGI::Context>, L<PAGI::Response>,
721 L<PAGI::App::Router>, the builder, L<PAGI::Lifespan>, L<PAGI::App::File>. You can
722 drop to raw PAGI mid-app, and a Nano app already I<is> a PAGI app.
723  
724 =item * B<Anti-magic.> The only convention is return-value coercion, which is
725 local and visible at the call site. C<@INC> is never touched.
726  
727 =back
728  
729 Strong-parameters (C<< $c->params >>) shape input; validation and persistence
730 are out of scope (use Valiant downstream and your own model).
731  
732 =head1 EXPORTS
733  
734 All of the following are exported by default:
735 C<app>, C<get>, C<post>, C<put>, C<patch>, C<del>, C<any>, C<raw>, C<group>,
736 C<mount>, C<enable>, C<startup>, C<shutdown>, C<static>, C<not_found>,
737 C<websocket>, C<sse>, C<name>, C<middleware>, C<service>, C<factory>.
738  
739 =head1 THE COLLECTOR
740  
741 =head2 app
742  
743 my $app = app { ... };
744  
745 Runs the block with a fresh, dynamically-scoped collector, registering whatever
746 the verbs declare, then assembles and returns the composed PAGI app: the router,
747 wrapped in any C<enable>'d middleware, wrapped in L<PAGI::Lifespan> if
748 C<startup>/C<shutdown> were declared. No package globals; nesting is supported.
749  
750 =head1 ROUTING
751  
752 =head2 get / post / put / patch / del
753  
754 get '/path' => sub ($c) { ... };
755 post '/path' => [\@middleware] => sub ($c) { ... };
756 del '/thing/:id' => sub ($c, $id) { ... };
757  
758 Each registers a route for the named HTTP method. C<del> is spelled without an
759 C<e> so it does not shadow Perl's C<delete>. An optional arrayref of middleware
760 may precede the handler.
761  
762 A route's C<:placeholders> become the handler's parameters, in path order, after
763 C<$c>: C<< get '/u/:uid/p/:pid' => sub ($c, $uid, $pid) { ... } >>. The supported
764 placeholder forms are C<:name>, C<{name}>, C<{name:regex}>, and C<*splat>.
765 C<< $c->path_param('name') >> remains available.
766  
767 Per-route attributes are given as markers in the same arrow chain, before the
768 handler, in any order: L</name> names the route for link generation, and
769 L</middleware> (or the C<[...]> shorthand) scopes middleware to it:
770  
771 get '/users/:id' => name('user') => middleware('Auth') => sub ($c, $id) { ... };
772 get '/users/:id' => name('user') => ['Auth'] => sub ($c, $id) { ... };
773  
774 =head2 any
775  
776 any '/health' => sub ($c) { ... };
777  
778 Like the verbs above, but matches every HTTP method.
779  
780 =head2 raw
781  
782 raw '/stream' => async sub ($c) {
783 await $c->respond($c->json({ ok => 1 })); # send your own response
784 };
785  
786 The imperative escape hatch. Unlike C<get>/C<post>/etc., a C<raw> handler is
787 B<not> coerced: it receives C<$c> (and any path placeholders) and is responsible
788 for sending its own response — via C<< $c->respond >>, C<< $c->response->stream >>,
789 or the raw protocol. Its return value is ignored. C<raw> matches every method
790 (the handler dispatches on C<< $c->method >> if it cares).
791  
792 This is where you drop to raw PAGI mid-app: C<< $c->scope >>, C<< $c->receive >>,
793 and C<< $c->send >> give the underlying C<($scope, $receive, $send)>, so a C<raw>
794 handler can do anything a hand-written PAGI app can — emit custom send events for
795 a middleware to render, stream a bespoke protocol, and so on — while still getting
796 path-parameter and middleware sugar. Because it is uncoerced, B<a raw handler that
797 never sends a response leaves the request hanging>; that is the handler's
798 responsibility.
799  
800 =head2 group
801  
802 group '/api' => [\@middleware] => sub { ...nested verbs... };
803  
804 Registers the nested verbs under a shared path prefix and (optional)
805 branch-shared middleware. Groups nest.
806  
807 =head2 mount
808  
809 mount '/admin' => $app_or_coercible;
810  
811 Nests any PAGI app (coerced via C<to_app>) under a prefix — another Nano app, a
812 L<PAGI::Endpoint::Router>, or any coderef app.
813  
814 The router does not forward lifespan events to mounted apps, so a mounted Nano
815 app's own C<startup>/C<shutdown> do not run; the outermost app owns lifecycle and
816 mounted children share its C<state>. Write mountable apps to initialize their
817 slice of state defensively. For the same reason, C<mount> croaks if the app
818 being mounted declared any L</SERVICES> — a service-less mounted app is fine,
819 and transparently shares the outermost app's services.
820  
821 =head1 RESPONSES AND COERCION
822  
823 A handler returns a value, which Nano coerces:
824  
825 =over 4
826  
827 =item * a L<PAGI::Response> (anything that C<can('respond')>) — sent as-is.
828  
829 =item * a hashref or arrayref — C<application/json> (with C<convert_blessed>, so
830 nested objects with a C<TO_JSON> method serialize themselves).
831  
832 =item * a defined non-ref scalar — C<text/plain>.
833  
834 =item * C<undef> / a bare C<return;> — a B<loud error> (becomes a 500): this
835 catches the forgot-to-return bug rather than sending a silent empty 200.
836  
837 =item * any other reference — an error.
838  
839 =back
840  
841 A handler that uses C<await> (for C<< $c->params >>, streaming, etc.) must be
842 declared C<async sub>, which requires C<use Future::AsyncAwait> in the file
843 alongside C<use PAGI::Nano>. For explicit control, the inherited context sugar
844 C<< $c->json($data, %opts) >>, C<< $c->text >>, C<< $c->html >>,
845 C<< $c->redirect >> returns L<PAGI::Response> values.
846  
847 A thrown respond-able value is sent as-is (the basis of C<required>'s on-missing
848 callback); any other exception propagates and becomes a 500, which
849 C<enable 'ErrorHandler'> can render.
850  
851 =head1 MIDDLEWARE
852  
853 =head2 enable
854  
855 enable 'GZip';
856 enable 'Session', secret => '...';
857  
858 Adds app-wide, event-layer middleware. A bare name (C<'GZip'>) resolves to
859 C<PAGI::Middleware::GZip>; a leading C<^> (C<'^My::MW'>) escapes the prefix.
860 Instances and coderefs (with the C<< ($scope, $receive, $send, $next) >>
861 signature) are also accepted. Route- and group-scoped middleware use the
862 C<[\@middleware]> form and are normalized the same way.
863  
864 =head1 NAMED ROUTES AND LINKS
865  
866 =head2 name
867  
868 get '/users/:id' => name('user') => sub ($c, $id) { ... };
869  
870 A marker that names the route. Names form a single flat namespace across the
871 whole app (including mounted sub-apps); a duplicate name is a loud error.
872  
873 =head2 middleware
874  
875 get '/x' => middleware('Auth', $coderef) => sub ($c) { ... };
876  
877 A marker that scopes the given middleware to the route (the C<[...]> arrayref is
878 the everyday shorthand). Each element is a middleware spec — a name, an instance,
879 or a coderef — resolved the same way L</enable> resolves a name. Unlike
880 C<enable>, the route forms take no per-name constructor arguments: every element
881 is its own spec, so to configure a name-based middleware, pre-instantiate it
882 (C<< [ PAGI::Middleware::Session->new(secret => '...') ] >>) and pass the
883 instance.
884  
885 =head2 C<< $c->uri_for >>
886  
887 $c->uri_for('user', { id => 5 }); # /users/5
888 $c->uri_for('user', { id => 5 }, { tab => 'a' }); # /users/5?tab=a
889  
890 Builds the URL for a named route, substituting path placeholders and appending
891 an optional query string. Because Nano injects one flat name registry onto the
892 request scope, C<uri_for> resolves B<any> name from B<anywhere> — including
893 across a C<mount> in both directions: a mounted app can link to a name defined
894 in its parent, and the parent can link to a name defined in the mount (paths are
895 returned with the mount prefix applied). C<uri_for> is available on the context
896 for every protocol — HTTP, WebSocket, and SSE handlers alike (see
897 L<PAGI::Nano::Context>).
898  
899 =head1 LIFECYCLE AND SHARED STATE
900  
901 =head2 startup / shutdown
902  
903 startup async sub ($state) { ... };
904 shutdown async sub ($state) { ... };
905  
906 Sugar over L<PAGI::Lifespan>. C<$state> is the shared, app-lifetime state
907 hashref; handlers read it via C<< $c->state >>.
908  
909 =head1 SERVICES
910  
911 =head2 service / factory
912  
913 service schema => sub ($app) {
914 return $schema; # app-scoped singleton
915 };
916  
917 service params => sub ($app) {
918 return sub ($ctx) { # per-request maker
919 return Params->new($ctx->params);
920 };
921 };
922  
923 service stamp => sub ($app) {
924 return factory sub ($ctx) { # per-call maker
925 return Stamp->new;
926 };
927 };
928  
929 A tiny three-scope registry. C<service NAME =E<gt> BUILDER> declares a
930 service; C<< $c->service(NAME) >> resolves it at request time, on every
931 context flavor (HTTP, WebSocket, and SSE alike). The scope is chosen by what
932 the builder I<returns>, not by any option:
933  
934 =over 4
935  
936 =item * a plain value (including any blessed object, other than a C<factory>
937 marker below) — an B<app-scoped singleton>. Every C<< $c->service >> access,
938 on every request, returns this same value.
939  
940 =item * an unblessed coderef — a B<per-request maker>. The first
941 C<< $c->service >> access in a request calls it with the context and memoizes
942 the result for the rest of that request (for a WebSocket or SSE context,
943 "request" means that connection); later accesses in the same
944 request/connection return the memoized value.
945  
946 =item * C<< factory sub { ... } >> — a B<per-call maker>. Every access calls
947 it with the context; nothing is memoized, so every C<< $c->service >> call
948 gets a fresh object.
949  
950 =back
951  
952 Builders run B<eagerly, once per worker, in declaration order>, at lifespan
953 startup — registered before any user C<startup> hook (see L</startup /
954 shutdown>). A builder that dies fails lifespan startup, so a misconfigured
955 service stops the worker at boot rather than surfacing on a customer's first
956 request. Builders are B<synchronous>: a builder written as C<async sub>
957 returns a Future, and returning a Future croaks at startup — for deferred
958 construction return a per-request maker (a plain coderef) or a C<factory>
959 maker instead.
960  
961 Builders B<compose>: each builder receives the registry itself (C<$app> in
962 the examples above), and C<< $app->service(NAME) >> returns an
963 already-built service, letting a later service incorporate an earlier one.
964 Because building is eager and ordered, asking for a service declared later in
965 the same C<app { }> block — or not declared at all — croaks, naming the
966 service: services can only depend on what has already been built.
967  
968 Since a plain returned coderef always means "per-request maker", a service
969 that itself needs to hand out a fixed callback (not build one per request)
970 uses the per-request-maker shape as an escape hatch, returning the same
971 closure every time:
972  
973 service on_tick => sub ($app) {
974 my $callback = sub { ... };
975 return sub ($ctx) { return $callback };
976 };
977  
978 There is no teardown pairing in v1: a service that owns a resource needing
979 cleanup should register its own C<shutdown> hook. There are also no generated
980 accessors — always C<< $c->service('schema') >>, never C<< $c->schema >>.
981  
982 B<Services and C<mount>: the outermost app owns lifecycle.> Just as a mounted
983 Nano app's own C<startup>/C<shutdown> never run (see L</mount> — the router
984 never forwards lifespan events into a mount), a mounted Nano app cannot
985 declare services at all: C<mount> croaks immediately if the app being mounted
986 declared any, since their builders would never get a chance to run. A mounted
987 Nano app that declares no services of its own is unaffected — it has no
988 registry, so C<< $c->service >> inside it simply resolves against whatever the
989 outermost app injected onto the scope, the same instances the rest of the app
990 sees. If lifespan forwarding to mounted apps is ever added, per-mount services
991 can be revisited.
992  
993 =head2 resolve_service
994  
995 my $app = app { service schema => sub { $dbh } };
996 my $client = PAGI::Test::Client->new(app => $app, lifespan => 1);
997 $client->start; # runs the builders
998 my $schema = PAGI::Nano::resolve_service($app, 'schema');
999  
1000 A test seam. C<< $c->service >> is only reachable from inside a request handler,
1001 so a test that wants to assert on an app-scoped service — or hand it to code
1002 under test — otherwise has to route a request just to reach it, or reconstruct
1003 the service by hand. C<resolve_service> (not exported; call it fully qualified)
1004 reaches the service directly: given the assembled app coderef and a name, it
1005 returns the built value, B<after lifespan startup has run> (drive it with
1006 C<< PAGI::Test::Client->start >>, or a lifespan C<startup> event by hand). The
1007 registry the startup hook builds is retained on the app coderef, so no request
1008 is involved.
1009  
1010 It resolves B<app-scoped> services (a plain value or a blessed non-C<factory>
1011 object). A per-request maker or a C<factory> is constructed against a request
1012 context, which does not exist here, so for those C<resolve_service> returns the
1013 raw maker coderef / factory marker rather than a per-request instance — a test
1014 needing the per-request value must drive a real request. Resolving an unknown
1015 name croaks (naming it), as does calling it on an app that declared no services.
1016  
1017 =head1 STATIC FILES AND CUSTOM 404
1018  
1019 =head2 static
1020  
1021 static '/assets' => 'public/';
1022  
1023 Serves files under C<public/> at C</assets/*> (wraps L<PAGI::App::File>).
1024  
1025 =head2 not_found
1026  
1027 not_found sub ($c) { ... };
1028  
1029 Sets the router's not-found handler; it is wrapped and coerced like any other
1030 HTTP handler. Write the handler as an ordinary HTTP-shaped Nano response.
1031 For an unmatched HTTP request its response events pass through unchanged; for
1032 an SSE scope Nano translates them to C<sse.http.response.*> decline events.
1033 Buffered and streamed byte bodies work for translated responses, but
1034 file-backed C<file>/C<fh> body events are not part of the SSE or WebSocket
1035 decline event families and croak loudly. Return bytes from the handler instead
1036 of C<send_file>.
1037  
1038 An unmatched WebSocket can carry the custom status, headers, and body only when
1039 the server advertises the C<websocket.http.response> extension. Nano then emits
1040 C<websocket.http.response.*> events.
1041  
1042 Without the extension Nano does not invoke the custom handler. It sends a
1043 pre-accept C<websocket.close>, asking the server to provide the portable,
1044 body-less 403 denial response.
1045  
1046 =head1 STREAMING, WEBSOCKET, SSE
1047  
1048 WebSocket and SSE handlers are imperative: like L</raw>, they own the connection,
1049 return nothing, and are B<not> coerced. Both take the same
1050 C<< PATH => [\@middleware] => $handler >> shape as the HTTP verbs (middleware and
1051 L</name> markers are optional and may appear in any order).
1052  
1053 =head2 websocket
1054  
1055 websocket '/echo' => async sub ($c) {
1056 my $ws = $c->websocket;
1057 await $ws->accept;
1058 await $ws->each_json(async sub ($msg) { await $ws->send_json({ echo => $msg }) });
1059 };
1060  
1061 Registers a WebSocket route. The handler gets the L<PAGI::Nano::Context::WebSocket>
1062 context (C<< $c->websocket >> for the socket API, C<< $c->uri_for >> for links).
1063  
1064 =head2 sse
1065  
1066 sse '/events' => async sub ($c) {
1067 my $s = $c->sse;
1068 for my $n (1 .. 5) { await $s->send("tick $n") }
1069 };
1070  
1071 Registers a Server-Sent Events route. The handler gets the
1072 L<PAGI::Nano::Context::SSE> context; C<< $c->send >> is the C<sse.send>
1073 convenience, and C<< $c->raw_send >> reaches the raw channel for custom event
1074 types.
1075  
1076 Streaming uses the response writer and request body stream:
1077  
1078 post '/upper' => async sub ($c) {
1079 my $in = $c->req->body_stream;
1080 $c->response->stream(async sub ($w) {
1081 while (defined(my $chunk = await $in->next_chunk)) { await $w->write(uc $chunk) }
1082 await $w->close;
1083 });
1084 };
1085  
1086 =head1 STRONG PARAMETERS
1087  
1088 C<< $c->params >> returns a request-bound L<PAGI::StructuredParameters::Request>
1089 selecting the source by content-type. The terminal C<permitted> (filter to a
1090 whitelist) and C<required> (whitelist plus a mandatory on-missing callback) are
1091 awaited, because reading a request body is asynchronous. The chainable
1092 C<namespace> (scope the rules to a key prefix) and C<flatten_array_value>
1093 (control array flattening for form sources) shape parsing before them. See
1094 L<PAGI::Nano::Context::HTTP> and L<PAGI::StructuredParameters> for the full rule
1095 grammar.
1096  
1097 =head1 RUNNING
1098  
1099 A Nano app is an ordinary PAGI app (a coderef). Run a single file with
1100 C<pagi-server app.pl>, where the file's last expression is the app. For a real
1101 app, use a modulino at C<lib/MyApp.pm> whose C<to_app> returns C<app { ... }>,
1102 and run C<pagi-server -Ilib lib/MyApp.pm>. Nano never touches C<@INC>.
1103  
1104 =head1 SEE ALSO
1105  
1106 L<PAGI::Tools>, L<PAGI::StructuredParameters>, L<PAGI::Nano::Context::HTTP>,
1107 L<PAGI::App::Router>, L<PAGI::Lifespan>, L<PAGI::Nano::ServiceRegistry>.
1108  
1109 =head1 AUTHOR
1110  
1111 John Napiorkowski C<< <jjnapiork@cpan.org> >>
1112  
1113 =head1 COPYRIGHT & LICENSE
1114  
1115 Copyright 2026, John Napiorkowski. This library is free software; you can
1116 redistribute it and/or modify it under the same terms as Perl itself.
1117  
1118 =cut
« blib/lib/PAGI/Nano/Context.pm ↑ Summary examples/game-of-life/app.pl »