blib/lib/PAGI/Server.pm

filter: Statementstmt 77.2% 927 / 1200 Branchbran 58.4% 380 / 650 Conditioncond 56.9% 208 / 365 MC/DCmcdc 33.9% 69 / 203 Subroutinesub 79.3% 92 / 116 Podpod 83.3% 10 / 12 totaltotal 66.2% 1686 / 2546 CC 514 SCAR 43.6
CC
514
Cov
68%
_listen_multiworker
549.4
configure
130.8
_pause_accepting
110.0
CRAP 78.3
↑ Summary blib/lib/PAGI/Server/AsyncFile.pm »
1 package PAGI::Server;
2 151 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 151 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 151 our $VERSION = '0.002011';
6  
7 # Future::XS support - opt-in via PAGI_FUTURE_XS=1 environment variable
8 # Must be loaded before Future to take effect, so we check env var in BEGIN
9 # Note: We declare these without initialization so BEGIN block values persist
10 151 our ($FUTURE_XS_AVAILABLE, $FUTURE_XS_ENABLED);
11 BEGIN {
12 151 ▶ $FUTURE_XS_AVAILABLE = eval { require Future::XS; 1 } ? 1 : 0;
Subroutine BEGIN: called CC=5 SCAR=23.1
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Future::XS; 1 } } ? : 0 151 151
13 151 $FUTURE_XS_ENABLED = 0; # Default to disabled
14  
15 151 ▶ if ($ENV{PAGI_FUTURE_XS}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($ENV{'PAGI_FUTURE_XS'}) { } 0 151 151
elsif ($PAGI::Server::FUTURE_XS_AVAILABLE) { } 0 151 151
16 0 ▶ if ($FUTURE_XS_AVAILABLE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($PAGI::Server::FUTURE_XS_AVAILABLE) { } 0 0 0
17 # Future::XS is already loaded from the availability check
18 0 $FUTURE_XS_ENABLED = 1;
19 } else {
20 0 die <<"END_FUTURE_XS_ERROR";
21 PAGI_FUTURE_XS=1 set but Future::XS is not installed.
22  
23 To install Future::XS:
24 cpanm Future::XS
25  
26 Or unset the PAGI_FUTURE_XS environment variable.
27 END_FUTURE_XS_ERROR
28 }
29 } elsif ($FUTURE_XS_AVAILABLE) {
30 # Available but not requested - unload it
31 0 delete $INC{'Future/XS.pm'};
32 }
33 }
34  
35 151 ▶use parent 'IO::Async::Notifier';
Subroutine BEGIN: called CC=1 SCAR=0.0
36 151 ▶use IO::Async::Listener;
Subroutine BEGIN: called CC=1 SCAR=0.0
37 151 ▶use IO::Async::Stream;
Subroutine BEGIN: called CC=1 SCAR=0.0
38 151 ▶use IO::Async::Loop;
Subroutine BEGIN: called CC=1 SCAR=0.0
39 151 ▶use IO::Async::Timer::Periodic;
Subroutine BEGIN: called CC=1 SCAR=0.0
40 151 ▶use IO::Socket::INET;
Subroutine BEGIN: called CC=1 SCAR=0.0
41 151 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
42 151 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
43  
44 151 ▶use Scalar::Util qw(weaken refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
45 151 ▶use Socket qw(sockaddr_family unpack_sockaddr_in unpack_sockaddr_un AF_UNIX AF_INET);
Subroutine BEGIN: called CC=1 SCAR=0.0
46 151 ▶use POSIX ();
Subroutine BEGIN: called CC=1 SCAR=0.0
47  
48 151 ▶use PAGI::Server::AppNormalizer ();
Subroutine BEGIN: called CC=1 SCAR=0.0
49 151 ▶use PAGI::Server::Connection;
Subroutine BEGIN: called CC=1 SCAR=0.0
50 151 ▶use PAGI::Server::EventValidator;
Subroutine BEGIN: called CC=1 SCAR=0.0
51 151 ▶use PAGI::Server::Protocol::HTTP1;
Subroutine BEGIN: called CC=1 SCAR=0.0
52  
53  
54 # Check TLS module availability (cached at load time for banner display)
55 151 our $TLS_AVAILABLE;
56 BEGIN {
57 151 ▶ $TLS_AVAILABLE = eval {
Subroutine BEGIN: called CC=2 SCAR=7.0
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require IO::Async::SSL; require IO::Socket::SSL; 1 } } ? : 151 0 151
58 151 require IO::Async::SSL;
59 151 require IO::Socket::SSL;
60 151 1;
61 } ? 1 : 0;
62 }
63  
64 7 ▶sub has_tls { return $TLS_AVAILABLE }
Subroutine has_tls: called CC=1 SCAR=0.0
Pod undocumented
65  
66 # Check HTTP/2 module availability (cached at load time)
67 151 our $HTTP2_AVAILABLE;
68 BEGIN {
69 151 ▶ $HTTP2_AVAILABLE = eval {
Subroutine BEGIN: called CC=2 SCAR=7.1
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require PAGI::Server::Protocol::HTTP2; 'PAGI::Server::Protocol::HTTP2'->available } } ? : 151 0 151
70 151 require PAGI::Server::Protocol::HTTP2;
71 151 PAGI::Server::Protocol::HTTP2->available;
72 } ? 1 : 0;
73 }
74  
75 14 ▶sub has_http2 { return $HTTP2_AVAILABLE }
Subroutine has_http2: called CC=1 SCAR=0.0
Pod undocumented
76  
77 # Windows doesn't support Unix signals - signal handling is conditional
78 151 ▶use constant WIN32 => $^O eq 'MSWin32';
Subroutine BEGIN: called CC=1 SCAR=0.0
79  
80 =encoding utf8
81  
82 =head1 NAME
83  
84 PAGI::Server - PAGI Reference Server Implementation
85  
86 =head1 SYNOPSIS
87  
88 use IO::Async::Loop;
89 use PAGI::Server;
90  
91 # If using Future::IO libraries (Async::Redis, SSE->every, etc.)
92 # load the IO::Async implementation BEFORE loading them:
93 use Future::IO::Impl::IOAsync;
94  
95 my $loop = IO::Async::Loop->new;
96  
97 my $server = PAGI::Server->new(
98 app => \&my_pagi_app,
99 host => '127.0.0.1',
100 port => 5000,
101 );
102  
103 $loop->add($server);
104 $server->listen->get; # Start accepting connections
105  
106 See L</LOOP INTEROPERABILITY> for details on Future::IO configuration.
107  
108 =head1 DESCRIPTION
109  
110 PAGI::Server is a reference implementation of a PAGI-compliant HTTP server.
111 It supports HTTP/1.1, WebSocket, and Server-Sent Events (SSE) as defined
112 in the PAGI specification. It prioritizes spec compliance and code clarity
113 over performance optimization. It serves as the canonical reference for how
114 PAGI servers should behave.
115  
116 =head1 PROTOCOL SUPPORT
117  
118 B<Currently supported:>
119  
120 =over 4
121  
122 =item * HTTP/1.1 (full support including chunked encoding, trailers, keepalive)
123  
124 =item * HTTP/2 (B<experimental> - via nghttp2, h2 over TLS and h2c cleartext)
125  
126 =item * WebSocket (RFC 6455, including over HTTP/2 via RFC 8441)
127  
128 =item * Server-Sent Events (SSE, including over HTTP/2)
129  
130 =back
131  
132 B<Not yet implemented:>
133  
134 =over 4
135  
136 =item * HTTP/3 (QUIC) - Under consideration
137  
138 =back
139  
140 For HTTP/2, see L</ENABLING HTTP/2 SUPPORT (EXPERIMENTAL)>.
141  
142 =head1 UNIX DOMAIN SOCKET SUPPORT (EXPERIMENTAL)
143  
144 B<This feature is experimental.> The API is subject to change in future
145 releases. Please report issues at L<https://github.com/jjn1056/pagi-server/issues>.
146  
147 Unix domain sockets provide efficient local communication between a reverse
148 proxy (nginx, HAProxy, etc.) and PAGI::Server running on the same machine.
149 They bypass the TCP/IP stack entirely, reducing latency and overhead compared
150 to connecting over C<127.0.0.1>.
151  
152 =head2 When to Use Unix Sockets
153  
154 =over 4
155  
156 =item * B<Behind a reverse proxy> — nginx or HAProxy on the same host handles
157 TLS termination, HTTP/2 negotiation, and static files, forwarding dynamic
158 requests to PAGI over a Unix socket.
159  
160 =item * B<Benchmarks> — frameworks like TechEmpower FrameworkBenchmarks use
161 Unix sockets to eliminate network variable from application benchmarks.
162  
163 =item * B<Microservice IPC> — services on the same host communicate without
164 network overhead.
165  
166 =back
167  
168 B<When NOT to use:> If clients connect over the network (remote browsers,
169 API consumers), use TCP. Unix sockets only accept connections from processes
170 on the same machine.
171  
172 =head2 Basic Usage
173  
174 B<Programmatic:>
175  
176 my $server = PAGI::Server->new(
177 app => $app,
178 socket => '/tmp/pagi.sock',
179 );
180  
181 B<CLI:>
182  
183 pagi-server --socket /tmp/pagi.sock ./app.pl
184  
185 B<With workers:>
186  
187 pagi-server --socket /tmp/pagi.sock --workers 4 ./app.pl
188  
189 In multi-worker mode, the parent process creates the Unix socket and all
190 worker processes inherit the file descriptor via C<fork()>. The kernel
191 distributes incoming connections across workers.
192  
193 =head2 How It Works
194  
195 =over 4
196  
197 =item 1. On startup, any existing file at the socket path is removed (stale
198 socket cleanup).
199  
200 =item 2. The server creates and binds a C<SOCK_STREAM> Unix domain socket
201 at the specified path using C<IO::Socket::UNIX> (multi-worker) or
202 C<IO::Async::Listener> with C<< family => 'unix' >> (single-worker).
203  
204 =item 3. If C<socket_mode> is set, C<chmod()> is called immediately after
205 binding to set the file permissions.
206  
207 =item 4. In multi-worker mode, the parent creates the socket before forking.
208 Workers inherit the listening fd and each runs its own C<IO::Async::Listener>
209 wrapping the inherited handle.
210  
211 =item 5. On graceful shutdown (SIGTERM/SIGINT), the socket file is unlinked
212 by both the single-worker C<shutdown()> path and the multi-worker
213 C<_initiate_multiworker_shutdown()> path.
214  
215 =back
216  
217 =head2 nginx Configuration
218  
219 B<Basic upstream:>
220  
221 upstream pagi_backend {
222 server unix:/var/run/myapp/pagi.sock;
223 keepalive 32;
224 }
225  
226 server {
227 listen 80;
228 server_name myapp.example.com;
229  
230 location / {
231 proxy_pass http://pagi_backend;
232  
233 # Required for upstream keepalive:
234 proxy_http_version 1.1;
235 proxy_set_header Connection "";
236  
237 # Forward client info (since PAGI can't see it over Unix socket):
238 proxy_set_header Host $host;
239 proxy_set_header X-Real-IP $remote_addr;
240 proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
241 proxy_set_header X-Forwarded-Proto $scheme;
242 }
243 }
244  
245 B<Important:> The C<keepalive> directive is critical for performance. Without
246 it, nginx opens a new Unix socket connection for every request.
247 C<proxy_http_version 1.1> and C<proxy_set_header Connection ""> are required
248 for keepalive to work.
249  
250 B<With TLS termination at nginx:>
251  
252 server {
253 listen 443 ssl http2;
254 ssl_certificate /etc/ssl/myapp.crt;
255 ssl_certificate_key /etc/ssl/myapp.key;
256  
257 location / {
258 proxy_pass http://pagi_backend;
259 # ... same proxy headers as above
260 }
261 }
262  
263 nginx handles TLS and HTTP/2 with clients, then speaks plain HTTP/1.1 to
264 PAGI over the Unix socket. This is the recommended production pattern.
265  
266 =head2 Socket Permissions and Security
267  
268 By default, the socket file inherits permissions from the process umask.
269 Use C<socket_mode> to set explicit permissions:
270  
271 # CLI
272 pagi-server --socket /var/run/myapp/pagi.sock --socket-mode 0660 ./app.pl
273  
274 # Programmatic
275 PAGI::Server->new(
276 app => $app,
277 socket => '/var/run/myapp/pagi.sock',
278 socket_mode => 0660,
279 );
280  
281 B<Production recommendations:>
282  
283 =over 4
284  
285 =item * B<Use a dedicated directory>, not C</tmp/>. Directories like
286 C</var/run/myapp/> or C</run/myapp/> prevent symlink attacks and provide
287 an additional permission layer.
288  
289 =item * B<Use C<0660> with a shared group.> Create a group (e.g., C<myapp>)
290 that both the application user and the nginx user belong to:
291  
292 sudo groupadd myapp
293 sudo usermod -aG myapp www-data # nginx user
294 sudo usermod -aG myapp myappuser # app user
295 sudo mkdir -p /var/run/myapp
296 sudo chown myappuser:myapp /var/run/myapp
297 sudo chmod 0750 /var/run/myapp
298  
299 =item * B<Use systemd C<RuntimeDirectory>> for automatic directory management:
300  
301 # /etc/systemd/system/myapp.service
302 [Service]
303 User=myappuser
304 Group=myapp
305 RuntimeDirectory=myapp
306 RuntimeDirectoryMode=0750
307 ExecStart=/usr/local/bin/pagi-server \
308 --socket /run/myapp/pagi.sock \
309 --socket-mode 0660 \
310 --workers 4 \
311 /opt/myapp/app.pl
312  
313 systemd creates C</run/myapp/> on service start and cleans it up on stop.
314  
315 =back
316  
317 =head2 TLS Over Unix Sockets
318  
319 TLS can be used over Unix sockets, though this is unusual — normally the
320 reverse proxy handles TLS termination. When TLS is configured on a Unix
321 socket listener, the server logs an info-level note suggesting reverse proxy
322 TLS termination instead.
323  
324 The combination is allowed because it has legitimate uses (encrypted
325 inter-container communication, compliance requirements). All major ASGI
326 servers (Uvicorn, Hypercorn, Granian) also allow it.
327  
328 =head2 HTTP/2 Over Unix Sockets
329  
330 h2c (HTTP/2 cleartext) works over Unix sockets. This is useful for gRPC
331 backends or reverse proxies that support HTTP/2 to upstreams (e.g., Envoy).
332 Note that nginx does B<not> currently support HTTP/2 to upstream backends
333 (except for gRPC via C<grpc_pass>).
334  
335 =head2 Scope Differences
336  
337 For Unix socket connections, the PAGI scope differs from TCP connections:
338  
339 =over 4
340  
341 =item * B<C<client> is absent> — Unix sockets have no peer IP address or
342 port. The C<client> key is omitted entirely from the scope hashref (not set
343 to C<undef>). This is spec-compliant: the PAGI specification marks C<client>
344 as optional.
345  
346 =item * B<C<server> is C<[$socket_path, undef]>>> — instead of C<[$host, $port]>.
347  
348 =back
349  
350 B<Middleware implications:> Any middleware that accesses C<< $scope->{client} >>
351 must check C<< exists $scope->{client} >> first. For client IP identification
352 behind a reverse proxy, use C<X-Forwarded-For> or C<X-Real-IP> headers
353 instead of C<< $scope->{client} >>. The C<PAGI::Middleware::XForwardedFor>
354 middleware (if available) handles this automatically.
355  
356 B<Access log:> Unix socket connections log C<unix> as the client IP in the
357 access log instead of an IP address.
358  
359 =head2 Stale Socket Cleanup
360  
361 If a socket file already exists at the configured path (e.g., from a previous
362 crash), it is automatically removed before binding. This matches the behavior
363 of Starman, Gunicorn, Uvicorn, and other production servers. The socket file
364 is also removed during graceful shutdown (SIGTERM/SIGINT).
365  
366 If the server is killed with SIGKILL (C<kill -9>), the socket file will
367 B<not> be cleaned up. It will be removed on the next startup.
368  
369 =head1 MULTI-LISTENER SUPPORT (EXPERIMENTAL)
370  
371 B<This feature is experimental.> The API is subject to change in future
372 releases.
373  
374 A single PAGI::Server instance can listen on multiple endpoints
375 simultaneously. This is useful for:
376  
377 =over 4
378  
379 =item * B<TCP for health checks + Unix socket for app traffic> — load
380 balancers probe a TCP port while nginx uses the Unix socket.
381  
382 =item * B<Multiple TCP ports> — serve different interfaces on different ports.
383  
384 =item * B<Gradual migration> — listen on both old and new ports during
385 a transition.
386  
387 =back
388  
389 =head2 Programmatic API
390  
391 my $server = PAGI::Server->new(
392 app => $app,
393 listen => [
394 { host => '0.0.0.0', port => 8080 },
395 { socket => '/tmp/pagi.sock', socket_mode => 0660 },
396 ],
397 );
398  
399 Each spec in the C<listen> array is a hashref with either C<< { host, port } >>
400 for TCP or C<< { socket } >> (with optional C<socket_mode>) for Unix sockets.
401  
402 B<Note:> Per-listener TLS configuration is not yet supported. TLS is configured
403 server-wide via the C<ssl> constructor option and applies to all TCP listeners.
404 Unix socket listeners behind a reverse proxy do not need TLS — the proxy handles
405 TLS termination.
406  
407 =head2 CLI
408  
409 The C<--listen> flag is repeatable. The server auto-detects TCP vs Unix
410 socket: values containing C<:> are parsed as C<host:port>, everything else
411 is treated as a Unix socket path.
412  
413 # TCP + Unix socket
414 pagi-server --listen 0.0.0.0:8080 --listen /tmp/pagi.sock ./app.pl
415  
416 # Multiple TCP ports
417 pagi-server --listen 0.0.0.0:8080 --listen 0.0.0.0:8443 ./app.pl
418  
419 # With workers
420 pagi-server --listen 0.0.0.0:8080 --listen /tmp/pagi.sock -w 4 ./app.pl
421  
422 # IPv6
423 pagi-server --listen [::1]:5000 ./app.pl
424  
425 C<--listen> is B<mutually exclusive> with C<--host>, C<--port>, and
426 C<--socket>. C<--socket-mode> applies to all Unix socket listeners when
427 using C<--listen>.
428  
429 =head2 How It Works
430  
431 =over 4
432  
433 =item * In B<single-worker mode>, one C<IO::Async::Listener> is created per
434 endpoint. All listeners share the same event loop and connection handler.
435  
436 =item * In B<multi-worker mode>, the parent process creates all listening
437 sockets (Unix and TCP) before forking. Workers inherit all file descriptors
438 and create their own C<IO::Async::Listener> for each inherited socket.
439  
440 =item * The C<reuseport> option applies only to TCP listeners. Unix socket
441 listeners always use the shared-socket model (parent creates, workers inherit).
442  
443 =item * On shutdown, all listeners are stopped and all Unix socket files are
444 cleaned up.
445  
446 =back
447  
448 =head2 Accessors
449  
450 $server->port; # Bound port of first TCP listener, or undef
451 $server->socket_path; # Path of first Unix socket listener, or undef
452 $server->listeners; # Arrayref of all listener specs
453  
454 =head2 Backward Compatibility
455  
456 The existing C<host>/C<port> constructor options continue to work exactly
457 as before. They are internally normalized to a single-element listener
458 array. The C<socket> option is similarly sugar for a single Unix socket
459 listener. Only C<listen> enables true multi-listener mode.
460  
461 =head1 SYSTEMD SOCKET ACTIVATION (EXPERIMENTAL)
462  
463 B<This feature is experimental.> The API is subject to change in future
464 releases.
465  
466 PAGI::Server supports systemd socket activation, which allows systemd to
467 create and hold listening sockets on behalf of the server. This enables
468 zero-downtime restarts: when the server is restarted, the kernel continues
469 to queue incoming connections on the socket without refusing or dropping
470 them, even during the gap between the old process exiting and the new one
471 starting.
472  
473 Benefits of systemd socket activation:
474  
475 =over 4
476  
477 =item * B<Zero-downtime restarts> — the kernel queues connections during restarts
478  
479 =item * B<Atomic permission handling> — systemd creates the socket as root, then drops privileges before exec
480  
481 =item * B<On-demand activation> — the server is started automatically when the first connection arrives
482  
483 =back
484  
485 =head2 Basic Setup
486  
487 Create two systemd unit files: a C<.socket> unit that describes the socket,
488 and a C<.service> unit for the server itself.
489  
490 B<TCP socket (C</etc/systemd/system/pagi.socket>):>
491  
492 [Unit]
493 Description=PAGI Application Socket
494  
495 [Socket]
496 ListenStream=0.0.0.0:8080
497 Accept=no
498  
499 [Install]
500 WantedBy=sockets.target
501  
502 B<Unix socket (C</etc/systemd/system/pagi.socket>):>
503  
504 [Unit]
505 Description=PAGI Application Socket
506  
507 [Socket]
508 ListenStream=/run/pagi/app.sock
509 SocketMode=0660
510 SocketUser=www-data
511 SocketGroup=www-data
512 Accept=no
513  
514 [Install]
515 WantedBy=sockets.target
516  
517 B<Service unit (C</etc/systemd/system/pagi.service>):>
518  
519 [Unit]
520 Description=PAGI Application Server
521 Requires=pagi.socket
522  
523 [Service]
524 User=www-data
525 ExecStart=/usr/local/bin/pagi-server -E production ./app.pl
526 Restart=on-failure
527  
528 [Install]
529 WantedBy=multi-user.target
530  
531 C<Accept=no> is B<required>. PAGI::Server accepts connections itself via
532 C<IO::Async>; systemd must not accept on its behalf.
533  
534 =head2 How Auto-Detection Works
535  
536 When PAGI::Server starts, it checks the C<LISTEN_FDS> and C<LISTEN_PID>
537 environment variables set by systemd. If C<LISTEN_PID> matches the current
538 process PID, the server inspects each inherited file descriptor (starting at
539 fd 3) with C<getsockname()> to determine its address.
540  
541 Each inherited socket is then matched against the configured listeners. For
542 example, if you configure C<< port => 8080 >> and systemd has a socket bound
543 to C<0.0.0.0:8080>, PAGI::Server will use the inherited fd instead of
544 creating a new socket.
545  
546 The same application code works identically with or without systemd:
547  
548 # Without systemd: PAGI::Server binds the socket itself
549 # With systemd: PAGI::Server inherits the socket from systemd
550 my $server = PAGI::Server->new(
551 app => $app,
552 host => '0.0.0.0',
553 port => 8080,
554 );
555  
556 After reading the inherited fds, PAGI::Server removes C<LISTEN_FDS>,
557 C<LISTEN_PID>, and C<LISTEN_FDNAMES> from the environment (per the
558 C<sd_listen_fds(3)> specification), so child processes do not re-inherit them.
559  
560 =head2 Unix Socket Cleanup
561  
562 Normally, PAGI::Server unlinks its Unix socket file on shutdown. For
563 systemd-activated Unix sockets, the socket file is B<not> unlinked because
564 systemd owns the socket and will recreate it for the next activation.
565  
566 =head1 FD REUSE INTERNALS (EXPERIMENTAL)
567  
568 B<This feature is experimental.> The API is subject to change in future
569 releases.
570  
571 PAGI::Server uses a C<PAGI_REUSE> environment variable to pass inherited
572 listening socket file descriptors to re-exec'd processes during hot restart
573 (see L</HOT RESTART (EXPERIMENTAL)>). This mechanism also supports systemd
574 socket activation (see L</SYSTEMD SOCKET ACTIVATION (EXPERIMENTAL)>).
575  
576 =head2 PAGI_REUSE Format
577  
578 The variable is a comma-separated list of C<addr:port:fd> entries:
579  
580 # TCP listeners
581 PAGI_REUSE=127.0.0.1:8080:3,0.0.0.0:8443:4
582  
583 # Unix socket listeners
584 PAGI_REUSE=unix:/run/pagi/app.sock:5
585  
586 # Mixed
587 PAGI_REUSE=0.0.0.0:8080:3,unix:/run/pagi/app.sock:4
588  
589 Each entry encodes the address the socket is bound to and the file descriptor
590 number to use.
591  
592 =head2 Fd Matching
593  
594 When starting, C<_collect_inherited_fds()> parses C<PAGI_REUSE> and/or
595 C<LISTEN_FDS>, building a table of C<< address => fd >> pairs. During
596 C<listen()>, each configured listener looks up its own address in the table.
597 If a match is found, the existing fd is used instead of calling C<bind()> and
598 C<listen()>. This allows the kernel's accept queue to be preserved across
599 restarts.
600  
601 =head2 File Descriptor Inheritance
602  
603 To ensure that listening socket fds are inherited across C<exec()>,
604 PAGI::Server sets C<$^F = 1023> before creating sockets. Perl uses C<$^F>
605 (the maximum system file descriptor, equivalent to C<POSIX_OPEN_MAX> in
606 spirit) to decide which fds receive the C<FD_CLOEXEC> close-on-exec flag:
607 fds with numbers greater than C<$^F> get C<FD_CLOEXEC> set automatically.
608 By raising C<$^F> to 1023, listen socket fds remain open across C<exec()>
609 without requiring explicit C<fcntl> calls.
610  
611 =head1 HOT RESTART (EXPERIMENTAL)
612  
613 B<This feature is experimental.> The API and signal behaviour are subject
614 to change in future releases.
615  
616 Deploying new code normally requires a server restart. During that restart
617 there is a gap — however brief — where the listening socket is closed and
618 incoming connections are dropped. Hot restart eliminates this gap by having
619 the old master fork and exec a brand-new master process that B<inherits> the
620 already-open listening sockets. Both the old master and the new master serve
621 requests during the transition; clients never see a refused connection.
622  
623 =head2 How It Works
624  
625 =over 4
626  
627 =item 1.
628  
629 An admin sends C<SIGUSR2> to the running master: C<kill -USR2 E<lt>master_pidE<gt>>
630  
631 =item 2.
632  
633 The old master sets C<PAGI_REUSE> (encoding each listening socket fd) and
634 C<PAGI_MASTER_PID> (its own PID) in the environment, then calls C<fork()>
635 followed immediately by C<exec()> of the original C<pagi-server> command
636 (reconstructed from C<PAGI_ARGV>).
637  
638 =item 3.
639  
640 The new master starts, finds the inherited file descriptors via C<PAGI_REUSE>,
641 and reuses the existing listening sockets rather than calling C<bind()>/C<listen()>
642 again. The kernel's accept queue is preserved — no connections are dropped.
643  
644 =item 4.
645  
646 The new master spawns its worker pool and waits for each worker to complete
647 the lifespan startup handshake (heartbeat).
648  
649 =item 5.
650  
651 Once all workers are healthy, the new master sends C<SIGTERM> to the old
652 master (read from C<PAGI_MASTER_PID>).
653  
654 =item 6.
655  
656 The old master receives C<SIGTERM>, finishes in-flight requests within its
657 shutdown timeout, and exits cleanly.
658  
659 =back
660  
661 =head2 HUP vs USR2
662  
663 HUP — Rolling worker restart. Workers are replaced one by one.
664 Code loaded at master startup (middleware, startup modules)
665 is NOT reloaded. Use for: config changes picked up per-worker.
666  
667 USR2 — Full master re-exec. Everything reloaded from disk including
668 the perl binary, all modules, middleware stack. Use for:
669 code deploys, Perl upgrades, PAGI::Server upgrades.
670  
671 =head2 Deploy Workflow
672  
673 # Deploy new code
674 rsync -a ./lib/ /opt/myapp/lib/
675  
676 # Hot restart (zero downtime)
677 kill -USR2 $(cat /var/run/myapp/pagi.pid)
678  
679 # Verify (optional)
680 curl http://localhost:8080/health
681  
682 =head2 systemd Unit File
683  
684 [Service]
685 Type=forking
686 PIDFile=/var/run/myapp/pagi.pid
687 ExecStart=/usr/local/bin/pagi-server \
688 --host 0.0.0.0 --port 8080 \
689 --workers 4 --pid /var/run/myapp/pagi.pid \
690 --daemonize /opt/myapp/app.pl
691 ExecReload=/bin/kill -USR2 $MAINPID
692 KillMode=process
693  
694 =head2 Failure Handling
695  
696 The design ensures the old master never stops until the new master explicitly
697 sends C<SIGTERM>:
698  
699 =over 4
700  
701 =item * B<Fork failure> — The old master logs the error and continues serving.
702 No new master is started.
703  
704 =item * B<Exec failure> — The forked child exits before loading any code.
705 The old master notices (via C<waitpid>) and continues serving.
706  
707 =item * B<New master crash during startup> — The old master never receives
708 C<SIGTERM> and continues serving indefinitely.
709  
710 =item * B<Workers fail lifespan startup> — The new master exits without
711 sending C<SIGTERM>. The old master is unaffected.
712  
713 =back
714  
715 =head2 PERL5LIB and Module Paths
716  
717 When the new master is C<exec>'d it inherits the process environment, but
718 B<not> any C<-I> flags that were on the original command line. If your
719 application uses C<-Ilib>, ensure C<PERL5LIB> is set in the environment or
720 in the systemd unit file so the re-exec'd process can find your modules.
721 Alternatively, use the C<--lib> flag (C<pagi-server --lib ./lib ./app.pl>),
722 which is captured in C<PAGI_ARGV> and replayed on re-exec.
723  
724 =head1 WINDOWS SUPPORT
725  
726 B<PAGI::Server does not support Windows.>
727  
728 The server relies on Unix-specific features that are not available on Windows:
729  
730 =over 4
731  
732 =item * B<Unix signals> - SIGTERM, SIGINT, SIGHUP for graceful shutdown and worker management
733  
734 =item * B<fork()> - Multi-worker mode requires real process forking, not thread emulation
735  
736 =item * B<IO::Async internals> - The event loop has Unix-specific optimizations
737  
738 =back
739  
740 For Windows development, consider using WSL (Windows Subsystem for Linux) to
741 run PAGI::Server in a Linux environment. The PAGI specification and middleware
742 components can still be developed and unit-tested on Windows, but the reference
743 server implementation requires a Unix-like operating system.
744  
745  
746 =head1 CONSTRUCTOR
747  
748 =head2 new
749  
750 my $server = PAGI::Server->new(%options);
751  
752 Creates a new PAGI::Server instance. Options:
753  
754 =over 4
755  
756 =item app => $app (required)
757  
758 Either a PAGI application coderef with signature
759 C<async sub ($scope, $receive, $send)> or an instantiated application-provider
760 object implementing C<to_app>. A provider is normalized exactly once during
761 construction, and C<to_app> must return a coderef. Package-name strings are not
762 providers. C<configure(app =E<gt> $app)> applies the same normalization rules.
763 Only the normalized coderef is retained for per-connection dispatch.
764  
765 =item host => $host
766  
767 Bind address (IP address or hostname). Default: C<'127.0.0.1'>
768  
769 The default binds only to the loopback interface, accepting connections only
770 from localhost. This is B<intentionally secure by default> - development
771 servers won't accidentally be exposed to the network.
772  
773 B<Common values:>
774  
775 '127.0.0.1' - Localhost only (default, secure for development)
776 '0.0.0.0' - All IPv4 interfaces (required for remote access)
777 '::' - All IPv6 interfaces (may also accept IPv4)
778 '192.168.1.100' - Specific interface only
779  
780 B<For headless servers or production deployments> where remote clients need
781 to connect, bind to all interfaces:
782  
783 my $server = PAGI::Server->new(
784 app => $app,
785 host => '0.0.0.0',
786 port => 8080,
787 );
788  
789 B<Security note:> When binding to C<0.0.0.0>, ensure appropriate firewall
790 rules are in place. For production, consider a reverse proxy (nginx, etc.)
791  
792 =item port => $port
793  
794 Bind port. Default: 5000
795  
796 =item socket => $path
797  
798 B<Experimental.> Unix domain socket path for listening instead of TCP host:port.
799 B<Mutually exclusive> with C<host>, C<port>, and C<listen>.
800 See L</UNIX DOMAIN SOCKET SUPPORT (EXPERIMENTAL)> for details.
801  
802 my $server = PAGI::Server->new(
803 app => $app,
804 socket => '/tmp/pagi.sock',
805 );
806  
807 =item socket_mode => $mode
808  
809 Set file permissions on the Unix domain socket after creation. The value
810 should be a numeric mode (e.g., C<0660>). If not specified, the socket
811 inherits the default permissions from the process umask. Silently ignored
812 if C<socket> is not set.
813  
814 my $server = PAGI::Server->new(
815 app => $app,
816 socket => '/tmp/pagi.sock',
817 socket_mode => 0660,
818 );
819  
820 =item listen => \@specs
821  
822 B<Experimental.> Array of listener specifications for multi-endpoint listening.
823 Each spec is a hashref with either C<< { host, port } >> for TCP or
824 C<< { socket, socket_mode } >> for Unix domain sockets.
825 B<Mutually exclusive> with C<host>, C<port>, C<socket>, and C<socket_mode>.
826 See L</MULTI-LISTENER SUPPORT (EXPERIMENTAL)> for details.
827  
828 my $server = PAGI::Server->new(
829 app => $app,
830 listen => [
831 { host => '0.0.0.0', port => 8080 },
832 { socket => '/tmp/pagi.sock', socket_mode => 0660 },
833 ],
834 );
835  
836 =item ssl => \%config
837  
838 Optional TLS/HTTPS configuration. B<Requires additional modules> - see
839 L</ENABLING TLS SUPPORT> below.
840  
841 Configuration keys:
842  
843 =over 4
844  
845 =item cert_file => $path
846  
847 Path to the SSL certificate file (PEM format).
848  
849 =item key_file => $path
850  
851 Path to the SSL private key file (PEM format).
852  
853 =item ca_file => $path
854  
855 Optional path to CA certificate for client verification.
856  
857 =item verify_client => $bool
858  
859 If true, require and verify client certificates.
860  
861 =item min_version => $version
862  
863 Minimum TLS version -- a B<floor>, not a pin: the server negotiates the highest
864 version the client also supports at or above this. Default: C<'TLSv1_2'> (so
865 TLS 1.3 is used with modern clients). Options: C<'TLSv1_2'>, C<'TLSv1_3'>.
866  
867 =item cipher_list => $string
868  
869 OpenSSL cipher list. Default uses modern secure ciphers.
870  
871 =back
872  
873 Example:
874  
875 my $server = PAGI::Server->new(
876 app => $app,
877 ssl => {
878 cert_file => '/path/to/server.crt',
879 key_file => '/path/to/server.key',
880 },
881 );
882  
883 =item disable_tls => $bool
884  
885 Force-disable TLS even if ssl config is provided. Useful for testing
886 TLS configuration parsing without actually enabling TLS. Default: false.
887  
888 =item extensions => \%extensions
889  
890 Extensions to advertise (e.g., { fullflush => {} })
891  
892 =item access_log => $filehandle | undef
893  
894 Access log filehandle. Default: STDERR
895  
896 Set to C<undef> to disable access logging entirely. This eliminates
897 per-request I/O overhead, improving throughput by 5-15% depending on
898 workload. Useful for benchmarking or when access logs are handled
899 externally (e.g., by a reverse proxy).
900  
901 # Disable access logging
902 my $server = PAGI::Server->new(
903 app => $app,
904 access_log => undef,
905 );
906  
907 =item access_log_format => $format_or_preset
908  
909 Access log format string or preset name. Default: C<'clf'>
910  
911 Named presets:
912  
913 clf - PAGI default: IP, timestamp, method/path, status, duration
914 combined - Apache combined: adds Referer and User-Agent
915 common - Apache common: adds response size
916 tiny - Minimal: method, path, status, duration
917  
918 Custom format strings use Apache-style atoms. See L</ACCESS LOG FORMAT>.
919  
920 my $server = PAGI::Server->new(
921 app => $app,
922 access_log_format => 'combined',
923 );
924  
925 =item log_level => $level
926  
927 Controls the verbosity of server log messages. Default: 'info'
928  
929 Valid levels (from least to most verbose):
930  
931 =over 4
932  
933 =item * B<error> - Only errors (application errors, fatal conditions)
934  
935 =item * B<warn> - Warnings and errors (connection issues, timeouts)
936  
937 =item * B<info> - Informational messages and above (startup, shutdown, worker spawning)
938  
939 =item * B<debug> - Everything (verbose diagnostics, frame-level details)
940  
941 =back
942  
943 my $server = PAGI::Server->new(
944 app => $app,
945 log_level => 'debug', # Very verbose
946 );
947  
948 B<CLI:> C<--log-level debug>
949  
950 =item quiet => $bool
951  
952 Suppress all log output except errors. Default: 0. When true, C<_log>
953 messages below the C<error> level are dropped regardless of C<log_level>;
954 error-level messages are always emitted. Worker processes run quiet
955 internally so only the master logs lifecycle events.
956  
957 B<CLI:> C<-q>, C<--quiet>
958  
959 =item workers => $count
960  
961 Number of worker processes for multi-worker mode. Default: 0 (single process mode).
962  
963 When set to a value greater than 0, the server uses a pre-fork model: it spawns
964 C<$count> independent worker processes, each with its own event loop, and each
965 running the C<lifespan> startup/shutdown cycle independently.
966  
967 B<Workers do not share memory.> Each worker is a separate process. Anything your
968 application keeps in memory -- a cache, a counter, a registry, an open database
969 handle, a pub/sub hub stored in C<< $scope->{state} >> -- exists once B<per
970 worker> and does not propagate to the others. This is inherent to C<fork>, and it
971 is exactly how the wider async ecosystem behaves: gunicorn/uvicorn workers, and
972 processes on separate hosts, are isolated the same way.
973  
974 The practical consequences:
975  
976 =over 4
977  
978 =item * A B<stateless> application -- or one whose shared state lives in an
979 external store such as a database or Redis -- scales across workers with no
980 special handling. This is the common case.
981  
982 =item * An application that relies on B<in-memory shared state> will see it
983 diverge: each worker holds its own copy, and a value written by one worker is
984 invisible to the rest. Open per-worker resources (database connections and the
985 like) in the C<lifespan> startup -- which runs in each worker -- rather than
986 before calling C<run()>.
987  
988 =item * To share B<events> across workers -- one worker publishes, handlers on
989 every worker receive -- you need an external broker, not in-memory state. See
990 L<PAGI::Middleware::Channels>; its Redis backend is the cross-process layer, the
991 same role Django Channels' channel layer plays for ASGI.
992  
993 =back
994  
995 The same boundary applies when you scale to multiple B<nodes> (for example
996 Kubernetes pods): nothing in process memory crosses it. In-memory state is
997 single-process; anything that must be shared has to live outside the process.
998  
999 =item listener_backlog => $number
1000  
1001 Value for the listener queue size. Default: 2048
1002  
1003 When in multi worker mode, the queue size for those workers inherits
1004 from this value.
1005  
1006 B<Which process consumes it:> the listening process -- the parent in
1007 traditional (shared-socket) mode, or each worker in C<reuseport> mode. In
1008 both cases it's the master's configured value being read at
1009 socket-creation time, not an independently configurable per-worker
1010 option.
1011  
1012 =item reuseport => $bool
1013  
1014 Enable SO_REUSEPORT mode for multi-worker servers. Default: 0 (disabled).
1015  
1016 When enabled, each worker process creates its own listening socket with
1017 SO_REUSEPORT, allowing the kernel to load-balance incoming connections
1018 across workers. This can reduce accept() contention and improve p99
1019 latency under high concurrency.
1020  
1021 B<Traditional mode (reuseport=0):> Parent creates one socket before forking,
1022 all workers inherit and share that socket. Workers compete on a single
1023 accept queue (potential thundering herd).
1024  
1025 B<Reuseport mode (reuseport=1):> Each worker creates its own socket with
1026 SO_REUSEPORT. The kernel distributes connections across sockets, each
1027 worker has its own accept queue (reduced contention).
1028  
1029 B<Platform notes:>
1030  
1031 =over 4
1032  
1033 =item * B<Linux 3.9+>: Full kernel-level load balancing. Recommended for high
1034 concurrency workloads.
1035  
1036 =item * B<macOS/BSD>: SO_REUSEPORT allows multiple binds but does NOT provide
1037 kernel load balancing. May actually decrease performance compared to shared
1038 socket mode. Use with caution - benchmark before deploying.
1039  
1040 =back
1041  
1042 B<Which process consumes it:> read by the parent to decide whether to
1043 create one shared listening socket or let each worker create its own;
1044 each worker then acts on this same master-configured value when creating
1045 its own socket. It is not an independently configurable per-worker
1046 option.
1047  
1048 =item max_receive_queue => $count
1049  
1050 Maximum number of messages that can be queued in the WebSocket receive queue
1051 before the connection is closed. This is a DoS protection mechanism.
1052  
1053 B<Unit:> Message count (not bytes). Each WebSocket text or binary frame counts
1054 as one message regardless of size.
1055  
1056 B<Default:> 1000 messages
1057  
1058 B<When exceeded:> The server sends a WebSocket close frame with code 1008
1059 (Policy Violation) and reason "Message queue overflow", then closes the
1060 connection.
1061  
1062 This value is also advertised to the application as the C<max_receive_queue>
1063 key on the websocket scope, per L<PAGI::Spec::Www/"WebSocket Scope"> --
1064 always present, since this cap is always enforced.
1065  
1066 B<Tuning guidelines:>
1067  
1068 =over 4
1069  
1070 =item * B<Memory impact:> Each queued message holds the full message payload.
1071 With default of 1000 messages and average 1KB messages, worst case is ~1MB
1072 per slow connection.
1073  
1074 =item * B<Workers:> Total memory risk = workers × max_connections × max_receive_queue × avg_message_size.
1075 For 4 workers, 100 connections each, 1000 queue, 1KB average = 400MB worst case.
1076  
1077 =item * B<Fast consumers:> If your app processes messages quickly, the queue
1078 rarely grows. Default of 1000 is generous for most applications.
1079  
1080 =item * B<Slow consumers:> If your app does expensive processing per message,
1081 consider lowering to 100-500 to limit memory exposure.
1082  
1083 =item * B<High throughput:> If you have trusted clients sending rapid bursts,
1084 you may increase to 5000-10000, but monitor memory usage.
1085  
1086 =back
1087  
1088 B<CLI:> C<--max-receive-queue 500>
1089  
1090 =item max_ws_frame_size => $bytes
1091  
1092 Maximum size in bytes for a single WebSocket frame payload. When a client
1093 sends a frame larger than this limit, the connection is closed with a
1094 protocol error.
1095  
1096 B<Unit:> Bytes
1097  
1098 B<Default:> 65536 (64KB) - matches Protocol::WebSocket default
1099  
1100 B<When exceeded:> The server closes the connection. The error is logged as
1101 "PAGI connection error: Payload is too big."
1102  
1103 This value is also advertised to the application as the C<max_frame_size>
1104 key on the websocket scope, per L<PAGI::Spec::Www/"WebSocket Scope">, when
1105 enforced. Set to C<0> to disable the limit; the scope then omits
1106 C<max_frame_size> rather than advertising a cap that isn't enforced.
1107  
1108 B<Tuning guidelines:>
1109  
1110 =over 4
1111  
1112 =item * B<Small messages:> For chat apps or control messages, default 64KB is plenty.
1113  
1114 =item * B<File uploads:> For binary data transfer via WebSocket, increase to 1MB-16MB
1115 depending on expected file sizes.
1116  
1117 =item * B<Memory impact:> Each connection can buffer up to max_ws_frame_size bytes
1118 during frame parsing. High values increase memory per connection.
1119  
1120 =item * B<DoS protection:> Lower values limit memory exhaustion from malicious clients
1121 sending oversized frames.
1122  
1123 =back
1124  
1125 B<CLI:> C<--max-ws-frame-size 1048576>
1126  
1127 =item max_connections => $count
1128  
1129 Maximum number of concurrent connections before returning HTTP 503.
1130 B<Default: 1000> (same as Mojolicious).
1131  
1132 When at capacity, new connections receive a 503 Service Unavailable
1133 response with a Retry-After header. This prevents resource exhaustion
1134 under heavy load.
1135  
1136 B<Which process consumes it:> in multi-worker mode, each worker enforces
1137 this limit independently against its own accepted connections -- it is a
1138 per-worker cap, not a total shared across all workers. C<workers>
1139 workers each configured with C<max_connections> => N gives an effective
1140 ceiling of roughly C<workers * N> connections across the whole server.
1141  
1142 B<Example:>
1143  
1144 my $server = PAGI::Server->new(
1145 app => $app,
1146 max_connections => 5000, # Higher limit for production
1147 );
1148  
1149 B<CLI:> C<--max-connections 5000>
1150  
1151 B<Monitoring:> Use C<< $server->connection_count >> and
1152 C<< $server->effective_max_connections >> to monitor usage.
1153  
1154 B<Production Tuning:>
1155  
1156 For high-traffic production deployments, you'll likely want to increase
1157 this value. The optimal setting depends on your workload, available
1158 memory, and system file descriptor limits.
1159  
1160 I<Linux - Check and increase file descriptor limits:>
1161  
1162 # Check current limits
1163 ulimit -n # Soft limit (per-process)
1164 cat /proc/sys/fs/file-max # System-wide limit
1165  
1166 # Increase for current session
1167 ulimit -n 65536
1168  
1169 # Permanent: add to /etc/security/limits.conf
1170 * soft nofile 65536
1171 * hard nofile 65536
1172  
1173 # Or for systemd services, in your unit file:
1174 [Service]
1175 LimitNOFILE=65536
1176  
1177 I<macOS - Check and increase file descriptor limits:>
1178  
1179 # Check current limits
1180 ulimit -n # Soft limit
1181 sysctl kern.maxfilesperproc # Per-process max
1182  
1183 # Increase for current session
1184 ulimit -n 65536
1185  
1186 # Permanent: add to /etc/launchd.conf or use launchctl
1187 sudo launchctl limit maxfiles 65536 200000
1188  
1189 I<Rule of thumb:> Set C<max_connections> to roughly 80% of your file
1190 descriptor limit to leave headroom for database connections, log files,
1191 and other resources.
1192  
1193 =item write_high_watermark => $bytes
1194  
1195 B<Power user setting.> Maximum bytes to buffer in the socket write queue
1196 before applying backpressure. When exceeded, C<< $send->() >> calls will
1197 pause until the buffer drains below C<write_low_watermark>.
1198 Default: 65536 (64KB).
1199  
1200 This prevents unbounded memory growth when the server writes data faster
1201 than the client can receive it. The default matches Python's asyncio
1202 transport defaults, providing a good balance between throughput and
1203 memory efficiency.
1204  
1205 B<When to adjust:>
1206  
1207 =over 4
1208  
1209 =item * B<Increase> (e.g., 256KB-1MB) for high-throughput bulk transfers
1210 where you want fewer context switches and higher throughput at the cost
1211 of more per-connection memory.
1212  
1213 =item * B<Decrease> (e.g., 16KB-32KB) if supporting many concurrent
1214 connections where memory efficiency is critical.
1215  
1216 =back
1217  
1218 B<Example:>
1219  
1220 # High-throughput file server - larger buffers
1221 my $server = PAGI::Server->new(
1222 app => $app,
1223 write_high_watermark => 262144, # 256KB
1224 write_low_watermark => 65536, # 64KB
1225 );
1226  
1227 =item write_low_watermark => $bytes
1228  
1229 B<Power user setting.> Threshold below which sending resumes after
1230 backpressure was applied. Must be less than or equal to
1231 C<write_high_watermark>. Default: 16384 (16KB, which is high/4).
1232  
1233 A larger gap between high and low watermarks reduces oscillation
1234 (frequent pause/resume cycles). A smaller gap provides more responsive
1235 backpressure but may increase context switching.
1236  
1237 B<Example:>
1238  
1239 # Minimize oscillation with wider gap
1240 my $server = PAGI::Server->new(
1241 app => $app,
1242 write_high_watermark => 131072, # 128KB
1243 write_low_watermark => 16384, # 16KB (8:1 ratio)
1244 );
1245  
1246 =item max_body_size => $bytes
1247  
1248 Maximum request body size in bytes. Default: 10,000,000 (10MB).
1249 Set to 0 for unlimited (not recommended for public-facing servers).
1250  
1251 Requests with Content-Length exceeding this limit receive HTTP 413
1252 (Payload Too Large). Chunked requests are also checked as data arrives.
1253  
1254 B<Example:>
1255  
1256 my $server = PAGI::Server->new(
1257 app => $app,
1258 max_body_size => 50_000_000, # 50MB for file uploads
1259 );
1260  
1261 # Unlimited (use with caution)
1262 my $server = PAGI::Server->new(
1263 app => $app,
1264 max_body_size => 0,
1265 );
1266  
1267 B<CLI:> C<--max-body-size 50000000>
1268  
1269 B<Security note:> Without a body size limit, attackers can exhaust server
1270 memory with large requests. The 10MB default balances security with common
1271 use cases (file uploads, JSON payloads). Increase for specific needs, or
1272 use 0 only behind a reverse proxy that enforces its own limit.
1273  
1274 =over 4
1275  
1276 =item * A listening socket is created before forking
1277  
1278 =item * Worker processes are spawned using C<< $loop->fork() >> which properly
1279 handles IO::Async's C<$ONE_TRUE_LOOP> singleton
1280  
1281 =item * Each worker gets a fresh event loop and runs lifespan startup independently
1282  
1283 =item * Workers that exit are automatically respawned via C<< $loop->watch_process() >>
1284  
1285 =item * Workers that fail lifespan startup (exit code 2) are B<not> respawned, since
1286 the failure would just repeat. If B<every> worker fails startup so that no workers
1287 remain, the master logs an error and exits non-zero, rather than holding the
1288 listening socket with nothing serving -- so a process supervisor can restart it.
1289  
1290 =item * SIGTERM/SIGINT triggers graceful shutdown of all workers
1291  
1292 =back
1293  
1294 =item max_header_size => $bytes
1295  
1296 Maximum size in bytes of the request line and of the combined header block
1297 for an HTTP/1.x request. Default: 8192 (8KB). A request line exceeding this
1298 limit receives HTTP 414 (URI Too Long); a header block exceeding it receives
1299 HTTP 431 (Request Header Fields Too Large).
1300  
1301 B<CLI:> C<--max-header-size 16384>
1302  
1303 =item max_header_count => $count
1304  
1305 Maximum number of header fields permitted in an HTTP/1.x request. Default:
1306 100. Requests with more headers receive HTTP 431 (Request Header Fields Too
1307 Large). This bounds memory and CPU spent parsing maliciously large header
1308 sets.
1309  
1310 B<CLI:> C<--max-header-count 200>
1311  
1312 =item sync_file_threshold => $bytes
1313  
1314 Threshold in bytes for synchronous file reads. Files smaller than this value
1315 are read synchronously in the event loop; larger files use async I/O via
1316 a worker pool.
1317  
1318 B<Default:> 65536 (64KB)
1319  
1320 Set to 0 for fully async file reads. This is recommended for:
1321  
1322 =over 4
1323  
1324 =item * Network filesystems (NFS, SMB, cloud storage)
1325  
1326 =item * High-latency storage (spinning disks under load)
1327  
1328 =item * Docker volumes with overlay filesystem
1329  
1330 =back
1331  
1332 The default (64KB) is optimized for local SSDs where small synchronous reads
1333 are faster than the overhead of async I/O.
1334  
1335 B<CLI:> C<--sync-file-threshold NUM>
1336  
1337 =item max_requests => $count
1338  
1339 Maximum number of requests a worker process will handle before restarting.
1340 After serving this many requests, the worker gracefully shuts down and the
1341 parent spawns a replacement.
1342  
1343 B<Default:> 0 (disabled - workers run indefinitely)
1344  
1345 B<When to use:>
1346  
1347 =over 4
1348  
1349 =item * Long-running deployments where gradual memory growth is a concern
1350  
1351 =item * Applications with known memory leaks that can't be easily fixed
1352  
1353 =item * Defense against slow memory growth (~6.5 bytes/request observed in PAGI)
1354  
1355 =back
1356  
1357 B<Note:> Only applies in multi-worker mode (C<< workers > 0 >>). In single-worker
1358 mode, this setting is ignored.
1359  
1360 B<CLI:> C<--max-requests 10000>
1361  
1362 Example: With 4 workers and max_requests=10000, total capacity before any
1363 restart is 40,000 requests. Workers restart individually without downtime.
1364  
1365 =item timeout => $seconds
1366  
1367 Connection idle timeout in seconds. Closes connections that are idle between
1368 requests (applies to keep-alive connections waiting for the next request).
1369 The internal disconnect reason recorded for this expiry follows
1370 L<PAGI::Spec::Www/"Standard Disconnect Reasons">: C<idle_timeout> when no
1371 request has ever completed on this connection (the client connected but
1372 never sent one), C<keepalive_timeout> once a request has completed and the
1373 kept-alive connection then idles out waiting for the next one.
1374  
1375 B<Default:> 60
1376  
1377 B<Performance note:> Each connection with a non-zero timeout creates a timer
1378 that is reset on every read event. For maximum throughput in high-performance
1379 scenarios, set C<timeout =E<gt> 0> to disable the idle timer entirely. This
1380 eliminates timer management overhead but means idle connections will never
1381 be automatically closed.
1382  
1383 B<Example:>
1384  
1385 # Disable idle timeout for maximum performance
1386 my $server = PAGI::Server->new(
1387 app => $app,
1388 timeout => 0,
1389 );
1390  
1391 # Short timeout to reclaim connections quickly
1392 my $server = PAGI::Server->new(
1393 app => $app,
1394 timeout => 30,
1395 );
1396  
1397 B<CLI:> C<--timeout 0> or C<--timeout 30>
1398  
1399 B<Note:> This differs from C<request_timeout> (stall timeout during active
1400 request processing). The C<timeout> applies between requests; the
1401 C<request_timeout> applies during a request. For WebSocket and SSE, use
1402 C<ws_idle_timeout> and C<sse_idle_timeout> respectively.
1403  
1404 =item lifespan_startup_timeout => $seconds
1405  
1406 Maximum time in seconds to wait for the lifespan application to signal startup
1407 (by sending C<lifespan.startup.complete> or C<lifespan.startup.failed>). If the
1408 lifespan handler neither signals startup nor returns within this window, the
1409 server logs an error and aborts startup rather than blocking forever.
1410  
1411 B<Default:> 30. C<< lifespan_startup_timeout => 0 >> is rejected at
1412 construction and by C<configure()>: the PAGI Lifespan spec requires that a
1413 server B<must not> block startup indefinitely waiting for a lifespan signal,
1414 so there is no way to disable this bound.
1415  
1416 =item lifespan_mode => 'auto' | 'on'
1417  
1418 Controls how the server treats the lifespan protocol.
1419  
1420 =over 4
1421  
1422 =item * B<auto> (default) -- run the lifespan handler if the application has one.
1423 If the application declines lifespan (by raising on the lifespan scope, or by
1424 returning without signalling startup), the server continues without it. This is
1425 the interoperable default: an application that does not implement lifespan still
1426 runs.
1427  
1428 =item * B<on> -- require lifespan. A decline at startup is B<fatal>: the server
1429 logs it and refuses to start. Use this for applications whose startup must
1430 succeed (for example, one that opens a database pool in lifespan).
1431  
1432 =back
1433  
1434 An explicit C<lifespan.startup.failed> aborts startup in all modes.
1435  
1436 There is no C<off> mode: the PAGI Lifespan spec requires every server instance
1437 or worker to send the lifespan events and forbids an "off" switch that skips
1438 the protocol entirely ("Skipping the lifespan protocol entirely is not a
1439 conforming option. ... A server must not offer an 'off' switch for this
1440 protocol."). Passing C<< lifespan_mode => 'off' >> is rejected at construction.
1441  
1442 B<Multi-worker mode:> each worker forked under C<workers> runs its own
1443 lifespan handshake against its own copy of the application and inherits both
1444 C<lifespan_mode> and C<lifespan_startup_timeout> from the master's
1445 configuration -- a worker never silently falls back to the C<auto> default
1446 when the master was configured with C<on>.
1447  
1448 =item request_timeout => $seconds
1449  
1450 Maximum time in seconds a request can stall without any I/O activity before
1451 being terminated. This is a "stall timeout" - the timer resets whenever data
1452 is read from the client or written to the client.
1453  
1454 B<Default:> 0 (disabled)
1455  
1456 B<Why disabled by default:> Creating per-request timers adds overhead that
1457 impacts throughput on high-performance workloads. For maximum performance,
1458 this is disabled by default. Most production deployments run behind a reverse
1459 proxy (nginx, haproxy) which provides its own timeout protection.
1460  
1461 B<When to enable:>
1462  
1463 =over 4
1464  
1465 =item * Running PAGI directly without a reverse proxy
1466  
1467 =item * Small/internal apps where simplicity matters more than max throughput
1468  
1469 =item * Untrusted clients that might send data slowly or hang
1470  
1471 =item * Defense against application bugs that cause requests to hang indefinitely
1472  
1473 =back
1474  
1475 B<How it works:>
1476  
1477 =over 4
1478  
1479 =item * Timer starts when request processing begins
1480  
1481 =item * Timer resets on any read activity (receiving request body)
1482  
1483 =item * Timer resets on any write activity (sending response)
1484  
1485 =item * If timer expires (no I/O for N seconds), connection is closed
1486  
1487 =item * Not used for WebSocket/SSE (they have C<ws_idle_timeout>/C<sse_idle_timeout>)
1488  
1489 =back
1490  
1491 B<Example:>
1492  
1493 # Enable 30 second stall timeout (recommended when not behind proxy)
1494 my $server = PAGI::Server->new(
1495 app => $app,
1496 request_timeout => 30,
1497 );
1498  
1499 B<CLI:> C<--request-timeout 30>
1500  
1501 B<Note:> This differs from C<timeout> (idle connection timeout). The
1502 C<timeout> applies between requests on keep-alive connections. The
1503 C<request_timeout> applies during active request processing.
1504  
1505 =item ws_idle_timeout => $seconds
1506  
1507 Maximum time in seconds a WebSocket connection can be idle without any
1508 activity (no messages sent or received) before being closed.
1509  
1510 B<Default:> 0 (disabled - WebSocket connections can be idle indefinitely)
1511  
1512 When enabled, the timer resets on:
1513  
1514 =over 4
1515  
1516 =item * Sending any WebSocket frame (accept, send, ping, close)
1517  
1518 =item * Receiving any WebSocket frame from client
1519  
1520 =back
1521  
1522 B<Example:>
1523  
1524 # Close idle WebSocket connections after 5 minutes
1525 my $server = PAGI::Server->new(
1526 app => $app,
1527 ws_idle_timeout => 300,
1528 );
1529  
1530 B<CLI:> C<--ws-idle-timeout 300>
1531  
1532 B<Note:> For more sophisticated keep-alive behavior with ping/pong, use
1533 C<< $ws->keepalive($interval, $timeout) >> for protocol-level ping/pong.
1534  
1535 =item sse_idle_timeout => $seconds
1536  
1537 Maximum time in seconds an SSE connection can be idle without any events
1538 being sent before being closed.
1539  
1540 B<Default:> 0 (disabled - SSE connections can be idle indefinitely)
1541  
1542 The timer resets each time an event is sent to the client (including
1543 comments and the initial headers).
1544  
1545 B<Example:>
1546  
1547 # Close idle SSE connections after 2 minutes
1548 my $server = PAGI::Server->new(
1549 app => $app,
1550 sse_idle_timeout => 120,
1551 );
1552  
1553 B<CLI:> C<--sse-idle-timeout 120>
1554  
1555 B<Note:> For SSE connections that may be legitimately idle, use
1556 C<< $sse->keepalive($interval) >> to send periodic comment keepalives.
1557  
1558 B<HTTP/2 caveat:> Over HTTP/2 this timeout applies at the connection level,
1559 not per-stream. See L<PAGI::Server::Connection/SSE Idle Timeout over HTTP/2>
1560 for details and recommendations.
1561  
1562 =item heartbeat_timeout => $seconds
1563  
1564 Worker liveness timeout in seconds. Only active in multi-worker mode
1565 (C<< workers > 0 >>). Has no effect when running without workers
1566 (C<< workers == 0 >>) — use C<timeout> for idle connection management there.
1567  
1568 Each worker sends a heartbeat to the parent process via a Unix pipe at
1569 an interval of C<heartbeat_timeout / 5>. The parent checks for missed
1570 heartbeats every C<heartbeat_timeout / 2>. If a worker has not sent a
1571 heartbeat within C<heartbeat_timeout> seconds, the parent kills it with
1572 SIGKILL and respawns a replacement.
1573  
1574 B<Which process consumes it:> both. The worker reads it to compute how
1575 often it writes a heartbeat ping; the parent reads it to compute how
1576 often it checks for missed heartbeats and how long to wait before
1577 declaring a worker dead. Each worker process gets its own copy of this
1578 value (propagated at spawn), so it always matches what the parent is
1579 checking against.
1580  
1581 B<What this detects:> Event loop starvation — when the worker's event
1582 loop is completely blocked and cannot process any events. This happens
1583 with blocking syscalls (C<sleep()>, synchronous DNS, blocking database
1584 drivers), deadlocks, runaway CPU-bound computation, or any code that
1585 does not yield to the event loop.
1586  
1587 B<What this does NOT detect:> Slow async operations. A request handler
1588 that does C<< await $db->query(...) >> for 5 minutes is fine — the
1589 C<await> returns control to the event loop, so heartbeats continue
1590 normally. This value should be larger than the maximum time you expect
1591 any single operation to block the event loop without yielding.
1592  
1593 B<Default:> 50 (seconds). Set to 0 to disable.
1594  
1595 B<Example:>
1596  
1597 # Tighter heartbeat for latency-sensitive service
1598 my $server = PAGI::Server->new(
1599 app => $app,
1600 workers => 4,
1601 heartbeat_timeout => 20,
1602 );
1603  
1604 # Disable heartbeat monitoring
1605 my $server = PAGI::Server->new(
1606 app => $app,
1607 workers => 4,
1608 heartbeat_timeout => 0,
1609 );
1610  
1611 B<CLI:> C<--heartbeat-timeout 20>
1612  
1613 =item shutdown_timeout => $seconds
1614  
1615 Maximum time in seconds to wait for graceful shutdown to complete.
1616 Default: 30. On SIGTERM/SIGINT the server stops accepting new connections
1617 and waits up to this many seconds for in-flight requests to finish before
1618 forcing remaining connections closed. In multi-worker mode it also bounds
1619 how long the master waits for a worker to exit after SIGTERM before
1620 escalating to SIGKILL.
1621  
1622 B<CLI:> C<--shutdown-timeout 30>
1623  
1624 =item validate_events => $bool
1625  
1626 B<Deprecated, no-op.> Outbound event validation (shape and send sequencing,
1627 per the PAGI spec) is always performed on every send path, in every
1628 environment; there is no way to disable it. This option is accepted for
1629 backward compatibility, is ignored, and will be removed in a future release.
1630  
1631 =item loop_type => $backend
1632  
1633 Specifies the IO::Async::Loop subclass to use when calling C<run()>.
1634 This option is ignored when embedding the server in an existing loop.
1635  
1636 B<Which process consumes it:> whichever process creates its own fresh
1637 loop -- the single (or embedding) process calling C<run()>, and, in
1638 multi-worker mode, each worker. Workers always build a brand-new loop
1639 after forking (there is nothing to embed into post-fork), so
1640 C<loop_type> applies there the same way it does under C<run()>, even
1641 though the master's own loop may itself be an embedder-supplied one that
1642 ignores this option.
1643  
1644 B<Default:> Auto-detect (IO::Async chooses the best available backend)
1645  
1646 B<Common values:>
1647  
1648 'EPoll' - Linux epoll (recommended for Linux)
1649 'EV' - libev-based (cross-platform, requires EV module)
1650 'Poll' - POSIX poll() (portable fallback)
1651 'Select' - select() (most portable, least scalable)
1652  
1653 B<Example:>
1654  
1655 my $server = PAGI::Server->new(
1656 app => $app,
1657 loop_type => 'EPoll',
1658 );
1659 $server->run;
1660  
1661 B<CLI:> C<--loop EPoll> (via pagi-server)
1662  
1663 B<Note:> The specified backend module must be installed. For example,
1664 C<loop_type =E<gt> 'EPoll'> requires L<IO::Async::Loop::EPoll>.
1665  
1666 =item h2_max_concurrent_streams => $count
1667  
1668 B<(Experimental - HTTP/2 support may change in future releases.)>
1669  
1670 Maximum number of concurrent HTTP/2 streams per connection. Each stream
1671 represents an in-flight request/response exchange, bounding concurrent
1672 resource consumption.
1673  
1674 B<Note:> this does I<not> defend the HTTP/2 Rapid Reset attack
1675 (CVE-2023-44487) — reset streams never count against this limit. Rapid Reset is
1676 defended by the incoming-C<RST_STREAM> rate limit; see C<h2_rst_rate_limit>.
1677  
1678 B<Default:> 100
1679  
1680 This matches Apache httpd, H2O, and Hypercorn defaults. The RFC 7540 default
1681 is unlimited, but 100 is the industry consensus for a safe maximum.
1682  
1683 B<Tuning:> Increase for API gateways handling many small concurrent requests.
1684 Decrease for memory-constrained environments or when each request is expensive.
1685  
1686 =item h2_rst_rate_limit => { burst => 1000, rate => 33 }
1687  
1688 B<(Experimental - HTTP/2.)> Token-bucket rate limit on incoming C<RST_STREAM>
1689 frames, defending the HTTP/2 Rapid Reset attack (CVE-2023-44487). C<burst>
1690 tokens are available immediately and refill at C<rate> per second; each
1691 C<RST_STREAM> consumes one. When the bucket empties the server sends GOAWAY and
1692 closes the connection. B<On by default> at nghttp2's defaults (burst 1000, rate
1693 33), which only an abusive create-and-reset flood will hit. Raise the values to
1694 loosen. Requires C<Net::HTTP2::nghttp2> >= 0.008 (nghttp2 >= 1.57).
1695  
1696 =item h2_initial_window_size => $bytes
1697  
1698 B<(Experimental)>
1699  
1700 Initial HTTP/2 flow control window size per stream, in bytes. Controls how
1701 much data a client can send before the server must acknowledge receipt. Also
1702 affects how much response data the server can buffer per stream before the
1703 client acknowledges.
1704  
1705 B<Default:> 65535 (64KB minus 1, the RFC 7540 default)
1706  
1707 B<Tuning:> Increase to 131072-262144 for high-throughput file upload/download
1708 workloads where the default window causes flow control stalls on high-latency
1709 connections. The tradeoff is higher per-stream memory usage.
1710  
1711 =item h2_max_frame_size => $bytes
1712  
1713 B<(Experimental)>
1714  
1715 Maximum size of a single HTTP/2 frame payload, in bytes. Must be between
1716 16384 (16KB, the RFC minimum) and 16777215 (16MB, the RFC maximum).
1717  
1718 B<Default:> 16384 (16KB, the RFC 7540 default)
1719  
1720 Most servers use the RFC default. Larger frames reduce framing overhead but
1721 increase head-of-line blocking within a stream.
1722  
1723 =item h2_enable_push => $bool
1724  
1725 B<(Experimental)>
1726  
1727 Enable HTTP/2 server push (SETTINGS_ENABLE_PUSH). When enabled, the server
1728 can proactively push resources to the client before they are requested.
1729  
1730 B<Default:> 0 (disabled)
1731  
1732 Server push is effectively deprecated. Chrome removed support in 2022,
1733 and nginx deprecated it in version 1.25.1. Unless you have a specific use
1734 case requiring server push, leave this disabled.
1735  
1736 =item h2_enable_connect_protocol => $bool
1737  
1738 B<(Experimental)>
1739  
1740 Enable the Extended CONNECT protocol (RFC 8441, SETTINGS_ENABLE_CONNECT_PROTOCOL).
1741 Required for WebSocket-over-HTTP/2 tunneling.
1742  
1743 B<Default:> 1 (enabled)
1744  
1745 When enabled, clients can use the Extended CONNECT method with a C<:protocol>
1746 pseudo-header to establish WebSocket connections over HTTP/2 streams. Disable
1747 this only if you do not need WebSocket support over HTTP/2.
1748  
1749 =item h2_max_header_list_size => $bytes
1750  
1751 B<(Experimental)>
1752  
1753 Maximum total size of the header block that the server will accept, in bytes.
1754 This is the sum of all header name lengths, value lengths, and 32-byte per-entry
1755 overhead as defined by RFC 7540 Section 6.5.2.
1756  
1757 B<Default:> 65536 (64KB)
1758  
1759 Matches Hypercorn and Node.js defaults. Provides a guard against header-based
1760 memory exhaustion attacks while being generous enough for normal use including
1761 large cookies and authorization tokens.
1762  
1763 =back
1764  
1765 =head1 METHODS
1766  
1767 =head2 listen
1768  
1769 my $future = $server->listen;
1770  
1771 Starts listening for connections. Returns a Future that completes when
1772 the server is ready to accept connections.
1773  
1774 =head2 shutdown
1775  
1776 my $future = $server->shutdown;
1777  
1778 Initiates graceful shutdown. Returns a Future that completes when
1779 shutdown is complete.
1780  
1781 =head2 port
1782  
1783 my $port = $server->port;
1784  
1785 Returns the bound port number. Useful when port => 0 is used.
1786  
1787 =head2 socket_path
1788  
1789 my $path = $server->socket_path;
1790  
1791 Returns the Unix socket path of the first Unix socket listener,
1792 or C<undef> if no Unix socket listeners are configured.
1793  
1794 =head2 listeners
1795  
1796 my $listeners = $server->listeners;
1797  
1798 Returns an arrayref of all normalized listener specifications.
1799 Each entry is a hashref with C<type> (C<'tcp'> or C<'unix'>)
1800 and type-specific keys (C<host>/C<port> for TCP, C<path> for Unix).
1801  
1802 =head2 is_running
1803  
1804 my $bool = $server->is_running;
1805  
1806 Returns true if the server is accepting connections.
1807  
1808 =head2 connection_count
1809  
1810 my $count = $server->connection_count;
1811  
1812 Returns the current number of active connections.
1813  
1814 =head2 effective_max_connections
1815  
1816 my $max = $server->effective_max_connections;
1817  
1818 Returns the effective maximum connections limit. If C<max_connections>
1819 was set explicitly, returns that value. Otherwise returns the default
1820 of 1000.
1821  
1822 =head1 FILE RESPONSE STREAMING
1823  
1824 PAGI::Server supports efficient file streaming via the C<file> and C<fh>
1825 keys in C<http.response.body> events:
1826  
1827 # Stream entire file
1828 await $send->({
1829 type => 'http.response.body',
1830 file => '/path/to/file.mp4',
1831 more => 0,
1832 });
1833  
1834 # Stream partial file (for Range requests)
1835 await $send->({
1836 type => 'http.response.body',
1837 file => '/path/to/file.mp4',
1838 offset => 1000,
1839 length => 5000,
1840 more => 0,
1841 });
1842  
1843 # Stream from filehandle
1844 open my $fh, '<:raw', $file;
1845 await $send->({
1846 type => 'http.response.body',
1847 fh => $fh,
1848 length => $size,
1849 more => 0,
1850 });
1851 close $fh;
1852  
1853 The server streams files in 64KB chunks to avoid memory bloat. Small files
1854 (under 64KB) are read synchronously for speed; larger files use async I/O
1855 via a worker pool (L<PAGI::Server::AsyncFile>, backed by
1856 L<IO::Async::Function>) to avoid blocking the event loop.
1857  
1858 B<Deploy note:> a very large C<RLIMIT_NOFILE> (soft file-descriptor limit) on
1859 the host -- around a million, the kind some container base images or systemd
1860 units set by default -- makes each worker in this async-file-I/O pool take
1861 over a second to start (measured: approximately 1.025s/worker at
1862 C<nofile=1048576>). The cost is C<IO::Async::Internals::ChildManager>'s
1863 post-fork file-descriptor-table sweep (it walks C<0 .. SC_OPEN_MAX>, the
1864 path C<IO::Async::Function> uses to spawn a worker via C<spawn_child>); the
1865 sweep's cost scales with the configured limit, not with how many descriptors
1866 are actually open. This is specific to this worker pool: C<workers> worker
1867 processes spawn via a bare C<fork> (no such sweep) and are unaffected
1868 (measured: approximately 0.026s at the same C<nofile> setting). If large
1869 files are served often enough that AsyncFile worker startup latency
1870 matters, cap C<RLIMIT_NOFILE> to a realistic value for the deployment (a few
1871 tens of thousands is enough for very high concurrency; see C<ulimit -n>
1872 under L</System Tuning>) before starting the server.
1873  
1874 =head2 Production Recommendations for Static Files
1875  
1876 B<For production deployments, we strongly recommend delegating static file
1877 serving to a reverse proxy:>
1878  
1879 =over 4
1880  
1881 =item 1. B<Use nginx, Apache, or a CDN>
1882  
1883 Place a reverse proxy in front of PAGI::Server and let it handle static
1884 files directly. This provides:
1885  
1886 =over 4
1887  
1888 =item * Optimized file serving with kernel sendfile
1889  
1890 =item * Efficient caching and compression
1891  
1892 =item * Protection from slow client attacks
1893  
1894 =item * HTTP/2 and HTTP/3 support
1895  
1896 =back
1897  
1898 =item 2. B<Use L<PAGI::Middleware::XSendfile>>
1899  
1900 For files that require authentication or authorization, use the XSendfile
1901 middleware to delegate file serving to the reverse proxy:
1902  
1903 use PAGI::Middleware::Builder;
1904  
1905 my $app = builder {
1906 enable 'XSendfile',
1907 type => 'X-Accel-Redirect', # For Nginx
1908 mapping => { '/var/www/protected/' => '/internal/' };
1909 $my_app;
1910 };
1911  
1912 See L<PAGI::Middleware::XSendfile> for details.
1913  
1914 =back
1915  
1916 =head1 ENABLING TLS SUPPORT
1917  
1918 PAGI::Server supports HTTPS/TLS connections, but requires additional modules
1919 that are not installed by default. This keeps the base installation minimal
1920 for users who don't need TLS.
1921  
1922 =head2 When You Need TLS
1923  
1924 You need TLS if you want to:
1925  
1926 =over 4
1927  
1928 =item * Serve HTTPS traffic directly from PAGI::Server
1929  
1930 =item * Test TLS locally during development
1931  
1932 =item * Use client certificate authentication
1933  
1934 =back
1935  
1936 You B<don't> need TLS if you:
1937  
1938 =over 4
1939  
1940 =item * Use a reverse proxy (nginx, Apache) that handles TLS termination
1941  
1942 =item * Only serve HTTP traffic on localhost for development
1943  
1944 =item * Deploy behind a load balancer that provides TLS
1945  
1946 =back
1947  
1948 B<Production recommendation:> Use a reverse proxy (nginx, HAProxy, etc.) for
1949 TLS termination. They offer better performance, easier certificate management,
1950 and battle-tested security. PAGI::Server's TLS support is primarily for
1951 development and testing.
1952  
1953 =head2 Installing TLS Modules
1954  
1955 To enable TLS support, install the required modules:
1956  
1957 B<Using cpanm:>
1958  
1959 cpanm IO::Async::SSL IO::Socket::SSL
1960  
1961 B<Using system packages (Debian/Ubuntu):>
1962  
1963 apt-get install libio-socket-ssl-perl
1964  
1965 B<Using system packages (RHEL/CentOS):>
1966  
1967 yum install perl-IO-Socket-SSL
1968  
1969 B<Verifying installation:>
1970  
1971 perl -MIO::Async::SSL -MIO::Socket::SSL -e 'print "TLS modules installed\n"'
1972  
1973 =head2 Basic TLS Configuration
1974  
1975 Once the modules are installed, configure TLS with certificate and key files:
1976  
1977 my $server = PAGI::Server->new(
1978 app => $app,
1979 host => '0.0.0.0',
1980 port => 5000,
1981 ssl => {
1982 cert_file => '/path/to/server.crt',
1983 key_file => '/path/to/server.key',
1984 },
1985 );
1986  
1987 =head2 Generating Self-Signed Certificates (Development)
1988  
1989 For local development and testing, you can generate a self-signed certificate:
1990  
1991 B<Quick self-signed certificate (1 year validity):>
1992  
1993 openssl req -x509 -newkey rsa:4096 -nodes \
1994 -keyout server.key -out server.crt -days 365 \
1995 -subj "/CN=localhost"
1996  
1997 B<With Subject Alternative Names (recommended):>
1998  
1999 # Create config file
2000 cat > ssl.conf <<EOF
2001 [req]
2002 distinguished_name = req_distinguished_name
2003 x509_extensions = v3_req
2004 prompt = no
2005  
2006 [req_distinguished_name]
2007 CN = localhost
2008  
2009 [v3_req]
2010 subjectAltName = @alt_names
2011  
2012 [alt_names]
2013 DNS.1 = localhost
2014 DNS.2 = *.localhost
2015 IP.1 = 127.0.0.1
2016 EOF
2017  
2018 # Generate certificate
2019 openssl req -x509 -newkey rsa:4096 -nodes \
2020 -keyout server.key -out server.crt -days 365 \
2021 -config ssl.conf -extensions v3_req
2022  
2023 B<Testing your TLS configuration:>
2024  
2025 # Start server
2026 pagi-server --app myapp.pl --ssl-cert server.crt --ssl-key server.key
2027  
2028 # Test with curl (ignore self-signed cert warning)
2029 curl -k https://localhost:5000/
2030  
2031 B<Production certificates:>
2032  
2033 For production, use certificates from a trusted CA (Let's Encrypt, etc.):
2034  
2035 # Let's Encrypt with certbot
2036 certbot certonly --standalone -d yourdomain.com
2037  
2038 # Then configure PAGI::Server
2039 my $server = PAGI::Server->new(
2040 app => $app,
2041 ssl => {
2042 cert_file => '/etc/letsencrypt/live/yourdomain.com/fullchain.pem',
2043 key_file => '/etc/letsencrypt/live/yourdomain.com/privkey.pem',
2044 },
2045 );
2046  
2047 =head2 Advanced TLS Configuration
2048  
2049 See the C<ssl> option in L</CONSTRUCTOR> for details on:
2050  
2051 =over 4
2052  
2053 =item * Client certificate verification (C<verify_client>, C<ca_file>)
2054  
2055 =item * TLS version requirements (C<min_version>)
2056  
2057 =item * Custom cipher suites (C<cipher_list>)
2058  
2059 =back
2060  
2061 =head1 ENABLING HTTP/2 SUPPORT (EXPERIMENTAL)
2062  
2063 B<HTTP/2 support is experimental.> The API and behavior may change in future
2064 releases. Please report issues and provide feedback.
2065  
2066 PAGI::Server provides native HTTP/2 support via the nghttp2 C library
2067 (L<Net::HTTP2::nghttp2>). When enabled, the server supports both TLS-based
2068 HTTP/2 (h2 via ALPN negotiation) and cleartext HTTP/2 (h2c).
2069  
2070 =head2 Requirements
2071  
2072 L<Net::HTTP2::nghttp2> must be installed, which requires the nghttp2 C library:
2073  
2074 # Install the C library
2075 brew install nghttp2 # macOS
2076 apt-get install libnghttp2-dev # Debian/Ubuntu
2077  
2078 # Install the Perl bindings
2079 cpanm Net::HTTP2::nghttp2
2080  
2081 =head2 Enabling HTTP/2
2082  
2083 B<Via CLI (pagi-server):>
2084  
2085 # HTTP/2 over TLS (recommended for production)
2086 pagi-server --http2 --ssl-cert cert.pem --ssl-key key.pem --app myapp.pl
2087  
2088 # HTTP/2 cleartext (h2c, for development/testing)
2089 pagi-server --http2 --app myapp.pl
2090  
2091 B<Via constructor:>
2092  
2093 my $server = PAGI::Server->new(
2094 app => $app,
2095 http2 => 1,
2096 ssl => { cert_file => 'cert.pem', key_file => 'key.pem' },
2097 );
2098  
2099 =head2 How It Works
2100  
2101 With TLS, the server advertises C<h2> and C<http/1.1> via ALPN during the
2102 TLS handshake. Clients that support HTTP/2 will negotiate C<h2> automatically;
2103 others fall back to HTTP/1.1 transparently.
2104  
2105 Without TLS, the server detects HTTP/2 via the client connection preface
2106 (h2c mode). HTTP/1.1 clients are handled normally.
2107  
2108 =head2 HTTP/2 Features
2109  
2110 =over 4
2111  
2112 =item * Stream multiplexing (100 concurrent streams per connection by default)
2113  
2114 =item * HPACK header compression
2115  
2116 =item * Per-stream and connection-level flow control
2117  
2118 =item * GOAWAY graceful session shutdown
2119  
2120 =item * Stream state validation (RST_STREAM on protocol violations)
2121  
2122 =item * WebSocket over HTTP/2 via Extended CONNECT (RFC 8441)
2123  
2124 =back
2125  
2126 =head2 Conformance
2127  
2128 Tested against h2spec (the HTTP/2 conformance test suite): B<137/146 (93.8%)>.
2129 All 9 remaining failures are shared with the bare nghttp2 C library and cannot
2130 be fixed at the application level.
2131  
2132 Load tested with h2load: 60,000 requests across 50 concurrent connections with
2133 zero failures.
2134  
2135 See L<PAGI::Server::Compliance> for full compliance details.
2136  
2137 =head2 Configuration
2138  
2139 HTTP/2 protocol settings are tuned via constructor options prefixed with
2140 C<h2_>. See L</CONSTRUCTOR> for details on:
2141  
2142 =over 4
2143  
2144 =item * C<h2_max_concurrent_streams> - Max streams per connection (default: 100)
2145  
2146 =item * C<h2_rst_rate_limit> - Incoming C<RST_STREAM> rate limit; HTTP/2 Rapid Reset defense (default burst 1000 / rate 33)
2147  
2148 =item * C<h2_initial_window_size> - Flow control window (default: 65535)
2149  
2150 =item * C<h2_max_frame_size> - Max frame payload (default: 16384)
2151  
2152 =item * C<h2_enable_push> - Server push (default: disabled)
2153  
2154 =item * C<h2_enable_connect_protocol> - WebSocket over HTTP/2 (default: enabled)
2155  
2156 =item * C<h2_max_header_list_size> - Max header block size (default: 65536)
2157  
2158 =back
2159  
2160 =head1 SIGNAL HANDLING
2161  
2162 PAGI::Server responds to Unix signals for process management. Signal behavior
2163 differs between single-worker and multi-worker modes.
2164  
2165 =head2 Supported Signals
2166  
2167 =over 4
2168  
2169 =item B<SIGTERM> - Graceful shutdown
2170  
2171 Initiates graceful shutdown. The server stops accepting new connections,
2172 waits for active requests to complete (up to C<shutdown_timeout> seconds),
2173 then exits. In multi-worker mode, SIGTERM is forwarded to all workers.
2174  
2175 kill -TERM <pid>
2176  
2177 =item B<SIGINT> - Graceful shutdown (Ctrl-C)
2178  
2179 Same behavior as SIGTERM. Triggered by Ctrl-C in the terminal. In multi-worker
2180 mode, the parent process catches SIGINT and coordinates shutdown of all workers
2181 to ensure proper lifespan.shutdown handling.
2182  
2183 kill -INT <pid>
2184 # or press Ctrl-C in terminal
2185  
2186 =item B<SIGHUP> - Graceful worker restart (multi-worker only)
2187  
2188 Performs a zero-downtime worker restart by spawning new workers before
2189 terminating old ones. Useful for recycling workers to reclaim leaked memory
2190 or reset per-worker state without dropping active connections.
2191  
2192 B<Note:> This does NOT reload application code. New workers fork from the
2193 existing parent process and inherit the same loaded code. For code deploys,
2194 perform a full server restart (SIGTERM + start).
2195  
2196 kill -HUP <pid>
2197  
2198 In single-worker mode, SIGHUP is logged but ignored (no graceful restart
2199 possible without multiple workers).
2200  
2201 =item B<SIGTTIN> - Increase worker count (multi-worker only)
2202  
2203 Spawns an additional worker process. Use this to scale up capacity dynamically.
2204  
2205 kill -TTIN <pid>
2206  
2207 =item B<SIGTTOU> - Decrease worker count (multi-worker only)
2208  
2209 Gracefully terminates one worker process. The minimum worker count is 1;
2210 sending SIGTTOU when only one worker remains has no effect.
2211  
2212 kill -TTOU <pid>
2213  
2214 =back
2215  
2216 =head2 Signal Handling in Multi-Worker Mode
2217  
2218 When running with C<< workers => N >> (where N > 1):
2219  
2220 =over 4
2221  
2222 =item * Parent process manages the worker pool
2223  
2224 =item * Workers handle requests; parent handles signals
2225  
2226 =item * SIGTERM/SIGINT to parent triggers coordinated shutdown of all workers
2227  
2228 =item * Each worker runs lifespan.shutdown before exiting
2229  
2230 =item * Workers that crash are automatically respawned
2231  
2232 =item * Heartbeat monitoring detects workers with blocked event loops and replaces them automatically (see C<heartbeat_timeout>)
2233  
2234 =back
2235  
2236 =head2 Examples
2237  
2238 B<Zero-downtime deployment:>
2239  
2240 # Deploy new code, then signal graceful restart
2241 kill -HUP $(cat /var/run/pagi.pid)
2242  
2243 B<Scale workers based on load:>
2244  
2245 # Add workers during peak hours
2246 kill -TTIN $(cat /var/run/pagi.pid)
2247 kill -TTIN $(cat /var/run/pagi.pid)
2248  
2249 # Remove workers during quiet periods
2250 kill -TTOU $(cat /var/run/pagi.pid)
2251  
2252 B<Graceful shutdown for maintenance:>
2253  
2254 # Stop accepting new connections, drain existing ones
2255 kill -TERM $(cat /var/run/pagi.pid)
2256  
2257 =cut
2258  
2259 sub _init {
2260 647 ▶ my ($self, $params) = @_;
Subroutine _init: called CC=81 SCAR=44.2
2261  
2262 647 my $app = delete $params->{app};
2263 647 ▶ die "app is required" unless defined $app;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $app 2 645 647
2264 645 $self->{app} = PAGI::Server::AppNormalizer::normalize_app($app, 'app');
2265  
2266 # Extract listener-related params
2267 644 my $listen = delete $params->{listen};
2268 644 my $socket = delete $params->{socket};
2269 644 my $socket_mode = delete $params->{socket_mode};
2270 644 my $host = delete $params->{host};
2271 644 my $port = delete $params->{port};
2272 644 $self->{ssl} = delete $params->{ssl};
2273 644 ▶ $self->{disable_tls} = delete $params->{disable_tls} // 0; # Extract early for validation
Condition100%2/2
delete $params->{"disable_tls"} // 0
l!l
2642
MC/DC100%1/1
delete $params->{"disable_tls"} // 0
delete $params->{"disable_tls"}
Truth table100%2/2
A
A= delete $params->{"disable_tls"}
Aresult
11
00
2274  
2275 # Validate SSL certificate files at startup (fail fast)
2276 # Skip validation if TLS is explicitly disabled
2277 644 ▶ if (my $ssl = $self->{ssl}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ssl = $self->{"ssl"}) 58 586 644
2278 58 ▶ if ($self->{disable_tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'disable_tls'}) { } 2 56 58
2279 # Skip TLS setup and cert validation — ssl config is stored but not applied
2280 2 warn "PAGI::Server: TLS disabled via disable_tls option, ssl config ignored\n";
2281 } else {
2282 56 ▶ if (my $cert = $ssl->{cert_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cert = $ssl->{"cert_file"}) 54 2 56
2283 54 ▶ die "SSL certificate file not found: $cert\n" unless -e $cert;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $cert 1 53 54
2284 53 ▶ die "SSL certificate file not readable: $cert\n" unless -r $cert;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $cert 1 52 53
2285 }
2286 54 ▶ if (my $key = $ssl->{key_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $key = $ssl->{"key_file"}) 53 1 54
2287 53 ▶ die "SSL key file not found: $key\n" unless -e $key;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $key 1 52 53
2288 52 ▶ die "SSL key file not readable: $key\n" unless -r $key;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $key 0 52 52
2289 }
2290 53 ▶ if (my $ca = $ssl->{ca_file}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ca = $ssl->{"ca_file"}) 9 44 53
2291 9 ▶ die "SSL CA file not found: $ca\n" unless -e $ca;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $ca 1 8 9
2292 8 ▶ die "SSL CA file not readable: $ca\n" unless -r $ca;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $ca 0 8 8
2293 }
2294 }
2295 }
2296  
2297 # Normalize all listener forms to $self->{listeners}
2298 640 ▶ if ($listen) {
Branch: 2 branches
BranchTrueFalseTotal
if ($listen) { } 31 609 640
elsif (defined $socket) { } 19 590 609
2299 # Explicit listen array
2300 31 ▶ die "Cannot specify both 'listen' and 'host' options\n" if defined $host;
Branch: 1 branch
BranchTrueFalseTotal
if defined $host 2 29 31
2301 29 ▶ die "Cannot specify both 'listen' and 'port' options\n" if defined $port;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 0 29 29
2302 29 ▶ die "Cannot specify both 'listen' and 'socket' options\n" if defined $socket;
Branch: 1 branch
BranchTrueFalseTotal
if defined $socket 0 29 29
2303 29 ▶ die "Cannot specify both 'listen' and 'socket_mode' options\n" if defined $socket_mode;
Branch: 1 branch
BranchTrueFalseTotal
if defined $socket_mode 0 29 29
2304 29 ▶ die "'listen' must be a non-empty arrayref\n"
Branch: 1 branch
BranchTrueFalseTotal
unless ref $listen eq "ARRAY" and @$listen 2 27 29
Condition66%2/3
ref $listen eq "ARRAY" and @$listen
!ll&&!rl&&r
0227
MC/DC50%1/2
ref $listen eq "ARRAY" and @$listen
ref $listen eq "ARRAY" @$listen
Truth table66%2/3
A and B
A= ref $listen eq "ARRAY"B= @$listen
ABresult
0X0
100
111
2305 unless ref $listen eq 'ARRAY' && @$listen;
2306  
2307 27 $self->{listeners} = [];
2308 27 for my $spec (@$listen) {
2309 34 ▶ die "Each listen spec must be a hashref\n" unless ref $spec eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $spec eq "HASH" 0 34 34
2310 34 ▶ if ($spec->{socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{'socket'}) { } 9 25 34
2311 9 ▶ die "Cannot specify both 'socket' and 'host' in a listen spec\n" if $spec->{host};
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"host"} 2 7 9
2312 7 ▶ die "Cannot specify both 'socket' and 'port' in a listen spec\n" if $spec->{port};
Branch: 1 branch
BranchTrueFalseTotal
if $spec->{"port"} 0 7 7
2313 7 push @{$self->{listeners}}, {
2314 type => 'unix',
2315 path => $spec->{socket},
2316 socket_mode => $spec->{socket_mode},
2317 7 };
2318 } else {
2319 die "TCP listen spec requires both 'host' and 'port'\n"
2320 25 ▶ unless defined $spec->{host} && defined $spec->{port};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $spec->{"host"} and defined $spec->{"port"} 2 23 25
Condition66%2/3
defined $spec->{"host"} and defined $spec->{"port"}
!ll&&!rl&&r
0223
MC/DC50%1/2
defined $spec->{"host"} and defined $spec->{"port"}
defined $spec->{"host"} defined $spec->{"port"}
Truth table66%2/3
A and B
A= defined $spec->{"host"}B= defined $spec->{"port"}
ABresult
0X0
100
111
2321 23 push @{$self->{listeners}}, {
2322 type => 'tcp',
2323 host => $spec->{host},
2324 port => $spec->{port},
2325 23 };
2326 }
2327 }
2328 23 $self->{host} = undef;
2329 23 $self->{port} = undef;
2330 } elsif (defined $socket) {
2331 # Socket sugar
2332 19 ▶ die "Cannot specify both 'socket' and 'host' options\n" if defined $host;
Branch: 1 branch
BranchTrueFalseTotal
if defined $host 2 17 19
2333 17 ▶ die "Cannot specify both 'socket' and 'port' options\n" if defined $port;
Branch: 1 branch
BranchTrueFalseTotal
if defined $port 2 15 17
2334 $self->{listeners} = [{
2335 15 type => 'unix',
2336 path => $socket,
2337 socket_mode => $socket_mode,
2338 }];
2339 15 $self->{host} = undef;
2340 15 $self->{port} = undef;
2341 } else {
2342 # Host/port sugar (backward compatible default)
2343 590 ▶ $host //= '127.0.0.1';
Condition100%2/2
$host //= "127.0.0.1"
l!l
56228
MC/DC100%1/1
$host //= "127.0.0.1"
$host
Truth table100%2/2
A
A= $host
Aresult
11
00
2344 590 ▶ $port //= 5000;
Condition100%2/2
$port //= 5000
l!l
57911
MC/DC100%1/1
$port //= 5000
$port
Truth table100%2/2
A
A= $port
Aresult
11
00
2345 $self->{listeners} = [{
2346 590 type => 'tcp',
2347 host => $host,
2348 port => $port,
2349 }];
2350 590 $self->{host} = $host;
2351 590 $self->{port} = $port;
2352 }
2353  
2354 # Apply server-wide SSL to all TCP listeners
2355 628 ▶ if ($self->{ssl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"ssl"}) 54 574 628
2356 54 for my $listener (@{$self->{listeners}}) {
2357 54 ▶ if ($listener->{type} eq 'tcp') {
Branch: 1 branch
BranchTrueFalseTotal
if ($listener->{"type"} eq "tcp") 54 0 54
2358 54 $listener->{ssl} = $self->{ssl};
2359 }
2360 }
2361 }
2362  
2363 628 ▶ $self->{extensions} = delete $params->{extensions} // {};
Condition100%2/2
delete $params->{"extensions"} // {}
l!l
24604
MC/DC100%1/1
delete $params->{"extensions"} // {}
delete $params->{"extensions"}
Truth table100%2/2
A
A= delete $params->{"extensions"}
Aresult
11
00
2364 628 ▶ $self->{access_log} = exists $params->{access_log} ? delete $params->{access_log} : \*STDERR;
Branch: 1 branch
BranchTrueFalseTotal
exists $params->{'access_log'} ? : 45 583 628
2365 628 ▶ $self->{access_log_format} = delete $params->{access_log_format} // 'clf';
Condition100%2/2
delete $params->{"access_log_format"} // "clf"
l!l
8620
MC/DC100%1/1
delete $params->{"access_log_format"} // "clf"
delete $params->{"access_log_format"}
Truth table100%2/2
A
A= delete $params->{"access_log_format"}
Aresult
11
00
2366 $self->{_access_log_formatter} = $self->_compile_access_log_format(
2367 $self->{access_log_format}
2368 628 );
2369 628 ▶ $self->{quiet} = delete $params->{quiet} // 0;
Condition100%2/2
delete $params->{"quiet"} // 0
l!l
6217
MC/DC100%1/1
delete $params->{"quiet"} // 0
delete $params->{"quiet"}
Truth table100%2/2
A
A= delete $params->{"quiet"}
Aresult
11
00
2370 628 ▶ $self->{log_level} = delete $params->{log_level} // 'info';
Condition100%2/2
delete $params->{"log_level"} // "info"
l!l
17611
MC/DC100%1/1
delete $params->{"log_level"} // "info"
delete $params->{"log_level"}
Truth table100%2/2
A
A= delete $params->{"log_level"}
Aresult
11
00
2371 # Validate log level
2372 628 my %valid_levels = (debug => 1, info => 2, warn => 3, error => 4);
2373 die "Invalid log_level '$self->{log_level}' - must be one of: debug, info, warn, error\n"
2374 628 ▶ unless $valid_levels{$self->{log_level}};
Branch: 1 branch
BranchTrueFalseTotal
unless $valid_levels{$self->{"log_level"}} 0 628 628
2375 628 $self->{_log_level_num} = $valid_levels{$self->{log_level}};
2376 628 ▶ $self->{timeout} = delete $params->{timeout} // 60; # Connection idle timeout (seconds)
Condition100%2/2
delete $params->{"timeout"} // 60
l!l
18610
MC/DC100%1/1
delete $params->{"timeout"} // 60
delete $params->{"timeout"}
Truth table100%2/2
A
A= delete $params->{"timeout"}
Aresult
11
00
2377 628 ▶ $self->{max_header_size} = delete $params->{max_header_size} // 8192; # Max header size in bytes
Condition100%2/2
delete $params->{"max_header_size"} // 8192
l!l
17611
MC/DC100%1/1
delete $params->{"max_header_size"} // 8192
delete $params->{"max_header_size"}
Truth table100%2/2
A
A= delete $params->{"max_header_size"}
Aresult
11
00
2378 628 ▶ $self->{max_header_count} = delete $params->{max_header_count} // 100; # Max number of headers
Condition100%2/2
delete $params->{"max_header_count"} // 100
l!l
17611
MC/DC100%1/1
delete $params->{"max_header_count"} // 100
delete $params->{"max_header_count"}
Truth table100%2/2
A
A= delete $params->{"max_header_count"}
Aresult
11
00
2379 628 ▶ $self->{max_body_size} = delete $params->{max_body_size} // 10_000_000; # Max body size in bytes (10MB default, 0 = unlimited)
Condition100%2/2
delete $params->{"max_body_size"} // 10000000
l!l
27601
MC/DC100%1/1
delete $params->{"max_body_size"} // 10000000
delete $params->{"max_body_size"}
Truth table100%2/2
A
A= delete $params->{"max_body_size"}
Aresult
11
00
2380 628 ▶ $self->{workers} = delete $params->{workers} // 0; # Number of worker processes (0 = single process)
Condition100%2/2
delete $params->{"workers"} // 0
l!l
79549
MC/DC100%1/1
delete $params->{"workers"} // 0
delete $params->{"workers"}
Truth table100%2/2
A
A= delete $params->{"workers"}
Aresult
11
00
2381 628 ▶ $self->{max_requests} = delete $params->{max_requests} // 0; # 0 = unlimited
Condition100%2/2
delete $params->{"max_requests"} // 0
l!l
21607
MC/DC100%1/1
delete $params->{"max_requests"} // 0
delete $params->{"max_requests"}
Truth table100%2/2
A
A= delete $params->{"max_requests"}
Aresult
11
00
2382 628 ▶ $self->{listener_backlog} = delete $params->{listener_backlog} // 2048; # Listener queue size
Condition50%1/2
delete $params->{"listener_backlog"} // 2048
l!l
0628
MC/DC0%0/1
delete $params->{"listener_backlog"} // 2048
delete $params->{"listener_backlog"}
Truth table50%1/2
A
A= delete $params->{"listener_backlog"}
Aresult
11
00
2383 628 ▶ $self->{shutdown_timeout} = delete $params->{shutdown_timeout} // 30; # Graceful shutdown timeout (seconds)
Condition100%2/2
delete $params->{"shutdown_timeout"} // 30
l!l
75553
MC/DC100%1/1
delete $params->{"shutdown_timeout"} // 30
delete $params->{"shutdown_timeout"}
Truth table100%2/2
A
A= delete $params->{"shutdown_timeout"}
Aresult
11
00
2384 628 ▶ $self->{reuseport} = delete $params->{reuseport} // 0; # SO_REUSEPORT mode for multi-worker
Condition50%1/2
delete $params->{"reuseport"} // 0
l!l
0628
MC/DC0%0/1
delete $params->{"reuseport"} // 0
delete $params->{"reuseport"}
Truth table50%1/2
A
A= delete $params->{"reuseport"}
Aresult
11
00
2385 628 ▶ $self->{max_receive_queue} = delete $params->{max_receive_queue} // 1000; # Max WebSocket receive queue size (messages)
Condition100%2/2
delete $params->{"max_receive_queue"} // 1000
l!l
21607
MC/DC100%1/1
delete $params->{"max_receive_queue"} // 1000
delete $params->{"max_receive_queue"}
Truth table100%2/2
A
A= delete $params->{"max_receive_queue"}
Aresult
11
00
2386 628 ▶ $self->{max_ws_frame_size} = delete $params->{max_ws_frame_size} // 65536; # Max WebSocket frame size in bytes (64KB default)
Condition100%2/2
delete $params->{"max_ws_frame_size"} // 65536
l!l
20608
MC/DC100%1/1
delete $params->{"max_ws_frame_size"} // 65536
delete $params->{"max_ws_frame_size"}
Truth table100%2/2
A
A= delete $params->{"max_ws_frame_size"}
Aresult
11
00
2387 628 ▶ $self->{max_connections} = delete $params->{max_connections} // 0; # 0 = use default (1000)
Condition100%2/2
delete $params->{"max_connections"} // 0
l!l
20608
MC/DC100%1/1
delete $params->{"max_connections"} // 0
delete $params->{"max_connections"}
Truth table100%2/2
A
A= delete $params->{"max_connections"}
Aresult
11
00
2388 628 ▶ $self->{sync_file_threshold} = delete $params->{sync_file_threshold} // 65536; # Threshold for sync file reads (0=always async)
Condition100%2/2
delete $params->{"sync_file_threshold"} // 65536
l!l
16612
MC/DC100%1/1
delete $params->{"sync_file_threshold"} // 65536
delete $params->{"sync_file_threshold"}
Truth table100%2/2
A
A= delete $params->{"sync_file_threshold"}
Aresult
11
00
2389 628 ▶ $self->{request_timeout} = delete $params->{request_timeout} // 0; # Request stall timeout in seconds (0 = disabled, default for performance)
Condition100%2/2
delete $params->{"request_timeout"} // 0
l!l
16612
MC/DC100%1/1
delete $params->{"request_timeout"} // 0
delete $params->{"request_timeout"}
Truth table100%2/2
A
A= delete $params->{"request_timeout"}
Aresult
11
00
2390 628 ▶ $self->{ws_idle_timeout} = delete $params->{ws_idle_timeout} // 0; # WebSocket idle timeout (0 = disabled)
Condition100%2/2
delete $params->{"ws_idle_timeout"} // 0
l!l
16612
MC/DC100%1/1
delete $params->{"ws_idle_timeout"} // 0
delete $params->{"ws_idle_timeout"}
Truth table100%2/2
A
A= delete $params->{"ws_idle_timeout"}
Aresult
11
00
2391 628 ▶ $self->{sse_idle_timeout} = delete $params->{sse_idle_timeout} // 0; # SSE idle timeout (0 = disabled)
Condition100%2/2
delete $params->{"sse_idle_timeout"} // 0
l!l
18610
MC/DC100%1/1
delete $params->{"sse_idle_timeout"} // 0
delete $params->{"sse_idle_timeout"}
Truth table100%2/2
A
A= delete $params->{"sse_idle_timeout"}
Aresult
11
00
2392 628 ▶ $self->{heartbeat_timeout} = delete $params->{heartbeat_timeout} // 50; # Worker heartbeat timeout (0 = disabled)
Condition100%2/2
delete $params->{"heartbeat_timeout"} // 50
l!l
16612
MC/DC100%1/1
delete $params->{"heartbeat_timeout"} // 50
delete $params->{"heartbeat_timeout"}
Truth table100%2/2
A
A= delete $params->{"heartbeat_timeout"}
Aresult
11
00
2393 628 ▶ $self->{lifespan_startup_timeout} = delete $params->{lifespan_startup_timeout} // 30; # Max wait for lifespan startup signal
Condition100%2/2
delete $params->{"lifespan_startup_timeout"} // 30
l!l
21607
MC/DC100%1/1
delete $params->{"lifespan_startup_timeout"} // 30
delete $params->{"lifespan_startup_timeout"}
Truth table100%2/2
A
A= delete $params->{"lifespan_startup_timeout"}
Aresult
11
00
2394 die "Invalid lifespan_startup_timeout '0' - the PAGI Lifespan spec requires that a server must not block startup indefinitely waiting for a lifespan signal\n"
2395 628 ▶ if $self->{lifespan_startup_timeout} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"lifespan_startup_timeout"} == 0 1 627 628
2396 627 ▶ $self->{lifespan_mode} = delete $params->{lifespan_mode} // 'auto'; # auto (default) | on (decline is fatal)
Condition100%2/2
delete $params->{"lifespan_mode"} // "auto"
l!l
23604
MC/DC100%1/1
delete $params->{"lifespan_mode"} // "auto"
delete $params->{"lifespan_mode"}
Truth table100%2/2
A
A= delete $params->{"lifespan_mode"}
Aresult
11
00
2397 die "Invalid lifespan_mode '$self->{lifespan_mode}' - must be 'auto' or 'on' ('off' is nonconforming: the PAGI Lifespan spec forbids skipping the protocol)\n"
2398 627 ▶ unless $self->{lifespan_mode} =~ /\A(?:auto|on)\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan_mode"} =~ /\A(?:auto|on)\z/ 3 624 627
2399 624 ▶ $self->{write_high_watermark} = delete $params->{write_high_watermark} // 65536; # 64KB - pause sending above this
Condition100%2/2
delete $params->{"write_high_watermark"} // 65536
l!l
32592
MC/DC100%1/1
delete $params->{"write_high_watermark"} // 65536
delete $params->{"write_high_watermark"}
Truth table100%2/2
A
A= delete $params->{"write_high_watermark"}
Aresult
11
00
2400 624 ▶ $self->{write_low_watermark} = delete $params->{write_low_watermark} // 16384; # 16KB - resume sending below this
Condition100%2/2
delete $params->{"write_low_watermark"} // 16384
l!l
32592
MC/DC100%1/1
delete $params->{"write_low_watermark"} // 16384
delete $params->{"write_low_watermark"}
Truth table100%2/2
A
A= delete $params->{"write_low_watermark"}
Aresult
11
00
2401 624 $self->{loop_type} = delete $params->{loop_type}; # Optional loop backend (EPoll, EV, Poll, etc.)
2402 624 ▶ if (my $lt = $self->{loop_type}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $lt = $self->{"loop_type"}) 12 612 624
2403 12 ▶ die "Invalid loop_type '$lt': must contain only letters, digits, and ::\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $lt =~ /\A[A-Za-z][A-Za-z0-9_]*(?:::[A-Za-z][A-Za-z0-9_]*)*\z/ 2 10 12
2404 unless $lt =~ /\A[A-Za-z][A-Za-z0-9_]*(?:::[A-Za-z][A-Za-z0-9_]*)*\z/;
2405 }
2406 # Deprecated: core event validation is mandatory; this flag is retained for compatibility and controls nothing.
2407 $self->{validate_events} = delete $params->{validate_events}
2408 622 ▶ // (($ENV{PAGI_ENV} // '') eq 'development' ? 1 : 0);
Branch: 1 branch
BranchTrueFalseTotal
($ENV{'PAGI_ENV'} // '') eq 'development' ? : 0 582 582
Condition80%4/5
delete $params->{"validate_events"} // (($ENV{"PAGI_ENV"} // "") eq "development" ? 1 : 0)
l!l&&r!l&&!r
400582
$ENV{"PAGI_ENV"} // ""
l!l
6576
MC/DC100%2/2
delete $params->{"validate_events"} // (($ENV{"PAGI_ENV"} // "") eq "development" ? 1 : 0)
delete $params->{"validate_events"} $ENV{"PAGI_ENV"}
Truth table100%3/3
A // B
A= delete $params->{"validate_events"}B= $ENV{"PAGI_ENV"}
ABresult
1X1
011
000
2409  
2410 # HTTP/2 support (opt-in, experimental)
2411 622 ▶ $self->{http2} = delete $params->{http2} // 0;
Condition100%2/2
delete $params->{"http2"} // 0
l!l
241381
MC/DC100%1/1
delete $params->{"http2"} // 0
delete $params->{"http2"}
Truth table100%2/2
A
A= delete $params->{"http2"}
Aresult
11
00
2412  
2413 # HTTP/2 protocol settings (only used when http2 is enabled)
2414 622 ▶ my $h2_max_concurrent_streams = delete $params->{h2_max_concurrent_streams} // 100;
Condition100%2/2
delete $params->{"h2_max_concurrent_streams"} // 100
l!l
2620
MC/DC100%1/1
delete $params->{"h2_max_concurrent_streams"} // 100
delete $params->{"h2_max_concurrent_streams"}
Truth table100%2/2
A
A= delete $params->{"h2_max_concurrent_streams"}
Aresult
11
00
2415 622 ▶ my $h2_initial_window_size = delete $params->{h2_initial_window_size} // 65535;
Condition100%2/2
delete $params->{"h2_initial_window_size"} // 65535
l!l
2620
MC/DC100%1/1
delete $params->{"h2_initial_window_size"} // 65535
delete $params->{"h2_initial_window_size"}
Truth table100%2/2
A
A= delete $params->{"h2_initial_window_size"}
Aresult
11
00
2416 622 ▶ my $h2_max_frame_size = delete $params->{h2_max_frame_size} // 16384;
Condition100%2/2
delete $params->{"h2_max_frame_size"} // 16384
l!l
1621
MC/DC100%1/1
delete $params->{"h2_max_frame_size"} // 16384
delete $params->{"h2_max_frame_size"}
Truth table100%2/2
A
A= delete $params->{"h2_max_frame_size"}
Aresult
11
00
2417 622 ▶ my $h2_enable_push = delete $params->{h2_enable_push} // 0;
Condition100%2/2
delete $params->{"h2_enable_push"} // 0
l!l
1621
MC/DC100%1/1
delete $params->{"h2_enable_push"} // 0
delete $params->{"h2_enable_push"}
Truth table100%2/2
A
A= delete $params->{"h2_enable_push"}
Aresult
11
00
2418 622 ▶ my $h2_enable_connect_protocol = delete $params->{h2_enable_connect_protocol} // 1;
Condition100%2/2
delete $params->{"h2_enable_connect_protocol"} // 1
l!l
1621
MC/DC100%1/1
delete $params->{"h2_enable_connect_protocol"} // 1
delete $params->{"h2_enable_connect_protocol"}
Truth table100%2/2
A
A= delete $params->{"h2_enable_connect_protocol"}
Aresult
11
00
2419 622 ▶ my $h2_max_header_list_size = delete $params->{h2_max_header_list_size} // 65536;
Condition100%2/2
delete $params->{"h2_max_header_list_size"} // 65536
l!l
4618
MC/DC100%1/1
delete $params->{"h2_max_header_list_size"} // 65536
delete $params->{"h2_max_header_list_size"}
Truth table100%2/2
A
A= delete $params->{"h2_max_header_list_size"}
Aresult
11
00
2420 622 ▶ my $h2_rst_rate_limit = delete $params->{h2_rst_rate_limit} // { burst => 1000, rate => 33 };
Condition50%1/2
delete $params->{"h2_rst_rate_limit"} // {"burst", 1000, "rate", 33}
l!l
0622
MC/DC0%0/1
delete $params->{"h2_rst_rate_limit"} // {"burst", 1000, "rate", 33}
delete $params->{"h2_rst_rate_limit"}
Truth table50%1/2
A
A= delete $params->{"h2_rst_rate_limit"}
Aresult
11
00
2421  
2422 622 $self->{running} = 0;
2423 622 $self->{bound_port} = undef;
2424 622 $self->{listener} = undef;
2425 622 $self->{connections} = {}; # Hash keyed by refaddr for O(1) add/remove
2426 $self->{protocol} = PAGI::Server::Protocol::HTTP1->new(
2427 max_header_size => $self->{max_header_size},
2428 max_header_count => $self->{max_header_count},
2429 622 );
2430 622 $self->{state} = {}; # Shared state from lifespan
2431 622 $self->{worker_pids} = {}; # Track worker PIDs in multi-worker mode
2432 622 $self->{is_worker} = 0; # True if this is a worker process
2433  
2434 # Initialize HTTP/2 protocol handler if enabled and available
2435 622 ▶ if ($self->{http2}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"http2"}) 227 395 622
2436 227 ▶ if ($HTTP2_AVAILABLE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($PAGI::Server::HTTP2_AVAILABLE) { } 227 0 227
2437 227 $self->{http2_protocol} = PAGI::Server::Protocol::HTTP2->new(
2438 max_concurrent_streams => $h2_max_concurrent_streams,
2439 initial_window_size => $h2_initial_window_size,
2440 max_frame_size => $h2_max_frame_size,
2441 enable_push => $h2_enable_push,
2442 enable_connect_protocol => $h2_enable_connect_protocol,
2443 max_header_list_size => $h2_max_header_list_size,
2444 h2_rst_rate_limit => $h2_rst_rate_limit,
2445 );
2446 227 $self->{http2_enabled} = 1;
2447  
2448 # h2c mode: HTTP/2 over cleartext (no TLS)
2449 227 ▶ if (!$self->{ssl}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"ssl"}) 220 7 227
2450 220 $self->{h2c_enabled} = 1;
2451 }
2452 } else {
2453 0 die <<"END_HTTP2_ERROR";
2454 HTTP/2 support requested but Net::HTTP2::nghttp2 is not installed, or is
2455 0 older than @{[ PAGI::Server::Protocol::HTTP2::MIN_NGHTTP2_VERSION() ]}.
2456  
2457 To install:
2458 cpanm Net::HTTP2::nghttp2
2459  
2460 Or disable HTTP/2:
2461 http2 => 0
2462 END_HTTP2_ERROR
2463 }
2464 }
2465  
2466 622 $self->SUPER::_init($params);
2467 }
2468  
2469 sub configure {
2470 626 ▶ my ($self, %params) = @_;
Subroutine configure: called CC=33 SCAR=48.7
Pod documented
2471  
2472 626 ▶ if (exists $params{app}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"app"}) 1 625 626
2473 1 my $app = delete $params{app};
2474 1 $self->{app} = PAGI::Server::AppNormalizer::normalize_app($app, 'app');
2475 }
2476 626 ▶ if (exists $params{host}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"host"}) 0 626 626
2477 0 $self->{host} = delete $params{host};
2478 }
2479 626 ▶ if (exists $params{port}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"port"}) 0 626 626
2480 0 $self->{port} = delete $params{port};
2481 }
2482 626 ▶ if (exists $params{socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"socket"}) 0 626 626
2483 0 delete $params{socket};
2484 }
2485 626 ▶ if (exists $params{socket_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"socket_mode"}) 0 626 626
2486 0 delete $params{socket_mode};
2487 }
2488 626 ▶ if (exists $params{listen}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"listen"}) 0 626 626
2489 0 delete $params{listen};
2490 }
2491 626 ▶ if (exists $params{ssl}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"ssl"}) 0 626 626
2492 0 $self->{ssl} = delete $params{ssl};
2493 }
2494 626 ▶ if (exists $params{extensions}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"extensions"}) 0 626 626
2495 0 $self->{extensions} = delete $params{extensions};
2496 }
2497 626 ▶ if (exists $params{access_log}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"access_log"}) 0 626 626
2498 0 $self->{access_log} = delete $params{access_log};
2499 }
2500 626 ▶ if (exists $params{access_log_format}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"access_log_format"}) 1 625 626
2501 1 $self->{access_log_format} = delete $params{access_log_format};
2502 $self->{_access_log_formatter} = $self->_compile_access_log_format(
2503 $self->{access_log_format}
2504 1 );
2505 }
2506 626 ▶ if (exists $params{quiet}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"quiet"}) 0 626 626
2507 0 $self->{quiet} = delete $params{quiet};
2508 }
2509 626 ▶ if (exists $params{log_level}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"log_level"}) 0 626 626
2510 0 my $level = delete $params{log_level};
2511 0 my %valid_levels = (debug => 1, info => 2, warn => 3, error => 4);
2512 die "Invalid log_level '$level' - must be one of: debug, info, warn, error\n"
2513 0 ▶ unless $valid_levels{$level};
Branch: 1 branch
BranchTrueFalseTotal
unless $valid_levels{$level} 0 0 0
2514 0 $self->{log_level} = $level;
2515 0 $self->{_log_level_num} = $valid_levels{$level};
2516 }
2517 626 ▶ if (exists $params{timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"timeout"}) 0 626 626
2518 0 $self->{timeout} = delete $params{timeout};
2519 }
2520 626 ▶ if (exists $params{max_header_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_header_size"}) 0 626 626
2521 0 $self->{max_header_size} = delete $params{max_header_size};
2522 }
2523 626 ▶ if (exists $params{max_header_count}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_header_count"}) 0 626 626
2524 0 $self->{max_header_count} = delete $params{max_header_count};
2525 }
2526 626 ▶ if (exists $params{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_body_size"}) 0 626 626
2527 0 $self->{max_body_size} = delete $params{max_body_size};
2528 }
2529 626 ▶ if (exists $params{workers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"workers"}) 0 626 626
2530 0 $self->{workers} = delete $params{workers};
2531 }
2532 626 ▶ if (exists $params{max_requests}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_requests"}) 0 626 626
2533 0 $self->{max_requests} = delete $params{max_requests};
2534 }
2535 626 ▶ if (exists $params{listener_backlog}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"listener_backlog"}) 0 626 626
2536 0 $self->{listener_backlog} = delete $params{listener_backlog};
2537 }
2538 626 ▶ if (exists $params{shutdown_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"shutdown_timeout"}) 0 626 626
2539 0 $self->{shutdown_timeout} = delete $params{shutdown_timeout};
2540 }
2541 626 ▶ if (exists $params{lifespan_startup_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"lifespan_startup_timeout"}) 1 625 626
2542 1 my $timeout = delete $params{lifespan_startup_timeout};
2543 1 ▶ die "Invalid lifespan_startup_timeout '0' - the PAGI Lifespan spec requires that a server must not block startup indefinitely waiting for a lifespan signal\n"
Branch: 1 branch
BranchTrueFalseTotal
if $timeout == 0 1 0 1
2544 if $timeout == 0;
2545 0 $self->{lifespan_startup_timeout} = $timeout;
2546 }
2547 625 ▶ if (exists $params{lifespan_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"lifespan_mode"}) 1 624 625
2548 1 my $mode = delete $params{lifespan_mode};
2549 1 ▶ die "Invalid lifespan_mode '$mode' - must be 'auto' or 'on' ('off' is nonconforming: the PAGI Lifespan spec forbids skipping the protocol)\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $mode =~ /\A(?:auto|on)\z/ 1 0 1
2550 unless $mode =~ /\A(?:auto|on)\z/;
2551 0 $self->{lifespan_mode} = $mode;
2552 }
2553 624 ▶ if (exists $params{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_receive_queue"}) 0 624 624
2554 0 $self->{max_receive_queue} = delete $params{max_receive_queue};
2555 }
2556 624 ▶ if (exists $params{max_ws_frame_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_ws_frame_size"}) 0 624 624
2557 0 $self->{max_ws_frame_size} = delete $params{max_ws_frame_size};
2558 }
2559 624 ▶ if (exists $params{max_connections}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"max_connections"}) 0 624 624
2560 0 $self->{max_connections} = delete $params{max_connections};
2561 }
2562 624 ▶ if (exists $params{request_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"request_timeout"}) 0 624 624
2563 0 $self->{request_timeout} = delete $params{request_timeout};
2564 }
2565 624 ▶ if (exists $params{ws_idle_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"ws_idle_timeout"}) 0 624 624
2566 0 $self->{ws_idle_timeout} = delete $params{ws_idle_timeout};
2567 }
2568 624 ▶ if (exists $params{sse_idle_timeout}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"sse_idle_timeout"}) 0 624 624
2569 0 $self->{sse_idle_timeout} = delete $params{sse_idle_timeout};
2570 }
2571 624 ▶ if (exists $params{http2}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $params{"http2"}) 0 624 624
2572 0 $self->{http2} = delete $params{http2};
2573 }
2574  
2575 624 $self->SUPER::configure(%params);
2576 }
2577  
2578 # Log levels: debug=1, info=2, warn=3, error=4
2579 151 my %_LOG_LEVELS = (debug => 1, info => 2, warn => 3, error => 4);
2580  
2581 sub _log {
2582 752 ▶ my ($self, $level, $msg) = @_;
Subroutine _log: called CC=5 SCAR=16.1
2583  
2584 752 ▶ my $level_num = $_LOG_LEVELS{$level} // 2;
Condition50%1/2
$_LOG_LEVELS{$level} // 2
l!l
7520
MC/DC0%0/1
$_LOG_LEVELS{$level} // 2
$_LOG_LEVELS{$level}
Truth table50%1/2
A
A= $_LOG_LEVELS{$level}
Aresult
11
00
2585 752 ▶ return if $level_num < $self->{_log_level_num};
Branch: 1 branch
BranchTrueFalseTotal
if $level_num < $self->{"_log_level_num"} 290 462 752
2586 462 ▶ return if $self->{quiet} && $level ne 'error';
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"quiet"} and $level ne "error" 431 31 462
Condition100%3/3
$self->{"quiet"} and $level ne "error"
!ll&&!rl&&r
247431
MC/DC100%2/2
$self->{"quiet"} and $level ne "error"
$self->{"quiet"} $level ne "error"
Truth table100%3/3
A and B
A= $self->{"quiet"}B= $level ne "error"
ABresult
0X0
100
111
2587 31 warn "$msg\n";
2588 }
2589  
2590 # Returns a human-readable TLS status string for the startup banner
2591 sub _tls_status_string {
2592 309 ▶ my ($self) = @_;
Subroutine _tls_status_string: called CC=5 SCAR=18.1
2593  
2594 309 ▶ if ($self->{disable_tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"disable_tls"}) 0 309 309
2595 0 ▶ return $TLS_AVAILABLE ? 'disabled' : 'n/a (disabled)';
Branch: 1 branch
BranchTrueFalseTotal
$PAGI::Server::TLS_AVAILABLE ? : 0 0 0
2596 }
2597 309 ▶ if ($self->{tls_enabled}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tls_enabled"}) 41 268 309
2598 41 return 'on';
2599 }
2600 268 ▶ return $TLS_AVAILABLE ? 'available' : 'not installed';
Branch: 1 branch
BranchTrueFalseTotal
$PAGI::Server::TLS_AVAILABLE ? : 268 0 268
2601 }
2602  
2603 # Returns a human-readable HTTP/2 status string for the startup banner
2604 sub _http2_status_string {
2605 309 ▶ my ($self) = @_;
Subroutine _http2_status_string: called CC=4 SCAR=14.2
2606  
2607 309 ▶ if ($self->{http2_enabled}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"http2_enabled"}) 3 306 309
2608 3 ▶ return $self->{h2c_enabled} ? 'on (h2c)' : 'on';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'h2c_enabled'} ? : 0 3 3
2609 }
2610 306 ▶ return $HTTP2_AVAILABLE ? 'available' : 'not installed';
Branch: 1 branch
BranchTrueFalseTotal
$PAGI::Server::HTTP2_AVAILABLE ? : 306 0 306
2611 }
2612  
2613 # Returns a human-readable Future::XS status string for the startup banner
2614 sub _future_xs_status_string {
2615 309 ▶ return 'on' if $FUTURE_XS_ENABLED;
Subroutine _future_xs_status_string: called CC=3 SCAR=11.7
Branch: 1 branch
BranchTrueFalseTotal
if $PAGI::Server::FUTURE_XS_ENABLED 0 309 309
2616 309 ▶ return 'available' if $FUTURE_XS_AVAILABLE;
Branch: 1 branch
BranchTrueFalseTotal
if $PAGI::Server::FUTURE_XS_AVAILABLE 0 309 309
2617 309 return 'not installed';
2618 }
2619  
2620 # Check if TLS modules are available
2621 sub _check_tls_available {
2622 51 ▶ my ($self) = @_;
Subroutine _check_tls_available: called CC=3 SCAR=13.3
2623  
2624 # Allow forcing TLS off for testing — return false to skip TLS setup
2625 51 ▶ if ($self->{disable_tls}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"disable_tls"}) 0 51 51
2626 0 return 0;
2627 }
2628  
2629 51 ▶ return 1 if $TLS_AVAILABLE;
Branch: 1 branch
BranchTrueFalseTotal
if $PAGI::Server::TLS_AVAILABLE 51 0 51
2630  
2631 0 die <<"END_TLS_ERROR";
2632 TLS support requested but required modules not installed.
2633  
2634 To enable HTTPS/TLS support, install:
2635  
2636 cpanm IO::Async::SSL IO::Socket::SSL
2637  
2638 Or on Debian/Ubuntu:
2639  
2640 apt-get install libio-socket-ssl-perl
2641  
2642 Then restart your application.
2643 END_TLS_ERROR
2644 }
2645  
2646 # Build SSL configuration parameters for use by both single-worker and multi-worker modes.
2647 # Returns a hashref of SSL params (including SSL_reuse_ctx) or undef if no SSL configured.
2648 sub _build_ssl_config {
2649 298 ▶ my ($self) = @_;
Subroutine _build_ssl_config: called CC=15 SCAR=27.4
2650 298 ▶ my $ssl = $self->{ssl} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $ssl = $self->{"ssl"} or return 253 45 298
2651  
2652 45 ▶ return unless $self->_check_tls_available;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->_check_tls_available 0 45 45
2653  
2654 45 my %ssl_params;
2655 45 $ssl_params{SSL_server} = 1;
2656 45 ▶ $ssl_params{SSL_cert_file} = $ssl->{cert_file} if $ssl->{cert_file};
Branch: 1 branch
BranchTrueFalseTotal
if $ssl->{"cert_file"} 45 0 45
2657 45 ▶ $ssl_params{SSL_key_file} = $ssl->{key_file} if $ssl->{key_file};
Branch: 1 branch
BranchTrueFalseTotal
if $ssl->{"key_file"} 45 0 45
2658 # SSL_version as a true floor: negotiate the highest version the client also
2659 # supports at or above min_version, so TLS 1.3 is offered. IO::Socket::SSL
2660 # pins to an exact version for a bare 'TLSv1_2' (the trailing ':' does NOT
2661 # mean "or higher"), so instead start from auto-negotiation ('SSLv23') and
2662 # exclude every protocol below the floor. A min_version outside the
2663 # documented TLSv1_2/TLSv1_3 set is passed through unchanged.
2664 45 my @tls_order = qw(SSLv2 SSLv3 TLSv1 TLSv1_1 TLSv1_2 TLSv1_3);
2665 45 ▶ my $min_version = $ssl->{min_version} // 'TLSv1_2';
Condition100%2/2
$ssl->{"min_version"} // "TLSv1_2"
l!l
540
MC/DC100%1/1
$ssl->{"min_version"} // "TLSv1_2"
$ssl->{"min_version"}
Truth table100%2/2
A
A= $ssl->{"min_version"}
Aresult
11
00
2666 45 ▶ if (grep { $_ eq $min_version } @tls_order) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_ eq $min_version;} @tls_order) { } 45 0 45
2667 45 my @below_floor;
2668 45 for my $v (@tls_order) {
2669 226 ▶ last if $v eq $min_version;
Branch: 1 branch
BranchTrueFalseTotal
if $v eq $min_version 45 181 226
2670 181 push @below_floor, "!$v";
2671 }
2672 45 $ssl_params{SSL_version} = join(':', 'SSLv23', @below_floor);
2673 }
2674 else {
2675 0 $ssl_params{SSL_version} = $min_version;
2676 }
2677 $ssl_params{SSL_cipher_list} = $ssl->{cipher_list}
2678 45 ▶ // 'ECDHE+AESGCM:DHE+AESGCM:ECDHE+CHACHA20:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA';
Condition100%2/2
$ssl->{"cipher_list"} // "ECDHE+AESGCM:DHE+AESGCM:ECDHE+CHACHA20:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
l!l
441
MC/DC100%1/1
$ssl->{"cipher_list"} // "ECDHE+AESGCM:DHE+AESGCM:ECDHE+CHACHA20:!aNULL:!eNULL:!EXPORT:!DES:!RC4:!MD5:!PSK:!aECDH:!EDH-DSS-DES-CBC3-SHA:!KRB5-DES-CBC3-SHA"
$ssl->{"cipher_list"}
Truth table100%2/2
A
A= $ssl->{"cipher_list"}
Aresult
11
00
2679  
2680 45 ▶ if ($ssl->{verify_client}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ssl->{'verify_client'}) { } 8 37 45
2681 # SSL_VERIFY_PEER (0x01) | SSL_VERIFY_FAIL_IF_NO_PEER_CERT (0x02)
2682 8 $ssl_params{SSL_verify_mode} = 0x03;
2683 8 ▶ $ssl_params{SSL_ca_file} = $ssl->{ca_file} if $ssl->{ca_file};
Branch: 1 branch
BranchTrueFalseTotal
if $ssl->{"ca_file"} 8 0 8
2684 } else {
2685 37 $ssl_params{SSL_verify_mode} = 0x00; # SSL_VERIFY_NONE
2686 }
2687  
2688 # ALPN negotiation for HTTP/2 support
2689 45 ▶ if ($self->{http2} && $HTTP2_AVAILABLE) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"http2"} and $PAGI::Server::HTTP2_AVAILABLE) 3 42 45
Condition66%2/3
$self->{"http2"} and $PAGI::Server::HTTP2_AVAILABLE
!ll&&!rl&&r
4203
MC/DC50%1/2
$self->{"http2"} and $PAGI::Server::HTTP2_AVAILABLE
$self->{"http2"} $PAGI::Server::HTTP2_AVAILABLE
Truth table66%2/3
A and B
A= $self->{"http2"}B= $PAGI::Server::HTTP2_AVAILABLE
ABresult
0X0
100
111
2690 3 $ssl_params{SSL_alpn_protocols} = ['h2', 'http/1.1'];
2691 3 $self->{http2_enabled} = 1;
2692 3 $self->{h2c_enabled} = 0; # TLS mode, not cleartext
2693 }
2694  
2695 # Pre-create shared SSL context to avoid per-connection CA bundle parsing
2696 45 my $ssl_ctx = IO::Socket::SSL::SSL_Context->new(\%ssl_params);
2697 45 $self->{_ssl_ctx} = $ssl_ctx;
2698 45 $ssl_params{SSL_reuse_ctx} = $ssl_ctx;
2699  
2700 # Mark TLS enabled and auto-add tls extension
2701 45 $self->{tls_enabled} = 1;
2702 45 ▶ $self->{extensions}{tls} = {} unless exists $self->{extensions}{tls};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $self->{"extensions"}{"tls"} 45 0 45
2703  
2704 45 return \%ssl_params;
2705 }
2706  
2707 =head2 run
2708  
2709 $server->run;
2710  
2711 Standalone entry point that creates an event loop, starts the server,
2712 and runs until shutdown. This is the simplest way to run a PAGI server:
2713  
2714 my $server = PAGI::Server->new(
2715 app => $app,
2716 port => 8080,
2717 );
2718 $server->run;
2719  
2720 For embedding in an existing IO::Async application, use the traditional
2721 pattern instead:
2722  
2723 my $loop = IO::Async::Loop->new;
2724 $loop->add($server);
2725 $server->listen->get;
2726 $loop->run;
2727  
2728 The C<run()> method handles:
2729  
2730 =over 4
2731  
2732 =item * Creating the event loop (respecting C<loop_type> if set)
2733  
2734 =item * Adding the server to the loop
2735  
2736 =item * Starting the listener
2737  
2738 =item * Setting up signal handlers for graceful shutdown
2739  
2740 =item * Running the event loop until shutdown
2741  
2742 =back
2743  
2744 =cut
2745  
2746 sub run {
2747 4 ▶ my ($self) = @_;
Subroutine run: called CC=5 SCAR=20.5
Pod documented
2748  
2749 4 my $loop = $self->_create_loop;
2750 4 $loop->add($self);
2751  
2752 # Start listening with error handling
2753 4 eval { $self->listen->get };
2754 2 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 2 2
2755 0 my $error = $@;
2756 0 my $port = $self->{port};
2757 0 ▶ if ($error =~ /Address already in use/i) {
Branch: 2 branches
BranchTrueFalseTotal
if ($error =~ /Address already in use/i) { } 0 0 0
elsif ($error =~ /Permission denied/i) { } 0 0 0
2758 0 die "Error: Port $port is already in use\n";
2759 }
2760 elsif ($error =~ /Permission denied/i) {
2761 0 die "Error: Permission denied to bind to port $port\n";
2762 }
2763 0 die "Error starting server: $error\n";
2764 }
2765  
2766 # Run the event loop (signal handlers were set up by listen())
2767 2 $loop->run;
2768  
2769 # If the loop stopped because every worker failed to start (multi-worker),
2770 # exit non-zero so a process supervisor restarts us rather than seeing a
2771 # clean exit from a server that never served anything.
2772 2 ▶ if ($self->{_workers_failed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_workers_failed"}) 1 1 2
2773 1 die "All workers failed to start; no workers remain\n";
2774 }
2775 }
2776  
2777 # Create an event loop, respecting loop_type config
2778 sub _create_loop {
2779 20 ▶ my ($self) = @_;
Subroutine _create_loop: called CC=4 SCAR=13.9
2780  
2781 20 ▶ if (my $loop_type = $self->{loop_type}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $loop_type = $self->{"loop_type"}) 2 18 20
2782 2 ▶ die "Invalid loop_type '$loop_type': must contain only letters, digits, and ::\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $loop_type =~ /\A[A-Za-z][A-Za-z0-9_]*(?:::[A-Za-z][A-Za-z0-9_]*)*\z/ 0 2 2
2783 unless $loop_type =~ /\A[A-Za-z][A-Za-z0-9_]*(?:::[A-Za-z][A-Za-z0-9_]*)*\z/;
2784 2 my $loop_class = "IO::Async::Loop::$loop_type";
2785 2 (my $loop_file = "$loop_class.pm") =~ s{::}{/}g;
2786 2 ▶ eval { require $loop_file }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require $loop_file } } or die "Cannot load loop backend '${loop_type}': $@\n" . "Install it with: cpanm $loop_class\n" 0 2 2
2787 or die "Cannot load loop backend '$loop_type': $@\n" .
2788 "Install it with: cpanm $loop_class\n";
2789 2 return $loop_class->new;
2790 }
2791  
2792 18 require IO::Async::Loop;
2793 18 return IO::Async::Loop->new;
2794 }
2795  
2796 # Listener fds this process's live PAGI::Server instances have published in
2797 # PAGI_REUSE. The env var is ambient process state meant for the exec-based
2798 # hot-restart handoff; without this registry, a SECOND server constructed in
2799 # the same process would collect a sibling's live listener as "inherited"
2800 # and reap it as unmatched -- closing it out from under both the sibling and
2801 # the event loop (IO::Async::Loop::Epoll croaks on the ensuing fd reuse).
2802 # Across exec the interpreter restarts and the registry is empty, so real
2803 # hot-restart inheritance is unaffected; forked workers inherit the copy and
2804 # correctly leave the master's fds alone.
2805 151 my %OWNED_REUSE_FDS;
2806  
2807 313 ▶async sub listen {
Subroutine listen: called CC=4 SCAR=14.0
Pod documented
2808 313 my ($self) = @_;
2809  
2810 313 ▶ return if $self->{running};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"running"} 0 313 313
2811  
2812 # Multi-worker mode uses a completely different code path
2813 313 ▶ if ($self->{workers} && $self->{workers} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"workers"} and $self->{"workers"} > 0) 27 286 313
Condition66%2/3
$self->{"workers"} and $self->{"workers"} > 0
!ll&&!rl&&r
286027
MC/DC50%1/2
$self->{"workers"} and $self->{"workers"} > 0
$self->{"workers"} $self->{"workers"} > 0
Truth table66%2/3
A and B
A= $self->{"workers"}B= $self->{"workers"} > 0
ABresult
0X0
100
111
2814 27 return $self->_listen_multiworker;
2815 }
2816  
2817 286 return await $self->_listen_singleworker;
2818 151 }
2819  
2820 # Single-worker mode - uses IO::Async normally
2821 286 ▶async sub _listen_singleworker {
Subroutine _listen_singleworker: called CC=43 SCAR=40.9
2822 286 my ($self) = @_;
2823  
2824 286 weaken(my $weak_self = $self);
2825  
2826 # Run lifespan startup before accepting connections
2827 286 my $startup_result = await $self->_run_lifespan_startup;
2828  
2829 286 ▶ if (!$startup_result->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($startup_result->{"success"}) 4 282 286
2830 4 ▶ my $message = $startup_result->{message} // 'Lifespan startup failed';
Condition50%1/2
$startup_result->{"message"} // "Lifespan startup failed"
l!l
40
MC/DC0%0/1
$startup_result->{"message"} // "Lifespan startup failed"
$startup_result->{"message"}
Truth table50%1/2
A
A= $startup_result->{"message"}
Aresult
11
00
2831 4 $self->_log(error => "PAGI Server startup failed: $message");
2832 4 die "Lifespan startup failed: $message\n";
2833 }
2834  
2835 # Collect any inherited fds (from PAGI_REUSE or LISTEN_FDS)
2836 282 my $inherited = $self->_collect_inherited_fds;
2837  
2838 # Iterate over listeners array, creating one IO::Async::Listener per spec
2839 282 my @listen_entries;
2840 282 for my $spec (@{$self->{listeners}}) {
2841  
2842 # Check for inherited fd matching this spec
2843 285 ▶ my $match_key = $spec->{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'type'} eq 'unix' ? : 11 274 285
2844 ? "unix:$spec->{path}"
2845 : "$spec->{host}:$spec->{port}";
2846  
2847 285 ▶ if (my $inh = delete $inherited->{$match_key}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $inh = delete $inherited->{$match_key}) 3 282 285
2848 # Reuse inherited fd — skip bind/listen entirely
2849 3 $spec->{_inherited} = 1;
2850  
2851 3 my $handle = $inh->{handle};
2852 3 ▶ if (!$handle) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($handle) 2 1 3
2853 2 ▶ my $class = $inh->{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
$inh->{'type'} eq 'unix' ? : 1 1 2
2854 ? 'IO::Socket::UNIX' : 'IO::Socket::INET';
2855 2 ▶ require IO::Socket::UNIX if $inh->{type} eq 'unix';
Branch: 1 branch
BranchTrueFalseTotal
if $inh->{"type"} eq "unix" 1 1 2
2856 2 ▶ $handle = $class->new_from_fd($inh->{fd}, 'r')
Branch: 1 branch
BranchTrueFalseTotal
$handle = $class->new_from_fd($inh->{"fd"}, "r") or die qq[Cannot open inherited fd $inh->{"fd"}: $!\n] 0 2 2
2857 or die "Cannot open inherited fd $inh->{fd}: $!\n";
2858 }
2859  
2860 3 ▶ if ($inh->{type} eq 'tcp' && $handle->can('sockport')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inh->{"type"} eq "tcp" and $handle->can("sockport")) 1 2 3
Condition100%3/3
$inh->{"type"} eq "tcp" and $handle->can("sockport")
!ll&&!rl&&r
111
MC/DC100%2/2
$inh->{"type"} eq "tcp" and $handle->can("sockport")
$inh->{"type"} eq "tcp" $handle->can("sockport")
Truth table100%3/3
A and B
A= $inh->{"type"} eq "tcp"B= $handle->can("sockport")
ABresult
0X0
100
111
2861 1 $spec->{port} = $handle->sockport;
2862 1 ▶ $self->{bound_port} //= $spec->{port};
Condition33%1/3
$self->{"bound_port"} //= $spec->{"port"}
l!l&&r!l&&!r
010
MC/DC0%0/2
$self->{"bound_port"} //= $spec->{"port"}
$self->{"bound_port"} $spec->{"port"}
Truth table33%1/3
A //= B
A= $self->{"bound_port"}B= $spec->{"port"}
ABresult
1X1
011
000
2863 }
2864  
2865 3 my $spec_ref = $spec;
2866 3 weaken(my $weak_inner = $self);
2867 my $listener = IO::Async::Listener->new(
2868 handle => $handle,
2869 on_stream => sub {
2870 2 ▶ my ($l, $stream) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
2871 2 ▶ return unless $weak_inner;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_inner 0 2 2
2872 2 $weak_inner->_on_connection($stream, $spec_ref);
2873 },
2874 3 );
2875 3 $self->add_child($listener);
2876  
2877 3 $self->_log(info => "Reusing inherited fd $inh->{fd} for $match_key"
2878 . " (source: $inh->{source})");
2879  
2880 3 push @listen_entries, { listener => $listener, spec => $spec };
2881 3 next; # Skip normal bind/listen
2882 }
2883  
2884 282 my $spec_copy = $spec; # capture for closure
2885 my $listener = IO::Async::Listener->new(
2886 on_stream => sub {
2887 295 ▶ my ($listener, $stream) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
2888 295 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 295 295
2889 295 $weak_self->_on_connection($stream, $spec_copy);
2890 },
2891 282 );
2892  
2893 282 $self->add_child($listener);
2894  
2895 # Build listener options
2896 my %listen_opts = (
2897 queuesize => $self->{listener_backlog},
2898 282 );
2899  
2900 282 ▶ if ($spec->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{'type'} eq 'unix') { } 10 272 282
2901 # Remove stale socket file if it exists
2902 10 ▶ unlink $spec->{path} if -e $spec->{path};
Branch: 1 branch
BranchTrueFalseTotal
if -e $spec->{"path"} 1 9 10
2903  
2904 $listen_opts{addr} = {
2905 family => 'unix',
2906 socktype => 'stream',
2907 path => $spec->{path},
2908 10 };
2909  
2910 10 ▶ if ($self->{tls_enabled}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tls_enabled"}) 0 10 10
2911 0 $self->_log(info => "Note: TLS is configured but does not apply to Unix socket $spec->{path}");
2912 }
2913 } else {
2914 # TCP listener
2915 $listen_opts{addr} = {
2916 family => 'inet',
2917 socktype => 'stream',
2918 ip => $spec->{host},
2919 port => $spec->{port},
2920 272 };
2921  
2922 # Add SSL options if configured (TCP only)
2923 272 ▶ if (my $ssl_params = $self->_build_ssl_config) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ssl_params = $self->_build_ssl_config) 35 237 272
2924 35 $listen_opts{extensions} = ['SSL'];
2925 35 %listen_opts = (%listen_opts, %$ssl_params);
2926  
2927 $listen_opts{on_ssl_error} = sub {
2928 4 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=2 SCAR=7.2
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 4 4
2929 4 $weak_self->_log(debug => "SSL handshake failed: $_[0]");
2930 35 };
2931 }
2932 }
2933  
2934 # Set restrictive umask for Unix socket bind to prevent brief
2935 # permission window (CVE-2023-45145 pattern in Redis)
2936 282 my $old_umask;
2937 282 ▶ if ($spec->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{"type"} eq "unix") 10 272 282
2938 10 $old_umask = umask(0177); # Owner-only until chmod
2939 }
2940  
2941 # Start listening ($^F raised so fd survives exec for hot restart)
2942 {
2943 282 local $^F = 1023;
2944 282 await $listener->listen(%listen_opts);
2945 }
2946  
2947 # Restore umask after bind
2948 282 ▶ umask($old_umask) if defined $old_umask;
Branch: 1 branch
BranchTrueFalseTotal
if defined $old_umask 10 272 282
2949  
2950 # Configure accept error handler after listen() to avoid SSL extension conflicts
2951 282 eval {
2952 $listener->configure(
2953 on_accept_error => sub {
2954 0 ▶ my ($listener, $error) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
2955 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
2956 0 $weak_self->_on_accept_error($error);
2957 },
2958 282 );
2959 };
2960 282 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 282 0 282
2961 282 $self->_log(debug => "Could not configure on_accept_error (likely SSL listener): $@");
2962 }
2963  
2964 # Post-listen setup
2965 282 ▶ if ($spec->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{'type'} eq 'unix') { } 10 272 282
2966 # Apply socket permissions if configured
2967 10 ▶ if (defined $spec->{socket_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"socket_mode"}) 1 9 10
2968 1 chmod $spec->{socket_mode}, $spec->{path};
2969 }
2970 } else {
2971 # Store the actual bound port from the listener's read handle
2972 272 my $socket = $listener->read_handle;
2973 272 ▶ if ($socket && $socket->can('sockport')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($socket and $socket->can("sockport")) 272 0 272
Condition33%1/3
$socket and $socket->can("sockport")
!ll&&!rl&&r
00272
MC/DC0%0/2
$socket and $socket->can("sockport")
$socket $socket->can("sockport")
Truth table33%1/3
A and B
A= $socketB= $socket->can("sockport")
ABresult
0X0
100
111
2974 272 my $bound = $socket->sockport;
2975 272 $spec->{port} = $bound; # update spec with actual port
2976 272 ▶ $self->{bound_port} //= $bound; # first TCP port wins
Condition33%1/3
$self->{"bound_port"} //= $bound
l!l&&r!l&&!r
02720
MC/DC0%0/2
$self->{"bound_port"} //= $bound
$self->{"bound_port"} $bound
Truth table33%1/3
A //= B
A= $self->{"bound_port"}B= $bound
ABresult
1X1
011
000
2977 }
2978 }
2979  
2980 # Register in PAGI_REUSE for hot restart fd inheritance
2981 282 my $rh = $listener->read_handle;
2982 282 ▶ if ($rh) {
Branch: 1 branch
BranchTrueFalseTotal
if ($rh) 282 0 282
2983 282 my $fd = fileno($rh);
2984 282 ▶ if (defined $fd) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $fd) 282 0 282
2985 282 ▶ my $reuse_key = $spec->{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'type'} eq 'unix' ? : 10 272 282
2986 ? "unix:$spec->{path}:$fd"
2987 : "$spec->{host}:$spec->{port}:$fd";
2988 282 $spec->{_reuse_key} = $reuse_key;
2989 282 $spec->{_reuse_fd} = $fd;
2990 282 $OWNED_REUSE_FDS{$fd} = 1;
2991 282 ▶ $ENV{PAGI_REUSE} = length($ENV{PAGI_REUSE} // '')
Branch: 1 branch
BranchTrueFalseTotal
length($ENV{'PAGI_REUSE'} // '') ? : 6 276 282
Condition100%2/2
$ENV{"PAGI_REUSE"} // ""
l!l
21765
MC/DC100%1/1
$ENV{"PAGI_REUSE"} // ""
$ENV{"PAGI_REUSE"}
Truth table100%2/2
A
A= $ENV{"PAGI_REUSE"}
Aresult
11
00
2992 ? "$ENV{PAGI_REUSE},$reuse_key"
2993 : $reuse_key;
2994 }
2995 }
2996  
2997 282 push @listen_entries, { listener => $listener, spec => $spec };
2998 }
2999  
3000 # Warn about unmatched inherited fds
3001 282 for my $key (sort keys %$inherited) {
3002 0 my $inh = $inherited->{$key};
3003 0 $self->_log(warn => "Inherited fd $inh->{fd} ($key) does not match "
3004 . "any listener spec — closing");
3005 0 ▶ if ($inh->{handle}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inh->{'handle'}) { } 0 0 0
3006 0 close($inh->{handle});
3007 } else {
3008 0 POSIX::close($inh->{fd});
3009 }
3010 }
3011  
3012 282 $self->{_listen_entries} = \@listen_entries;
3013 # Backward compat: keep $self->{listener} pointing to first entry
3014 282 ▶ $self->{listener} = $listen_entries[0]{listener} if @listen_entries;
Branch: 1 branch
BranchTrueFalseTotal
if @listen_entries 282 0 282
3015 282 $self->{running} = 1;
3016  
3017 # Set up signal handlers for graceful shutdown (single-worker mode)
3018 # Note: Windows doesn't support Unix signals, so this is skipped there
3019 282 unless (WIN32) {
3020 282 my $shutdown_triggered = 0;
3021 my $shutdown_handler = sub {
3022 2 ▶ return if $shutdown_triggered;
Subroutine __ANON__: called CC=2 SCAR=8.5
Branch: 1 branch
BranchTrueFalseTotal
if $shutdown_triggered 0 2 2
3023 2 $shutdown_triggered = 1;
3024 $self->adopt_future(
3025 $self->shutdown->on_done(sub {
3026 2 ▶ $self->loop->stop;
Subroutine __ANON__: called CC=1 SCAR=0.0
3027 })->on_fail(sub {
3028 0 ▶ my ($error) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
3029 0 $self->_log(error => "Shutdown error: $error");
3030 0 $self->loop->stop; # Still stop even on error
3031 })
3032 2 );
3033 282 };
3034 282 $self->loop->watch_signal(TERM => $shutdown_handler);
3035 282 $self->loop->watch_signal(INT => $shutdown_handler);
3036  
3037 # HUP in single-worker mode just warns (graceful restart requires multi-worker)
3038 282 my $weak_self = $self;
3039 282 weaken($weak_self);
3040 $self->loop->watch_signal(HUP => sub {
3041 $weak_self->_log(warn => "Received HUP signal (graceful restart only works in multi-worker mode)")
3042 0 ▶ if $weak_self && !$weak_self->{quiet};
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self and not $weak_self->{"quiet"} 0 0 0
Condition0%0/3
$weak_self and not $weak_self->{"quiet"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self and not $weak_self->{"quiet"}
$weak_self not $weak_self->{"quiet"}
Truth table0%0/3
A and not(B)
A= $weak_selfB= not $weak_self->{"quiet"}
ABresult
0X0
100
111
3043 282 });
3044  
3045 $self->loop->watch_signal(USR2 => sub {
3046 $weak_self->_log(warn => "Received USR2 signal (hot restart only works in multi-worker mode)")
3047 0 ▶ if $weak_self && !$weak_self->{quiet};
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self and not $weak_self->{"quiet"} 0 0 0
Condition0%0/3
$weak_self and not $weak_self->{"quiet"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self and not $weak_self->{"quiet"}
$weak_self not $weak_self->{"quiet"}
Truth table0%0/3
A and not(B)
A= $weak_selfB= not $weak_self->{"quiet"}
ABresult
0X0
100
111
3048 282 });
3049 }
3050  
3051 282 my $loop_class = ref($self->loop);
3052 282 $loop_class =~ s/^IO::Async::Loop:://; # Shorten for display
3053 282 my $max_conn = $self->effective_max_connections;
3054 282 my $tls_status = $self->_tls_status_string;
3055 282 my $http2_status = $self->_http2_status_string;
3056 282 my $future_xs_status = $self->_future_xs_status_string;
3057  
3058 # Warn if access_log is a terminal (slow for benchmarks)
3059 282 ▶ if ($self->{access_log} && -t $self->{access_log}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"access_log"} and -t $self->{"access_log"}) 0 282 282
Condition66%2/3
$self->{"access_log"} and -t $self->{"access_log"}
!ll&&!rl&&r
142680
MC/DC0%0/2
$self->{"access_log"} and -t $self->{"access_log"}
$self->{"access_log"} -t $self->{"access_log"}
Truth table66%2/3
A and B
A= $self->{"access_log"}B= -t $self->{"access_log"}
ABresult
0X0
100
111
3060 0 $self->_log(warn =>
3061 "access_log is a terminal; this may impact performance. " .
3062 "Consider redirecting to a file or setting access_log => undef for benchmarks."
3063 );
3064 }
3065  
3066 # Log listening banner
3067 282 ▶ my $scheme = $self->{tls_enabled} ? 'https' : 'http';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tls_enabled'} ? : 35 247 282
3068 282 ▶ if (@listen_entries == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (@listen_entries == 1) { } 279 3 282
3069 279 my $spec = $listen_entries[0]{spec};
3070 279 ▶ if ($spec->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($spec->{'type'} eq 'unix') { } 8 271 279
3071 8 $self->_log(info => "PAGI Server listening on unix:$spec->{path} (loop: $loop_class, max_conn: $max_conn, http2: $http2_status, tls: $tls_status, future_xs: $future_xs_status)");
3072 } else {
3073 271 $self->_log(info => "PAGI Server listening on $scheme://$spec->{host}:$spec->{port}/ (loop: $loop_class, max_conn: $max_conn, http2: $http2_status, tls: $tls_status, future_xs: $future_xs_status)");
3074 }
3075 } else {
3076 3 my @addrs;
3077 3 for my $entry (@listen_entries) {
3078 6 my $s = $entry->{spec};
3079 6 ▶ if ($s->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($s->{'type'} eq 'unix') { } 3 3 6
3080 3 push @addrs, "unix:$s->{path}";
3081 } else {
3082 3 push @addrs, "$scheme://$s->{host}:$s->{port}/";
3083 }
3084 }
3085 3 $self->_log(info => "PAGI Server listening on: " . join(', ', @addrs) . " (loop: $loop_class, max_conn: $max_conn, http2: $http2_status, tls: $tls_status, future_xs: $future_xs_status)");
3086 }
3087  
3088 # Warn in production if using default max_connections
3089 282 ▶ if (($ENV{PAGI_ENV} // '') eq 'production' && !$self->{max_connections}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ENV{"PAGI_ENV"} // "") eq "production" and not $self->{"max_connections"}) 1 281 282
Condition80%4/5
($ENV{"PAGI_ENV"} // "") eq "production" and not $self->{"max_connections"}
!ll&&!rl&&r
28101
$ENV{"PAGI_ENV"} // ""
l!l
1281
MC/DC50%1/2
($ENV{"PAGI_ENV"} // "") eq "production" and not $self->{"max_connections"}
$ENV{"PAGI_ENV"} not $self->{"max_connections"}
Truth table66%2/3
A and not(B)
A= $ENV{"PAGI_ENV"}B= not $self->{"max_connections"}
ABresult
0X0
100
111
3090 1 $self->_log(warn =>
3091 "Using default max_connections (1000). For production, consider tuning this value " .
3092 "based on your workload. See 'perldoc PAGI::Server' for guidance."
3093 );
3094 }
3095  
3096 282 return $self;
3097 151 }
3098  
3099 # Multi-worker mode - forks workers, each with their own event loop
3100 sub _listen_multiworker {
3101 27 ▶ my ($self) = @_;
Subroutine _listen_multiworker: called CC=49 SCAR=63.1
3102  
3103 27 my $workers = $self->{workers};
3104 27 my $reuseport = $self->{reuseport};
3105  
3106 # Create all listening sockets before forking workers
3107 27 my @listen_entries;
3108  
3109 # Collect any inherited fds (from PAGI_REUSE or LISTEN_FDS)
3110 27 my $inherited = $self->_collect_inherited_fds;
3111  
3112 27 for my $spec (@{$self->{listeners}}) {
3113 27 my $socket;
3114  
3115 # Check for inherited fd matching this spec
3116 27 ▶ my $match_key = $spec->{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
$spec->{'type'} eq 'unix' ? : 0 27 27
3117 ? "unix:$spec->{path}"
3118 : "$spec->{host}:$spec->{port}";
3119  
3120 27 ▶ if (my $inh = delete $inherited->{$match_key}) {
Branch: 3 branches
BranchTrueFalseTotal
if (my $inh = delete $inherited->{$match_key}) { } 0 27 27
elsif ($spec->{'type'} eq 'unix') { } 0 27 27
elsif ($reuseport) { } 0 27 27
3121 0 $spec->{_inherited} = 1;
3122  
3123 0 ▶ if ($inh->{handle}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inh->{'handle'}) { } 0 0 0
3124 0 $socket = $inh->{handle};
3125 } else {
3126 0 ▶ my $class = $inh->{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
$inh->{'type'} eq 'unix' ? : 0 0 0
3127 ? 'IO::Socket::UNIX' : 'IO::Socket::INET';
3128 0 ▶ require IO::Socket::UNIX if $inh->{type} eq 'unix';
Branch: 1 branch
BranchTrueFalseTotal
if $inh->{"type"} eq "unix" 0 0 0
3129 0 ▶ $socket = $class->new_from_fd($inh->{fd}, 'r')
Branch: 1 branch
BranchTrueFalseTotal
$socket = $class->new_from_fd($inh->{"fd"}, "r") or die qq[Cannot open inherited fd $inh->{"fd"}: $!\n] 0 0 0
3130 or die "Cannot open inherited fd $inh->{fd}: $!\n";
3131 }
3132  
3133 0 ▶ if ($inh->{type} eq 'tcp' && $socket->can('sockport')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inh->{"type"} eq "tcp" and $socket->can("sockport")) 0 0 0
Condition0%0/3
$inh->{"type"} eq "tcp" and $socket->can("sockport")
!ll&&!rl&&r
000
MC/DC0%0/2
$inh->{"type"} eq "tcp" and $socket->can("sockport")
$inh->{"type"} eq "tcp" $socket->can("sockport")
Truth table0%0/3
A and B
A= $inh->{"type"} eq "tcp"B= $socket->can("sockport")
ABresult
0X0
100
111
3134 0 $spec->{bound_port} = $socket->sockport;
3135 0 ▶ $self->{bound_port} //= $spec->{bound_port};
Condition0%0/3
$self->{"bound_port"} //= $spec->{"bound_port"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"bound_port"} //= $spec->{"bound_port"}
$self->{"bound_port"} $spec->{"bound_port"}
Truth table0%0/3
A //= B
A= $self->{"bound_port"}B= $spec->{"bound_port"}
ABresult
1X1
011
000
3136 }
3137  
3138 0 $self->_log(info => "Reusing inherited fd $inh->{fd} for $match_key"
3139 . " (source: $inh->{source})");
3140 }
3141 elsif ($spec->{type} eq 'unix') {
3142 # Unix socket: parent creates, workers inherit
3143 0 ▶ unlink $spec->{path} if -e $spec->{path};
Branch: 1 branch
BranchTrueFalseTotal
if -e $spec->{"path"} 0 0 0
3144  
3145 # Set restrictive umask for bind (CVE-2023-45145 mitigation)
3146 0 my $old_umask = umask(0177);
3147  
3148 0 require IO::Socket::UNIX;
3149 {
3150 0 local $^F = 1023;
3151 $socket = IO::Socket::UNIX->new(
3152 Local => $spec->{path},
3153 Type => Socket::SOCK_STREAM(),
3154 Listen => $self->{listener_backlog},
3155 0 ▶ ) or die "Cannot create Unix socket $spec->{path}: $!";
Branch: 1 branch
BranchTrueFalseTotal
$socket = "IO::Socket::UNIX"->new("Local", $spec->{"path"}, "Type", 1, "Listen", $self->{"listener_backlog"}) or die qq[Cannot create Unix socket $spec->{"path"}: $!] 0 0 0
3156 }
3157  
3158 0 umask($old_umask);
3159  
3160 0 ▶ if (defined $spec->{socket_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $spec->{"socket_mode"}) 0 0 0
3161 chmod($spec->{socket_mode}, $spec->{path})
3162 0 ▶ or die "Cannot chmod $spec->{path}: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
chmod $spec->{"socket_mode"}, $spec->{"path"} or die qq[Cannot chmod $spec->{"path"}: $!\n] 0 0 0
3163 }
3164  
3165 # Register in PAGI_REUSE for hot restart fd inheritance
3166 0 ▶ if ($socket && !$spec->{_inherited}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($socket and not $spec->{"_inherited"}) 0 0 0
Condition0%0/3
$socket and not $spec->{"_inherited"}
!ll&&!rl&&r
000
MC/DC0%0/2
$socket and not $spec->{"_inherited"}
$socket not $spec->{"_inherited"}
Truth table0%0/3
A and not(B)
A= $socketB= not $spec->{"_inherited"}
ABresult
0X0
100
111
3167 0 my $fd = fileno($socket);
3168 0 my $reuse_key = "unix:$spec->{path}:$fd";
3169 0 $spec->{_reuse_key} = $reuse_key;
3170 0 $spec->{_reuse_fd} = $fd;
3171 0 $OWNED_REUSE_FDS{$fd} = 1;
3172 0 ▶ $ENV{PAGI_REUSE} = length($ENV{PAGI_REUSE} // '')
Branch: 1 branch
BranchTrueFalseTotal
length($ENV{'PAGI_REUSE'} // '') ? : 0 0 0
Condition0%0/2
$ENV{"PAGI_REUSE"} // ""
l!l
00
MC/DC0%0/1
$ENV{"PAGI_REUSE"} // ""
$ENV{"PAGI_REUSE"}
Truth table0%0/2
A
A= $ENV{"PAGI_REUSE"}
Aresult
11
00
3173 ? "$ENV{PAGI_REUSE},$reuse_key"
3174 : $reuse_key;
3175 }
3176 } elsif ($reuseport) {
3177 # reuseport TCP: probe to get port, workers create their own
3178 # Note: reuseport sockets are not registered in PAGI_REUSE because
3179 # each worker creates its own socket. fd inheritance for reuseport
3180 # mode is not currently supported — use shared-socket mode for
3181 # hot restart / systemd socket activation.
3182 my $probe_socket = IO::Socket::INET->new(
3183 LocalAddr => $spec->{host},
3184 LocalPort => $spec->{port},
3185 0 ▶ Proto => 'tcp',
Branch: 1 branch
BranchTrueFalseTotal
my $probe_socket = "IO::Socket::INET"->new("LocalAddr", $spec->{"host"}, "LocalPort", $spec->{"port"}, "Proto", "tcp", "Listen", 1, "ReuseAddr", 1, "ReusePort", 1) or die qq[Cannot bind to $spec->{"host"}:$spec->{"port"}: $!] 0 0 0
3186 Listen => 1,
3187 ReuseAddr => 1,
3188 ReusePort => 1,
3189 ) or die "Cannot bind to $spec->{host}:$spec->{port}: $!";
3190 0 $spec->{bound_port} = $probe_socket->sockport;
3191 0 ▶ $self->{bound_port} //= $spec->{bound_port};
Condition0%0/3
$self->{"bound_port"} //= $spec->{"bound_port"}
l!l&&r!l&&!r
000
MC/DC0%0/2
$self->{"bound_port"} //= $spec->{"bound_port"}
$self->{"bound_port"} $spec->{"bound_port"}
Truth table0%0/3
A //= B
A= $self->{"bound_port"}B= $spec->{"bound_port"}
ABresult
1X1
011
000
3192 0 close($probe_socket);
3193 } else {
3194 # Shared-socket TCP: parent creates, workers inherit
3195 {
3196 27 local $^F = 1023;
3197 $socket = IO::Socket::INET->new(
3198 LocalAddr => $spec->{host},
3199 LocalPort => $spec->{port},
3200 Proto => 'tcp',
3201 Listen => $self->{listener_backlog},
3202 27 ▶ ReuseAddr => 1,
Branch: 1 branch
BranchTrueFalseTotal
$socket = "IO::Socket::INET"->new("LocalAddr", $spec->{"host"}, "LocalPort", $spec->{"port"}, "Proto", "tcp", "Listen", $self->{"listener_backlog"}, "ReuseAddr", 1, "Blocking", 0) or die qq[Cannot create listening socket on $spec->{"host"}:$spec->{"port"}: $!] 0 27 27
3203 Blocking => 0,
3204 ) or die "Cannot create listening socket on $spec->{host}:$spec->{port}: $!";
3205 }
3206 27 $spec->{bound_port} = $socket->sockport;
3207 27 ▶ $self->{bound_port} //= $spec->{bound_port};
Condition33%1/3
$self->{"bound_port"} //= $spec->{"bound_port"}
l!l&&r!l&&!r
0270
MC/DC0%0/2
$self->{"bound_port"} //= $spec->{"bound_port"}
$self->{"bound_port"} $spec->{"bound_port"}
Truth table33%1/3
A //= B
A= $self->{"bound_port"}B= $spec->{"bound_port"}
ABresult
1X1
011
000
3208  
3209 # Register in PAGI_REUSE for hot restart fd inheritance
3210 27 ▶ if ($socket && !$spec->{_inherited}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($socket and not $spec->{"_inherited"}) 27 0 27
Condition33%1/3
$socket and not $spec->{"_inherited"}
!ll&&!rl&&r
0027
MC/DC0%0/2
$socket and not $spec->{"_inherited"}
$socket not $spec->{"_inherited"}
Truth table33%1/3
A and not(B)
A= $socketB= not $spec->{"_inherited"}
ABresult
0X0
100
111
3211 27 my $fd = fileno($socket);
3212 27 my $reuse_key = "$spec->{host}:" . $socket->sockport . ":$fd";
3213 27 $spec->{_reuse_key} = $reuse_key;
3214 27 $spec->{_reuse_fd} = $fd;
3215 27 $OWNED_REUSE_FDS{$fd} = 1;
3216 27 ▶ $ENV{PAGI_REUSE} = length($ENV{PAGI_REUSE} // '')
Branch: 1 branch
BranchTrueFalseTotal
length($ENV{'PAGI_REUSE'} // '') ? : 0 27 27
Condition100%2/2
$ENV{"PAGI_REUSE"} // ""
l!l
621
MC/DC100%1/1
$ENV{"PAGI_REUSE"} // ""
$ENV{"PAGI_REUSE"}
Truth table100%2/2
A
A= $ENV{"PAGI_REUSE"}
Aresult
11
00
3217 ? "$ENV{PAGI_REUSE},$reuse_key"
3218 : $reuse_key;
3219 }
3220 }
3221  
3222 27 push @listen_entries, { socket => $socket, spec => $spec };
3223 }
3224  
3225 # Warn about unmatched inherited fds
3226 27 for my $key (sort keys %$inherited) {
3227 0 my $inh = $inherited->{$key};
3228 0 $self->_log(warn => "Inherited fd $inh->{fd} ($key) does not match "
3229 . "any listener spec — closing");
3230 0 ▶ if ($inh->{handle}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($inh->{'handle'}) { } 0 0 0
3231 0 close($inh->{handle});
3232 } else {
3233 0 POSIX::close($inh->{fd});
3234 }
3235 }
3236  
3237 27 $self->{_listen_entries} = \@listen_entries;
3238 # Backward compat: keep listen_socket pointing to first entry's socket
3239 27 ▶ $self->{listen_socket} = $listen_entries[0]{socket} if @listen_entries && $listen_entries[0]{socket};
Branch: 1 branch
BranchTrueFalseTotal
if @listen_entries and $listen_entries[0]{"socket"} 27 0 27
Condition33%1/3
@listen_entries and $listen_entries[0]{"socket"}
!ll&&!rl&&r
0027
MC/DC0%0/2
@listen_entries and $listen_entries[0]{"socket"}
@listen_entries $listen_entries[0]{"socket"}
Truth table33%1/3
A and B
A= @listen_entriesB= $listen_entries[0]{"socket"}
ABresult
0X0
100
111
3240  
3241 27 $self->{running} = 1;
3242  
3243 # Validate TLS modules and set tls_enabled before forking workers
3244 27 ▶ if ($self->{ssl}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"ssl"}) 6 21 27
3245 6 $self->_check_tls_available;
3246 6 $self->{tls_enabled} = 1;
3247 }
3248  
3249 27 ▶ my $scheme = $self->{ssl} ? 'https' : 'http';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'ssl'} ? : 6 21 27
3250 27 my $loop_class = ref($self->loop);
3251 27 $loop_class =~ s/^IO::Async::Loop:://; # Shorten for display
3252 27 ▶ my $mode = $reuseport ? 'reuseport' : 'shared-socket';
Branch: 1 branch
BranchTrueFalseTotal
$reuseport ? : 0 27 27
3253 27 my $max_conn = $self->effective_max_connections;
3254 27 my $tls_status = $self->_tls_status_string;
3255 27 my $http2_status = $self->_http2_status_string;
3256 27 my $future_xs_status = $self->_future_xs_status_string;
3257  
3258 # Warn if access_log is a terminal (slow for benchmarks)
3259 27 ▶ if ($self->{access_log} && -t $self->{access_log}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"access_log"} and -t $self->{"access_log"}) 0 27 27
Condition66%2/3
$self->{"access_log"} and -t $self->{"access_log"}
!ll&&!rl&&r
3240
MC/DC0%0/2
$self->{"access_log"} and -t $self->{"access_log"}
$self->{"access_log"} -t $self->{"access_log"}
Truth table66%2/3
A and B
A= $self->{"access_log"}B= -t $self->{"access_log"}
ABresult
0X0
100
111
3260 0 $self->_log(warn =>
3261 "access_log is a terminal; this may impact performance. " .
3262 "Consider redirecting to a file or setting access_log => undef for benchmarks."
3263 );
3264 }
3265  
3266 # Log listening banner for all listeners
3267 27 my @addrs;
3268 27 for my $entry (@listen_entries) {
3269 27 my $s = $entry->{spec};
3270 27 ▶ if ($s->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($s->{'type'} eq 'unix') { } 0 27 27
3271 0 push @addrs, "unix:$s->{path}";
3272 } else {
3273 27 ▶ my $port = $s->{bound_port} // $s->{port};
Condition33%1/3
$s->{"bound_port"} // $s->{"port"}
l!l&&r!l&&!r
2700
MC/DC0%0/2
$s->{"bound_port"} // $s->{"port"}
$s->{"bound_port"} $s->{"port"}
Truth table33%1/3
A // B
A= $s->{"bound_port"}B= $s->{"port"}
ABresult
1X1
011
000
3274 27 push @addrs, "$scheme://$s->{host}:$port/";
3275 }
3276 }
3277 27 my $addr_str = join(', ', @addrs);
3278 27 $self->_log(info => "PAGI Server (multi-worker, $mode) listening on $addr_str with $workers workers (loop: $loop_class, max_conn: $max_conn/worker, http2: $http2_status, tls: $tls_status, future_xs: $future_xs_status)");
3279  
3280 # Warn in production if using default max_connections
3281 27 ▶ if (($ENV{PAGI_ENV} // '') eq 'production' && !$self->{max_connections}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ENV{"PAGI_ENV"} // "") eq "production" and not $self->{"max_connections"}) 3 24 27
Condition80%4/5
($ENV{"PAGI_ENV"} // "") eq "production" and not $self->{"max_connections"}
!ll&&!rl&&r
2403
$ENV{"PAGI_ENV"} // ""
l!l
324
MC/DC50%1/2
($ENV{"PAGI_ENV"} // "") eq "production" and not $self->{"max_connections"}
$ENV{"PAGI_ENV"} not $self->{"max_connections"}
Truth table66%2/3
A and not(B)
A= $ENV{"PAGI_ENV"}B= not $self->{"max_connections"}
ABresult
0X0
100
111
3282 3 $self->_log(warn =>
3283 "Using default max_connections (1000). For production, consider tuning this value " .
3284 "based on your workload. See 'perldoc PAGI::Server' for guidance."
3285 );
3286 }
3287  
3288 27 my $loop = $self->loop;
3289  
3290 # Fork the workers FIRST, before setting up signal handlers.
3291 # This prevents children from inheriting the parent's sigpipe setup,
3292 # which can cause issues with Ctrl-C signal delivery on macOS.
3293 27 for my $i (1 .. $workers) {
3294 40 $self->_spawn_worker(\@listen_entries, $i);
3295 }
3296  
3297 # Set up signal handlers for parent process AFTER forking
3298 # Note: Windows doesn't support Unix signals, so this is skipped there
3299 11 unless (WIN32) {
3300 11 ▶ $loop->watch_signal(TERM => sub { $self->_initiate_multiworker_shutdown });
Subroutine __ANON__: called CC=1 SCAR=0.0
3301 11 ▶ $loop->watch_signal(INT => sub { $self->_initiate_multiworker_shutdown });
Subroutine __ANON__: called CC=1 SCAR=0.0
3302 11 ▶ $loop->watch_signal(HUP => sub { $self->_graceful_restart });
Subroutine __ANON__: not called CC=1 SCAR=1.2
3303 11 ▶ $loop->watch_signal(TTIN => sub { $self->_increase_workers });
Subroutine __ANON__: not called CC=1 SCAR=1.2
3304 11 ▶ $loop->watch_signal(TTOU => sub { $self->_decrease_workers });
Subroutine __ANON__: not called CC=1 SCAR=1.2
3305 11 ▶ $loop->watch_signal(USR2 => sub { $self->_hot_restart });
Subroutine __ANON__: not called CC=1 SCAR=1.2
3306 }
3307  
3308 # Start heartbeat monitor if enabled
3309 11 ▶ if ($self->{heartbeat_timeout} && $self->{heartbeat_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"heartbeat_timeout"} and $self->{"heartbeat_timeout"} > 0) 11 0 11
Condition33%1/3
$self->{"heartbeat_timeout"} and $self->{"heartbeat_timeout"} > 0
!ll&&!rl&&r
0011
MC/DC0%0/2
$self->{"heartbeat_timeout"} and $self->{"heartbeat_timeout"} > 0
$self->{"heartbeat_timeout"} $self->{"heartbeat_timeout"} > 0
Truth table33%1/3
A and B
A= $self->{"heartbeat_timeout"}B= $self->{"heartbeat_timeout"} > 0
ABresult
0X0
100
111
3310 11 my $hb_timeout = $self->{heartbeat_timeout};
3311 11 my $check_interval = $hb_timeout / 2;
3312 11 weaken(my $weak_self = $self);
3313  
3314 my $hb_check_timer = IO::Async::Timer::Periodic->new(
3315 interval => $check_interval,
3316 on_tick => sub {
3317 0 ▶ return unless $weak_self;
Subroutine __ANON__: not called CC=7 SCAR=40.3
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3318 0 ▶ return if $weak_self->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"shutting_down"} 0 0 0
3319  
3320 0 my $now = time();
3321 0 for my $pid (keys %{$weak_self->{worker_pids}}) {
3322 0 my $info = $weak_self->{worker_pids}{$pid};
3323 0 ▶ next unless $info->{heartbeat_rd};
Branch: 1 branch
BranchTrueFalseTotal
unless $info->{"heartbeat_rd"} 0 0 0
3324  
3325 # Drain all available heartbeat bytes
3326 0 ▶ while (sysread($info->{heartbeat_rd}, my $buf, 64)) {
Branch: 1 branch
BranchTrueFalseTotal
if (sysread $info->{"heartbeat_rd"}, my $buf, 64) 0 0 0
3327 0 $info->{last_heartbeat} = $now;
3328 }
3329  
3330 # Kill if heartbeat expired
3331 0 ▶ if ($now - $info->{last_heartbeat} > $hb_timeout) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $info->{"last_heartbeat"} > $hb_timeout) 0 0 0
3332 0 $weak_self->_log(warn =>
3333 "Worker $pid (worker $info->{worker_num}) heartbeat " .
3334 "timeout after ${hb_timeout}s, sending SIGKILL");
3335 0 kill 'KILL', $pid;
3336 }
3337 }
3338 },
3339 11 );
3340  
3341 11 $self->add_child($hb_check_timer);
3342 11 $hb_check_timer->start;
3343 11 $self->{_heartbeat_check_timer} = $hb_check_timer;
3344 }
3345  
3346 # Hot restart handoff: if we were spawned by USR2, signal the old master
3347 11 ▶ if (my $old_master_pid = delete $ENV{PAGI_MASTER_PID}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $old_master_pid = delete $ENV{"PAGI_MASTER_PID"}) 0 11 11
3348 0 $old_master_pid = int($old_master_pid);
3349  
3350 # Wait for workers to be healthy before retiring old master
3351 # Delay = half the heartbeat timeout + 1 second buffer
3352 0 ▶ my $handoff_delay = ($self->{heartbeat_timeout} || 10) / 2 + 1;
Condition0%0/2
$self->{'heartbeat_timeout'} || 10
l!l
00
MC/DC0%0/1
$self->{'heartbeat_timeout'} || 10
$self->{'heartbeat_timeout'}
Truth table0%0/2
A
A= $self->{'heartbeat_timeout'}
Aresult
11
00
3353 0 weaken(my $weak_self_handoff = $self);
3354  
3355 $self->loop->watch_time(
3356 after => $handoff_delay,
3357 code => sub {
3358 0 ▶ return unless $weak_self_handoff;
Subroutine __ANON__: not called CC=4 SCAR=30.0
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self_handoff 0 0 0
3359  
3360 0 my $worker_count = scalar keys %{$weak_self_handoff->{worker_pids}};
3361 0 ▶ if ($worker_count == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($worker_count == 0) 0 0 0
3362 0 $weak_self_handoff->_log(error =>
3363 "Hot restart: no workers running, not retiring old master $old_master_pid");
3364 0 return;
3365 }
3366  
3367 0 ▶ if (kill(0, $old_master_pid)) {
Branch: 1 branch
BranchTrueFalseTotal
if (kill 0, $old_master_pid) { } 0 0 0
3368 0 $weak_self_handoff->_log(info =>
3369 "Hot restart: $worker_count workers healthy, "
3370 . "sending SIGTERM to old master $old_master_pid");
3371 0 kill('TERM', $old_master_pid);
3372 } else {
3373 0 $weak_self_handoff->_log(warn =>
3374 "Hot restart: old master $old_master_pid is no longer running");
3375 }
3376 },
3377 0 );
3378 }
3379  
3380 # Return immediately - caller (Runner) will call $loop->run()
3381 # This is consistent with single-worker mode behavior
3382 11 return $self;
3383 }
3384  
3385 # Collect inherited file descriptors from PAGI_REUSE and LISTEN_FDS.
3386 # Returns a hashref keyed by "host:port" or "unix:path", values are
3387 # { fd, type, host/port/path, handle?, source }
3388 sub _collect_inherited_fds {
3389 317 ▶ my ($self) = @_;
Subroutine _collect_inherited_fds: called CC=20 SCAR=32.3
3390 317 my %inherited;
3391  
3392 # Source 1: PAGI_REUSE (format: addr:port:fd,unix:path:fd,...)
3393 317 ▶ if (my $reuse = $ENV{PAGI_REUSE}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $reuse = $ENV{"PAGI_REUSE"}) 10 307 317
3394 10 for my $entry (split /,/, $reuse) {
3395 13 ▶ if ($entry =~ /^unix:(.+):(\d+)$/) {
Branch: 3 branches
BranchTrueFalseTotal
if ($entry =~ /^unix:(.+):(\d+)$/) { } 3 10 13
elsif ($entry =~ /^(\[.+?\]):(\d+):(\d+)$/) { } 1 9 10
elsif ($entry =~ /^(.+):(\d+):(\d+)$/) { } 7 2 9
3396 3 my ($path, $fd) = ($1, int($2));
3397 3 $inherited{"unix:$path"} = {
3398 fd => $fd, type => 'unix', path => $path,
3399 source => 'pagi_reuse',
3400 };
3401 } elsif ($entry =~ /^(\[.+?\]):(\d+):(\d+)$/) {
3402 1 my ($host, $port, $fd) = ($1, int($2), int($3));
3403 1 $inherited{"$host:$port"} = {
3404 fd => $fd, type => 'tcp', host => $host, port => $port,
3405 source => 'pagi_reuse',
3406 };
3407 } elsif ($entry =~ /^(.+):(\d+):(\d+)$/) {
3408 7 my ($host, $port, $fd) = ($1, int($2), int($3));
3409 7 $inherited{"$host:$port"} = {
3410 fd => $fd, type => 'tcp', host => $host, port => $port,
3411 source => 'pagi_reuse',
3412 };
3413 }
3414 # Malformed entries silently skipped
3415 }
3416 }
3417  
3418 # Source 2: LISTEN_FDS (systemd socket activation)
3419 317 my $listen_fds = $ENV{LISTEN_FDS};
3420 317 ▶ if (defined $listen_fds && $listen_fds =~ /^\d+$/ && $listen_fds > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $listen_fds and $listen_fds =~ /^\d+$/ and $listen_fds > 0) 3 314 317
Condition66%4/6
defined $listen_fds and $listen_fds =~ /^\d+$/ and $listen_fds > 0
!ll&&!rl&&r
31403
defined $listen_fds and $listen_fds =~ /^\d+$/
!ll&&!rl&&r
31403
MC/DC33%1/3
defined $listen_fds and $listen_fds =~ /^\d+$/ and $listen_fds > 0
defined $listen_fds $listen_fds =~ /^\d+$/ $listen_fds > 0
Truth table50%2/4
A and B and C
A= defined $listen_fdsB= $listen_fds =~ /^\d+$/C= $listen_fds > 0
ABCresult
0XX0
10X0
1100
1111
3421 3 ▶ if (defined $ENV{LISTEN_PID} && $ENV{LISTEN_PID} == $$) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $ENV{"LISTEN_PID"} and $ENV{"LISTEN_PID"} == $$) 1 2 3
Condition66%2/3
defined $ENV{"LISTEN_PID"} and $ENV{"LISTEN_PID"} == $$
!ll&&!rl&&r
021
MC/DC50%1/2
defined $ENV{"LISTEN_PID"} and $ENV{"LISTEN_PID"} == $$
defined $ENV{"LISTEN_PID"} $ENV{"LISTEN_PID"} == $$
Truth table66%2/3
A and B
A= defined $ENV{"LISTEN_PID"}B= $ENV{"LISTEN_PID"} == $$
ABresult
0X0
100
111
3422 1 my $n = int($listen_fds);
3423 1 for my $i (0 .. $n - 1) {
3424 1 my $fd = 3 + $i; # SD_LISTEN_FDS_START
3425  
3426 1 my $fh;
3427 1 ▶ unless (open($fh, '+<&=', $fd)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (open $fh, "+<&=", $fd) 0 1 1
3428 0 $self->_log(warn => "Cannot fdopen inherited fd $fd: $!");
3429 0 next;
3430 }
3431  
3432 1 my $addr = getsockname($fh);
3433 1 ▶ unless ($addr) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($addr) 0 1 1
3434 0 $self->_log(warn => "Cannot getsockname on inherited fd $fd: $!");
3435 0 next;
3436 }
3437  
3438 1 my $family = sockaddr_family($addr);
3439  
3440 1 ▶ if ($family == AF_UNIX) {
Branch: 2 branches
BranchTrueFalseTotal
if ($family == 1) { } 0 1 1
elsif ($family == 2) { } 1 0 1
3441 0 my $path = unpack_sockaddr_un($addr);
3442 0 my $key = "unix:$path";
3443 0 ▶ $inherited{$key} //= {
Condition0%0/2
$inherited{$key} //= {"fd", $fd, "type", "unix", "path", $path, "handle", $fh, "source", "systemd"}
l!l
00
MC/DC0%0/1
$inherited{$key} //= {"fd", $fd, "type", "unix", "path", $path, "handle", $fh, "source", "systemd"}
$inherited{$key}
Truth table0%0/2
A
A= $inherited{$key}
Aresult
11
00
3444 fd => $fd, type => 'unix', path => $path,
3445 handle => $fh, source => 'systemd',
3446 };
3447 } elsif ($family == AF_INET) {
3448 1 my ($port, $host_packed) = unpack_sockaddr_in($addr);
3449 1 my $host = Socket::inet_ntoa($host_packed);
3450 1 my $key = "$host:$port";
3451 1 ▶ $inherited{$key} //= {
Condition50%1/2
$inherited{$key} //= {"fd", $fd, "type", "tcp", "host", $host, "port", $port, "handle", $fh, "source", "systemd"}
l!l
01
MC/DC0%0/1
$inherited{$key} //= {"fd", $fd, "type", "tcp", "host", $host, "port", $port, "handle", $fh, "source", "systemd"}
$inherited{$key}
Truth table50%1/2
A
A= $inherited{$key}
Aresult
11
00
3452 fd => $fd, type => 'tcp', host => $host, port => $port,
3453 handle => $fh, source => 'systemd',
3454 };
3455 } else {
3456 0 $self->_log(warn =>
3457 "Inherited fd $fd has unsupported address family $family");
3458 }
3459 }
3460 }
3461  
3462 # Always clean up systemd env vars (per sd_listen_fds spec)
3463 3 delete @ENV{qw(LISTEN_FDS LISTEN_PID LISTEN_FDNAMES)};
3464 }
3465  
3466 # Entries published by a live sibling server in THIS process are not
3467 # inheritance -- leave them alone (neither claim nor close).
3468 317 for my $key (keys %inherited) {
3469 12 ▶ next unless $OWNED_REUSE_FDS{ $inherited{$key}{fd} };
Branch: 1 branch
BranchTrueFalseTotal
unless $OWNED_REUSE_FDS{$inherited{$key}{"fd"}} 9 3 12
3470 3 $self->_log(debug => "PAGI_REUSE entry $key belongs to a live server "
3471 . "in this process; leaving it alone");
3472 3 delete $inherited{$key};
3473 }
3474  
3475 317 return \%inherited;
3476 }
3477  
3478 # Initiate graceful shutdown in multi-worker mode
3479 sub _initiate_multiworker_shutdown {
3480 8 ▶ my ($self) = @_;
Subroutine _initiate_multiworker_shutdown: called CC=24 SCAR=39.8
3481  
3482 8 ▶ return if $self->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"shutting_down"} 0 8 8
3483 8 $self->{shutting_down} = 1;
3484 8 $self->{running} = 0;
3485  
3486 # Stop heartbeat monitoring — shutdown escalation timer handles stuck workers
3487 8 ▶ if ($self->{_heartbeat_check_timer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_heartbeat_check_timer"}) 8 0 8
3488 8 $self->{_heartbeat_check_timer}->stop;
3489 8 $self->remove_child($self->{_heartbeat_check_timer});
3490 8 delete $self->{_heartbeat_check_timer};
3491 }
3492  
3493 # Close all listen sockets to stop accepting new connections
3494 # (skip during hot restart — new master is using these fds)
3495 8 ▶ if (!$self->{_hot_restart_in_progress}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_hot_restart_in_progress"}) 8 0 8
3496 8 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition50%1/2
$self->{"_listen_entries"} // []
l!l
80
MC/DC0%0/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table50%1/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
3497 8 ▶ if ($entry->{socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"socket"}) 8 0 8
3498 8 close($entry->{socket});
3499 }
3500 }
3501 8 ▶ if ($self->{listen_socket}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"listen_socket"}) 8 0 8
3502 8 delete $self->{listen_socket};
3503 }
3504 }
3505  
3506 # Clean up PAGI_REUSE entries (skip during hot restart)
3507 8 ▶ if (!$self->{_hot_restart_in_progress}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_hot_restart_in_progress"}) 8 0 8
3508 8 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition50%1/2
$self->{"_listen_entries"} // []
l!l
80
MC/DC0%0/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table50%1/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
3509 8 my $key = $entry->{spec}{_reuse_key};
3510 8 ▶ if ($key && defined $ENV{PAGI_REUSE}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key and defined $ENV{"PAGI_REUSE"}) 8 0 8
Condition33%1/3
$key and defined $ENV{"PAGI_REUSE"}
!ll&&!rl&&r
008
MC/DC0%0/2
$key and defined $ENV{"PAGI_REUSE"}
$key defined $ENV{"PAGI_REUSE"}
Truth table33%1/3
A and B
A= $keyB= defined $ENV{"PAGI_REUSE"}
ABresult
0X0
100
111
3511 8 $ENV{PAGI_REUSE} =~ s/(?:^|,)\Q$key\E//;
3512 delete $OWNED_REUSE_FDS{ $entry->{spec}{_reuse_fd} }
3513 8 ▶ if defined $entry->{spec}{_reuse_fd};
Branch: 1 branch
BranchTrueFalseTotal
if defined $entry->{"spec"}{"_reuse_fd"} 8 0 8
3514 8 ▶ $ENV{PAGI_REUSE} =~ s/^,// if defined $ENV{PAGI_REUSE};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"PAGI_REUSE"} 8 0 8
3515 }
3516 }
3517 }
3518  
3519 # Clean up Unix socket files (skip inherited, skip during hot restart)
3520 8 ▶ if (!$self->{_hot_restart_in_progress}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_hot_restart_in_progress"}) 8 0 8
3521 8 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition50%1/2
$self->{"_listen_entries"} // []
l!l
80
MC/DC0%0/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table50%1/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
3522 8 ▶ if ($entry->{spec}{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"} and -e $entry->{"spec"}{"path"}) 0 8 8
Condition33%2/6
$entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"} and -e $entry->{"spec"}{"path"}
!ll&&!rl&&r
800
$entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"}
!ll&&!rl&&r
800
MC/DC0%0/3
$entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"} and -e $entry->{"spec"}{"path"}
$entry->{"spec"}{"type"} eq "unix" not $entry->{"spec"}{"_inherited"} -e $entry->{"spec"}{"path"}
Truth table25%1/4
A and not(B) and C
A= $entry->{"spec"}{"type"} eq "unix"B= not $entry->{"spec"}{"_inherited"}C= -e $entry->{"spec"}{"path"}
ABCresult
0XX0
10X0
1100
1111
3523 && !$entry->{spec}{_inherited}
3524 && -e $entry->{spec}{path}) {
3525 0 unlink $entry->{spec}{path};
3526 }
3527 }
3528 }
3529  
3530 # Signal all workers to shutdown
3531 8 for my $pid (keys %{$self->{worker_pids}}) {
3532 12 kill 'TERM', $pid;
3533 }
3534  
3535 # If no workers, stop the loop immediately
3536 8 ▶ if (!keys %{$self->{worker_pids}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (keys %{$$self{"worker_pids"};}) 0 8 8
3537 0 $self->loop->stop;
3538 0 return;
3539 }
3540  
3541 # Escalate to SIGKILL after shutdown_timeout for workers that ignore SIGTERM
3542 8 ▶ my $timeout = $self->{shutdown_timeout} // 30;
Condition50%1/2
$self->{"shutdown_timeout"} // 30
l!l
80
MC/DC0%0/1
$self->{"shutdown_timeout"} // 30
$self->{"shutdown_timeout"}
Truth table50%1/2
A
A= $self->{"shutdown_timeout"}
Aresult
11
00
3543 8 weaken(my $weak_self = $self);
3544 $self->{_shutdown_kill_timer} = $self->loop->watch_time(
3545 after => $timeout,
3546 code => sub {
3547 0 ▶ return unless $weak_self;
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3548 0 for my $pid (keys %{$weak_self->{worker_pids}}) {
3549 0 $weak_self->_log(warn =>
3550 "Worker $pid did not exit after ${timeout}s, sending SIGKILL");
3551 0 kill 'KILL', $pid;
3552 }
3553 },
3554 8 );
3555 }
3556  
3557 # Graceful restart: replace all workers one by one
3558 sub _graceful_restart {
3559 0 ▶ my ($self) = @_;
Subroutine _graceful_restart: not called CC=4 SCAR=30.0
3560  
3561 0 ▶ return if $self->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"shutting_down"} 0 0 0
3562  
3563 0 $self->_log(info => "Received HUP, performing graceful restart");
3564  
3565 # Signal all current workers to shutdown
3566 # watch_process callbacks will respawn them
3567 0 ▶ my $timeout = $self->{shutdown_timeout} // 30;
Condition0%0/2
$self->{"shutdown_timeout"} // 30
l!l
00
MC/DC0%0/1
$self->{"shutdown_timeout"} // 30
$self->{"shutdown_timeout"}
Truth table0%0/2
A
A= $self->{"shutdown_timeout"}
Aresult
11
00
3568 0 for my $pid (keys %{$self->{worker_pids}}) {
3569 0 kill 'TERM', $pid;
3570  
3571 # Escalate to SIGKILL if worker doesn't exit within shutdown_timeout
3572 0 weaken(my $weak_self = $self);
3573 $self->{_restart_kill_timers}{$pid} = $self->loop->watch_time(
3574 after => $timeout,
3575 code => sub {
3576 0 ▶ return unless $weak_self;
Subroutine __ANON__: not called CC=3 SCAR=24.8
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3577 0 ▶ if (exists $weak_self->{worker_pids}{$pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $weak_self->{"worker_pids"}{$pid}) 0 0 0
3578 0 $weak_self->_log(warn =>
3579 "Worker $pid did not exit after ${timeout}s during restart, sending SIGKILL");
3580 0 kill 'KILL', $pid;
3581 }
3582 },
3583 0 );
3584 }
3585 }
3586  
3587 # Hot restart: fork+exec a new master that inherits listen sockets via PAGI_REUSE
3588 sub _hot_restart {
3589 0 ▶ my ($self) = @_;
Subroutine _hot_restart: not called CC=7 SCAR=40.3
3590  
3591 0 ▶ if ($self->{_hot_restart_in_progress}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_hot_restart_in_progress"}) 0 0 0
3592 0 $self->_log(warn => "Hot restart already in progress, ignoring USR2");
3593 0 return;
3594 }
3595  
3596 0 ▶ if ($self->{shutting_down}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutting_down"}) 0 0 0
3597 0 $self->_log(warn => "Server is shutting down, ignoring USR2");
3598 0 return;
3599 }
3600  
3601 0 $self->{_hot_restart_in_progress} = 1;
3602 0 $self->_log(info => "Received USR2, starting hot restart");
3603  
3604 # Store our PID so the new master can signal us when ready
3605 0 $ENV{PAGI_MASTER_PID} = $$;
3606  
3607 # Fork and exec a new master process
3608 0 my $pid = fork();
3609  
3610 0 ▶ if (!defined $pid) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $pid) 0 0 0
3611 0 $self->_log(error => "Hot restart fork failed: $!");
3612 0 $self->{_hot_restart_in_progress} = 0;
3613 0 delete $ENV{PAGI_MASTER_PID};
3614 0 return;
3615 }
3616  
3617 0 ▶ if ($pid == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pid == 0) 0 0 0
3618 # Child: exec new master
3619 my @args = defined $ENV{PAGI_ARGV}
3620 ? split(/\0/, $ENV{PAGI_ARGV})
3621 0 ▶ : ();
Branch: 1 branch
BranchTrueFalseTotal
defined $ENV{'PAGI_ARGV'} ? : 0 0 0
3622 exec($^X, $0, @args)
3623 0 ▶ or do {
Branch: 1 branch
BranchTrueFalseTotal
exec $^X, $0, @args or do { warn "Hot restart exec failed: $!\n"; POSIX::_exit(1) } 0 0 0
3624 0 warn "Hot restart exec failed: $!\n";
3625 0 POSIX::_exit(1);
3626 };
3627 }
3628  
3629 # Parent: log and continue running
3630 0 $self->_log(info => "Hot restart: new master spawned as PID $pid");
3631 }
3632  
3633 # Increase worker pool by 1
3634 sub _increase_workers {
3635 0 ▶ my ($self) = @_;
Subroutine _increase_workers: not called CC=2 SCAR=17.9
3636  
3637 0 ▶ return if $self->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"shutting_down"} 0 0 0
3638  
3639 0 my $current = scalar keys %{$self->{worker_pids}};
3640 0 my $new_worker_num = $current + 1;
3641  
3642 0 $self->_log(info => "Received TTIN, spawning worker $new_worker_num (total: $new_worker_num)");
3643 0 $self->_spawn_worker($self->{_listen_entries}, $new_worker_num);
3644 }
3645  
3646 # Decrease worker pool by 1
3647 sub _decrease_workers {
3648 0 ▶ my ($self) = @_;
Subroutine _decrease_workers: not called CC=3 SCAR=24.8
3649  
3650 0 ▶ return if $self->{shutting_down};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"shutting_down"} 0 0 0
3651  
3652 0 my @pids = keys %{$self->{worker_pids}};
3653 0 ▶ return unless @pids > 1; # Keep at least 1 worker
Branch: 1 branch
BranchTrueFalseTotal
unless @pids > 1 0 0 0
3654  
3655 0 my $victim_pid = $pids[-1]; # Kill most recent
3656 0 my $remaining = scalar(@pids) - 1;
3657  
3658 0 $self->_log(info => "Received TTOU, killing worker (remaining: $remaining)");
3659  
3660 # Mark as "don't respawn" by setting a flag before killing
3661 0 $self->{_dont_respawn}{$victim_pid} = 1;
3662 0 kill 'TERM', $victim_pid;
3663 }
3664  
3665 sub _spawn_worker {
3666 40 ▶ my ($self, $listen_entries, $worker_num) = @_;
Subroutine _spawn_worker: called CC=6 SCAR=19.0
3667  
3668 40 my $loop = $self->loop;
3669 40 weaken(my $weak_self = $self);
3670  
3671 # Create heartbeat pipe if enabled
3672 40 my ($hb_rd, $hb_wr);
3673 40 ▶ if ($self->{heartbeat_timeout} && $self->{heartbeat_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"heartbeat_timeout"} and $self->{"heartbeat_timeout"} > 0) 40 0 40
Condition33%1/3
$self->{"heartbeat_timeout"} and $self->{"heartbeat_timeout"} > 0
!ll&&!rl&&r
0040
MC/DC0%0/2
$self->{"heartbeat_timeout"} and $self->{"heartbeat_timeout"} > 0
$self->{"heartbeat_timeout"} $self->{"heartbeat_timeout"} > 0
Truth table33%1/3
A and B
A= $self->{"heartbeat_timeout"}B= $self->{"heartbeat_timeout"} > 0
ABresult
0X0
100
111
3674 40 ▶ pipe($hb_rd, $hb_wr) or die "Cannot create heartbeat pipe: $!";
Branch: 1 branch
BranchTrueFalseTotal
pipe $hb_rd, $hb_wr or die "Cannot create heartbeat pipe: $!" 0 40 40
3675 }
3676  
3677 # Set IGNORE before fork - child inherits it. IO::Async only resets
3678 # CODE refs, so 'IGNORE' (a string) survives. Child must NOT call
3679 # watch_signal(INT) or it will overwrite the IGNORE.
3680 40 my $old_sigint = $SIG{INT};
3681 40 $SIG{INT} = 'IGNORE' unless WIN32;
3682  
3683 my $pid = $loop->fork(
3684 code => sub {
3685 16 ▶ close($hb_rd) if $hb_rd;
Subroutine __ANON__: called CC=2 SCAR=8.1
Branch: 1 branch
BranchTrueFalseTotal
if $hb_rd 16 0 16
3686 16 $self->_run_as_worker($listen_entries, $worker_num, $hb_wr);
3687 0 return 0;
3688 },
3689 40 );
3690  
3691 # Restore parent's SIGINT handler
3692 24 $SIG{INT} = $old_sigint unless WIN32;
3693  
3694 24 ▶ die "Fork failed" unless defined $pid;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pid 0 24 24
3695  
3696 # Parent — close write end, set read end non-blocking
3697 24 ▶ if ($hb_wr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($hb_wr) 24 0 24
3698 24 close($hb_wr);
3699 24 $hb_rd->blocking(0);
3700 }
3701  
3702 # Parent - track the worker
3703 24 $self->{worker_pids}{$pid} = {
3704 worker_num => $worker_num,
3705 started => time(),
3706 heartbeat_rd => $hb_rd,
3707 last_heartbeat => time(),
3708 };
3709  
3710 # Use watch_process to handle worker exit (replaces manual SIGCHLD handling)
3711 $loop->watch_process($pid => sub {
3712 14 ▶ my ($exit_pid, $exitcode) = @_;
Subroutine __ANON__: called CC=12 SCAR=27.4
3713 14 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 14 14
3714  
3715 # Close heartbeat pipe read end
3716 14 ▶ if (my $info = $weak_self->{worker_pids}{$exit_pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $info = $weak_self->{"worker_pids"}{$exit_pid}) 14 0 14
3717 14 ▶ close($info->{heartbeat_rd}) if $info->{heartbeat_rd};
Branch: 1 branch
BranchTrueFalseTotal
if $info->{"heartbeat_rd"} 14 0 14
3718 }
3719  
3720 # Remove from tracking
3721 14 delete $weak_self->{worker_pids}{$exit_pid};
3722  
3723 # Cancel per-worker restart kill timer if one exists
3724 14 ▶ if (my $timer_id = delete $weak_self->{_restart_kill_timers}{$exit_pid}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $timer_id = delete $weak_self->{"_restart_kill_timers"}{$exit_pid}) 0 14 14
3725 0 $loop->unwatch_time($timer_id);
3726 }
3727  
3728 # Check exit code: exit(2) = startup failure, don't respawn
3729 14 my $exit_code = $exitcode >> 8;
3730 14 ▶ if ($exit_code == 2) {
Branch: 2 branches
BranchTrueFalseTotal
if ($exit_code == 2) { } 4 10 14
elsif ($weak_self->{'running'} and not $weak_self->{'shutting_down'}) { } 0 20 20
3731 4 $weak_self->_log(warn => "Worker $worker_num startup failed, not respawning");
3732 # Don't respawn - startup failure would just repeat
3733 }
3734 # Respawn if still running and not shutting down
3735 ▶ elsif ($weak_self->{running} && !$weak_self->{shutting_down}) {
Condition33%1/3
$weak_self->{"running"} and not $weak_self->{"shutting_down"}
!ll&&!rl&&r
1000
MC/DC0%0/2
$weak_self->{"running"} and not $weak_self->{"shutting_down"}
$weak_self->{"running"} not $weak_self->{"shutting_down"}
Truth table33%1/3
A and not(B)
A= $weak_self->{"running"}B= not $weak_self->{"shutting_down"}
ABresult
0X0
100
111
3736 # Don't respawn if this was a TTOU reduction
3737 0 ▶ unless (delete $weak_self->{_dont_respawn}{$exit_pid}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (delete $weak_self->{"_dont_respawn"}{$exit_pid}) 0 0 0
3738 0 $weak_self->_spawn_worker($listen_entries, $worker_num);
3739 }
3740 }
3741  
3742 # Check if all workers have exited.
3743 14 ▶ if (!keys %{$weak_self->{worker_pids}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not keys %{$$weak_self{"worker_pids"};}) 9 5 14
3744 9 ▶ if ($weak_self->{shutting_down}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{'shutting_down'}) { } 7 2 9
3745 # Normal shutdown: stop once the last worker is gone.
3746 7 ▶ if ($weak_self->{_shutdown_kill_timer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"_shutdown_kill_timer"}) 7 0 7
3747 7 $loop->unwatch_time($weak_self->{_shutdown_kill_timer});
3748 7 delete $weak_self->{_shutdown_kill_timer};
3749 }
3750 7 $loop->stop;
3751 }
3752 else {
3753 # Not shutting down, yet no workers remain and none were
3754 # respawned -- e.g. every worker failed lifespan startup (exit 2).
3755 # The master would otherwise sit holding the listening socket with
3756 # zero workers serving and never exit. Like uvicorn (#1115/#1177),
3757 # stop and exit non-zero so a supervisor detects the failure and
3758 # restarts us.
3759 2 $weak_self->_log(error =>
3760 "All workers have exited and none were respawned; shutting down");
3761 2 $weak_self->{_workers_failed} = 1;
3762 2 $loop->stop;
3763 }
3764 }
3765 24 });
3766  
3767 24 return $pid;
3768 }
3769  
3770 sub _run_as_worker {
3771 16 ▶ my ($self, $listen_entries, $worker_num, $heartbeat_wr) = @_;
Subroutine _run_as_worker: called CC=26 SCAR=37.9
3772  
3773 # Note: $SIG{INT} = 'IGNORE' inherited from parent - do NOT call watch_signal(INT)
3774 # or it will overwrite the IGNORE with a CODE ref!
3775 #
3776 # The loop itself is created below, after $worker_server exists, via
3777 # $worker_server->_create_loop -- so it respects a configured loop_type
3778 # the same way the single-process run() path does. (Note: $ONE_TRUE_LOOP
3779 # was already cleared by $loop->fork(), so this always creates a fresh loop.)
3780  
3781 # In reuseport mode, each worker creates its own TCP listening socket
3782 16 my $reuseport = $self->{reuseport};
3783 16 for my $entry (@$listen_entries) {
3784 16 my $spec = $entry->{spec};
3785 16 ▶ if (!$entry->{socket} && $reuseport && $spec->{type} eq 'tcp') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $entry->{"socket"} and $reuseport and $spec->{"type"} eq "tcp") 0 16 16
Condition33%2/6
not $entry->{"socket"} and $reuseport and $spec->{"type"} eq "tcp"
!ll&&!rl&&r
1600
not $entry->{"socket"} and $reuseport
!ll&&!rl&&r
1600
MC/DC0%0/3
not $entry->{"socket"} and $reuseport and $spec->{"type"} eq "tcp"
not $entry->{"socket"} $reuseport $spec->{"type"} eq "tcp"
Truth table25%1/4
not(A) and B and C
A= not $entry->{"socket"}B= $reuseportC= $spec->{"type"} eq "tcp"
ABCresult
0XX0
10X0
1100
1111
3786 $entry->{socket} = IO::Socket::INET->new(
3787 LocalAddr => $spec->{host},
3788 LocalPort => $spec->{bound_port},
3789 Proto => 'tcp',
3790 Listen => $self->{listener_backlog},
3791 0 ▶ ReuseAddr => 1,
Branch: 1 branch
BranchTrueFalseTotal
$entry->{"socket"} = "IO::Socket::INET"->new("LocalAddr", $spec->{"host"}, "LocalPort", $spec->{"bound_port"}, "Proto", "tcp", "Listen", $self->{"listener_backlog"}, "ReuseAddr", 1, "ReusePort", 1, "Blocking", 0) or die "Worker ${worker_num}: Cannot create listening socket: $!" 0 0 0
3792 ReusePort => 1,
3793 Blocking => 0,
3794 ) or die "Worker $worker_num: Cannot create listening socket: $!";
3795 }
3796 }
3797  
3798 # Build listener specs for the worker server constructor
3799 16 my @listen_specs;
3800 16 for my $entry (@$listen_entries) {
3801 16 my $s = $entry->{spec};
3802 16 ▶ if ($s->{type} eq 'unix') {
Branch: 1 branch
BranchTrueFalseTotal
if ($s->{'type'} eq 'unix') { } 0 16 16
3803 0 ▶ push @listen_specs, { socket => $s->{path}, (defined $s->{socket_mode} ? (socket_mode => $s->{socket_mode}) : ()) };
Branch: 1 branch
BranchTrueFalseTotal
defined $s->{'socket_mode'} ? : 0 0 0
3804 } else {
3805 16 ▶ push @listen_specs, { host => $s->{host}, port => $s->{port}, ($s->{ssl} ? (ssl => $s->{ssl}) : ()) };
Branch: 1 branch
BranchTrueFalseTotal
$s->{'ssl'} ? : 4 12 16
3806 }
3807 }
3808  
3809 # Create a fresh server instance for this worker (single-worker mode)
3810 my $worker_server = PAGI::Server->new(
3811 app => $self->{app},
3812 listen => \@listen_specs,
3813 ssl => $self->{ssl},
3814 http2 => $self->{http2},
3815 extensions => $self->{extensions},
3816 access_log => $self->{access_log},
3817 log_level => $self->{log_level},
3818 quiet => 1, # Workers should be quiet
3819 timeout => $self->{timeout},
3820 max_header_size => $self->{max_header_size},
3821 max_header_count => $self->{max_header_count},
3822 max_body_size => $self->{max_body_size},
3823 max_requests => $self->{max_requests},
3824 shutdown_timeout => $self->{shutdown_timeout},
3825 request_timeout => $self->{request_timeout},
3826 ws_idle_timeout => $self->{ws_idle_timeout},
3827 sse_idle_timeout => $self->{sse_idle_timeout},
3828 sync_file_threshold => $self->{sync_file_threshold},
3829 max_receive_queue => $self->{max_receive_queue},
3830 max_ws_frame_size => $self->{max_ws_frame_size},
3831 write_high_watermark => $self->{write_high_watermark},
3832 write_low_watermark => $self->{write_low_watermark},
3833 max_connections => $self->{max_connections},
3834 heartbeat_timeout => $self->{heartbeat_timeout},
3835 lifespan_mode => $self->{lifespan_mode},
3836 lifespan_startup_timeout => $self->{lifespan_startup_timeout},
3837 loop_type => $self->{loop_type},
3838 16 workers => 0, # Single-worker mode in worker process
3839 );
3840 16 $worker_server->{is_worker} = 1;
3841 16 $worker_server->{worker_num} = $worker_num; # Store for lifespan scope
3842 16 $worker_server->{_request_count} = 0; # Track requests handled
3843  
3844 # Set bound_port from first TCP listener's socket
3845 16 for my $entry (@$listen_entries) {
3846 16 ▶ if ($entry->{spec}{type} eq 'tcp' && $entry->{socket} && $entry->{socket}->can('sockport')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"spec"}{"type"} eq "tcp" and $entry->{"socket"} and $entry->{"socket"}->can("sockport")) 16 0 16
Condition33%2/6
$entry->{"spec"}{"type"} eq "tcp" and $entry->{"socket"} and $entry->{"socket"}->can("sockport")
!ll&&!rl&&r
0016
$entry->{"spec"}{"type"} eq "tcp" and $entry->{"socket"}
!ll&&!rl&&r
0016
MC/DC0%0/3
$entry->{"spec"}{"type"} eq "tcp" and $entry->{"socket"} and $entry->{"socket"}->can("sockport")
$entry->{"spec"}{"type"} eq "tcp" $entry->{"socket"} $entry->{"socket"}->can("sockport")
Truth table25%1/4
A and B and C
A= $entry->{"spec"}{"type"} eq "tcp"B= $entry->{"socket"}C= $entry->{"socket"}->can("sockport")
ABCresult
0XX0
10X0
1100
1111
3847 16 $worker_server->{bound_port} = $entry->{socket}->sockport;
3848 16 last;
3849 }
3850 }
3851  
3852 # Create the worker's own event loop now, respecting loop_type the same
3853 # way the single-process run() path does (see _create_loop).
3854 16 my $loop = $worker_server->_create_loop;
3855 16 $loop->add($worker_server);
3856  
3857 # Build SSL config for this worker (each worker gets its own SSL context post-fork)
3858 16 my $ssl_params = $worker_server->_build_ssl_config;
3859  
3860 # Set up graceful shutdown on SIGTERM using IO::Async's signal watching
3861 # (raw $SIG handlers don't work reliably when the loop is running)
3862 # Note: Windows doesn't support Unix signals, so this is skipped there
3863 # Note: We do NOT set up watch_signal(INT) here - workers inherit $SIG{INT}='IGNORE'
3864 # from parent, so they ignore SIGINT (including Ctrl-C). Parent sends SIGTERM.
3865 16 unless (WIN32) {
3866 16 my $shutdown_triggered = 0;
3867 $loop->watch_signal(TERM => sub {
3868 12 ▶ return if $shutdown_triggered;
Subroutine __ANON__: called CC=2 SCAR=8.5
Branch: 1 branch
BranchTrueFalseTotal
if $shutdown_triggered 0 12 12
3869 12 $shutdown_triggered = 1;
3870 $worker_server->adopt_future(
3871 $worker_server->shutdown->on_done(sub {
3872 12 ▶ $loop->stop;
Subroutine __ANON__: called CC=1 SCAR=0.0
3873 })->on_fail(sub {
3874 0 ▶ my ($error) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
3875 0 $worker_server->_log(error => "Worker shutdown error: $error");
3876 0 $loop->stop; # Still stop even on error
3877 })
3878 12 );
3879 16 });
3880 }
3881  
3882 # Run lifespan startup using a proper async wrapper
3883 16 my $startup_done = 0;
3884 16 my $startup_error;
3885  
3886 16 ▶ my $startup_future = (async sub {
Subroutine __ANON__: called CC=5 SCAR=16.4
3887 16 eval {
3888 16 my $startup_result = await $worker_server->_run_lifespan_startup;
3889 16 ▶ if (!$startup_result->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($startup_result->{"success"}) 4 12 16
3890 4 ▶ $startup_error = $startup_result->{message} // 'Lifespan startup failed';
Condition50%1/2
$startup_result->{"message"} // "Lifespan startup failed"
l!l
40
MC/DC0%0/1
$startup_result->{"message"} // "Lifespan startup failed"
$startup_result->{"message"}
Truth table50%1/2
A
A= $startup_result->{"message"}
Aresult
11
00
3891 }
3892 };
3893 16 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 16 16
3894 0 $startup_error = $@;
3895 }
3896 16 $startup_done = 1;
3897 16 ▶ $loop->stop if $startup_error; # Stop loop on error
Branch: 1 branch
BranchTrueFalseTotal
if $startup_error 4 12 16
3898 16 })->();
3899  
3900 # Use adopt_future instead of retain
3901 16 $worker_server->adopt_future($startup_future);
3902  
3903 # Run the loop briefly to let async startup complete
3904 16 ▶ $loop->loop_once while !$startup_done;
Branch: 1 branch
BranchTrueFalseTotal
$startup_done or do { $loop->loop_once } 0 16 16
3905  
3906 16 ▶ if ($startup_error) {
Branch: 1 branch
BranchTrueFalseTotal
if ($startup_error) 4 12 16
3907 4 $self->_log(error => "Worker $worker_num ($$): startup failed: $startup_error");
3908 4 for my $entry (@$listen_entries) {
3909 4 ▶ close($entry->{socket}) if $entry->{socket};
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"socket"} 4 0 4
3910 }
3911 4 exit(2); # Exit code 2 = startup failure (don't respawn)
3912 }
3913  
3914 # Create IO::Async::Listener for each inherited socket
3915 12 weaken(my $weak_server = $worker_server);
3916  
3917 12 for my $entry (@$listen_entries) {
3918 12 ▶ next unless $entry->{socket};
Branch: 1 branch
BranchTrueFalseTotal
unless $entry->{"socket"} 0 12 12
3919 12 my $spec = $entry->{spec};
3920  
3921 # Build SSL config for TCP listeners if needed
3922 12 ▶ my $use_ssl = ($ssl_params && $spec->{type} eq 'tcp');
Condition66%2/3
$ssl_params && $spec->{'type'} eq 'tcp'
!ll&&!rl&&r
804
MC/DC50%1/2
$ssl_params && $spec->{'type'} eq 'tcp'
$ssl_params $spec->{'type'} eq 'tcp'
Truth table66%2/3
A && B
A= $ssl_paramsB= $spec->{'type'} eq 'tcp'
ABresult
0X0
100
111
3923  
3924 my $listener = IO::Async::Listener->new(
3925 handle => $entry->{socket},
3926 on_stream => sub {
3927 7 ▶ my ($listener, $stream) = @_;
Subroutine __ANON__: called CC=3 SCAR=12.5
3928 7 ▶ return unless $weak_server;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_server 0 7 7
3929  
3930 7 ▶ if ($use_ssl) {
Branch: 1 branch
BranchTrueFalseTotal
if ($use_ssl) { } 3 4 7
3931 $loop->SSL_upgrade(
3932 handle => $stream,
3933 SSL_server => 1,
3934 SSL_reuse_ctx => $worker_server->{_ssl_ctx},
3935 )->on_done(sub {
3936 3 ▶ $weak_server->_on_connection($stream, $spec) if $weak_server;
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
if $weak_server 3 0 3
3937 })->on_fail(sub {
3938 0 ▶ my ($failure) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
3939 0 ▶ $weak_server->_log(debug => "SSL handshake failed: $failure")
Branch: 1 branch
BranchTrueFalseTotal
if $weak_server 0 0 0
3940 if $weak_server;
3941 3 });
3942 } else {
3943 4 $weak_server->_on_connection($stream, $spec);
3944 }
3945 },
3946 12 );
3947  
3948 12 $worker_server->add_child($listener);
3949  
3950 # Configure accept error handler - try but ignore if it fails
3951 12 eval {
3952 $listener->configure(
3953 on_accept_error => sub {
3954 0 ▶ my ($listener, $error) = @_;
Subroutine __ANON__: not called CC=2 SCAR=17.9
3955 0 ▶ return unless $weak_server;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_server 0 0 0
3956 0 $weak_server->_on_accept_error($error);
3957 },
3958 12 );
3959 };
3960 # Silently ignore configuration errors in workers
3961 }
3962  
3963 # Set up heartbeat writer: periodically signal liveness to parent
3964 12 ▶ if ($heartbeat_wr) {
Branch: 1 branch
BranchTrueFalseTotal
if ($heartbeat_wr) 12 0 12
3965 12 ▶ my $interval = ($worker_server->{heartbeat_timeout} || 50) / 5;
Condition50%1/2
$worker_server->{'heartbeat_timeout'} || 50
l!l
120
MC/DC0%0/1
$worker_server->{'heartbeat_timeout'} || 50
$worker_server->{'heartbeat_timeout'}
Truth table50%1/2
A
A= $worker_server->{'heartbeat_timeout'}
Aresult
11
00
3966 my $hb_timer = IO::Async::Timer::Periodic->new(
3967 interval => $interval,
3968 on_tick => sub {
3969 0 ▶ syswrite($heartbeat_wr, "\x00", 1);
Subroutine __ANON__: not called CC=1 SCAR=6.9
3970 },
3971 12 );
3972 12 $worker_server->add_child($hb_timer);
3973 12 $hb_timer->start;
3974 }
3975  
3976 12 $worker_server->{running} = 1;
3977  
3978 # Run the event loop
3979 12 $loop->run;
3980  
3981 # Clean up FDs before exit
3982 12 ▶ close($heartbeat_wr) if $heartbeat_wr;
Branch: 1 branch
BranchTrueFalseTotal
if $heartbeat_wr 12 0 12
3983 12 for my $entry (@$listen_entries) {
3984 12 ▶ close($entry->{socket}) if $entry->{socket};
Branch: 1 branch
BranchTrueFalseTotal
if $entry->{"socket"} 12 0 12
3985 }
3986 12 exit(0);
3987 }
3988  
3989 sub _on_connection {
3990 304 ▶ my ($self, $stream, $listener_spec) = @_;
Subroutine _on_connection: called CC=13 SCAR=27.1
3991  
3992 304 weaken(my $weak_self = $self);
3993  
3994 # Check if we're at capacity
3995 304 my $max = $self->effective_max_connections;
3996 304 ▶ if ($self->connection_count >= $max) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->connection_count >= $max) 3 301 304
3997 # Over capacity - send 503 and close
3998 3 $self->_send_503_and_close($stream);
3999 3 return;
4000 }
4001  
4002 # Detect ALPN-negotiated protocol from TLS handle
4003 301 my $alpn_protocol;
4004 301 ▶ if ($self->{tls_enabled} && $self->{http2_enabled}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tls_enabled"} and $self->{"http2_enabled"}) 1 300 301
Condition100%3/3
$self->{"tls_enabled"} and $self->{"http2_enabled"}
!ll&&!rl&&r
256441
MC/DC100%2/2
$self->{"tls_enabled"} and $self->{"http2_enabled"}
$self->{"tls_enabled"} $self->{"http2_enabled"}
Truth table100%3/3
A and B
A= $self->{"tls_enabled"}B= $self->{"http2_enabled"}
ABresult
0X0
100
111
4005 1 ▶ my $handle = $stream->write_handle // $stream->read_handle;
Condition33%1/3
$stream->write_handle // $stream->read_handle
l!l&&r!l&&!r
100
MC/DC0%0/2
$stream->write_handle // $stream->read_handle
$stream->write_handle $stream->read_handle
Truth table33%1/3
A // B
A= $stream->write_handleB= $stream->read_handle
ABresult
1X1
011
000
4006 1 ▶ if ($handle && $handle->can('alpn_selected')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handle and $handle->can("alpn_selected")) 1 0 1
Condition33%1/3
$handle and $handle->can("alpn_selected")
!ll&&!rl&&r
001
MC/DC0%0/2
$handle and $handle->can("alpn_selected")
$handle $handle->can("alpn_selected")
Truth table33%1/3
A and B
A= $handleB= $handle->can("alpn_selected")
ABresult
0X0
100
111
4007 1 $alpn_protocol = eval { $handle->alpn_selected };
4008 }
4009 }
4010  
4011 my $conn = PAGI::Server::Connection->new(
4012 stream => $stream,
4013 app => $self->{app},
4014 protocol => $self->{protocol},
4015 server => $self,
4016 extensions => $self->{extensions},
4017 state => $self->{state},
4018 tls_enabled => $self->{tls_enabled} // 0,
4019 timeout => $self->{timeout},
4020 request_timeout => $self->{request_timeout},
4021 ws_idle_timeout => $self->{ws_idle_timeout},
4022 sse_idle_timeout => $self->{sse_idle_timeout},
4023 max_body_size => $self->{max_body_size},
4024 access_log => $self->{access_log},
4025 _access_log_formatter => $self->{_access_log_formatter},
4026 max_receive_queue => $self->{max_receive_queue},
4027 max_ws_frame_size => $self->{max_ws_frame_size},
4028 sync_file_threshold => $self->{sync_file_threshold},
4029 validate_events => $self->{validate_events},
4030 write_high_watermark => $self->{write_high_watermark},
4031 write_low_watermark => $self->{write_low_watermark},
4032 transport_type => ($listener_spec && $listener_spec->{type}) // 'tcp',
4033 transport_path => ($listener_spec ? $listener_spec->{path} : undef),
4034 ($self->{http2_enabled} ? (
4035 h2_protocol => $self->{http2_protocol},
4036 alpn_protocol => $alpn_protocol,
4037 301 ▶ h2c_enabled => $self->{h2c_enabled} // 0,
Branch: 2 branches
BranchTrueFalseTotal
$listener_spec ? : 301 0 301
$self->{'http2_enabled'} ? : 1 300 301
Condition55%5/9
$self->{"tls_enabled"} // 0
l!l
45256
$listener_spec && $listener_spec->{"type"} // "tcp"
l!l
3010
$listener_spec and $listener_spec->{"type"}
!ll&&!rl&&r
00301
$self->{"h2c_enabled"} // 0
l!l
10
MC/DC100%1/1
$self->{"tls_enabled"} // 0
$self->{"tls_enabled"}
MC/DC0%0/2
$listener_spec && $listener_spec->{"type"} // "tcp"
$listener_spec $listener_spec->{"type"}
MC/DC0%0/1
$self->{"h2c_enabled"} // 0
$self->{"h2c_enabled"}
Truth table100%2/2
A
A= $self->{"tls_enabled"}
Aresult
11
00
Truth table33%1/3
A and B
A= $listener_specB= $listener_spec->{"type"}
ABresult
111
0X0
100
Truth table50%1/2
A
A= $self->{"h2c_enabled"}
Aresult
11
00
4038 ) : ()),
4039 );
4040  
4041 # Track the connection (O(1) hash insert)
4042 301 $self->{connections}{refaddr($conn)} = $conn;
4043  
4044 # Configure stream with callbacks BEFORE adding to loop
4045 301 $conn->start;
4046  
4047 # Add stream to the loop so it can read/write
4048 301 $self->add_child($stream);
4049 }
4050  
4051 sub _send_503_and_close {
4052 3 ▶ my ($self, $stream) = @_;
Subroutine _send_503_and_close: called CC=1 SCAR=0.0
4053  
4054 3 my $body = "503 Service Unavailable - Server at capacity\r\n";
4055 my $response = join("\r\n",
4056 "HTTP/1.1 503 Service Unavailable",
4057 "Content-Type: text/plain",
4058 "Content-Length: " . length($body),
4059 "Connection: close",
4060 "Retry-After: 5",
4061 "Date: " . $self->{protocol}->format_date,
4062 3 "",
4063 $body
4064 );
4065  
4066 # Configure stream with minimal on_read handler (required by IO::Async)
4067 $stream->configure(
4068 2 ▶ on_read => sub { 0 }, # Ignore any incoming data
Subroutine __ANON__: called CC=1 SCAR=0.0
4069 3 );
4070  
4071 # Add stream to loop so it can write
4072 3 $self->add_child($stream);
4073  
4074 # Write response and close
4075 3 $stream->write($response);
4076 3 $stream->close_when_empty;
4077  
4078 3 $self->_log(warn => "Connection rejected: at capacity (" . $self->connection_count . "/" . $self->effective_max_connections . ")");
4079 }
4080  
4081 sub _on_accept_error {
4082 0 ▶ my ($self, $error) = @_;
Subroutine _on_accept_error: not called CC=3 SCAR=24.8
4083  
4084 # EMFILE = "Too many open files" - we're out of file descriptors
4085 # ENFILE = System-wide FD limit reached
4086 0 ▶ if ($error =~ /Too many open files|EMFILE|ENFILE/i) {
Branch: 1 branch
BranchTrueFalseTotal
if ($error =~ /Too many open files|EMFILE|ENFILE/i) { } 0 0 0
4087 # Only log the first EMFILE in a burst (when we're not already paused)
4088 0 ▶ unless ($self->{_accept_paused}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_accept_paused"}) 0 0 0
4089 0 $self->_log(warn => "Accept error (FD exhaustion): $error - pausing accept for 100ms");
4090 }
4091  
4092 # Pause accepting for a short time to let connections drain
4093 0 $self->_pause_accepting(0.1);
4094 }
4095 else {
4096 # Log other accept errors but don't crash
4097 0 $self->_log(error => "Accept error: $error");
4098 }
4099 }
4100  
4101 sub _pause_accepting {
4102 0 ▶ my ($self, $duration) = @_;
Subroutine _pause_accepting: not called CC=10 SCAR=47.0
4103  
4104 0 ▶ return if $self->{_accept_paused};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_accept_paused"} 0 0 0
4105 0 $self->{_accept_paused} = 1;
4106  
4107 # Cancel any existing timer before creating new one
4108 0 ▶ if ($self->{_accept_pause_timer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_accept_pause_timer"}) 0 0 0
4109 0 $self->loop->unwatch_time($self->{_accept_pause_timer});
4110 0 delete $self->{_accept_pause_timer};
4111 }
4112  
4113 # Temporarily disable all listeners
4114 0 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition0%0/2
$self->{"_listen_entries"} // []
l!l
00
MC/DC0%0/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table0%0/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
4115 0 my $listener = $entry->{listener};
4116 0 ▶ if ($listener && $listener->read_handle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($listener and $listener->read_handle) 0 0 0
Condition0%0/3
$listener and $listener->read_handle
!ll&&!rl&&r
000
MC/DC0%0/2
$listener and $listener->read_handle
$listener $listener->read_handle
Truth table0%0/3
A and B
A= $listenerB= $listener->read_handle
ABresult
0X0
100
111
4117 0 $listener->want_readready(0);
4118 }
4119 }
4120 # Backward compat: also pause $self->{listener} if not in entries
4121 0 ▶ if ($self->{listener} && !$self->{_listen_entries}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"listener"} and not $self->{"_listen_entries"}) 0 0 0
Condition0%0/3
$self->{"listener"} and not $self->{"_listen_entries"}
!ll&&!rl&&r
000
MC/DC0%0/2
$self->{"listener"} and not $self->{"_listen_entries"}
$self->{"listener"} not $self->{"_listen_entries"}
Truth table0%0/3
A and not(B)
A= $self->{"listener"}B= not $self->{"_listen_entries"}
ABresult
0X0
100
111
4122 0 ▶ $self->{listener}->want_readready(0) if $self->{listener}->read_handle;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"listener"}->read_handle 0 0 0
4123 }
4124  
4125 # Re-enable after duration
4126 0 weaken(my $weak_self = $self);
4127 my $timer_id = $self->loop->watch_time(after => $duration, code => sub {
4128 0 ▶ return unless $weak_self && $weak_self->{running};
Subroutine __ANON__: not called CC=10 SCAR=47.0
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self and $weak_self->{"running"} 0 0 0
Condition0%0/3
$weak_self and $weak_self->{"running"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self and $weak_self->{"running"}
$weak_self $weak_self->{"running"}
Truth table0%0/3
A and B
A= $weak_selfB= $weak_self->{"running"}
ABresult
0X0
100
111
4129 0 $weak_self->{_accept_paused} = 0;
4130 0 delete $weak_self->{_accept_pause_timer};
4131  
4132 # Resume all listeners
4133 0 ▶ for my $entry (@{$weak_self->{_listen_entries} // []}) {
Condition0%0/2
$weak_self->{"_listen_entries"} // []
l!l
00
MC/DC0%0/1
$weak_self->{"_listen_entries"} // []
$weak_self->{"_listen_entries"}
Truth table0%0/2
A
A= $weak_self->{"_listen_entries"}
Aresult
11
00
4134 0 my $listener = $entry->{listener};
4135 0 ▶ if ($listener && $listener->read_handle) {
Branch: 1 branch
BranchTrueFalseTotal
if ($listener and $listener->read_handle) 0 0 0
Condition0%0/3
$listener and $listener->read_handle
!ll&&!rl&&r
000
MC/DC0%0/2
$listener and $listener->read_handle
$listener $listener->read_handle
Truth table0%0/3
A and B
A= $listenerB= $listener->read_handle
ABresult
0X0
100
111
4136 0 $listener->want_readready(1);
4137 }
4138 }
4139 # Backward compat
4140 0 ▶ if ($weak_self->{listener} && !$weak_self->{_listen_entries}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"listener"} and not $weak_self->{"_listen_entries"}) 0 0 0
Condition0%0/3
$weak_self->{"listener"} and not $weak_self->{"_listen_entries"}
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self->{"listener"} and not $weak_self->{"_listen_entries"}
$weak_self->{"listener"} not $weak_self->{"_listen_entries"}
Truth table0%0/3
A and not(B)
A= $weak_self->{"listener"}B= not $weak_self->{"_listen_entries"}
ABresult
0X0
100
111
4141 0 ▶ $weak_self->{listener}->want_readready(1) if $weak_self->{listener}->read_handle;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"listener"}->read_handle 0 0 0
4142 }
4143  
4144 0 $weak_self->_log(debug => "Accept resumed after FD exhaustion pause");
4145 0 });
4146  
4147 0 $self->{_accept_pause_timer} = $timer_id;
4148 }
4149  
4150 # Called when a request completes (for max_requests tracking)
4151 sub _on_request_complete {
4152 527 ▶ my ($self) = @_;
Subroutine _on_request_complete: called CC=6 SCAR=18.4
4153  
4154 527 ▶ return unless $self->{is_worker};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"is_worker"} 517 10 527
4155 10 ▶ return unless $self->{max_requests} && $self->{max_requests} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"max_requests"} and $self->{"max_requests"} > 0 5 5 10
Condition66%2/3
$self->{"max_requests"} and $self->{"max_requests"} > 0
!ll&&!rl&&r
505
MC/DC50%1/2
$self->{"max_requests"} and $self->{"max_requests"} > 0
$self->{"max_requests"} $self->{"max_requests"} > 0
Truth table66%2/3
A and B
A= $self->{"max_requests"}B= $self->{"max_requests"} > 0
ABresult
0X0
100
111
4156  
4157 5 $self->{_request_count}++;
4158  
4159 5 ▶ if ($self->{_request_count} >= $self->{max_requests}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_request_count"} >= $self->{"max_requests"}) 2 3 5
4160 2 ▶ return if $self->{_max_requests_shutdown_triggered}; # Prevent duplicate shutdowns
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_max_requests_shutdown_triggered"} 0 2 2
4161 2 $self->{_max_requests_shutdown_triggered} = 1;
4162 2 $self->_log(info => "Worker $$: reached max_requests ($self->{max_requests}), shutting down");
4163 # Initiate graceful shutdown (finish current connections, then exit)
4164 $self->adopt_future(
4165 $self->shutdown->on_done(sub {
4166 2 ▶ $self->loop->stop;
Subroutine __ANON__: called CC=1 SCAR=0.0
4167 })->on_fail(sub {
4168 0 ▶ my ($error) = @_;
Subroutine __ANON__: not called CC=1 SCAR=6.9
4169 0 $self->_log(error => "Worker $$: max_requests shutdown error: $error");
4170 0 $self->loop->stop; # Still stop even on error
4171 })
4172 2 );
4173 }
4174 }
4175  
4176 # Lifespan Protocol Implementation
4177  
4178 302 ▶async sub _run_lifespan_startup {
Subroutine _run_lifespan_startup: called CC=7 SCAR=20.0
4179 302 my ($self) = @_;
4180  
4181 # Create lifespan scope
4182 my $scope = {
4183 type => 'lifespan',
4184 pagi => {
4185 version => '0.5',
4186 spec_version => '0.3',
4187 is_worker => $self->{is_worker} // 0,
4188 worker_num => $self->{worker_num}, # undef for single-worker, 1-N for multi-worker
4189 },
4190 state => $self->{state}, # App can populate this
4191 302 ▶ };
Condition50%1/2
$self->{"is_worker"} // 0
l!l
3020
MC/DC0%0/1
$self->{"is_worker"} // 0
$self->{"is_worker"}
Truth table50%1/2
A
A= $self->{"is_worker"}
Aresult
11
00
4192  
4193 # Create receive/send for lifespan protocol
4194 302 my @send_queue;
4195 my $receive_pending;
4196 302 my $startup_complete = Future->new;
4197  
4198 302 $self->{lifespan_phase} = 'startup_pending';
4199  
4200 # $receive for the app - returns events from the server
4201 my $receive = sub {
4202 371 ▶ if (@send_queue) {
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if (@send_queue) 198 173 371
4203 198 return Future->done(shift @send_queue);
4204 }
4205 173 $receive_pending = Future->new;
4206 173 return $receive_pending;
4207 302 };
4208  
4209 # $send for the app - handles app responses
4210 385 ▶ my $send = async sub {
Subroutine __ANON__: called CC=10 SCAR=28.0
4211 385 my ($event) = @_;
4212 385 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
3850
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
4213  
4214 385 PAGI::Server::EventValidator::validate_lifespan_send($event);
4215 $self->{lifespan_phase} = PAGI::Server::EventValidator::advance_lifespan(
4216 346 $self->{lifespan_phase}, $event);
4217  
4218 344 ▶ if ($type eq 'lifespan.startup.complete') {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'lifespan.startup.complete') { } 174 170 344
elsif ($type eq 'lifespan.startup.failed') { } 4 166 170
elsif ($type eq 'lifespan.shutdown.complete') { } 166 0 166
elsif ($type eq 'lifespan.shutdown.failed') { } 0 0 0
4219 174 $startup_complete->done({ success => 1 });
4220 }
4221 elsif ($type eq 'lifespan.startup.failed') {
4222 4 ▶ my $message = $event->{message} // '';
Condition50%1/2
$event->{"message"} // ""
l!l
40
MC/DC0%0/1
$event->{"message"} // ""
$event->{"message"}
Truth table50%1/2
A
A= $event->{"message"}
Aresult
11
00
4223 4 $startup_complete->done({ success => 0, message => $message });
4224 }
4225 elsif ($type eq 'lifespan.shutdown.complete') {
4226 # Store for shutdown handling
4227 166 $self->{shutdown_complete} = 1;
4228 166 ▶ if ($self->{shutdown_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutdown_pending"}) 166 0 166
4229 166 $self->{shutdown_pending}->done({ success => 1 });
4230 }
4231 }
4232 elsif ($type eq 'lifespan.shutdown.failed') {
4233 0 ▶ my $message = $event->{message} // '';
Condition0%0/2
$event->{"message"} // ""
l!l
00
MC/DC0%0/1
$event->{"message"} // ""
$event->{"message"}
Truth table0%0/2
A
A= $event->{"message"}
Aresult
11
00
4234 0 $self->{shutdown_complete} = 1;
4235 0 ▶ if ($self->{shutdown_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"shutdown_pending"}) 0 0 0
4236 0 $self->{shutdown_pending}->done({ success => 0, message => $message });
4237 }
4238 }
4239  
4240 344 return;
4241 302 };
4242  
4243 # Queue the startup event
4244 302 push @send_queue, { type => 'lifespan.startup' };
4245 302 ▶ if ($receive_pending && !$receive_pending->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($receive_pending and not $receive_pending->is_ready) 0 302 302
Condition33%1/3
$receive_pending and not $receive_pending->is_ready
!ll&&!rl&&r
30200
MC/DC0%0/2
$receive_pending and not $receive_pending->is_ready
$receive_pending not $receive_pending->is_ready
Truth table33%1/3
A and not(B)
A= $receive_pendingB= not $receive_pending->is_ready
ABresult
0X0
100
111
4246 0 my $f = $receive_pending;
4247 0 $receive_pending = undef;
4248 0 $f->done(shift @send_queue);
4249 }
4250  
4251 # Store lifespan handlers for shutdown
4252 302 $self->{lifespan_receive} = $receive;
4253 302 $self->{lifespan_send} = $send;
4254 302 $self->{lifespan_send_queue} = \@send_queue;
4255 302 $self->{lifespan_receive_pending} = \$receive_pending;
4256  
4257 # Start the lifespan app handler
4258 # We run it in the background and wait for startup.complete
4259 302 ▶ my $app_future = (async sub {
Subroutine __ANON__: called CC=9 SCAR=22.0
4260 302 my $ok = eval {
4261 302 await $self->{app}->($scope, $receive, $send);
4262 174 1;
4263 };
4264 295 ▶ my $err = $ok ? undef : $@;
Branch: 1 branch
BranchTrueFalseTotal
$ok ? : 174 121 295
4265  
4266 295 ▶ if (!$startup_complete->is_ready) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $startup_complete->is_ready) { } 123 172 295
elsif (defined $err) { } 2 170 172
4267 # The app finished -- by returning cleanly OR by throwing -- without
4268 # ever signalling startup.
4269 123 my $detail;
4270 123 ▶ if (defined $err) { ($detail = $err) =~ s/\s+\z//; }
Branch: 1 branch
BranchTrueFalseTotal
if (defined $err) 119 4 123
4271  
4272 123 ▶ if (($self->{lifespan_mode} // 'auto') eq 'on') {
Branch: 1 branch
BranchTrueFalseTotal
if (($self->{'lifespan_mode'} // 'auto') eq 'on') { } 3 120 123
Condition50%1/2
$self->{"lifespan_mode"} // "auto"
l!l
1230
MC/DC0%0/1
$self->{"lifespan_mode"} // "auto"
$self->{"lifespan_mode"}
Truth table50%1/2
A
A= $self->{"lifespan_mode"}
Aresult
11
00
4273 # 'on' requires lifespan: a decline (a raise, or a clean return
4274 # that never signalled startup) is a fatal startup failure rather
4275 # than "continue without it".
4276 3 ▶ my $why = defined $detail
Branch: 1 branch
BranchTrueFalseTotal
defined $detail ? : 3 0 3
4277 ? "the application raised: $detail"
4278 : "the application returned without signalling startup";
4279 3 $startup_complete->done({ success => 0,
4280 message => "lifespan_mode is 'on' but $why" });
4281 }
4282 else {
4283 # auto: continue without lifespan. This matches Uvicorn/Hypercorn
4284 # "auto"; an app may decline by returning on the lifespan scope or
4285 # by dying on it. Include the raised message so a genuine startup
4286 # failure masquerading as a decline is still visible.
4287 120 my $msg = "Lifespan not supported, continuing without it";
4288 120 ▶ $msg .= " (application raised: $detail)" if defined $detail;
Branch: 1 branch
BranchTrueFalseTotal
if defined $detail 116 4 120
4289 120 $self->_log(info => $msg);
4290 120 $startup_complete->done({ success => 1, lifespan_supported => 0 });
4291 }
4292 }
4293 elsif (defined $err) {
4294 # The app's long-lived lifespan task failed AFTER startup completed.
4295 # Surface it at error level rather than swallowing it silently, so a
4296 # crashed background task is visible to operators.
4297 2 $self->_log(error => "Lifespan app failed after startup: $err");
4298 }
4299 # else: the app returned cleanly after startup completed -- the handler
4300 # simply exited early; nothing to do.
4301 302 })->();
4302  
4303 # Keep the app future so we can trigger shutdown later
4304 302 $self->{lifespan_app_future} = $app_future;
4305 # Use adopt_future instead of retain for proper error handling
4306 302 $self->adopt_future($app_future);
4307  
4308 # Wait for startup complete, bounded by lifespan_startup_timeout so a hung
4309 # lifespan handler (one that neither signals startup nor returns) cannot
4310 # block the server forever. The constructor and configure() both reject a
4311 # value of 0, so this bound always applies -- the PAGI Lifespan spec
4312 # requires that a server must not block startup indefinitely.
4313 # without_cancel keeps $startup_complete pending on timeout, so a late
4314 # signal cannot croak.
4315 302 ▶ my $startup_timeout = $self->{lifespan_startup_timeout} // 30;
Condition50%1/2
$self->{"lifespan_startup_timeout"} // 30
l!l
3020
MC/DC0%0/1
$self->{"lifespan_startup_timeout"} // 30
$self->{"lifespan_startup_timeout"}
Truth table50%1/2
A
A= $self->{"lifespan_startup_timeout"}
Aresult
11
00
4316 my $timeout_f = $self->loop->delay_future(after => $startup_timeout)
4317 302 ▶ ->then(sub { Future->done(undef) });
Subroutine __ANON__: called CC=1 SCAR=0.0
4318 302 my $result = await Future->wait_any($startup_complete->without_cancel, $timeout_f);
4319 302 ▶ if (!defined $result) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $result) 1 301 302
4320 1 my $message = "Lifespan startup timed out after ${startup_timeout}s";
4321 1 $self->_log(error => $message);
4322 1 return { success => 0, message => $message };
4323 }
4324  
4325 # Track if lifespan is supported
4326 301 ▶ $self->{lifespan_supported} = $result->{lifespan_supported} // 1;
Condition100%2/2
$result->{"lifespan_supported"} // 1
l!l
120181
MC/DC100%1/1
$result->{"lifespan_supported"} // 1
$result->{"lifespan_supported"}
Truth table100%2/2
A
A= $result->{"lifespan_supported"}
Aresult
11
00
4327  
4328 301 return $result;
4329 151 }
4330  
4331 287 ▶async sub _run_lifespan_shutdown {
Subroutine _run_lifespan_shutdown: called CC=9 SCAR=23.2
4332 287 my ($self) = @_;
4333  
4334 # If lifespan is not supported or no lifespan was started, just return success
4335 287 ▶ return { success => 1 } unless $self->{lifespan_supported};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan_supported"} 120 167 287
4336 167 ▶ return { success => 1 } unless $self->{lifespan_send_queue};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"lifespan_send_queue"} 0 167 167
4337  
4338 167 $self->{shutdown_pending} = $self->loop->new_future;
4339  
4340 # Queue the shutdown event
4341 167 my $send_queue = $self->{lifespan_send_queue};
4342 167 my $receive_pending_ref = $self->{lifespan_receive_pending};
4343  
4344 167 $self->{lifespan_phase} = 'shutdown_pending';
4345 167 push @$send_queue, { type => 'lifespan.shutdown' };
4346  
4347 # Trigger pending receive if waiting
4348 167 ▶ if ($$receive_pending_ref && !$$receive_pending_ref->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($$receive_pending_ref and not $$receive_pending_ref->is_ready) 167 0 167
Condition33%1/3
$$receive_pending_ref and not $$receive_pending_ref->is_ready
!ll&&!rl&&r
00167
MC/DC0%0/2
$$receive_pending_ref and not $$receive_pending_ref->is_ready
$$receive_pending_ref not $$receive_pending_ref->is_ready
Truth table33%1/3
A and not(B)
A= $$receive_pending_refB= not $$receive_pending_ref->is_ready
ABresult
0X0
100
111
4349 167 my $f = $$receive_pending_ref;
4350 167 $$receive_pending_ref = undef;
4351 167 $f->done(shift @$send_queue);
4352 }
4353  
4354 # Wait for shutdown complete (with timeout to prevent hanging)
4355 167 ▶ my $timeout = $self->{shutdown_timeout} // 30;
Condition50%1/2
$self->{"shutdown_timeout"} // 30
l!l
1670
MC/DC0%0/1
$self->{"shutdown_timeout"} // 30
$self->{"shutdown_timeout"}
Truth table50%1/2
A
A= $self->{"shutdown_timeout"}
Aresult
11
00
4356 167 my $timeout_f = $self->loop->delay_future(after => $timeout);
4357  
4358 167 my $result = await Future->wait_any($self->{shutdown_pending}, $timeout_f);
4359  
4360 # If timeout won, return failure
4361 167 ▶ if ($timeout_f->is_ready && !$self->{shutdown_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($timeout_f->is_ready and not $self->{"shutdown_pending"}->is_ready) 0 167 167
Condition33%1/3
$timeout_f->is_ready and not $self->{"shutdown_pending"}->is_ready
!ll&&!rl&&r
01670
MC/DC0%0/2
$timeout_f->is_ready and not $self->{"shutdown_pending"}->is_ready
$timeout_f->is_ready not $self->{"shutdown_pending"}->is_ready
Truth table33%1/3
A and not(B)
A= $timeout_f->is_readyB= not $self->{"shutdown_pending"}->is_ready
ABresult
0X0
100
111
4362 0 return { success => 0, message => "Lifespan shutdown timed out after ${timeout}s" };
4363 }
4364  
4365 167 ▶ return $result // { success => 1 };
Condition100%2/2
$result // {"success", 1}
l!l
1661
MC/DC100%1/1
$result // {"success", 1}
$result
Truth table100%2/2
A
A= $result
Aresult
11
00
4366 151 }
4367  
4368 290 ▶async sub shutdown {
Subroutine shutdown: called CC=19 SCAR=31.1
Pod documented
4369 290 my ($self) = @_;
4370  
4371 290 ▶ return unless $self->{running};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"running"} 2 288 290
4372 288 $self->{running} = 0;
4373 288 $self->{shutting_down} = 1;
4374  
4375 # Cancel accept pause timer if active
4376 288 ▶ if ($self->{_accept_pause_timer}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_accept_pause_timer"}) 0 288 288
4377 0 $self->loop->unwatch_time($self->{_accept_pause_timer});
4378 0 delete $self->{_accept_pause_timer};
4379 0 $self->{_accept_paused} = 0;
4380 }
4381  
4382 # Stop accepting new connections on all listeners
4383 288 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition100%2/2
$self->{"_listen_entries"} // []
l!l
27612
MC/DC100%1/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table100%2/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
4384 277 eval { $self->remove_child($entry->{listener}) };
4385 }
4386 288 $self->{listener} = undef;
4387  
4388 # Clean up PAGI_REUSE entries for sockets we created (not inherited)
4389 288 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition100%2/2
$self->{"_listen_entries"} // []
l!l
27612
MC/DC100%1/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table100%2/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
4390 277 my $key = $entry->{spec}{_reuse_key};
4391 277 ▶ if ($key && !$self->{_hot_restart_in_progress} && defined $ENV{PAGI_REUSE}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key and not $self->{"_hot_restart_in_progress"} and defined $ENV{"PAGI_REUSE"}) 274 3 277
Condition66%4/6
$key and not $self->{"_hot_restart_in_progress"} and defined $ENV{"PAGI_REUSE"}
!ll&&!rl&&r
30274
$key and not $self->{"_hot_restart_in_progress"}
!ll&&!rl&&r
30274
MC/DC33%1/3
$key and not $self->{"_hot_restart_in_progress"} and defined $ENV{"PAGI_REUSE"}
$key not $self->{"_hot_restart_in_progress"} defined $ENV{"PAGI_REUSE"}
Truth table50%2/4
A and not(B) and C
A= $keyB= not $self->{"_hot_restart_in_progress"}C= defined $ENV{"PAGI_REUSE"}
ABCresult
0XX0
10X0
1100
1111
4392 274 $ENV{PAGI_REUSE} =~ s/(?:^|,)\Q$key\E//;
4393 delete $OWNED_REUSE_FDS{ $entry->{spec}{_reuse_fd} }
4394 274 ▶ if defined $entry->{spec}{_reuse_fd};
Branch: 1 branch
BranchTrueFalseTotal
if defined $entry->{"spec"}{"_reuse_fd"} 274 0 274
4395 274 ▶ $ENV{PAGI_REUSE} =~ s/^,// if defined $ENV{PAGI_REUSE};
Branch: 1 branch
BranchTrueFalseTotal
if defined $ENV{"PAGI_REUSE"} 274 0 274
4396 }
4397 }
4398  
4399 # Clean up Unix socket files (only those we created, not inherited)
4400 288 ▶ for my $entry (@{$self->{_listen_entries} // []}) {
Condition100%2/2
$self->{"_listen_entries"} // []
l!l
27612
MC/DC100%1/1
$self->{"_listen_entries"} // []
$self->{"_listen_entries"}
Truth table100%2/2
A
A= $self->{"_listen_entries"}
Aresult
11
00
4401 277 ▶ if ($entry->{spec}{type} eq 'unix'
Branch: 1 branch
BranchTrueFalseTotal
if ($entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"} and -e $entry->{"spec"}{"path"}) 7 270 277
Condition83%5/6
$entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"} and -e $entry->{"spec"}{"path"}
!ll&&!rl&&r
27007
$entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"}
!ll&&!rl&&r
26917
MC/DC66%2/3
$entry->{"spec"}{"type"} eq "unix" and not $entry->{"spec"}{"_inherited"} and -e $entry->{"spec"}{"path"}
$entry->{"spec"}{"type"} eq "unix" not $entry->{"spec"}{"_inherited"} -e $entry->{"spec"}{"path"}
Truth table75%3/4
A and not(B) and C
A= $entry->{"spec"}{"type"} eq "unix"B= not $entry->{"spec"}{"_inherited"}C= -e $entry->{"spec"}{"path"}
ABCresult
0XX0
10X0
1100
1111
4402 && !$entry->{spec}{_inherited}
4403 && -e $entry->{spec}{path}) {
4404 7 unlink $entry->{spec}{path};
4405 }
4406 }
4407 288 $self->{_listen_entries} = [];
4408  
4409 # Wait for active connections to drain (graceful shutdown)
4410 288 await $self->_drain_connections;
4411  
4412 # Run lifespan shutdown
4413 287 my $shutdown_result = await $self->_run_lifespan_shutdown;
4414  
4415 287 ▶ if (!$shutdown_result->{success}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($shutdown_result->{"success"}) 0 287 287
4416 0 ▶ my $message = $shutdown_result->{message} // 'Lifespan shutdown failed';
Condition0%0/2
$shutdown_result->{"message"} // "Lifespan shutdown failed"
l!l
00
MC/DC0%0/1
$shutdown_result->{"message"} // "Lifespan shutdown failed"
$shutdown_result->{"message"}
Truth table0%0/2
A
A= $shutdown_result->{"message"}
Aresult
11
00
4417 0 $self->_log(warn => "PAGI Server shutdown warning: $message");
4418 }
4419  
4420 287 return $self;
4421 151 }
4422  
4423 # Wait for active connections to complete, with timeout
4424 # Uses event-driven approach: Connection._close() signals when last one closes
4425 288 ▶async sub _drain_connections {
Subroutine _drain_connections: called CC=11 SCAR=29.7
4426 288 my ($self) = @_;
4427  
4428 288 ▶ my $timeout = $self->{shutdown_timeout} // 30;
Condition50%1/2
$self->{"shutdown_timeout"} // 30
l!l
2880
MC/DC0%0/1
$self->{"shutdown_timeout"} // 30
$self->{"shutdown_timeout"}
Truth table50%1/2
A
A= $self->{"shutdown_timeout"}
Aresult
11
00
4429 288 my $loop = $self->loop;
4430  
4431 # First, close all idle connections immediately (not processing a request)
4432 # Keep-alive connections waiting for next request should be closed
4433 288 my @idle = grep { !$_->{handling_request} } values %{$self->{connections}};
4434 288 for my $conn (@idle) {
4435 165 $conn->_handle_disconnect_and_close('server_shutdown');
4436 }
4437  
4438 # Also close long-lived connections (SSE, WebSocket) immediately
4439 # These never become "idle" so would wait for full timeout otherwise
4440 288 ▶ my @longlived = grep { $_->{sse_mode} || $_->{websocket_mode} } values %{$self->{connections}};
Branch: 1 branch
BranchTrueFalseTotal
$_->{"sse_mode"} or $_->{"websocket_mode"} 11 2 13
4441 288 for my $conn (@longlived) {
4442 12 $conn->_handle_disconnect_and_close('server_shutdown');
4443 }
4444  
4445 # If all connections are now closed, we're done
4446 288 ▶ return if keys %{$self->{connections}} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$$self{"connections"};} == 0 287 1 288
4447  
4448 # Create a Future that Connection._close() will resolve when last one closes
4449 1 $self->{drain_complete} = $loop->new_future;
4450  
4451 # Wait for either: all connections close OR timeout
4452 1 my $timeout_f = $loop->delay_future(after => $timeout);
4453  
4454 1 await Future->wait_any($self->{drain_complete}, $timeout_f);
4455  
4456 # Brief pause to let any final socket writes flush
4457 # (stream->write is async; data may still be in kernel buffer)
4458 1 ▶ await $loop->delay_future(after => 0.05) if keys %{$self->{connections}} == 0;
Branch: 1 branch
BranchTrueFalseTotal
if keys %{$$self{"connections"};} == 0 1 0 1
4459  
4460 # If timeout won (connections still remain), force close them
4461 0 ▶ if (keys %{$self->{connections}} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (keys %{$$self{"connections"};} > 0) 0 0 0
4462 0 my $remaining = scalar keys %{$self->{connections}};
4463 0 $self->_log(warn => "Shutdown timeout: force-closing $remaining active connections");
4464  
4465 0 for my $conn (values %{$self->{connections}}) {
4466 0 ▶ $conn->_close if $conn && $conn->can('_close');
Branch: 1 branch
BranchTrueFalseTotal
if $conn and $conn->can("_close") 0 0 0
Condition0%0/3
$conn and $conn->can("_close")
!ll&&!rl&&r
000
MC/DC0%0/2
$conn and $conn->can("_close")
$conn $conn->can("_close")
Truth table0%0/3
A and B
A= $connB= $conn->can("_close")
ABresult
0X0
100
111
4467 }
4468 }
4469  
4470 0 delete $self->{drain_complete};
4471 0 return;
4472 151 }
4473  
4474 # --- Access log format compiler ---
4475  
4476 151 my %ACCESS_LOG_PRESETS = (
4477 clf => '%h - - [%t] "%m %U%q" %s %ds',
4478 combined => '%h - - [%t] "%r" %s %b "%{Referer}i" "%{User-Agent}i"',
4479 common => '%h - - [%t] "%r" %s %b',
4480 tiny => '%m %U%q %s %Dms',
4481 );
4482  
4483 sub _compile_access_log_format {
4484 663 ▶ my ($class_or_self, $format) = @_;
Subroutine _compile_access_log_format: called CC=11 SCAR=24.0
4485  
4486 # Resolve preset names
4487 663 ▶ if (exists $ACCESS_LOG_PRESETS{$format}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $ACCESS_LOG_PRESETS{$format}) 629 34 663
4488 629 $format = $ACCESS_LOG_PRESETS{$format};
4489 }
4490  
4491 # Parse format string into a list of fragments (closures or literal strings)
4492 663 my @fragments;
4493 663 my $pos = 0;
4494 663 my $len = length($format);
4495  
4496 663 ▶ while ($pos < $len) {
Branch: 1 branch
BranchTrueFalseTotal
if ($pos < $len) 8217 662 8879
4497 8217 my $ch = substr($format, $pos, 1);
4498  
4499 8217 ▶ if ($ch eq '%') {
Branch: 1 branch
BranchTrueFalseTotal
if ($ch eq '%') { } 4436 3781 8217
4500 4436 $pos++;
4501 4436 ▶ last if $pos >= $len;
Branch: 1 branch
BranchTrueFalseTotal
if $pos >= $len 0 4436 4436
4502  
4503 4436 my $next = substr($format, $pos, 1);
4504  
4505 4436 ▶ if ($next eq '%') {
Branch: 2 branches
BranchTrueFalseTotal
if ($next eq '%') { } 1 4435 4436
elsif ($next eq '{') { } 13 4422 4435
4506 # Literal percent
4507 1 push @fragments, '%';
4508 1 $pos++;
4509 }
4510 elsif ($next eq '{') {
4511 # Header extraction: %{Name}i
4512 13 my $end = index($format, '}', $pos);
4513 13 ▶ die "Unterminated %{...} in access log format\n" if $end < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $end < 0 0 13 13
4514 13 my $header_name = substr($format, $pos + 1, $end - $pos - 1);
4515 13 $pos = $end + 1;
4516  
4517 # Must be followed by 'i' (request header)
4518 13 ▶ die "Expected 'i' after %{$header_name} in access log format\n"
Branch: 1 branch
BranchTrueFalseTotal
if $pos >= $len or substr($format, $pos, 1) ne "i" 0 13 13
Condition33%1/3
$pos >= $len or substr($format, $pos, 1) ne "i"
l!l&&r!l&&!r
0013
MC/DC0%0/2
$pos >= $len or substr($format, $pos, 1) ne "i"
$pos >= $len substr($format, $pos, 1) ne "i"
Truth table33%1/3
A or B
A= $pos >= $lenB= substr($format, $pos, 1) ne "i"
ABresult
1X1
011
000
4519 if $pos >= $len || substr($format, $pos, 1) ne 'i';
4520 13 $pos++;
4521  
4522 13 my $lc_name = lc($header_name);
4523 push @fragments, sub {
4524 11 ▶ my ($info) = @_;
Subroutine __ANON__: called CC=3 SCAR=11.0
4525 11 for my $h (@{$info->{request_headers}}) {
4526 27 ▶ return $h->[1] if lc($h->[0]) eq $lc_name;
Branch: 1 branch
BranchTrueFalseTotal
if lc $h->[0] eq $lc_name 9 18 27
4527 }
4528 2 return '-';
4529 13 };
4530 }
4531 else {
4532 # Simple atom
4533 4422 my $atom = $next;
4534 4422 $pos++;
4535  
4536 4422 my $frag = _access_log_atom($atom);
4537 4421 push @fragments, $frag;
4538 }
4539 }
4540 else {
4541 # Literal text: collect until next %
4542 3781 my $next_pct = index($format, '%', $pos);
4543 3781 ▶ if ($next_pct < 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($next_pct < 0) { } 629 3152 3781
4544 629 push @fragments, substr($format, $pos);
4545 629 $pos = $len;
4546 }
4547 else {
4548 3152 push @fragments, substr($format, $pos, $next_pct - $pos);
4549 3152 $pos = $next_pct;
4550 }
4551 }
4552 }
4553  
4554 # Build a single closure from fragments
4555 return sub {
4556 343 ▶ my ($info) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
4557 343 ▶ return join('', map { ref $_ ? $_->($info) : $_ } @fragments);
Branch: 1 branch
BranchTrueFalseTotal
ref $_ ? : 2198 1864 4062
4558 662 };
4559 }
4560  
4561 sub _access_log_atom {
4562 4422 ▶ my ($atom) = @_;
Subroutine _access_log_atom: called CC=2 SCAR=7.1
4563  
4564 my %atoms = (
4565 311 ▶ h => sub { $_[0]->{client_ip} // '-' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"client_ip"} // "-"
l!l
3110
MC/DC0%0/1
$_[0]{"client_ip"} // "-"
$_[0]{"client_ip"}
Truth table50%1/2
A
A= $_[0]{"client_ip"}
Aresult
11
00
4566 1 ▶ l => sub { '-' },
Subroutine __ANON__: called CC=1 SCAR=0.0
4567 1 ▶ u => sub { '-' },
Subroutine __ANON__: called CC=1 SCAR=0.0
4568 309 ▶ t => sub { $_[0]->{timestamp} // '-' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"timestamp"} // "-"
l!l
3090
MC/DC0%0/1
$_[0]{"timestamp"} // "-"
$_[0]{"timestamp"}
Truth table50%1/2
A
A= $_[0]{"timestamp"}
Aresult
11
00
4569 r => sub {
4570 5 ▶ my $i = $_[0];
Subroutine __ANON__: called CC=6 SCAR=18.8
4571 5 ▶ my $uri = $i->{path} // '/';
Condition50%1/2
$i->{"path"} // "/"
l!l
50
MC/DC0%0/1
$i->{"path"} // "/"
$i->{"path"}
Truth table50%1/2
A
A= $i->{"path"}
Aresult
11
00
4572 5 my $qs = $i->{query};
4573 5 ▶ $uri .= "?$qs" if defined $qs && length $qs;
Branch: 1 branch
BranchTrueFalseTotal
if defined $qs and length $qs 3 2 5
Condition66%2/3
defined $qs and length $qs
!ll&&!rl&&r
023
MC/DC50%1/2
defined $qs and length $qs
defined $qs length $qs
Truth table66%2/3
A and B
A= defined $qsB= length $qs
ABresult
0X0
100
111
4574 5 ▶ sprintf('%s %s HTTP/%s', $i->{method} // '-', $uri, $i->{http_version} // '1.1');
Condition50%2/4
$i->{"method"} // "-"
l!l
50
$i->{"http_version"} // "1.1"
l!l
50
MC/DC0%0/1
$i->{"method"} // "-"
$i->{"method"}
MC/DC0%0/1
$i->{"http_version"} // "1.1"
$i->{"http_version"}
Truth table50%1/2
A
A= $i->{"method"}
Aresult
11
00
Truth table50%1/2
A
A= $i->{"http_version"}
Aresult
11
00
4575 },
4576 306 ▶ m => sub { $_[0]->{method} // '-' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"method"} // "-"
l!l
3060
MC/DC0%0/1
$_[0]{"method"} // "-"
$_[0]{"method"}
Truth table50%1/2
A
A= $_[0]{"method"}
Aresult
11
00
4577 306 ▶ U => sub { $_[0]->{path} // '/' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"path"} // "/"
l!l
3060
MC/DC0%0/1
$_[0]{"path"} // "/"
$_[0]{"path"}
Truth table50%1/2
A
A= $_[0]{"path"}
Aresult
11
00
4578 q => sub {
4579 308 ▶ my $qs = $_[0]->{query};
Subroutine __ANON__: called CC=3 SCAR=11.0
4580 308 ▶ (defined $qs && length $qs) ? "?$qs" : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $qs && length $qs ? : 16 292 308
Condition100%3/3
defined $qs and length $qs
!ll&&!rl&&r
129116
MC/DC100%2/2
defined $qs and length $qs
defined $qs length $qs
Truth table100%3/3
A and B
A= defined $qsB= length $qs
ABresult
0X0
100
111
4581 },
4582 1 ▶ H => sub { 'HTTP/' . ($_[0]->{http_version} // '1.1') },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"http_version"} // "1.1"
l!l
10
MC/DC0%0/1
$_[0]{"http_version"} // "1.1"
$_[0]{"http_version"}
Truth table50%1/2
A
A= $_[0]{"http_version"}
Aresult
11
00
4583 316 ▶ s => sub { $_[0]->{status} // '-' },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"status"} // "-"
l!l
3160
MC/DC0%0/1
$_[0]{"status"} // "-"
$_[0]{"status"}
Truth table50%1/2
A
A= $_[0]{"status"}
Aresult
11
00
4584 b => sub {
4585 10 ▶ my $size = $_[0]->{size} // 0;
Subroutine __ANON__: called CC=3 SCAR=11.1
Condition50%1/2
$_[0]{"size"} // 0
l!l
100
MC/DC0%0/1
$_[0]{"size"} // 0
$_[0]{"size"}
Truth table50%1/2
A
A= $_[0]{"size"}
Aresult
11
00
4586 10 ▶ $size ? $size : '-';
Branch: 1 branch
BranchTrueFalseTotal
$size ? : 9 1 10
4587 },
4588 2 ▶ B => sub { $_[0]->{size} // 0 },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"size"} // 0
l!l
20
MC/DC0%0/1
$_[0]{"size"} // 0
$_[0]{"size"}
Truth table50%1/2
A
A= $_[0]{"size"}
Aresult
11
00
4589 305 ▶ d => sub { sprintf('%.3f', $_[0]->{duration} // 0) },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"duration"} // 0
l!l
3050
MC/DC0%0/1
$_[0]{"duration"} // 0
$_[0]{"duration"}
Truth table50%1/2
A
A= $_[0]{"duration"}
Aresult
11
00
4590 4 ▶ D => sub { int(($_[0]->{duration} // 0) * 1_000_000) },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"duration"} // 0
l!l
40
MC/DC0%0/1
$_[0]{"duration"} // 0
$_[0]{"duration"}
Truth table50%1/2
A
A= $_[0]{"duration"}
Aresult
11
00
4591 2 ▶ T => sub { int($_[0]->{duration} // 0) },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$_[0]{"duration"} // 0
l!l
20
MC/DC0%0/1
$_[0]{"duration"} // 0
$_[0]{"duration"}
Truth table50%1/2
A
A= $_[0]{"duration"}
Aresult
11
00
4592 4422 );
4593  
4594 4422 ▶ if (my $frag = $atoms{$atom}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $frag = $atoms{$atom}) 4421 1 4422
4595 4421 return $frag;
4596 }
4597  
4598 1 die "Unknown access log format atom '%$atom'\n";
4599 }
4600  
4601 sub port {
4602 265 ▶ my ($self) = @_;
Subroutine port: called CC=2 SCAR=7.1
Pod documented
4603  
4604 265 ▶ return $self->{bound_port} // $self->{port};
Condition66%2/3
$self->{"bound_port"} // $self->{"port"}
l!l&&r!l&&!r
26401
MC/DC50%1/2
$self->{"bound_port"} // $self->{"port"}
$self->{"bound_port"} $self->{"port"}
Truth table66%2/3
A // B
A= $self->{"bound_port"}B= $self->{"port"}
ABresult
1X1
011
000
4605 }
4606  
4607 sub socket_path {
4608 4 ▶ my ($self) = @_;
Subroutine socket_path: called CC=4 SCAR=13.9
Pod documented
4609 4 ▶ for my $listener (@{$self->{listeners} // []}) {
Condition50%1/2
$self->{"listeners"} // []
l!l
40
MC/DC0%0/1
$self->{"listeners"} // []
$self->{"listeners"}
Truth table50%1/2
A
A= $self->{"listeners"}
Aresult
11
00
4610 4 ▶ return $listener->{path} if $listener->{type} eq 'unix';
Branch: 1 branch
BranchTrueFalseTotal
if $listener->{"type"} eq "unix" 2 2 4
4611 }
4612 2 return undef;
4613 }
4614  
4615 sub listeners {
4616 5 ▶ my ($self) = @_;
Subroutine listeners: called CC=2 SCAR=7.2
Pod documented
4617 5 ▶ return $self->{listeners} // [];
Condition50%1/2
$self->{"listeners"} // []
l!l
50
MC/DC0%0/1
$self->{"listeners"} // []
$self->{"listeners"}
Truth table50%1/2
A
A= $self->{"listeners"}
Aresult
11
00
4618 }
4619  
4620 sub is_running {
4621 23 ▶ my ($self) = @_;
Subroutine is_running: called CC=2 SCAR=6.9
Pod documented
4622  
4623 23 ▶ return $self->{running} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'running'} ? : 19 4 23
4624 }
4625  
4626 sub connection_count {
4627 314 ▶ my ($self) = @_;
Subroutine connection_count: called CC=1 SCAR=0.0
Pod documented
4628  
4629 314 return scalar keys %{$self->{connections}};
4630 }
4631  
4632 sub effective_max_connections {
4633 618 ▶ my ($self) = @_;
Subroutine effective_max_connections: called CC=3 SCAR=11.1
Pod documented
4634  
4635 # If explicitly set, use that; otherwise default to 1000
4636 # (Same default as Mojolicious - simple, predictable, no platform-specific hacks)
4637 return $self->{max_connections} && $self->{max_connections} > 0
4638 ? $self->{max_connections}
4639 618 ▶ : 1000;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'max_connections'} && $self->{'max_connections'} > 0 ? : 15 603 618
Condition66%2/3
$self->{"max_connections"} and $self->{"max_connections"} > 0
!ll&&!rl&&r
603015
MC/DC50%1/2
$self->{"max_connections"} and $self->{"max_connections"} > 0
$self->{"max_connections"} $self->{"max_connections"} > 0
Truth table66%2/3
A and B
A= $self->{"max_connections"}B= $self->{"max_connections"} > 0
ABresult
0X0
100
111
4640 }
4641  
4642 151 1;
4643  
4644 __END__
↑ Summary blib/lib/PAGI/Server/AsyncFile.pm »