blib/lib/PAGI/Server/Connection.pm

filter: Statementstmt 92.2% 2518 / 2731 Branchbran 70.3% 1152 / 1638 Conditioncond 64.8% 579 / 893 MC/DCmcdc 36.2% 177 / 488 Subroutinesub 97.5% 200 / 205 Podpod 0.0% 0 / 2 totaltotal 77.6% 4626 / 5957 CC 1206 SCAR 35.3
CC
1206
Cov
81%
_process_websocket_frames
157.8
__ANON__
120.2
_read_chunked_body
119.7
CRAP 34.2
« blib/lib/PAGI/Server/AsyncFile.pm ↑ Summary blib/lib/PAGI/Server/Runner.pm »
1 package PAGI::Server::Connection;
2 154 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 154 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 154 our $VERSION = '0.002012';
6  
7 154 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 154 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 154 ▶use Scalar::Util qw(weaken refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 154 ▶use Protocol::WebSocket::Handshake::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 154 ▶use Protocol::WebSocket::Frame;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 154 ▶use Digest::SHA qw(sha1_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 154 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 154 ▶use URI::Escape qw(uri_unescape);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 154 ▶use IO::Async::Timer::Countdown;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 154 ▶use IO::Async::Timer::Periodic;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 154 ▶use Time::HiRes qw(gettimeofday tv_interval);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 154 ▶use PAGI::Server::AsyncFile;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 154 ▶use PAGI::Server::ConnectionState;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 154 ▶use PAGI::Server::TransportState;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 154 ▶use PAGI::Server::EventValidator;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23  
24 154 ▶use constant FILE_CHUNK_SIZE => 65536; # 64KB chunks for file streaming
Subroutine BEGIN: called CC=1 SCAR=0.0
25  
26 # Per-second cache for CLF timestamp in access log (same pattern as HTTP1::format_date)
27 154 my $_cached_log_timestamp;
28 154 my $_cached_log_time = 0;
29  
30 # =============================================================================
31 # Header Validation (CRLF Injection Prevention)
32 # =============================================================================
33 # RFC 7230 Section 3.2.6: Field values MUST NOT contain CR or LF
34  
35 172 ▶sub _validate_header_value { PAGI::Server::EventValidator::check_header_value($_[0]) }
Subroutine _validate_header_value: called CC=1 SCAR=0.0
36  
37 172 ▶sub _validate_header_name { PAGI::Server::EventValidator::check_header_name($_[0]) }
Subroutine _validate_header_name: called CC=1 SCAR=0.0
38  
39 # =============================================================================
40 # HTTP/2 connection-specific header stripping (RFC 9113 section 8.2.2, design
41 # doc section 13.3)
42 # =============================================================================
43 # HTTP/2 forbids connection-specific header fields. An app-supplied
44 # connection, keep-alive, proxy-connection, transfer-encoding, or upgrade
45 # header -- or a te header carrying anything but the token 'trailers' --
46 # corrupts the response at the framing layer: the client receives only
47 # :status, with no body. HTTP/1.1 has no such prohibition, so this strip
48 # applies only to the HTTP/2 response paths that call it.
49 154 my %H2_CONNECTION_SPECIFIC_HEADER = map { $_ => 1 }
50 qw(connection keep-alive proxy-connection transfer-encoding upgrade te);
51  
52 # Returns a new arrayref with connection-specific header pairs removed,
53 # warning once per stripped occurrence (not deduplicated by name -- two
54 # 'keep-alive' headers warn twice). Does not mutate $headers.
55 #
56 # $in_trailers (optional, default false) selects the trailer-block variant
57 # of this rule: RFC 9110 section 6.6.2 forbids every connection-specific
58 # field from a trailer section outright, so unlike a response's HEADERS
59 # block there is no 'te: trailers' carve-out inside a trailer block itself
60 # -- that carve-out is what lets a response ADVERTISE trailers are coming,
61 # not something a trailer block may then contain. A trailer-borne 'te'
62 # tuple is therefore stripped regardless of its value.
63 sub _h2_strip_connection_headers {
64 198 ▶ my ($headers, $in_trailers) = @_;
Subroutine _h2_strip_connection_headers: called CC=7 SCAR=19.5
65 198 ▶ my $context = $in_trailers ? 'trailers' : 'response';
Branch: 1 branch
BranchTrueFalseTotal
$in_trailers ? : 10 188 198
66 198 my @kept;
67 198 for my $h (@$headers) {
68 152 my ($name, $value) = @$h;
69 152 my $lc_name = lc $name;
70 152 ▶ if ($H2_CONNECTION_SPECIFIC_HEADER{$lc_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($H2_CONNECTION_SPECIFIC_HEADER{$lc_name}) 25 127 152
71 # RFC 9113 permits a response 'te' only with the exact token
72 # 'trailers'; a case-insensitive VALUE compare (not a name/list
73 # match) is what the token grammar calls for. OWS
74 # (leading/trailing whitespace) around the token is trimmed
75 # before the compare, per RFC 9110's field-value grammar -- a
76 # compound value like 'trailers, gzip' is not the bare token and
77 # is still stripped. This carve-out does not apply in a trailer
78 # block (see $in_trailers above).
79 25 ▶ if (!$in_trailers && $lc_name eq 'te') {
Branch: 1 branch
BranchTrueFalseTotal
if (not $in_trailers and $lc_name eq "te") 4 21 25
Condition100%3/3
not $in_trailers and $lc_name eq "te"
!ll&&!rl&&r
6154
MC/DC100%2/2
not $in_trailers and $lc_name eq "te"
not $in_trailers $lc_name eq "te"
Truth table100%3/3
not(A) and B
A= not $in_trailersB= $lc_name eq "te"
ABresult
0X0
100
111
80 4 (my $v = lc $value) =~ s/^\s+|\s+\z//g;
81 4 ▶ if ($v eq 'trailers') {
Branch: 1 branch
BranchTrueFalseTotal
if ($v eq "trailers") 2 2 4
82 # Submit the normalized token, never the original value:
83 # RFC 9113 8.2.1 forbids OWS in field values, and
84 # libnghttp2 versions disagree on how to punish one
85 # (omit the field vs corrupt the whole response).
86 2 push @kept, [$name, 'trailers'];
87 2 next;
88 }
89 }
90 23 warn "PAGI: connection-specific header '$name' stripped from HTTP/2 $context (RFC 9113)\n";
91 23 next;
92 }
93 127 push @kept, $h;
94 }
95 198 return \@kept;
96 }
97  
98 # =============================================================================
99 # HTTP/1.1 connection-specific header stripping (PAGI spec: "Over HTTP/1.1
100 # the server must ignore or strip application-supplied Transfer-Encoding and
101 # Connection -- it supplies its own -- and SHOULD log when it does")
102 # =============================================================================
103 # Deliberately narrower than the HTTP/2 six-name strip above: HTTP/1.1 has
104 # no prohibition on keep-alive, proxy-connection, upgrade, or te as ordinary
105 # application response headers, so only the two names the server itself
106 # always owns the framing/connection-state for -- transfer-encoding and
107 # connection -- are stripped here.
108 154 my %H1_CONNECTION_SPECIFIC_HEADER = map { $_ => 1 } qw(transfer-encoding connection);
109  
110 # Returns a new arrayref with app-supplied transfer-encoding/connection pairs
111 # removed, warning once per stripped occurrence (not deduplicated by name --
112 # two 'connection' headers warn twice). Does not mutate $headers.
113 sub _h1_strip_connection_headers {
114 284 ▶ my ($headers) = @_;
Subroutine _h1_strip_connection_headers: called CC=3 SCAR=11.0
115 284 my @kept;
116 284 for my $h (@$headers) {
117 288 my ($name, $value) = @$h;
118 288 ▶ if ($H1_CONNECTION_SPECIFIC_HEADER{lc $name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($H1_CONNECTION_SPECIFIC_HEADER{lc $name}) 14 274 288
119 14 warn "PAGI: connection-specific header '$name' stripped from HTTP/1.1 response\n";
120 14 next;
121 }
122 274 push @kept, $h;
123 }
124 284 return \@kept;
125 }
126  
127 # SSE client-signal check (PAGI Www.pod "SSE Connection Detection"): the
128 # exact media range text/event-stream, case-insensitively, with q > 0.
129 # A boolean signal test, not content negotiation: wildcards never signal
130 # SSE, and q=0 is an explicit refusal.
131 sub _accept_signals_sse {
132 451 ▶ my ($headers) = @_;
Subroutine _accept_signals_sse: called CC=9 SCAR=22.0
133 451 my @values;
134 451 for my $h (@$headers) {
135 977 ▶ push @values, $h->[1] if $h->[0] eq 'accept';
Branch: 1 branch
BranchTrueFalseTotal
if $h->[0] eq "accept" 110 867 977
136 }
137 451 ▶ return 0 unless @values;
Branch: 1 branch
BranchTrueFalseTotal
unless @values 342 109 451
138 109 for my $range (split /,/, join(',', @values)) {
139 113 my ($type, @params) = split /;/, $range;
140 113 $type =~ s/\A\s+|\s+\z//g;
141 113 ▶ next unless lc($type) eq 'text/event-stream';
Branch: 1 branch
BranchTrueFalseTotal
unless lc $type eq "text/event-stream" 11 102 113
142 102 my $q = 1;
143 102 for my $p (@params) {
144 4 $p =~ s/\A\s+|\s+\z//g;
145 4 ▶ $q = $1 if $p =~ /\Aq\s*=\s*([0-9.]+)\z/i;
Branch: 1 branch
BranchTrueFalseTotal
if $p =~ /\Aq\s*=\s*([0-9.]+)\z/i 4 0 4
146 }
147 102 ▶ return 1 if $q > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $q > 0 100 2 102
148 }
149 9 return 0;
150 }
151  
152 # RFC 6455 Section 11.3.4: Subprotocol must be a token (no whitespace, separators)
153 sub _validate_subprotocol {
154 1 ▶ my ($value) = @_;
Subroutine _validate_subprotocol: called CC=3 SCAR=16.0
155  
156 1 ▶ if ($value =~ /[\r\n\0\s]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /[\r\n\0\s]/) 1 0 1
157 1 die "Invalid subprotocol: contains CR, LF, null, or whitespace\n";
158 }
159 # Token characters only (roughly)
160 0 ▶ if ($value !~ /^[\w\-\.]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($value =~ /^[\w\-\.]+$/) 0 0 0
161 0 die "Invalid subprotocol: must be alphanumeric, dash, underscore, or dot\n";
162 }
163 0 return $value;
164 }
165  
166 =head1 NAME
167  
168 PAGI::Server::Connection - Per-connection state machine
169  
170 =head1 SYNOPSIS
171  
172 # Internal use by PAGI::Server
173 my $conn = PAGI::Server::Connection->new(
174 stream => $stream,
175 app => $app,
176 protocol => $protocol,
177 server => $server,
178 extensions => {},
179 );
180 $conn->start;
181  
182 =head1 DESCRIPTION
183  
184 PAGI::Server::Connection manages the state machine for a single client
185 connection. It handles:
186  
187 =over 4
188  
189 =item * Request parsing via Protocol::HTTP1
190  
191 =item * Scope creation for the application
192  
193 =item * Event queue management for $receive and $send
194  
195 =item * Protocol upgrades (WebSocket, SSE)
196  
197 =item * SSE over HTTP/1.1 and HTTP/2
198  
199 =item * Connection lifecycle and cleanup
200  
201 =back
202  
203 =cut
204  
205 sub new {
206 521 ▶ my ($class, %args) = @_;
Subroutine new: called CC=17 SCAR=28.3
Pod undocumented
207  
208 my $self = bless {
209 stream => $args{stream},
210 app => $args{app},
211 protocol => $args{protocol},
212 server => $args{server},
213 extensions => $args{extensions} // {},
214 state => $args{state} // {},
215 tls_enabled => $args{tls_enabled} // 0,
216 timeout => $args{timeout} // 60, # Idle timeout in seconds
217 request_timeout => $args{request_timeout} // 0, # Request stall timeout in seconds (0 = disabled, default for performance)
218 ws_idle_timeout => $args{ws_idle_timeout} // 0, # WebSocket idle timeout (0 = disabled)
219 sse_idle_timeout => $args{sse_idle_timeout} // 0, # SSE idle timeout (0 = disabled)
220 max_body_size => $args{max_body_size}, # 0 = unlimited
221 access_log => $args{access_log}, # Filehandle for access logging
222 _access_log_formatter => $args{_access_log_formatter}, # Pre-compiled format closure
223 max_receive_queue => $args{max_receive_queue} // 1000, # Max WebSocket receive queue size
224 max_ws_frame_size => $args{max_ws_frame_size} // 65536, # Max WebSocket frame size in bytes
225 sync_file_threshold => $args{sync_file_threshold} // 65536, # Threshold for sync file reads (default 64KB)
226 validate_events => $args{validate_events} // 0, # Deprecated: core event validation is mandatory; this flag is retained for compatibility and controls nothing.
227 # Send-side backpressure (watermarks in bytes)
228 # Defaults match Python asyncio: 64KB high, 16KB low (high/4)
229 write_high_watermark => $args{write_high_watermark} // 65536, # 64KB - pause sending above this
230 write_low_watermark => $args{write_low_watermark} // 16384, # 16KB - resume sending below this
231 _drain_waiters => [], # Pending Futures for blocking backpressure (a producer awaiting buffer drain)
232 _drain_fires => [], # arm_drain callback fires (on_drain hysteresis) -- kept separate from
233 # _drain_waiters so teardown can resume the former without invoking the
234 # latter (mirrors h2's stream_drain_waiters vs transport_drain_fires split)
235 _drain_check_active => 0, # Flag to prevent redundant on_outgoing_empty setup
236 tls_info => undef, # Populated on first request if TLS
237 buffer => '',
238 closed => 0,
239 response_started => 0,
240 h1_seq => 'initial', # Mirrors the h1 send closure's $seq (see _create_send)
241 response_status => undef, # Track response status for logging
242 _response_size => 0, # Track response body bytes for logging
243 request_start => undef, # Track request start time for logging
244 idle_timer => undef, # IO::Async::Timer for idle timeout
245 _served_a_request => 0, # True once a request has completed on this connection (idle_timer reason: idle_timeout -> keepalive_timeout)
246 stall_timer => undef, # IO::Async::Timer for request stall timeout
247 ws_idle_timer => undef, # IO::Async::Timer for WebSocket idle timeout
248 sse_idle_timer => undef, # IO::Async::Timer for SSE idle timeout
249 # Event queue for $receive
250 receive_queue => [],
251 receive_pending => undef,
252 # Track all pending receive Futures to cancel on close
253 receive_futures => [],
254 # Track request handling Future to prevent "lost future" warning
255 request_future => undef,
256 # Idempotency guard for disconnect handling
257 _disconnect_handled => 0,
258 # WebSocket state
259 websocket_mode => 0,
260 websocket_frame => undef, # Protocol::WebSocket::Frame for parsing
261 websocket_accepted => 0,
262 # SSE state
263 sse_mode => 0,
264 sse_started => 0,
265 sse_disconnect_reason => undef, # Reason for SSE disconnect (client_closed, write_error, etc.)
266 ws_disconnect_reason => undef, # Standard reason token for the app-facing websocket.disconnect event
267 ws_disconnect_code => undef, # Wire close code for that event (defaults to 1006, abnormal closure)
268 # Keepalive state (protocol-level ping/pong for WebSocket, comments for SSE)
269 ws_keepalive_timer => undef, # Periodic timer for sending WebSocket pings
270 ws_pong_timeout => undef, # Timeout timer for pong response
271 ws_waiting_pong => 0, # Flag: are we waiting for a pong?
272 ws_keepalive_interval => 0, # Current keepalive interval (0 = disabled)
273 ws_keepalive_timeout => 0, # Current pong timeout (0 = no timeout check)
274 sse_keepalive_timer => undef, # Periodic timer for sending SSE keepalive comments
275 sse_keepalive_comment => '', # Comment text to send
276 # HTTP/2 state
277 alpn_protocol => $args{alpn_protocol}, # ALPN-negotiated protocol (e.g. 'h2', 'http/1.1')
278 h2_protocol => $args{h2_protocol}, # PAGI::Server::Protocol::HTTP2 instance
279 h2c_enabled => $args{h2c_enabled} // 0, # Allow h2c preface detection on cleartext
280 is_h2 => 0, # Set during start() if HTTP/2 detected
281 h2_session => undef, # PAGI::Server::Protocol::HTTP2::Session
282 h2_streams => {}, # Per-stream state for HTTP/2
283 # Transport info (tcp or unix)
284 transport_type => $args{transport_type} // 'tcp',
285 transport_path => $args{transport_path}, # socket path for unix
286 # Cached connection info (populated in start(), used by _create_scope)
287 521 ▶ client_host => '127.0.0.1',
Condition100%30/30
$args{"extensions"} // {}
l!l
313208
$args{"state"} // {}
l!l
302219
$args{"tls_enabled"} // 0
l!l
302219
$args{"timeout"} // 60
l!l
305216
$args{"request_timeout"} // 0
l!l
302219
$args{"ws_idle_timeout"} // 0
l!l
302219
$args{"sse_idle_timeout"} // 0
l!l
311210
$args{"max_receive_queue"} // 1000
l!l
305216
$args{"max_ws_frame_size"} // 65536
l!l
304217
$args{"sync_file_threshold"} // 65536
l!l
302219
$args{"validate_events"} // 0
l!l
302219
$args{"write_high_watermark"} // 65536
l!l
322199
$args{"write_low_watermark"} // 16384
l!l
319202
$args{"h2c_enabled"} // 0
l!l
144377
$args{"transport_type"} // "tcp"
l!l
305216
MC/DC100%1/1
$args{"extensions"} // {}
$args{"extensions"}
MC/DC100%1/1
$args{"state"} // {}
$args{"state"}
MC/DC100%1/1
$args{"tls_enabled"} // 0
$args{"tls_enabled"}
MC/DC100%1/1
$args{"timeout"} // 60
$args{"timeout"}
MC/DC100%1/1
$args{"request_timeout"} // 0
$args{"request_timeout"}
MC/DC100%1/1
$args{"ws_idle_timeout"} // 0
$args{"ws_idle_timeout"}
MC/DC100%1/1
$args{"sse_idle_timeout"} // 0
$args{"sse_idle_timeout"}
MC/DC100%1/1
$args{"max_receive_queue"} // 1000
$args{"max_receive_queue"}
MC/DC100%1/1
$args{"max_ws_frame_size"} // 65536
$args{"max_ws_frame_size"}
MC/DC100%1/1
$args{"sync_file_threshold"} // 65536
$args{"sync_file_threshold"}
MC/DC100%1/1
$args{"validate_events"} // 0
$args{"validate_events"}
MC/DC100%1/1
$args{"write_high_watermark"} // 65536
$args{"write_high_watermark"}
MC/DC100%1/1
$args{"write_low_watermark"} // 16384
$args{"write_low_watermark"}
MC/DC100%1/1
$args{"h2c_enabled"} // 0
$args{"h2c_enabled"}
MC/DC100%1/1
$args{"transport_type"} // "tcp"
$args{"transport_type"}
Truth table100%2/2
A
A= $args{"extensions"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"state"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"tls_enabled"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"request_timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"ws_idle_timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"sse_idle_timeout"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"max_receive_queue"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"max_ws_frame_size"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"sync_file_threshold"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"validate_events"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"write_high_watermark"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"write_low_watermark"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"h2c_enabled"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"transport_type"}
Aresult
11
00
288 client_port => 0,
289 server_host => '127.0.0.1',
290 server_port => 5000,
291 }, $class;
292  
293 # Extract TLS info if this is a TLS connection
294 521 ▶ if ($self->{tls_enabled}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tls_enabled"}) 45 476 521
295 45 $self->_extract_tls_info;
296 }
297  
298 521 return $self;
299 }
300  
301 154 ▶use Socket qw(IPPROTO_TCP TCP_NODELAY);
Subroutine BEGIN: called CC=1 SCAR=0.0
302  
303 sub start {
304 512 ▶ my ($self) = @_;
Subroutine start: called CC=15 SCAR=27.3
Pod undocumented
305  
306 512 my $stream = $self->{stream};
307 512 weaken(my $weak_self = $self);
308  
309 # Enable TCP_NODELAY to reduce latency for small responses (TCP only)
310 512 ▶ my $handle = $stream->write_handle // $stream->read_handle;
Condition33%1/3
$stream->write_handle // $stream->read_handle
l!l&&r!l&&!r
51200
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
311 512 ▶ if ($self->{transport_type} eq 'tcp' && $handle && $handle->can('setsockopt')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"transport_type"} eq "tcp" and $handle and $handle->can("setsockopt")) 300 212 512
Condition83%5/6
$self->{"transport_type"} eq "tcp" and $handle and $handle->can("setsockopt")
!ll&&!rl&&r
5207300
$self->{"transport_type"} eq "tcp" and $handle
!ll&&!rl&&r
50507
MC/DC66%2/3
$self->{"transport_type"} eq "tcp" and $handle and $handle->can("setsockopt")
$self->{"transport_type"} eq "tcp" $handle $handle->can("setsockopt")
Truth table75%3/4
A and B and C
A= $self->{"transport_type"} eq "tcp"B= $handleC= $handle->can("setsockopt")
ABCresult
0XX0
10X0
1100
1111
312 300 eval {
313 300 $handle->setsockopt(IPPROTO_TCP, TCP_NODELAY, 1);
314 };
315 # Ignore errors - not all sockets support this
316 }
317  
318 # Cache connection info once (avoids per-request socket method calls)
319 512 ▶ if ($self->{transport_type} eq 'unix') {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'transport_type'} eq 'unix') { } 5 507 512
elsif ($handle and $handle->can('peerhost')) { } 299 208 507
320 # Unix socket: no peer IP/port, server is identified by path
321 5 $self->{client_host} = undef;
322 5 $self->{client_port} = undef;
323 5 $self->{server_host} = $self->{transport_path};
324 5 $self->{server_port} = undef;
325 ▶ } elsif ($handle && $handle->can('peerhost')) {
Condition66%2/3
$handle and $handle->can("peerhost")
!ll&&!rl&&r
0208299
MC/DC50%1/2
$handle and $handle->can("peerhost")
$handle $handle->can("peerhost")
Truth table66%2/3
A and B
A= $handleB= $handle->can("peerhost")
ABresult
0X0
100
111
326 299 eval {
327 299 ▶ $self->{client_host} = $handle->peerhost // '127.0.0.1';
Condition100%2/2
$handle->peerhost // "127.0.0.1"
l!l
2981
MC/DC100%1/1
$handle->peerhost // "127.0.0.1"
$handle->peerhost
Truth table100%2/2
A
A= $handle->peerhost
Aresult
11
00
328 299 ▶ $self->{client_port} = $handle->peerport // 0;
Condition100%2/2
$handle->peerport // 0
l!l
2981
MC/DC100%1/1
$handle->peerport // 0
$handle->peerport
Truth table100%2/2
A
A= $handle->peerport
Aresult
11
00
329 299 ▶ $self->{server_host} = $handle->sockhost // '127.0.0.1';
Condition50%1/2
$handle->sockhost // "127.0.0.1"
l!l
2990
MC/DC0%0/1
$handle->sockhost // "127.0.0.1"
$handle->sockhost
Truth table50%1/2
A
A= $handle->sockhost
Aresult
11
00
330 299 ▶ $self->{server_port} = $handle->sockport // 5000;
Condition50%1/2
$handle->sockport // 5000
l!l
2990
MC/DC0%0/1
$handle->sockport // 5000
$handle->sockport
Truth table50%1/2
A
A= $handle->sockport
Aresult
11
00
331 };
332 # Ignore errors - keep defaults if extraction fails
333 }
334  
335 # Detect HTTP/2 via ALPN negotiation
336 512 ▶ if ($self->{alpn_protocol} && $self->{alpn_protocol} eq 'h2' && $self->{h2_protocol}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"alpn_protocol"} and $self->{"alpn_protocol"} eq "h2" and $self->{"h2_protocol"}) 62 450 512
Condition83%5/6
$self->{"alpn_protocol"} and $self->{"alpn_protocol"} eq "h2" and $self->{"h2_protocol"}
!ll&&!rl&&r
450062
$self->{"alpn_protocol"} and $self->{"alpn_protocol"} eq "h2"
!ll&&!rl&&r
449162
MC/DC66%2/3
$self->{"alpn_protocol"} and $self->{"alpn_protocol"} eq "h2" and $self->{"h2_protocol"}
$self->{"alpn_protocol"} $self->{"alpn_protocol"} eq "h2" $self->{"h2_protocol"}
Truth table75%3/4
A and B and C
A= $self->{"alpn_protocol"}B= $self->{"alpn_protocol"} eq "h2"C= $self->{"h2_protocol"}
ABCresult
0XX0
10X0
1100
1111
337 62 $self->_init_h2_session;
338 }
339  
340 # Set up idle timeout timer
341 512 $self->_start_idle_timer;
342  
343 # Set up read handler
344 $stream->configure(
345 on_read => sub {
346 1151 ▶ my ($s, $buffref, $eof) = @_;
Subroutine __ANON__: called CC=15 SCAR=27.2
347 1151 ▶ return 0 unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 7 1144 1151
348  
349 # Reset idle timer on any read activity
350 1144 $weak_self->_reset_idle_timer;
351  
352 # Reset stall timer on read activity (if handling a request)
353 1144 ▶ $weak_self->_reset_stall_timer if $weak_self->{handling_request};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"handling_request"} 57 1087 1144
354  
355 1144 $weak_self->{buffer} .= $$buffref;
356 1144 $$buffref = '';
357  
358 1144 ▶ if ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 31 1113 1144
359 # EOF means client closed - handle disconnect and cleanup
360 31 $weak_self->_handle_disconnect_and_close('client_closed');
361 31 return 0;
362 }
363  
364 # h2c detection: check if cleartext connection starts with HTTP/2 preface
365 1113 ▶ if ($weak_self->{h2c_enabled} && !$weak_self->{is_h2}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"h2c_enabled"} and not $weak_self->{"is_h2"}) 143 970 1113
Condition66%2/3
$weak_self->{"h2c_enabled"} and not $weak_self->{"is_h2"}
!ll&&!rl&&r
9700143
MC/DC50%1/2
$weak_self->{"h2c_enabled"} and not $weak_self->{"is_h2"}
$weak_self->{"h2c_enabled"} not $weak_self->{"is_h2"}
Truth table66%2/3
A and not(B)
A= $weak_self->{"h2c_enabled"}B= not $weak_self->{"is_h2"}
ABresult
0X0
100
111
366 143 ▶ if (length($weak_self->{buffer}) >= 24) { # HTTP/2 preface is 24 bytes
Branch: 1 branch
BranchTrueFalseTotal
if (length $weak_self->{'buffer'} >= 24) { } 143 0 143
367 143 ▶ if ($weak_self->{h2_protocol} && PAGI::Server::Protocol::HTTP2->detect_preface($weak_self->{buffer})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{'h2_protocol'} and 'PAGI::Server::Protocol::HTTP2'->detect_preface($weak_self->{'buffer'})) { } 142 1 143
Condition66%2/3
$weak_self->{"h2_protocol"} and "PAGI::Server::Protocol::HTTP2"->detect_preface($weak_self->{"buffer"})
!ll&&!rl&&r
01142
MC/DC50%1/2
$weak_self->{"h2_protocol"} and "PAGI::Server::Protocol::HTTP2"->detect_preface($weak_self->{"buffer"})
$weak_self->{"h2_protocol"} "PAGI::Server::Protocol::HTTP2"->detect_preface($weak_self->{"buffer"})
Truth table66%2/3
A and B
A= $weak_self->{"h2_protocol"}B= "PAGI::Server::Protocol::HTTP2"->detect_preface($weak_self->{"buffer"})
ABresult
0X0
100
111
368 142 $weak_self->_init_h2_session;
369 142 $weak_self->{h2c_enabled} = 0; # Detection done
370 } else {
371 1 $weak_self->{h2c_enabled} = 0; # Not h2c, stop checking
372 }
373 } else {
374 # Not enough data yet to determine protocol, wait for more
375 0 return 0;
376 }
377 }
378  
379 # Wrap processing in eval to prevent exceptions from crashing the event loop
380 # This is critical - Protocol::WebSocket::Frame can throw exceptions for
381 # oversized payloads, and other parsing code may throw as well
382 1113 eval {
383 # HTTP/2: feed data to session for frame processing
384 1113 ▶ if ($weak_self->{is_h2}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"is_h2"}) 738 375 1113
385 738 $weak_self->_h2_process_data;
386 738 return;
387 }
388  
389 # If in WebSocket mode, process WebSocket frames
390 375 ▶ if ($weak_self->{websocket_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"websocket_mode"}) 27 348 375
391 27 $weak_self->_process_websocket_frames;
392 26 return;
393 }
394  
395 # If we're waiting for body data, notify the receive handler
396 348 ▶ if ($weak_self->{receive_pending} && !$weak_self->{receive_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready) 15 333 348
Condition66%2/3
$weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready
!ll&&!rl&&r
333015
MC/DC50%1/2
$weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready
$weak_self->{"receive_pending"} not $weak_self->{"receive_pending"}->is_ready
Truth table66%2/3
A and not(B)
A= $weak_self->{"receive_pending"}B= not $weak_self->{"receive_pending"}->is_ready
ABresult
0X0
100
111
397 15 my $f = $weak_self->{receive_pending};
398 15 $weak_self->{receive_pending} = undef;
399 15 $f->done;
400 }
401  
402 348 $weak_self->_try_handle_request;
403 };
404 1113 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 1 1112 1113
405 # Log the error and close the connection gracefully
406 1 warn "PAGI connection error: $error";
407 1 ▶ return 0 unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
408 1 $weak_self->_handle_disconnect_and_close('server_error');
409 }
410 1113 return 0;
411 },
412 on_closed => sub {
413 505 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 95 410 505
414 # Stream closed - handle disconnect and remove from connections hash
415 410 $weak_self->_handle_disconnect_and_close('client_closed');
416 },
417 # Without these, IO::Async::Stream's own contract applies: "If an
418 # error occurs when the corresponding error callback is not
419 # supplied, ... the close method is called instead" -- i.e. it would
420 # call close_now itself and (via on_closed above) report every
421 # socket error as client_closed, indistinguishable from an ordinary
422 # peer disconnect. Registering a handler here -- regardless of what
423 # it returns -- is sufficient by itself to suppress that close_now
424 # (maybe_invoke_event always returns a truthy value once any handler
425 # exists), so there is no double-teardown risk from IO::Async's
426 # side; _handle_disconnect_and_close's own _disconnect_handled guard
427 # covers the (harmless, pre-existing) case where on_closed also
428 # fires afterward once the socket actually finishes closing.
429 on_read_error => sub {
430 6 ▶ my ($s, $errno) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
431 6 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 6 6
432 6 $weak_self->_handle_disconnect_and_close('read_error');
433 },
434 on_write_error => sub {
435 5 ▶ my ($s, $errno) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
436 5 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 3 2 5
437 2 $weak_self->_handle_disconnect_and_close('write_error');
438 },
439 512 );
440 }
441  
442 # Arm the idle timeout. Called once at connection setup (before any request
443 # has completed on this connection) and again whenever a long-lived mode
444 # that removed the timer (SSE) hands the connection back to ordinary
445 # keep-alive request handling, or a plain request completes and the
446 # connection stays open awaiting the next one. The same timer instance
447 # serves both cases (it is only reset, never re-created, by ordinary reads);
448 # on_expire decides its reason token at fire time from _served_a_request,
449 # per the spec's split between idle_timeout (nothing has arrived yet) and
450 # keepalive_timeout (a request already completed on this connection).
451 sub _start_idle_timer {
452 537 ▶ my ($self) = @_;
Subroutine _start_idle_timer: called CC=5 SCAR=16.6
453  
454 537 ▶ return if $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"} 0 537 537
455 537 ▶ return unless $self->{timeout} && $self->{timeout} > 0 && $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"timeout"} and $self->{"timeout"} > 0 and $self->{"server"} 0 534 534
Condition66%4/6
$self->{"timeout"} and $self->{"timeout"} > 0 and $self->{"server"}
!ll&&!rl&&r
30534
$self->{"timeout"} and $self->{"timeout"} > 0
!ll&&!rl&&r
30534
MC/DC33%1/3
$self->{"timeout"} and $self->{"timeout"} > 0 and $self->{"server"}
$self->{"timeout"} $self->{"timeout"} > 0 $self->{"server"}
Truth table50%2/4
A and B and C
A= $self->{"timeout"}B= $self->{"timeout"} > 0C= $self->{"server"}
ABCresult
0XX0
10X0
1100
1111
456  
457 534 weaken(my $weak_self = $self);
458  
459 my $timer = IO::Async::Timer::Countdown->new(
460 delay => $self->{timeout},
461 on_expire => sub {
462 2 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=4 SCAR=14.2
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
463 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
464 # Close idle connection
465 2 ▶ my $reason = $weak_self->{_served_a_request} ? 'keepalive_timeout' : 'idle_timeout';
Branch: 1 branch
BranchTrueFalseTotal
$weak_self->{'_served_a_request'} ? : 1 1 2
466 2 $weak_self->_handle_disconnect_and_close($reason);
467 },
468 534 );
469 534 $self->{idle_timer} = $timer;
470 534 $self->{server}->add_child($timer);
471 534 $timer->start;
472 }
473  
474 sub _reset_idle_timer {
475 1144 ▶ my ($self) = @_;
Subroutine _reset_idle_timer: called CC=5 SCAR=16.1
476  
477 1144 ▶ return unless $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_timer"} 40 1104 1144
478  
479 # Debounce: rescheduling the IO::Async countdown on every read is costly
480 # under keep-alive load -- it re-enqueues a loop timer each time. Reset at
481 # most ~20x/second; this coarsens the idle timeout by at most ~50ms, which is
482 # immaterial for a multi-second idle timeout but cuts the per-request timer
483 # churn dramatically under load.
484 1104 my $now = Time::HiRes::time();
485 1104 ▶ return if defined $self->{_idle_reset_at} && ($now - $self->{_idle_reset_at}) < 0.05;
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"_idle_reset_at"} and $now - $self->{"_idle_reset_at"} < "0.05" 387 717 1104
Condition100%3/3
defined $self->{"_idle_reset_at"} and $now - $self->{"_idle_reset_at"} < "0.05"
!ll&&!rl&&r
502215387
MC/DC100%2/2
defined $self->{"_idle_reset_at"} and $now - $self->{"_idle_reset_at"} < "0.05"
defined $self->{"_idle_reset_at"} $now - $self->{"_idle_reset_at"} < "0.05"
Truth table100%3/3
A and B
A= defined $self->{"_idle_reset_at"}B= $now - $self->{"_idle_reset_at"} < "0.05"
ABresult
0X0
100
111
486 717 $self->{_idle_reset_at} = $now;
487  
488 717 $self->{idle_timer}->reset;
489 717 ▶ $self->{idle_timer}->start unless $self->{idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_timer"}->is_running 0 717 717
490 }
491  
492 sub _stop_idle_timer {
493 602 ▶ my ($self) = @_;
Subroutine _stop_idle_timer: called CC=4 SCAR=13.9
494  
495 602 ▶ return unless $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_timer"} 70 532 602
496 532 ▶ $self->{idle_timer}->stop if $self->{idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"}->is_running 530 2 532
497 # Remove timer completely so _reset_idle_timer won't restart it
498 # This is important for long-lived connections (WebSocket, SSE)
499 532 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 532 0 532
500 532 $self->{server}->remove_child($self->{idle_timer});
501 }
502 532 $self->{idle_timer} = undef;
503 }
504  
505 # =============================================================================
506 # HTTP/2 Session Initialization
507 # =============================================================================
508  
509 sub _init_h2_session {
510 204 ▶ my ($self) = @_;
Subroutine _init_h2_session: called CC=1 SCAR=0.0
511  
512 204 $self->{is_h2} = 1;
513  
514 204 weaken(my $weak_self = $self);
515  
516 $self->{h2_session} = $self->{h2_protocol}->create_session(
517 on_request => sub {
518 209 ▶ my ($stream_id, $pseudo, $headers, $has_body) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
519 209 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 209 209
520 209 $weak_self->_h2_on_request($stream_id, $pseudo, $headers, $has_body);
521 },
522 on_body => sub {
523 85 ▶ my ($stream_id, $data, $eof) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
524 85 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 85 85
525 85 $weak_self->_h2_on_body($stream_id, $data, $eof);
526 },
527 on_close => sub {
528 141 ▶ my ($stream_id, $error_code) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
529 141 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 141 141
530 141 $weak_self->_h2_on_close($stream_id, $error_code);
531 },
532 on_header_overflow => sub {
533 2 ▶ my ($stream_id) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.1
534 2 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
535 2 $weak_self->_h2_on_header_overflow($stream_id);
536 },
537 204 );
538  
539 # Send initial SETTINGS to client
540 204 $self->_h2_write_pending;
541 }
542  
543 sub _h2_process_data {
544 739 ▶ my ($self) = @_;
Subroutine _h2_process_data: called CC=5 SCAR=16.2
545 739 ▶ return unless $self->{h2_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"h2_session"} 0 739 739
546  
547 739 ▶ if (length($self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} > 0) 738 1 739
548 738 $self->{h2_session}->feed($self->{buffer});
549 738 $self->{buffer} = '';
550 }
551  
552 739 $self->_h2_write_pending;
553  
554 # Close connection when session is done (GOAWAY received or sent)
555 739 ▶ if ($self->{h2_session} && !$self->{h2_session}->want_read) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_session"} and not $self->{"h2_session"}->want_read) 2 737 739
Condition66%2/3
$self->{"h2_session"} and not $self->{"h2_session"}->want_read
!ll&&!rl&&r
07372
MC/DC50%1/2
$self->{"h2_session"} and not $self->{"h2_session"}->want_read
$self->{"h2_session"} not $self->{"h2_session"}->want_read
Truth table66%2/3
A and not(B)
A= $self->{"h2_session"}B= not $self->{"h2_session"}->want_read
ABresult
0X0
100
111
556 2 $self->_h2_write_pending; # Flush any remaining output
557 2 $self->_handle_disconnect_and_close;
558 }
559 }
560  
561 sub _h2_write_pending {
562 1436 ▶ my ($self) = @_;
Subroutine _h2_write_pending: called CC=4 SCAR=14.0
563 1436 ▶ return unless $self->{h2_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"h2_session"} 0 1436 1436
564 1436 while (1) {
565 2322 my $data = $self->{h2_session}->extract;
566 2322 ▶ last unless defined $data && length($data) > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data and length $data > 0 1436 886 2322
Condition66%2/3
defined $data and length $data > 0
!ll&&!rl&&r
01436886
MC/DC50%1/2
defined $data and length $data > 0
defined $data length $data > 0
Truth table66%2/3
A and B
A= defined $dataB= length $data > 0
ABresult
0X0
100
111
567 886 $self->{stream}->write($data);
568 }
569 }
570  
571 # =============================================================================
572 # HTTP/2 Stream Callbacks
573 # =============================================================================
574  
575 # RFC 9113 section 10.5.1: "a server that receives a larger header block
576 # than it is willing to handle can send an HTTP 431". Fired by the protocol
577 # layer (PAGI::Server::Protocol::HTTP2) instead of on_request when a
578 # request's HEADERS block exceeds max_header_list_size -- no request state
579 # was ever dispatched (HTTP2.pm never called on_request for this stream),
580 # so there is nothing in {h2_streams} to initialize or clean up here.
581 # Mirrors the plain-CONNECT-501 and content-length-413 idiom below: defer
582 # the response to avoid re-entrant nghttp2 calls (we're inside feed/mem_recv).
583 sub _h2_on_header_overflow {
584 2 ▶ my ($self, $stream_id) = @_;
Subroutine _h2_on_header_overflow: called CC=1 SCAR=0.1
585  
586 2 weaken(my $ws = $self);
587 $self->{server}->loop->later(sub {
588 2 ▶ return unless $ws;
Subroutine __ANON__: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
unless $ws 0 2 2
589 2 ▶ return if $ws->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"closed"} 0 2 2
590 $ws->{h2_session}->submit_response($stream_id,
591 status => 431,
592 headers => [
593 ['content-type', 'text/plain'],
594 2 ['date', $ws->{protocol}->format_date],
595 ],
596 body => "Request Header Fields Too Large\n",
597 );
598 2 $ws->_h2_write_pending;
599 2 });
600 }
601  
602 sub _h2_on_request {
603 210 ▶ my ($self, $stream_id, $pseudo, $headers, $has_body) = @_;
Subroutine _h2_on_request: called CC=12 SCAR=25.5
604  
605 # Defensive second layer (belt under the protocol layer's own
606 # suspenders, PAGI::Server::Protocol::HTTP2's HEADERS-block
607 # classification): a live in-flight stream must never be overwritten
608 # by a duplicate dispatch. This should be unreachable now that the
609 # protocol layer classifies received HEADERS blocks by category and
610 # only calls on_request for NGHTTP2_HCAT_REQUEST -- it exists so a
611 # future protocol-layer regression can't silently destroy an
612 # in-flight request's accumulated state (body, receive_queue,
613 # connection_state, seq_state).
614 210 ▶ if ($self->{h2_streams}{$stream_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_streams"}{$stream_id}) 0 210 210
615 0 warn "PAGI::Server::Connection: ignoring duplicate HTTP/2 request dispatch for stream $stream_id (existing in-flight request would have been destroyed)\n";
616 0 return;
617 }
618  
619 # Detect CONNECT method
620 210 my $is_websocket = 0;
621 210 ▶ if (($pseudo->{':method'} // '') eq 'CONNECT') {
Branch: 1 branch
BranchTrueFalseTotal
if (($pseudo->{":method"} // "") eq "CONNECT") 52 158 210
Condition50%1/2
$pseudo->{":method"} // ""
l!l
2100
MC/DC0%0/1
$pseudo->{":method"} // ""
$pseudo->{":method"}
Truth table50%1/2
A
A= $pseudo->{":method"}
Aresult
11
00
622 52 ▶ if (($pseudo->{':protocol'} // '') eq 'websocket') {
Branch: 1 branch
BranchTrueFalseTotal
if (($pseudo->{':protocol'} // '') eq 'websocket') { } 51 1 52
Condition100%2/2
$pseudo->{":protocol"} // ""
l!l
511
MC/DC100%1/1
$pseudo->{":protocol"} // ""
$pseudo->{":protocol"}
Truth table100%2/2
A
A= $pseudo->{":protocol"}
Aresult
11
00
623 # Extended CONNECT for WebSocket (RFC 8441)
624 51 $is_websocket = 1;
625 } else {
626 # Plain CONNECT not supported — defer response to avoid
627 # re-entrant nghttp2 calls (we're inside feed/mem_recv)
628 1 weaken(my $ws = $self);
629 $self->{server}->loop->later(sub {
630 1 ▶ return unless $ws;
Subroutine __ANON__: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
unless $ws 0 1 1
631 1 ▶ return if $ws->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"closed"} 0 1 1
632 $ws->{h2_session}->submit_response($stream_id,
633 status => 501,
634 headers => [
635 ['content-type', 'text/plain'],
636 1 ['date', $ws->{protocol}->format_date],
637 ],
638 body => "CONNECT method not supported\n",
639 );
640 1 $ws->_h2_write_pending;
641 1 });
642 1 return;
643 }
644 }
645  
646 # Detect SSE (Accept: text/event-stream)
647 209 my $is_sse = 0;
648 209 ▶ if (!$is_websocket) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_websocket) 158 51 209
649 158 $is_sse = _accept_signals_sse($headers);
650 }
651  
652 # Initialize per-stream state
653 209 $self->{h2_streams}{$stream_id} = {
654 pseudo => $pseudo,
655 headers => $headers,
656 has_body => $has_body,
657 body => '',
658 body_complete => !$has_body,
659 body_pending => undef, # Future for body availability
660 receive_queue => [],
661 response_started => 0,
662 seq_state => 'initial',
663 is_websocket => $is_websocket,
664 is_sse => $is_sse,
665 ws_accepted => 0,
666 ws_frame => undef, # Protocol::WebSocket::Frame for parsing
667 ws_connect_sent => 0,
668 ws_disconnect_delivered => 0, # True once the scope's single websocket.disconnect has been queued
669 };
670  
671 # Check Content-Length against max_body_size limit before dispatching
672 # (after stream init so _h2_on_body/_h2_on_close can find the stream)
673 209 ▶ if ($self->{max_body_size} && $has_body) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_body_size"} and $has_body) 37 172 209
Condition100%3/3
$self->{"max_body_size"} and $has_body
!ll&&!rl&&r
1403237
MC/DC100%2/2
$self->{"max_body_size"} and $has_body
$self->{"max_body_size"} $has_body
Truth table100%3/3
A and B
A= $self->{"max_body_size"}B= $has_body
ABresult
0X0
100
111
674 37 for my $h (@$headers) {
675 73 ▶ if ($h->[0] eq 'content-length') {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->[0] eq "content-length") 2 71 73
676 2 ▶ if ($h->[1] > $self->{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->[1] > $self->{"max_body_size"}) 2 0 2
677 # Defer response to avoid re-entrant nghttp2 calls
678 2 weaken(my $ws = $self);
679 $self->{server}->loop->later(sub {
680 2 ▶ return unless $ws;
Subroutine __ANON__: called CC=3 SCAR=11.4
Branch: 1 branch
BranchTrueFalseTotal
unless $ws 0 2 2
681 2 ▶ return if $ws->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"closed"} 0 2 2
682 $ws->{h2_session}->submit_response($stream_id,
683 status => 413,
684 headers => [
685 ['content-type', 'text/plain'],
686 2 ['date', $ws->{protocol}->format_date],
687 ],
688 body => "Payload Too Large\n",
689 );
690 2 $ws->_h2_write_pending;
691 2 });
692 2 return;
693 }
694 0 last;
695 }
696 }
697 }
698  
699 # Defer dispatch to next event loop tick to prevent re-entrant nghttp2 calls
700 207 weaken(my $weak_self = $self);
701 $self->{server}->loop->later(sub {
702 207 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=3 SCAR=11.7
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 207 207
703 207 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 207 207
704 207 $weak_self->_h2_dispatch_stream($stream_id);
705 207 });
706 }
707  
708 sub _h2_on_body {
709 85 ▶ my ($self, $stream_id, $data, $eof) = @_;
Subroutine _h2_on_body: called CC=15 SCAR=27.1
710  
711 85 my $stream = $self->{h2_streams}{$stream_id};
712 85 ▶ return unless $stream;
Branch: 1 branch
BranchTrueFalseTotal
unless $stream 4 81 85
713  
714 81 ▶ if ($stream->{is_websocket} && $stream->{ws_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_websocket"} and $stream->{"ws_accepted"}) 58 23 81
Condition100%3/3
$stream->{"is_websocket"} and $stream->{"ws_accepted"}
!ll&&!rl&&r
22158
MC/DC100%2/2
$stream->{"is_websocket"} and $stream->{"ws_accepted"}
$stream->{"is_websocket"} $stream->{"ws_accepted"}
Truth table100%3/3
A and B
A= $stream->{"is_websocket"}B= $stream->{"ws_accepted"}
ABresult
0X0
100
111
715 # WebSocket: DATA frames contain raw WebSocket frames
716 58 ▶ $self->_h2_process_ws_frames($stream_id, $stream, $data) if length($data);
Branch: 1 branch
BranchTrueFalseTotal
if length $data 55 3 58
717  
718 58 ▶ if ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 3 55 58
719 # END_STREAM with no close handshake (bare END_STREAM): abnormal
720 # closure per RFC 6455 (Www.pod "Disconnect - receive event").
721 3 $self->_h2_ws_enqueue_disconnect($stream, 1006, 'client_closed');
722 }
723 58 return;
724 }
725  
726 23 ▶ if (length($data) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data > 0) 17 6 23
727 17 $stream->{body} .= $data;
728  
729 # Enforce max_body_size (0 = unlimited)
730 17 ▶ if ($self->{max_body_size} && length($stream->{body}) > $self->{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_body_size"} and length $stream->{"body"} > $self->{"max_body_size"}) 7 10 17
Condition100%3/3
$self->{"max_body_size"} and length $stream->{"body"} > $self->{"max_body_size"}
!ll&&!rl&&r
917
MC/DC100%2/2
$self->{"max_body_size"} and length $stream->{"body"} > $self->{"max_body_size"}
$self->{"max_body_size"} length $stream->{"body"} > $self->{"max_body_size"}
Truth table100%3/3
A and B
A= $self->{"max_body_size"}B= length $stream->{"body"} > $self->{"max_body_size"}
ABresult
0X0
100
111
731 $self->{h2_session}->submit_response($stream_id,
732 status => 413,
733 headers => [
734 ['content-type', 'text/plain'],
735 7 ['date', $self->{protocol}->format_date],
736 ],
737 body => 'Payload Too Large',
738 );
739 # No _h2_write_pending here — we're inside feed(); _h2_process_data
740 # flushes after feed() returns
741 7 $self->_h2_resolve_stream_drain_waiters($stream);
742 7 $self->_h2_resolve_stream_trailer_wait($stream);
743 # Drop (don't fire) the app's on_drain fires: the stream is closing,
744 # not draining, and the transport handle is going away. Also break
745 # the $stream <-> transport_state cycle (the handle's measure/arm
746 # closures hold $stream strongly), or the stream state leaks for the
747 # life of the process once h2_streams drops its external ref.
748 7 $stream->{transport_drain_fires} = [];
749 7 delete $stream->{transport_state};
750 # This stream is going away here too -- stop its keepalive (and,
751 # for SSE, idle) timers before dropping the hash entry, the same
752 # as _h2_on_close does. Those timers are add_child'ed to the
753 # SERVER, not to this stream state, so without this the deleted
754 # entry below leaves them running for the life of the process:
755 # _h2_on_close never runs for this path (no h2-level stream close
756 # event fires here), and the connection's own close-time sweep
757 # only iterates h2_streams, which no longer lists this stream.
758 7 ▶ $self->_h2_stop_ws_keepalive($stream) if $stream->{is_websocket};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"is_websocket"} 1 6 7
759 7 ▶ if ($stream->{is_sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_sse"}) 2 5 7
760 2 $self->_h2_stop_sse_keepalive($stream);
761 2 $self->_h2_stop_sse_idle_timer($stream);
762 }
763  
764 # Unblock a pending receive() instead of leaving it hanging
765 # forever: mark the body complete, queue this scope's disconnect
766 # event, drive connection_state (http scopes only -- sse/ws
767 # scopes never attach one, per spec), then wake body_pending.
768 # Order matters: the queued event must land BEFORE the wake so a
769 # parked receive() sees it (both h2 receive closures check the
770 # queue first on resume), and all of this must happen BEFORE the
771 # delete below, after which the stream state is unreachable.
772 7 $stream->{body_complete} = 1;
773 7 ▶ if ($stream->{is_sse}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($stream->{'is_sse'}) { } 2 5 7
elsif ($stream->{'is_websocket'}) { } 1 4 5
774 2 push @{$stream->{receive_queue}}, {
775 type => 'sse.disconnect',
776 reason => 'body_too_large',
777 };
778 } elsif ($stream->{is_websocket}) {
779 # An accepted ws stream returns early at the top of this sub
780 # (the ws_accepted guard above), so is_websocket true here
781 # always means pre-accept. Deliver the scope's single
782 # websocket.disconnect (Www.pod "Disconnect - receive
783 # event": server-detected abnormal close is code 1006 plus
784 # the matching Standard Disconnect Reasons token, and
785 # body_too_large is one). Pushed directly rather than
786 # through _h2_ws_enqueue_disconnect: that helper also calls
787 # _h2_wake_pending, but the wake here must wait until
788 # h2_closed is set below (same ordering the sse/http arms
789 # rely on -- see the comment above h2_closed). Still honor
790 # the single-delivery contract so a later delivery attempt
791 # for this (about-to-be-deleted) stream is a no-op.
792 1 $stream->{ws_disconnect_delivered}++;
793 1 push @{$stream->{receive_queue}}, {
794 type => 'websocket.disconnect',
795 code => 1006,
796 reason => 'body_too_large',
797 };
798 } else {
799 4 push @{$stream->{receive_queue}}, { type => 'http.disconnect' };
800 }
801 $stream->{connection_state}->_mark_disconnected('body_too_large')
802 7 ▶ if $stream->{connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"connection_state"} 2 5 7
803 # Mark death BEFORE the wake, mirroring _h2_on_close's own
804 # h2_closed marker (see its comment): the wake below can resume
805 # the app's async sub synchronously, and a resumed app may call
806 # $send before this function reaches its own delete further
807 # down -- $ss would still be a live h2_streams entry at that
808 # point (STREAM_GONE / already-closed carve-outs key off entry
809 # existence). h2_closed lets every send closure recognize a
810 # doomed-but-still-present entry and no-op on it, same as an
811 # absent one, per the post-close contract (design §6.2 / §21
812 # item 1).
813 7 $stream->{h2_closed} = 1;
814 7 $self->_h2_wake_pending($stream);
815  
816 7 delete $self->{h2_streams}{$stream_id};
817 7 return;
818 }
819 }
820  
821 16 ▶ if ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 6 10 16
822 6 $stream->{body_complete} = 1;
823 }
824  
825 16 $self->_h2_wake_pending($stream);
826 }
827  
828 sub _h2_wake_pending {
829 217 ▶ my ($self, $stream) = @_;
Subroutine _h2_wake_pending: called CC=3 SCAR=11.0
830 217 ▶ if ($stream->{body_pending} && !$stream->{body_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready) 71 146 217
Condition66%2/3
$stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready
!ll&&!rl&&r
146071
MC/DC50%1/2
$stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready
$stream->{"body_pending"} not $stream->{"body_pending"}->is_ready
Truth table66%2/3
A and not(B)
A= $stream->{"body_pending"}B= not $stream->{"body_pending"}->is_ready
ABresult
0X0
100
111
831 71 my $f = $stream->{body_pending};
832 71 $stream->{body_pending} = undef;
833 71 $f->done;
834 }
835 }
836  
837 # Enqueue the scope's single websocket.disconnect event (PAGI: exactly one
838 # per WebSocket scope). Every h2 delivery site MUST come through here.
839 sub _h2_ws_enqueue_disconnect {
840 31 ▶ my ($self, $stream, $code, $reason) = @_;
Subroutine _h2_ws_enqueue_disconnect: called CC=2 SCAR=6.9
841 31 ▶ return if $stream->{ws_disconnect_delivered}++;
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"ws_disconnect_delivered"}++ 12 19 31
842 19 push @{$stream->{receive_queue}}, {
843 type => 'websocket.disconnect',
844 code => $code,
845 reason => $reason,
846 };
847 19 $self->_h2_wake_pending($stream);
848 }
849  
850 sub _h2_on_close {
851 141 ▶ my ($self, $stream_id, $error_code) = @_;
Subroutine _h2_on_close: called CC=14 SCAR=26.4
852  
853 141 my $stream = $self->{h2_streams}{$stream_id};
854 141 ▶ return unless $stream;
Branch: 1 branch
BranchTrueFalseTotal
unless $stream 6 135 141
855  
856 # Record death at the earliest possible moment -- before any of the
857 # deferred work below (including this function's own loop->later
858 # delete of the h2_streams entry further down). nghttp2 has already
859 # forgotten this stream by the time this callback fires, but the
860 # entry stays in h2_streams for one more tick so pending futures can
861 # resolve. The dispatch wrapper's liveness check may run nested
862 # inside this very call (a woken receive() future can resume an
863 # app's async sub synchronously), so it needs a fact that flips true
864 # HERE, not one that only becomes true once the deferred delete runs.
865 135 $stream->{h2_closed} = 1;
866  
867 # This stream is going away one way or another -- stop its keepalive
868 # (and, for SSE, idle) timers so they don't fire (or leak) after the
869 # stream state is reclaimed.
870 135 ▶ $self->_h2_stop_ws_keepalive($stream) if $stream->{is_websocket};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"is_websocket"} 8 127 135
871 135 ▶ if ($stream->{is_sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_sse"}) 20 115 135
872 20 $self->_h2_stop_sse_keepalive($stream);
873 20 $self->_h2_stop_sse_idle_timer($stream);
874 }
875  
876 # Drive this stream's own connection_state to its terminal state exactly
877 # once. Three outcomes, and the h2 error code alone does not separate
878 # them -- a server-sent END_STREAM closes a stream with error code 0 just
879 # as a client's clean close does:
880 #
881 # 1. seq_state 'complete' and no error code -- the whole response went
882 # out and the stream ended cleanly: a completion, not a disconnect.
883 # 2. no error code but the response never reached 'complete' -- the
884 # stream ended early with no h2-level error, which on this side only
885 # the server can cause. (A declared-but-unsent-trailers response, or
886 # any other response left started-but-incomplete, does NOT land
887 # here today: the dispatch wrapper resets it with RST_STREAM
888 # INTERNAL_ERROR -- a NONZERO code -- so that case falls into
889 # outcome 3 below. This branch is kept for any other server-caused
890 # clean end that leaves seq_state short of 'complete'.) An early
891 # end to an unfinished response is an incomplete response per the
892 # PAGI spec, and the fault is the server's: the client did nothing
893 # and must not be blamed with 'client_closed'.
894 # 3. a nonzero error code -- the peer reset the stream (CANCEL,
895 # INTERNAL_ERROR, ...): the client went away.
896 #
897 # Both marks are idempotent, so a stream the dispatch wrapper already
898 # marked (e.g. server_error before its own RST) keeps that first reason.
899 #
900 # server_close_reason: a server-initiated per-stream teardown (idle
901 # timeout, keepalive timeout, ...) records its own token here BEFORE
902 # driving the close, so it takes precedence over the generic
903 # 'client_closed' fallback below in the queued disconnect events pushed
904 # further down -- that part is operative today, since WebSocket
905 # keepalive timeout and SSE idle timeout are exactly the writers of this
906 # token and both stream types push a queued disconnect. The
907 # nonzero-error-code $cs mark below also consults $reason, but that arm
908 # is a forward guard, not yet operative: WebSocket/SSE streams (this
909 # token's only current writers) never attach a connection_state, so no
910 # $cs-bearing stream sets server_close_reason today -- this exists for
911 # when a server-initiated per-stream teardown reaches a stream that does
912 # carry one. The zero-error-code arms above are untouched either way:
913 # they distinguish a clean completion from an incomplete response, not
914 # a server-initiated abnormal close, so they never consult this token.
915 135 my $reason = $stream->{server_close_reason};
916 135 ▶ if (my $cs = $stream->{connection_state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cs = $stream->{"connection_state"}) 107 28 135
917 107 ▶ if (($stream->{seq_state} // '') eq 'complete' && !$error_code) {
Branch: 2 branches
BranchTrueFalseTotal
if (($stream->{'seq_state'} // '') eq 'complete' and not $error_code) { } 87 20 107
elsif (not $error_code) { } 4 16 20
Condition80%4/5
($stream->{"seq_state"} // "") eq "complete" and not $error_code
!ll&&!rl&&r
18287
$stream->{"seq_state"} // ""
l!l
1070
MC/DC50%1/2
($stream->{"seq_state"} // "") eq "complete" and not $error_code
$stream->{"seq_state"} not $error_code
Truth table66%2/3
A and not(B)
A= $stream->{"seq_state"}B= not $error_code
ABresult
0X0
100
111
918 87 $cs->_mark_complete;
919 } elsif (!$error_code) {
920 4 $cs->_mark_disconnected('server_error');
921 } else {
922 16 ▶ $cs->_mark_disconnected($reason // 'client_closed');
Condition50%1/2
$reason // "client_closed"
l!l
016
MC/DC0%0/1
$reason // "client_closed"
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
923 }
924 }
925  
926 # Mark body complete to unblock any pending receive
927 135 $stream->{body_complete} = 1;
928  
929 # Enqueue disconnect event
930 135 ▶ if ($stream->{is_websocket}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($stream->{'is_websocket'}) { } 8 127 135
elsif ($stream->{'is_sse'}) { } 20 107 127
931 # Close without a WebSocket close handshake (RST_STREAM, timeout, ...):
932 # abnormal closure per RFC 6455. Deduped -- a no-op if the close-frame
933 # or bare-END_STREAM path already delivered the scope's one disconnect.
934 8 ▶ $self->_h2_ws_enqueue_disconnect($stream, 1006, $reason // 'client_closed');
Condition100%2/2
$reason // "client_closed"
l!l
26
MC/DC100%1/1
$reason // "client_closed"
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
935 } elsif ($stream->{is_sse}) {
936 20 ▶ push @{$stream->{receive_queue}}, {
Condition100%2/2
$reason // "client_closed"
l!l
218
MC/DC100%1/1
$reason // "client_closed"
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
937 type => 'sse.disconnect',
938 reason => $reason // 'client_closed',
939 };
940 } else {
941 107 push @{$stream->{receive_queue}}, { type => 'http.disconnect' };
942 }
943  
944 135 $self->_h2_wake_pending($stream);
945  
946 # Release any producer blocked on this stream's backpressure drain — the
947 # stream is closing, so it must not hang waiting for a queue that will
948 # never drain.
949 135 $self->_h2_resolve_stream_drain_waiters($stream);
950 # Same for a send() parked awaiting the data callback's own terminal
951 # invocation to submit its staged trailers (h2_closed carve-out: a
952 # trailers send racing a disconnect resolves as a successful no-op,
953 # same as every other post-close send).
954 135 $self->_h2_resolve_stream_trailer_wait($stream);
955 # Drop (don't fire) the app's on_drain fires: this is a close, not a drain.
956 # Also break the $stream <-> transport_state cycle so the stream state can be
957 # collected once the deferred delete below drops h2_streams' external ref.
958 135 $stream->{transport_drain_fires} = [];
959 135 delete $stream->{transport_state};
960  
961 # Clean up after a delay (let any pending futures resolve)
962 135 weaken(my $weak_self = $self);
963 $self->{server}->loop->later(sub {
964 135 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=2 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 1 134 135
965 134 delete $weak_self->{h2_streams}{$stream_id};
966 135 });
967 }
968  
969 # =============================================================================
970 # HTTP/2 Stream Dispatch (scope/receive/send creation)
971 # =============================================================================
972  
973 sub _h2_dispatch_stream {
974 207 ▶ my ($self, $stream_id) = @_;
Subroutine _h2_dispatch_stream: called CC=4 SCAR=13.9
975  
976 207 my $stream_state = $self->{h2_streams}{$stream_id};
977 207 ▶ return unless $stream_state;
Branch: 1 branch
BranchTrueFalseTotal
unless $stream_state 2 205 207
978  
979 205 my ($scope, $receive, $send);
980  
981 205 ▶ if ($stream_state->{is_websocket}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($stream_state->{'is_websocket'}) { } 51 154 205
elsif ($stream_state->{'is_sse'}) { } 42 112 154
982 51 $scope = $self->_h2_create_websocket_scope($stream_id, $stream_state);
983 51 $receive = $self->_h2_create_websocket_receive($stream_id, $stream_state);
984 51 $send = $self->_h2_create_websocket_send($stream_id, $stream_state);
985 } elsif ($stream_state->{is_sse}) {
986 42 $scope = $self->_h2_create_sse_scope($stream_id, $stream_state);
987 42 $receive = $self->_h2_create_sse_receive($stream_id, $stream_state);
988 42 $send = $self->_h2_create_sse_send($stream_id, $stream_state);
989 } else {
990 112 $scope = $self->_h2_create_scope($stream_id, $stream_state);
991 112 $receive = $self->_h2_create_receive($stream_id, $stream_state);
992 112 $send = $self->_h2_create_send($stream_id, $stream_state);
993 }
994  
995 205 weaken(my $weak_self = $self);
996  
997 205 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=20 SCAR=30.2
998 205 eval {
999 205 await $weak_self->{app}->($scope, $receive, $send);
1000 };
1001 202 my $error = $@;
1002  
1003 202 ▶ if ($weak_self) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self) 202 0 202
1004 202 my $cs = $stream_state->{connection_state};
1005  
1006 # Client-already-gone carve-out: if the client reset this stream
1007 # (or the whole connection tore down) while the app's Future was
1008 # still pending, _h2_on_close already ran and drove $cs to an
1009 # ABNORMAL terminal state. There is then nothing left to report:
1010 # no synthesized 500, no incomplete-response RST, no warning
1011 # about a stream the client no longer cares about.
1012 #
1013 # The test is "abnormal", not merely "terminal": a clean
1014 # _mark_complete also leaves $cs disconnected, and it happens
1015 # routinely BEFORE the app returns (the send closure flushes
1016 # END_STREAM synchronously, so _h2_on_close -> _mark_complete
1017 # normally runs inside the app's final await). Keying off
1018 # is_connected would swallow every exception thrown after a
1019 # fully-delivered response. An abnormal end has a
1020 # disconnect_reason; a clean completion leaves it undef.
1021 # Streams with no connection_state (WebSocket/SSE) fall back to
1022 # a liveness fact ($stream_alive below) that is true if and
1023 # only if nghttp2 still owns the stream.
1024 #
1025 # A recorded reason of 'server_error' is NOT a client-gone signal:
1026 # it means the SERVER caused the abnormal end (e.g. this very
1027 # dispatch wrapper's own incomplete-response branch below marks
1028 # server_error before resetting the stream with RST_STREAM
1029 # INTERNAL_ERROR for a response left started-but-unfinished,
1030 # including a trailers-declared response that never sent its
1031 # trailers). Per the PAGI spec's incomplete-response section, the
1032 # log carve-out exists only for "the client had already
1033 # disconnected" -- so server-caused ends must still warn.
1034 #
1035 # $stream_alive is entry-exists-AND-not-yet-closed, not merely
1036 # entry-exists: _h2_on_close marks $stream->{h2_closed} the
1037 # instant it runs, but its h2_streams delete is deferred one
1038 # tick (loop->later) so pending futures can resolve. Waking
1039 # this very Future is one of those pending resolutions -- a
1040 # receive() blocked on body_pending can be woken by
1041 # _h2_on_close and resume this app synchronously, landing here
1042 # before that deferred delete has run. Keying liveness off
1043 # entry-existence alone (as before) missed exactly that
1044 # window: nghttp2 had already forgotten the stream, but
1045 # h2_streams still had it, so the carve-out below saw a "live"
1046 # stream and went on to call submit_response/submit_rst_stream
1047 # on a stream id nghttp2 no longer tracks -- undefined
1048 # behavior at the C level, not something the surrounding eval
1049 # can catch.
1050 my $stream_alive = $weak_self->{h2_streams}{$stream_id}
1051 202 ▶ && !$weak_self->{h2_streams}{$stream_id}{h2_closed};
Condition100%3/3
$weak_self->{'h2_streams'}{$stream_id} && !$weak_self->{'h2_streams'}{$stream_id}{'h2_closed'}
!ll&&!rl&&r
611581
MC/DC100%2/2
$weak_self->{'h2_streams'}{$stream_id} && !$weak_self->{'h2_streams'}{$stream_id}{'h2_closed'}
$weak_self->{'h2_streams'}{$stream_id} !$weak_self->{'h2_streams'}{$stream_id}{'h2_closed'}
Truth table100%3/3
A && not(B)
A= $weak_self->{'h2_streams'}{$stream_id}B= !$weak_self->{'h2_streams'}{$stream_id}{'h2_closed'}
ABresult
0X0
100
111
1052 202 ▶ my $reason = $cs ? $cs->disconnect_reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
$cs ? : 109 93 202
1053 202 ▶ my $client_gone = $cs ? (defined($reason) && $reason ne 'server_error')
Branch: 1 branch
BranchTrueFalseTotal
$cs ? : 109 93 202
Condition66%2/3
defined $reason and $reason ne "server_error"
!ll&&!rl&&r
97012
MC/DC50%1/2
defined $reason and $reason ne "server_error"
defined $reason $reason ne "server_error"
Truth table66%2/3
A and B
A= defined $reasonB= $reason ne "server_error"
ABresult
0X0
100
111
1054 : !$stream_alive;
1055  
1056 202 ▶ if ($client_gone) {
Branch: 4 branches
BranchTrueFalseTotal
if ($client_gone) { } 39 163 202
elsif (not $stream_state->{'response_started'}) { } 7 156 163
elsif ($cs and ($stream_state->{'seq_state'} // 'complete') ne 'complete') { } 6 150 156
elsif ($error) { } 1 149 150
1057 # Nothing to do.
1058 }
1059 elsif (!$stream_state->{response_started}) {
1060 # If the application failed, OR returned without starting a
1061 # response, synthesize a 500 (only possible while no response
1062 # has begun). A clean return that produced no response is a
1063 # protocol error, same as a throw.
1064 7 ▶ warn $error
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 2 5 7
1065 ? "PAGI application error (HTTP/2 stream $stream_id): $error\n"
1066 : "PAGI application returned without starting a response (HTTP/2 stream $stream_id)\n";
1067 # Mark BEFORE the response settles: submitting it (below) can
1068 # complete the stream synchronously once flushed, and
1069 # _h2_on_close would then mark this same connection_state
1070 # terminal if it got there first. _mark_disconnected is
1071 # idempotent -- first mark wins -- so marking here first
1072 # guarantees the app observes server_error. The synthesized
1073 # 500 is this stream's response (spec section 9.1), so mark
1074 # it started FIRST: _mark_disconnected fires on_disconnect
1075 # callbacks synchronously, and they must observe
1076 # response_started true.
1077 7 ▶ $cs->_mark_response_started if $cs;
Branch: 1 branch
BranchTrueFalseTotal
if $cs 4 3 7
1078 7 ▶ $cs->_mark_disconnected('server_error') if $cs;
Branch: 1 branch
BranchTrueFalseTotal
if $cs 4 3 7
1079 7 eval {
1080 $weak_self->{h2_session}->submit_response($stream_id,
1081 status => 500,
1082 headers => [
1083 ['content-type', 'text/plain'],
1084 7 ['date', $weak_self->{protocol}->format_date],
1085 ],
1086 body => "Internal Server Error\n",
1087 );
1088 7 $weak_self->_h2_write_pending;
1089 };
1090 }
1091 ▶ elsif ($cs && (($stream_state->{seq_state} // 'complete') ne 'complete')) {
Condition80%4/5
$cs and ($stream_state->{"seq_state"} // "complete") ne "complete"
!ll&&!rl&&r
63876
$stream_state->{"seq_state"} // "complete"
l!l
930
MC/DC50%1/2
$cs and ($stream_state->{"seq_state"} // "complete") ne "complete"
$cs $stream_state->{"seq_state"}
Truth table66%2/3
A and B
A= $csB= $stream_state->{"seq_state"}
ABresult
0X0
100
111
1092 # Response started but never finished: the app either
1093 # returned cleanly without sending the terminal body/file/fh
1094 # (or trailers), or threw after starting. Either way the
1095 # stream is framed but unterminated -- there is no way to
1096 # synthesize END_STREAM without lying about the body, so
1097 # reset the stream instead. (Only plain HTTP streams reach
1098 # here: WebSocket/SSE never attach a connection_state, so
1099 # $cs guards them out -- their seq_state is never tracked
1100 # and would otherwise misread as permanently incomplete.)
1101 # Trailers-specific parenthetical mirrors the h1 wording (see
1102 # _handle_request's incomplete branch) -- appended after the
1103 # stream-id parenthetical so t/http2/24-incomplete-response.t's
1104 # "...incomplete response (HTTP/2 stream $stream_id)" pin
1105 # still matches as a contiguous substring.
1106 6 ▶ my $trailers_note = (($stream_state->{seq_state} // '') eq 'awaiting_trailers')
Branch: 1 branch
BranchTrueFalseTotal
($stream_state->{'seq_state'} // '') eq 'awaiting_trailers' ? : 4 2 6
Condition50%1/2
$stream_state->{"seq_state"} // ""
l!l
60
MC/DC0%0/1
$stream_state->{"seq_state"} // ""
$stream_state->{"seq_state"}
Truth table50%1/2
A
A= $stream_state->{"seq_state"}
Aresult
11
00
1107 ? ' (trailers were declared but never sent)' : '';
1108 6 ▶ warn $error
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 1 5 6
1109 ? "PAGI application error after response started (HTTP/2 stream $stream_id): $error\n"
1110 : "PAGI application returned with an incomplete response (HTTP/2 stream $stream_id)$trailers_note\n";
1111 # Mark BEFORE the RST. _h2_on_close fires for our own RST
1112 # too (as an abnormal close, since seq_state never reached
1113 # 'complete') and would mark this same connection_state
1114 # 'client_closed' if it got there first. _mark_disconnected
1115 # is idempotent -- first mark wins -- so marking here first
1116 # guarantees the app observes server_error.
1117 6 $cs->_mark_disconnected('server_error');
1118 6 eval {
1119 $weak_self->{h2_session}->submit_rst_stream(
1120 6 $stream_id, _h2_rst_error_code());
1121 6 $weak_self->_h2_write_pending;
1122 };
1123 }
1124 elsif ($error) {
1125 # Response already complete; cannot send a 500 or usefully
1126 # reset a finished stream. Log only.
1127 1 warn "PAGI application error after response started (HTTP/2 stream $stream_id): $error\n";
1128 }
1129 }
1130  
1131 # Notify server that request completed (for max_requests tracking)
1132 202 ▶ $weak_self->{server}->_on_request_complete if $weak_self && $weak_self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self and $weak_self->{"server"} 202 0 202
Condition33%1/3
$weak_self and $weak_self->{"server"}
!ll&&!rl&&r
00202
MC/DC0%0/2
$weak_self and $weak_self->{"server"}
$weak_self $weak_self->{"server"}
Truth table33%1/3
A and B
A= $weak_selfB= $weak_self->{"server"}
ABresult
0X0
100
111
1133 205 })->();
1134  
1135 205 $self->{server}->adopt_future($future);
1136 }
1137  
1138 # HTTP/2 error code for the RST_STREAM sent when a response is left started
1139 # but incomplete (see _h2_dispatch_stream above). NGHTTP2_INTERNAL_ERROR
1140 # (RFC 9113 section 7, code 0x2) is exported by Net::HTTP2::nghttp2.
1141 sub _h2_rst_error_code {
1142 6 ▶ return Net::HTTP2::nghttp2::NGHTTP2_INTERNAL_ERROR();
Subroutine _h2_rst_error_code: called CC=1 SCAR=0.0
1143 }
1144  
1145 # RST_STREAM error code for a stream the server no longer needs but that is
1146 # nobody's fault -- RFC 9113 section 7 CANCEL. NGHTTP2_CANCEL is exported by
1147 # Net::HTTP2::nghttp2.
1148 sub _h2_rst_cancel_code {
1149 2 ▶ return Net::HTTP2::nghttp2::NGHTTP2_CANCEL();
Subroutine _h2_rst_cancel_code: called CC=1 SCAR=0.0
1150 }
1151  
1152 sub _h2_create_scope {
1153 115 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_scope: called CC=8 SCAR=22.8
1154  
1155 115 my $pseudo = $stream_state->{pseudo};
1156 115 my $headers = $stream_state->{headers};
1157  
1158 # Parse path and query string from :path pseudo-header
1159 115 ▶ my $full_path = $pseudo->{':path'} // '/';
Condition50%1/2
$pseudo->{":path"} // "/"
l!l
1150
MC/DC0%0/1
$pseudo->{":path"} // "/"
$pseudo->{":path"}
Truth table50%1/2
A
A= $pseudo->{":path"}
Aresult
11
00
1160 115 my ($path, $query_string) = split(/\?/, $full_path, 2);
1161 115 ▶ $query_string //= '';
Condition100%2/2
$query_string //= ""
l!l
2113
MC/DC100%1/1
$query_string //= ""
$query_string
Truth table100%2/2
A
A= $query_string
Aresult
11
00
1162  
1163 # Decode percent-encoded path for scope (keep raw_path as-is)
1164 # Match HTTP/1.1 pipeline: URI::Escape + UTF-8 decode with fallback
1165 115 my $unescaped = uri_unescape($path);
1166 115 ▶ my $decoded_path = eval { decode('UTF-8', $unescaped, Encode::FB_CROAK) }
Condition33%1/3
eval { do { &decode("UTF-8", $unescaped, 1) } } // $unescaped
l!l&&r!l&&!r
11500
MC/DC0%0/2
eval { do { &decode("UTF-8", $unescaped, 1) } } // $unescaped
eval { do { &decode("UTF-8", $unescaped, 1) } } $unescaped
Truth table33%1/3
A // B
A= eval { do { &decode("UTF-8", $unescaped, 1) } }B= $unescaped
ABresult
1X1
011
000
1167 // $unescaped;
1168  
1169 115 my $connection_state = PAGI::Server::ConnectionState->new(
1170 connection => $self,
1171 );
1172 # Store on the stream-state so the send path can mark response_started on
1173 # this stream's own connection object (h2 multiplexes many streams).
1174 115 $stream_state->{connection_state} = $connection_state;
1175  
1176 return {
1177 type => 'http',
1178 pagi => {
1179 version => '0.5',
1180 spec_version => '0.5',
1181 },
1182 http_version => '2',
1183 method => $pseudo->{':method'} // 'GET',
1184 scheme => $pseudo->{':scheme'} // $self->_get_scheme,
1185 path => $decoded_path,
1186 raw_path => $path,
1187 query_string => $query_string,
1188 root_path => '',
1189 headers => $headers,
1190 (defined $self->{client_host}
1191 ? (client => [$self->{client_host}, $self->{client_port}])
1192 : ()
1193 ),
1194 server => [$self->{server_host}, $self->{server_port}],
1195 115 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
1196 extensions => $self->_get_extensions_for_scope,
1197 'pagi.connection' => $connection_state,
1198 # h2 transport handle measures THIS stream's send queue (per-stream),
1199 # stored on the stream state rather than $self->{current_transport_state}
1200 # because h2 multiplexes many concurrent streams over one connection.
1201 115 ▶ 'pagi.transport' => ($stream_state->{transport_state} = $self->_h2_transport_state($stream_state)),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 115 0 115
keys %{$$self{'state'};} ? : 0 115 115
Condition40%2/5
$pseudo->{":method"} // "GET"
l!l
1150
$pseudo->{":scheme"} // $self->_get_scheme
l!l&&r!l&&!r
11500
MC/DC0%0/1
$pseudo->{":method"} // "GET"
$pseudo->{":method"}
MC/DC0%0/2
$pseudo->{":scheme"} // $self->_get_scheme
$pseudo->{":scheme"} $self->_get_scheme
Truth table50%1/2
A
A= $pseudo->{":method"}
Aresult
11
00
Truth table33%1/3
A // B
A= $pseudo->{":scheme"}B= $self->_get_scheme
ABresult
1X1
011
000
1202 };
1203 }
1204  
1205 sub _h2_create_receive {
1206 112 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_receive: called CC=1 SCAR=0.4
1207  
1208 112 weaken(my $weak_self = $self);
1209  
1210 return sub {
1211 110 ▶ return Future->done({ type => 'http.disconnect' }) unless $weak_self;
Subroutine __ANON__: called CC=4 SCAR=15.6
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 110 110
1212 110 ▶ return Future->done({ type => 'http.disconnect' }) if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 110 110
1213  
1214 110 my $ss = $weak_self->{h2_streams}{$stream_id};
1215 110 ▶ return Future->done({ type => 'http.disconnect' }) unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 110 110
1216  
1217 110 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=12 SCAR=30.1
1218 110 ▶ return { type => 'http.disconnect' } unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 110 110
1219  
1220 110 my $ss = $weak_self->{h2_streams}{$stream_id};
1221 110 ▶ return { type => 'http.disconnect' } unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 110 110
1222  
1223 # Check queue first
1224 110 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 110 110
1225 0 return shift @{$ss->{receive_queue}};
1226 }
1227  
1228 # If body is already complete, return the final body event --
1229 # once. A receive called after the terminal event parks in the
1230 # wait loop below until the stream ends, matching h1's
1231 # post-request receive contract (stream close queues
1232 # http.disconnect and wakes body_pending). Same one-shot
1233 # discipline as the SSE closure's sse_request_sent.
1234 110 ▶ if ($ss->{body_complete} && !$ss->{final_request_delivered}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($ss->{"body_complete"} and not $ss->{"final_request_delivered"}) 103 7 110
Condition100%3/3
$ss->{"body_complete"} and not $ss->{"final_request_delivered"}
!ll&&!rl&&r
61103
MC/DC100%2/2
$ss->{"body_complete"} and not $ss->{"final_request_delivered"}
$ss->{"body_complete"} not $ss->{"final_request_delivered"}
Truth table100%3/3
A and not(B)
A= $ss->{"body_complete"}B= not $ss->{"final_request_delivered"}
ABresult
0X0
100
111
1235 103 $ss->{final_request_delivered} = 1;
1236 103 my $body = $ss->{body};
1237 103 $ss->{body} = '';
1238 return {
1239 103 type => 'http.request',
1240 body => $body,
1241 more => 0,
1242 };
1243 }
1244  
1245 7 while (1) {
1246 # Wait for body data (or, once the request has been fully
1247 # delivered, for the stream to end)
1248 7 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 7 0 7
1249 7 $ss->{body_pending} = Future->new;
1250 }
1251 7 await $ss->{body_pending};
1252  
1253 # Re-fetch stream state (may have changed)
1254 7 $ss = $weak_self->{h2_streams}{$stream_id};
1255 7 ▶ return { type => 'http.disconnect' } unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 7 7
1256  
1257 # Check queue after waking -- a queued event wins over the
1258 # body fallthrough (a close can set body_complete AND queue
1259 # http.disconnect on the same wake)
1260 7 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 7 0 7
1261 7 return shift @{$ss->{receive_queue}};
1262 }
1263  
1264 # Terminal event already delivered: this wake brought
1265 # nothing for the application -- park again rather than
1266 # re-synthesize the final body event.
1267 0 ▶ next if $ss->{final_request_delivered};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"final_request_delivered"} 0 0 0
1268  
1269 0 ▶ my $more = $ss->{body_complete} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$ss->{'body_complete'} ? : 0 0 0
1270 0 ▶ $ss->{final_request_delivered} = 1 unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 0 0 0
1271 0 my $body = $ss->{body};
1272 0 $ss->{body} = '';
1273 return {
1274 0 type => 'http.request',
1275 body => $body,
1276 more => $more,
1277 };
1278 }
1279 110 })->();
1280  
1281 110 return $future;
1282 112 };
1283 }
1284  
1285 sub _h2_create_send {
1286 112 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_send: called CC=2 SCAR=7.0
1287  
1288 112 weaken(my $weak_self = $self);
1289  
1290 112 my $status;
1291 my @response_headers;
1292  
1293 # Streaming state for deferred data provider pattern.
1294 # The send queue lives on per-stream state ($ss->{send_queue} /
1295 # $ss->{send_queue_bytes}) so the h2 transport handle can measure it;
1296 # $eof_pending / $streaming_started stay closure-local.
1297 112 my $eof_pending = 0;
1298 112 my $streaming_started = 0;
1299 # Mirrors the stream state's own starting point (see the seq_state =>
1300 # 'initial' initializer in _h2_on_request); the two must stay in step.
1301 112 my $seq = 'initial';
1302 112 ▶ my $is_head = (($stream_state->{pseudo}{':method'} // '') eq 'HEAD');
Condition50%1/2
$stream_state->{"pseudo"}{":method"} // ""
l!l
1120
MC/DC0%0/1
$stream_state->{"pseudo"}{":method"} // ""
$stream_state->{"pseudo"}{":method"}
Truth table50%1/2
A
A= $stream_state->{"pseudo"}{":method"}
Aresult
11
00
1303 # Set once, from http.response.start's own 'trailers' flag (section 6
1304 # below), and never changed again. $data_callback's no_end computation
1305 # MUST key off this rather than $ss->{seq_state}: the trailers arm
1306 # advances that mirror to 'complete' as soon as the app's send() call
1307 # is made, which can be BEFORE the data provider has actually drained
1308 # (deferred submit, see below) -- keying off seq_state there raced the
1309 # mirror update and let END_STREAM land back on the DATA frame.
1310 112 my $trailers_declared = 0;
1311  
1312 # Trailers-vs-data-provider handshake (design §8.3). Confirmed
1313 # empirically: calling submit_trailer() BEFORE the data provider has
1314 # actually handed nghttp2 its terminal (eof=1) chunk silently abandons
1315 # any DATA nghttp2 has not yet pulled through $data_callback (observed
1316 # under real per-stream flow control -- the still-queued tail of a
1317 # file/fh body never reached the wire, yet the stream closed "cleanly"
1318 # with the trailer -- a DEFERRED data-provider item is detached from
1319 # nghttp2's own outbound queue, so an early trailing HEADERS orphans
1320 # it). The Net::HTTP2::nghttp2 binding's own POD says submit_trailer()
1321 # "can be called inside" the data-provider callback OR after it
1322 # returns -- it does not say "at any later, unrelated time" -- so the
1323 # invariant this handshake actually enforces is narrower and stricter:
1324 # never BEFORE the provider has delivered its terminal EOF. The
1325 # trailers arm below submits directly ONLY once $data_eof_delivered is
1326 # already true (no further callback invocation will occur for this
1327 # stream); otherwise it stages the headers here and PARKS the send()
1328 # until the callback's own terminal invocation submits them.
1329 #
1330 # Contract note (flag for Task 6 / Compliance.pod): this means a
1331 # trailers send() can now block for as long as the peer withholds
1332 # flow-control window on a still-draining body -- new, unbounded-in-
1333 # the-app's-view blocking that a pre-Task-4 (stub) reading of the spec
1334 # would not have anticipated. This is arguably MORE correct, not a
1335 # regression: trailers now participate in the same backpressure body
1336 # sends already do, rather than racing ahead of undelivered DATA.
1337 112 my $data_eof_delivered = 0;
1338 112 my $pending_trailer_headers;
1339  
1340 # Called by $data_callback at the exact point it hands nghttp2 the
1341 # terminal (eof=1) chunk. If a trailers send() is waiting on this
1342 # (staged $pending_trailer_headers), submits it HERE -- synchronously,
1343 # from inside the data-provider callback, per nghttp2's own sanctioned
1344 # pattern -- then wakes the waiting send() on the next loop tick (never
1345 # resolve an app Future from inside a native nghttp2 callback -- same
1346 # discipline as the drain waiters above).
1347 my $deliver_trailer_eof = sub {
1348 34 ▶ $data_eof_delivered = 1;
Subroutine __ANON__: called CC=7 SCAR=20.5
1349 34 ▶ return unless defined $pending_trailer_headers;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pending_trailer_headers 32 2 34
1350 2 my $headers = $pending_trailer_headers;
1351 2 $pending_trailer_headers = undef;
1352 2 ▶ my $ss2 = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
002
MC/DC0%0/2
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
$weak_self $weak_self->{'h2_streams'}{$stream_id}
Truth table33%1/3
A && B
A= $weak_selfB= $weak_self->{'h2_streams'}{$stream_id}
ABresult
0X0
100
111
1353 # Dead-stream invariant, kept local here rather than inferred from
1354 # the doomed-but-still-present carve-out pattern used across this
1355 # file (h2_closed set, entry not yet reclaimed): don't reach
1356 # nghttp2 a second time on a stream id it may already be tearing
1357 # down. Two close paths, two mechanisms, same outcome -- there's
1358 # nothing left to do here either way: _h2_on_close and the 413
1359 # early-close branch set h2_closed on the still-present entry
1360 # (caught by the check below), while a whole-connection _close
1361 # deletes the h2_streams entry outright (so $ss2 comes back undef
1362 # here) and releases trailer_wait itself via its own sweep. Either
1363 # way, whichever close path is running has already released -- or
1364 # is about to release -- trailer_wait.
1365 2 ▶ return if $ss2 && $ss2->{h2_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ss2 and $ss2->{"h2_closed"} 0 2 2
Condition33%1/3
$ss2 and $ss2->{"h2_closed"}
!ll&&!rl&&r
020
MC/DC0%0/2
$ss2 and $ss2->{"h2_closed"}
$ss2 $ss2->{"h2_closed"}
Truth table33%1/3
A and B
A= $ss2B= $ss2->{"h2_closed"}
ABresult
0X0
100
111
1366 2 my $ok = eval {
1367 2 $weak_self->{h2_session}->submit_trailer($stream_id, headers => $headers);
1368 1 1;
1369 };
1370 2 my $err = $@;
1371 2 ▶ my $f = $ss2 && delete $ss2->{trailer_wait};
Condition33%1/3
$ss2 && delete $ss2->{'trailer_wait'}
!ll&&!rl&&r
002
MC/DC0%0/2
$ss2 && delete $ss2->{'trailer_wait'}
$ss2 delete $ss2->{'trailer_wait'}
Truth table33%1/3
A && B
A= $ss2B= delete $ss2->{'trailer_wait'}
ABresult
0X0
100
111
1372 2 ▶ return unless $f;
Branch: 1 branch
BranchTrueFalseTotal
unless $f 0 2 2
1373 $weak_self->{server}->loop->later(sub {
1374 2 ▶ return if $f->is_ready;
Subroutine __ANON__: called CC=3 SCAR=11.0
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_ready 0 2 2
1375 2 ▶ if ($ok) { $f->done(1) } else { $f->fail($err) }
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 1 1 2
1376 2 });
1377 112 };
1378  
1379 # Data callback for nghttp2's streaming response.
1380 # Returns ($data, $eof) when data is available, or undef to defer.
1381 my $data_callback = sub {
1382 320 ▶ my ($cb_stream_id, $max_len) = @_;
Subroutine __ANON__: called CC=20 SCAR=30.1
1383  
1384 320 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
00320
MC/DC0%0/2
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
$weak_self $weak_self->{'h2_streams'}{$stream_id}
Truth table33%1/3
A && B
A= $weak_selfB= $weak_self->{'h2_streams'}{$stream_id}
ABresult
0X0
100
111
1385 320 ▶ return undef unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 320 320
1386 320 ▶ my $q = $ss->{send_queue} ||= [];
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
3200
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
1387  
1388 320 ▶ if (@$q) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$q) 239 81 320
1389 239 my $chunk = shift @$q;
1390 # Respect max_len — XS truncates without preserving remainder
1391 239 ▶ if (length($chunk) > $max_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk > $max_len) 108 131 239
1392 108 unshift @$q, substr($chunk, $max_len);
1393 108 $chunk = substr($chunk, 0, $max_len);
1394 }
1395 239 $ss->{send_queue_bytes} -= length($chunk);
1396  
1397 # Per-stream backpressure: once this stream's queue falls below the
1398 # low watermark, release any producer blocked in
1399 # _h2_wait_for_stream_drain. This callback runs inside nghttp2's
1400 # extract(), so resolve on the next loop tick — completing the Future
1401 # resumes the awaiting producer synchronously, and it must not call
1402 # resume_stream/_h2_write_pending re-entrantly into nghttp2.
1403 239 ▶ if (($ss->{send_queue_bytes} // 0) < $weak_self->{write_low_watermark}
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}) 10 229 239
Condition87%7/8
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}
!ll&&!rl&&r
2181110
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
1229621
$ss->{"send_queue_bytes"} // 0
l!l
2390
MC/DC66%2/3
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}
$ss->{"send_queue_bytes"} $ss->{"stream_drain_waiters"} @{$ss->{"stream_drain_waiters"};}
Truth table75%3/4
A and B and C
A= $ss->{"send_queue_bytes"}B= $ss->{"stream_drain_waiters"}C= @{$ss->{"stream_drain_waiters"};}
ABCresult
0XX0
10X0
1100
1111
1404 21 && $ss->{stream_drain_waiters} && @{$ss->{stream_drain_waiters}}) {
1405 10 my @waiters = splice @{$ss->{stream_drain_waiters}};
1406 $weak_self->{server}->loop->later(sub {
1407 10 ▶ $_->done for grep { !$_->is_ready } @waiters;
Subroutine __ANON__: called CC=2 SCAR=6.9
1408 10 });
1409 }
1410  
1411 # Fire the app's on_drain hysteresis callbacks once this stream's
1412 # queue falls below the low watermark. Like the waiters above, this
1413 # runs inside nghttp2's extract(), and an on_drain callback may call
1414 # $send to resume its source — which would re-enter nghttp2. Splice
1415 # the fires out first (so they can't double-fire), then invoke them on
1416 # the next loop tick.
1417 239 ▶ if (($ss->{send_queue_bytes} // 0) < $weak_self->{write_low_watermark}
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}) 17 222 239
Condition87%7/8
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}
!ll&&!rl&&r
1932917
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"}
!ll&&!rl&&r
1227146
$ss->{"send_queue_bytes"} // 0
l!l
2390
MC/DC66%2/3
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}
$ss->{"send_queue_bytes"} $ss->{"transport_drain_fires"} @{$ss->{"transport_drain_fires"};}
Truth table75%3/4
A and B and C
A= $ss->{"send_queue_bytes"}B= $ss->{"transport_drain_fires"}C= @{$ss->{"transport_drain_fires"};}
ABCresult
0XX0
10X0
1100
1111
1418 46 && $ss->{transport_drain_fires} && @{$ss->{transport_drain_fires}}) {
1419 17 my @fires = splice @{$ss->{transport_drain_fires}};
1420 $weak_self->{server}->loop->later(sub {
1421 17 ▶ $_->() for @fires;
Subroutine __ANON__: called CC=2 SCAR=6.9
1422 17 });
1423 }
1424  
1425 239 ▶ my $eof = (!@$q && $eof_pending) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!@$q && $eof_pending ? : 24 215 239
Condition100%3/3
not @$q and $eof_pending
!ll&&!rl&&r
1625324
MC/DC100%2/2
not @$q and $eof_pending
not @$q $eof_pending
Truth table100%3/3
not(A) and B
A= not @$qB= $eof_pending
ABresult
0X0
100
111
1426 # Trailers declared: reserve END_STREAM for the trailing
1427 # HEADERS block (design §8.3) instead of letting it land on
1428 # this DATA frame. Has no effect unless $eof is also true
1429 # (Net::HTTP2::nghttp2's own contract), so it is safe to key
1430 # off $trailers_declared unconditionally here rather than the
1431 # $ss->{seq_state} mirror, which the trailers arm may have
1432 # already advanced past 'awaiting_trailers' by this point.
1433 239 ▶ my $no_end = $trailers_declared ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$trailers_declared ? : 49 190 239
1434 239 ▶ $deliver_trailer_eof->() if $eof;
Branch: 1 branch
BranchTrueFalseTotal
if $eof 24 215 239
1435 239 return ($chunk, $eof, $no_end);
1436 }
1437  
1438 # Queue empty but EOF pending — signal end of stream
1439 81 ▶ if ($eof_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof_pending) 10 71 81
1440 10 ▶ my $no_end = $trailers_declared ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$trailers_declared ? : 2 8 10
1441 10 $deliver_trailer_eof->();
1442 10 return ('', 1, $no_end);
1443 }
1444  
1445 # Queue empty, more data expected — defer (NGHTTP2_ERR_DEFERRED in C layer)
1446 71 return undef;
1447 112 };
1448  
1449 # Shared file/fh chunk pump: pushes produced chunks into this stream's
1450 # send queue under the per-stream watermark, then marks EOF. The producer
1451 # is an async sub that receives an async "emit" callback and must await it
1452 # per chunk; emit dies with the sentinel below if the stream vanishes
1453 # (client reset) so the pump stops reading without treating it as an error.
1454 112 my $STREAM_GONE = "PAGI::h2 stream gone\n";
1455 39 ▶ my $emit_chunk = async sub {
Subroutine __ANON__: called CC=13 SCAR=27.5
1456 39 my ($chunk) = @_;
1457 39 ▶ my $ss = $weak_self ? $weak_self->{h2_streams}{$stream_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 39 0 39
1458 39 ▶ die $STREAM_GONE unless $ss && !$ss->{h2_closed} && !$weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and not $ss->{"h2_closed"} and not $weak_self->{"closed"} 0 39 39
Condition33%2/6
$ss and not $ss->{"h2_closed"} and not $weak_self->{"closed"}
!ll&&!rl&&r
0039
$ss and not $ss->{"h2_closed"}
!ll&&!rl&&r
0039
MC/DC0%0/3
$ss and not $ss->{"h2_closed"} and not $weak_self->{"closed"}
$ss not $ss->{"h2_closed"} not $weak_self->{"closed"}
Truth table25%1/4
A and not(B) and not(C)
A= $ssB= not $ss->{"h2_closed"}C= not $weak_self->{"closed"}
ABCresult
0XX0
10X0
1100
1111
1459 39 ▶ if (($ss->{send_queue_bytes} // 0) >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) >= $weak_self->{"write_high_watermark"}) 6 33 39
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
390
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
1460 6 await $weak_self->_h2_wait_for_stream_drain($stream_id);
1461 6 ▶ $ss = $weak_self ? $weak_self->{h2_streams}{$stream_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 6 0 6
1462 6 ▶ die $STREAM_GONE unless $ss && !$ss->{h2_closed} && !$weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and not $ss->{"h2_closed"} and not $weak_self->{"closed"} 1 5 6
Condition66%4/6
$ss and not $ss->{"h2_closed"} and not $weak_self->{"closed"}
!ll&&!rl&&r
105
$ss and not $ss->{"h2_closed"}
!ll&&!rl&&r
015
MC/DC33%1/3
$ss and not $ss->{"h2_closed"} and not $weak_self->{"closed"}
$ss not $ss->{"h2_closed"} not $weak_self->{"closed"}
Truth table50%2/4
A and not(B) and not(C)
A= $ssB= not $ss->{"h2_closed"}C= not $weak_self->{"closed"}
ABCresult
0XX0
10X0
1100
1111
1463 }
1464 38 ▶ if (length $chunk) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk) 37 1 38
1465 37 push @{$ss->{send_queue}}, $chunk;
1466 37 $ss->{send_queue_bytes} += length $chunk;
1467 }
1468 38 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 38 0 38
1469 38 $weak_self->{h2_session}->resume_stream($stream_id);
1470 38 $weak_self->_h2_write_pending;
1471 38 return;
1472 112 };
1473  
1474 # Shared tail for the file/fh arms below: mark EOF pending and resume the
1475 # stream once the read loop finishes without error. A no-op if the stream
1476 # vanished (client reset) while the last chunk was in flight.
1477 my $finish_body_stream = sub {
1478 13 ▶ $eof_pending = 1;
Subroutine __ANON__: called CC=3 SCAR=11.3
1479 13 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 13 13
1480 13 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 13 13
1481 13 $weak_self->{h2_session}->resume_stream($stream_id);
1482 13 $weak_self->_h2_write_pending;
1483 112 };
1484  
1485 # Shared preamble for the file/fh body arms below (extraction, not a
1486 # redesign -- see the arms themselves for why each piece sits where it
1487 # does). Split in two because the two pieces cross the arms' own
1488 # eval boundary: the file arm must report an illegal-sequence error
1489 # (from advance_http) ahead of a misleading "File not found" from its
1490 # own -f/-r checks, but must NOT have submitted response headers to the
1491 # client before those checks pass -- so the sequence advance runs
1492 # BEFORE the arm's eval (a comment-preserving-only move: advance_http
1493 # is a pure function, and a caught vs. uncaught throw here already
1494 # behaved identically before this extraction, since $seq is simply
1495 # never reassigned on a throw either way), while the streaming-start
1496 # call must stay INSIDE the eval, at each arm's own correct position
1497 # relative to its own pre-checks, so a failure there still rolls back
1498 # via the shared tail below instead of leaking a submitted-but-broken
1499 # response.
1500  
1501 # Outside-eval half: snapshot+advance+mirror the sequence state ahead
1502 # of either arm's own validity checks. Returns the pre-advance $seq so
1503 # the tail helper below can roll back to it on failure.
1504 my $advance_seq_for_body = sub {
1505 19 ▶ my ($ss, $event) = @_;
Subroutine __ANON__: called CC=2 SCAR=7.0
1506 19 my $seq_before = $seq;
1507 19 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1508 17 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 17 0 17
1509 17 return $seq_before;
1510 112 };
1511  
1512 # Inside-eval half: submit the streaming response exactly once, the
1513 # first time either arm actually has a chunk ready to send. Each arm
1514 # calls this at its own correct point (after its own pre-checks, so a
1515 # failed check never causes headers to reach the client for a response
1516 # that goes on to fail).
1517 my $ensure_h2_streaming_started = sub {
1518 16 ▶ my ($ss) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.3
1519 16 ▶ return if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 0 16 16
1520 16 $streaming_started = 1;
1521 16 ▶ $ss->{send_queue} //= []; $ss->{send_queue_bytes} //= 0;
Condition50%2/4
$ss->{"send_queue"} //= []
l!l
016
$ss->{"send_queue_bytes"} //= 0
l!l
016
MC/DC0%0/1
$ss->{"send_queue"} //= []
$ss->{"send_queue"}
MC/DC0%0/1
$ss->{"send_queue_bytes"} //= 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
1522 $weak_self->{h2_session}->submit_response_streaming(
1523 16 $stream_id,
1524 status => $status, headers => \@response_headers,
1525 data_callback => $data_callback,
1526 );
1527 16 $weak_self->_h2_write_pending;
1528 112 };
1529  
1530 # Shared failure-rollback-or-finish tail for the file/fh body arms:
1531 # given the arm's own eval result, either rolls $seq back to its
1532 # pre-event value and re-raises (recoverable per contract, unless the
1533 # stream is simply gone -- a quiet no-op), or marks the body stream's
1534 # EOF pending on success. Mirrors h1's D1 advance-then-rollback pattern.
1535 my $finish_or_rollback_body_send = sub {
1536 17 ▶ my ($ok, $err, $ss, $seq_before) = @_;
Subroutine __ANON__: called CC=4 SCAR=13.9
1537 17 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 4 13 17
1538 4 ▶ return if $err eq $STREAM_GONE; # client reset: quiet no-op
Branch: 1 branch
BranchTrueFalseTotal
if $err eq $STREAM_GONE 1 3 4
1539 3 $seq = $seq_before; # recoverable, per contract
1540 3 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 3 0 3
1541 3 die $err;
1542 }
1543 13 $finish_body_stream->();
1544 112 };
1545  
1546 316 ▶ return async sub {
Subroutine __ANON__: called CC=90 SCAR=47.9
1547 316 my ($event) = @_;
1548 316 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 316 316
1549  
1550 316 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
3160
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
1551  
1552 # Once the machine has recorded the response complete, the machine
1553 # decides what happens next -- 'complete' has no idempotent case, so
1554 # any further send always raises -- not the stream-gone check below.
1555 # h2_streams entries for a finished stream are reclaimed
1556 # asynchronously by _h2_on_close, so by the time a post-complete send
1557 # arrives $ss may already be gone.
1558 316 my $already_closed = ($seq eq 'complete');
1559  
1560 316 my $ss = $weak_self->{h2_streams}{$stream_id};
1561 # A doomed-but-still-present entry (h2_closed set but not yet
1562 # deleted -- see the 413-overrun branch in _h2_on_body) is treated
1563 # the same as an absent one: both are post-close sends and must
1564 # silently no-op, not reach nghttp2 a second time on this stream id.
1565 316 ▶ return if (!$ss || $ss->{h2_closed}) && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if !$ss || $ss->{"h2_closed"} and not $already_closed 6 310 316
Condition100%6/6
!$ss || $ss->{"h2_closed"} and not $already_closed
!ll&&!rl&&r
30916
not $ss or $ss->{"h2_closed"}
l!l&&r!l&&!r
16309
MC/DC100%3/3
!$ss || $ss->{"h2_closed"} and not $already_closed
not $ss $ss->{"h2_closed"} not $already_closed
Truth table80%4/5
not(A) or B and not(C)
A= not $ssB= $ss->{"h2_closed"}C= not $already_closed
ABCresult
00X0
1X00
0100
1X11
0111
1566  
1567 310 ▶ return if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 0 310 310
Condition33%1/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
31000
MC/DC0%0/2
$weak_self->{"closed"} and not $already_closed
$weak_self->{"closed"} not $already_closed
Truth table33%1/3
A and not(B)
A= $weak_self->{"closed"}B= not $already_closed
ABresult
0X0
100
111
1568  
1569 # 1. Shape validation (mandatory)
1570 PAGI::Server::EventValidator::validate_http_send(
1571 310 $event, { extensions => $weak_self->{extensions} });
1572  
1573 # 2. HEAD: the server suppresses the body (PAGI Www.pod "HEAD Requests").
1574 # The app responds exactly as for GET; we discard payloads, never open
1575 # file/fh, and accept-and-discard trailers. Sequence state still
1576 # advances so the lifecycle (completion, post-complete raises) matches GET.
1577 307 ▶ if ($is_head && ($type eq 'http.response.body' || $type eq 'http.response.trailers')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head and $type eq "http.response.body" || $type eq "http.response.trailers") 9 298 307
Condition100%6/6
$is_head and $type eq "http.response.body" || $type eq "http.response.trailers"
!ll&&!rl&&r
291142
$type eq "http.response.body" or $type eq "http.response.trailers"
l!l&&r!l&&!r
817
MC/DC100%3/3
$is_head and $type eq "http.response.body" || $type eq "http.response.trailers"
$is_head $type eq "http.response.body" $type eq "http.response.trailers"
Truth table100%4/4
A and B or C
A= $is_headB= $type eq "http.response.body"C= $type eq "http.response.trailers"
ABCresult
0XX0
1000
11X1
1011
1578 9 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1579 9 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 9 0 9
1580 9 ▶ if ($seq eq 'complete' && !$ss->{h2_head_finished}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($seq eq "complete" and not $ss->{"h2_head_finished"}) 7 2 9
Condition66%2/3
$seq eq "complete" and not $ss->{"h2_head_finished"}
!ll&&!rl&&r
207
MC/DC50%1/2
$seq eq "complete" and not $ss->{"h2_head_finished"}
$seq eq "complete" not $ss->{"h2_head_finished"}
Truth table66%2/3
A and not(B)
A= $seq eq "complete"B= not $ss->{"h2_head_finished"}
ABresult
0X0
100
111
1581 7 $ss->{h2_head_finished} = 1;
1582 7 $weak_self->{h2_session}->submit_response($stream_id,
1583 status => $status,
1584 headers => \@response_headers,
1585 body => '',
1586 );
1587 7 $weak_self->_h2_write_pending;
1588 }
1589 9 return;
1590 }
1591  
1592 # 3. http.response.trailers (design §8.3): submits the trailing
1593 # HEADERS block with END_STREAM, completing a response that declared
1594 # trailers at start. advance-then-rollback (h1 D1 pattern, mirrored
1595 # from _create_send's chunked-framing check): the sequence machine
1596 # and its $ss mirror advance FIRST, then the native submit is
1597 # attempted (directly here, or via $deliver_trailer_eof above --
1598 # see the closure-top comment for why). advance_http itself may
1599 # croak here (trailers undeclared or body not yet complete) -- that
1600 # propagates unrolled-back, same as validate_http_send's shape
1601 # check above, since $seq was never reassigned in that case. If
1602 # submit_trailer throws, both are rolled back to their pre-event
1603 # value and the error propagates: the app's return then lands in
1604 # the existing incomplete-response arm (RST NGHTTP2_INTERNAL_ERROR)
1605 # -- the same machinery a dropped body chunk already relies on, not
1606 # duplicated here.
1607 298 ▶ if ($type eq 'http.response.trailers') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "http.response.trailers") 11 287 298
1608 11 my $seq_before = $seq;
1609 11 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1610 10 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 10 0 10
1611  
1612 # Empty/absent headers still calls submit_trailer with [] --
1613 # trailers were declared and must still terminate the response.
1614 my $trailer_headers = [
1615 16 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
1616 10 ▶ @{ $event->{headers} // [] }
Condition100%2/2
$event->{"headers"} // []
l!l
91
MC/DC100%1/1
$event->{"headers"} // []
$event->{"headers"}
Truth table100%2/2
A
A= $event->{"headers"}
Aresult
11
00
1617 ];
1618 # RFC 9110 6.6.2 / design 13.3 -- an app-supplied connection,
1619 # transfer-encoding, etc. in a trailer block corrupts it at the
1620 # framing layer exactly like a response header: nghttp2 rejects
1621 # the whole trailer HEADERS block, so the peer sees zero
1622 # trailing HEADERS (on_stream_close never fires) even though
1623 # submit_trailer below reports success. Strip before submission,
1624 # same as every response-header path; $in_trailers=1 drops the
1625 # response-only 'te: trailers' carve-out (RFC 9110 6.6.2 bans
1626 # connection-specific fields from trailers outright).
1627 10 $trailer_headers = _h2_strip_connection_headers($trailer_headers, 1);
1628  
1629 10 my $ok;
1630 10 ▶ if ($data_eof_delivered) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data_eof_delivered) { } 6 4 10
1631 # The data provider already handed nghttp2 its terminal
1632 # chunk -- no further $data_callback invocation will occur
1633 # for this stream, so it is safe to submit directly here.
1634 6 $ok = eval {
1635 $weak_self->{h2_session}->submit_trailer(
1636 6 $stream_id, headers => $trailer_headers);
1637 5 1;
1638 };
1639 } else {
1640 # The data provider has not yet delivered EOF to nghttp2
1641 # (still mid-transfer, possibly blocked on real per-stream
1642 # flow control). Stage the headers for $deliver_trailer_eof
1643 # to submit from inside the callback's own terminal
1644 # invocation, and await that -- resolving this send() any
1645 # earlier would let submit_trailer race ahead of not-yet-
1646 # extracted DATA (see the closure-top comment). This PARKS
1647 # the send() until the body actually finishes draining --
1648 # e.g. until the peer grants enough flow-control window --
1649 # which can be a real, unbounded wait from the app's point
1650 # of view (closure-top comment has the full contract note).
1651 4 $pending_trailer_headers = $trailer_headers;
1652 4 my $f = $weak_self->{server}->loop->new_future;
1653 4 $ss->{trailer_wait} = $f;
1654 4 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 4 0 4
1655 4 $weak_self->_h2_write_pending;
1656 # eval wraps the await (not just a plain assignment) so a
1657 # failed $f (native rejection, via $deliver_trailer_eof's
1658 # own $f->fail) is caught into $@ and folds into the same
1659 # $ok/rollback handling the direct branch above uses.
1660 4 $ok = eval { await $f; 1 };
1661 # $f resolves DONE (not fail) on a whole-connection teardown
1662 # too (_close's own sweep releases trailer_wait -- see
1663 # _h2_resolve_stream_trailer_wait) -- the h2_closed carve-
1664 # out's "successful no-op" contract, same discipline as the
1665 # body arms' own post-drain-wait liveness re-check
1666 # (:1616-1619 / :1635-1638 above). Without this, a
1667 # connection that died while we awaited would leave
1668 # $weak_self->{h2_session} undef and the shared tail below
1669 # would call a method on it.
1670 4 ▶ return unless $weak_self && !$weak_self->{closed} && $weak_self->{h2_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self and not $weak_self->{"closed"} and $weak_self->{"h2_session"} 1 3 4
Condition66%4/6
$weak_self and not $weak_self->{"closed"} and $weak_self->{"h2_session"}
!ll&&!rl&&r
103
$weak_self and not $weak_self->{"closed"}
!ll&&!rl&&r
013
MC/DC33%1/3
$weak_self and not $weak_self->{"closed"} and $weak_self->{"h2_session"}
$weak_self not $weak_self->{"closed"} $weak_self->{"h2_session"}
Truth table50%2/4
A and not(B) and C
A= $weak_selfB= not $weak_self->{"closed"}C= $weak_self->{"h2_session"}
ABCresult
0XX0
10X0
1100
1111
1671 }
1672 9 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 7 9
1673 2 my $err = $@;
1674 2 $seq = $seq_before;
1675 2 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 2 0 2
1676 2 die $err;
1677 }
1678  
1679 # Stream-existence re-check, same discipline as every sibling
1680 # await site's own $ss re-fetch (e.g. $emit_chunk above): the
1681 # connection-liveness check at :1524 only covers the deferred
1682 # branch and only the connection, not this stream specifically.
1683 # Placed AFTER the rollback above (not folded into :1524) so a
1684 # deferred native failure still reaches its rollback+die even if
1685 # the stream looks gone by the time we get here -- only the
1686 # success-path tail below, which is about to call resume_stream/
1687 # _h2_write_pending on this stream id again, needs the guard.
1688 # A gone stream here is the h2_closed carve-out's ordinary
1689 # "successful no-op" case: the trailers already landed (ok=1)
1690 # before the stream went away, so returning quietly is correct,
1691 # not a swallowed error.
1692 7 ▶ $ss = $weak_self ? $weak_self->{h2_streams}{$stream_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 7 0 7
1693 7 ▶ return if !$ss || $ss->{h2_closed};
Branch: 1 branch
BranchTrueFalseTotal
if not $ss or $ss->{"h2_closed"} 2 5 7
Condition66%2/3
not $ss or $ss->{"h2_closed"}
l!l&&r!l&&!r
025
MC/DC50%1/2
not $ss or $ss->{"h2_closed"}
not $ss $ss->{"h2_closed"}
Truth table66%2/3
not(A) or B
A= not $ssB= $ss->{"h2_closed"}
ABresult
1X1
011
000
1694  
1695 # Flush any still-queued DATA before the trailing HEADERS --
1696 # nghttp2 orders trailers after queued data on its own, but the
1697 # stream must be resumed if the data callback had deferred.
1698 5 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 5 0 5
1699 5 $weak_self->_h2_write_pending;
1700 5 return;
1701 }
1702  
1703 # 4. file body: streamed through the send queue via $emit_chunk, one
1704 # chunk at a time, under this stream's own backpressure. The type
1705 # guard (not just "defined $event->{file}") keeps a nonconforming
1706 # http.response.start carrying a stray 'file' key from being
1707 # misrouted into this arm.
1708 287 ▶ if ($type eq 'http.response.body' && defined $event->{file}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "http.response.body" and defined $event->{"file"}) 10 277 287
Condition100%3/3
$type eq "http.response.body" and defined $event->{"file"}
!ll&&!rl&&r
10317410
MC/DC100%2/2
$type eq "http.response.body" and defined $event->{"file"}
$type eq "http.response.body" defined $event->{"file"}
Truth table100%3/3
A and B
A= $type eq "http.response.body"B= defined $event->{"file"}
ABresult
0X0
100
111
1709 10 my $file = $event->{file};
1710 10 ▶ my $offset = $event->{offset} // 0;
Condition100%2/2
$event->{"offset"} // 0
l!l
28
MC/DC100%1/1
$event->{"offset"} // 0
$event->{"offset"}
Truth table100%2/2
A
A= $event->{"offset"}
Aresult
11
00
1711 10 my $length = $event->{length};
1712  
1713 # Snapshot+advance BEFORE the -f/-r checks (and the checks live
1714 # inside the eval below) so a file event arriving in an illegal
1715 # sequence state reports the SEQUENCE error, not a misleading
1716 # "File not found" -- h1 parity. A failed file send must NOT
1717 # mark the response complete, so on failure $seq rolls back to
1718 # $seq_before exactly as the h1 twin in _create_send does.
1719 10 my $seq_before = $advance_seq_for_body->($ss, $event);
1720  
1721 8 my $ok = eval {
1722 8 ▶ die "File not found: $file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 7 8
1723 7 ▶ die "Cannot read file: $file\n" unless -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $file 0 7 7
1724  
1725 7 $ensure_h2_streaming_started->($ss);
1726  
1727 # Mirror h1's effective-length computation (_send_file_response)
1728 # so the sync-vs-async choice below sees the same number h1
1729 # would, including the Www.pod rule that an offset past EOF
1730 # clamps to zero bytes rather than failing.
1731 7 my $file_size = -s $file;
1732 7 ▶ die "Cannot stat file $file: $!\n" unless defined $file_size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_size 0 7 7
1733 7 ▶ my $effective_length = $length // ($file_size - $offset);
Condition66%2/3
$length // $file_size - $offset
l!l&&r!l&&!r
160
MC/DC0%0/2
$length // $file_size - $offset
$length $file_size - $offset
Truth table66%2/3
A // B
A= $lengthB= $file_size - $offset
ABresult
1X1
011
000
1734 7 ▶ $effective_length = 0 if $effective_length < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $effective_length < 0 1 6 7
1735  
1736 7 ▶ if ($weak_self->{sync_file_threshold} > 0
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{'sync_file_threshold'} > 0 and $effective_length <= $weak_self->{'sync_file_threshold'}) { } 4 3 7
Condition66%2/3
$weak_self->{"sync_file_threshold"} > 0 and $effective_length <= $weak_self->{"sync_file_threshold"}
!ll&&!rl&&r
034
MC/DC50%1/2
$weak_self->{"sync_file_threshold"} > 0 and $effective_length <= $weak_self->{"sync_file_threshold"}
$weak_self->{"sync_file_threshold"} > 0 $effective_length <= $weak_self->{"sync_file_threshold"}
Truth table66%2/3
A and B
A= $weak_self->{"sync_file_threshold"} > 0B= $effective_length <= $weak_self->{"sync_file_threshold"}
ABresult
0X0
100
111
1737 && $effective_length <= $weak_self->{sync_file_threshold}) {
1738 # Small-file fast path (parity with h1's sync_file_threshold):
1739 # a file at or under the threshold is read synchronously,
1740 # in-process, as ONE queue chunk -- avoiding a worker-pool
1741 # round trip for a body small enough that it costs more
1742 # than it saves. The no-slurp rule targets large files.
1743 4 ▶ open my $fh, '<:raw', $file or die "Cannot open file $file: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or die "Cannot open file ${file}: $!\n" 0 4 4
1744 4 ▶ seek($fh, $offset, 0) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 2 2 4
1745 4 my $bytes_read = read($fh, my $data, $effective_length);
1746 4 ▶ die "Failed to read file $file: $!\n" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 0 4 4
1747 4 close $fh;
1748 4 await $emit_chunk->($data);
1749 }
1750 else {
1751 3 my $loop = $weak_self->{server}->loop;
1752 3 ▶ await PAGI::Server::AsyncFile->read_file_chunked(
Branch: 1 branch
BranchTrueFalseTotal
defined $length ? : 0 3 3
1753 $loop, $file, $emit_chunk,
1754 offset => $offset,
1755 (defined $length ? (length => $length) : ()),
1756 chunk_size => FILE_CHUNK_SIZE,
1757 );
1758 }
1759 6 1;
1760 };
1761 8 $finish_or_rollback_body_send->($ok, $@, $ss, $seq_before);
1762 7 return;
1763 }
1764  
1765 # 5. fh body: streamed through the send queue via $emit_chunk, one
1766 # chunk at a time, under this stream's own backpressure. The
1767 # application owns $fh (opened before the send, closed or not by the
1768 # app afterward) -- the server never closes it. Mirrors the file arm
1769 # above; the read loop is adapted from h1's _send_fh_response. The
1770 # type guard mirrors the file arm's M1 fix above.
1771 277 ▶ if ($type eq 'http.response.body' && defined $event->{fh}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "http.response.body" and defined $event->{"fh"}) 9 268 277
Condition100%3/3
$type eq "http.response.body" and defined $event->{"fh"}
!ll&&!rl&&r
1031659
MC/DC100%2/2
$type eq "http.response.body" and defined $event->{"fh"}
$type eq "http.response.body" defined $event->{"fh"}
Truth table100%3/3
A and B
A= $type eq "http.response.body"B= defined $event->{"fh"}
ABresult
0X0
100
111
1772 9 my $fh = $event->{fh};
1773  
1774 9 my $seq_before = $advance_seq_for_body->($ss, $event);
1775  
1776 9 my $ok = eval {
1777 9 $ensure_h2_streaming_started->($ss);
1778 9 ▶ if (my $off = $event->{offset}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $off = $event->{"offset"}) 3 6 9
1779 3 ▶ seek($fh, $off, 0) or die "Cannot seek: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $off, 0 or die "Cannot seek: $!\n" 1 2 3
1780 }
1781 8 my $remaining = $event->{length};
1782 8 while (1) {
1783 30 my $to_read = FILE_CHUNK_SIZE;
1784 30 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 2 28 30
1785 2 ▶ $to_read = $remaining if $remaining < $to_read;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining < $to_read 2 0 2
1786 2 ▶ last if $to_read <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $to_read <= 0 1 1 2
1787 }
1788 # The bare block scopes only the 'closed' warning
1789 # suppression around read() -- a bare block is itself a
1790 # one-iteration loop, so die/last/await must live outside
1791 # it or 'last' would only exit the block, not this while.
1792 29 my ($bytes_read, $chunk);
1793 154 ▶ { no warnings 'closed';
Subroutine BEGIN: called CC=1 SCAR=0.0
1794 29 $bytes_read = read($fh, $chunk, $to_read);
1795 }
1796 29 ▶ die "Failed to read filehandle: $!\n" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 1 28 29
1797 28 ▶ last if $bytes_read == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_read == 0 6 22 28
1798 22 await $emit_chunk->($chunk);
1799 22 ▶ $remaining -= $bytes_read if defined $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if defined $remaining 1 21 22
1800 }
1801 7 1;
1802 };
1803 9 $finish_or_rollback_body_send->($ok, $@, $ss, $seq_before);
1804 7 return;
1805 }
1806  
1807 # 6. Sequence enforcement (start / plain body / fullflush). advance_http
1808 # is deliberately called from four places in this sub — the HEAD
1809 # block above, the file arm, the fh arm, and here — each has
1810 # different pre/post-state needs; do not consolidate them.
1811 268 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1812 265 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 265 0 265
1813  
1814 265 ▶ if ($type eq 'http.response.start') {
Branch: 3 branches
BranchTrueFalseTotal
if ($type eq 'http.response.start') { } 101 164 265
elsif ($type eq 'http.response.body') { } 163 1 164
elsif ($type eq 'http.fullflush') { } 1 0 1
1815 101 $ss->{response_started} = 1;
1816 101 ▶ $ss->{connection_state}->_mark_response_started if $ss->{connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"connection_state"} 101 0 101
1817 101 ▶ $trailers_declared = 1 if $event->{trailers};
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"trailers"} 14 87 101
1818  
1819 101 ▶ $status = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
1010
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
1820 @response_headers = map {
1821 113 [_validate_header_name($_->[0]), _validate_header_value($_->[1])]
1822 101 ▶ } @{$event->{headers} // []};
Condition50%1/2
$event->{"headers"} // []
l!l
1010
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
1823 # RFC 9113 8.2.2 / design 13.3 — strips app-supplied connection,
1824 # transfer-encoding, etc. before this list reaches nghttp2 (also
1825 # covers the HEAD path below, which submits this same array).
1826 101 @response_headers = @{ _h2_strip_connection_headers(\@response_headers) };
1827 # Server-supplied Date header (HTTP/1.1 parity) — add if the app didn't.
1828 101 ▶ unless (grep { lc($_->[0]) eq 'date' } @response_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @response_headers) 101 0 101
1829 101 push @response_headers, ['date', $weak_self->{protocol}->format_date];
1830 }
1831 }
1832 elsif ($type eq 'http.response.body') {
1833 163 ▶ my $body = $event->{body} // '';
Condition50%1/2
$event->{"body"} // ""
l!l
1630
MC/DC0%0/1
$event->{"body"} // ""
$event->{"body"}
Truth table50%1/2
A
A= $event->{"body"}
Aresult
11
00
1834 163 ▶ my $more = $event->{more} // 0;
Condition100%2/2
$event->{"more"} // 0
l!l
15310
MC/DC100%1/1
$event->{"more"} // 0
$event->{"more"}
Truth table100%2/2
A
A= $event->{"more"}
Aresult
11
00
1835  
1836 163 ▶ if ($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) { } 89 74 163
1837 89 ▶ if (!$streaming_started) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $streaming_started) { } 20 69 89
1838 # First streaming chunk — submit with data callback
1839 20 $streaming_started = 1;
1840 20 ▶ $ss->{send_queue} //= [];
Condition50%1/2
$ss->{"send_queue"} //= []
l!l
020
MC/DC0%0/1
$ss->{"send_queue"} //= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
1841 20 ▶ $ss->{send_queue_bytes} //= 0;
Condition50%1/2
$ss->{"send_queue_bytes"} //= 0
l!l
020
MC/DC0%0/1
$ss->{"send_queue_bytes"} //= 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
1842 20 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 20 0 20
1843 20 push @{$ss->{send_queue}}, $body;
1844 20 $ss->{send_queue_bytes} += length $body;
1845 }
1846 # Synchronous: we're in the app's send path (not nghttp2's
1847 # extract), so on_high_water can fire here to tell the app to
1848 # pause its source.
1849 20 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 20 0 20
1850 $weak_self->{h2_session}->submit_response_streaming(
1851 20 $stream_id,
1852 status => $status,
1853 headers => \@response_headers,
1854 data_callback => $data_callback,
1855 );
1856 20 $weak_self->_h2_write_pending;
1857 } else {
1858 # Subsequent chunk — backpressure check then push and resume.
1859 # Bound on THIS stream's send queue (per-stream), not the
1860 # shared TCP buffer which is meaningless across multiplexed
1861 # streams.
1862 69 ▶ if (($ss->{send_queue_bytes} // 0) >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) >= $weak_self->{"write_high_watermark"}) 6 63 69
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
690
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
1863 6 await $weak_self->_h2_wait_for_stream_drain($stream_id);
1864 6 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 6 6
1865 6 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 6 6
1866 6 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 6 6
1867 }
1868 69 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 69 0 69
1869 69 push @{$ss->{send_queue}}, $body;
1870 69 $ss->{send_queue_bytes} += length $body;
1871 }
1872 # Synchronous — app send path, not nghttp2 extract.
1873 69 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 68 1 69
1874 69 $weak_self->{h2_session}->resume_stream($stream_id);
1875 69 $weak_self->_h2_write_pending;
1876 }
1877 } else {
1878 74 ▶ if ($streaming_started) {
Branch: 2 branches
BranchTrueFalseTotal
if ($streaming_started) { } 16 58 74
elsif ($seq eq 'awaiting_trailers') { } 7 51 58
1879 # Final chunk on an already-streaming response. Bound on THIS
1880 # stream's send queue (per-stream), not the shared TCP buffer.
1881 16 ▶ if (($ss->{send_queue_bytes} // 0) >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) >= $weak_self->{"write_high_watermark"}) 0 16 16
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
160
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
1882 0 await $weak_self->_h2_wait_for_stream_drain($stream_id);
1883 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
1884 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
1885 0 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 0 0
1886 }
1887 16 $eof_pending = 1;
1888 16 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 14 2 16
1889 14 push @{$ss->{send_queue}}, $body;
1890 14 $ss->{send_queue_bytes} += length $body;
1891 }
1892 # Synchronous — app send path, not nghttp2 extract.
1893 16 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 16 0 16
1894 16 $weak_self->{h2_session}->resume_stream($stream_id);
1895 16 $weak_self->_h2_write_pending;
1896 } elsif ($seq eq 'awaiting_trailers') {
1897 # Trailers were declared and this is the (single-shot)
1898 # terminal body event: a plain submit_response would set
1899 # END_STREAM immediately, ending the stream before the
1900 # trailers arrive -- design §8.3 forbids that. Route
1901 # through the streaming path instead, mirroring the
1902 # file/fh arms' $streaming_started idiom; the data
1903 # callback above already reserves END_STREAM for the
1904 # trailing HEADERS block once it observes
1905 # 'awaiting_trailers'.
1906 7 $streaming_started = 1;
1907 7 ▶ $ss->{send_queue} //= [];
Condition50%1/2
$ss->{"send_queue"} //= []
l!l
07
MC/DC0%0/1
$ss->{"send_queue"} //= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
1908 7 ▶ $ss->{send_queue_bytes} //= 0;
Condition50%1/2
$ss->{"send_queue_bytes"} //= 0
l!l
07
MC/DC0%0/1
$ss->{"send_queue_bytes"} //= 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
1909 7 $eof_pending = 1;
1910 7 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 5 2 7
1911 5 push @{$ss->{send_queue}}, $body;
1912 5 $ss->{send_queue_bytes} += length $body;
1913 }
1914 7 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 7 0 7
1915 $weak_self->{h2_session}->submit_response_streaming(
1916 7 $stream_id,
1917 status => $status,
1918 headers => \@response_headers,
1919 data_callback => $data_callback,
1920 );
1921 7 $weak_self->_h2_write_pending;
1922 } else {
1923 # Non-streaming: single response (unchanged one-shot path)
1924 51 $weak_self->{h2_session}->submit_response($stream_id,
1925 status => $status,
1926 headers => \@response_headers,
1927 body => $body,
1928 );
1929 51 $weak_self->_h2_write_pending;
1930 }
1931 }
1932 }
1933 elsif ($type eq 'http.fullflush') {
1934 # Hand any pending frames to the session's write path (design §8.4).
1935 1 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 1 0 1
1936 1 $weak_self->_h2_write_pending;
1937 }
1938 112 };
1939 }
1940  
1941 # =============================================================================
1942 # HTTP/2 WebSocket over HTTP/2 (RFC 8441)
1943 # =============================================================================
1944  
1945 sub _h2_create_websocket_scope {
1946 53 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_websocket_scope: called CC=9 SCAR=22.6
1947  
1948 53 my $pseudo = $stream_state->{pseudo};
1949 53 my $headers = $stream_state->{headers};
1950  
1951 53 ▶ my $full_path = $pseudo->{':path'} // '/';
Condition50%1/2
$pseudo->{":path"} // "/"
l!l
530
MC/DC0%0/1
$pseudo->{":path"} // "/"
$pseudo->{":path"}
Truth table50%1/2
A
A= $pseudo->{":path"}
Aresult
11
00
1952 53 my ($path, $query_string) = split(/\?/, $full_path, 2);
1953 53 ▶ $query_string //= '';
Condition50%1/2
$query_string //= ""
l!l
053
MC/DC0%0/1
$query_string //= ""
$query_string
Truth table50%1/2
A
A= $query_string
Aresult
11
00
1954  
1955 # Match HTTP/1.1 pipeline: URI::Escape + UTF-8 decode with fallback
1956 53 my $unescaped = uri_unescape($path);
1957 53 ▶ my $decoded_path = eval { decode('UTF-8', $unescaped, Encode::FB_CROAK) }
Condition33%1/3
eval { do { &decode("UTF-8", $unescaped, 1) } } // $unescaped
l!l&&r!l&&!r
5300
MC/DC0%0/2
eval { do { &decode("UTF-8", $unescaped, 1) } } // $unescaped
eval { do { &decode("UTF-8", $unescaped, 1) } } $unescaped
Truth table33%1/3
A // B
A= eval { do { &decode("UTF-8", $unescaped, 1) } }B= $unescaped
ABresult
1X1
011
000
1958 // $unescaped;
1959  
1960 # Extract subprotocols from headers
1961 53 my @subprotocols;
1962 53 for my $header (@$headers) {
1963 104 my ($name, $value) = @$header;
1964 104 ▶ if ($name eq 'sec-websocket-protocol') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "sec-websocket-protocol") 1 103 104
1965 1 push @subprotocols, map { s/^\s+|\s+$//gr } split /,/, $value;
1966 }
1967 }
1968  
1969 return {
1970 type => 'websocket',
1971 pagi => {
1972 version => '0.5',
1973 spec_version => '0.5',
1974 },
1975 http_version => '2',
1976 scheme => $self->_get_ws_scheme,
1977 path => $decoded_path,
1978 raw_path => $path,
1979 query_string => $query_string,
1980 root_path => '',
1981 headers => $headers,
1982 (defined $self->{client_host}
1983 ? (client => [$self->{client_host}, $self->{client_port}])
1984 : ()
1985 ),
1986 server => [$self->{server_host}, $self->{server_port}],
1987 subprotocols => \@subprotocols,
1988 53 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
1989 extensions => do {
1990 53 my %ext = (%{$self->_get_extensions_for_scope}, 'websocket.http.response' => {});
1991 # fullflush has no validate_websocket_send arm; advertising it here
1992 # would lie to the app (design 13.2).
1993 53 delete $ext{fullflush};
1994 53 ▶ \%ext;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'max_ws_frame_size'} ? : 50 3 53
1995 },
1996 # max_frame_size: omitted when unenforced (max_ws_frame_size 0/undef
1997 # means unlimited, per Protocol::WebSocket::Frame's max_payload_size
1998 # semantics -- a server that does not enforce a cap must not
1999 # advertise one). max_receive_queue has no unlimited mode (a hard,
2000 # always-enforced cap), so it is always present.
2001 ($self->{max_ws_frame_size}
2002 ? (max_frame_size => $self->{max_ws_frame_size})
2003 : ()
2004 ),
2005 max_receive_queue => $self->{max_receive_queue},
2006 # Per-stream outbound flow-control handle. Like the h2 sse/streaming
2007 # scopes, it measures THIS stream's send queue (h2 multiplexes many
2008 # streams over one connection, so the shared TCP buffer is
2009 # meaningless per stream). Gives WebSocket-over-h2 the same
2010 # pagi.transport surface HTTP/1.1 WebSocket already provides.
2011 53 ▶ 'pagi.transport' => ($stream_state->{transport_state} = $self->_h2_transport_state($stream_state)),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 53 0 53
keys %{$$self{'state'};} ? : 0 53 53
2012 };
2013 }
2014  
2015 sub _h2_create_websocket_receive {
2016 53 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_websocket_receive: called CC=1 SCAR=0.0
2017  
2018 53 weaken(my $weak_self = $self);
2019  
2020 # Fallback disconnect for a receive() that resolves after this stream is
2021 # gone or the connection is closed: 1006/'' by default (RFC 6455
2022 # abnormal closure, no reason available), but prefers the per-stream
2023 # server_close_reason token when the stream's own state is still
2024 # reachable in h2_streams -- a server-initiated teardown (idle timeout,
2025 # keepalive timeout, ...) records that token there before tearing the
2026 # stream down, so a receive() racing that teardown still reports why.
2027 my $fallback_disconnect = sub {
2028 20 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Subroutine __ANON__: called CC=4 SCAR=13.9
Condition66%2/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
0119
MC/DC50%1/2
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
$weak_self $weak_self->{'h2_streams'}{$stream_id}
Truth table66%2/3
A && B
A= $weak_selfB= $weak_self->{'h2_streams'}{$stream_id}
ABresult
0X0
100
111
2029 return {
2030 type => 'websocket.disconnect',
2031 code => 1006,
2032 20 ▶ reason => ($ss && $ss->{server_close_reason}) // '',
Condition100%5/5
$ss && $ss->{"server_close_reason"} // ""
l!l
119
$ss and $ss->{"server_close_reason"}
!ll&&!rl&&r
1181
MC/DC100%2/2
$ss && $ss->{"server_close_reason"} // ""
$ss $ss->{"server_close_reason"}
Truth table100%3/3
A and B
A= $ssB= $ss->{"server_close_reason"}
ABresult
111
0X0
100
2033 };
2034 53 };
2035  
2036 return sub {
2037 115 ▶ return Future->done($fallback_disconnect->())
Subroutine __ANON__: called CC=4 SCAR=14.1
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 115 115
2038 unless $weak_self;
2039 return Future->done($fallback_disconnect->())
2040 115 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 2 113 115
2041  
2042 113 my $ss = $weak_self->{h2_streams}{$stream_id};
2043 113 ▶ return Future->done($fallback_disconnect->())
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 113 113
2044 unless $ss;
2045  
2046 113 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=9 SCAR=22.5
2047 113 ▶ return $fallback_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 113 113
2048 unless $weak_self;
2049  
2050 113 my $ss = $weak_self->{h2_streams}{$stream_id};
2051 113 ▶ return $fallback_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 113 113
2052 unless $ss;
2053  
2054 # Check queue first
2055 113 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 113 113
2056 0 return shift @{$ss->{receive_queue}};
2057 }
2058  
2059 # First call returns websocket.connect
2060 113 ▶ if (!$ss->{ws_connect_sent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"ws_connect_sent"}) 47 66 113
2061 47 $ss->{ws_connect_sent} = 1;
2062 47 return { type => 'websocket.connect' };
2063 }
2064  
2065 # Wait for events
2066 66 while (1) {
2067 142 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 41 101 142
2068 41 return shift @{$ss->{receive_queue}};
2069 }
2070  
2071 return $fallback_disconnect->()
2072 101 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 18 83 101
2073  
2074 83 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 83 0 83
2075 83 $ss->{body_pending} = Future->new;
2076 }
2077 83 await $ss->{body_pending};
2078  
2079 76 $ss = $weak_self->{h2_streams}{$stream_id};
2080 76 ▶ return $fallback_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 76 76
2081 unless $ss;
2082 }
2083 113 })->();
2084  
2085 113 return $future;
2086 53 };
2087 }
2088  
2089 sub _h2_create_websocket_send {
2090 51 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_websocket_send: called CC=1 SCAR=0.1
2091  
2092 51 weaken(my $weak_self = $self);
2093 51 my $seq = 'connecting';
2094  
2095 # Data callback for nghttp2's streaming response (the same pull-based
2096 # data-provider model _h2_create_send/_h2_create_sse_send already use).
2097 # Pulls raw WS frame bytes from the per-stream queue -- app messages,
2098 # protocol replies (pong, close-echo), and this stream's own keepalive
2099 # ping are all pushed there in call order, so FIFO ordering on the wire
2100 # is preserved exactly as it was under direct submit_data calls.
2101 #
2102 # $ss->{ws_eof_pending} lives on the stream state (not a closure-local,
2103 # unlike the http streaming callback's $eof_pending) because it is set
2104 # from other subs entirely -- _h2_ws_close and the close-frame arm of
2105 # _h2_process_ws_frames -- not just from this closure. When set, it
2106 # merges END_STREAM onto the LAST queued chunk (the close frame itself)
2107 # rather than emitting a separate empty terminal frame, matching the
2108 # previous submit_data($id, $close_frame_bytes, 1) behavior exactly.
2109 my $data_callback = sub {
2110 190 ▶ my ($cb_stream_id, $max_len) = @_;
Subroutine __ANON__: called CC=17 SCAR=28.5
2111  
2112 190 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
00190
MC/DC0%0/2
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
$weak_self $weak_self->{'h2_streams'}{$stream_id}
Truth table33%1/3
A && B
A= $weak_selfB= $weak_self->{'h2_streams'}{$stream_id}
ABresult
0X0
100
111
2113 190 ▶ return undef unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 190 190
2114 190 ▶ my $q = $ss->{send_queue} ||= [];
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
1900
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2115  
2116 190 ▶ if (@$q) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$q) 93 97 190
2117 93 my $chunk = shift @$q;
2118 # Respect max_len — XS truncates without preserving remainder
2119 93 ▶ if (length($chunk) > $max_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk > $max_len) 20 73 93
2120 20 unshift @$q, substr($chunk, $max_len);
2121 20 $chunk = substr($chunk, 0, $max_len);
2122 }
2123 93 $ss->{send_queue_bytes} -= length($chunk);
2124  
2125 # Per-stream backpressure: once this stream's queue falls below the
2126 # low watermark, release any producer blocked in
2127 # _h2_wait_for_stream_drain. This runs inside nghttp2's extract(), so
2128 # resolve on the next loop tick — completing the Future resumes the
2129 # awaiting producer synchronously, and it must not re-enter nghttp2.
2130 93 ▶ if (($ss->{send_queue_bytes} // 0) < $weak_self->{write_low_watermark}
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}) 1 92 93
Condition87%7/8
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}
!ll&&!rl&&r
9021
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
12783
$ss->{"send_queue_bytes"} // 0
l!l
930
MC/DC66%2/3
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}
$ss->{"send_queue_bytes"} $ss->{"stream_drain_waiters"} @{$ss->{"stream_drain_waiters"};}
Truth table75%3/4
A and B and C
A= $ss->{"send_queue_bytes"}B= $ss->{"stream_drain_waiters"}C= @{$ss->{"stream_drain_waiters"};}
ABCresult
0XX0
10X0
1100
1111
2131 3 && $ss->{stream_drain_waiters} && @{$ss->{stream_drain_waiters}}) {
2132 1 my @waiters = splice @{$ss->{stream_drain_waiters}};
2133 $weak_self->{server}->loop->later(sub {
2134 1 ▶ $_->done for grep { !$_->is_ready } @waiters;
Subroutine __ANON__: called CC=2 SCAR=6.9
2135 1 });
2136 }
2137  
2138 # Fire the app's on_drain hysteresis callbacks once this stream's
2139 # queue falls below the low watermark. Deferred for the same reason:
2140 # an on_drain callback may call $send, which would re-enter nghttp2.
2141 93 ▶ if (($ss->{send_queue_bytes} // 0) < $weak_self->{write_low_watermark}
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}) 5 88 93
Condition87%7/8
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}
!ll&&!rl&&r
8445
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"}
!ll&&!rl&&r
12729
$ss->{"send_queue_bytes"} // 0
l!l
930
MC/DC66%2/3
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}
$ss->{"send_queue_bytes"} $ss->{"transport_drain_fires"} @{$ss->{"transport_drain_fires"};}
Truth table75%3/4
A and B and C
A= $ss->{"send_queue_bytes"}B= $ss->{"transport_drain_fires"}C= @{$ss->{"transport_drain_fires"};}
ABCresult
0XX0
10X0
1100
1111
2142 9 && $ss->{transport_drain_fires} && @{$ss->{transport_drain_fires}}) {
2143 5 my @fires = splice @{$ss->{transport_drain_fires}};
2144 $weak_self->{server}->loop->later(sub {
2145 5 ▶ $_->() for @fires;
Subroutine __ANON__: called CC=2 SCAR=6.9
2146 5 });
2147 }
2148  
2149 93 ▶ my $eof = (!@$q && $ss->{ws_eof_pending}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!@$q && $ss->{'ws_eof_pending'} ? : 17 76 93
Condition100%3/3
not @$q and $ss->{"ws_eof_pending"}
!ll&&!rl&&r
215517
MC/DC100%2/2
not @$q and $ss->{"ws_eof_pending"}
not @$q $ss->{"ws_eof_pending"}
Truth table100%3/3
not(A) and B
A= not @$qB= $ss->{"ws_eof_pending"}
ABresult
0X0
100
111
2150 93 return ($chunk, $eof);
2151 }
2152  
2153 # Queue empty but EOF pending (a close frame already delivered as
2154 # the terminal chunk above) — signal end of stream.
2155 97 ▶ return ('', 1) if $ss->{ws_eof_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_eof_pending"} 0 97 97
2156  
2157 # Queue empty, more data expected — defer (NGHTTP2_ERR_DEFERRED in C layer)
2158 97 return undef;
2159 51 };
2160  
2161 93 ▶ return async sub {
Subroutine __ANON__: called CC=47 SCAR=42.3
2162 93 my ($event) = @_;
2163 93 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 93 93
2164  
2165 93 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
930
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
2166  
2167 # Once the machine has recorded the connection closed or the denial
2168 # response complete, the machine decides what happens next -- both
2169 # 'closed' and 'denial_complete' have no idempotent case, so any
2170 # further send always raises -- not the stream-gone check below.
2171 # h2_streams entries for a finished stream are reclaimed
2172 # asynchronously by _h2_on_close (websocket.close itself triggers
2173 # this via END_STREAM, same mechanism as the h2 HTTP/SSE closures),
2174 # so by the time a post-close send arrives $ss may already be gone.
2175 93 ▶ my $already_closed = ($seq eq 'closed' || $seq eq 'denial_complete');
Condition100%3/3
$seq eq 'closed' || $seq eq 'denial_complete'
l!l&&r!l&&!r
1191
MC/DC100%2/2
$seq eq 'closed' || $seq eq 'denial_complete'
$seq eq 'closed' $seq eq 'denial_complete'
Truth table100%3/3
A || B
A= $seq eq 'closed'B= $seq eq 'denial_complete'
ABresult
1X1
011
000
2176  
2177 93 my $ss = $weak_self->{h2_streams}{$stream_id};
2178 # A doomed-but-still-present entry (h2_closed set but not yet
2179 # deleted -- see the 413-overrun branch in _h2_on_body) is treated
2180 # the same as an absent one: both are post-close sends and must
2181 # silently no-op, not reach nghttp2 a second time on this stream id.
2182 93 ▶ return if (!$ss || $ss->{h2_closed}) && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if !$ss || $ss->{"h2_closed"} and not $already_closed 0 93 93
Condition33%2/6
!$ss || $ss->{"h2_closed"} and not $already_closed
!ll&&!rl&&r
9300
not $ss or $ss->{"h2_closed"}
l!l&&r!l&&!r
0093
MC/DC0%0/3
!$ss || $ss->{"h2_closed"} and not $already_closed
not $ss $ss->{"h2_closed"} not $already_closed
Truth table20%1/5
not(A) or B and not(C)
A= not $ssB= $ss->{"h2_closed"}C= not $already_closed
ABCresult
00X0
1X00
0100
1X11
0111
2183  
2184 93 ▶ return if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 0 93 93
Condition33%1/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
9300
MC/DC0%0/2
$weak_self->{"closed"} and not $already_closed
$weak_self->{"closed"} not $already_closed
Truth table33%1/3
A and not(B)
A= $weak_self->{"closed"}B= not $already_closed
ABresult
0X0
100
111
2185  
2186 # websocket.http.response is always available on this path (the
2187 # scope advertises it unconditionally; see
2188 # _h2_create_websocket_scope), unlike connection-level extensions
2189 # such as fullflush.
2190 PAGI::Server::EventValidator::validate_websocket_send(
2191 93 $event, { extensions => { %{$weak_self->{extensions}}, 'websocket.http.response' => {} } });
2192 93 $seq = PAGI::Server::EventValidator::advance_websocket($seq, $event);
2193  
2194 91 ▶ if ($type eq 'websocket.accept') {
Branch: 6 branches
BranchTrueFalseTotal
if ($type eq 'websocket.accept') { } 42 49 91
elsif ($type eq 'websocket.send') { } 19 30 49
elsif ($type eq 'websocket.http.response.start') { } 5 25 30
elsif ($type eq 'websocket.http.response.body') { } 6 19 25
elsif ($type eq 'websocket.close') { } 8 11 19
elsif ($type eq 'websocket.keepalive') { } 11 0 11
2195 # A duplicate accept is already rejected by advance_websocket.
2196  
2197 # HTTP/2 WebSocket: respond with 200 (not 101)
2198 42 my @headers;
2199 42 ▶ if (my $subprotocol = $event->{subprotocol}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $subprotocol = $event->{"subprotocol"}) 0 42 42
2200 0 $subprotocol = _validate_subprotocol($subprotocol);
2201 0 push @headers, ['sec-websocket-protocol', $subprotocol];
2202 }
2203 42 ▶ if (my $extra = $event->{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $extra = $event->{"headers"}) 1 41 42
2204 push @headers, map {
2205 1 [_validate_header_name($_->[0]), _validate_header_value($_->[1])]
2206 } @$extra;
2207 }
2208 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2209 # transfer-encoding, etc. before submission.
2210 42 @headers = @{ _h2_strip_connection_headers(\@headers) };
2211  
2212 42 $ss->{ws_accepted} = 1;
2213 42 $ss->{response_started} = 1;
2214 $ss->{ws_frame} = Protocol::WebSocket::Frame->new(
2215 max_payload_size => $weak_self->{max_ws_frame_size},
2216 42 );
2217  
2218 # Submit 200 response with a pull-based data provider (same
2219 # model as h2 streaming/SSE): frames are pushed onto
2220 # $ss->{send_queue} and pulled by $data_callback as nghttp2's
2221 # per-stream flow-control window allows.
2222 42 ▶ $ss->{send_queue} //= [];
Condition50%1/2
$ss->{"send_queue"} //= []
l!l
042
MC/DC0%0/1
$ss->{"send_queue"} //= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2223 42 ▶ $ss->{send_queue_bytes} //= 0;
Condition50%1/2
$ss->{"send_queue_bytes"} //= 0
l!l
042
MC/DC0%0/1
$ss->{"send_queue_bytes"} //= 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2224 42 $weak_self->{h2_session}->submit_response_streaming($stream_id,
2225 status => 200,
2226 headers => \@headers,
2227 data_callback => $data_callback,
2228 );
2229 42 $weak_self->_h2_write_pending;
2230  
2231 # Process any data that arrived before accept
2232 42 ▶ if (length($ss->{body}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $ss->{"body"} > 0) 0 42 42
2233 0 my $buffered = $ss->{body};
2234 0 $ss->{body} = '';
2235 0 $weak_self->_h2_process_ws_frames($stream_id, $ss, $buffered);
2236 }
2237 }
2238 elsif ($type eq 'websocket.send') {
2239 19 ▶ return unless $ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_accepted"} 0 19 19
2240  
2241 19 my $frame;
2242 19 ▶ if (defined $event->{text}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $event->{'text'}) { } 18 1 19
elsif (defined $event->{'bytes'}) { } 1 0 1
2243 $frame = Protocol::WebSocket::Frame->new(
2244 buffer => $event->{text},
2245 18 type => 'text',
2246 );
2247 }
2248 elsif (defined $event->{bytes}) {
2249 $frame = Protocol::WebSocket::Frame->new(
2250 buffer => $event->{bytes},
2251 1 type => 'binary',
2252 );
2253 }
2254 else {
2255 0 return;
2256 }
2257  
2258 19 my $bytes = $frame->to_bytes;
2259  
2260 # Per-stream backpressure: bound on THIS stream's queue, not the
2261 # shared TCP buffer (meaningless across multiplexed h2 streams).
2262 19 ▶ if (($ss->{send_queue_bytes} // 0) >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) >= $weak_self->{"write_high_watermark"}) 3 16 19
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
190
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2263 3 await $weak_self->_h2_wait_for_stream_drain($stream_id);
2264 3 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 3 3
2265 3 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 3 3
2266 # Refetch (same idiom as emit_chunk, :1374-1375): a stream
2267 # can close while this send was parked.
2268 3 $ss = $weak_self->{h2_streams}{$stream_id};
2269 3 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 3 3
2270 3 ▶ return if $ss->{h2_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"h2_closed"} 1 2 3
2271 # This send can wake AFTER this stream's close frame was
2272 # already queued (window opened below the low watermark
2273 # while ws_eof_pending was set) -- pushing app data now would
2274 # land it BEHIND the close frame: Close would ship without
2275 # END_STREAM and a Text/Binary frame would follow it,
2276 # violating RFC 6455 5.5.1. Same post-close no-op contract
2277 # as the top-of-closure $already_closed check.
2278 2 ▶ return if $ss->{ws_eof_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_eof_pending"} 1 1 2
2279 }
2280  
2281 17 push @{$ss->{send_queue}}, $bytes;
2282 17 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
170
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2283 # Synchronous — app send path, not nghttp2 extract — so on_high_water
2284 # may fire here to tell the app to pause its source.
2285 17 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 17 0 17
2286 17 $weak_self->{h2_session}->resume_stream($stream_id);
2287 17 $weak_self->_h2_write_pending;
2288 }
2289 elsif ($type eq 'websocket.http.response.start') {
2290 5 ▶ return if $ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_accepted"} 0 5 5
2291 5 ▶ return if $ss->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_denial_started"} 0 5 5
2292 5 $ss->{ws_denial_started} = 1;
2293 5 ▶ $ss->{ws_denial_status} = $event->{status} // 403;
Condition50%1/2
$event->{"status"} // 403
l!l
50
MC/DC0%0/1
$event->{"status"} // 403
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
2294 $ss->{ws_denial_headers} = [
2295 7 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
2296 5 ▶ @{$event->{headers} // []}
Condition50%1/2
$event->{"headers"} // []
l!l
50
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
2297 ];
2298 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2299 # transfer-encoding, etc. before submission.
2300 5 $ss->{ws_denial_headers} = _h2_strip_connection_headers($ss->{ws_denial_headers});
2301 5 $ss->{ws_denial_body} = '';
2302 }
2303 elsif ($type eq 'websocket.http.response.body') {
2304 6 ▶ return unless $ss->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_denial_started"} 0 6 6
2305 6 ▶ return if $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"response_started"} 0 6 6
2306 6 ▶ $ss->{ws_denial_body} .= $event->{body} // '';
Condition50%1/2
$event->{"body"} // ""
l!l
60
MC/DC0%0/1
$event->{"body"} // ""
$event->{"body"}
Truth table50%1/2
A
A= $event->{"body"}
Aresult
11
00
2307 6 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 1 5 6
2308  
2309 5 $ss->{response_started} = 1;
2310 5 ▶ unless (grep { lc($_->[0]) eq 'date' } @{$ss->{ws_denial_headers}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @{$$ss{"ws_denial_headers"};}) 5 0 5
2311 5 push @{$ss->{ws_denial_headers}}, ['date', $weak_self->{protocol}->format_date];
2312 }
2313 $weak_self->{h2_session}->submit_response($stream_id,
2314 status => $ss->{ws_denial_status},
2315 headers => $ss->{ws_denial_headers},
2316 body => $ss->{ws_denial_body},
2317 5 );
2318 5 $weak_self->_h2_write_pending;
2319 }
2320 elsif ($type eq 'websocket.close') {
2321 8 ▶ if (!$ss->{ws_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"ws_accepted"}) 3 5 8
2322 # Reject: send 403
2323 $weak_self->{h2_session}->submit_response($stream_id,
2324 status => 403,
2325 headers => [
2326 ['content-type', 'text/plain'],
2327 3 ['date', $weak_self->{protocol}->format_date],
2328 ],
2329 body => 'Forbidden',
2330 );
2331 3 $weak_self->_h2_write_pending;
2332 3 return;
2333 }
2334  
2335 # Close frame + END_STREAM, and release this stream's keepalive
2336 # (_h2_ws_close does both). Runs outside feed(), so flush here.
2337 $weak_self->_h2_ws_close($stream_id,
2338 5 ▶ $event->{code} // 1000, $event->{reason} // '');
Condition100%4/4
$event->{"code"} // 1000
l!l
41
$event->{"reason"} // ""
l!l
41
MC/DC100%1/1
$event->{"code"} // 1000
$event->{"code"}
MC/DC100%1/1
$event->{"reason"} // ""
$event->{"reason"}
Truth table100%2/2
A
A= $event->{"code"}
Aresult
11
00
Truth table100%2/2
A
A= $event->{"reason"}
Aresult
11
00
2339 5 $weak_self->_h2_write_pending;
2340 }
2341 elsif ($type eq 'websocket.keepalive') {
2342 11 ▶ return unless $ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_accepted"} 0 11 11
2343  
2344 11 ▶ my $interval = $event->{interval} // 0;
Condition50%1/2
$event->{"interval"} // 0
l!l
110
MC/DC0%0/1
$event->{"interval"} // 0
$event->{"interval"}
Truth table50%1/2
A
A= $event->{"interval"}
Aresult
11
00
2345 11 my $timeout = $event->{timeout};
2346  
2347 11 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 10 1 11
2348 10 $weak_self->_h2_start_ws_keepalive($stream_id, $ss, $interval, $timeout);
2349 }
2350 else {
2351 1 $weak_self->_h2_stop_ws_keepalive($ss);
2352 }
2353 }
2354  
2355 85 return;
2356 51 };
2357 }
2358  
2359 # =============================================================================
2360 # HTTP/2 SSE (Server-Sent Events over HTTP/2)
2361 # =============================================================================
2362  
2363 sub _h2_create_sse_scope {
2364 43 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_sse_scope: called CC=8 SCAR=23.9
2365  
2366 43 my $pseudo = $stream_state->{pseudo};
2367 43 my $headers = $stream_state->{headers};
2368  
2369 43 ▶ my $full_path = $pseudo->{':path'} // '/';
Condition50%1/2
$pseudo->{":path"} // "/"
l!l
430
MC/DC0%0/1
$pseudo->{":path"} // "/"
$pseudo->{":path"}
Truth table50%1/2
A
A= $pseudo->{":path"}
Aresult
11
00
2370 43 my ($path, $query_string) = split(/\?/, $full_path, 2);
2371 43 ▶ $query_string //= '';
Condition50%1/2
$query_string //= ""
l!l
043
MC/DC0%0/1
$query_string //= ""
$query_string
Truth table50%1/2
A
A= $query_string
Aresult
11
00
2372  
2373 # Match HTTP/1.1 pipeline: URI::Escape + UTF-8 decode with fallback
2374 43 my $unescaped = uri_unescape($path);
2375 43 ▶ my $decoded_path = eval { decode('UTF-8', $unescaped, Encode::FB_CROAK) }
Condition33%1/3
eval { do { &decode("UTF-8", $unescaped, 1) } } // $unescaped
l!l&&r!l&&!r
4300
MC/DC0%0/2
eval { do { &decode("UTF-8", $unescaped, 1) } } // $unescaped
eval { do { &decode("UTF-8", $unescaped, 1) } } $unescaped
Truth table33%1/3
A // B
A= eval { do { &decode("UTF-8", $unescaped, 1) } }B= $unescaped
ABresult
1X1
011
000
2376 // $unescaped;
2377  
2378 return {
2379 type => 'sse',
2380 pagi => {
2381 version => '0.5',
2382 spec_version => '0.5',
2383 },
2384 http_version => '2',
2385 method => $pseudo->{':method'} // 'GET',
2386 scheme => $pseudo->{':scheme'} // $self->_get_scheme,
2387 path => $decoded_path,
2388 raw_path => $path,
2389 query_string => $query_string,
2390 root_path => '',
2391 headers => $headers,
2392 (defined $self->{client_host}
2393 ? (client => [$self->{client_host}, $self->{client_port}])
2394 : ()
2395 ),
2396 server => [$self->{server_host}, $self->{server_port}],
2397 43 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
2398 extensions => $self->_get_extensions_for_scope,
2399 # Per-stream outbound flow-control handle. Like the h2 streaming scope,
2400 # it measures THIS stream's send queue (h2 multiplexes many streams over
2401 # one connection, so the shared TCP buffer is meaningless per stream).
2402 43 ▶ 'pagi.transport' => ($stream_state->{transport_state} = $self->_h2_transport_state($stream_state)),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 43 0 43
keys %{$$self{'state'};} ? : 0 43 43
Condition40%2/5
$pseudo->{":method"} // "GET"
l!l
430
$pseudo->{":scheme"} // $self->_get_scheme
l!l&&r!l&&!r
4300
MC/DC0%0/1
$pseudo->{":method"} // "GET"
$pseudo->{":method"}
MC/DC0%0/2
$pseudo->{":scheme"} // $self->_get_scheme
$pseudo->{":scheme"} $self->_get_scheme
Truth table50%1/2
A
A= $pseudo->{":method"}
Aresult
11
00
Truth table33%1/3
A // B
A= $pseudo->{":scheme"}B= $self->_get_scheme
ABresult
1X1
011
000
2403 };
2404 }
2405  
2406 sub _h2_create_sse_receive {
2407 42 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_sse_receive: called CC=1 SCAR=0.1
2408  
2409 42 weaken(my $weak_self = $self);
2410  
2411 my $sse_disconnect = sub {
2412 return {
2413 3 ▶ type => 'sse.disconnect',
Subroutine __ANON__: called CC=1 SCAR=0.0
2414 reason => 'client_closed',
2415 };
2416 42 };
2417  
2418 return sub {
2419 32 ▶ return Future->done($sse_disconnect->()) unless $weak_self;
Subroutine __ANON__: called CC=4 SCAR=14.2
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 32 32
2420 32 ▶ return Future->done($sse_disconnect->()) if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 32 32
2421  
2422 32 my $ss = $weak_self->{h2_streams}{$stream_id};
2423 32 ▶ return Future->done($sse_disconnect->()) unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 32 32
2424  
2425 32 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=15 SCAR=28.2
2426 32 ▶ return $sse_disconnect->() unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 32 32
2427  
2428 32 my $ss = $weak_self->{h2_streams}{$stream_id};
2429 32 ▶ return $sse_disconnect->() unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 32 32
2430  
2431 # Check queue first
2432 32 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 32 32
2433 0 return shift @{$ss->{receive_queue}};
2434 }
2435  
2436 # First call returns sse.request once the full body has arrived.
2437 # A POST body still streaming across DATA frames must not be
2438 # truncated behind a truthful more=>0 -- wait for body_complete
2439 # (set on END_STREAM or stream close, see _h2_on_body/_h2_on_close)
2440 # before delivering it as a single terminal event. This is the
2441 # smaller change relative to reworking sse.request into a
2442 # truthful multi-chunk stream: the wire shape here was already
2443 # one-shot, so completing that contract fixes the dispatch-timing
2444 # bug (design section 11.1) without touching the event shape.
2445 32 ▶ if (!$ss->{sse_request_sent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"sse_request_sent"}) 27 5 32
2446 27 ▶ while (!$ss->{body_complete}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_complete"}) 4 27 31
2447 4 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 4 4
2448 0 return shift @{$ss->{receive_queue}};
2449 }
2450  
2451 4 ▶ return $sse_disconnect->() if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 4 4
2452  
2453 4 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 4 0 4
2454 4 $ss->{body_pending} = Future->new;
2455 }
2456 4 await $ss->{body_pending};
2457  
2458 4 $ss = $weak_self->{h2_streams}{$stream_id};
2459 4 ▶ return $sse_disconnect->() unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 4 4
2460 }
2461  
2462 # body_complete can flip true on the very wake that also
2463 # queued a terminal event -- e.g. _h2_on_close sets
2464 # body_complete AND pushes sse.disconnect before waking
2465 # body_pending. That queued event must win over delivering
2466 # a (possibly truncated) body: the loop's own queue check
2467 # only runs at the top of an iteration, so a queue entry
2468 # that arrives on the wake that also satisfies the while
2469 # condition is never seen there.
2470 27 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 2 25 27
2471 2 return shift @{$ss->{receive_queue}};
2472 }
2473  
2474 25 $ss->{sse_request_sent} = 1;
2475 return {
2476 type => 'sse.request',
2477 body => $ss->{body},
2478 25 more => 0,
2479 };
2480 }
2481  
2482 # Wait for disconnect
2483 5 while (1) {
2484 10 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 2 8 10
2485 2 return shift @{$ss->{receive_queue}};
2486 }
2487  
2488 return $sse_disconnect->()
2489 8 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 3 5 8
2490  
2491 5 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 5 0 5
2492 5 $ss->{body_pending} = Future->new;
2493 }
2494 5 await $ss->{body_pending};
2495  
2496 5 $ss = $weak_self->{h2_streams}{$stream_id};
2497 5 ▶ return $sse_disconnect->() unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 5 5
2498 }
2499 32 })->();
2500  
2501 32 return $future;
2502 42 };
2503 }
2504  
2505 sub _h2_create_sse_send {
2506 42 ▶ my ($self, $stream_id, $stream_state) = @_;
Subroutine _h2_create_sse_send: called CC=1 SCAR=0.1
2507  
2508 42 weaken(my $weak_self = $self);
2509 42 my $seq = 'initial';
2510  
2511 # Streaming state for the data-provider pull pattern. The send queue lives on
2512 # per-stream state ($ss->{send_queue} / $ss->{send_queue_bytes}) so the
2513 # pagi.transport handle can measure THIS stream's backlog. $streaming_started
2514 # stays closure-local.
2515 42 my $streaming_started = 0;
2516  
2517 # Data callback for nghttp2's streaming response. Pulls from the per-stream
2518 # queue; SSE responses stay open, so this never signals EOF (returns eof=0),
2519 # or undef to defer when the queue is empty.
2520 my $data_callback = sub {
2521 163 ▶ my ($cb_stream_id, $max_len) = @_;
Subroutine __ANON__: called CC=15 SCAR=30.1
2522  
2523 163 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
00163
MC/DC0%0/2
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
$weak_self $weak_self->{'h2_streams'}{$stream_id}
Truth table33%1/3
A && B
A= $weak_selfB= $weak_self->{'h2_streams'}{$stream_id}
ABresult
0X0
100
111
2524 163 ▶ return undef unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 163 163
2525 163 ▶ my $q = $ss->{send_queue} ||= [];
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
1630
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2526  
2527 163 ▶ if (@$q) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$q) 65 98 163
2528 65 my $chunk = shift @$q;
2529 # Respect max_len — XS truncates without preserving remainder
2530 65 ▶ if (length($chunk) > $max_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk > $max_len) 4 61 65
2531 4 unshift @$q, substr($chunk, $max_len);
2532 4 $chunk = substr($chunk, 0, $max_len);
2533 }
2534 65 $ss->{send_queue_bytes} -= length($chunk);
2535  
2536 # Per-stream backpressure: once this stream's queue falls below the
2537 # low watermark, release any producer blocked in
2538 # _h2_wait_for_stream_drain. This runs inside nghttp2's extract(), so
2539 # resolve on the next loop tick — completing the Future resumes the
2540 # awaiting producer synchronously, and it must not re-enter nghttp2.
2541 65 ▶ if (($ss->{send_queue_bytes} // 0) < $weak_self->{write_low_watermark}
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}) 0 65 65
Condition50%4/8
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}
!ll&&!rl&&r
6500
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
3620
$ss->{"send_queue_bytes"} // 0
l!l
650
MC/DC0%0/3
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"} and @{$ss->{"stream_drain_waiters"};}
$ss->{"send_queue_bytes"} $ss->{"stream_drain_waiters"} @{$ss->{"stream_drain_waiters"};}
Truth table25%1/4
A and B and C
A= $ss->{"send_queue_bytes"}B= $ss->{"stream_drain_waiters"}C= @{$ss->{"stream_drain_waiters"};}
ABCresult
0XX0
10X0
1100
1111
2542 0 && $ss->{stream_drain_waiters} && @{$ss->{stream_drain_waiters}}) {
2543 0 my @waiters = splice @{$ss->{stream_drain_waiters}};
2544 $weak_self->{server}->loop->later(sub {
2545 0 ▶ $_->done for grep { !$_->is_ready } @waiters;
Subroutine __ANON__: not called CC=2 SCAR=17.9
2546 0 });
2547 }
2548  
2549 # Fire the app's on_drain hysteresis callbacks once this stream's
2550 # queue falls below the low watermark. Deferred for the same reason:
2551 # an on_drain callback may call $send, which would re-enter nghttp2.
2552 65 ▶ if (($ss->{send_queue_bytes} // 0) < $weak_self->{write_low_watermark}
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}) 1 64 65
Condition75%6/8
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}
!ll&&!rl&&r
6401
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"}
!ll&&!rl&&r
3611
$ss->{"send_queue_bytes"} // 0
l!l
650
MC/DC33%1/3
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"} and @{$ss->{"transport_drain_fires"};}
$ss->{"send_queue_bytes"} $ss->{"transport_drain_fires"} @{$ss->{"transport_drain_fires"};}
Truth table50%2/4
A and B and C
A= $ss->{"send_queue_bytes"}B= $ss->{"transport_drain_fires"}C= @{$ss->{"transport_drain_fires"};}
ABCresult
0XX0
10X0
1100
1111
2553 1 && $ss->{transport_drain_fires} && @{$ss->{transport_drain_fires}}) {
2554 1 my @fires = splice @{$ss->{transport_drain_fires}};
2555 $weak_self->{server}->loop->later(sub {
2556 1 ▶ $_->() for @fires;
Subroutine __ANON__: called CC=2 SCAR=6.9
2557 1 });
2558 }
2559  
2560 65 return ($chunk, 0); # SSE streams never EOF via data_callback
2561 }
2562  
2563 # Queue empty. If the application closed this stream (sse.close), emit a
2564 # final empty DATA frame with END_STREAM to terminate it; otherwise defer.
2565 98 ▶ return ('', 1) if $ss->{sse_closing};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_closing"} 7 91 98
2566  
2567 # Queue empty — defer (NGHTTP2_ERR_DEFERRED in the C layer)
2568 91 return undef;
2569 42 };
2570  
2571 115 ▶ return async sub {
Subroutine __ANON__: called CC=57 SCAR=44.5
2572 115 my ($event) = @_;
2573 115 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 115 115
2574  
2575 115 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
1150
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
2576  
2577 # Once the machine has already recorded this stream as closed --
2578 # either an app-initiated sse.close or a completed decline response
2579 # -- the machine, not the stream-gone check below, decides what
2580 # happens next: idempotent no-op for a repeat sse.close, croak for
2581 # anything else (decline_complete has no idempotent case; it croaks
2582 # unconditionally). h2_streams entries for a closed stream are
2583 # reclaimed asynchronously by _h2_on_close, so by the time a
2584 # post-close send arrives $ss may already be gone.
2585 115 ▶ my $already_closed = ($seq eq 'closed' || $seq eq 'decline_complete');
Condition100%3/3
$seq eq 'closed' || $seq eq 'decline_complete'
l!l&&r!l&&!r
21112
MC/DC100%2/2
$seq eq 'closed' || $seq eq 'decline_complete'
$seq eq 'closed' $seq eq 'decline_complete'
Truth table100%3/3
A || B
A= $seq eq 'closed'B= $seq eq 'decline_complete'
ABresult
1X1
011
000
2586  
2587 115 my $ss = $weak_self->{h2_streams}{$stream_id};
2588 # A doomed-but-still-present entry (h2_closed set but not yet
2589 # deleted -- see the 413-overrun branch in _h2_on_body) is treated
2590 # the same as an absent one: both are post-close sends and must
2591 # silently no-op, not reach nghttp2 a second time on this stream id.
2592 115 ▶ return if (!$ss || $ss->{h2_closed}) && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if !$ss || $ss->{"h2_closed"} and not $already_closed 1 114 115
Condition83%5/6
!$ss || $ss->{"h2_closed"} and not $already_closed
!ll&&!rl&&r
11131
not $ss or $ss->{"h2_closed"}
l!l&&r!l&&!r
04111
MC/DC66%2/3
!$ss || $ss->{"h2_closed"} and not $already_closed
not $ss $ss->{"h2_closed"} not $already_closed
Truth table60%3/5
not(A) or B and not(C)
A= not $ssB= $ss->{"h2_closed"}C= not $already_closed
ABCresult
00X0
1X00
0100
1X11
0111
2593  
2594 114 ▶ return if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 0 114 114
Condition33%1/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
11400
MC/DC0%0/2
$weak_self->{"closed"} and not $already_closed
$weak_self->{"closed"} not $already_closed
Truth table33%1/3
A and not(B)
A= $weak_self->{"closed"}B= not $already_closed
ABresult
0X0
100
111
2595  
2596 # Reset THIS stream's SSE idle timer on send activity (skip once fully closed)
2597 114 ▶ $weak_self->_h2_reset_sse_idle_timer($ss) unless $already_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $already_closed 111 3 114
2598  
2599 # Mandatory event validation and sequencing (PAGI spec compliance).
2600 PAGI::Server::EventValidator::validate_sse_send(
2601 114 $event, { extensions => $weak_self->{extensions} });
2602 114 $seq = PAGI::Server::EventValidator::advance_sse($seq, $event);
2603  
2604 109 ▶ if ($type eq 'sse.start') {
Branch: 8 branches
BranchTrueFalseTotal
if ($type eq 'sse.start') { } 29 80 109
elsif ($type eq 'sse.send') { } 43 37 80
elsif ($type eq 'sse.comment') { } 2 35 37
elsif ($type eq 'sse.keepalive') { } 6 29 35
elsif ($type eq 'sse.close') { } 5 24 29
elsif ($type eq 'sse.http.response.start') { } 11 13 24
elsif ($type eq 'sse.http.response.body') { } 12 1 13
elsif ($type eq 'http.fullflush') { } 1 0 1
2605 29 ▶ return if $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"response_started"} 0 29 29
2606 29 $ss->{response_started} = 1;
2607  
2608 29 ▶ my $status = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
290
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
2609 29 ▶ my $headers = $event->{headers} // [];
Condition100%2/2
$event->{"headers"} // []
l!l
227
MC/DC100%1/1
$event->{"headers"} // []
$event->{"headers"}
Truth table100%2/2
A
A= $event->{"headers"}
Aresult
11
00
2610  
2611 # Ensure Content-Type is text/event-stream
2612 29 my $has_content_type = 0;
2613 29 for my $h (@$headers) {
2614 4 ▶ if (lc($h->[0]) eq 'content-type') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-type") 1 3 4
2615 1 $has_content_type = 1;
2616 1 last;
2617 }
2618 }
2619  
2620 29 my @final_headers;
2621 29 for my $h (@$headers) {
2622 6 push @final_headers, [_validate_header_name($h->[0]), _validate_header_value($h->[1])];
2623 }
2624 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2625 # transfer-encoding, etc. before submission.
2626 29 @final_headers = @{ _h2_strip_connection_headers(\@final_headers) };
2627 29 ▶ if (!$has_content_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_type) 28 1 29
2628 28 push @final_headers, ['content-type', 'text/event-stream'];
2629 }
2630 # Cache-Control and Date: server-supplied only when the app didn't
2631 # supply them (design doc section 11.4).
2632 29 ▶ unless (grep { lc($_->[0]) eq 'cache-control' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "cache-control";} @final_headers) 28 1 29
2633 28 push @final_headers, ['cache-control', 'no-cache'];
2634 }
2635 # Server-supplied Date header (HTTP/1.1 parity) — the h1 SSE path adds
2636 # this too; add it unless the app supplied one.
2637 29 ▶ unless (grep { lc($_->[0]) eq 'date' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @final_headers) 28 1 29
2638 28 push @final_headers, ['date', $weak_self->{protocol}->format_date];
2639 }
2640  
2641 29 $streaming_started = 1;
2642 29 ▶ $ss->{send_queue} //= [];
Condition50%1/2
$ss->{"send_queue"} //= []
l!l
029
MC/DC0%0/1
$ss->{"send_queue"} //= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2643 29 ▶ $ss->{send_queue_bytes} //= 0;
Condition50%1/2
$ss->{"send_queue_bytes"} //= 0
l!l
029
MC/DC0%0/1
$ss->{"send_queue_bytes"} //= 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2644 $weak_self->{h2_session}->submit_response_streaming(
2645 29 $stream_id,
2646 status => $status,
2647 headers => \@final_headers,
2648 data_callback => $data_callback,
2649 );
2650 29 $weak_self->_h2_write_pending;
2651  
2652 # Protocol-specific keepalive writer (HTTP/2 DATA frames), scoped to
2653 # THIS stream (design section 11.3): a second multiplexed SSE stream
2654 # must not steal or replace this one's writer. Keepalive bytes are
2655 # counted in the per-stream backlog so buffered_amount stays
2656 # accurate, but they do not poke the watermark callbacks — a server
2657 # heartbeat is not an application send.
2658 $ss->{sse_ka_writer} = sub {
2659 18 ▶ my ($text) = @_;
Subroutine __ANON__: called CC=7 SCAR=20.5
2660 18 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 18 18
2661 18 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 18 18
2662 18 ▶ my $ss = $weak_self->{h2_streams}{$stream_id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $ss = $weak_self->{"h2_streams"}{$stream_id} or return 0 18 18
2663 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at
2664 # the wire boundary — all queue-length math below is on the
2665 # resulting BYTE string.
2666 18 my $bytes = eval { Encode::encode('UTF-8', $text, Encode::FB_CROAK) };
2667 18 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 18 18
2668 18 ▶ push @{$ss->{send_queue} ||= []}, $bytes;
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
180
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2669 18 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
180
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2670 18 $weak_self->{h2_session}->resume_stream($stream_id);
2671 18 $weak_self->_h2_write_pending;
2672 29 };
2673  
2674 # Start THIS stream's SSE idle timer if configured
2675 29 $weak_self->_h2_start_sse_idle_timer($stream_id, $ss);
2676 }
2677 elsif ($type eq 'sse.send') {
2678 43 ▶ return unless $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"response_started"} 0 43 43
2679  
2680 # Per-stream backpressure: bound on THIS stream's queue, not the
2681 # shared TCP buffer (meaningless across multiplexed h2 streams).
2682 43 ▶ if (($ss->{send_queue_bytes} // 0) >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) >= $weak_self->{"write_high_watermark"}) 0 43 43
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
430
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2683 0 await $weak_self->_h2_wait_for_stream_drain($stream_id);
2684 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
2685 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
2686 0 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 0 0
2687 }
2688  
2689 43 my $sse_data = _format_sse_event($event);
2690 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at the
2691 # wire boundary — a failed encode fails this send's Future.
2692 43 my $bytes = eval { Encode::encode('UTF-8', $sse_data, Encode::FB_CROAK) };
2693 43 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 1 42 43
2694 42 ▶ push @{$ss->{send_queue} ||= []}, $bytes;
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
420
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2695 42 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
420
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2696 # Synchronous — app send path, not nghttp2 extract — so on_high_water
2697 # may fire here to tell the app to pause its source.
2698 42 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 42 0 42
2699 42 $weak_self->{h2_session}->resume_stream($stream_id);
2700 42 $weak_self->_h2_write_pending;
2701 }
2702 elsif ($type eq 'sse.comment') {
2703 2 ▶ return unless $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"response_started"} 0 2 2
2704  
2705 2 my $comment = _format_sse_comment($event);
2706 2 my $bytes = eval { Encode::encode('UTF-8', $comment, Encode::FB_CROAK) };
2707 2 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 2 2
2708 2 ▶ push @{$ss->{send_queue} ||= []}, $bytes;
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
20
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2709 2 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
20
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
2710 2 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 2 0 2
2711 2 $weak_self->{h2_session}->resume_stream($stream_id);
2712 2 $weak_self->_h2_write_pending;
2713 }
2714 elsif ($type eq 'sse.keepalive') {
2715 6 ▶ my $interval = $event->{interval} // 0;
Condition50%1/2
$event->{"interval"} // 0
l!l
60
MC/DC0%0/1
$event->{"interval"} // 0
$event->{"interval"}
Truth table50%1/2
A
A= $event->{"interval"}
Aresult
11
00
2716 6 my $comment = $event->{comment};
2717  
2718 6 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 6 0 6
2719 6 $weak_self->_h2_start_sse_keepalive($stream_id, $ss, $interval, $comment);
2720 }
2721 else {
2722 0 $weak_self->_h2_stop_sse_keepalive($ss);
2723 }
2724 }
2725 elsif ($type eq 'sse.close') {
2726 # A repeat sse.close after the stream's h2_streams entry has
2727 # already been reclaimed (see the already-closed comment above)
2728 # is the idempotent no-op advance_sse just allowed; nothing left
2729 # to do.
2730 5 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 5 5
2731  
2732 # This stream is ending -- stop its keepalive and idle timers so
2733 # neither fires (or leaks) after the stream is reclaimed.
2734 5 $weak_self->_h2_stop_sse_keepalive($ss);
2735 5 $weak_self->_h2_stop_sse_idle_timer($ss);
2736  
2737 # End THIS HTTP/2 stream now: flush remaining queued events, then the
2738 # data_callback emits a final END_STREAM frame. `reason` is
2739 # server-side only and is never written to the wire.
2740 5 $ss->{sse_close_sent} = 1;
2741 5 $ss->{sse_closing} = 1;
2742 $weak_self->{sse_disconnect_reason} = $event->{reason}
2743 5 ▶ if defined $event->{reason};
Branch: 1 branch
BranchTrueFalseTotal
if defined $event->{"reason"} 1 4 5
2744 5 $weak_self->{h2_session}->resume_stream($stream_id);
2745 5 $weak_self->_h2_write_pending;
2746 }
2747 elsif ($type eq 'sse.http.response.start') {
2748 # A decline-after-start attempt is already rejected by advance_sse.
2749 11 ▶ return if $ss->{sse_decline_started}; # idempotent
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_decline_started"} 0 11 11
2750 11 $ss->{sse_decline_started} = 1;
2751 11 ▶ $ss->{sse_decline_status} = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
110
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
2752 $ss->{sse_decline_headers} = [
2753 7 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
2754 11 ▶ @{$event->{headers} // []}
Condition50%1/2
$event->{"headers"} // []
l!l
110
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
2755 ];
2756 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2757 # transfer-encoding, etc. before submission.
2758 11 $ss->{sse_decline_headers} = _h2_strip_connection_headers($ss->{sse_decline_headers});
2759 11 $ss->{sse_decline_body} = '';
2760 }
2761 elsif ($type eq 'sse.http.response.body') {
2762 12 ▶ return unless $ss->{sse_decline_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"sse_decline_started"} 0 12 12
2763 12 ▶ return if $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"response_started"} 0 12 12
2764 12 ▶ $ss->{sse_decline_body} .= $event->{body} // '';
Condition50%1/2
$event->{"body"} // ""
l!l
120
MC/DC0%0/1
$event->{"body"} // ""
$event->{"body"}
Truth table50%1/2
A
A= $event->{"body"}
Aresult
11
00
2765 12 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 1 11 12
2766  
2767 # Defensive: the send-sequence state machine never permits
2768 # sse.keepalive before sse.start, so neither timer can actually be
2769 # armed here -- stopped anyway for the same every-closure-path
2770 # discipline the other SSE/WS stop sites follow.
2771 11 $weak_self->_h2_stop_sse_keepalive($ss);
2772 11 $weak_self->_h2_stop_sse_idle_timer($ss);
2773  
2774 11 $ss->{response_started} = 1;
2775 11 ▶ unless (grep { lc($_->[0]) eq 'date' } @{$ss->{sse_decline_headers}}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @{$$ss{"sse_decline_headers"};}) 11 0 11
2776 11 push @{$ss->{sse_decline_headers}}, ['date', $weak_self->{protocol}->format_date];
2777 }
2778 $weak_self->{h2_session}->submit_response($stream_id,
2779 status => $ss->{sse_decline_status},
2780 headers => $ss->{sse_decline_headers},
2781 body => $ss->{sse_decline_body},
2782 11 );
2783 11 $weak_self->_h2_write_pending;
2784 }
2785 elsif ($type eq 'http.fullflush') {
2786 # Hand any pending frames to the session's write path (design §8.4).
2787 1 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 1 0 1
2788 1 $weak_self->_h2_write_pending;
2789 }
2790  
2791 107 return;
2792 42 };
2793 }
2794  
2795 sub _h2_process_ws_frames {
2796 55 ▶ my ($self, $stream_id, $stream, $data) = @_;
Subroutine _h2_process_ws_frames: called CC=40 SCAR=38.0
2797  
2798 55 my $frame = $stream->{ws_frame};
2799 55 ▶ return unless $frame;
Branch: 1 branch
BranchTrueFalseTotal
unless $frame 0 55 55
2800  
2801 55 $frame->append($data);
2802  
2803 55 ▶ while (defined(my $bytes = $frame->next_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $bytes = $frame->next_bytes)) 49 40 89
2804 49 my $opcode = $frame->opcode;
2805  
2806 # RFC 6455 Section 5.2: RSV1-3 MUST be 0 unless extension defines
2807 # meaning. PAGI doesn't support compression extensions, so RSV must
2808 # always be 0. Same enforcement as h1's _process_websocket_frames
2809 # (Www.pod: transport-agnostic framing enforcement, and RFC 8441's
2810 # "identical to HTTP/1.1" claim).
2811 49 my $rsv = $frame->rsv;
2812 49 ▶ if ($rsv && ref($rsv) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rsv and ref $rsv eq "ARRAY") 49 0 49
Condition33%1/3
$rsv and ref $rsv eq "ARRAY"
!ll&&!rl&&r
0049
MC/DC0%0/2
$rsv and ref $rsv eq "ARRAY"
$rsv ref $rsv eq "ARRAY"
Truth table33%1/3
A and B
A= $rsvB= ref $rsv eq "ARRAY"
ABresult
0X0
100
111
2813 49 ▶ if (grep { $_ } @$rsv) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_;} @$rsv) 1 48 49
2814 1 $self->_h2_ws_close($stream_id, 1002, 'RSV bits must be 0');
2815 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2816 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2817 1 return;
2818 }
2819 }
2820  
2821 # RFC 6455 Section 5.2: Opcodes 3-7 and 11-15 (0xB-0xF) are reserved.
2822 # Must fail connection with 1002 Protocol Error.
2823 48 ▶ if (($opcode >= 3 && $opcode <= 7) || ($opcode >= 11 && $opcode <= 15)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15) 1 47 48
Condition66%6/9
$opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15
l!l&&r!l&&!r
1047
$opcode >= 3 and $opcode <= 7
!ll&&!rl&&r
34131
$opcode >= 11 and $opcode <= 15
!ll&&!rl&&r
4700
MC/DC0%0/4
$opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15
$opcode >= 3 $opcode <= 7 $opcode >= 11 $opcode <= 15
Truth table14%1/7
A and B or C and D
A= $opcode >= 3B= $opcode <= 7C= $opcode >= 11D= $opcode <= 15
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
2824 1 $self->_h2_ws_close($stream_id, 1002, 'Reserved opcode');
2825 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2826 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2827 1 return;
2828 }
2829  
2830 # RFC 6455 Section 5.5: Control frames (close/ping/pong) MUST have
2831 # payload length <= 125 bytes.
2832 47 ▶ if (($opcode == 8 || $opcode == 9 || $opcode == 10) && length($bytes) > 125) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode == 8 || $opcode == 9 || $opcode == 10 and length $bytes > 125) 1 46 47
Condition100%9/9
$opcode == 8 || $opcode == 9 || $opcode == 10 and length $bytes > 125
!ll&&!rl&&r
34121
$opcode == 8 or $opcode == 9 or $opcode == 10
l!l&&r!l&&!r
8534
$opcode == 8 or $opcode == 9
l!l&&r!l&&!r
6239
MC/DC50%2/4
$opcode == 8 || $opcode == 9 || $opcode == 10 and length $bytes > 125
$opcode == 8 $opcode == 9 $opcode == 10 length $bytes > 125
Truth table71%5/7
A or B or C and D
A= $opcode == 8B= $opcode == 9C= $opcode == 10D= length $bytes > 125
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
2833 1 $self->_h2_ws_close($stream_id, 1002, 'Control frame too large');
2834 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2835 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2836 1 return;
2837 }
2838  
2839 46 ▶ if ($opcode == 1) {
Branch: 5 branches
BranchTrueFalseTotal
if ($opcode == 1) { } 33 13 46
elsif ($opcode == 2) { } 1 12 13
elsif ($opcode == 8) { } 6 6 12
elsif ($opcode == 9) { } 1 5 6
elsif ($opcode == 10) { } 5 0 5
2840 # Text frame
2841 33 my $text = eval { Encode::decode('UTF-8', $bytes, Encode::FB_CROAK) };
2842 33 ▶ unless (defined $text) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $text) 2 31 33
2843 2 $self->_h2_ws_close($stream_id, 1007, 'Invalid UTF-8');
2844 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2845 2 $self->_h2_ws_enqueue_disconnect($stream, 1007, 'protocol_error');
2846 2 return;
2847 }
2848 # Check queue limit before adding (DoS protection) -- same cap
2849 # and pairing h1 enforces (Www.pod pins 1008 <-> queue_overflow).
2850 31 ▶ if (@{$stream->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stream->{"receive_queue"};} >= $self->{"max_receive_queue"}) 7 24 31
2851 7 $self->_h2_ws_close($stream_id, 1008, 'Message queue overflow');
2852 7 $self->_h2_ws_enqueue_disconnect($stream, 1008, 'queue_overflow');
2853 7 return;
2854 }
2855 24 push @{$stream->{receive_queue}}, {
2856 type => 'websocket.receive',
2857 text => $text,
2858 };
2859 }
2860 elsif ($opcode == 2) {
2861 # Binary frame
2862 # Check queue limit before adding (DoS protection) -- same cap
2863 # and pairing h1 enforces (Www.pod pins 1008 <-> queue_overflow).
2864 1 ▶ if (@{$stream->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stream->{"receive_queue"};} >= $self->{"max_receive_queue"}) 0 1 1
2865 0 $self->_h2_ws_close($stream_id, 1008, 'Message queue overflow');
2866 0 $self->_h2_ws_enqueue_disconnect($stream, 1008, 'queue_overflow');
2867 0 return;
2868 }
2869 1 push @{$stream->{receive_queue}}, {
2870 type => 'websocket.receive',
2871 bytes => $bytes,
2872 };
2873 }
2874 elsif ($opcode == 8) {
2875 # Close frame -- the WS session on this stream is ending, one way
2876 # or another (a validation failure below closes it too), so stop
2877 # this stream's keepalive up front.
2878 6 $self->_h2_stop_ws_keepalive($stream);
2879  
2880 6 my ($code, $reason) = (1005, '');
2881  
2882 # RFC 6455 Section 5.5.1: Close frame payload is 0 or >=2 bytes
2883 6 ▶ if (length($bytes) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes == 1) 1 5 6
2884 1 $self->_h2_ws_close($stream_id, 1002, 'Invalid close frame');
2885 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2886 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2887 1 return;
2888 }
2889  
2890 5 ▶ if (length($bytes) >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes >= 2) 4 1 5
2891 4 $code = unpack('n', substr($bytes, 0, 2));
2892 4 ▶ $reason = substr($bytes, 2) // '';
Condition50%1/2
substr($bytes, 2) // ""
l!l
40
MC/DC0%0/1
substr($bytes, 2) // ""
substr($bytes, 2)
Truth table50%1/2
A
A= substr($bytes, 2)
Aresult
11
00
2893  
2894 # RFC 6455 Section 7.4.1: Validate close code
2895 4 my $valid_code = 0;
2896 4 ▶ if ($code == 1000 || $code == 1001 || $code == 1002 || $code == 1003) {
Branch: 3 branches
BranchTrueFalseTotal
if ($code == 1000 or $code == 1001 or $code == 1002 or $code == 1003) { } 2 2 4
elsif ($code >= 1007 and $code <= 1011) { } 0 2 2
elsif ($code >= 3000 and $code <= 4999) { } 1 2 3
Condition66%6/9
$code == 1000 or $code == 1001 or $code == 1002 or $code == 1003
l!l&&r!l&&!r
202
$code == 1000 or $code == 1001 or $code == 1002
l!l&&r!l&&!r
202
$code == 1000 or $code == 1001
l!l&&r!l&&!r
202
MC/DC25%1/4
$code == 1000 or $code == 1001 or $code == 1002 or $code == 1003
$code == 1000 $code == 1001 $code == 1002 $code == 1003
Truth table40%2/5
A or B or C or D
A= $code == 1000B= $code == 1001C= $code == 1002D= $code == 1003
ABCDresult
1XXX1
01XX1
001X1
00011
00000
2897 2 $valid_code = 1;
2898 }
2899 ▶ elsif ($code >= 1007 && $code <= 1011) {
Condition66%2/3
$code >= 1007 and $code <= 1011
!ll&&!rl&&r
110
MC/DC0%0/2
$code >= 1007 and $code <= 1011
$code >= 1007 $code <= 1011
Truth table66%2/3
A and B
A= $code >= 1007B= $code <= 1011
ABresult
0X0
100
111
2900 0 $valid_code = 1;
2901 }
2902 ▶ elsif ($code >= 3000 && $code <= 4999) {
Condition66%2/3
$code >= 3000 and $code <= 4999
!ll&&!rl&&r
101
MC/DC50%1/2
$code >= 3000 and $code <= 4999
$code >= 3000 $code <= 4999
Truth table66%2/3
A and B
A= $code >= 3000B= $code <= 4999
ABresult
0X0
100
111
2903 1 $valid_code = 1;
2904 }
2905 4 ▶ unless ($valid_code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid_code) 1 3 4
2906 1 $self->_h2_ws_close($stream_id, 1002, 'Invalid close code');
2907 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2908 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2909 1 return;
2910 }
2911  
2912 # RFC 6455: Close reason must be valid UTF-8
2913 3 ▶ if (length($reason) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $reason > 0) 3 0 3
2914 3 my $reason_copy = $reason;
2915 3 my $decoded = eval { Encode::decode('UTF-8', $reason_copy, Encode::FB_CROAK) };
2916 3 ▶ unless (defined $decoded) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $decoded) 1 2 3
2917 1 $self->_h2_ws_close($stream_id, 1007, 'Invalid UTF-8 in close reason');
2918 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2919 1 $self->_h2_ws_enqueue_disconnect($stream, 1007, 'protocol_error');
2920 1 return;
2921 }
2922 }
2923 }
2924  
2925 # Send close frame back + END_STREAM. Queued (not submit_data)
2926 # so the data_callback's own eof_pending merge puts END_STREAM on
2927 # this exact chunk, same as the previous submit_data(..., 1) did.
2928 # Not an application send — no transport_state->_check_watermarks.
2929 3 my $close_frame = Protocol::WebSocket::Frame->new(
2930 type => 'close',
2931 buffer => pack('n', $code) . $reason,
2932 );
2933 3 my $close_bytes = $close_frame->to_bytes;
2934 3 ▶ push @{$stream->{send_queue} ||= []}, $close_bytes;
Condition50%1/2
$stream->{"send_queue"} ||= []
l!l
30
MC/DC0%0/1
$stream->{"send_queue"} ||= []
$stream->{"send_queue"}
Truth table50%1/2
A
A= $stream->{"send_queue"}
Aresult
11
00
2935 3 ▶ $stream->{send_queue_bytes} = ($stream->{send_queue_bytes} // 0) + length $close_bytes;
Condition50%1/2
$stream->{"send_queue_bytes"} // 0
l!l
30
MC/DC0%0/1
$stream->{"send_queue_bytes"} // 0
$stream->{"send_queue_bytes"}
Truth table50%1/2
A
A= $stream->{"send_queue_bytes"}
Aresult
11
00
2936 3 $stream->{ws_eof_pending} = 1;
2937 3 $self->{h2_session}->resume_stream($stream_id);
2938 # No _h2_write_pending — inside feed(); flushed by _h2_process_data
2939  
2940 # Peer's Close frame: its own code (1005 default when the frame
2941 # carried none) and reason text (Www.pod "Disconnect - receive event").
2942 3 $self->_h2_ws_enqueue_disconnect($stream, $code, $reason);
2943 }
2944 elsif ($opcode == 9) {
2945 # Ping — respond with pong. Queued, not an application send.
2946 1 my $pong = Protocol::WebSocket::Frame->new(
2947 type => 'pong',
2948 buffer => $bytes,
2949 );
2950 1 my $pong_bytes = $pong->to_bytes;
2951 1 ▶ push @{$stream->{send_queue} ||= []}, $pong_bytes;
Condition50%1/2
$stream->{"send_queue"} ||= []
l!l
10
MC/DC0%0/1
$stream->{"send_queue"} ||= []
$stream->{"send_queue"}
Truth table50%1/2
A
A= $stream->{"send_queue"}
Aresult
11
00
2952 1 ▶ $stream->{send_queue_bytes} = ($stream->{send_queue_bytes} // 0) + length $pong_bytes;
Condition50%1/2
$stream->{"send_queue_bytes"} // 0
l!l
10
MC/DC0%0/1
$stream->{"send_queue_bytes"} // 0
$stream->{"send_queue_bytes"}
Truth table50%1/2
A
A= $stream->{"send_queue_bytes"}
Aresult
11
00
2953 1 $self->{h2_session}->resume_stream($stream_id);
2954 # No _h2_write_pending — inside feed(); flushed by _h2_process_data
2955 }
2956 elsif ($opcode == 10) {
2957 # Pong — clear this stream's keepalive wait flag (response to
2958 # our own ping); cancel only the per-stream pong-timeout
2959 # Countdown, not the periodic ping timer itself.
2960 5 $self->_h2_cancel_ws_pong_timeout($stream);
2961 }
2962 }
2963  
2964 40 $self->_h2_wake_pending($stream);
2965 }
2966  
2967 # Send a Close frame with END_STREAM on one h2 WebSocket stream. The WS
2968 # session on that stream is over once this returns, so this is also where
2969 # the stream's keepalive is released -- every closure path funnels through
2970 # here, and releasing it at the funnel is what keeps a ping timer from
2971 # outliving its stream (it would otherwise keep pinging a half-closed
2972 # stream for the life of the connection).
2973 #
2974 # Callers inside feed() need no flush (_h2_process_data flushes after
2975 # feed() returns); callers outside it must call _h2_write_pending
2976 # themselves.
2977 sub _h2_ws_close {
2978 20 ▶ my ($self, $stream_id, $code, $reason) = @_;
Subroutine _h2_ws_close: called CC=6 SCAR=18.3
2979  
2980 20 my $ss = $self->{h2_streams}{$stream_id};
2981 20 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 20 20
2982  
2983 # Idempotency guard: a stream already closing (a Close frame already
2984 # queued, ws_eof_pending true) must not queue a second one. Without
2985 # this, a burst of several frames that each independently warrant
2986 # closure -- e.g. more inbound messages than max_receive_queue allows,
2987 # already buffered in the parser before the first violation's `return`
2988 # unwinds -- re-enters this sub once per remaining buffered frame (each
2989 # later call to _h2_process_ws_frames resumes parsing where the last
2990 # one left off) and would otherwise queue one Close frame per frame
2991 # instead of the one the wire is supposed to see.
2992 20 ▶ return if $ss->{ws_eof_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_eof_pending"} 6 14 20
2993  
2994 14 $self->_h2_stop_ws_keepalive($ss);
2995  
2996 # Queued (not submit_data) so the data_callback's own eof_pending merge
2997 # puts END_STREAM on this exact chunk, same as the previous
2998 # submit_data(..., 1) did.
2999 14 ▶ my $frame = Protocol::WebSocket::Frame->new(
Condition50%1/2
$reason // ""
l!l
140
MC/DC0%0/1
$reason // ""
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
3000 type => 'close',
3001 buffer => pack('n', $code) . ($reason // ''),
3002 );
3003 14 my $bytes = $frame->to_bytes;
3004 14 ▶ push @{$ss->{send_queue} ||= []}, $bytes;
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
140
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
3005 14 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
140
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
3006 14 $ss->{ws_eof_pending} = 1;
3007 14 $self->{h2_session}->resume_stream($stream_id);
3008 }
3009  
3010 # HTTP/2 per-stream WebSocket keepalive (design section 10.2 -- the h2
3011 # analogue of _start_ws_keepalive/_stop_ws_keepalive). h1 shares one TCP
3012 # stream per connection, so its keepalive state and timers live on $self;
3013 # h2 multiplexes many WebSocket streams per connection, so this state and
3014 # these timers live on the per-stream hash ($ss, aka $self->{h2_streams}
3015 # {$stream_id}) and the ping is delivered as an h2 DATA frame via the
3016 # stream's own send queue + data-provider callback, same as every other
3017 # ws frame on this stream, rather than a raw stream write.
3018 sub _h2_start_ws_keepalive {
3019 10 ▶ my ($self, $stream_id, $ss, $interval, $timeout) = @_;
Subroutine _h2_start_ws_keepalive: called CC=5 SCAR=16.5
3020  
3021 # Last event wins: stop whatever was running before applying new settings.
3022 10 $self->_h2_stop_ws_keepalive($ss);
3023  
3024 10 ▶ return unless $interval && $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $interval and $interval > 0 0 10 10
Condition33%1/3
$interval and $interval > 0
!ll&&!rl&&r
0010
MC/DC0%0/2
$interval and $interval > 0
$interval $interval > 0
Truth table33%1/3
A and B
A= $intervalB= $interval > 0
ABresult
0X0
100
111
3025 10 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 10 10
3026  
3027 10 $ss->{ws_ka_interval} = $interval;
3028 10 ▶ $ss->{ws_ka_timeout} = $timeout // 0;
Condition100%2/2
$timeout // 0
l!l
46
MC/DC100%1/1
$timeout // 0
$timeout
Truth table100%2/2
A
A= $timeout
Aresult
11
00
3029  
3030 10 weaken(my $weak_self = $self);
3031 10 weaken(my $weak_ss = $ss);
3032  
3033 my $timer = IO::Async::Timer::Periodic->new(
3034 interval => $interval,
3035 on_tick => sub {
3036 40 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=8 SCAR=21.6
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 40 40
3037 40 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 40 40
3038 40 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 40 40
3039 40 ▶ return unless $weak_ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss->{"ws_accepted"} 0 40 40
3040  
3041 # Queued, not an application send (no transport_state watermark
3042 # poke) -- this timer callback runs outside feed(), so resume
3043 # AND flush explicitly, unlike the in-feed() queue pushes above.
3044 40 my $ping = Protocol::WebSocket::Frame->new(
3045 type => 'ping',
3046 buffer => '',
3047 );
3048 40 my $ping_bytes = $ping->to_bytes;
3049 40 ▶ push @{$weak_ss->{send_queue} ||= []}, $ping_bytes;
Condition50%1/2
$weak_ss->{"send_queue"} ||= []
l!l
400
MC/DC0%0/1
$weak_ss->{"send_queue"} ||= []
$weak_ss->{"send_queue"}
Truth table50%1/2
A
A= $weak_ss->{"send_queue"}
Aresult
11
00
3050 40 ▶ $weak_ss->{send_queue_bytes} = ($weak_ss->{send_queue_bytes} // 0) + length $ping_bytes;
Condition50%1/2
$weak_ss->{"send_queue_bytes"} // 0
l!l
400
MC/DC0%0/1
$weak_ss->{"send_queue_bytes"} // 0
$weak_ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $weak_ss->{"send_queue_bytes"}
Aresult
11
00
3051 40 $weak_self->{h2_session}->resume_stream($stream_id);
3052 40 $weak_self->_h2_write_pending;
3053  
3054 # Start pong timeout if configured
3055 40 ▶ if ($weak_ss->{ws_ka_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_ss->{"ws_ka_timeout"} > 0) 10 30 40
3056 10 $weak_ss->{ws_ka_waiting_pong} = 1;
3057 10 $weak_self->_h2_start_ws_pong_timeout($stream_id, $weak_ss);
3058 }
3059 },
3060 10 );
3061  
3062 10 $ss->{ws_ka_timer} = $timer;
3063 10 $self->{server}->add_child($timer);
3064 10 $timer->start;
3065 }
3066  
3067 sub _h2_start_ws_pong_timeout {
3068 10 ▶ my ($self, $stream_id, $ss) = @_;
Subroutine _h2_start_ws_pong_timeout: called CC=4 SCAR=14.3
3069  
3070 # Don't start another timeout if one is running
3071 10 ▶ return if $ss->{ws_ka_pong_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_ka_pong_timer"} 2 8 10
3072 8 ▶ return unless $ss->{ws_ka_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_ka_timeout"} > 0 0 8 8
3073 8 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 8 8
3074  
3075 8 weaken(my $weak_self = $self);
3076 8 weaken(my $weak_ss = $ss);
3077  
3078 my $timer = IO::Async::Timer::Countdown->new(
3079 delay => $ss->{ws_ka_timeout},
3080 on_expire => sub {
3081 2 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=7 SCAR=21.1
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
3082 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
3083 2 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 2 2
3084  
3085 2 ▶ if ($weak_ss->{ws_ka_waiting_pong}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_ss->{"ws_ka_waiting_pong"}) 2 0 2
3086 # No pong received within timeout - close only THIS stream.
3087 2 ▶ if ($weak_self->{server} && $weak_self->{server}->can('_log')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"server"} and $weak_self->{"server"}->can("_log")) 2 0 2
Condition33%1/3
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
!ll&&!rl&&r
002
MC/DC0%0/2
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
$weak_self->{"server"} $weak_self->{"server"}->can("_log")
Truth table33%1/3
A and B
A= $weak_self->{"server"}B= $weak_self->{"server"}->can("_log")
ABresult
0X0
100
111
3088 2 $weak_self->{server}->_log(warn =>
3089 "HTTP/2 WebSocket stream $stream_id keepalive timeout - no pong received within $weak_ss->{ws_ka_timeout}s");
3090 }
3091  
3092 2 $weak_self->_h2_stop_ws_keepalive($weak_ss);
3093  
3094 # Record why this stream is ending BEFORE the teardown: this
3095 # is a server-initiated close, not the client going away, and
3096 # _h2_on_close prefers this token over its hardcoded fallback
3097 # for the $cs marking (the queued disconnect event below is
3098 # already correct via the first-wins dedup, but the $cs mark
3099 # only happens in _h2_on_close, downstream of this RST).
3100 2 $weak_ss->{server_close_reason} = 'keepalive_timeout';
3101  
3102 # RFC 6455 section 7.4.1: 1006 MUST NOT be set as the status
3103 # code of a Close control frame -- it means "the connection
3104 # dropped with no close handshake". So a keepalive timeout
3105 # does not send a Close frame at all: it tears the stream
3106 # down with RST_STREAM, the HTTP/2 analogue of h1 dropping
3107 # the transport. The app still sees 1006/'keepalive_timeout'.
3108 #
3109 # Order dependency: the enqueue MUST precede the flush. The
3110 # flush is the only call here that can synchronously drive
3111 # on_stream_close (which enqueues the generic 1006/
3112 # 'client_closed'), and the enqueue is first-wins-deduped, so
3113 # enqueueing first is what makes 'keepalive_timeout' the
3114 # reason the app observes. Do not hoist _h2_write_pending.
3115 2 $weak_self->_h2_ws_enqueue_disconnect($weak_ss, 1006, 'keepalive_timeout');
3116 $weak_self->{h2_session}->submit_rst_stream(
3117 2 $stream_id, _h2_rst_cancel_code());
3118 # This runs outside feed() (async timer callback), so flush
3119 # explicitly.
3120 2 $weak_self->_h2_write_pending;
3121 }
3122 },
3123 8 );
3124  
3125 8 $ss->{ws_ka_pong_timer} = $timer;
3126 8 $self->{server}->add_child($timer);
3127 8 $timer->start;
3128 }
3129  
3130 sub _h2_cancel_ws_pong_timeout {
3131 89 ▶ my ($self, $ss) = @_;
Subroutine _h2_cancel_ws_pong_timeout: called CC=5 SCAR=16.2
3132 89 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 89 89
3133  
3134 89 $ss->{ws_ka_waiting_pong} = 0;
3135  
3136 89 ▶ return unless $ss->{ws_ka_pong_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_ka_pong_timer"} 81 8 89
3137 8 ▶ $ss->{ws_ka_pong_timer}->stop if $ss->{ws_ka_pong_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_ka_pong_timer"}->is_running 6 2 8
3138 8 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 8 0 8
3139 8 $self->{server}->remove_child($ss->{ws_ka_pong_timer});
3140 }
3141 8 $ss->{ws_ka_pong_timer} = undef;
3142 }
3143  
3144 sub _h2_stop_ws_keepalive {
3145 84 ▶ my ($self, $ss) = @_;
Subroutine _h2_stop_ws_keepalive: called CC=5 SCAR=16.3
3146 84 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 84 84
3147  
3148 # Stop pong timeout first
3149 84 $self->_h2_cancel_ws_pong_timeout($ss);
3150  
3151 84 ▶ return unless $ss->{ws_ka_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_ka_timer"} 74 10 84
3152 10 ▶ $ss->{ws_ka_timer}->stop if $ss->{ws_ka_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_ka_timer"}->is_running 10 0 10
3153 10 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 10 0 10
3154 10 $self->{server}->remove_child($ss->{ws_ka_timer});
3155 }
3156 10 $ss->{ws_ka_timer} = undef;
3157 10 $ss->{ws_ka_interval} = 0;
3158 10 $ss->{ws_ka_timeout} = 0;
3159 }
3160  
3161 # HTTP/2 per-stream SSE keepalive and idle timeout (design section 11.3 --
3162 # the h2 analogue of _start_sse_keepalive/_stop_sse_keepalive and
3163 # _start_sse_idle_timer/_reset_sse_idle_timer/_stop_sse_idle_timer). HTTP/1
3164 # carries only one long-lived scope per connection, so its keepalive/idle
3165 # state and timers stay on $self; HTTP/2 multiplexes many SSE streams per
3166 # connection, so this state and these timers live on the per-stream hash
3167 # ($ss, aka $self->{h2_streams}{$stream_id}) instead -- starting or updating
3168 # keepalive on one stream must never stop, replace, or redirect another
3169 # stream's timer or writer.
3170 sub _h2_start_sse_keepalive {
3171 6 ▶ my ($self, $stream_id, $ss, $interval, $comment) = @_;
Subroutine _h2_start_sse_keepalive: called CC=5 SCAR=16.9
3172  
3173 # Last event wins: stop whatever was running before applying new settings.
3174 6 $self->_h2_stop_sse_keepalive($ss);
3175  
3176 6 ▶ return unless $interval && $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $interval and $interval > 0 0 6 6
Condition33%1/3
$interval and $interval > 0
!ll&&!rl&&r
006
MC/DC0%0/2
$interval and $interval > 0
$interval $interval > 0
Truth table33%1/3
A and B
A= $intervalB= $interval > 0
ABresult
0X0
100
111
3177 6 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 6 6
3178  
3179 6 $ss->{sse_ka_interval} = $interval;
3180 6 ▶ $ss->{sse_ka_comment} = $comment // '';
Condition50%1/2
$comment // ""
l!l
60
MC/DC0%0/1
$comment // ""
$comment
Truth table50%1/2
A
A= $comment
Aresult
11
00
3181  
3182 6 weaken(my $weak_self = $self);
3183 6 weaken(my $weak_ss = $ss);
3184  
3185 my $timer = IO::Async::Timer::Periodic->new(
3186 interval => $interval,
3187 on_tick => sub {
3188 18 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=6 SCAR=19.1
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 18 18
3189 18 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 18 18
3190 18 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 18 18
3191  
3192 18 my $text = $weak_ss->{sse_ka_comment};
3193 18 ▶ $text = ":$text" unless $text =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /^:/ 18 0 18
3194 18 my $formatted = "$text\n\n";
3195  
3196 18 ▶ if (my $writer = $weak_ss->{sse_ka_writer}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $writer = $weak_ss->{"sse_ka_writer"}) 18 0 18
3197 18 $writer->($formatted);
3198 }
3199 },
3200 6 );
3201  
3202 6 $ss->{sse_ka_timer} = $timer;
3203 6 $self->{server}->add_child($timer);
3204 6 $timer->start;
3205 }
3206  
3207 sub _h2_stop_sse_keepalive {
3208 66 ▶ my ($self, $ss) = @_;
Subroutine _h2_stop_sse_keepalive: called CC=5 SCAR=16.4
3209 66 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 66 66
3210  
3211 66 ▶ return unless $ss->{sse_ka_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"sse_ka_timer"} 60 6 66
3212 6 ▶ $ss->{sse_ka_timer}->stop if $ss->{sse_ka_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_ka_timer"}->is_running 6 0 6
3213 6 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 6 0 6
3214 6 $self->{server}->remove_child($ss->{sse_ka_timer});
3215 }
3216 6 $ss->{sse_ka_timer} = undef;
3217 6 $ss->{sse_ka_interval} = 0;
3218 6 $ss->{sse_ka_comment} = '';
3219 }
3220  
3221 # Per-stream SSE idle timeout: resets on send activity (design section
3222 # 11.3's "idle timer and activity reset"). On expiry, only THIS stream ends
3223 # -- mirroring an app-initiated sse.close server-side -- so a stalled SSE
3224 # stream cannot take down sibling streams multiplexed on the same h2
3225 # connection.
3226 sub _h2_start_sse_idle_timer {
3227 29 ▶ my ($self, $stream_id, $ss) = @_;
Subroutine _h2_start_sse_idle_timer: called CC=5 SCAR=16.6
3228  
3229 29 ▶ return unless $self->{sse_idle_timeout} && $self->{sse_idle_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0 26 3 29
Condition66%2/3
$self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0
!ll&&!rl&&r
2603
MC/DC50%1/2
$self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0
$self->{"sse_idle_timeout"} $self->{"sse_idle_timeout"} > 0
Truth table66%2/3
A and B
A= $self->{"sse_idle_timeout"}B= $self->{"sse_idle_timeout"} > 0
ABresult
0X0
100
111
3230 3 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 3 3
3231 3 ▶ return if $ss->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_idle_timer"} 0 3 3
3232  
3233 3 weaken(my $weak_self = $self);
3234 3 weaken(my $weak_ss = $ss);
3235  
3236 my $timer = IO::Async::Timer::Countdown->new(
3237 delay => $self->{sse_idle_timeout},
3238 on_expire => sub {
3239 2 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=7 SCAR=20.7
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
3240 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
3241 2 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 2 2
3242 2 ▶ return if $weak_ss->{sse_closing}; # already ending some other way
Branch: 1 branch
BranchTrueFalseTotal
if $weak_ss->{"sse_closing"} 0 2 2
3243  
3244 2 ▶ if ($weak_self->{server} && $weak_self->{server}->can('_log')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"server"} and $weak_self->{"server"}->can("_log")) 2 0 2
Condition33%1/3
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
!ll&&!rl&&r
002
MC/DC0%0/2
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
$weak_self->{"server"} $weak_self->{"server"}->can("_log")
Truth table33%1/3
A and B
A= $weak_self->{"server"}B= $weak_self->{"server"}->can("_log")
ABresult
0X0
100
111
3245 2 $weak_self->{server}->_log(warn =>
3246 "HTTP/2 SSE stream $stream_id idle timeout ($weak_self->{sse_idle_timeout}s) - closing stream");
3247 }
3248  
3249 2 $weak_self->_h2_stop_sse_keepalive($weak_ss);
3250 2 $weak_self->_h2_stop_sse_idle_timer($weak_ss);
3251  
3252 # Record why this stream is ending BEFORE the teardown: this is a
3253 # server-initiated close, not the client going away, and
3254 # _h2_on_close prefers this token over its hardcoded fallback for
3255 # both the $cs marking and the queued sse.disconnect event.
3256 2 $weak_ss->{server_close_reason} = 'idle_timeout';
3257  
3258 # End THIS stream only, the same way an app-initiated sse.close
3259 # does: mark it closing so the data_callback emits the final
3260 # END_STREAM frame once the queue drains. _h2_on_close delivers
3261 # the app-facing sse.disconnect once the h2 layer reports the
3262 # stream fully closed -- sibling streams on this connection are
3263 # unaffected.
3264 2 $weak_ss->{sse_close_sent} = 1;
3265 2 $weak_ss->{sse_closing} = 1;
3266 2 $weak_self->{h2_session}->resume_stream($stream_id);
3267 2 $weak_self->_h2_write_pending;
3268 },
3269 3 );
3270  
3271 3 $ss->{sse_idle_timer} = $timer;
3272 3 $self->{server}->add_child($timer);
3273 3 $timer->start;
3274 }
3275  
3276 sub _h2_reset_sse_idle_timer {
3277 111 ▶ my ($self, $ss) = @_;
Subroutine _h2_reset_sse_idle_timer: called CC=4 SCAR=14.1
3278 111 ▶ return unless $ss && $ss->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and $ss->{"sse_idle_timer"} 102 9 111
Condition66%2/3
$ss and $ss->{"sse_idle_timer"}
!ll&&!rl&&r
01029
MC/DC50%1/2
$ss and $ss->{"sse_idle_timer"}
$ss $ss->{"sse_idle_timer"}
Truth table66%2/3
A and B
A= $ssB= $ss->{"sse_idle_timer"}
ABresult
0X0
100
111
3279 9 $ss->{sse_idle_timer}->reset;
3280 9 ▶ $ss->{sse_idle_timer}->start unless $ss->{sse_idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"sse_idle_timer"}->is_running 0 9 9
3281 }
3282  
3283 sub _h2_stop_sse_idle_timer {
3284 60 ▶ my ($self, $ss) = @_;
Subroutine _h2_stop_sse_idle_timer: called CC=5 SCAR=16.2
3285 60 ▶ return unless $ss && $ss->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and $ss->{"sse_idle_timer"} 57 3 60
Condition66%2/3
$ss and $ss->{"sse_idle_timer"}
!ll&&!rl&&r
0573
MC/DC50%1/2
$ss and $ss->{"sse_idle_timer"}
$ss $ss->{"sse_idle_timer"}
Truth table66%2/3
A and B
A= $ssB= $ss->{"sse_idle_timer"}
ABresult
0X0
100
111
3286 3 ▶ $ss->{sse_idle_timer}->stop if $ss->{sse_idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_idle_timer"}->is_running 1 2 3
3287 3 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 3 0 3
3288 3 $self->{server}->remove_child($ss->{sse_idle_timer});
3289 }
3290 3 $ss->{sse_idle_timer} = undef;
3291 }
3292  
3293 # Request stall timeout - closes connection if no I/O activity during request processing
3294 sub _start_stall_timer {
3295 235 ▶ my ($self) = @_;
Subroutine _start_stall_timer: called CC=5 SCAR=30.8
3296  
3297 235 ▶ return unless $self->{request_timeout} && $self->{request_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"request_timeout"} and $self->{"request_timeout"} > 0 235 0 235
Condition33%1/3
$self->{"request_timeout"} and $self->{"request_timeout"} > 0
!ll&&!rl&&r
23500
MC/DC0%0/2
$self->{"request_timeout"} and $self->{"request_timeout"} > 0
$self->{"request_timeout"} $self->{"request_timeout"} > 0
Truth table33%1/3
A and B
A= $self->{"request_timeout"}B= $self->{"request_timeout"} > 0
ABresult
0X0
100
111
3298 0 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 0 0
3299 0 ▶ return if $self->{stall_timer}; # Already running
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stall_timer"} 0 0 0
3300  
3301 0 weaken(my $weak_self = $self);
3302  
3303 my $timer = IO::Async::Timer::Countdown->new(
3304 delay => $self->{request_timeout},
3305 on_expire => sub {
3306 0 ▶ return unless $weak_self;
Subroutine __ANON__: not called CC=5 SCAR=34.0
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3307 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
3308 # Log the timeout
3309 0 ▶ if ($weak_self->{server} && $weak_self->{server}->can('_log')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"server"} and $weak_self->{"server"}->can("_log")) 0 0 0
Condition0%0/3
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
$weak_self->{"server"} $weak_self->{"server"}->can("_log")
Truth table0%0/3
A and B
A= $weak_self->{"server"}B= $weak_self->{"server"}->can("_log")
ABresult
0X0
100
111
3310 0 $weak_self->{server}->_log(warn =>
3311 "Request stall timeout ($weak_self->{request_timeout}s) - closing connection");
3312 }
3313 0 $weak_self->_handle_disconnect_and_close('client_timeout');
3314 },
3315 0 );
3316 0 $self->{stall_timer} = $timer;
3317 0 $self->{server}->add_child($timer);
3318 0 $timer->start;
3319 }
3320  
3321 sub _reset_stall_timer {
3322 524 ▶ my ($self) = @_;
Subroutine _reset_stall_timer: called CC=3 SCAR=16.5
3323  
3324 524 ▶ return unless $self->{stall_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stall_timer"} 524 0 524
3325 0 $self->{stall_timer}->reset;
3326 0 ▶ $self->{stall_timer}->start unless $self->{stall_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stall_timer"}->is_running 0 0 0
3327 }
3328  
3329 sub _stop_stall_timer {
3330 718 ▶ my ($self) = @_;
Subroutine _stop_stall_timer: called CC=4 SCAR=23.7
3331  
3332 718 ▶ return unless $self->{stall_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stall_timer"} 718 0 718
3333 0 ▶ $self->{stall_timer}->stop if $self->{stall_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stall_timer"}->is_running 0 0 0
3334 0 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 0 0 0
3335 0 $self->{server}->remove_child($self->{stall_timer});
3336 }
3337 0 $self->{stall_timer} = undef;
3338 }
3339  
3340 # WebSocket idle timeout - closes connection if no activity
3341 sub _start_ws_idle_timer {
3342 34 ▶ my ($self) = @_;
Subroutine _start_ws_idle_timer: called CC=5 SCAR=30.8
3343  
3344 34 ▶ return unless $self->{ws_idle_timeout} && $self->{ws_idle_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_idle_timeout"} and $self->{"ws_idle_timeout"} > 0 34 0 34
Condition33%1/3
$self->{"ws_idle_timeout"} and $self->{"ws_idle_timeout"} > 0
!ll&&!rl&&r
3400
MC/DC0%0/2
$self->{"ws_idle_timeout"} and $self->{"ws_idle_timeout"} > 0
$self->{"ws_idle_timeout"} $self->{"ws_idle_timeout"} > 0
Truth table33%1/3
A and B
A= $self->{"ws_idle_timeout"}B= $self->{"ws_idle_timeout"} > 0
ABresult
0X0
100
111
3345 0 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 0 0
3346 0 ▶ return if $self->{ws_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_idle_timer"} 0 0 0
3347  
3348 0 weaken(my $weak_self = $self);
3349  
3350 my $timer = IO::Async::Timer::Countdown->new(
3351 delay => $self->{ws_idle_timeout},
3352 on_expire => sub {
3353 0 ▶ return unless $weak_self;
Subroutine __ANON__: not called CC=5 SCAR=34.0
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3354 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
3355 0 ▶ if ($weak_self->{server} && $weak_self->{server}->can('_log')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"server"} and $weak_self->{"server"}->can("_log")) 0 0 0
Condition0%0/3
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
$weak_self->{"server"} $weak_self->{"server"}->can("_log")
Truth table0%0/3
A and B
A= $weak_self->{"server"}B= $weak_self->{"server"}->can("_log")
ABresult
0X0
100
111
3356 0 $weak_self->{server}->_log(warn =>
3357 "WebSocket idle timeout ($weak_self->{ws_idle_timeout}s) - closing connection");
3358 }
3359 0 $weak_self->_handle_disconnect_and_close('idle_timeout');
3360 },
3361 0 );
3362 0 $self->{ws_idle_timer} = $timer;
3363 0 $self->{server}->add_child($timer);
3364 0 $timer->start;
3365 }
3366  
3367 sub _reset_ws_idle_timer {
3368 97 ▶ my ($self) = @_;
Subroutine _reset_ws_idle_timer: called CC=3 SCAR=16.5
3369  
3370 97 ▶ return unless $self->{ws_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_idle_timer"} 97 0 97
3371 0 $self->{ws_idle_timer}->reset;
3372 0 ▶ $self->{ws_idle_timer}->start unless $self->{ws_idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_idle_timer"}->is_running 0 0 0
3373 }
3374  
3375 sub _stop_ws_idle_timer {
3376 510 ▶ my ($self) = @_;
Subroutine _stop_ws_idle_timer: called CC=4 SCAR=23.7
3377  
3378 510 ▶ return unless $self->{ws_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_idle_timer"} 510 0 510
3379 0 ▶ $self->{ws_idle_timer}->stop if $self->{ws_idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_idle_timer"}->is_running 0 0 0
3380 0 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 0 0 0
3381 0 $self->{server}->remove_child($self->{ws_idle_timer});
3382 }
3383 0 $self->{ws_idle_timer} = undef;
3384 }
3385  
3386 # SSE idle timeout - closes connection if no activity
3387 sub _start_sse_idle_timer {
3388 58 ▶ my ($self) = @_;
Subroutine _start_sse_idle_timer: called CC=5 SCAR=30.9
3389  
3390 58 ▶ return unless $self->{sse_idle_timeout} && $self->{sse_idle_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0 58 0 58
Condition33%1/3
$self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0
!ll&&!rl&&r
5800
MC/DC0%0/2
$self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0
$self->{"sse_idle_timeout"} $self->{"sse_idle_timeout"} > 0
Truth table33%1/3
A and B
A= $self->{"sse_idle_timeout"}B= $self->{"sse_idle_timeout"} > 0
ABresult
0X0
100
111
3391 0 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 0 0
3392 0 ▶ return if $self->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse_idle_timer"} 0 0 0
3393  
3394 0 weaken(my $weak_self = $self);
3395  
3396 my $timer = IO::Async::Timer::Countdown->new(
3397 delay => $self->{sse_idle_timeout},
3398 on_expire => sub {
3399 0 ▶ return unless $weak_self;
Subroutine __ANON__: not called CC=5 SCAR=34.0
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3400 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
3401 0 ▶ if ($weak_self->{server} && $weak_self->{server}->can('_log')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"server"} and $weak_self->{"server"}->can("_log")) 0 0 0
Condition0%0/3
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
$weak_self->{"server"} $weak_self->{"server"}->can("_log")
Truth table0%0/3
A and B
A= $weak_self->{"server"}B= $weak_self->{"server"}->can("_log")
ABresult
0X0
100
111
3402 0 $weak_self->{server}->_log(warn =>
3403 "SSE idle timeout ($weak_self->{sse_idle_timeout}s) - closing connection");
3404 }
3405 0 $weak_self->{sse_disconnect_reason} = 'idle_timeout';
3406 0 $weak_self->_handle_disconnect_and_close('idle_timeout');
3407 },
3408 0 );
3409 0 $self->{sse_idle_timer} = $timer;
3410 0 $self->{server}->add_child($timer);
3411 0 $timer->start;
3412 }
3413  
3414 sub _reset_sse_idle_timer {
3415 141 ▶ my ($self) = @_;
Subroutine _reset_sse_idle_timer: called CC=3 SCAR=16.5
3416  
3417 141 ▶ return unless $self->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timer"} 141 0 141
3418 0 $self->{sse_idle_timer}->reset;
3419 0 ▶ $self->{sse_idle_timer}->start unless $self->{sse_idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timer"}->is_running 0 0 0
3420 }
3421  
3422 sub _stop_sse_idle_timer {
3423 593 ▶ my ($self) = @_;
Subroutine _stop_sse_idle_timer: called CC=4 SCAR=23.7
3424  
3425 593 ▶ return unless $self->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timer"} 593 0 593
3426 0 ▶ $self->{sse_idle_timer}->stop if $self->{sse_idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse_idle_timer"}->is_running 0 0 0
3427 0 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 0 0 0
3428 0 $self->{server}->remove_child($self->{sse_idle_timer});
3429 }
3430 0 $self->{sse_idle_timer} = undef;
3431 }
3432  
3433 # ============================================================================
3434 # Send-side backpressure support
3435 # ============================================================================
3436 #
3437 # Prevents unbounded memory growth when apps send faster than slow clients
3438 # can receive. Uses watermark-based flow control:
3439 # - High watermark (default 1MB): pause sending when buffer exceeds this
3440 # - Low watermark (default 256KB): resume sending when buffer drops below this
3441 #
3442 # The $send->() Future will block (await) when high watermark is exceeded,
3443 # and resolve when buffer drains below low watermark.
3444  
3445 sub _get_write_buffer_size {
3446 583 ▶ my ($self) = @_;
Subroutine _get_write_buffer_size: called CC=6 SCAR=19.1
3447  
3448 583 ▶ return 0 unless $self->{stream};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream"} 0 583 583
3449  
3450 # Access IO::Async::Stream's internal write queue
3451 # IO::Async doesn't expose a public API for buffer size, so we access internals
3452 583 ▶ my $queue = $self->{stream}{writequeue} // [];
Condition50%1/2
$self->{"stream"}{"writequeue"} // []
l!l
5830
MC/DC0%0/1
$self->{"stream"}{"writequeue"} // []
$self->{"stream"}{"writequeue"}
Truth table50%1/2
A
A= $self->{"stream"}{"writequeue"}
Aresult
11
00
3453 583 my $total = 0;
3454  
3455 583 for my $writer (@$queue) {
3456 425 my $data = $writer->data;
3457 425 ▶ if (defined $data && !ref $data) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data and not ref $data) 425 0 425
Condition33%1/3
defined $data and not ref $data
!ll&&!rl&&r
00425
MC/DC0%0/2
defined $data and not ref $data
defined $data not ref $data
Truth table33%1/3
A and not(B)
A= defined $dataB= not ref $data
ABresult
0X0
100
111
3458 425 $total += length($data);
3459 }
3460 }
3461  
3462 583 return $total;
3463 }
3464  
3465 # HTTP/1.1: the transport handle reads the shared TCP write buffer. One
3466 # connection is one stream here, so the IO::Async write queue is the per-stream
3467 # backlog. The connection is held weakly so the handle never keeps it alive.
3468 # arm_drain parks the $fire callback in _drain_fires, deliberately separate
3469 # from _drain_waiters (blocking producer Futures, see _wait_for_drain) --
3470 # teardown (_cancel_drain_waiters) resumes the latter but drops the former
3471 # unfired, the same split h2 keeps between stream_drain_waiters and
3472 # transport_drain_fires: the connection going away is not a drain.
3473 sub _h1_transport_state {
3474 330 ▶ my ($self) = @_;
Subroutine _h1_transport_state: called CC=1 SCAR=0.1
3475 330 weaken(my $w = $self);
3476 return PAGI::Server::TransportState->new(
3477 280 ▶ measure => sub { $w ? $w->_get_write_buffer_size : 0 },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 280 0 280
3478 276 ▶ high => sub { $w ? $w->{write_high_watermark} : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 276 0 276
3479 5 ▶ low => sub { $w ? $w->{write_low_watermark} : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 5 0 5
3480 arm_drain => sub {
3481 8 ▶ my $fire = shift;
Subroutine __ANON__: called CC=2 SCAR=7.0
3482 8 ▶ return unless $w;
Branch: 1 branch
BranchTrueFalseTotal
unless $w 0 8 8
3483 8 push @{$w->{_drain_fires}}, $fire;
3484 8 $w->_setup_drain_detection;
3485 },
3486 330 );
3487 }
3488  
3489 # HTTP/2: the transport handle reads this stream's send queue, not the shared
3490 # TCP write buffer — under h2, N streams multiplex one connection, so that
3491 # buffer is the whole connection's backlog (meaningless per stream). $ss is the
3492 # per-stream state hashref; it's held directly (it is the stream's own state),
3493 # while $self is weakened so the handle never keeps the connection alive.
3494 # arm_drain parks the $fire callback on the stream; the data_callback pull fires
3495 # it (deferred) when the queue crosses below the low watermark. Kept separate
3496 # from stream_drain_waiters: those are Futures for blocking backpressure, these
3497 # are the on_drain hysteresis fires.
3498 sub _h2_transport_state {
3499 209 ▶ my ($self, $ss) = @_;
Subroutine _h2_transport_state: called CC=1 SCAR=0.0
3500 209 weaken(my $w = $self);
3501 return PAGI::Server::TransportState->new(
3502 204 ▶ measure => sub { $ss->{send_queue_bytes} // 0 },
Subroutine __ANON__: called CC=2 SCAR=6.9
Condition100%2/2
$ss->{"send_queue_bytes"} // 0
l!l
1977
MC/DC100%1/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table100%2/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
3503 194 ▶ high => sub { $w ? $w->{write_high_watermark} : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 194 0 194
3504 3 ▶ low => sub { $w ? $w->{write_low_watermark} : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 3 0 3
3505 26 ▶ arm_drain => sub { my $fire = shift; push @{$ss->{transport_drain_fires}}, $fire },
Subroutine __ANON__: called CC=1 SCAR=0.0
3506 209 );
3507 }
3508  
3509 # Notify the current transport-state handle after an application write so its
3510 # backpressure callbacks (on_high_water/on_drain) can fire on a watermark cross.
3511 sub _notify_transport_write {
3512 266 ▶ my ($self) = @_;
Subroutine _notify_transport_write: called CC=2 SCAR=7.1
3513 266 my $ts = $self->{current_transport_state};
3514 266 ▶ $ts->_check_watermarks if $ts;
Branch: 1 branch
BranchTrueFalseTotal
if $ts 266 0 266
3515 }
3516  
3517 sub _check_drain_waiters {
3518 4 ▶ my ($self) = @_;
Subroutine _check_drain_waiters: called CC=8 SCAR=21.3
3519  
3520 4 ▶ return unless @{$self->{_drain_waiters}} || @{$self->{_drain_fires}};
Branch: 1 branch
BranchTrueFalseTotal
unless @{$self->{"_drain_waiters"};} or @{$self->{"_drain_fires"};} 0 4 4
Condition66%2/3
@{$self->{"_drain_waiters"};} or @{$self->{"_drain_fires"};}
l!l&&r!l&&!r
130
MC/DC0%0/2
@{$self->{"_drain_waiters"};} or @{$self->{"_drain_fires"};}
@{$self->{"_drain_waiters"};} @{$self->{"_drain_fires"};}
Truth table66%2/3
A or B
A= @{$self->{"_drain_waiters"};}B= @{$self->{"_drain_fires"};}
ABresult
1X1
011
000
3521 4 ▶ return unless $self->{stream};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream"} 0 4 4
3522  
3523 4 my $buffered = $self->_get_write_buffer_size;
3524  
3525 # Resolve/fire everyone once we've drained below low watermark: blocking
3526 # producer Futures resolve, and arm_drain's on_drain hysteresis callbacks
3527 # fire -- this IS an actual drain, unlike teardown (_cancel_drain_waiters).
3528 4 ▶ if ($buffered < $self->{write_low_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffered < $self->{"write_low_watermark"}) 4 0 4
3529 4 my @waiters = splice @{$self->{_drain_waiters}};
3530 4 for my $f (@waiters) {
3531 1 ▶ $f->done unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 1 0 1
3532 }
3533 4 my @fires = splice @{$self->{_drain_fires}};
3534 4 $_->() for @fires;
3535 # Disable drain checking until next high watermark hit
3536 4 $self->{_drain_check_active} = 0;
3537 }
3538 }
3539  
3540 sub _setup_drain_detection {
3541 13 ▶ my ($self) = @_;
Subroutine _setup_drain_detection: called CC=2 SCAR=7.0
3542  
3543 # Avoid redundant setup
3544 13 ▶ return if $self->{_drain_check_active};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_drain_check_active"} 5 8 13
3545 8 $self->{_drain_check_active} = 1;
3546  
3547 8 weaken(my $weak_self = $self);
3548  
3549 # Primary mechanism: check when write queue empties
3550 # This guarantees we notice drain even for fast-draining connections
3551 # Store previous handler to chain if needed
3552 8 my $prev_on_empty = $self->{_prev_on_outgoing_empty};
3553  
3554 $self->{stream}->configure(
3555 on_outgoing_empty => sub {
3556 3 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=3 SCAR=11.7
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 3 3
3557 3 $weak_self->_check_drain_waiters;
3558 # Call previous handler if any
3559 3 ▶ $prev_on_empty->(@_) if $prev_on_empty;
Branch: 1 branch
BranchTrueFalseTotal
if $prev_on_empty 0 3 3
3560 },
3561 8 );
3562 }
3563  
3564 sub _wait_for_drain {
3565 5 ▶ my ($self) = @_;
Subroutine _wait_for_drain: called CC=2 SCAR=7.1
3566  
3567 # Fast path: already below low watermark
3568 5 my $buffered = $self->_get_write_buffer_size;
3569 5 ▶ if ($buffered < $self->{write_low_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffered < $self->{"write_low_watermark"}) 0 5 5
3570 0 return Future->done;
3571 }
3572  
3573 # Create Future to be resolved when drained
3574 5 my $f = $self->{server}->loop->new_future;
3575 5 push @{$self->{_drain_waiters}}, $f;
3576  
3577 # Ensure drain detection is active
3578 5 $self->_setup_drain_detection;
3579  
3580 5 return $f;
3581 }
3582  
3583 sub _cancel_drain_waiters {
3584 1020 ▶ my ($self, $reason) = @_;
Subroutine _cancel_drain_waiters: called CC=4 SCAR=14.0
3585 1020 ▶ $reason //= 'connection closed';
Condition50%1/2
$reason //= "connection closed"
l!l
10200
MC/DC0%0/1
$reason //= "connection closed"
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
3586  
3587 1020 my @waiters = splice @{$self->{_drain_waiters}};
3588 1020 for my $f (@waiters) {
3589 # Resolve (not fail) - app should check connection state after await
3590 5 ▶ $f->done unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 5 0 5
3591 }
3592 # Drop (don't fire) the app's on_drain fires: the connection is going
3593 # away, not draining -- matches h2's teardown handling of
3594 # transport_drain_fires. The blocking waiters above still resume (so no
3595 # coroutine leak), but on_drain is a hysteresis signal for a buffer that
3596 # actually fell back below the low mark, which never happened here.
3597 1020 $self->{_drain_fires} = [];
3598 1020 $self->{_drain_check_active} = 0;
3599 }
3600  
3601 # HTTP/2 per-stream backpressure: the h2 analogue of _wait_for_drain. Resolves
3602 # when this stream's send queue falls below the low watermark. Each multiplexed
3603 # stream is bounded independently, so a quiet TCP buffer can't let one stream's
3604 # queue grow without limit.
3605 sub _h2_wait_for_stream_drain {
3606 15 ▶ my ($self, $stream_id) = @_;
Subroutine _h2_wait_for_stream_drain: called CC=5 SCAR=16.8
3607  
3608 15 ▶ my $ss = $self->{h2_streams}{$stream_id} or return Future->done;
Branch: 1 branch
BranchTrueFalseTotal
my $ss = $self->{"h2_streams"}{$stream_id} or return "Future"->done 0 15 15
3609  
3610 # Fast path: already below low watermark
3611 15 ▶ if (($ss->{send_queue_bytes} // 0) < $self->{write_low_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if (($ss->{"send_queue_bytes"} // 0) < $self->{"write_low_watermark"}) 0 15 15
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
150
MC/DC0%0/1
$ss->{"send_queue_bytes"} // 0
$ss->{"send_queue_bytes"}
Truth table50%1/2
A
A= $ss->{"send_queue_bytes"}
Aresult
11
00
3612 0 return Future->done;
3613 }
3614  
3615 # Create Future to be resolved when this stream's queue drains (in the
3616 # data_callback pull) or when the stream is torn down.
3617 15 my $f = $self->{server}->loop->new_future;
3618 15 ▶ push @{$ss->{stream_drain_waiters} //= []}, $f;
Condition100%2/2
$ss->{"stream_drain_waiters"} //= []
l!l
78
MC/DC100%1/1
$ss->{"stream_drain_waiters"} //= []
$ss->{"stream_drain_waiters"}
Truth table100%2/2
A
A= $ss->{"stream_drain_waiters"}
Aresult
11
00
3619  
3620 15 return $f;
3621 }
3622  
3623 # Release any producer blocked on _h2_wait_for_stream_drain for a stream that
3624 # is being torn down (close/RST/connection shutdown). Resolve, never fail - the
3625 # producer rechecks connection/stream state after the await. Some teardown
3626 # sites run inside nghttp2's feed() (e.g. the oversize-body 413 path); completing
3627 # a waiter resumes the producer synchronously, so defer to the next loop tick to
3628 # keep the resumed producer out of a re-entrant nghttp2 call.
3629 sub _h2_resolve_stream_drain_waiters {
3630 212 ▶ my ($self, $ss) = @_;
Subroutine _h2_resolve_stream_drain_waiters: called CC=4 SCAR=13.9
3631 212 ▶ return unless $ss && $ss->{stream_drain_waiters};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and $ss->{"stream_drain_waiters"} 203 9 212
Condition66%2/3
$ss and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
02039
MC/DC50%1/2
$ss and $ss->{"stream_drain_waiters"}
$ss $ss->{"stream_drain_waiters"}
Truth table66%2/3
A and B
A= $ssB= $ss->{"stream_drain_waiters"}
ABresult
0X0
100
111
3632 9 my @waiters = splice @{$ss->{stream_drain_waiters}};
3633 9 ▶ return unless @waiters;
Branch: 1 branch
BranchTrueFalseTotal
unless @waiters 5 4 9
3634 $self->{server}->loop->later(sub {
3635 4 ▶ $_->done for grep { !$_->is_ready } @waiters;
Subroutine __ANON__: called CC=2 SCAR=6.9
3636 4 });
3637 }
3638  
3639 # Release a send() parked in the http.response.trailers arm awaiting
3640 # $deliver_trailer_eof (the data callback's own terminal invocation) for a
3641 # stream that is being torn down before that ever happens. Resolve, never
3642 # fail -- same h2_closed carve-out contract as every other post-close send
3643 # (design §6.2 / §21 item 1): a trailers send racing a disconnect is a
3644 # successful no-op, not an error the app must handle. Same re-entrancy
3645 # discipline as _h2_resolve_stream_drain_waiters above (deferred one loop
3646 # tick -- some teardown sites run inside nghttp2's feed()).
3647 sub _h2_resolve_stream_trailer_wait {
3648 211 ▶ my ($self, $ss) = @_;
Subroutine _h2_resolve_stream_trailer_wait: called CC=3 SCAR=11.1
3649 211 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 211 211
3650 211 my $f = delete $ss->{trailer_wait};
3651 211 ▶ return unless $f;
Branch: 1 branch
BranchTrueFalseTotal
unless $f 209 2 211
3652 $self->{server}->loop->later(sub {
3653 2 ▶ $f->done unless $f->is_ready;
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 2 0 2
3654 2 });
3655 }
3656  
3657 # ============================================================================
3658  
3659 # WebSocket keepalive - sends protocol-level ping frames (RFC 6455)
3660 sub _start_ws_keepalive {
3661 1 ▶ my ($self, $interval, $timeout) = @_;
Subroutine _start_ws_keepalive: called CC=5 SCAR=16.8
3662  
3663 # Stop existing timers first
3664 1 $self->_stop_ws_keepalive;
3665  
3666 1 ▶ return unless $interval && $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $interval and $interval > 0 0 1 1
Condition33%1/3
$interval and $interval > 0
!ll&&!rl&&r
001
MC/DC0%0/2
$interval and $interval > 0
$interval $interval > 0
Truth table33%1/3
A and B
A= $intervalB= $interval > 0
ABresult
0X0
100
111
3667 1 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 1 1
3668  
3669 1 $self->{ws_keepalive_interval} = $interval;
3670 1 ▶ $self->{ws_keepalive_timeout} = $timeout // 0;
Condition50%1/2
$timeout // 0
l!l
10
MC/DC0%0/1
$timeout // 0
$timeout
Truth table50%1/2
A
A= $timeout
Aresult
11
00
3671  
3672 1 weaken(my $weak_self = $self);
3673  
3674 my $timer = IO::Async::Timer::Periodic->new(
3675 interval => $interval,
3676 on_tick => sub {
3677 2 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=5 SCAR=16.8
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
3678 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
3679 2 ▶ return unless $weak_self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"websocket_mode"} 0 2 2
3680  
3681 # Send ping frame
3682 2 my $ping = Protocol::WebSocket::Frame->new(
3683 type => 'ping',
3684 buffer => '',
3685 );
3686 2 $weak_self->{stream}->write($ping->to_bytes);
3687  
3688 # Start pong timeout if configured
3689 2 ▶ if ($weak_self->{ws_keepalive_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"ws_keepalive_timeout"} > 0) 2 0 2
3690 2 $weak_self->{ws_waiting_pong} = 1;
3691 2 $weak_self->_start_ws_pong_timeout;
3692 }
3693 },
3694 1 );
3695  
3696 1 $self->{ws_keepalive_timer} = $timer;
3697 1 $self->{server}->add_child($timer);
3698 1 $timer->start;
3699 }
3700  
3701 sub _start_ws_pong_timeout {
3702 2 ▶ my ($self) = @_;
Subroutine _start_ws_pong_timeout: called CC=4 SCAR=14.5
3703  
3704 # Don't start another timeout if one is running
3705 2 ▶ return if $self->{ws_pong_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_pong_timeout"} 1 1 2
3706 1 ▶ return unless $self->{ws_keepalive_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_keepalive_timeout"} > 0 0 1 1
3707 1 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 1 1
3708  
3709 1 weaken(my $weak_self = $self);
3710  
3711 my $timer = IO::Async::Timer::Countdown->new(
3712 delay => $self->{ws_keepalive_timeout},
3713 on_expire => sub {
3714 1 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=6 SCAR=20.3
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
3715 1 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 1 1
3716  
3717 1 ▶ if ($weak_self->{ws_waiting_pong}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"ws_waiting_pong"}) 1 0 1
3718 # No pong received within timeout - close connection
3719 1 ▶ if ($weak_self->{server} && $weak_self->{server}->can('_log')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"server"} and $weak_self->{"server"}->can("_log")) 1 0 1
Condition33%1/3
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
!ll&&!rl&&r
001
MC/DC0%0/2
$weak_self->{"server"} and $weak_self->{"server"}->can("_log")
$weak_self->{"server"} $weak_self->{"server"}->can("_log")
Truth table33%1/3
A and B
A= $weak_self->{"server"}B= $weak_self->{"server"}->can("_log")
ABresult
0X0
100
111
3720 1 $weak_self->{server}->_log(warn =>
3721 "WebSocket keepalive timeout - no pong received within $weak_self->{ws_keepalive_timeout}s");
3722 }
3723 1 $weak_self->_handle_disconnect_and_close('keepalive_timeout');
3724 }
3725 },
3726 1 );
3727  
3728 1 $self->{ws_pong_timeout} = $timer;
3729 1 $self->{server}->add_child($timer);
3730 1 $timer->start;
3731 }
3732  
3733 sub _cancel_ws_pong_timeout {
3734 511 ▶ my ($self) = @_;
Subroutine _cancel_ws_pong_timeout: called CC=4 SCAR=14.0
3735  
3736 511 $self->{ws_waiting_pong} = 0;
3737  
3738 511 ▶ return unless $self->{ws_pong_timeout};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_pong_timeout"} 510 1 511
3739 1 ▶ $self->{ws_pong_timeout}->stop if $self->{ws_pong_timeout}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_pong_timeout"}->is_running 0 1 1
3740 1 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 1 0 1
3741 1 $self->{server}->remove_child($self->{ws_pong_timeout});
3742 }
3743 1 $self->{ws_pong_timeout} = undef;
3744 }
3745  
3746 sub _stop_ws_keepalive {
3747 511 ▶ my ($self) = @_;
Subroutine _stop_ws_keepalive: called CC=4 SCAR=14.0
3748  
3749 # Stop pong timeout first
3750 511 $self->_cancel_ws_pong_timeout;
3751  
3752 511 ▶ return unless $self->{ws_keepalive_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_keepalive_timer"} 510 1 511
3753 1 ▶ $self->{ws_keepalive_timer}->stop if $self->{ws_keepalive_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_keepalive_timer"}->is_running 1 0 1
3754 1 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 1 0 1
3755 1 $self->{server}->remove_child($self->{ws_keepalive_timer});
3756 }
3757 1 $self->{ws_keepalive_timer} = undef;
3758 1 $self->{ws_keepalive_interval} = 0;
3759 1 $self->{ws_keepalive_timeout} = 0;
3760 }
3761  
3762 # SSE keepalive - sends comment lines to prevent proxy timeouts
3763 sub _start_sse_keepalive {
3764 4 ▶ my ($self, $interval, $comment) = @_;
Subroutine _start_sse_keepalive: called CC=5 SCAR=17.0
3765  
3766 # Stop existing timer first
3767 4 $self->_stop_sse_keepalive;
3768  
3769 4 ▶ return unless $interval && $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $interval and $interval > 0 0 4 4
Condition33%1/3
$interval and $interval > 0
!ll&&!rl&&r
004
MC/DC0%0/2
$interval and $interval > 0
$interval $interval > 0
Truth table33%1/3
A and B
A= $intervalB= $interval > 0
ABresult
0X0
100
111
3770 4 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 4 4
3771  
3772 4 ▶ $self->{sse_keepalive_comment} = $comment // '';
Condition50%1/2
$comment // ""
l!l
40
MC/DC0%0/1
$comment // ""
$comment
Truth table50%1/2
A
A= $comment
Aresult
11
00
3773  
3774 4 weaken(my $weak_self = $self);
3775  
3776 my $timer = IO::Async::Timer::Periodic->new(
3777 interval => $interval,
3778 on_tick => sub {
3779 9 ▶ return unless $weak_self;
Subroutine __ANON__: called CC=5 SCAR=17.0
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 9 9
3780 9 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 9 9
3781  
3782 9 my $text = $weak_self->{sse_keepalive_comment};
3783 9 ▶ $text = ":$text" unless $text =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /^:/ 9 0 9
3784 9 my $formatted = "$text\n\n";
3785  
3786 9 ▶ if (my $writer = $weak_self->{sse_keepalive_writer}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $writer = $weak_self->{"sse_keepalive_writer"}) 9 0 9
3787 9 $writer->($formatted);
3788 }
3789 },
3790 4 );
3791  
3792 4 $self->{sse_keepalive_timer} = $timer;
3793 4 $self->{server}->add_child($timer);
3794 4 $timer->start;
3795 }
3796  
3797 sub _stop_sse_keepalive {
3798 597 ▶ my ($self) = @_;
Subroutine _stop_sse_keepalive: called CC=4 SCAR=14.0
3799  
3800 597 ▶ return unless $self->{sse_keepalive_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_keepalive_timer"} 593 4 597
3801 4 ▶ $self->{sse_keepalive_timer}->stop if $self->{sse_keepalive_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse_keepalive_timer"}->is_running 4 0 4
3802 4 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 4 0 4
3803 4 $self->{server}->remove_child($self->{sse_keepalive_timer});
3804 }
3805 4 $self->{sse_keepalive_timer} = undef;
3806 4 $self->{sse_keepalive_comment} = '';
3807 }
3808  
3809 sub _try_handle_request {
3810 349 ▶ my ($self) = @_;
Subroutine _try_handle_request: called CC=11 SCAR=24.0
3811  
3812 349 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 349 349
3813 349 ▶ return if $self->{handling_request};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"handling_request"} 14 335 349
3814  
3815 # Try to parse a request from the buffer
3816 335 my ($request, $consumed) = $self->{protocol}->parse_request($self->{buffer});
3817  
3818 335 ▶ return unless $request;
Branch: 1 branch
BranchTrueFalseTotal
unless $request 2 333 335
3819  
3820 # Remove consumed bytes from buffer
3821 333 substr($self->{buffer}, 0, $consumed) = '';
3822  
3823 # Handle parse errors (malformed request, header too large)
3824 333 ▶ if ($request->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"error"}) 5 328 333
3825 # Mark connection as disconnected with protocol_error reason (PAGI spec compliance)
3826 5 $self->_handle_disconnect('protocol_error');
3827 5 $self->_send_error_response($request->{error}, $request->{message});
3828 5 $self->_close;
3829 5 return;
3830 }
3831  
3832 # Check Content-Length against max_body_size limit (0 = unlimited)
3833 328 ▶ if ($self->{max_body_size} && defined $request->{content_length}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_body_size"} and defined $request->{"content_length"}) 9 319 328
Condition100%3/3
$self->{"max_body_size"} and defined $request->{"content_length"}
!ll&&!rl&&r
23179
MC/DC100%2/2
$self->{"max_body_size"} and defined $request->{"content_length"}
$self->{"max_body_size"} defined $request->{"content_length"}
Truth table100%3/3
A and B
A= $self->{"max_body_size"}B= defined $request->{"content_length"}
ABresult
0X0
100
111
3834 9 ▶ if ($request->{content_length} > $self->{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"content_length"} > $self->{"max_body_size"}) 1 8 9
3835 1 $self->_handle_disconnect('body_too_large');
3836 1 $self->_send_error_response(413, 'Payload Too Large');
3837 1 $self->_close;
3838 1 return;
3839 }
3840 }
3841  
3842 # Check if this is a WebSocket upgrade request
3843 327 my $is_websocket = $self->_is_websocket_upgrade($request);
3844  
3845 # Check if this is an SSE request
3846 327 ▶ my $is_sse = !$is_websocket && $self->_is_sse_request($request);
Condition100%3/3
!$is_websocket && $self->_is_sse_request($request)
!ll&&!rl&&r
3423558
MC/DC100%2/2
!$is_websocket && $self->_is_sse_request($request)
!$is_websocket $self->_is_sse_request($request)
Truth table100%3/3
not(A) && B
A= !$is_websocketB= $self->_is_sse_request($request)
ABresult
0X0
100
111
3847  
3848 # Handle the request - store the Future to prevent "lost future" warning
3849 327 $self->{handling_request} = 1;
3850 327 $self->{request_start} = [gettimeofday];
3851 327 $self->{current_request} = $request; # Store for access logging
3852  
3853 327 ▶ if ($is_websocket) {
Branch: 2 branches
BranchTrueFalseTotal
if ($is_websocket) { } 34 293 327
elsif ($is_sse) { } 58 235 293
3854 34 $self->{request_future} = $self->_handle_websocket_request($request);
3855 } elsif ($is_sse) {
3856 58 $self->{request_future} = $self->_handle_sse_request($request);
3857 } else {
3858 # Start stall timer for HTTP requests (WebSocket/SSE have their own handling)
3859 235 $self->_start_stall_timer;
3860 235 $self->{request_future} = $self->_handle_request($request);
3861 }
3862  
3863 # Use adopt_future for proper error tracking instead of retain
3864 # This ensures errors are propagated to the server's error handling
3865 327 $self->{server}->adopt_future($self->{request_future});
3866 }
3867  
3868 sub _is_websocket_upgrade {
3869 327 ▶ my ($self, $request) = @_;
Subroutine _is_websocket_upgrade: called CC=9 SCAR=22.1
3870  
3871 # Check for WebSocket upgrade headers
3872 327 my $has_upgrade = 0;
3873 327 my $has_connection_upgrade = 0;
3874 327 my $has_ws_key = 0;
3875  
3876 327 for my $header (@{$request->{headers}}) {
3877 943 my ($name, $value) = @$header;
3878 943 ▶ if ($name eq 'upgrade' && lc($value) eq 'websocket') {
Branch: 3 branches
BranchTrueFalseTotal
if ($name eq 'upgrade' and lc $value eq 'websocket') { } 34 909 943
elsif ($name eq 'connection') { } 251 658 909
elsif ($name eq 'sec-websocket-key') { } 34 624 658
Condition66%2/3
$name eq "upgrade" and lc $value eq "websocket"
!ll&&!rl&&r
909034
MC/DC50%1/2
$name eq "upgrade" and lc $value eq "websocket"
$name eq "upgrade" lc $value eq "websocket"
Truth table66%2/3
A and B
A= $name eq "upgrade"B= lc $value eq "websocket"
ABresult
0X0
100
111
3879 34 $has_upgrade = 1;
3880 }
3881 elsif ($name eq 'connection') {
3882 # Connection header can have multiple values
3883 251 ▶ $has_connection_upgrade = 1 if lc($value) =~ /upgrade/;
Branch: 1 branch
BranchTrueFalseTotal
if lc($value) =~ /upgrade/ 34 217 251
3884 }
3885 elsif ($name eq 'sec-websocket-key') {
3886 34 $has_ws_key = 1;
3887 }
3888 }
3889  
3890 327 ▶ return $has_upgrade && $has_connection_upgrade && $has_ws_key;
Condition66%4/6
$has_upgrade && $has_connection_upgrade && $has_ws_key
!ll&&!rl&&r
293034
$has_upgrade and $has_connection_upgrade
!ll&&!rl&&r
293034
MC/DC33%1/3
$has_upgrade && $has_connection_upgrade && $has_ws_key
$has_upgrade $has_connection_upgrade $has_ws_key
Truth table50%2/4
A and B && C
A= $has_upgradeB= $has_connection_upgradeC= $has_ws_key
ABCresult
0XX0
10X0
1100
1111
3891 }
3892  
3893 sub _is_sse_request {
3894 293 ▶ my ($self, $request) = @_;
Subroutine _is_sse_request: called CC=1 SCAR=0.0
3895  
3896 # SSE detection per spec (see _accept_signals_sse above).
3897 # Request has not been upgraded to WebSocket (already checked).
3898 # Note: SSE works with any HTTP method (GET, POST, etc.) to support
3899 # modern patterns like htmx 4 and datastar using fetch-event-source
3900  
3901 293 return _accept_signals_sse($request->{headers});
3902 }
3903  
3904 235 ▶async sub _handle_request {
Subroutine _handle_request: called CC=23 SCAR=31.6
3905 235 my ($self, $request) = @_;
3906  
3907 235 my $scope = $self->_create_scope($request);
3908 235 my $receive = $self->_create_receive($request);
3909 235 my $send = $self->_create_send($request);
3910  
3911 235 eval {
3912 235 await $self->{app}->($scope, $receive, $send);
3913 };
3914  
3915 234 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 17 217 234
3916 # Delivery defines completion (Www.pod:1156-1165): if the terminal
3917 # response event already went out, an exception thrown afterward is
3918 # not a disconnect. Fire on_complete (never on_disconnect), leave
3919 # disconnect_reason() undef, still warn (SHOULD log), and still
3920 # close (MAY close) -- mirrors _h2_dispatch_stream's own log-only
3921 # branch for an error after the response is already complete: that
3922 # stream's connection_state is likewise marked complete before the
3923 # exception is even observed there.
3924 17 ▶ if ($self->{response_started} && (($self->{h1_seq} // '') eq 'complete')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"response_started"} and ($self->{"h1_seq"} // "") eq "complete") 1 16 17
Condition80%4/5
$self->{"response_started"} and ($self->{"h1_seq"} // "") eq "complete"
!ll&&!rl&&r
1511
$self->{"h1_seq"} // ""
l!l
20
MC/DC50%1/2
$self->{"response_started"} and ($self->{"h1_seq"} // "") eq "complete"
$self->{"response_started"} $self->{"h1_seq"}
Truth table66%2/3
A and B
A= $self->{"response_started"}B= $self->{"h1_seq"}
ABresult
0X0
100
111
3925 1 warn "PAGI application error (after response complete): $error\n";
3926 1 $self->_write_access_log;
3927 1 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 1 0 1
3928 1 ▶ if (my $conn_state = $self->{current_connection_state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn_state = $self->{"current_connection_state"}) 1 0 1
3929 1 $conn_state->_mark_complete;
3930 }
3931 1 $self->_close;
3932 1 return;
3933 }
3934  
3935 # Handle application error - always close connection after exception
3936 # If response already started, we can't send error page (3.17)
3937 16 ▶ if ($self->{response_started}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'response_started'}) { } 1 15 16
3938 1 $self->_flush_pending_headers; # don't lose a started response's headers
3939 1 warn "PAGI application error (after response started): $error\n";
3940 } else {
3941 15 $self->_send_error_response(500, "Internal Server Error");
3942 15 warn "PAGI application error: $error\n";
3943 }
3944 # Write access log before closing
3945 16 $self->_write_access_log;
3946 # Notify server that request completed (for max_requests tracking)
3947 16 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 16 0 16
3948 # Always close connection after exception (3.2) - don't try keep-alive
3949 16 $self->_handle_disconnect('server_error');
3950 16 $self->_close;
3951 16 return;
3952 }
3953  
3954 # The application returned without starting a response. An incomplete
3955 # response is a protocol error: if the client is still connected, synthesize
3956 # a 500; either way do not keep-alive a connection on which no response was
3957 # written (that would hang the client, which is waiting for a response). A
3958 # response that was started but not completed is handled by the body-framing
3959 # and keep-alive logic below.
3960 217 ▶ if (!$self->{response_started}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"response_started"}) 4 213 217
3961 4 ▶ unless ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"closed"}) 1 3 4
3962 1 warn "PAGI application returned without starting a response\n";
3963 1 $self->_send_error_response(500, "Internal Server Error");
3964 }
3965 4 $self->_write_access_log;
3966 4 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 4 0 4
3967 4 $self->_handle_disconnect('server_error');
3968 4 $self->_close;
3969 4 return;
3970 }
3971  
3972 # The application resolved with a started but incomplete response
3973 # (terminal body/file/fh — or promised trailers — never sent). Per the
3974 # PAGI spec this is an abnormal end: never synthesize the terminal
3975 # framing, never keep the connection alive, and report server_error
3976 # through on_disconnect — a truncated response must be observable as
3977 # truncated.
3978 213 ▶ if ($self->{response_started} && ($self->{h1_seq} // 'complete') ne 'complete') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"response_started"} and ($self->{"h1_seq"} // "complete") ne "complete") 5 208 213
Condition60%3/5
$self->{"response_started"} and ($self->{"h1_seq"} // "complete") ne "complete"
!ll&&!rl&&r
02085
$self->{"h1_seq"} // "complete"
l!l
2130
MC/DC0%0/2
$self->{"response_started"} and ($self->{"h1_seq"} // "complete") ne "complete"
$self->{"response_started"} $self->{"h1_seq"}
Truth table33%1/3
A and B
A= $self->{"response_started"}B= $self->{"h1_seq"}
ABresult
0X0
100
111
3979 5 $self->_flush_pending_headers; # headers may still be buffered; no terminator follows
3980 5 ▶ unless ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"closed"}) 4 1 5
3981 4 ▶ warn(($self->{h1_seq} // '') eq 'awaiting_trailers'
Branch: 1 branch
BranchTrueFalseTotal
($self->{'h1_seq'} // '') eq 'awaiting_trailers' ? : 2 2 4
Condition50%1/2
$self->{"h1_seq"} // ""
l!l
40
MC/DC0%0/1
$self->{"h1_seq"} // ""
$self->{"h1_seq"}
Truth table50%1/2
A
A= $self->{"h1_seq"}
Aresult
11
00
3982 ? "PAGI application returned with an incomplete response (trailers were declared but never sent)\n"
3983 : "PAGI application returned with an incomplete response\n");
3984 }
3985 5 $self->_write_access_log;
3986 5 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 5 0 5
3987 5 $self->_handle_disconnect_and_close('server_error');
3988 5 return;
3989 }
3990  
3991 # Flush any headers buffered by response.start that were never paired with a
3992 # body write (a started-but-bodyless response).
3993 208 $self->_flush_pending_headers;
3994  
3995 # Write access log entry
3996 208 $self->_write_access_log;
3997  
3998 # Notify server that request completed (for max_requests tracking)
3999 208 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 208 0 208
4000  
4001 # Stop stall timer - request completed successfully
4002 208 $self->_stop_stall_timer;
4003  
4004 # Request finished cleanly: fire on_complete (not on_disconnect) on the
4005 # HTTP connection-state object. Must happen on BOTH the keep-alive and
4006 # close paths, and before the keep-alive branch clears the state below.
4007 # Once marked complete, the non-keep-alive _handle_disconnect_and_close
4008 # call below no-ops the state transition, so on_disconnect never fires for
4009 # a completed request.
4010 208 ▶ if (my $conn_state = $self->{current_connection_state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn_state = $self->{"current_connection_state"}) 208 0 208
4011 208 $conn_state->_mark_complete;
4012 }
4013  
4014 # A request has now completed on this connection: the idle timer's next
4015 # expiry (if the connection stays open awaiting another request) reports
4016 # keepalive_timeout rather than idle_timeout.
4017 208 $self->{_served_a_request} = 1;
4018  
4019 # Determine if we should keep the connection alive
4020 208 my $keep_alive = $self->_should_keep_alive($request);
4021  
4022 208 ▶ if ($keep_alive) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keep_alive) { } 184 24 208
4023 # Reset for next request
4024 184 $self->{handling_request} = 0;
4025 184 $self->{response_started} = 0;
4026 184 $self->{h1_seq} = 'initial';
4027 184 $self->{_resp_pending} = undef;
4028 184 $self->{response_status} = undef;
4029 184 $self->{_response_size} = 0;
4030 184 $self->{request_start} = undef;
4031 184 $self->{current_request} = undef;
4032 184 $self->{request_future} = undef;
4033 184 $self->{current_connection_state} = undef; # Clear for next request
4034 184 $self->{current_transport_state} = undef; # New request gets a fresh handle
4035  
4036 # Check if there's more data in the buffer (pipelining)
4037 184 ▶ if (length($self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} > 0) 1 183 184
4038 1 $self->_try_handle_request;
4039 }
4040 } else {
4041 # Not keeping alive - close connection
4042 24 $self->_handle_disconnect_and_close('request_complete');
4043 }
4044 154 }
4045  
4046 sub _should_keep_alive {
4047 242 ▶ my ($self, $request) = @_;
Subroutine _should_keep_alive: called CC=10 SCAR=23.2
4048  
4049 242 ▶ my $http_version = $request->{http_version} // '1.1';
Condition50%1/2
$request->{"http_version"} // "1.1"
l!l
2420
MC/DC0%0/1
$request->{"http_version"} // "1.1"
$request->{"http_version"}
Truth table50%1/2
A
A= $request->{"http_version"}
Aresult
11
00
4050  
4051 # Check for Connection header
4052 242 my $connection_header;
4053 242 for my $header (@{$request->{headers}}) {
4054 455 ▶ if ($header->[0] eq 'connection') {
Branch: 1 branch
BranchTrueFalseTotal
if ($header->[0] eq "connection") 195 260 455
4055 195 $connection_header = lc($header->[1]);
4056 195 last;
4057 }
4058 }
4059  
4060 # HTTP/1.1: keep-alive by default unless Connection: close
4061 242 ▶ if ($http_version eq '1.1') {
Branch: 1 branch
BranchTrueFalseTotal
if ($http_version eq "1.1") 238 4 242
4062 238 ▶ return 0 if $connection_header && $connection_header =~ /close/;
Branch: 1 branch
BranchTrueFalseTotal
if $connection_header and $connection_header =~ /close/ 30 208 238
Condition100%3/3
$connection_header and $connection_header =~ /close/
!ll&&!rl&&r
4416430
MC/DC100%2/2
$connection_header and $connection_header =~ /close/
$connection_header $connection_header =~ /close/
Truth table100%3/3
A and B
A= $connection_headerB= $connection_header =~ /close/
ABresult
0X0
100
111
4063 208 return 1;
4064 }
4065  
4066 # HTTP/1.0: close by default unless Connection: keep-alive
4067 4 ▶ if ($http_version eq '1.0') {
Branch: 1 branch
BranchTrueFalseTotal
if ($http_version eq "1.0") 4 0 4
4068 4 ▶ return 1 if $connection_header && $connection_header =~ /keep-alive/;
Branch: 1 branch
BranchTrueFalseTotal
if $connection_header and $connection_header =~ /keep-alive/ 1 3 4
Condition66%2/3
$connection_header and $connection_header =~ /keep-alive/
!ll&&!rl&&r
301
MC/DC50%1/2
$connection_header and $connection_header =~ /keep-alive/
$connection_header $connection_header =~ /keep-alive/
Truth table66%2/3
A and B
A= $connection_headerB= $connection_header =~ /keep-alive/
ABresult
0X0
100
111
4069 3 return 0;
4070 }
4071  
4072 # Unknown version: close connection
4073 0 return 0;
4074 }
4075  
4076 sub _create_scope {
4077 235 ▶ my ($self, $request) = @_;
Subroutine _create_scope: called CC=3 SCAR=11.0
4078  
4079 # Create connection state object for disconnect tracking
4080 # Uses lazy Future creation - Future only allocated if disconnect_future() is called
4081 235 my $connection_state = PAGI::Server::ConnectionState->new(
4082 connection => $self,
4083 );
4084 235 $self->{current_connection_state} = $connection_state;
4085  
4086 my $scope = {
4087 type => 'http',
4088 pagi => {
4089 version => '0.5',
4090 spec_version => '0.5',
4091 },
4092 http_version => $request->{http_version},
4093 method => $request->{method},
4094 scheme => $self->_get_scheme,
4095 path => $request->{path},
4096 raw_path => $request->{raw_path},
4097 query_string => $request->{query_string},
4098 root_path => '',
4099 headers => $request->{headers},
4100 (defined $self->{client_host}
4101 ? (client => [$self->{client_host}, $self->{client_port}])
4102 : ()
4103 ),
4104 server => [$self->{server_host}, $self->{server_port}],
4105 # Optimized: avoid hash copy when state is empty (common case)
4106 235 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
4107 extensions => $self->_get_extensions_for_scope,
4108 # Connection state for non-destructive disconnect detection
4109 'pagi.connection' => $connection_state,
4110 # Outbound flow-control introspection (buffered_amount, watermarks,
4111 # on_high_water/on_drain). Stashed on the connection too, so the send
4112 # path can poke _check_watermarks after each write.
4113 235 ▶ 'pagi.transport' => ($self->{current_transport_state} = $self->_h1_transport_state),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 233 2 235
keys %{$$self{'state'};} ? : 3 232 235
4114 };
4115  
4116 235 return $scope;
4117 }
4118  
4119 # Shared by _create_receive (http.request) and _create_sse_receive
4120 # (sse.request): parses one attempt's worth of a chunked Transfer-Encoding
4121 # request body out of $self->{buffer}, waiting for more bytes if none are
4122 # available yet. Returns the next event for the caller's receive() closure
4123 # to return directly -- a body event (event_type/body/more), the caller's
4124 # disconnect event (via $make_disconnect on a protocol error, an oversized
4125 # body, or the connection closing), or a truthful more=>1 placeholder when
4126 # a receive_pending wake produced no parseable chunk yet.
4127 #
4128 # $body_complete_ref/$bytes_read_ref are scalar refs into the caller's own
4129 # closure-local state so it persists across receive() calls; $event_type
4130 # is 'http.request' or 'sse.request'; $make_disconnect is a coderef
4131 # producing this scope's disconnect event ({type=>'http.disconnect'} or
4132 # the SSE closure's sse.disconnect constructor).
4133 2 ▶async sub _read_chunked_body {
Subroutine _read_chunked_body: called CC=19 SCAR=47.8
4134 2 my ($self, $event_type, $make_disconnect, $body_complete_ref, $bytes_read_ref) = @_;
4135  
4136 # Wait for data if buffer is empty
4137 2 ▶ while (length($self->{buffer}) == 0 && !$self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} == 0 and not $self->{"closed"}) 0 2 2
Condition33%1/3
length $self->{"buffer"} == 0 and not $self->{"closed"}
!ll&&!rl&&r
200
MC/DC0%0/2
length $self->{"buffer"} == 0 and not $self->{"closed"}
length $self->{"buffer"} == 0 not $self->{"closed"}
Truth table33%1/3
A and not(B)
A= length $self->{"buffer"} == 0B= not $self->{"closed"}
ABresult
0X0
100
111
4138 0 ▶ if (!$self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"receive_pending"}) 0 0 0
4139 0 $self->{receive_pending} = Future->new;
4140 }
4141 0 await $self->{receive_pending};
4142 0 $self->{receive_pending} = undef;
4143  
4144 # Check queue after waiting
4145 0 ▶ if (@{$self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"receive_queue"};}) 0 0 0
4146 0 return shift @{$self->{receive_queue}};
4147 }
4148 }
4149  
4150 return $make_disconnect->()
4151 2 ▶ if $self->{closed} && length($self->{buffer}) == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} and length $self->{"buffer"} == 0 0 2 2
Condition33%1/3
$self->{"closed"} and length $self->{"buffer"} == 0
!ll&&!rl&&r
200
MC/DC0%0/2
$self->{"closed"} and length $self->{"buffer"} == 0
$self->{"closed"} length $self->{"buffer"} == 0
Truth table33%1/3
A and B
A= $self->{"closed"}B= length $self->{"buffer"} == 0
ABresult
0X0
100
111
4152  
4153 # Try to parse chunked data
4154 2 my ($data, $consumed, $complete) = $self->{protocol}->parse_chunked_body($self->{buffer});
4155  
4156 # Check for parse error (invalid chunk size)
4157 2 ▶ if (ref($data) eq 'HASH' && $data->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data eq "HASH" and $data->{"error"}) 0 2 2
Condition33%1/3
ref $data eq "HASH" and $data->{"error"}
!ll&&!rl&&r
200
MC/DC0%0/2
ref $data eq "HASH" and $data->{"error"}
ref $data eq "HASH" $data->{"error"}
Truth table33%1/3
A and B
A= ref $data eq "HASH"B= $data->{"error"}
ABresult
0X0
100
111
4158 0 $self->_handle_disconnect('protocol_error');
4159 0 ▶ $self->_send_error_response($data->{error}, $data->{message} // 'Bad Request');
Condition0%0/2
$data->{"message"} // "Bad Request"
l!l
00
MC/DC0%0/1
$data->{"message"} // "Bad Request"
$data->{"message"}
Truth table0%0/2
A
A= $data->{"message"}
Aresult
11
00
4160 0 $self->_close;
4161 0 return $make_disconnect->();
4162 }
4163  
4164 2 ▶ if ($consumed > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($consumed > 0) 2 0 2
4165 2 substr($self->{buffer}, 0, $consumed) = '';
4166  
4167 # Track total bytes read for max_body_size check
4168 2 ▶ $$bytes_read_ref += length($data // '');
Condition50%1/2
$data // ""
l!l
20
MC/DC0%0/1
$data // ""
$data
Truth table50%1/2
A
A= $data
Aresult
11
00
4169  
4170 # Check max_body_size for chunked requests (0 = unlimited)
4171 2 ▶ if ($self->{max_body_size} && $$bytes_read_ref > $self->{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_body_size"} and $$bytes_read_ref > $self->{"max_body_size"}) 0 2 2
Condition33%1/3
$self->{"max_body_size"} and $$bytes_read_ref > $self->{"max_body_size"}
!ll&&!rl&&r
020
MC/DC0%0/2
$self->{"max_body_size"} and $$bytes_read_ref > $self->{"max_body_size"}
$self->{"max_body_size"} $$bytes_read_ref > $self->{"max_body_size"}
Truth table33%1/3
A and B
A= $self->{"max_body_size"}B= $$bytes_read_ref > $self->{"max_body_size"}
ABresult
0X0
100
111
4172 # Body too large - close connection
4173 0 $self->_send_error_response(413, 'Payload Too Large');
4174 0 $self->_handle_disconnect('body_too_large');
4175 0 $self->_close;
4176 0 return $make_disconnect->();
4177 }
4178  
4179 2 ▶ if ($complete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($complete) 2 0 2
4180 2 $$body_complete_ref = 1;
4181 }
4182  
4183 return {
4184 2 ▶ type => $event_type,
Branch: 1 branch
BranchTrueFalseTotal
$complete ? : 2 0 2
Condition50%1/2
$data // ""
l!l
20
MC/DC0%0/1
$data // ""
$data
Truth table50%1/2
A
A= $data
Aresult
11
00
4185 body => $data // '',
4186 more => $complete ? 0 : 1,
4187 };
4188 }
4189  
4190 # Need more data - wait for it
4191 0 ▶ if (!$self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"receive_pending"}) 0 0 0
4192 0 $self->{receive_pending} = Future->new;
4193 }
4194 0 await $self->{receive_pending};
4195 0 $self->{receive_pending} = undef;
4196  
4197 # Recursive call to re-process - but we can't use __SUB__ in nested async
4198 # Just return disconnect if closed
4199 0 ▶ return $make_disconnect->() if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 0 0
4200 # This shouldn't happen often - caller should retry
4201 0 return { type => $event_type, body => '', more => 1 };
4202 154 }
4203  
4204 sub _create_receive {
4205 235 ▶ my ($self, $request) = @_;
Subroutine _create_receive: called CC=5 SCAR=17.1
4206  
4207 235 my $content_length = $request->{content_length};
4208 235 ▶ my $is_chunked = $request->{chunked} // 0;
Condition50%1/2
$request->{"chunked"} // 0
l!l
2350
MC/DC0%0/1
$request->{"chunked"} // 0
$request->{"chunked"}
Truth table50%1/2
A
A= $request->{"chunked"}
Aresult
11
00
4209 235 ▶ my $expect_continue = $request->{expect_continue} // 0;
Condition50%1/2
$request->{"expect_continue"} // 0
l!l
2350
MC/DC0%0/1
$request->{"expect_continue"} // 0
$request->{"expect_continue"}
Truth table50%1/2
A
A= $request->{"expect_continue"}
Aresult
11
00
4210 235 my $continue_sent = 0;
4211 235 my $body_complete = 0;
4212 235 my $bytes_read = 0;
4213 235 my $chunk_size = 65536; # 64KB chunks for large bodies
4214  
4215 # For requests without Content-Length and not chunked, treat as no body
4216 235 ▶ my $has_body = defined($content_length) && $content_length > 0 || $is_chunked;
Condition83%5/6
defined $content_length && $content_length > 0 || $is_chunked
l!l&&r!l&&!r
61228
defined $content_length and $content_length > 0
!ll&&!rl&&r
22906
MC/DC66%2/3
defined $content_length && $content_length > 0 || $is_chunked
defined $content_length $content_length > 0 $is_chunked
Truth table60%3/5
A and B || C
A= defined $content_lengthB= $content_length > 0C= $is_chunked
ABCresult
11X1
0X11
1011
0X00
1000
4217  
4218 235 weaken(my $weak_self = $self);
4219  
4220 # Return a wrapper that tracks the Future from the async receive
4221 return sub {
4222 104 ▶ return Future->done({ type => 'http.disconnect' }) unless $weak_self;
Subroutine __ANON__: called CC=3 SCAR=11.7
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 104 104
4223 104 ▶ return Future->done({ type => 'http.disconnect' }) if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 104 104
4224  
4225 # The actual async implementation
4226 104 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=24 SCAR=37.5
4227 104 ▶ return { type => 'http.disconnect' } unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 104 104
4228 104 ▶ return { type => 'http.disconnect' } if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 104 104
4229  
4230 # Check queue first - events from disconnect handler
4231 104 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 104 104
4232 0 return shift @{$weak_self->{receive_queue}};
4233 }
4234  
4235 # If body is already complete, wait for disconnect
4236 104 ▶ if ($body_complete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body_complete) 4 100 104
4237 4 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 4 0 4
4238 4 $weak_self->{receive_pending} = Future->new;
4239 }
4240  
4241 4 ▶ if ($weak_self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"closed"}) 0 4 4
4242 0 $weak_self->{receive_pending} = undef;
4243 0 return { type => 'http.disconnect' };
4244 }
4245  
4246 4 my $result = await $weak_self->{receive_pending};
4247 # receive_pending may be completed with a value (disconnect event)
4248 # or just done() as a signal
4249 4 ▶ return $result if ref $result eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $result eq "HASH" 4 0 4
4250 # If no value, check queue
4251 0 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 0 0
4252 0 return shift @{$weak_self->{receive_queue}};
4253 }
4254 0 return { type => 'http.disconnect' };
4255 }
4256  
4257 # For requests without body, return empty body immediately
4258 100 ▶ if (!$has_body) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_body) 82 18 100
4259 82 $body_complete = 1;
4260 return {
4261 82 type => 'http.request',
4262 body => '',
4263 more => 0,
4264 };
4265 }
4266  
4267 # Send 100 Continue if client expects it (before reading body)
4268 18 ▶ if ($expect_continue && !$continue_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expect_continue and not $continue_sent) 0 18 18
Condition33%1/3
$expect_continue and not $continue_sent
!ll&&!rl&&r
1800
MC/DC0%0/2
$expect_continue and not $continue_sent
$expect_continue not $continue_sent
Truth table33%1/3
A and not(B)
A= $expect_continueB= not $continue_sent
ABresult
0X0
100
111
4269 0 $continue_sent = 1;
4270 0 $weak_self->{stream}->write($weak_self->{protocol}->serialize_continue);
4271 }
4272  
4273 # Handle chunked Transfer-Encoding
4274 18 ▶ if ($is_chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_chunked) 1 17 18
4275 return await $weak_self->_read_chunked_body(
4276 'http.request',
4277 0 ▶ sub { { type => 'http.disconnect' } },
Subroutine __ANON__: not called CC=1 SCAR=6.9
4278 1 \$body_complete,
4279 \$bytes_read,
4280 );
4281 }
4282  
4283 # Handle Content-Length based body reading
4284 17 my $remaining = $content_length - $bytes_read;
4285  
4286 17 ▶ if ($remaining <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining <= 0) 0 17 17
4287 0 $body_complete = 1;
4288 return {
4289 0 type => 'http.request',
4290 body => '',
4291 more => 0,
4292 };
4293 }
4294  
4295 # Wait for data if buffer is empty
4296 17 ▶ while (length($weak_self->{buffer}) == 0 && !$weak_self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"}) 13 16 29
Condition66%2/3
length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"}
!ll&&!rl&&r
16013
MC/DC50%1/2
length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"}
length $weak_self->{"buffer"} == 0 not $weak_self->{"closed"}
Truth table66%2/3
A and not(B)
A= length $weak_self->{"buffer"} == 0B= not $weak_self->{"closed"}
ABresult
0X0
100
111
4297 13 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 13 0 13
4298 13 $weak_self->{receive_pending} = Future->new;
4299 }
4300 13 await $weak_self->{receive_pending};
4301 13 $weak_self->{receive_pending} = undef;
4302  
4303 # Check queue after waiting
4304 13 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 1 12 13
4305 1 return shift @{$weak_self->{receive_queue}};
4306 }
4307 }
4308  
4309 # Return disconnect if closed while waiting
4310 16 ▶ if ($weak_self->{closed} && length($weak_self->{buffer}) == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"closed"} and length $weak_self->{"buffer"} == 0) 0 16 16
Condition33%1/3
$weak_self->{"closed"} and length $weak_self->{"buffer"} == 0
!ll&&!rl&&r
1600
MC/DC0%0/2
$weak_self->{"closed"} and length $weak_self->{"buffer"} == 0
$weak_self->{"closed"} length $weak_self->{"buffer"} == 0
Truth table33%1/3
A and B
A= $weak_self->{"closed"}B= length $weak_self->{"buffer"} == 0
ABresult
0X0
100
111
4311 0 return { type => 'http.disconnect' };
4312 }
4313  
4314 # Read up to chunk_size or remaining bytes, whichever is smaller
4315 16 ▶ my $to_read = $remaining < $chunk_size ? $remaining : $chunk_size;
Branch: 1 branch
BranchTrueFalseTotal
$remaining < $chunk_size ? : 11 5 16
4316 16 ▶ $to_read = length($weak_self->{buffer}) if length($weak_self->{buffer}) < $to_read;
Branch: 1 branch
BranchTrueFalseTotal
if length $weak_self->{"buffer"} < $to_read 12 4 16
4317  
4318 16 my $body = substr($weak_self->{buffer}, 0, $to_read, '');
4319 16 $bytes_read += length($body);
4320  
4321 # Check if we've read all the body
4322 16 ▶ my $more = ($bytes_read < $content_length) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$bytes_read < $content_length ? : 12 4 16
4323  
4324 16 ▶ if (!$more) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($more) 4 12 16
4325 4 $body_complete = 1;
4326 }
4327  
4328 return {
4329 16 type => 'http.request',
4330 body => $body,
4331 more => $more,
4332 };
4333 104 })->();
4334  
4335 # Track this Future so we can cancel it on close
4336 104 push @{$weak_self->{receive_futures}}, $future;
4337  
4338 # Clean up completed futures from the list
4339 104 @{$weak_self->{receive_futures}} = grep { !$_->is_ready } @{$weak_self->{receive_futures}};
4340  
4341 104 return $future;
4342 235 };
4343 }
4344  
4345 sub _create_send {
4346 235 ▶ my ($self, $request) = @_;
Subroutine _create_send: called CC=7 SCAR=19.5
4347  
4348 235 my $chunked = 0;
4349 235 my $expects_trailers = 0;
4350 235 my $seq = 'initial';
4351 # Publish the closure-local $seq on $self so the app-return path in
4352 # _handle_request can tell a completed response from one the app left
4353 # incomplete (see the mirror contract at every $seq assignment below).
4354 235 $self->{h1_seq} = $seq;
4355 235 ▶ my $is_head_request = ($request->{method} // '') eq 'HEAD';
Condition50%1/2
$request->{"method"} // ""
l!l
2350
MC/DC0%0/1
$request->{"method"} // ""
$request->{"method"}
Truth table50%1/2
A
A= $request->{"method"}
Aresult
11
00
4356 235 ▶ my $http_version = $request->{http_version} // '1.1';
Condition50%1/2
$request->{"http_version"} // "1.1"
l!l
2350
MC/DC0%0/1
$request->{"http_version"} // "1.1"
$request->{"http_version"}
Truth table50%1/2
A
A= $request->{"http_version"}
Aresult
11
00
4357 235 my $is_http10 = ($http_version eq '1.0');
4358  
4359 # Check if HTTP/1.0 client requested keep-alive
4360 235 my $client_wants_keepalive = 0;
4361 235 ▶ if ($is_http10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_http10) 3 232 235
4362 3 for my $h (@{$request->{headers}}) {
4363 2 ▶ if ($h->[0] eq 'connection' && lc($h->[1]) =~ /keep-alive/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->[0] eq "connection" and lc($h->[1]) =~ /keep-alive/) 1 1 2
Condition66%2/3
$h->[0] eq "connection" and lc($h->[1]) =~ /keep-alive/
!ll&&!rl&&r
101
MC/DC50%1/2
$h->[0] eq "connection" and lc($h->[1]) =~ /keep-alive/
$h->[0] eq "connection" lc($h->[1]) =~ /keep-alive/
Truth table66%2/3
A and B
A= $h->[0] eq "connection"B= lc($h->[1]) =~ /keep-alive/
ABresult
0X0
100
111
4364 1 $client_wants_keepalive = 1;
4365 1 last;
4366 }
4367 }
4368 }
4369  
4370 235 weaken(my $weak_self = $self);
4371  
4372 468 ▶ return async sub {
Subroutine __ANON__: called CC=49 SCAR=39.1
4373 468 my ($event) = @_;
4374 468 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 468 468
4375 468 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 467 468
4376  
4377 # Reset stall timer on write activity
4378 467 $weak_self->_reset_stall_timer;
4379  
4380 467 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
4670
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
4381  
4382 # Mandatory event validation and sequencing (PAGI spec compliance).
4383 # Order per spec: transport-closed no-op check above runs first.
4384 PAGI::Server::EventValidator::validate_http_send(
4385 467 $event, { extensions => $weak_self->{extensions} });
4386 461 my $seq_before_advance = $seq;
4387 461 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
4388 456 $weak_self->{h1_seq} = $seq;
4389  
4390 456 ▶ if ($type eq 'http.response.start') {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'http.response.start') { } 216 240 456
elsif ($type eq 'http.response.body') { } 230 10 240
elsif ($type eq 'http.response.trailers') { } 8 2 10
elsif ($type eq 'http.fullflush') { } 2 0 2
4391 216 $weak_self->{response_started} = 1;
4392 $weak_self->{current_connection_state}->_mark_response_started
4393 216 ▶ if $weak_self->{current_connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"current_connection_state"} 216 0 216
4394 216 ▶ $weak_self->{response_status} = $event->{status} // 200; # Track for logging
Condition50%1/2
$event->{"status"} // 200
l!l
2160
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
4395 216 ▶ $expects_trailers = $event->{trailers} // 0;
Condition100%2/2
$event->{"trailers"} // 0
l!l
9207
MC/DC100%1/1
$event->{"trailers"} // 0
$event->{"trailers"}
Truth table100%2/2
A
A= $event->{"trailers"}
Aresult
11
00
4396  
4397 216 ▶ my $status = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
2160
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
4398 216 ▶ my $headers = $event->{headers} // [];
Condition50%1/2
$event->{"headers"} // []
l!l
2160
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
4399 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
4400 # strip any app-supplied values before they reach the wire.
4401 216 $headers = _h1_strip_connection_headers($headers);
4402  
4403 # Check if we need chunked encoding (no Content-Length)
4404 216 my $has_content_length = 0;
4405 216 for my $h (@$headers) {
4406 236 ▶ if (lc($h->[0]) eq 'content-length') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-length") 31 205 236
4407 31 $has_content_length = 1;
4408 31 last;
4409 }
4410 }
4411  
4412 # Add Date header, but only if the app didn't already supply one.
4413 216 my @final_headers = @$headers;
4414 216 ▶ unless (grep { lc($_->[0]) eq 'date' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @final_headers) 215 1 216
4415 215 push @final_headers, ['date', $weak_self->{protocol}->format_date];
4416 }
4417  
4418 # PAGI spec Upgrade companion rule: over HTTP/1.1, a response
4419 # carrying an app-supplied Upgrade header (e.g. 426 Upgrade
4420 # Required) must also carry 'upgrade' among the server-supplied
4421 # Connection tokens -- RFC 9110 requires the pair from any
4422 # Upgrade sender, and the app's own Connection header was
4423 # stripped above. HTTP/1.0 has no upgrade mechanism.
4424 216 ▶ if (!$is_http10 && grep { lc($_->[0]) eq 'upgrade' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $is_http10 and grep {lc $_->[0] eq "upgrade";} @final_headers) 1 215 216
Condition100%3/3
not $is_http10 and grep {lc $_->[0] eq "upgrade";} @final_headers
!ll&&!rl&&r
32121
MC/DC100%2/2
not $is_http10 and grep {lc $_->[0] eq "upgrade";} @final_headers
not $is_http10 grep {lc $_->[0] eq "upgrade";} @final_headers
Truth table100%3/3
not(A) and B
A= not $is_http10B= grep {lc $_->[0] eq "upgrade";} @final_headers
ABresult
0X0
100
111
4425 1 push @final_headers, ['connection', 'upgrade'];
4426 }
4427  
4428 # For HEAD requests, don't use chunked encoding (no body will be sent)
4429 # For HTTP/1.0, don't use chunked encoding - use Connection: close instead
4430 216 ▶ if ($is_head_request || $is_http10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head_request or $is_http10) { } 7 209 216
Condition100%3/3
$is_head_request or $is_http10
l!l&&r!l&&!r
43209
MC/DC100%2/2
$is_head_request or $is_http10
$is_head_request $is_http10
Truth table100%3/3
A or B
A= $is_head_requestB= $is_http10
ABresult
1X1
011
000
4431 7 $chunked = 0;
4432 7 ▶ if ($is_http10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_http10) 3 4 7
4433 3 ▶ if (!$has_content_length) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $has_content_length) { } 1 2 3
elsif ($client_wants_keepalive) { } 1 1 2
4434 # No Content-Length means we can't do keep-alive
4435 1 push @final_headers, ['connection', 'close'];
4436 } elsif ($client_wants_keepalive) {
4437 # HTTP/1.0 client requested keep-alive and we can honor it
4438 # Must explicitly acknowledge with Connection: keep-alive
4439 1 push @final_headers, ['connection', 'keep-alive'];
4440 }
4441 }
4442 } else {
4443 209 $chunked = !$has_content_length;
4444 }
4445  
4446 my $response = $weak_self->{protocol}->serialize_response_start(
4447 216 $status, \@final_headers, $chunked, $http_version
4448 );
4449  
4450 # Buffer the headers instead of writing them now; they are flushed
4451 # together with the first body write (or at finalization). This
4452 # coalesces the common "start + complete body" case into a single
4453 # stream write instead of one per headers/chunk/terminator.
4454 216 $weak_self->{_resp_pending} = $response;
4455 }
4456 elsif ($type eq 'http.response.body') {
4457 # For HEAD requests, suppress the body
4458 230 ▶ if ($is_head_request) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head_request) 4 226 230
4459 # HEAD has headers but no body, so flush the buffered headers now.
4460 4 $weak_self->_flush_pending_headers;
4461 4 return; # Don't send any body for HEAD
4462 }
4463  
4464 # --- BACKPRESSURE CHECK ---
4465 # Wait for buffer to drain if we're above high watermark
4466 # This prevents unbounded memory growth with slow clients
4467 226 ▶ if ($weak_self->_get_write_buffer_size >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->_get_write_buffer_size >= $weak_self->{"write_high_watermark"}) 1 225 226
4468 1 await $weak_self->_wait_for_drain;
4469 # Re-check connection state after await
4470 1 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
4471 1 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 0 1
4472 }
4473 # --- END BACKPRESSURE CHECK ---
4474  
4475 # Determine body source: body, file, or fh (mutually exclusive)
4476 225 my $body = $event->{body};
4477 225 my $file = $event->{file};
4478 225 my $fh = $event->{fh};
4479 225 ▶ my $offset = $event->{offset} // 0;
Condition100%2/2
$event->{"offset"} // 0
l!l
7218
MC/DC100%1/1
$event->{"offset"} // 0
$event->{"offset"}
Truth table100%2/2
A
A= $event->{"offset"}
Aresult
11
00
4480 225 my $length = $event->{length};
4481  
4482 225 ▶ if (defined $file) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $file) { } 15 210 225
elsif (defined $fh) { } 9 201 210
4483 # File path response - stream from file (async, non-blocking)
4484 # File responses are implicitly complete (more is ignored) on
4485 # success. A failed file/fh send must NOT mark the response
4486 # complete: advance_http already advanced $seq to a terminal
4487 # state before we got here (it can't know the read will fail),
4488 # so on failure we roll $seq back to its pre-event value. That
4489 # lets a conforming app recover with a normal error body
4490 # instead of being permanently locked out by "response already
4491 # complete" for a body that was never actually sent.
4492 15 $weak_self->_flush_pending_headers; # headers before the file body
4493 eval {
4494 # h2 parity (Connection.pm _h2_create_send file arm): fail
4495 # fast on a missing/unreadable file with the same messages,
4496 # ahead of _send_file_response's own -s/open, which would
4497 # otherwise report a less specific error for the same fault.
4498 15 ▶ die "File not found: $file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 14 15
4499 14 ▶ die "Cannot read file: $file\n" unless -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $file 1 13 14
4500  
4501 13 await $weak_self->_send_file_response($file, $offset, $length, $chunked);
4502 13 1;
4503 15 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { die "File not found: $file\n" unless -f $file; die "Cannot read file: $file\n" unless -r $file; XXX; 1 } } or do { my $error = $@; $seq = $seq_before_advance; $weak_self->{"h1_seq"} = $seq; die $error } 2 13 15
4504 2 my $error = $@;
4505 2 $seq = $seq_before_advance;
4506 2 $weak_self->{h1_seq} = $seq;
4507 2 die $error;
4508 };
4509 }
4510 elsif (defined $fh) {
4511 # Filehandle response - stream from handle (async, non-blocking)
4512 # Filehandle responses are implicitly complete (more is ignored)
4513 # on success; see the file-path comment above for why a failed
4514 # send must roll $seq back instead of leaving it 'complete'.
4515 9 $weak_self->_flush_pending_headers; # headers before the fh body
4516 eval {
4517 9 await $weak_self->_send_fh_response($fh, $offset, $length, $chunked);
4518 7 1;
4519 9 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { XXX; 1 } } or do { my $error = $@; $seq = $seq_before_advance; $weak_self->{"h1_seq"} = $seq; die $error } 2 7 9
4520 2 my $error = $@;
4521 2 $seq = $seq_before_advance;
4522 2 $weak_self->{h1_seq} = $seq;
4523 2 die $error;
4524 };
4525 }
4526 else {
4527 # Traditional body response
4528 201 ▶ $body //= '';
Condition50%1/2
$body //= ""
l!l
2010
MC/DC0%0/1
$body //= ""
$body
Truth table50%1/2
A
A= $body
Aresult
11
00
4529 201 ▶ my $more = $event->{more} // 0;
Condition100%2/2
$event->{"more"} // 0
l!l
18021
MC/DC100%1/1
$event->{"more"} // 0
$event->{"more"}
Truth table100%2/2
A
A= $event->{"more"}
Aresult
11
00
4530  
4531 201 $weak_self->{_response_size} += length($body);
4532  
4533 # Coalesce any buffered headers, the body (chunk framing if
4534 # chunked), and the final terminator into a single stream write.
4535 # The common start + complete-body response becomes one write
4536 # rather than three.
4537 201 my $out = $weak_self->{_resp_pending};
4538 201 ▶ $out = '' unless defined $out;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $out 14 187 201
4539 201 $weak_self->{_resp_pending} = undef;
4540  
4541 201 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 184 17 201
4542 184 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 183 1 184
4543 183 my $len = sprintf("%x", length($body));
4544 183 $out .= "$len\r\n$body\r\n";
4545 }
4546 184 ▶ if (!$more && !$expects_trailers) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($more or $expects_trailers) 164 20 184
Condition100%3/3
$more or $expects_trailers
l!l&&r!l&&!r
137164
MC/DC100%2/2
$more or $expects_trailers
$more $expects_trailers
Truth table100%3/3
A or B
A= $moreB= $expects_trailers
ABresult
1X1
011
000
4547 164 $out .= "0\r\n\r\n";
4548 }
4549 }
4550 else {
4551 17 $out .= $body;
4552 }
4553  
4554 201 ▶ $weak_self->{stream}->write($out) if length $out;
Branch: 1 branch
BranchTrueFalseTotal
if length $out 201 0 201
4555 201 $weak_self->_notify_transport_write;
4556 }
4557 }
4558 elsif ($type eq 'http.response.trailers') {
4559 # No "return unless $expects_trailers" guard here: advance_http
4560 # (called unconditionally above, line ~2886) already croaks for
4561 # undeclared trailers -- "cannot send http.response.trailers:
4562 # trailers were not declared or body is not complete" -- before
4563 # execution ever reaches this branch, so the guard was dead code.
4564  
4565 8 ▶ if ($is_head_request) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head_request) 1 7 8
4566 # HEAD: accept-and-discard, per PAGI Www.pod's HEAD rule
4567 # (mirrors the h2 HEAD block from Phase 2 Task 1). The
4568 # generic advance_http call above already advanced the
4569 # machine; transmit nothing.
4570 1 return;
4571 }
4572  
4573 7 ▶ unless ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($chunked) 1 6 7
4574 # Trailers ride chunked framing only (RFC 7230); a
4575 # content-length response has no place to put them, and
4576 # silently dropping promised trailers lies to the
4577 # application. advance_http already advanced $seq to
4578 # 'complete' generically above (it can't know the framing
4579 # can't carry trailers) -- roll it back to its pre-event
4580 # value, same guard/hoist pattern used by the file/fh arms
4581 # above, so the machine stays 'awaiting_trailers' and never
4582 # claims a response completed that never actually went out.
4583 # advance_http is a pure function with no side effects beyond
4584 # its return value, which is what makes advance-then-rollback
4585 # safe.
4586 1 $seq = $seq_before_advance;
4587 1 $weak_self->{h1_seq} = $seq;
4588 1 die "http.response.trailers requires chunked framing (response declared content-length)\n";
4589 }
4590  
4591 # RFC 9110 section 6.5.1 additionally forbids connection-specific/
4592 # framing fields in trailers outright, on any HTTP version -- not
4593 # just the PAGI spec's h1 response-header rule this strip
4594 # otherwise exists for. Strip at ingestion, same placement as
4595 # every h1 response-header site above.
4596 6 ▶ my $trailer_headers = _h1_strip_connection_headers($event->{headers} // []);
Condition100%2/2
$event->{"headers"} // []
l!l
51
MC/DC100%1/1
$event->{"headers"} // []
$event->{"headers"}
Truth table100%2/2
A
A= $event->{"headers"}
Aresult
11
00
4597  
4598 # Send final chunk + trailers (prepend any still-buffered headers).
4599 6 ▶ my $trailers = $weak_self->{_resp_pending} // '';
Condition50%1/2
$weak_self->{"_resp_pending"} // ""
l!l
06
MC/DC0%0/1
$weak_self->{"_resp_pending"} // ""
$weak_self->{"_resp_pending"}
Truth table50%1/2
A
A= $weak_self->{"_resp_pending"}
Aresult
11
00
4600 6 $weak_self->{_resp_pending} = undef;
4601 6 $trailers .= "0\r\n";
4602  
4603 6 my @validated_trailers;
4604 6 for my $header (@$trailer_headers) {
4605 3 my ($name, $value) = @$header;
4606 3 $name = _validate_header_name($name);
4607 3 $value = _validate_header_value($value);
4608 3 push @validated_trailers, [$name, $value];
4609 }
4610 6 $trailers .= $weak_self->{protocol}->serialize_trailers(\@validated_trailers);
4611  
4612 6 $weak_self->{stream}->write($trailers);
4613 }
4614 elsif ($type eq 'http.fullflush') {
4615 # Fullflush extension - force immediate TCP buffer flush.
4616 # validate_http_send (called above, unconditionally) already
4617 # croaks "Extension not enabled: fullflush" when the extension
4618 # isn't advertised, so no re-check is needed here.
4619  
4620 # Force flush by ensuring TCP_NODELAY and flushing any pending writes
4621 2 my $handle = $weak_self->{stream}->write_handle;
4622 2 ▶ if ($handle && $handle->can('setsockopt')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handle and $handle->can("setsockopt")) 2 0 2
Condition33%1/3
$handle and $handle->can("setsockopt")
!ll&&!rl&&r
002
MC/DC0%0/2
$handle and $handle->can("setsockopt")
$handle $handle->can("setsockopt")
Truth table33%1/3
A and B
A= $handleB= $handle->can("setsockopt")
ABresult
0X0
100
111
4623 # Ensure TCP_NODELAY is set to disable Nagle buffering
4624 2 require Socket;
4625 2 $handle->setsockopt(Socket::IPPROTO_TCP(), Socket::TCP_NODELAY(), 1);
4626 }
4627  
4628 # In IO::Async, writes are queued and sent when the event loop allows.
4629 # The above TCP_NODELAY ensures no Nagle buffering delays.
4630 # For this reference implementation, we return immediately as the
4631 # write buffer will be flushed by the event loop.
4632 }
4633  
4634 445 return;
4635 235 };
4636 }
4637  
4638 # Flush any response headers buffered by http.response.start that were not yet
4639 # paired with a body write (HEAD/file/fh paths, started-but-incomplete responses).
4640 sub _flush_pending_headers {
4641 242 ▶ my ($self) = @_;
Subroutine _flush_pending_headers: called CC=3 SCAR=11.0
4642 242 my $pending = $self->{_resp_pending};
4643 242 ▶ return unless defined $pending && length $pending;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pending and length $pending 213 29 242
Condition66%2/3
defined $pending and length $pending
!ll&&!rl&&r
213029
MC/DC50%1/2
defined $pending and length $pending
defined $pending length $pending
Truth table66%2/3
A and B
A= defined $pendingB= length $pending
ABresult
0X0
100
111
4644 29 $self->{_resp_pending} = undef;
4645 29 $self->{stream}->write($pending);
4646 }
4647  
4648 sub _send_error_response {
4649 27 ▶ my ($self, $status, $message) = @_;
Subroutine _send_error_response: called CC=4 SCAR=13.9
4650  
4651 27 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 27 27
4652 27 ▶ return if $self->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"response_started"} 0 27 27
4653  
4654 27 my $body = $message;
4655 my $headers = [
4656 ['content-type', 'text/plain'],
4657 ['content-length', length($body)],
4658 27 ['date', $self->{protocol}->format_date],
4659 ];
4660  
4661 27 my $response = $self->{protocol}->serialize_response_start($status, $headers, 0);
4662 27 $response .= $body;
4663  
4664 27 $self->{stream}->write($response);
4665 27 $self->{response_started} = 1;
4666 # A server-synthesized response is still "this request's response started".
4667 $self->{current_connection_state}->_mark_response_started
4668 27 ▶ if $self->{current_connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"current_connection_state"} 16 11 27
4669 27 $self->{response_status} = $status; # Track for logging
4670 }
4671  
4672 sub _write_access_log {
4673 324 ▶ my ($self) = @_;
Subroutine _write_access_log: called CC=16 SCAR=33.4
4674  
4675 324 ▶ return unless $self->{access_log};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"access_log"} 13 311 324
4676 311 ▶ return unless $self->{current_request};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"current_request"} 0 311 311
4677  
4678 311 my $request = $self->{current_request};
4679  
4680 # Calculate request duration
4681 311 my $duration = 0;
4682 311 ▶ if ($self->{request_start}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"request_start"}) 311 0 311
4683 311 $duration = tv_interval($self->{request_start});
4684 }
4685  
4686 # Per-second cached CLF timestamp
4687 311 my $now = time();
4688 311 ▶ if ($now != $_cached_log_time) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now != $_cached_log_time) 94 217 311
4689 94 $_cached_log_time = $now;
4690 94 my @gmt = gmtime($now);
4691 94 my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
4692 94 $_cached_log_timestamp = sprintf("%02d/%s/%04d:%02d:%02d:%02d +0000",
4693 $gmt[3], $months[$gmt[4]], $gmt[5] + 1900,
4694 $gmt[2], $gmt[1], $gmt[0]);
4695 }
4696  
4697 my $info = {
4698 client_ip => $self->{client_host} // ($self->{transport_type} eq 'unix' ? 'unix' : '-'),
4699 timestamp => $_cached_log_timestamp,
4700 method => $request->{method} // '-',
4701 path => $request->{raw_path} // '/',
4702 query => $request->{query_string},
4703 http_version => $request->{http_version} // '1.1',
4704 status => $self->{response_status} // '-',
4705 size => $self->{_response_size} // 0,
4706 duration => $duration,
4707 311 ▶ request_headers => $request->{headers} // [],
Branch: 1 branch
BranchTrueFalseTotal
$self->{'transport_type'} eq 'unix' ? : 2 0 2
Condition60%9/15
$self->{"client_host"} // ($self->{"transport_type"} eq "unix" ? "unix" : "-")
l!l&&r!l&&!r
30920
$request->{"method"} // "-"
l!l
3110
$request->{"raw_path"} // "/"
l!l
3110
$request->{"http_version"} // "1.1"
l!l
3110
$self->{"response_status"} // "-"
l!l
3092
$self->{"_response_size"} // 0
l!l
3110
$request->{"headers"} // []
l!l
3110
MC/DC0%0/2
$self->{"client_host"} // ($self->{"transport_type"} eq "unix" ? "unix" : "-")
$self->{"client_host"} ($self->{"transport_type"} eq "unix" ? "unix" : "-")
MC/DC0%0/1
$request->{"method"} // "-"
$request->{"method"}
MC/DC0%0/1
$request->{"raw_path"} // "/"
$request->{"raw_path"}
MC/DC0%0/1
$request->{"http_version"} // "1.1"
$request->{"http_version"}
MC/DC100%1/1
$self->{"response_status"} // "-"
$self->{"response_status"}
MC/DC0%0/1
$self->{"_response_size"} // 0
$self->{"_response_size"}
MC/DC0%0/1
$request->{"headers"} // []
$request->{"headers"}
Truth table66%2/3
A // B
A= $self->{"client_host"}B= ($self->{"transport_type"} eq "unix" ? "unix" : "-")
ABresult
1X1
011
000
Truth table50%1/2
A
A= $request->{"method"}
Aresult
11
00
Truth table50%1/2
A
A= $request->{"raw_path"}
Aresult
11
00
Truth table50%1/2
A
A= $request->{"http_version"}
Aresult
11
00
Truth table100%2/2
A
A= $self->{"response_status"}
Aresult
11
00
Truth table50%1/2
A
A= $self->{"_response_size"}
Aresult
11
00
Truth table50%1/2
A
A= $request->{"headers"}
Aresult
11
00
4708 };
4709  
4710 311 my $formatter = $self->{_access_log_formatter};
4711 311 ▶ if ($formatter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($formatter) { } 311 0 311
4712 311 print {$self->{access_log}} $formatter->($info), "\n";
4713 }
4714 else {
4715 # Fallback (should not happen with properly initialized server)
4716 0 my $path = $info->{path};
4717 0 my $query = $info->{query};
4718 0 ▶ $path .= "?$query" if defined $query && length $query;
Branch: 1 branch
BranchTrueFalseTotal
if defined $query and length $query 0 0 0
Condition0%0/3
defined $query and length $query
!ll&&!rl&&r
000
MC/DC0%0/2
defined $query and length $query
defined $query length $query
Truth table0%0/3
A and B
A= defined $queryB= length $query
ABresult
0X0
100
111
4719 0 print {$self->{access_log}} "$info->{client_ip} - - [$info->{timestamp}] \"$info->{method} $path\" $info->{status} $info->{duration}s\n";
4720 }
4721 }
4722  
4723 # Reasons passed to _handle_disconnect only for teardown after a clean finish
4724 # (the app has already returned). They are completions, not abnormal disconnects,
4725 # and must not surface as a disconnect reason to the application.
4726 154 my %COMPLETION_REASON = map { ($_ => 1) } qw(
4727 request_complete
4728 stream_complete
4729 session_complete
4730 );
4731  
4732 # Build the app-facing websocket.disconnect event for a server-detected close.
4733 # The code and reason come from the close the server initiated; the defaults are
4734 # the RFC 6455 "abnormal closure, no status received" pair (1006 / empty), used
4735 # when the connection dropped with no close handshake (timeout, TCP FIN).
4736 sub _ws_disconnect_event {
4737 56 ▶ my ($self) = @_;
Subroutine _ws_disconnect_event: called CC=3 SCAR=11.0
4738 return {
4739 type => 'websocket.disconnect',
4740 code => $self->{ws_disconnect_code} // 1006,
4741 56 ▶ reason => $self->{ws_disconnect_reason} // '',
Condition100%4/4
$self->{"ws_disconnect_code"} // 1006
l!l
848
$self->{"ws_disconnect_reason"} // ""
l!l
4412
MC/DC100%1/1
$self->{"ws_disconnect_code"} // 1006
$self->{"ws_disconnect_code"}
MC/DC100%1/1
$self->{"ws_disconnect_reason"} // ""
$self->{"ws_disconnect_reason"}
Truth table100%2/2
A
A= $self->{"ws_disconnect_code"}
Aresult
11
00
Truth table100%2/2
A
A= $self->{"ws_disconnect_reason"}
Aresult
11
00
4742 };
4743 }
4744  
4745 sub _handle_disconnect {
4746 776 ▶ my ($self, $reason) = @_;
Subroutine _handle_disconnect: called CC=25 SCAR=32.5
4747  
4748 # Idempotency guard - prevent duplicate disconnect handling
4749 # Multiple paths can trigger disconnect (timeout, protocol error, session end)
4750 776 ▶ return if $self->{_disconnect_handled};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_disconnect_handled"} 267 509 776
4751 509 $self->{_disconnect_handled} = 1;
4752  
4753 # Auto-detect server shutdown (PAGI spec compliance)
4754 # If no explicit reason and server is shutting down, use server_shutdown
4755 509 ▶ if (!$reason && $self->{server} && $self->{server}{shutting_down}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $reason and $self->{"server"} and $self->{"server"}{"shutting_down"}) 0 509 509
Condition66%4/6
not $reason and $self->{"server"} and $self->{"server"}{"shutting_down"}
!ll&&!rl&&r
50720
not $reason and $self->{"server"}
!ll&&!rl&&r
50702
MC/DC0%0/3
not $reason and $self->{"server"} and $self->{"server"}{"shutting_down"}
not $reason $self->{"server"} $self->{"server"}{"shutting_down"}
Truth table50%2/4
not(A) and B and C
A= not $reasonB= $self->{"server"}C= $self->{"server"}{"shutting_down"}
ABCresult
0XX0
10X0
1100
1111
4756 0 $reason = 'server_shutdown';
4757 }
4758  
4759 # Default reason is client_closed (TCP FIN received)
4760 509 ▶ $reason //= 'client_closed';
Condition100%2/2
$reason //= "client_closed"
l!l
5072
MC/DC100%1/1
$reason //= "client_closed"
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
4761  
4762 # A clean completion is not an abnormal disconnect: don't surface its reason.
4763 509 my $is_completion = $COMPLETION_REASON{$reason};
4764  
4765 # Mark HTTP connection state as disconnected (abnormal only).
4766 # Only for HTTP - WebSocket/SSE have their own patterns.
4767 509 ▶ if ($self->{current_connection_state} && !$self->{websocket_mode} && !$self->{sse_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"current_connection_state"} and not $self->{"websocket_mode"} and not $self->{"sse_mode"}) 53 456 509
Condition66%4/6
$self->{"current_connection_state"} and not $self->{"websocket_mode"} and not $self->{"sse_mode"}
!ll&&!rl&&r
456053
$self->{"current_connection_state"} and not $self->{"websocket_mode"}
!ll&&!rl&&r
456053
MC/DC33%1/3
$self->{"current_connection_state"} and not $self->{"websocket_mode"} and not $self->{"sse_mode"}
$self->{"current_connection_state"} not $self->{"websocket_mode"} not $self->{"sse_mode"}
Truth table50%2/4
A and not(B) and not(C)
A= $self->{"current_connection_state"}B= not $self->{"websocket_mode"}C= not $self->{"sse_mode"}
ABCresult
0XX0
10X0
1100
1111
4768 53 ▶ $self->{current_connection_state}->_mark_disconnected($reason)
Branch: 1 branch
BranchTrueFalseTotal
unless $is_completion 29 24 53
4769 unless $is_completion;
4770 }
4771  
4772 # HTTP/2: connection-level teardown (server shutdown, socket error, ...)
4773 # sweeps every open stream's own connection_state with this reason, so a
4774 # stream still mid-response when the whole connection dies still reports
4775 # why. _mark_disconnected is idempotent -- a stream _h2_on_close already
4776 # took to a terminal state (complete, or its own client_closed/server_error)
4777 # keeps that first reason; only still-open streams pick this one up.
4778 # WebSocket/SSE streams never attach a connection_state (N/A per spec),
4779 # so the guard on $stream->{connection_state} skips them naturally.
4780 509 ▶ if ($self->{is_h2} && $self->{h2_streams} && !$is_completion) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"is_h2"} and $self->{"h2_streams"} and not $is_completion) 200 309 509
Condition83%5/6
$self->{"is_h2"} and $self->{"h2_streams"} and not $is_completion
!ll&&!rl&&r
3090200
$self->{"is_h2"} and $self->{"h2_streams"}
!ll&&!rl&&r
3072200
MC/DC66%2/3
$self->{"is_h2"} and $self->{"h2_streams"} and not $is_completion
$self->{"is_h2"} $self->{"h2_streams"} not $is_completion
Truth table75%3/4
A and B and not(C)
A= $self->{"is_h2"}B= $self->{"h2_streams"}C= not $is_completion
ABCresult
0XX0
10X0
1100
1111
4781 200 for my $stream (values %{$self->{h2_streams}}) {
4782 $stream->{connection_state}->_mark_disconnected($reason)
4783 69 ▶ if $stream->{connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"connection_state"} 5 64 69
4784 }
4785 }
4786  
4787 # Cancel any pending drain waiters (backpressure) AFTER connection state
4788 # is marked above: resolving a parked waiter can synchronously resume an
4789 # awaiting app coroutine (Future::AsyncAwait resumes inline off ->done),
4790 # and that resumed app's first act may be to read is_connected() /
4791 # disconnect_reason() -- those must already reflect this disconnect, not
4792 # a stale "still connected" snapshot from before it was detected.
4793 509 $self->_cancel_drain_waiters($reason);
4794  
4795 # Record the abnormal reason so the WebSocket disconnect event reports it
4796 # (instead of the old empty string). SSE tracks its own reason at the
4797 # detection sites via sse_disconnect_reason.
4798 509 ▶ if ($self->{websocket_mode} && !$is_completion) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"websocket_mode"} and not $is_completion) 22 487 509
Condition100%3/3
$self->{"websocket_mode"} and not $is_completion
!ll&&!rl&&r
483422
MC/DC100%2/2
$self->{"websocket_mode"} and not $is_completion
$self->{"websocket_mode"} not $is_completion
Truth table100%3/3
A and not(B)
A= $self->{"websocket_mode"}B= not $is_completion
ABresult
0X0
100
111
4799 22 $self->{ws_disconnect_reason} = $reason;
4800 }
4801  
4802 # Determine disconnect event type based on mode
4803 509 my $disconnect_event;
4804 509 ▶ if ($self->{websocket_mode}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'websocket_mode'}) { } 26 483 509
elsif ($self->{'sse_mode'}) { } 33 450 483
4805 26 $disconnect_event = $self->_ws_disconnect_event;
4806 } elsif ($self->{sse_mode}) {
4807 # A completed decline is not an abnormal end -- the spec says a
4808 # decline delivers no events at all, so leave $disconnect_event
4809 # unset rather than synthesizing sse.disconnect for it.
4810 $disconnect_event = {
4811 type => 'sse.disconnect',
4812 reason => $self->{sse_disconnect_reason} // 'client_closed',
4813 33 ▶ } unless $self->{sse_decline_completed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_decline_completed"} 20 13 33
Condition50%1/2
$self->{"sse_disconnect_reason"} // "client_closed"
l!l
020
MC/DC0%0/1
$self->{"sse_disconnect_reason"} // "client_closed"
$self->{"sse_disconnect_reason"}
Truth table50%1/2
A
A= $self->{"sse_disconnect_reason"}
Aresult
11
00
4814 } else {
4815 450 $disconnect_event = { type => 'http.disconnect' };
4816 }
4817  
4818 # Queue disconnect event (do this even if already closed)
4819 509 ▶ push @{$self->{receive_queue}}, $disconnect_event if $disconnect_event;
Branch: 1 branch
BranchTrueFalseTotal
if $disconnect_event 496 13 509
4820  
4821 # Complete any pending receive
4822 509 ▶ if ($disconnect_event && $self->{receive_pending} && !$self->{receive_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disconnect_event and $self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready) 29 480 509
Condition83%5/6
$disconnect_event and $self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready
!ll&&!rl&&r
480029
$disconnect_event and $self->{"receive_pending"}
!ll&&!rl&&r
1346729
MC/DC66%2/3
$disconnect_event and $self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready
$disconnect_event $self->{"receive_pending"} not $self->{"receive_pending"}->is_ready
Truth table75%3/4
A and B and not(C)
A= $disconnect_eventB= $self->{"receive_pending"}C= not $self->{"receive_pending"}->is_ready
ABCresult
0XX0
10X0
1100
1111
4823 29 $self->{receive_pending}->done($disconnect_event);
4824 29 $self->{receive_pending} = undef;
4825 }
4826 }
4827  
4828 # Send a WebSocket close frame with status code and optional reason
4829 # Per RFC 6455 Section 7.4, common codes:
4830 # 1000 - Normal closure
4831 # 1007 - Invalid frame payload data (e.g., invalid UTF-8)
4832 # 1009 - Message too big
4833 # 1011 - Unexpected condition
4834 sub _send_close_frame {
4835 4 ▶ my ($self, $code, $reason) = @_;
Subroutine _send_close_frame: called CC=4 SCAR=14.2
4836 4 ▶ $reason //= '';
Condition50%1/2
$reason //= ""
l!l
40
MC/DC0%0/1
$reason //= ""
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
4837  
4838 4 ▶ return unless $self->{stream};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream"} 0 4 4
4839 4 ▶ return if $self->{close_sent};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"close_sent"} 0 4 4
4840  
4841 # Remember the wire code so the app-facing websocket.disconnect event reports
4842 # the same code the peer received, rather than the 1006 abnormal-close default.
4843 4 $self->{ws_disconnect_code} = $code;
4844  
4845 4 my $frame = Protocol::WebSocket::Frame->new(
4846 type => 'close',
4847 buffer => pack('n', $code) . $reason,
4848 );
4849  
4850 4 $self->{stream}->write($frame->to_bytes);
4851 4 $self->{close_sent} = 1;
4852 }
4853  
4854 sub _close {
4855 777 ▶ my ($self) = @_;
Subroutine _close: called CC=23 SCAR=31.5
4856  
4857 # Idempotency guard for cleanup, kept separate from the "closed" flag
4858 # itself: _handle_disconnect_and_close may already have set {closed} = 1
4859 # before calling here, so the send-side closed-check sees it early.
4860 777 ▶ return if $self->{_cleanup_done};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_cleanup_done"} 267 510 777
4861 510 $self->{_cleanup_done} = 1;
4862 510 $self->{closed} = 1;
4863  
4864 # Cancel pending drain waiters early (before other cleanup)
4865 510 $self->_cancel_drain_waiters('connection closing');
4866  
4867 # Clean up HTTP/2 per-stream state
4868 510 ▶ if ($self->{h2_streams}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_streams"}) 510 0 510
4869 510 for my $stream (values %{$self->{h2_streams}}) {
4870 # Whole connection is going away -- stop every WS/SSE stream's
4871 # keepalive (and SSE idle) timers so none leak past this teardown
4872 # sweep.
4873 69 ▶ $self->_h2_stop_ws_keepalive($stream) if $stream->{is_websocket};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"is_websocket"} 42 27 69
4874 69 ▶ if ($stream->{is_sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_sse"}) 20 49 69
4875 20 $self->_h2_stop_sse_keepalive($stream);
4876 20 $self->_h2_stop_sse_idle_timer($stream);
4877 }
4878  
4879 69 ▶ if ($stream->{body_pending} && !$stream->{body_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready) 21 48 69
Condition100%3/3
$stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready
!ll&&!rl&&r
44421
MC/DC100%2/2
$stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready
$stream->{"body_pending"} not $stream->{"body_pending"}->is_ready
Truth table100%3/3
A and not(B)
A= $stream->{"body_pending"}B= not $stream->{"body_pending"}->is_ready
ABresult
0X0
100
111
4880 my $event = $stream->{is_sse}
4881 21 ▶ ? { type => 'sse.disconnect', reason => 'client_closed' }
Branch: 1 branch
BranchTrueFalseTotal
$stream->{'is_sse'} ? : 3 18 21
4882 : { type => 'http.disconnect' };
4883 21 $stream->{body_pending}->done($event);
4884 }
4885 # Release producers blocked on per-stream backpressure so they
4886 # don't hang on a connection that is going away.
4887 69 $self->_h2_resolve_stream_drain_waiters($stream);
4888 # Same for a send() parked in the deferred trailers branch --
4889 # without this, a peer that just drops the TCP connection (FIN,
4890 # idle timeout, shutdown) never fires on_stream_close (no h2
4891 # protocol event at all), so _h2_on_close's own release never
4892 # runs, and the parked send hangs forever.
4893 69 $self->_h2_resolve_stream_trailer_wait($stream);
4894 # Drop (don't fire) the app's on_drain fires: the connection is going
4895 # away, not draining. Also break the $stream <-> transport_state cycle
4896 # so the stream state is freed when h2_streams is deleted below.
4897 69 $stream->{transport_drain_fires} = [];
4898 69 delete $stream->{transport_state};
4899 }
4900 510 delete $self->{h2_streams};
4901 }
4902 510 ▶ if ($self->{h2_session}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_session"}) 202 308 510
4903 202 eval { $self->{h2_session}->terminate(0) };
4904 202 delete $self->{h2_session};
4905 }
4906  
4907 # Clean up WebSocket frame parser to free memory immediately
4908 510 delete $self->{websocket_frame};
4909  
4910 # Remove from server's connection list (O(1) hash delete)
4911 510 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 510 0 510
4912 510 delete $self->{server}{connections}{refaddr($self)};
4913  
4914 # Signal drain complete if this was the last connection during shutdown
4915 510 ▶ if ($self->{server}{shutting_down} &&
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0 and $self->{"server"}{"drain_complete"} and not $self->{"server"}{"drain_complete"}->is_ready) 1 509 510
Condition88%8/9
$self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0 and $self->{"server"}{"drain_complete"} and not $self->{"server"}{"drain_complete"}->is_ready
!ll&&!rl&&r
50901
$self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0 and $self->{"server"}{"drain_complete"}
!ll&&!rl&&r
3451641
$self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0
!ll&&!rl&&r
33114165
MC/DC75%3/4
$self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0 and $self->{"server"}{"drain_complete"} and not $self->{"server"}{"drain_complete"}->is_ready
$self->{"server"}{"shutting_down"} keys %{$$self{"server"}{"connections"};} == 0 $self->{"server"}{"drain_complete"} not $self->{"server"}{"drain_complete"}->is_ready
Truth table80%4/5
A and B and C and not(D)
A= $self->{"server"}{"shutting_down"}B= keys %{$$self{"server"}{"connections"};} == 0C= $self->{"server"}{"drain_complete"}D= not $self->{"server"}{"drain_complete"}->is_ready
ABCDresult
0XXX0
10XX0
110X0
11100
11111
4916 179 keys %{$self->{server}{connections}} == 0 &&
4917 $self->{server}{drain_complete} &&
4918 !$self->{server}{drain_complete}->is_ready) {
4919 1 $self->{server}{drain_complete}->done;
4920 }
4921 }
4922  
4923 # Stop idle timer
4924 510 $self->_stop_idle_timer;
4925  
4926 # Stop stall timer
4927 510 $self->_stop_stall_timer;
4928  
4929 # Stop WS/SSE idle timers
4930 510 $self->_stop_ws_idle_timer;
4931 510 $self->_stop_sse_idle_timer;
4932  
4933 # Stop keepalive timers
4934 510 $self->_stop_ws_keepalive;
4935 510 $self->_stop_sse_keepalive;
4936  
4937 # Note: _close is resource cleanup ONLY. Callers should use
4938 # _handle_disconnect_and_close() which handles both protocol
4939 # notification and cleanup.
4940  
4941 # Determine disconnect event type based on mode
4942 510 my $disconnect_event;
4943 510 ▶ if ($self->{websocket_mode}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'websocket_mode'}) { } 27 483 510
elsif ($self->{'sse_mode'}) { } 33 450 483
4944 27 $disconnect_event = $self->_ws_disconnect_event;
4945 } elsif ($self->{sse_mode}) {
4946 # See _handle_disconnect: a completed decline delivers no events.
4947 $disconnect_event = {
4948 type => 'sse.disconnect',
4949 reason => $self->{sse_disconnect_reason} // 'client_closed',
4950 33 ▶ } unless $self->{sse_decline_completed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_decline_completed"} 20 13 33
Condition50%1/2
$self->{"sse_disconnect_reason"} // "client_closed"
l!l
020
MC/DC0%0/1
$self->{"sse_disconnect_reason"} // "client_closed"
$self->{"sse_disconnect_reason"}
Truth table50%1/2
A
A= $self->{"sse_disconnect_reason"}
Aresult
11
00
4951 } else {
4952 450 $disconnect_event = { type => 'http.disconnect' };
4953 }
4954  
4955 # Cancel any tracked receive Futures that are still pending
4956 510 ▶ if ($disconnect_event) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disconnect_event) 497 13 510
4957 497 for my $future (@{$self->{receive_futures}}) {
4958 31 ▶ if (!$future->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($future->is_ready) 0 31 31
4959 # Complete with disconnect event instead of cancelling
4960 # This allows the async sub to complete cleanly
4961 0 $future->done($disconnect_event);
4962 }
4963 }
4964 }
4965 510 $self->{receive_futures} = [];
4966  
4967 510 ▶ if ($self->{stream}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stream"}) 510 0 510
4968 510 $self->{stream}->close_when_empty;
4969 }
4970 }
4971  
4972 # Combined disconnect and close - use this from callbacks where $weak_self may
4973 # become undefined after _handle_disconnect completes its Future callbacks.
4974 # This method holds a strong reference to $self throughout the operation.
4975 sub _handle_disconnect_and_close {
4976 748 ▶ my ($self, $reason) = @_;
Subroutine _handle_disconnect_and_close: called CC=1 SCAR=0.0
4977  
4978 # Mark the transport closed before notifying: _handle_disconnect below
4979 # completes any pending receive(), which can synchronously resume the
4980 # app coroutine (it may run straight through a subsequent send()), so
4981 # the send-side closed-check needs "closed" to already be true at that
4982 # point (spec order: closed-check precedes validation). Resource
4983 # cleanup itself still happens in _close, gated by its own idempotency
4984 # flag so it isn't skipped by this early flip.
4985 748 $self->{closed} = 1;
4986  
4987 748 $self->_handle_disconnect($reason);
4988 748 $self->_close;
4989 }
4990  
4991 #
4992 # TLS Support Methods
4993 #
4994  
4995 sub _extract_tls_info {
4996 45 ▶ my ($self) = @_;
Subroutine _extract_tls_info: called CC=17 SCAR=32.3
4997  
4998 45 my $stream = $self->{stream};
4999 45 my $handle = $stream->read_handle;
5000  
5001 # Check if handle is an IO::Socket::SSL
5002 45 ▶ return unless $handle && $handle->isa('IO::Socket::SSL');
Branch: 1 branch
BranchTrueFalseTotal
unless $handle and $handle->isa("IO::Socket::SSL") 0 45 45
Condition33%1/3
$handle and $handle->isa("IO::Socket::SSL")
!ll&&!rl&&r
0045
MC/DC0%0/2
$handle and $handle->isa("IO::Socket::SSL")
$handle $handle->isa("IO::Socket::SSL")
Truth table33%1/3
A and B
A= $handleB= $handle->isa("IO::Socket::SSL")
ABresult
0X0
100
111
5003  
5004 45 my $tls_info = {
5005 server_cert => undef,
5006 client_cert_chain => [],
5007 client_cert_name => undef,
5008 client_cert_error => undef,
5009 tls_version => undef,
5010 cipher_suite => undef,
5011 };
5012  
5013 # Get TLS version - IO::Socket::SSL returns something like 'TLSv1_3'
5014 45 ▶ if (my $version_str = $handle->get_sslversion) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $version_str = $handle->get_sslversion) 45 0 45
5015 # Map version string to numeric value per TLS spec
5016 45 my %version_map = (
5017 'SSLv3' => 0x0300,
5018 'TLSv1' => 0x0301,
5019 'TLSv1_1' => 0x0302,
5020 'TLSv1_2' => 0x0303,
5021 'TLSv1_3' => 0x0304,
5022 );
5023 45 $tls_info->{tls_version} = $version_map{$version_str};
5024 }
5025  
5026 # Cipher suite (numeric IANA id). Net::SSLeay/IO::Socket::SSL expose only the
5027 # cipher *name*, not the 16-bit id the spec asks for. For TLS 1.3 the OpenSSL
5028 # name IS the IANA name and the registry is frozen at five suites, so we map
5029 # those exactly. For TLS 1.2 the names are OpenSSL-specific (a large, shifting
5030 # set), so we leave cipher_suite undef -- the spec permits undef when the
5031 # server cannot determine the value.
5032 45 ▶ if (my $cipher_name = $handle->get_cipher) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cipher_name = $handle->get_cipher) 45 0 45
5033 45 my %tls13_cipher_suites = (
5034 'TLS_AES_128_GCM_SHA256' => 0x1301,
5035 'TLS_AES_256_GCM_SHA384' => 0x1302,
5036 'TLS_CHACHA20_POLY1305_SHA256' => 0x1303,
5037 'TLS_AES_128_CCM_SHA256' => 0x1304,
5038 'TLS_AES_128_CCM_8_SHA256' => 0x1305,
5039 );
5040 $tls_info->{cipher_suite} = $tls13_cipher_suites{$cipher_name}
5041 45 ▶ if exists $tls13_cipher_suites{$cipher_name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tls13_cipher_suites{$cipher_name} 45 0 45
5042 }
5043  
5044 # Get server certificate (our certificate)
5045 # IO::Socket::SSL uses sock_certificate() for the server's own cert
5046 45 eval {
5047 45 my $cert = $handle->sock_certificate;
5048 45 ▶ if ($cert) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cert) 45 0 45
5049 45 require Net::SSLeay;
5050 45 $tls_info->{server_cert} = Net::SSLeay::PEM_get_string_X509($cert);
5051 }
5052 };
5053 45 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 45 45
5054 0 warn "TLS server certificate extraction error: $@\n";
5055 }
5056  
5057 # Get client certificate if provided
5058 45 eval {
5059 45 my $client_cert = $handle->peer_certificate;
5060 45 ▶ if ($client_cert) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_cert) 8 37 45
5061 8 require Net::SSLeay;
5062  
5063 # Get client cert chain
5064 8 my @chain;
5065 8 push @chain, Net::SSLeay::PEM_get_string_X509($client_cert);
5066  
5067 # Try to get additional certs in chain
5068 8 ▶ if (my $ssl = $handle->_get_ssl_object) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ssl = $handle->_get_ssl_object) 8 0 8
5069 8 my $chain_obj = Net::SSLeay::get_peer_cert_chain($ssl);
5070 8 ▶ if ($chain_obj) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chain_obj) 0 8 8
5071 0 for my $i (0 .. Net::SSLeay::sk_X509_num($chain_obj) - 1) {
5072 0 my $cert = Net::SSLeay::sk_X509_value($chain_obj, $i);
5073 0 ▶ push @chain, Net::SSLeay::PEM_get_string_X509($cert) if $cert;
Branch: 1 branch
BranchTrueFalseTotal
if $cert 0 0 0
5074 }
5075 }
5076 }
5077 8 $tls_info->{client_cert_chain} = \@chain;
5078  
5079 # Get client cert DN (Subject)
5080 8 my $subject = Net::SSLeay::X509_NAME_oneline(
5081 Net::SSLeay::X509_get_subject_name($client_cert)
5082 );
5083 8 ▶ $tls_info->{client_cert_name} = $subject if $subject;
Branch: 1 branch
BranchTrueFalseTotal
if $subject 8 0 8
5084  
5085 # Check for verification errors
5086 8 my $verify_result = $handle->get_sslversion_int;
5087 # Actually, use verify_result
5088 8 ▶ if (my $ssl = $handle->_get_ssl_object) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ssl = $handle->_get_ssl_object) 8 0 8
5089 8 my $result = Net::SSLeay::get_verify_result($ssl);
5090 8 ▶ if ($result != 0) { # X509_V_OK = 0
Branch: 1 branch
BranchTrueFalseTotal
if ($result != 0) 0 8 8
5091 0 $tls_info->{client_cert_error} = Net::SSLeay::X509_verify_cert_error_string($result);
5092 }
5093 }
5094 }
5095 };
5096 45 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 45 45
5097 0 warn "TLS client certificate extraction error: $@\n";
5098 }
5099  
5100 45 $self->{tls_info} = $tls_info;
5101 }
5102  
5103 sub _get_scheme {
5104 293 ▶ my ($self) = @_;
Subroutine _get_scheme: called CC=2 SCAR=6.9
5105  
5106 293 ▶ return $self->{tls_enabled} ? 'https' : 'http';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tls_enabled'} ? : 44 249 293
5107 }
5108  
5109 sub _get_ws_scheme {
5110 88 ▶ my ($self) = @_;
Subroutine _get_ws_scheme: called CC=2 SCAR=7.2
5111  
5112 88 ▶ return $self->{tls_enabled} ? 'wss' : 'ws';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tls_enabled'} ? : 0 88 88
5113 }
5114  
5115 sub _get_extensions_for_scope {
5116 537 ▶ my ($self) = @_;
Subroutine _get_extensions_for_scope: called CC=4 SCAR=14.0
5117  
5118 537 my %extensions = %{$self->{extensions}};
5119  
5120 # Add TLS info to extensions if this is a TLS connection
5121 537 ▶ if ($self->{tls_enabled} && $self->{tls_info}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'tls_enabled'} and $self->{'tls_info'}) { } 45 492 537
elsif (not $self->{'tls_enabled'}) { } 492 0 492
Condition66%2/3
$self->{"tls_enabled"} and $self->{"tls_info"}
!ll&&!rl&&r
492045
MC/DC50%1/2
$self->{"tls_enabled"} and $self->{"tls_info"}
$self->{"tls_enabled"} $self->{"tls_info"}
Truth table66%2/3
A and B
A= $self->{"tls_enabled"}B= $self->{"tls_info"}
ABresult
0X0
100
111
5122 45 $extensions{tls} = $self->{tls_info};
5123 }
5124 # Remove tls extension if not a TLS connection (per spec)
5125 elsif (!$self->{tls_enabled}) {
5126 492 delete $extensions{tls};
5127 }
5128  
5129 537 return \%extensions;
5130 }
5131  
5132 #
5133 # SSE (Server-Sent Events) Support Methods
5134 #
5135  
5136 58 ▶async sub _handle_sse_request {
Subroutine _handle_sse_request: called CC=12 SCAR=26.0
5137 58 my ($self, $request) = @_;
5138  
5139 58 $self->{sse_mode} = 1;
5140 58 $self->_stop_idle_timer; # SSE connections are long-lived
5141 58 $self->_start_sse_idle_timer; # Start SSE-specific idle timer if configured
5142  
5143 58 my $scope = $self->_create_sse_scope($request);
5144 58 my $receive = $self->_create_sse_receive($request);
5145 58 my $send = $self->_create_sse_send($request);
5146  
5147 58 my $app_failed = 0;
5148 58 eval {
5149 58 await $self->{app}->($scope, $receive, $send);
5150 };
5151  
5152 58 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 58 58
5153 # If SSE not yet started, send HTTP error
5154 0 ▶ if (!$self->{sse_started}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"sse_started"}) 0 0 0
5155 0 $self->_send_error_response(500, "Internal Server Error");
5156 }
5157 0 warn "PAGI application error (SSE): $error\n";
5158 # An exception is not a clean end -- never keep the connection alive
5159 # after one, exactly as the plain HTTP request path does.
5160 0 $app_failed = 1;
5161 }
5162  
5163 # End the stream (no-op if an explicit sse.close already finished it).
5164 58 $self->_finish_sse_stream('stream_complete');
5165  
5166 # The application produced no response at all: no sse.start, and no
5167 # completed decline. That is the same protocol error the plain HTTP path
5168 # reports, and it must never reach the keep-alive branch below -- the
5169 # client is still waiting for a response, so handing it back a connection
5170 # with zero bytes written would hang it until the idle timeout, or forever
5171 # when timeout => 0. A COMPLETED decline set response_started and closed
5172 # the connection itself, so it never lands here; a decline that started
5173 # but never sent its terminal body does, and its buffered headers are
5174 # about to be discarded, so it is equally unanswerable.
5175 58 ▶ if (!$self->{sse_started} && !$self->{response_started}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"sse_started"} or $self->{"response_started"}) 2 56 58
Condition100%3/3
$self->{"sse_started"} or $self->{"response_started"}
l!l&&r!l&&!r
43132
MC/DC100%2/2
$self->{"sse_started"} or $self->{"response_started"}
$self->{"sse_started"} $self->{"response_started"}
Truth table100%3/3
A or B
A= $self->{"sse_started"}B= $self->{"response_started"}
ABresult
1X1
011
000
5176 2 ▶ unless ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"closed"}) 2 0 2
5177 2 warn "PAGI application returned without starting an SSE stream or a response\n";
5178 2 $self->_send_error_response(500, "Internal Server Error");
5179 }
5180 2 $self->_write_access_log;
5181 # Notify server that request completed (for max_requests tracking)
5182 2 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 2 0 2
5183 2 $self->_handle_disconnect_and_close('server_error');
5184 2 return;
5185 }
5186  
5187 # Write access log entry (logs at stream end with total duration). Must
5188 # precede the reset below, which clears the request it logs.
5189 56 $self->_write_access_log;
5190  
5191 # Notify server that request completed (for max_requests tracking). One
5192 # call site covers both fates below (keep-alive and close) -- the SSE
5193 # "request" completes here, when the stream ends, not at sse.start.
5194 56 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 56 0 56
5195  
5196 # Design section 11.6: a CLEAN end (the application returned, or it sent
5197 # sse.close) honors the "Connection: keep-alive" header the server itself
5198 # emitted on sse.start -- the terminator is written above and the
5199 # connection returns to ordinary request handling. Keep-alive still yields
5200 # to the usual overrides: an application exception, a transport already
5201 # gone (client disconnect, timeout, write error, server shutdown), a
5202 # client "Connection: close", and HTTP/1.0 semantics.
5203 56 ▶ if (!$app_failed && !$self->{closed} && $self->_should_keep_alive($request)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $app_failed || $self->{"closed"} and $self->_should_keep_alive($request)) 25 31 56
Condition83%5/6
not $app_failed || $self->{"closed"} and $self->_should_keep_alive($request)
!ll&&!rl&&r
22925
$app_failed || $self->{'closed'}
l!l&&r!l&&!r
02234
MC/DC66%2/3
not $app_failed || $self->{"closed"} and $self->_should_keep_alive($request)
$app_failed $self->{'closed'} $self->_should_keep_alive($request)
Truth table75%3/4
not(A || B) and C
A= $app_failedB= $self->{'closed'}C= $self->_should_keep_alive($request)
ABCresult
1XX0
01X0
0000
0011
5204 25 $self->_reset_after_sse_stream;
5205 25 return;
5206 }
5207  
5208 31 ▶ $self->_handle_disconnect_and_close($self->{sse_finish_reason} // 'stream_complete');
Condition50%1/2
$self->{"sse_finish_reason"} // "stream_complete"
l!l
310
MC/DC0%0/1
$self->{"sse_finish_reason"} // "stream_complete"
$self->{"sse_finish_reason"}
Truth table50%1/2
A
A= $self->{"sse_finish_reason"}
Aresult
11
00
5209 154 }
5210  
5211 # Idempotently end an SSE stream: write the chunked terminator (HTTP/1.1) and
5212 # release the stream's timers so nothing can write after the terminator.
5213 # Called both by the on-return path above and by an explicit sse.close event
5214 # (which ends the stream while the application is still running), so it must
5215 # run exactly once and must NOT decide the connection's fate -- that decision
5216 # belongs to _handle_sse_request, once the application has actually returned.
5217 sub _finish_sse_stream {
5218 69 ▶ my ($self, $reason) = @_;
Subroutine _finish_sse_stream: called CC=6 SCAR=18.0
5219 69 ▶ return if $self->{sse_finished};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse_finished"} 11 58 69
5220 58 $self->{sse_finished} = 1;
5221 58 $self->{sse_finish_reason} = $reason;
5222  
5223 # Nothing may reach the wire after the terminating chunk.
5224 58 $self->_stop_sse_keepalive;
5225 58 $self->_stop_sse_idle_timer;
5226  
5227 # Send chunked terminator if SSE was started and the stream is still writable
5228 58 ▶ if ($self->{sse_started} && !$self->{closed} &&
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"sse_started"} and not $self->{"closed"} and $self->{"stream"} and $self->{"stream"}->write_handle) 35 23 58
Condition77%7/9
$self->{"sse_started"} and not $self->{"closed"} and $self->{"stream"} and $self->{"stream"}->write_handle
!ll&&!rl&&r
23035
$self->{"sse_started"} and not $self->{"closed"} and $self->{"stream"}
!ll&&!rl&&r
23035
$self->{"sse_started"} and not $self->{"closed"}
!ll&&!rl&&r
15835
MC/DC50%2/4
$self->{"sse_started"} and not $self->{"closed"} and $self->{"stream"} and $self->{"stream"}->write_handle
$self->{"sse_started"} not $self->{"closed"} $self->{"stream"} $self->{"stream"}->write_handle
Truth table60%3/5
A and not(B) and C and D
A= $self->{"sse_started"}B= not $self->{"closed"}C= $self->{"stream"}D= $self->{"stream"}->write_handle
ABCDresult
0XXX0
10XX0
110X0
11100
11111
5229 $self->{stream} && $self->{stream}->write_handle) {
5230 35 $self->{stream}->write("0\r\n\r\n");
5231 }
5232 }
5233  
5234 # Per-request state that must not survive a kept-alive HTTP/1.1 SSE stream
5235 # (design section 11.6). The connection is about to serve an ordinary request
5236 # on the same socket, so every field the stream touched has to be back at its
5237 # constructor value. Inventory, as a constraint list:
5238 #
5239 # SSE stream flags sse_mode, sse_started, sse_finished, sse_finish_reason,
5240 # sse_close_sent, sse_disconnect_reason
5241 # SSE decline state sse_decline_started/status/headers/body
5242 # SSE timers/writer sse_keepalive_timer + comment, sse_idle_timer,
5243 # sse_keepalive_writer (closes over this stream's framing)
5244 # Response state handling_request, response_started, h1_seq,
5245 # _resp_pending, response_status, _response_size
5246 # Request state request_start, current_request, request_future,
5247 # current_connection_state, current_transport_state
5248 # Receive state receive_queue, receive_pending, receive_futures
5249 # Idle timeout the between-requests idle timer, removed when the
5250 # stream started, must be re-armed
5251 #
5252 # The send closure's own $seq is per-request by construction (a new closure is
5253 # built per request), so the post-sse.close raise contract survives untouched.
5254 #
5255 # _disconnect_handled is deliberately NOT reset: every _handle_disconnect pairs
5256 # with _close (and so with {closed}), which the keep-alive branch excludes, so
5257 # reaching here means no disconnect was ever handled and the flag is still 0.
5258 sub _reset_after_sse_stream {
5259 25 ▶ my ($self) = @_;
Subroutine _reset_after_sse_stream: called CC=2 SCAR=6.9
5260  
5261 25 $self->_stop_sse_keepalive;
5262 25 $self->_stop_sse_idle_timer;
5263 25 delete $self->{sse_keepalive_writer};
5264  
5265 25 $self->{sse_mode} = 0;
5266 25 $self->{sse_started} = 0;
5267 25 $self->{sse_finished} = 0;
5268 25 $self->{sse_finish_reason} = undef;
5269 25 $self->{sse_close_sent} = 0;
5270 25 $self->{sse_disconnect_reason} = undef;
5271 25 delete @{$self}{qw(
5272 sse_decline_started sse_decline_status sse_decline_headers sse_decline_body
5273 )};
5274  
5275 # Mirrors the keep-alive reset in _handle_request.
5276 25 $self->{handling_request} = 0;
5277 25 $self->{response_started} = 0;
5278 25 $self->{h1_seq} = 'initial';
5279 25 $self->{_resp_pending} = undef;
5280 25 $self->{response_status} = undef;
5281 25 $self->{_response_size} = 0;
5282 25 $self->{request_start} = undef;
5283 25 $self->{current_request} = undef;
5284 25 $self->{request_future} = undef;
5285 25 $self->{current_connection_state} = undef;
5286 25 $self->{current_transport_state} = undef;
5287  
5288 # The finished stream's receive bookkeeping never belongs to the next
5289 # request. The application has returned, so nothing is awaiting these.
5290 25 $self->{receive_queue} = [];
5291 25 $self->{receive_pending} = undef;
5292 25 $self->{receive_futures} = [];
5293  
5294 # The SSE stream that just ended completed a request on this connection,
5295 # same as the plain HTTP path: the next idle expiry reports
5296 # keepalive_timeout rather than idle_timeout.
5297 25 $self->{_served_a_request} = 1;
5298  
5299 # SSE removed the between-requests idle timer as a long-lived mode; an
5300 # ordinary keep-alive connection must not sit open forever.
5301 25 $self->_start_idle_timer;
5302  
5303 # Check if there's more data in the buffer (pipelining)
5304 25 ▶ if (length($self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} > 0) 0 25 25
5305 0 $self->_try_handle_request;
5306 }
5307 }
5308  
5309 sub _create_sse_scope {
5310 58 ▶ my ($self, $request) = @_;
Subroutine _create_sse_scope: called CC=3 SCAR=12.0
5311  
5312 my $scope = {
5313 type => 'sse',
5314 pagi => {
5315 version => '0.5',
5316 spec_version => '0.5',
5317 },
5318 http_version => $request->{http_version},
5319 method => $request->{method},
5320 scheme => $self->_get_scheme,
5321 path => $request->{path},
5322 raw_path => $request->{raw_path},
5323 query_string => $request->{query_string},
5324 root_path => '',
5325 headers => $request->{headers},
5326 (defined $self->{client_host}
5327 ? (client => [$self->{client_host}, $self->{client_port}])
5328 : ()
5329 ),
5330 server => [$self->{server_host}, $self->{server_port}],
5331 # Optimized: avoid hash copy when state is empty (common case)
5332 58 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
5333 extensions => $self->_get_extensions_for_scope,
5334 # Outbound flow-control introspection (buffered_amount, watermarks,
5335 # on_high_water/on_drain). Stashed on the connection too, so the send
5336 # path can poke _check_watermarks after each write.
5337 58 ▶ 'pagi.transport' => ($self->{current_transport_state} = $self->_h1_transport_state),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 58 0 58
keys %{$$self{'state'};} ? : 0 58 58
5338 };
5339  
5340 58 return $scope;
5341 }
5342  
5343 sub _create_sse_receive {
5344 58 ▶ my ($self, $request) = @_;
Subroutine _create_sse_receive: called CC=5 SCAR=16.3
5345  
5346 58 my $content_length = $request->{content_length};
5347 58 ▶ my $is_chunked = $request->{chunked} // 0;
Condition50%1/2
$request->{"chunked"} // 0
l!l
580
MC/DC0%0/1
$request->{"chunked"} // 0
$request->{"chunked"}
Truth table50%1/2
A
A= $request->{"chunked"}
Aresult
11
00
5348 58 ▶ my $expect_continue = $request->{expect_continue} // 0;
Condition50%1/2
$request->{"expect_continue"} // 0
l!l
580
MC/DC0%0/1
$request->{"expect_continue"} // 0
$request->{"expect_continue"}
Truth table50%1/2
A
A= $request->{"expect_continue"}
Aresult
11
00
5349 58 my $continue_sent = 0;
5350 58 ▶ my $has_body = defined($content_length) && $content_length > 0 || $is_chunked;
Condition83%5/6
defined $content_length && $content_length > 0 || $is_chunked
l!l&&r!l&&!r
3154
defined $content_length and $content_length > 0
!ll&&!rl&&r
5503
MC/DC66%2/3
defined $content_length && $content_length > 0 || $is_chunked
defined $content_length $content_length > 0 $is_chunked
Truth table60%3/5
A and B || C
A= defined $content_lengthB= $content_length > 0C= $is_chunked
ABCresult
11X1
0X11
1011
0X00
1000
5351 58 my $body_complete = 0;
5352 58 my $bytes_read = 0;
5353  
5354 58 weaken(my $weak_self = $self);
5355  
5356 # Helper to create SSE disconnect event with reason
5357 my $sse_disconnect = sub {
5358 return {
5359 type => 'sse.disconnect',
5360 1 ▶ reason => ($weak_self ? $weak_self->{sse_disconnect_reason} : undef) // 'client_closed',
Subroutine __ANON__: called CC=3 SCAR=12.7
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 1 0 1
Condition50%1/2
($weak_self ? $weak_self->{"sse_disconnect_reason"} : undef) // "client_closed"
l!l
01
MC/DC0%0/1
($weak_self ? $weak_self->{"sse_disconnect_reason"} : undef) // "client_closed"
($weak_self ? $weak_self->{"sse_disconnect_reason"} : undef)
Truth table50%1/2
A
A= ($weak_self ? $weak_self->{"sse_disconnect_reason"} : undef)
Aresult
11
00
5361 };
5362 58 };
5363  
5364 # The stream is over -- either the transport is gone, or the application
5365 # ended it with sse.close and is still running (the connection stays open
5366 # for keep-alive, design section 11.6). Nothing more will ever arrive
5367 # on this scope, so answer immediately instead of blocking forever. This
5368 # answers a receive() the application chose to make; it is not a disconnect
5369 # fired at the application because the stream ended.
5370 my $stream_over = sub {
5371 48 ▶ return 1 unless $weak_self;
Subroutine __ANON__: called CC=3 SCAR=11.7
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 48 48
5372 48 ▶ return $weak_self->{closed} || $weak_self->{sse_finished};
Condition66%2/3
$weak_self->{'closed'} || $weak_self->{'sse_finished'}
l!l&&r!l&&!r
2046
MC/DC50%1/2
$weak_self->{'closed'} || $weak_self->{'sse_finished'}
$weak_self->{'closed'} $weak_self->{'sse_finished'}
Truth table66%2/3
A || B
A= $weak_self->{'closed'}B= $weak_self->{'sse_finished'}
ABresult
1X1
011
000
5373 58 };
5374  
5375 return sub {
5376 25 ▶ if ($stream_over->()) {
Subroutine __ANON__: called CC=4 SCAR=14.0
Branch: 1 branch
BranchTrueFalseTotal
if (&$stream_over()) 2 23 25
5377 # A completed decline delivers no events at all (spec): a
5378 # receive() call made after the decline response has already
5379 # finished must not be answered with a synthesized
5380 # sse.disconnect -- nothing abnormal happened. Park instead;
5381 # the app has already gotten its answer (the decline response)
5382 # and has nothing further to receive.
5383 return $weak_self->{server}->loop->new_future
5384 2 ▶ if $weak_self && $weak_self->{sse_decline_completed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self and $weak_self->{"sse_decline_completed"} 1 1 2
Condition66%2/3
$weak_self and $weak_self->{"sse_decline_completed"}
!ll&&!rl&&r
011
MC/DC50%1/2
$weak_self and $weak_self->{"sse_decline_completed"}
$weak_self $weak_self->{"sse_decline_completed"}
Truth table66%2/3
A and B
A= $weak_selfB= $weak_self->{"sse_decline_completed"}
ABresult
0X0
100
111
5385 1 return Future->done($sse_disconnect->());
5386 }
5387  
5388 23 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=21 SCAR=31.5
5389 23 ▶ return $sse_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
if &$stream_over() 0 23 23
5390 if $stream_over->();
5391  
5392 # Check queue first
5393 23 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 23 23
5394 0 return shift @{$weak_self->{receive_queue}};
5395 }
5396  
5397 # Handle request body for POST/PUT SSE requests
5398 23 ▶ if ($has_body && !$body_complete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($has_body and not $body_complete) 5 18 23
Condition100%3/3
$has_body and not $body_complete
!ll&&!rl&&r
1535
MC/DC100%2/2
$has_body and not $body_complete
$has_body not $body_complete
Truth table100%3/3
A and not(B)
A= $has_bodyB= not $body_complete
ABresult
0X0
100
111
5399 # Send 100 Continue if client expects it (before reading body)
5400 5 ▶ if ($expect_continue && !$continue_sent) {
Branch: 1 branch
BranchTrueFalseTotal
if ($expect_continue and not $continue_sent) 1 4 5
Condition66%2/3
$expect_continue and not $continue_sent
!ll&&!rl&&r
401
MC/DC50%1/2
$expect_continue and not $continue_sent
$expect_continue not $continue_sent
Truth table66%2/3
A and not(B)
A= $expect_continueB= not $continue_sent
ABresult
0X0
100
111
5401 1 $continue_sent = 1;
5402 1 $weak_self->{stream}->write($weak_self->{protocol}->serialize_continue);
5403 }
5404  
5405 5 ▶ if ($is_chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_chunked) 1 4 5
5406 1 return await $weak_self->_read_chunked_body(
5407 'sse.request',
5408 $sse_disconnect,
5409 \$body_complete,
5410 \$bytes_read,
5411 );
5412 }
5413  
5414 4 my $remaining = $content_length - $bytes_read;
5415  
5416 # Wait for data if buffer is empty
5417 4 ▶ while (length($weak_self->{buffer}) == 0 && !$weak_self->{closed} && $remaining > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"} and $remaining > 0) 3 4 7
Condition66%4/6
length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"} and $remaining > 0
!ll&&!rl&&r
403
length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"}
!ll&&!rl&&r
403
MC/DC33%1/3
length $weak_self->{"buffer"} == 0 and not $weak_self->{"closed"} and $remaining > 0
length $weak_self->{"buffer"} == 0 not $weak_self->{"closed"} $remaining > 0
Truth table50%2/4
A and not(B) and C
A= length $weak_self->{"buffer"} == 0B= not $weak_self->{"closed"}C= $remaining > 0
ABCresult
0XX0
10X0
1100
1111
5418 3 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 3 0 3
5419 3 $weak_self->{receive_pending} = Future->new;
5420 }
5421 3 await $weak_self->{receive_pending};
5422 3 $weak_self->{receive_pending} = undef;
5423  
5424 3 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 3 3
5425 0 return shift @{$weak_self->{receive_queue}};
5426 }
5427 }
5428  
5429 4 ▶ return $sse_disconnect->() if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 4 4
5430  
5431 # Read available data up to remaining
5432 my $to_read = $remaining < length($weak_self->{buffer})
5433 ? $remaining
5434 4 ▶ : length($weak_self->{buffer});
Branch: 1 branch
BranchTrueFalseTotal
$remaining < length $weak_self->{'buffer'} ? : 0 4 4
5435  
5436 4 my $chunk = substr($weak_self->{buffer}, 0, $to_read, '');
5437 4 $bytes_read += length($chunk);
5438  
5439 4 ▶ my $more = ($bytes_read < $content_length) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$bytes_read < $content_length ? : 1 3 4
5440 4 ▶ $body_complete = 1 if !$more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 3 1 4
5441  
5442 return {
5443 4 type => 'sse.request',
5444 body => $chunk,
5445 more => $more,
5446 };
5447 }
5448  
5449 # No body or body complete - return empty body if not yet returned
5450 18 ▶ if (!$body_complete) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body_complete) 10 8 18
5451 10 $body_complete = 1;
5452 return {
5453 10 type => 'sse.request',
5454 body => '',
5455 more => 0,
5456 };
5457 }
5458  
5459 # Wait for disconnect
5460 8 while (1) {
5461 15 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 7 8 15
5462 7 return shift @{$weak_self->{receive_queue}};
5463 }
5464  
5465 return $sse_disconnect->()
5466 8 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 8 8
5467  
5468 8 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 8 0 8
5469 8 $weak_self->{receive_pending} = Future->new;
5470 }
5471 8 await $weak_self->{receive_pending};
5472 7 $weak_self->{receive_pending} = undef;
5473 }
5474 23 })->();
5475  
5476 # Track this Future
5477 23 push @{$weak_self->{receive_futures}}, $future;
5478 23 @{$weak_self->{receive_futures}} = grep { !$_->is_ready } @{$weak_self->{receive_futures}};
5479  
5480 23 return $future;
5481 58 };
5482 }
5483  
5484 sub _format_sse_event {
5485 98 ▶ my ($event) = @_;
Subroutine _format_sse_event: called CC=11 SCAR=24.0
5486 98 my $sse_data = '';
5487  
5488 98 ▶ if (defined $event->{event} && length $event->{event}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event->{"event"} and length $event->{"event"}) 30 68 98
Condition66%2/3
defined $event->{"event"} and length $event->{"event"}
!ll&&!rl&&r
68030
MC/DC50%1/2
defined $event->{"event"} and length $event->{"event"}
defined $event->{"event"} length $event->{"event"}
Truth table66%2/3
A and B
A= defined $event->{"event"}B= length $event->{"event"}
ABresult
0X0
100
111
5489 die "Invalid SSE event name: contains newline\n"
5490 30 ▶ if $event->{event} =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"event"} =~ /[\r\n]/ 1 29 30
5491 29 $sse_data .= "event: $event->{event}\n";
5492 }
5493  
5494 97 ▶ my $data = $event->{data} // '';
Condition50%1/2
$event->{"data"} // ""
l!l
970
MC/DC0%0/1
$event->{"data"} // ""
$event->{"data"}
Truth table50%1/2
A
A= $event->{"data"}
Aresult
11
00
5495 97 for my $line (split /\r?\n|\r/, $data, -1) {
5496 112 $sse_data .= "data: $line\n";
5497 }
5498  
5499 97 ▶ if (defined $event->{id} && length $event->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event->{"id"} and length $event->{"id"}) 9 88 97
Condition66%2/3
defined $event->{"id"} and length $event->{"id"}
!ll&&!rl&&r
8809
MC/DC50%1/2
defined $event->{"id"} and length $event->{"id"}
defined $event->{"id"} length $event->{"id"}
Truth table66%2/3
A and B
A= defined $event->{"id"}B= length $event->{"id"}
ABresult
0X0
100
111
5500 die "Invalid SSE id: contains newline\n"
5501 9 ▶ if $event->{id} =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"id"} =~ /[\r\n]/ 1 8 9
5502 8 $sse_data .= "id: $event->{id}\n";
5503 }
5504  
5505 96 ▶ if (defined $event->{retry}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event->{"retry"}) 7 89 96
5506 die "Invalid SSE retry: must be a non-negative integer\n"
5507 7 ▶ unless $event->{retry} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"retry"} =~ /\A[0-9]+\z/ 2 5 7
5508 5 $sse_data .= "retry: $event->{retry}\n";
5509 }
5510  
5511 94 $sse_data .= "\n";
5512 94 return $sse_data;
5513 }
5514  
5515 sub _format_sse_comment {
5516 7 ▶ my ($event) = @_;
Subroutine _format_sse_comment: called CC=4 SCAR=13.9
5517 7 ▶ my $text = $event->{comment} // '';
Condition50%1/2
$event->{"comment"} // ""
l!l
70
MC/DC0%0/1
$event->{"comment"} // ""
$event->{"comment"}
Truth table50%1/2
A
A= $event->{"comment"}
Aresult
11
00
5518 7 my $formatted = '';
5519 7 for my $line (split /\r?\n|\r/, $text, -1) {
5520 11 ▶ $line = ":$line" unless $line =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^:/ 10 1 11
5521 11 $formatted .= "$line\n";
5522 }
5523 7 $formatted .= "\n";
5524 7 return $formatted;
5525 }
5526  
5527 sub _create_sse_send {
5528 58 ▶ my ($self, $request) = @_;
Subroutine _create_sse_send: called CC=1 SCAR=0.0
5529  
5530 58 weaken(my $weak_self = $self);
5531 58 my $seq = 'initial';
5532  
5533 543 ▶ return async sub {
Subroutine __ANON__: called CC=44 SCAR=38.7
5534 543 my ($event) = @_;
5535 543 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 543 543
5536  
5537 543 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
5430
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
5538  
5539 # Once the machine has already recorded this stream as closed --
5540 # either an app-initiated sse.close (which closes the transport as a
5541 # side effect of ending the stream) or a completed decline response
5542 # (whose finalize branch also closes the transport as a side
5543 # effect) -- the machine, not the transport-closed check below,
5544 # decides what happens next: idempotent no-op for a repeat
5545 # sse.close, croak for anything else (decline_complete has no
5546 # idempotent case; it croaks unconditionally).
5547 543 ▶ my $already_closed = ($seq eq 'closed' || $seq eq 'decline_complete');
Condition100%3/3
$seq eq 'closed' || $seq eq 'decline_complete'
l!l&&r!l&&!r
31539
MC/DC100%2/2
$seq eq 'closed' || $seq eq 'decline_complete'
$seq eq 'closed' $seq eq 'decline_complete'
Truth table100%3/3
A || B
A= $seq eq 'closed'B= $seq eq 'decline_complete'
ABresult
1X1
011
000
5548  
5549 # Transport already gone for reasons other than our own close (a real
5550 # client disconnect): sends are a silent no-op.
5551 543 ▶ return Future->done if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 398 145 543
Condition100%3/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
1441398
MC/DC100%2/2
$weak_self->{"closed"} and not $already_closed
$weak_self->{"closed"} not $already_closed
Truth table100%3/3
A and not(B)
A= $weak_self->{"closed"}B= not $already_closed
ABresult
0X0
100
111
5552  
5553 # Reset SSE idle timer on send activity (skip once fully closed)
5554 145 ▶ $weak_self->_reset_sse_idle_timer unless $already_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $already_closed 141 4 145
5555  
5556 # Mandatory event validation and sequencing (PAGI spec compliance).
5557 # Order per spec: transport-closed no-op check above runs first.
5558 PAGI::Server::EventValidator::validate_sse_send(
5559 145 $event, { extensions => $weak_self->{extensions} });
5560 142 $seq = PAGI::Server::EventValidator::advance_sse($seq, $event);
5561  
5562 135 ▶ if ($type eq 'sse.start') {
Branch: 8 branches
BranchTrueFalseTotal
if ($type eq 'sse.start') { } 43 92 135
elsif ($type eq 'sse.send') { } 46 46 92
elsif ($type eq 'sse.comment') { } 3 43 46
elsif ($type eq 'sse.keepalive') { } 4 39 43
elsif ($type eq 'sse.close') { } 11 28 39
elsif ($type eq 'sse.http.response.start') { } 14 14 28
elsif ($type eq 'sse.http.response.body') { } 13 1 14
elsif ($type eq 'http.fullflush') { } 1 0 1
5563 43 ▶ return if $weak_self->{sse_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"sse_started"} 0 43 43
5564 43 $weak_self->{sse_started} = 1;
5565 43 $weak_self->{response_started} = 1;
5566  
5567 43 ▶ my $status = $event->{status} // 200;
Condition100%2/2
$event->{"status"} // 200
l!l
412
MC/DC100%1/1
$event->{"status"} // 200
$event->{"status"}
Truth table100%2/2
A
A= $event->{"status"}
Aresult
11
00
5568 43 $weak_self->{response_status} = $status; # Track for access logging
5569 43 ▶ my $headers = $event->{headers} // [];
Condition100%2/2
$event->{"headers"} // []
l!l
2716
MC/DC100%1/1
$event->{"headers"} // []
$event->{"headers"}
Truth table100%2/2
A
A= $event->{"headers"}
Aresult
11
00
5570 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
5571 # strip any app-supplied values before they reach the wire.
5572 43 $headers = _h1_strip_connection_headers($headers);
5573  
5574 # Ensure Content-Type is text/event-stream
5575 43 my $has_content_type = 0;
5576 43 for my $h (@$headers) {
5577 19 ▶ if (lc($h->[0]) eq 'content-type') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-type") 18 1 19
5578 18 $has_content_type = 1;
5579 18 last;
5580 }
5581 }
5582  
5583 43 my @final_headers = @$headers;
5584 43 ▶ if (!$has_content_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_type) 25 18 43
5585 25 push @final_headers, ['content-type', 'text/event-stream'];
5586 }
5587  
5588 # Cache-Control and Date: server-supplied only when the app didn't
5589 # supply them (design doc section 11.4). Connection is a framing
5590 # header the protocol requires the server to control, so it is
5591 # always advertised regardless of what the app sent.
5592 43 ▶ unless (grep { lc($_->[0]) eq 'cache-control' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "cache-control";} @final_headers) 42 1 43
5593 42 push @final_headers, ['cache-control', 'no-cache'];
5594 }
5595 43 push @final_headers, ['connection', 'keep-alive'];
5596 43 ▶ unless (grep { lc($_->[0]) eq 'date' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @final_headers) 42 1 43
5597 42 push @final_headers, ['date', $weak_self->{protocol}->format_date];
5598 }
5599  
5600 # SSE uses chunked encoding implicitly (no Content-Length)
5601 my $response = $weak_self->{protocol}->serialize_response_start(
5602 43 $status, \@final_headers, 1 # chunked = 1
5603 );
5604  
5605 43 $weak_self->{stream}->write($response);
5606  
5607 # Set protocol-specific keepalive writer (HTTP/1.1 chunked)
5608 $weak_self->{sse_keepalive_writer} = sub {
5609 9 ▶ my ($text) = @_;
Subroutine __ANON__: called CC=4 SCAR=14.2
5610 9 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 9 9
5611 9 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 9 9
5612 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at
5613 # the wire boundary — the chunk-size prefix below is on the
5614 # resulting BYTE string.
5615 9 my $bytes = eval { Encode::encode('UTF-8', $text, Encode::FB_CROAK) };
5616 9 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 9 9
5617 9 my $len = sprintf("%x", length($bytes));
5618 9 $weak_self->{stream}->write("$len\r\n$bytes\r\n");
5619 43 };
5620 }
5621 elsif ($type eq 'sse.send') {
5622 46 ▶ return unless $weak_self->{sse_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"sse_started"} 0 46 46
5623  
5624 # --- BACKPRESSURE CHECK ---
5625 46 ▶ if ($weak_self->_get_write_buffer_size >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->_get_write_buffer_size >= $weak_self->{"write_high_watermark"}) 1 45 46
5626 1 await $weak_self->_wait_for_drain;
5627 1 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
5628 1 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 0 1
5629 }
5630 # --- END BACKPRESSURE CHECK ---
5631  
5632 45 my $sse_data = _format_sse_event($event);
5633 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at the
5634 # wire boundary — a failed encode fails this send's Future.
5635 45 my $bytes = eval { Encode::encode('UTF-8', $sse_data, Encode::FB_CROAK) };
5636 45 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 1 44 45
5637  
5638 # Send as chunked data
5639 44 my $len = sprintf("%x", length($bytes));
5640 44 $weak_self->{stream}->write("$len\r\n$bytes\r\n");
5641 44 $weak_self->_notify_transport_write;
5642 }
5643 elsif ($type eq 'sse.comment') {
5644 3 ▶ return unless $weak_self->{sse_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"sse_started"} 0 3 3
5645  
5646 3 my $comment = _format_sse_comment($event);
5647 3 my $bytes = eval { Encode::encode('UTF-8', $comment, Encode::FB_CROAK) };
5648 3 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 3 3
5649  
5650 3 my $len = sprintf("%x", length($bytes));
5651 3 $weak_self->{stream}->write("$len\r\n$bytes\r\n");
5652 }
5653 elsif ($type eq 'sse.keepalive') {
5654 # SSE keepalive - starts/stops periodic comment timer
5655 4 ▶ my $interval = $event->{interval} // 0;
Condition50%1/2
$event->{"interval"} // 0
l!l
40
MC/DC0%0/1
$event->{"interval"} // 0
$event->{"interval"}
Truth table50%1/2
A
A= $event->{"interval"}
Aresult
11
00
5656 4 my $comment = $event->{comment};
5657  
5658 4 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 4 0 4
5659 4 $weak_self->_start_sse_keepalive($interval, $comment);
5660 }
5661 else {
5662 0 $weak_self->_stop_sse_keepalive;
5663 }
5664 }
5665 elsif ($type eq 'sse.close') {
5666 # Explicit application-initiated end of the SSE stream. End it now,
5667 # decoupled from the application returning: the terminator goes out
5668 # here, but the connection's fate is settled by _handle_sse_request
5669 # once the application has actually returned (design section 11.6),
5670 # so the application keeps running against a live transport and its
5671 # further sends are rejected by the sequence machine, not by a
5672 # closed check. `reason` is server-side metadata only and is never
5673 # written to the wire. Idempotency for a repeat sse.close is handled
5674 # by advance_sse (the 'closed' state accepts another sse.close as a
5675 # no-op).
5676 11 $weak_self->{sse_close_sent} = 1;
5677 $weak_self->{sse_disconnect_reason} = $event->{reason}
5678 11 ▶ if defined $event->{reason};
Branch: 1 branch
BranchTrueFalseTotal
if defined $event->{"reason"} 1 10 11
5679 11 ▶ $weak_self->_finish_sse_stream($event->{reason} // 'app_closed');
Condition100%2/2
$event->{"reason"} // "app_closed"
l!l
110
MC/DC100%1/1
$event->{"reason"} // "app_closed"
$event->{"reason"}
Truth table100%2/2
A
A= $event->{"reason"}
Aresult
11
00
5680 }
5681 elsif ($type eq 'sse.http.response.start') {
5682 # Decline the SSE stream and return a normal HTTP response. Valid only
5683 # before sse.start; namespaced under sse. (mirrors websocket.http.response.*).
5684 # A decline-after-start attempt, and a repeat sse.http.response.start,
5685 # are already rejected by advance_sse (the 'declining' state only
5686 # accepts sse.http.response.body).
5687 14 $weak_self->{sse_decline_started} = 1;
5688 14 ▶ $weak_self->{sse_decline_status} = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
140
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
5689 $weak_self->{sse_decline_headers} = [
5690 8 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
5691 14 ▶ @{$event->{headers} // []}
Condition50%1/2
$event->{"headers"} // []
l!l
140
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
5692 ];
5693 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
5694 # strip any app-supplied values before submission.
5695 14 $weak_self->{sse_decline_headers} = _h1_strip_connection_headers($weak_self->{sse_decline_headers});
5696 14 $weak_self->{sse_decline_body} = '';
5697 }
5698 elsif ($type eq 'sse.http.response.body') {
5699 13 ▶ return unless $weak_self->{sse_decline_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"sse_decline_started"} 0 13 13
5700 13 ▶ return if $weak_self->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"response_started"} 0 13 13
5701 13 ▶ $weak_self->{sse_decline_body} .= $event->{body} // '';
Condition50%1/2
$event->{"body"} // ""
l!l
130
MC/DC0%0/1
$event->{"body"} // ""
$event->{"body"}
Truth table50%1/2
A
A= $event->{"body"}
Aresult
11
00
5702 13 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 0 13 13
5703  
5704 13 my $status = $weak_self->{sse_decline_status};
5705 13 my $body = $weak_self->{sse_decline_body};
5706 my @headers = (
5707 13 @{$weak_self->{sse_decline_headers}},
5708 ['content-length', length $body],
5709 );
5710 13 ▶ unless (grep { lc($_->[0]) eq 'date' } @headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @headers) 12 1 13
5711 12 push @headers, ['date', $weak_self->{protocol}->format_date];
5712 }
5713 # This response is always followed by closing the connection; tell
5714 # a keep-alive-pooling client so it doesn't reuse a dead socket.
5715 13 ▶ unless (grep { lc($_->[0]) eq 'connection' } @headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "connection";} @headers) 13 0 13
5716 13 push @headers, ['connection', 'close'];
5717 }
5718 13 my $response = $weak_self->{protocol}->serialize_response_start($status, \@headers, 0);
5719 13 $response .= $body;
5720 13 $weak_self->{stream}->write($response);
5721 13 $weak_self->{response_started} = 1;
5722 13 $weak_self->{response_status} = $status; # access log
5723 # Declined: close the connection (no event stream was started).
5724 # Marked BEFORE teardown so _handle_disconnect and a later
5725 # receive() both know this closure is a completed decline, not
5726 # an abnormal end -- per the spec, a decline delivers no events
5727 # at all, so neither may synthesize sse.disconnect for it.
5728 13 $weak_self->{sse_decline_completed} = 1;
5729 13 $weak_self->_handle_disconnect_and_close('client_closed');
5730 }
5731 elsif ($type eq 'http.fullflush') {
5732 # Fullflush extension - force immediate TCP buffer flush.
5733 # validate_sse_send (called above, unconditionally) already
5734 # croaks "Extension not enabled: fullflush" when the extension
5735 # isn't advertised, so no re-check is needed here.
5736  
5737 # Force flush by ensuring TCP_NODELAY
5738 1 my $handle = $weak_self->{stream}->write_handle;
5739 1 ▶ if ($handle && $handle->can('setsockopt')) {
Branch: 1 branch
BranchTrueFalseTotal
if ($handle and $handle->can("setsockopt")) 1 0 1
Condition33%1/3
$handle and $handle->can("setsockopt")
!ll&&!rl&&r
001
MC/DC0%0/2
$handle and $handle->can("setsockopt")
$handle $handle->can("setsockopt")
Truth table33%1/3
A and B
A= $handleB= $handle->can("setsockopt")
ABresult
0X0
100
111
5740 1 require Socket;
5741 1 $handle->setsockopt(Socket::IPPROTO_TCP(), Socket::TCP_NODELAY(), 1);
5742 }
5743 }
5744  
5745 133 return;
5746 58 };
5747 }
5748  
5749 #
5750 # WebSocket Support Methods
5751 #
5752  
5753 # WebSocket handshake magic GUID per RFC 6455
5754 154 ▶use constant WS_GUID => '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
Subroutine BEGIN: called CC=1 SCAR=0.0
5755  
5756 34 ▶async sub _handle_websocket_request {
Subroutine _handle_websocket_request: called CC=4 SCAR=13.9
5757 34 my ($self, $request) = @_;
5758  
5759 34 $self->_stop_idle_timer; # WebSocket connections are long-lived
5760 34 $self->_start_ws_idle_timer; # Start WebSocket-specific idle timer if configured
5761  
5762 34 my $scope = $self->_create_websocket_scope($request);
5763 34 my $receive = $self->_create_websocket_receive($request);
5764 34 my $send = $self->_create_websocket_send($request);
5765  
5766 34 eval {
5767 34 await $self->{app}->($scope, $receive, $send);
5768 };
5769  
5770 32 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 2 30 32
5771 # If handshake not yet done, send HTTP error
5772 2 ▶ if (!$self->{websocket_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"websocket_accepted"}) 2 0 2
5773 2 $self->_send_error_response(500, "Internal Server Error");
5774 }
5775 2 warn "PAGI application error (WebSocket): $error\n";
5776 }
5777  
5778 # Write access log entry (logs at connection close with total duration)
5779 32 $self->_write_access_log;
5780  
5781 # Notify server that request completed (for max_requests tracking)
5782 32 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 32 0 32
5783  
5784 # Close connection after WebSocket session ends
5785 32 $self->_handle_disconnect_and_close('session_complete');
5786 154 }
5787  
5788 sub _create_websocket_scope {
5789 35 ▶ my ($self, $request) = @_;
Subroutine _create_websocket_scope: called CC=7 SCAR=19.5
5790  
5791 # Extract WebSocket key and subprotocols from headers
5792 35 my $ws_key;
5793 my @subprotocols;
5794  
5795 35 for my $header (@{$request->{headers}}) {
5796 184 my ($name, $value) = @$header;
5797 184 ▶ if ($name eq 'sec-websocket-key') {
Branch: 2 branches
BranchTrueFalseTotal
if ($name eq 'sec-websocket-key') { } 34 150 184
elsif ($name eq 'sec-websocket-protocol') { } 2 148 150
5798 34 $ws_key = $value;
5799 }
5800 elsif ($name eq 'sec-websocket-protocol') {
5801 # Parse comma-separated list of subprotocols
5802 2 push @subprotocols, map { s/^\s+|\s+$//gr } split /,/, $value;
5803 }
5804 }
5805  
5806 # Store ws_key for handshake response
5807 35 $self->{ws_key} = $ws_key;
5808  
5809 my $scope = {
5810 type => 'websocket',
5811 pagi => {
5812 version => '0.5',
5813 spec_version => '0.5',
5814 },
5815 http_version => $request->{http_version},
5816 scheme => $self->_get_ws_scheme,
5817 path => $request->{path},
5818 raw_path => $request->{raw_path},
5819 query_string => $request->{query_string},
5820 root_path => '',
5821 headers => $request->{headers},
5822 (defined $self->{client_host}
5823 ? (client => [$self->{client_host}, $self->{client_port}])
5824 : ()
5825 ),
5826 server => [$self->{server_host}, $self->{server_port}],
5827 subprotocols => \@subprotocols,
5828 # Optimized: avoid hash copy when state is empty (common case)
5829 35 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
5830 extensions => do {
5831 35 my %ext = (%{$self->_get_extensions_for_scope}, 'websocket.http.response' => {});
5832 # fullflush has no validate_websocket_send arm; advertising it here
5833 # would lie to the app (design 13.2).
5834 35 delete $ext{fullflush};
5835 35 ▶ \%ext;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'max_ws_frame_size'} ? : 33 2 35
5836 },
5837 # max_frame_size: omitted when unenforced (max_ws_frame_size 0/undef
5838 # means unlimited, per Protocol::WebSocket::Frame's max_payload_size
5839 # semantics -- a server that does not enforce a cap must not
5840 # advertise one). max_receive_queue has no unlimited mode (a hard,
5841 # always-enforced cap), so it is always present.
5842 ($self->{max_ws_frame_size}
5843 ? (max_frame_size => $self->{max_ws_frame_size})
5844 : ()
5845 ),
5846 max_receive_queue => $self->{max_receive_queue},
5847 # Outbound flow-control introspection (buffered_amount, watermarks,
5848 # on_high_water/on_drain). Stashed on the connection too, so the send
5849 # path can poke _check_watermarks after each write.
5850 35 ▶ 'pagi.transport' => ($self->{current_transport_state} = $self->_h1_transport_state),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 35 0 35
keys %{$$self{'state'};} ? : 0 35 35
5851 };
5852  
5853 35 return $scope;
5854 }
5855  
5856 sub _create_websocket_receive {
5857 36 ▶ my ($self, $request) = @_;
Subroutine _create_websocket_receive: called CC=1 SCAR=0.3
5858  
5859 36 my $connect_sent = 0;
5860 36 weaken(my $weak_self = $self);
5861  
5862 return sub {
5863 175 ▶ return Future->done({ type => 'websocket.disconnect', code => 1006, reason => '' })
Subroutine __ANON__: called CC=4 SCAR=15.1
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 175 175
5864 unless $weak_self;
5865  
5866 # Check queue first - drain queued messages even if closed
5867 175 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 113 62 175
5868 113 return Future->done(shift @{$weak_self->{receive_queue}});
5869 }
5870  
5871 # $weak_self is known live here, so the fallback can report the
5872 # abnormal reason a server-initiated close recorded (idle timeout,
5873 # queue overflow, ...) instead of an always-empty ''.
5874 return Future->done($weak_self->_ws_disconnect_event)
5875 62 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 3 59 62
5876  
5877 59 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=13 SCAR=32.3
5878 59 ▶ return { type => 'websocket.disconnect', code => 1006, reason => '' }
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 59 59
5879 unless $weak_self;
5880  
5881 # Check queue first - drain queued messages even if closed
5882 59 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 59 59
5883 0 return shift @{$weak_self->{receive_queue}};
5884 }
5885  
5886 return $weak_self->_ws_disconnect_event
5887 59 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 59 59
5888  
5889 # First call returns websocket.connect
5890 59 ▶ if (!$connect_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($connect_sent) 30 29 59
5891 30 $connect_sent = 1;
5892 30 return { type => 'websocket.connect' };
5893 }
5894  
5895 # If not in WebSocket mode yet (waiting for accept), wait
5896 29 ▶ while (!$weak_self->{websocket_mode} && !$weak_self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"websocket_mode"} or $weak_self->{"closed"}) 0 29 29
Condition33%1/3
$weak_self->{"websocket_mode"} or $weak_self->{"closed"}
l!l&&r!l&&!r
2900
MC/DC0%0/2
$weak_self->{"websocket_mode"} or $weak_self->{"closed"}
$weak_self->{"websocket_mode"} $weak_self->{"closed"}
Truth table33%1/3
A or B
A= $weak_self->{"websocket_mode"}B= $weak_self->{"closed"}
ABresult
1X1
011
000
5897 0 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 0 0 0
5898 0 $weak_self->{receive_pending} = Future->new;
5899 }
5900 0 await $weak_self->{receive_pending};
5901 0 $weak_self->{receive_pending} = undef;
5902  
5903 0 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 0 0
5904 0 return shift @{$weak_self->{receive_queue}};
5905 }
5906 }
5907  
5908 return $weak_self->_ws_disconnect_event
5909 29 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 29 29
5910  
5911 # Wait for events from frame processing
5912 29 while (1) {
5913 58 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 29 29 58
5914 29 return shift @{$weak_self->{receive_queue}};
5915 }
5916  
5917 return $weak_self->_ws_disconnect_event
5918 29 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 29 29
5919  
5920 29 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 29 0 29
5921 29 $weak_self->{receive_pending} = Future->new;
5922 }
5923 29 await $weak_self->{receive_pending};
5924 29 $weak_self->{receive_pending} = undef;
5925 }
5926 59 })->();
5927  
5928 # Track this Future
5929 59 push @{$weak_self->{receive_futures}}, $future;
5930 59 @{$weak_self->{receive_futures}} = grep { !$_->is_ready } @{$weak_self->{receive_futures}};
5931  
5932 59 return $future;
5933 36 };
5934 }
5935  
5936 sub _create_websocket_send {
5937 34 ▶ my ($self, $request) = @_;
Subroutine _create_websocket_send: called CC=1 SCAR=0.1
5938  
5939 34 weaken(my $weak_self = $self);
5940 34 my $seq = 'connecting';
5941  
5942 468 ▶ return async sub {
Subroutine __ANON__: called CC=41 SCAR=39.4
5943 468 my ($event) = @_;
5944 468 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 468 468
5945  
5946 # Once the machine has recorded the connection closed or the denial
5947 # response complete, the machine decides what happens next -- both
5948 # 'closed' and 'denial_complete' have no idempotent case, so any
5949 # further send always raises -- not the transport-closed check below.
5950 # Only app-initiated terminals get this carve-out: websocket.close
5951 # itself flips {closed} synchronously via _handle_disconnect_and_close
5952 # when the client had already sent its own close frame first, but
5953 # that's still the app's own logical close (it chose to answer with
5954 # websocket.close), so a post-close send from the app is a protocol
5955 # violation, not a benign transport no-op. A real client disconnect
5956 # with no app-initiated terminal in play still falls through to the
5957 # plain no-op below.
5958 468 ▶ my $already_closed = ($seq eq 'closed' || $seq eq 'denial_complete');
Condition100%3/3
$seq eq 'closed' || $seq eq 'denial_complete'
l!l&&r!l&&!r
11466
MC/DC100%2/2
$seq eq 'closed' || $seq eq 'denial_complete'
$seq eq 'closed' $seq eq 'denial_complete'
Truth table100%3/3
A || B
A= $seq eq 'closed'B= $seq eq 'denial_complete'
ABresult
1X1
011
000
5959  
5960 468 ▶ return Future->done if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 398 70 468
Condition100%3/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
691398
MC/DC100%2/2
$weak_self->{"closed"} and not $already_closed
$weak_self->{"closed"} not $already_closed
Truth table100%3/3
A and not(B)
A= $weak_self->{"closed"}B= not $already_closed
ABresult
0X0
100
111
5961  
5962 # Reset WebSocket idle timer on send activity
5963 70 $weak_self->_reset_ws_idle_timer;
5964  
5965 70 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
700
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
5966  
5967 # Mandatory event validation and sequencing (PAGI spec compliance).
5968 # Order per spec: transport-closed no-op check above runs first.
5969 # websocket.http.response is always available on this path (the scope
5970 # advertises it unconditionally; see _create_websocket_scope), unlike
5971 # connection-level extensions such as fullflush.
5972 PAGI::Server::EventValidator::validate_websocket_send(
5973 70 $event, { extensions => { %{$weak_self->{extensions}}, 'websocket.http.response' => {} } });
5974 68 $seq = PAGI::Server::EventValidator::advance_websocket($seq, $event);
5975  
5976 65 ▶ if ($type eq 'websocket.accept') {
Branch: 6 branches
BranchTrueFalseTotal
if ($type eq 'websocket.accept') { } 28 37 65
elsif ($type eq 'websocket.send') { } 22 15 37
elsif ($type eq 'websocket.http.response.start') { } 4 11 15
elsif ($type eq 'websocket.http.response.body') { } 4 7 11
elsif ($type eq 'websocket.close') { } 6 1 7
elsif ($type eq 'websocket.keepalive') { } 1 0 1
5977 # A duplicate accept is already rejected by advance_websocket.
5978  
5979 # Complete the WebSocket handshake
5980 28 my $ws_key = $weak_self->{ws_key};
5981 28 my $accept_key = sha1_base64($ws_key . WS_GUID);
5982 # sha1_base64 doesn't add padding, but WebSocket requires it
5983 28 ▶ $accept_key .= '=' while length($accept_key) % 4;
Branch: 1 branch
BranchTrueFalseTotal
length($accept_key) % 4 and do { $accept_key .= '=' } 28 28 56
5984  
5985 28 my @headers = (
5986 "HTTP/1.1 101 Switching Protocols\r\n",
5987 "Upgrade: websocket\r\n",
5988 "Connection: Upgrade\r\n",
5989 "Sec-WebSocket-Accept: $accept_key\r\n",
5990 );
5991  
5992 # Add subprotocol if specified (with validation)
5993 28 ▶ if (my $subprotocol = $event->{subprotocol}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $subprotocol = $event->{"subprotocol"}) 1 27 28
5994 1 $subprotocol = _validate_subprotocol($subprotocol);
5995 0 push @headers, "Sec-WebSocket-Protocol: $subprotocol\r\n";
5996 }
5997  
5998 # Add custom headers if specified (with CRLF injection validation).
5999 # The server's own "Connection: Upgrade" line above is untouched
6000 # (RFC 6455 requires it) -- strip the app's extra headers the same
6001 # way every other h1 response-header path already does, so an
6002 # app-supplied connection/transfer-encoding value can't duplicate
6003 # or contradict it on the wire.
6004 27 ▶ if (my $extra_headers = $event->{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $extra_headers = $event->{"headers"}) 1 26 27
6005 1 $extra_headers = _h1_strip_connection_headers($extra_headers);
6006 1 for my $h (@$extra_headers) {
6007 1 my ($name, $value) = @$h;
6008 1 $name = _validate_header_name($name);
6009 1 $value = _validate_header_value($value);
6010 1 push @headers, "$name: $value\r\n";
6011 }
6012 }
6013  
6014 27 push @headers, "\r\n";
6015  
6016 27 $weak_self->{stream}->write(join('', @headers));
6017  
6018 # Switch to WebSocket mode
6019 27 $weak_self->{websocket_mode} = 1;
6020 27 $weak_self->{websocket_accepted} = 1;
6021 $weak_self->{websocket_frame} = Protocol::WebSocket::Frame->new(
6022 max_payload_size => $weak_self->{max_ws_frame_size},
6023 27 );
6024 27 $weak_self->{response_status} = 101; # Track for access logging
6025  
6026 # Notify any waiting receive
6027 27 ▶ if ($weak_self->{receive_pending} && !$weak_self->{receive_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready) 0 27 27
Condition33%1/3
$weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready
!ll&&!rl&&r
2700
MC/DC0%0/2
$weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready
$weak_self->{"receive_pending"} not $weak_self->{"receive_pending"}->is_ready
Truth table33%1/3
A and not(B)
A= $weak_self->{"receive_pending"}B= not $weak_self->{"receive_pending"}->is_ready
ABresult
0X0
100
111
6028 0 my $f = $weak_self->{receive_pending};
6029 0 $weak_self->{receive_pending} = undef;
6030 0 $f->done;
6031 }
6032  
6033 # Process any data that arrived before accept
6034 27 ▶ if (length($weak_self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weak_self->{"buffer"} > 0) 0 27 27
6035 0 $weak_self->_process_websocket_frames;
6036 }
6037 }
6038 elsif ($type eq 'websocket.send') {
6039 22 ▶ return unless $weak_self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"websocket_mode"} 0 22 22
6040  
6041 # --- BACKPRESSURE CHECK ---
6042 22 ▶ if ($weak_self->_get_write_buffer_size >= $weak_self->{write_high_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->_get_write_buffer_size >= $weak_self->{"write_high_watermark"}) 1 21 22
6043 1 await $weak_self->_wait_for_drain;
6044 1 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
6045 1 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 0 1
6046 }
6047 # --- END BACKPRESSURE CHECK ---
6048  
6049 21 my $frame;
6050 21 ▶ if (defined $event->{text}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $event->{'text'}) { } 18 3 21
elsif (defined $event->{'bytes'}) { } 3 0 3
6051 $frame = Protocol::WebSocket::Frame->new(
6052 buffer => $event->{text},
6053 18 type => 'text',
6054 );
6055 }
6056 elsif (defined $event->{bytes}) {
6057 $frame = Protocol::WebSocket::Frame->new(
6058 buffer => $event->{bytes},
6059 3 type => 'binary',
6060 );
6061 }
6062 else {
6063 0 return; # Nothing to send
6064 }
6065  
6066 21 my $bytes = $frame->to_bytes;
6067 21 $weak_self->{stream}->write($bytes);
6068 21 $weak_self->_notify_transport_write;
6069 }
6070 elsif ($type eq 'websocket.http.response.start') {
6071 # Custom handshake denial (websocket.http.response extension). Only
6072 # valid before accept; buffer the response head until the body
6073 # arrives.
6074 4 ▶ return if $weak_self->{websocket_accepted};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"websocket_accepted"} 0 4 4
6075 4 ▶ return if $weak_self->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"ws_denial_started"} 0 4 4
6076 4 $weak_self->{ws_denial_started} = 1;
6077 4 ▶ $weak_self->{ws_denial_status} = $event->{status} // 403;
Condition50%1/2
$event->{"status"} // 403
l!l
40
MC/DC0%0/1
$event->{"status"} // 403
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
6078 $weak_self->{ws_denial_headers} = [
6079 8 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
6080 4 ▶ @{$event->{headers} // []}
Condition50%1/2
$event->{"headers"} // []
l!l
40
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
6081 ];
6082 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
6083 # strip any app-supplied values before submission.
6084 4 $weak_self->{ws_denial_headers} = _h1_strip_connection_headers($weak_self->{ws_denial_headers});
6085 4 $weak_self->{ws_denial_body} = '';
6086 }
6087 elsif ($type eq 'websocket.http.response.body') {
6088 4 ▶ return unless $weak_self->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"ws_denial_started"} 0 4 4
6089 4 ▶ return if $weak_self->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"response_started"} 0 4 4
6090 4 ▶ $weak_self->{ws_denial_body} .= $event->{body} // '';
Condition50%1/2
$event->{"body"} // ""
l!l
40
MC/DC0%0/1
$event->{"body"} // ""
$event->{"body"}
Truth table50%1/2
A
A= $event->{"body"}
Aresult
11
00
6091 4 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 0 4 4
6092  
6093 4 my $status = $weak_self->{ws_denial_status};
6094 4 my $body = $weak_self->{ws_denial_body};
6095 my @headers = (
6096 4 @{$weak_self->{ws_denial_headers}},
6097 ['content-length', length $body],
6098 );
6099 4 ▶ unless (grep { lc($_->[0]) eq 'date' } @headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @headers) 3 1 4
6100 3 push @headers, ['date', $weak_self->{protocol}->format_date];
6101 }
6102 4 my $response = $weak_self->{protocol}->serialize_response_start($status, \@headers, 0);
6103 4 $response .= $body;
6104 4 $weak_self->{stream}->write($response);
6105 4 $weak_self->{response_started} = 1;
6106 4 $weak_self->{response_status} = $status; # access log
6107 # Handshake rejected: close like the bare-403 path (no upgrade).
6108 4 $weak_self->_handle_disconnect_and_close('client_closed');
6109 }
6110 elsif ($type eq 'websocket.close') {
6111 # If not accepted yet, send 403 Forbidden
6112 6 ▶ if (!$weak_self->{websocket_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"websocket_accepted"}) 1 5 6
6113 1 $weak_self->_send_error_response(403, 'Forbidden');
6114 1 return;
6115 }
6116  
6117 # Send close frame
6118 5 ▶ my $code = $event->{code} // 1000;
Condition100%2/2
$event->{"code"} // 1000
l!l
14
MC/DC100%1/1
$event->{"code"} // 1000
$event->{"code"}
Truth table100%2/2
A
A= $event->{"code"}
Aresult
11
00
6119 5 ▶ my $reason = $event->{reason} // '';
Condition50%1/2
$event->{"reason"} // ""
l!l
05
MC/DC0%0/1
$event->{"reason"} // ""
$event->{"reason"}
Truth table50%1/2
A
A= $event->{"reason"}
Aresult
11
00
6120  
6121 5 my $frame = Protocol::WebSocket::Frame->new(
6122 type => 'close',
6123 buffer => pack('n', $code) . $reason,
6124 );
6125  
6126 5 $weak_self->{stream}->write($frame->to_bytes);
6127 5 $weak_self->{close_sent} = 1;
6128  
6129 # If we received a close frame, close immediately
6130 # Otherwise wait for close from client (handled in frame processing)
6131 5 ▶ if ($weak_self->{close_received}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"close_received"}) 0 5 5
6132 0 $weak_self->_handle_disconnect_and_close('client_closed');
6133 }
6134 }
6135 elsif ($type eq 'websocket.keepalive') {
6136 1 ▶ return unless $weak_self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"websocket_mode"} 0 1 1
6137  
6138 1 ▶ my $interval = $event->{interval} // 0;
Condition50%1/2
$event->{"interval"} // 0
l!l
10
MC/DC0%0/1
$event->{"interval"} // 0
$event->{"interval"}
Truth table50%1/2
A
A= $event->{"interval"}
Aresult
11
00
6139 1 my $timeout = $event->{timeout};
6140  
6141 1 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 1 0 1
6142 1 $weak_self->_start_ws_keepalive($interval, $timeout);
6143 }
6144 else {
6145 0 $weak_self->_stop_ws_keepalive;
6146 }
6147 }
6148  
6149 62 return;
6150 34 };
6151 }
6152  
6153 sub _process_websocket_frames {
6154 27 ▶ my ($self) = @_;
Subroutine _process_websocket_frames: called CC=41 SCAR=50.6
6155  
6156 27 ▶ return unless $self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"websocket_mode"} 0 27 27
6157 27 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 27 27
6158  
6159 # Reset WebSocket idle timer on receive activity
6160 27 $self->_reset_ws_idle_timer;
6161  
6162 27 my $frame = $self->{websocket_frame};
6163  
6164 # Append buffer to frame parser
6165 27 $frame->append($self->{buffer});
6166 27 $self->{buffer} = '';
6167  
6168 # Process all complete frames - use next_bytes to get raw bytes
6169 # Protocol::WebSocket::Frame->next() decodes as UTF-8, which corrupts binary data
6170 27 ▶ while (defined(my $bytes = $frame->next_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $bytes = $frame->next_bytes)) 132 22 154
6171 132 my $opcode = $frame->opcode;
6172  
6173 # RFC 6455 Section 5.2: RSV1-3 MUST be 0 unless extension defines meaning
6174 # PAGI doesn't support compression extensions, so RSV must always be 0
6175 132 my $rsv = $frame->rsv;
6176 132 ▶ if ($rsv && ref($rsv) eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($rsv and ref $rsv eq "ARRAY") 132 0 132
Condition33%1/3
$rsv and ref $rsv eq "ARRAY"
!ll&&!rl&&r
00132
MC/DC0%0/2
$rsv and ref $rsv eq "ARRAY"
$rsv ref $rsv eq "ARRAY"
Truth table33%1/3
A and B
A= $rsvB= ref $rsv eq "ARRAY"
ABresult
0X0
100
111
6177 132 ▶ if (grep { $_ } @$rsv) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_;} @$rsv) 0 132 132
6178 0 $self->_send_close_frame(1002, 'RSV bits must be 0');
6179 0 $self->_handle_disconnect_and_close('protocol_error');
6180 0 return;
6181 }
6182 }
6183  
6184 # RFC 6455 Section 5.2: Opcodes 3-7 and 11-15 (0xB-0xF) are reserved
6185 # Must fail connection with 1002 Protocol Error
6186 132 ▶ if (($opcode >= 3 && $opcode <= 7) || ($opcode >= 11 && $opcode <= 15)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15) 0 132 132
Condition44%4/9
$opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15
l!l&&r!l&&!r
00132
$opcode >= 3 and $opcode <= 7
!ll&&!rl&&r
13110
$opcode >= 11 and $opcode <= 15
!ll&&!rl&&r
13200
MC/DC0%0/4
$opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15
$opcode >= 3 $opcode <= 7 $opcode >= 11 $opcode <= 15
Truth table0%0/7
A and B or C and D
A= $opcode >= 3B= $opcode <= 7C= $opcode >= 11D= $opcode <= 15
ABCDresult
11XX1
0X111
10111
0X0X0
0X100
100X0
10100
6187 0 $self->_send_close_frame(1002, 'Reserved opcode');
6188 0 $self->_handle_disconnect_and_close('protocol_error');
6189 0 return;
6190 }
6191  
6192 # RFC 6455 Section 5.5: Control frames (close/ping/pong) MUST have
6193 # payload length <= 125 bytes
6194 132 ▶ if (($opcode == 8 || $opcode == 9 || $opcode == 10) && length($bytes) > 125) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opcode == 8 || $opcode == 9 || $opcode == 10 and length $bytes > 125) 0 132 132
Condition66%6/9
$opcode == 8 || $opcode == 9 || $opcode == 10 and length $bytes > 125
!ll&&!rl&&r
13110
$opcode == 8 or $opcode == 9 or $opcode == 10
l!l&&r!l&&!r
10131
$opcode == 8 or $opcode == 9
l!l&&r!l&&!r
10131
MC/DC0%0/4
$opcode == 8 || $opcode == 9 || $opcode == 10 and length $bytes > 125
$opcode == 8 $opcode == 9 $opcode == 10 length $bytes > 125
Truth table28%2/7
A or B or C and D
A= $opcode == 8B= $opcode == 9C= $opcode == 10D= length $bytes > 125
ABCDresult
000X0
1XX00
01X00
00100
1XX11
01X11
00111
6195 0 $self->_send_close_frame(1002, 'Control frame too large');
6196 0 $self->_handle_disconnect_and_close('protocol_error');
6197 0 return;
6198 }
6199  
6200 132 ▶ if ($opcode == 1) {
Branch: 5 branches
BranchTrueFalseTotal
if ($opcode == 1) { } 130 2 132
elsif ($opcode == 2) { } 1 1 2
elsif ($opcode == 8) { } 1 0 1
elsif ($opcode == 9) { } 0 0 0
elsif ($opcode == 10) { } 0 0 0
6201 # Text frame - decode as UTF-8
6202 130 my $text = eval { Encode::decode('UTF-8', $bytes, Encode::FB_CROAK) };
6203 130 ▶ unless (defined $text) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $text) 2 128 130
6204 # Invalid UTF-8 - close with 1007 per RFC 6455
6205 2 $self->_send_close_frame(1007, 'Invalid UTF-8');
6206 2 $self->_handle_disconnect_and_close('protocol_error');
6207 2 return;
6208 }
6209 # Check queue limit before adding (DoS protection)
6210 128 ▶ if (@{$self->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"receive_queue"};} >= $self->{"max_receive_queue"}) 2 126 128
6211 2 $self->_send_close_frame(1008, 'Message queue overflow');
6212 2 $self->_handle_disconnect_and_close('queue_overflow');
6213 2 return;
6214 }
6215 126 push @{$self->{receive_queue}}, {
6216 type => 'websocket.receive',
6217 text => $text,
6218 };
6219 }
6220 elsif ($opcode == 2) {
6221 # Binary frame - keep as raw bytes
6222 # Check queue limit before adding (DoS protection)
6223 1 ▶ if (@{$self->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"receive_queue"};} >= $self->{"max_receive_queue"}) 0 1 1
6224 0 $self->_send_close_frame(1008, 'Message queue overflow');
6225 0 $self->_handle_disconnect_and_close('queue_overflow');
6226 0 return;
6227 }
6228 1 push @{$self->{receive_queue}}, {
6229 type => 'websocket.receive',
6230 bytes => $bytes,
6231 };
6232 }
6233 elsif ($opcode == 8) {
6234 # Close frame
6235 1 $self->{close_received} = 1;
6236 1 my ($code, $reason) = (1005, '');
6237  
6238 # RFC 6455 Section 5.5.1: Close frame payload is 0 or >=2 bytes
6239 # 1 byte is invalid
6240 1 ▶ if (length($bytes) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes == 1) 0 1 1
6241 0 $self->_send_close_frame(1002, 'Invalid close frame');
6242 0 $self->_handle_disconnect_and_close('protocol_error');
6243 0 return;
6244 }
6245  
6246 1 ▶ if (length($bytes) >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes >= 2) 1 0 1
6247 1 $code = unpack('n', substr($bytes, 0, 2));
6248 1 ▶ $reason = substr($bytes, 2) // '';
Condition50%1/2
substr($bytes, 2) // ""
l!l
10
MC/DC0%0/1
substr($bytes, 2) // ""
substr($bytes, 2)
Truth table50%1/2
A
A= substr($bytes, 2)
Aresult
11
00
6249  
6250 # RFC 6455 Section 7.4.1: Validate close code
6251 # Valid codes: 1000-1003, 1007-1011, 3000-4999
6252 # Invalid: 0-999, 1004-1006, 1012-2999, 5000+
6253 1 my $valid_code = 0;
6254 1 ▶ if ($code == 1000 || $code == 1001 || $code == 1002 || $code == 1003) {
Branch: 3 branches
BranchTrueFalseTotal
if ($code == 1000 or $code == 1001 or $code == 1002 or $code == 1003) { } 1 0 1
elsif ($code >= 1007 and $code <= 1011) { } 0 0 0
elsif ($code >= 3000 and $code <= 4999) { } 0 0 0
Condition33%3/9
$code == 1000 or $code == 1001 or $code == 1002 or $code == 1003
l!l&&r!l&&!r
100
$code == 1000 or $code == 1001 or $code == 1002
l!l&&r!l&&!r
100
$code == 1000 or $code == 1001
l!l&&r!l&&!r
100
MC/DC0%0/4
$code == 1000 or $code == 1001 or $code == 1002 or $code == 1003
$code == 1000 $code == 1001 $code == 1002 $code == 1003
Truth table20%1/5
A or B or C or D
A= $code == 1000B= $code == 1001C= $code == 1002D= $code == 1003
ABCDresult
1XXX1
01XX1
001X1
00011
00000
6255 1 $valid_code = 1;
6256 }
6257 ▶ elsif ($code >= 1007 && $code <= 1011) {
Condition0%0/3
$code >= 1007 and $code <= 1011
!ll&&!rl&&r
000
MC/DC0%0/2
$code >= 1007 and $code <= 1011
$code >= 1007 $code <= 1011
Truth table0%0/3
A and B
A= $code >= 1007B= $code <= 1011
ABresult
0X0
100
111
6258 0 $valid_code = 1;
6259 }
6260 ▶ elsif ($code >= 3000 && $code <= 4999) {
Condition0%0/3
$code >= 3000 and $code <= 4999
!ll&&!rl&&r
000
MC/DC0%0/2
$code >= 3000 and $code <= 4999
$code >= 3000 $code <= 4999
Truth table0%0/3
A and B
A= $code >= 3000B= $code <= 4999
ABresult
0X0
100
111
6261 0 $valid_code = 1;
6262 }
6263 1 ▶ unless ($valid_code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid_code) 0 1 1
6264 0 $self->_send_close_frame(1002, 'Invalid close code');
6265 0 $self->_handle_disconnect_and_close('protocol_error');
6266 0 return;
6267 }
6268  
6269 # RFC 6455: Close reason must be valid UTF-8
6270 1 ▶ if (length($reason) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $reason > 0) 1 0 1
6271 1 my $reason_copy = $reason;
6272 1 my $decoded = eval { Encode::decode('UTF-8', $reason_copy, Encode::FB_CROAK) };
6273 1 ▶ unless (defined $decoded) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $decoded) 0 1 1
6274 0 $self->_send_close_frame(1007, 'Invalid UTF-8 in close reason');
6275 0 $self->_handle_disconnect_and_close('protocol_error');
6276 0 return;
6277 }
6278 }
6279 }
6280  
6281 # If we haven't sent close yet, send it now
6282 1 ▶ if (!$self->{close_sent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"close_sent"}) 1 0 1
6283 1 my $close_frame = Protocol::WebSocket::Frame->new(
6284 type => 'close',
6285 buffer => pack('n', $code) . $reason,
6286 );
6287 1 $self->{stream}->write($close_frame->to_bytes);
6288 1 $self->{close_sent} = 1;
6289 }
6290  
6291 1 push @{$self->{receive_queue}}, {
6292 type => 'websocket.disconnect',
6293 code => $code,
6294 reason => $reason,
6295 };
6296  
6297 # This is the scope's one and only websocket.disconnect: mark
6298 # disconnect-handled now (the same guard _handle_disconnect
6299 # checks) so a later TCP close (on_closed -> client_closed) or
6300 # the app's own session-complete teardown finds the guard
6301 # already set and delivers nothing further. Without this, either
6302 # of those paths queues a second, ghost disconnect event that
6303 # nobody asked for and nobody drains (h2's equivalent guard is
6304 # ws_disconnect_delivered / _h2_ws_enqueue_disconnect).
6305 1 $self->{_disconnect_handled} = 1;
6306 }
6307 elsif ($opcode == 9) {
6308 # Ping - respond with pong (transparent to app)
6309 0 my $pong = Protocol::WebSocket::Frame->new(
6310 type => 'pong',
6311 buffer => $bytes,
6312 );
6313 0 $self->{stream}->write($pong->to_bytes);
6314 }
6315 elsif ($opcode == 10) {
6316 # Pong - cancel any pending timeout (response to our ping)
6317 0 $self->_cancel_ws_pong_timeout;
6318 }
6319 }
6320  
6321 # Notify any waiting receive
6322 22 ▶ if ($self->{receive_pending} && !$self->{receive_pending}->is_ready && @{$self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready and @{$self->{"receive_queue"};}) 12 10 22
Condition66%4/6
$self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready and @{$self->{"receive_queue"};}
!ll&&!rl&&r
10012
$self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready
!ll&&!rl&&r
10012
MC/DC33%1/3
$self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready and @{$self->{"receive_queue"};}
$self->{"receive_pending"} not $self->{"receive_pending"}->is_ready @{$self->{"receive_queue"};}
Truth table50%2/4
A and not(B) and C
A= $self->{"receive_pending"}B= not $self->{"receive_pending"}->is_readyC= @{$self->{"receive_queue"};}
ABCresult
0XX0
10X0
1100
1111
6323 12 my $f = $self->{receive_pending};
6324 12 $self->{receive_pending} = undef;
6325 12 $f->done;
6326 }
6327 }
6328  
6329 # Async file response - prioritizes speed based on file size:
6330 # 1. Small files (<=64KB): direct in-process read (fastest for small files)
6331 # 2. Large files: async chunked reads via worker pool (non-blocking)
6332 13 ▶async sub _send_file_response {
Subroutine _send_file_response: called CC=14 SCAR=26.6
6333 13 my ($self, $file, $offset, $length, $chunked) = @_;
6334  
6335 # Get file size if length not specified
6336 13 my $file_size = -s $file;
6337 13 ▶ die "Cannot stat file $file: $!\n" unless defined $file_size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_size 0 13 13
6338 13 ▶ $length //= $file_size - $offset;
Condition66%2/3
$length //= $file_size - $offset
l!l&&r!l&&!r
1120
MC/DC0%0/2
$length //= $file_size - $offset
$length $file_size - $offset
Truth table66%2/3
A //= B
A= $lengthB= $file_size - $offset
ABresult
1X1
011
000
6339  
6340 # PAGI spec (Www.pod, Response Body validation): an offset past the end
6341 # of the file SHOULD send zero bytes rather than fail the response.
6342 13 ▶ $length = 0 if $length < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length < 0 2 11 13
6343  
6344 13 $self->{_response_size} += $length;
6345  
6346 13 my $stream = $self->{stream};
6347  
6348 13 ▶ if ($self->{sync_file_threshold} > 0 && $length <= $self->{sync_file_threshold}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'sync_file_threshold'} > 0 and $length <= $self->{'sync_file_threshold'}) { } 10 3 13
Condition66%2/3
$self->{"sync_file_threshold"} > 0 and $length <= $self->{"sync_file_threshold"}
!ll&&!rl&&r
0310
MC/DC50%1/2
$self->{"sync_file_threshold"} > 0 and $length <= $self->{"sync_file_threshold"}
$self->{"sync_file_threshold"} > 0 $length <= $self->{"sync_file_threshold"}
Truth table66%2/3
A and B
A= $self->{"sync_file_threshold"} > 0B= $length <= $self->{"sync_file_threshold"}
ABresult
0X0
100
111
6349 # Small file fast path: read directly in-process
6350 # For files <= 64KB, a simple read() is fast and avoids async overhead
6351 10 ▶ open my $fh, '<:raw', $file or die "Cannot open file $file: $!";
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<:raw", $file or die "Cannot open file ${file}: $!" 0 10 10
6352 10 ▶ seek($fh, $offset, 0) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 4 6 10
6353 10 my $bytes_read = read($fh, my $data, $length);
6354 10 close $fh;
6355  
6356 10 ▶ die "Failed to read file $file: $!" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 0 10 10
6357  
6358 10 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 2 8 10
6359 # A zero-length body IS the terminator chunk -- writing a
6360 # separate empty data chunk before it would send "0\r\n\r\n"
6361 # twice and desync the connection.
6362 2 ▶ if (length($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data) 1 1 2
6363 1 my $len = sprintf("%x", length($data));
6364 1 $stream->write("$len\r\n$data\r\n");
6365 }
6366 2 $stream->write("0\r\n\r\n");
6367 }
6368 else {
6369 8 $stream->write($data);
6370 }
6371 }
6372 else {
6373 # Large file path: async chunked reads via worker pool
6374 3 ▶ my $loop = $self->{server} ? $self->{server}->loop : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'server'} ? : 3 0 3
6375 3 ▶ die "No event loop available for async file I/O" unless $loop;
Branch: 1 branch
BranchTrueFalseTotal
unless $loop 0 3 3
6376  
6377 await PAGI::Server::AsyncFile->read_file_chunked(
6378 $loop, $file,
6379 sub {
6380 6 ▶ my ($chunk) = @_;
Subroutine __ANON__: called CC=2 SCAR=6.9
6381 6 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 2 4 6
6382 2 my $len = sprintf("%x", length($chunk));
6383 2 $stream->write("$len\r\n$chunk\r\n");
6384 }
6385 else {
6386 4 $stream->write($chunk);
6387 }
6388 6 return; # Sync callback
6389 },
6390 3 offset => $offset,
6391 length => $length,
6392 chunk_size => FILE_CHUNK_SIZE,
6393 );
6394  
6395 # Send final chunk terminator if chunked
6396 3 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) 1 2 3
6397 1 $stream->write("0\r\n\r\n");
6398 }
6399 }
6400 154 }
6401  
6402 # Async filehandle response - synchronous chunked reads in the send loop
6403 # (the fh can't cross a fork into the worker pool; see below).
6404 # Note: Can't easily use sendfile for arbitrary filehandles (may not have fd,
6405 # may be pipes, may be in-memory). Falls back to chunked reads.
6406 9 ▶async sub _send_fh_response {
Subroutine _send_fh_response: called CC=12 SCAR=24.9
6407 9 my ($self, $fh, $offset, $length, $chunked) = @_;
6408  
6409 # Seek to offset if specified
6410 9 ▶ if ($offset && $offset > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset and $offset > 0) 3 6 9
Condition66%2/3
$offset and $offset > 0
!ll&&!rl&&r
603
MC/DC50%1/2
$offset and $offset > 0
$offset $offset > 0
Truth table66%2/3
A and B
A= $offsetB= $offset > 0
ABresult
0X0
100
111
6411 3 ▶ seek($fh, $offset, 0) or die "Cannot seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $offset, 0 or die "Cannot seek: $!" 1 2 3
6412 }
6413  
6414 # For filehandles, we can't easily use the worker pool (can't pass fh across fork).
6415 # Use blocking reads in small chunks - not ideal but practical.
6416 # TODO: Consider IO::Async::FileStream for better event loop integration.
6417  
6418 8 my $remaining = $length; # undef means read to EOF
6419 8 my $stream = $self->{stream};
6420  
6421 8 while (1) {
6422 14 my $to_read = FILE_CHUNK_SIZE;
6423 14 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 5 9 14
6424 5 ▶ $to_read = $remaining if $remaining < $to_read;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining < $to_read 5 0 5
6425 5 ▶ last if $to_read <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $to_read <= 0 2 3 5
6426 }
6427  
6428 12 my ($bytes_read, $chunk);
6429 {
6430 154 ▶ no warnings 'closed';
Subroutine BEGIN: called CC=1 SCAR=0.0
6431 12 $bytes_read = read($fh, $chunk, $to_read);
6432 }
6433  
6434 12 ▶ die "Failed to read filehandle: $!\n" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 1 11 12
6435 11 ▶ last if $bytes_read == 0; # EOF
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_read == 0 5 6 11
6436  
6437 6 $self->{_response_size} += $bytes_read;
6438  
6439 6 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 3 3 6
6440 3 my $len = sprintf("%x", length($chunk));
6441 3 $stream->write("$len\r\n$chunk\r\n");
6442 }
6443 else {
6444 3 $stream->write($chunk);
6445 }
6446  
6447 6 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 2 4 6
6448 2 $remaining -= $bytes_read;
6449 }
6450 }
6451  
6452 # Send final chunk if chunked encoding
6453 7 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) 4 3 7
6454 4 $stream->write("0\r\n\r\n");
6455 }
6456 154 }
6457  
6458 154 1;
6459  
6460 __END__
« blib/lib/PAGI/Server/AsyncFile.pm ↑ Summary blib/lib/PAGI/Server/Runner.pm »