blib/lib/PAGI/Server/Connection.pm

filter: Statementstmt 91.7% 2512 / 2738 Branchbran 69.6% 1142 / 1640 Conditioncond 64.7% 576 / 890 MC/DCmcdc 37.1% 180 / 485 Subroutinesub 97.0% 200 / 206 Podpod 0.0% 0 / 2 totaltotal 77.3% 4610 / 5961 CC 1207 SCAR 35.6
CC
1207
Cov
80%
_process_websocket_frames
157.8
_read_chunked_body
119.7
__ANON__
118.9
CRAP 35.3
« blib/lib/PAGI/Server/AsyncFile.pm ↑ Summary blib/lib/PAGI/Server/Protocol/HTTP1.pm »
1 package PAGI::Server::Connection;
2 156 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 156 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 156 our $VERSION = '0.002013';
6  
7 156 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 156 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 156 ▶use Scalar::Util qw(weaken refaddr);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 156 ▶use Protocol::WebSocket::Handshake::Server;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 156 ▶use Protocol::WebSocket::Frame;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 156 ▶use Digest::SHA qw(sha1_base64);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 156 ▶use Encode;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 156 ▶use URI::Escape qw(uri_unescape);
Subroutine BEGIN: called CC=1 SCAR=0.0
15 156 ▶use IO::Async::Timer::Countdown;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 156 ▶use IO::Async::Timer::Periodic;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 156 ▶use Time::HiRes qw(gettimeofday tv_interval);
Subroutine BEGIN: called CC=1 SCAR=0.0
18 156 ▶use PAGI::Server::AsyncFile;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 156 ▶use PAGI::Server::ConnectionState;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 156 ▶use PAGI::Server::TransportState;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 156 ▶use PAGI::Server::EventValidator;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23  
24 156 ▶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 156 my $_cached_log_timestamp;
28 156 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 156 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 198 ▶sub _h2_strip_connection_headers {
Subroutine _h2_strip_connection_headers: called CC=7 SCAR=19.5
64 198 my $self = shift;
65 198 my ($headers, $in_trailers) = @_;
66 198 ▶ my $context = $in_trailers ? 'trailers' : 'response';
Branch: 1 branch
BranchTrueFalseTotal
$in_trailers ? : 10 188 198
67 198 my @kept;
68 198 for my $h (@$headers) {
69 152 my ($name, $value) = @$h;
70 152 my $lc_name = lc $name;
71 152 ▶ if ($H2_CONNECTION_SPECIFIC_HEADER{$lc_name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($H2_CONNECTION_SPECIFIC_HEADER{$lc_name}) 25 127 152
72 # RFC 9113 permits a response 'te' only with the exact token
73 # 'trailers'; a case-insensitive VALUE compare (not a name/list
74 # match) is what the token grammar calls for. OWS
75 # (leading/trailing whitespace) around the token is trimmed
76 # before the compare, per RFC 9110's field-value grammar -- a
77 # compound value like 'trailers, gzip' is not the bare token and
78 # is still stripped. This carve-out does not apply in a trailer
79 # block (see $in_trailers above).
80 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
81 4 (my $v = lc $value) =~ s/^\s+|\s+\z//g;
82 4 ▶ if ($v eq 'trailers') {
Branch: 1 branch
BranchTrueFalseTotal
if ($v eq "trailers") 2 2 4
83 # Submit the normalized token, never the original value:
84 # RFC 9113 8.2.1 forbids OWS in field values, and
85 # libnghttp2 versions disagree on how to punish one
86 # (omit the field vs corrupt the whole response).
87 2 push @kept, [$name, 'trailers'];
88 2 next;
89 }
90 }
91 23 $self->_log(warn => "PAGI: connection-specific header '$name' stripped from HTTP/2 $context (RFC 9113)");
92 23 next;
93 }
94 127 push @kept, $h;
95 }
96 198 return \@kept;
97 }
98  
99 # =============================================================================
100 # HTTP/1.1 connection-specific header stripping (PAGI spec: "Over HTTP/1.1
101 # the server must ignore or strip application-supplied Transfer-Encoding and
102 # Connection -- it supplies its own -- and SHOULD log when it does")
103 # =============================================================================
104 # Deliberately narrower than the HTTP/2 six-name strip above: HTTP/1.1 has
105 # no prohibition on keep-alive, proxy-connection, upgrade, or te as ordinary
106 # application response headers, so only the two names the server itself
107 # always owns the framing/connection-state for -- transfer-encoding and
108 # connection -- are stripped here.
109 156 my %H1_CONNECTION_SPECIFIC_HEADER = map { $_ => 1 } qw(transfer-encoding connection);
110  
111 # Returns a new arrayref with app-supplied transfer-encoding/connection pairs
112 # removed, warning once per stripped occurrence (not deduplicated by name --
113 # two 'connection' headers warn twice). Does not mutate $headers.
114 283 ▶sub _h1_strip_connection_headers {
Subroutine _h1_strip_connection_headers: called CC=3 SCAR=11.0
115 283 my $self = shift;
116 283 my ($headers) = @_;
117 283 my @kept;
118 283 for my $h (@$headers) {
119 287 my ($name, $value) = @$h;
120 287 ▶ if ($H1_CONNECTION_SPECIFIC_HEADER{lc $name}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($H1_CONNECTION_SPECIFIC_HEADER{lc $name}) 14 273 287
121 14 $self->_log(warn => "PAGI: connection-specific header '$name' stripped from HTTP/1.1 response");
122 14 next;
123 }
124 273 push @kept, $h;
125 }
126 283 return \@kept;
127 }
128  
129 # SSE client-signal check (PAGI Www.pod "SSE Connection Detection"): the
130 # exact media range text/event-stream, case-insensitively, with q > 0.
131 # A boolean signal test, not content negotiation: wildcards never signal
132 # SSE, and q=0 is an explicit refusal.
133 450 ▶sub _accept_signals_sse {
Subroutine _accept_signals_sse: called CC=9 SCAR=22.0
134 450 my ($headers) = @_;
135 450 my @values;
136 450 for my $h (@$headers) {
137 974 ▶ push @values, $h->[1] if $h->[0] eq 'accept';
Branch: 1 branch
BranchTrueFalseTotal
if $h->[0] eq "accept" 110 864 974
138 }
139 450 ▶ return 0 unless @values;
Branch: 1 branch
BranchTrueFalseTotal
unless @values 341 109 450
140 109 for my $range (split /,/, join(',', @values)) {
141 113 my ($type, @params) = split /;/, $range;
142 113 $type =~ s/\A\s+|\s+\z//g;
143 113 ▶ next unless lc($type) eq 'text/event-stream';
Branch: 1 branch
BranchTrueFalseTotal
unless lc $type eq "text/event-stream" 11 102 113
144 102 my $q = 1;
145 102 for my $p (@params) {
146 4 $p =~ s/\A\s+|\s+\z//g;
147 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
148 }
149 102 ▶ return 1 if $q > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $q > 0 100 2 102
150 }
151 9 return 0;
152 }
153  
154 # RFC 6455 Section 11.3.4: Subprotocol must be a token (no whitespace, separators)
155 1 ▶sub _validate_subprotocol {
Subroutine _validate_subprotocol: called CC=3 SCAR=16.0
156 1 my ($value) = @_;
157  
158 1 ▶ if ($value =~ /[\r\n\0\s]/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($value =~ /[\r\n\0\s]/) 1 0 1
159 1 die "Invalid subprotocol: contains CR, LF, null, or whitespace\n";
160 }
161 # Token characters only (roughly)
162 0 ▶ if ($value !~ /^[\w\-\.]+$/) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($value =~ /^[\w\-\.]+$/) 0 0 0
163 0 die "Invalid subprotocol: must be alphanumeric, dash, underscore, or dot\n";
164 }
165 0 return $value;
166 }
167  
168 =head1 NAME
169  
170 PAGI::Server::Connection - Per-connection state machine
171  
172 =head1 SYNOPSIS
173  
174 # Internal use by PAGI::Server
175 my $conn = PAGI::Server::Connection->new(
176 stream => $stream,
177 app => $app,
178 protocol => $protocol,
179 server => $server,
180 extensions => {},
181 );
182 $conn->start;
183  
184 =head1 DESCRIPTION
185  
186 PAGI::Server::Connection manages the state machine for a single client
187 connection. It handles:
188  
189 =over 4
190  
191 =item * Request parsing via Protocol::HTTP1
192  
193 =item * Scope creation for the application
194  
195 =item * Event queue management for $receive and $send
196  
197 =item * Protocol upgrades (WebSocket, SSE)
198  
199 =item * SSE over HTTP/1.1 and HTTP/2
200  
201 =item * Connection lifecycle and cleanup
202  
203 =back
204  
205 =cut
206  
207 520 ▶sub new {
Subroutine new: called CC=17 SCAR=28.3
Pod undocumented
208 520 my ($class, %args) = @_;
209  
210 my $self = bless {
211 stream => $args{stream},
212 app => $args{app},
213 protocol => $args{protocol},
214 server => $args{server},
215 extensions => $args{extensions} // {},
216 state => $args{state} // {},
217 tls_enabled => $args{tls_enabled} // 0,
218 timeout => $args{timeout} // 60, # Idle timeout in seconds
219 request_timeout => $args{request_timeout} // 0, # Request stall timeout in seconds (0 = disabled, default for performance)
220 ws_idle_timeout => $args{ws_idle_timeout} // 0, # WebSocket idle timeout (0 = disabled)
221 sse_idle_timeout => $args{sse_idle_timeout} // 0, # SSE idle timeout (0 = disabled)
222 max_body_size => $args{max_body_size}, # 0 = unlimited
223 access_log => $args{access_log}, # Filehandle for access logging
224 _access_log_formatter => $args{_access_log_formatter}, # Pre-compiled format closure
225 max_receive_queue => $args{max_receive_queue} // 1000, # Max WebSocket receive queue size
226 max_ws_frame_size => $args{max_ws_frame_size} // 65536, # Max WebSocket frame size in bytes
227 sync_file_threshold => $args{sync_file_threshold} // 65536, # Threshold for sync file reads (default 64KB)
228 validate_events => $args{validate_events} // 0, # Deprecated: core event validation is mandatory; this flag is retained for compatibility and controls nothing.
229 # Send-side backpressure (watermarks in bytes)
230 # Defaults match Python asyncio: 64KB high, 16KB low (high/4)
231 write_high_watermark => $args{write_high_watermark} // 65536, # 64KB - pause sending above this
232 write_low_watermark => $args{write_low_watermark} // 16384, # 16KB - resume sending below this
233 _drain_waiters => [], # Pending Futures for blocking backpressure (a producer awaiting buffer drain)
234 _drain_fires => [], # arm_drain callback fires (on_drain hysteresis) -- kept separate from
235 # _drain_waiters so teardown can resume the former without invoking the
236 # latter (mirrors h2's stream_drain_waiters vs transport_drain_fires split)
237 _drain_check_active => 0, # Flag to prevent redundant on_outgoing_empty setup
238 tls_info => undef, # Populated on first request if TLS
239 buffer => '',
240 closed => 0,
241 response_started => 0,
242 h1_seq => 'initial', # Mirrors the h1 send closure's $seq (see _create_send)
243 response_status => undef, # Track response status for logging
244 _response_size => 0, # Track response body bytes for logging
245 request_start => undef, # Track request start time for logging
246 idle_timer => undef, # IO::Async::Timer for idle timeout
247 _served_a_request => 0, # True once a request has completed on this connection (idle_timer reason: idle_timeout -> keepalive_timeout)
248 stall_timer => undef, # IO::Async::Timer for request stall timeout
249 ws_idle_timer => undef, # IO::Async::Timer for WebSocket idle timeout
250 sse_idle_timer => undef, # IO::Async::Timer for SSE idle timeout
251 # Event queue for $receive
252 receive_queue => [],
253 receive_pending => undef,
254 # Track all pending receive Futures to cancel on close
255 receive_futures => [],
256 # Track request handling Future to prevent "lost future" warning
257 request_future => undef,
258 # Idempotency guard for disconnect handling
259 _disconnect_handled => 0,
260 # WebSocket state
261 websocket_mode => 0,
262 websocket_frame => undef, # Protocol::WebSocket::Frame for parsing
263 websocket_accepted => 0,
264 # SSE state
265 sse_mode => 0,
266 sse_started => 0,
267 sse_disconnect_reason => undef, # Reason for SSE disconnect (client_closed, write_error, etc.)
268 ws_disconnect_reason => undef, # Standard reason token for the app-facing websocket.disconnect event
269 ws_disconnect_code => undef, # Wire close code for that event (defaults to 1006, abnormal closure)
270 # Keepalive state (protocol-level ping/pong for WebSocket, comments for SSE)
271 ws_keepalive_timer => undef, # Periodic timer for sending WebSocket pings
272 ws_pong_timeout => undef, # Timeout timer for pong response
273 ws_waiting_pong => 0, # Flag: are we waiting for a pong?
274 ws_keepalive_interval => 0, # Current keepalive interval (0 = disabled)
275 ws_keepalive_timeout => 0, # Current pong timeout (0 = no timeout check)
276 sse_keepalive_timer => undef, # Periodic timer for sending SSE keepalive comments
277 sse_keepalive_comment => '', # Comment text to send
278 # HTTP/2 state
279 alpn_protocol => $args{alpn_protocol}, # ALPN-negotiated protocol (e.g. 'h2', 'http/1.1')
280 h2_protocol => $args{h2_protocol}, # PAGI::Server::Protocol::HTTP2 instance
281 h2c_enabled => $args{h2c_enabled} // 0, # Allow h2c preface detection on cleartext
282 is_h2 => 0, # Set during start() if HTTP/2 detected
283 h2_session => undef, # PAGI::Server::Protocol::HTTP2::Session
284 h2_streams => {}, # Per-stream state for HTTP/2
285 # Transport info (tcp or unix)
286 transport_type => $args{transport_type} // 'tcp',
287 transport_path => $args{transport_path}, # socket path for unix
288 # Cached connection info (populated in start(), used by _create_scope)
289 520 ▶ client_host => '127.0.0.1',
Condition100%30/30
$args{"extensions"} // {}
l!l
312208
$args{"state"} // {}
l!l
301219
$args{"tls_enabled"} // 0
l!l
301219
$args{"timeout"} // 60
l!l
304216
$args{"request_timeout"} // 0
l!l
301219
$args{"ws_idle_timeout"} // 0
l!l
301219
$args{"sse_idle_timeout"} // 0
l!l
310210
$args{"max_receive_queue"} // 1000
l!l
304216
$args{"max_ws_frame_size"} // 65536
l!l
303217
$args{"sync_file_threshold"} // 65536
l!l
301219
$args{"validate_events"} // 0
l!l
301219
$args{"write_high_watermark"} // 65536
l!l
321199
$args{"write_low_watermark"} // 16384
l!l
318202
$args{"h2c_enabled"} // 0
l!l
144376
$args{"transport_type"} // "tcp"
l!l
304216
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
290 client_port => 0,
291 server_host => '127.0.0.1',
292 server_port => 5000,
293 }, $class;
294  
295 # Extract TLS info if this is a TLS connection
296 520 ▶ if ($self->{tls_enabled}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"tls_enabled"}) 45 475 520
297 45 $self->_extract_tls_info;
298 }
299  
300 520 return $self;
301 }
302  
303 156 ▶use Socket qw(IPPROTO_TCP TCP_NODELAY);
Subroutine BEGIN: called CC=1 SCAR=0.0
304  
305 511 ▶sub start {
Subroutine start: called CC=15 SCAR=27.4
Pod undocumented
306 511 my ($self) = @_;
307  
308 511 my $stream = $self->{stream};
309 511 weaken(my $weak_self = $self);
310  
311 # Enable TCP_NODELAY to reduce latency for small responses (TCP only)
312 511 ▶ my $handle = $stream->write_handle // $stream->read_handle;
Condition33%1/3
$stream->write_handle // $stream->read_handle
l!l&&r!l&&!r
51100
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
313 511 ▶ 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")) 299 212 511
Condition83%5/6
$self->{"transport_type"} eq "tcp" and $handle and $handle->can("setsockopt")
!ll&&!rl&&r
5207299
$self->{"transport_type"} eq "tcp" and $handle
!ll&&!rl&&r
50506
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
314 299 eval {
315 299 $handle->setsockopt(IPPROTO_TCP, TCP_NODELAY, 1);
316 };
317 # Ignore errors - not all sockets support this
318 }
319  
320 # Cache connection info once (avoids per-request socket method calls)
321 511 ▶ if ($self->{transport_type} eq 'unix') {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'transport_type'} eq 'unix') { } 5 506 511
elsif ($handle and $handle->can('peerhost')) { } 298 208 506
322 # Unix socket: no peer IP/port, server is identified by path
323 5 $self->{client_host} = undef;
324 5 $self->{client_port} = undef;
325 5 $self->{server_host} = $self->{transport_path};
326 5 $self->{server_port} = undef;
327 ▶ } elsif ($handle && $handle->can('peerhost')) {
Condition66%2/3
$handle and $handle->can("peerhost")
!ll&&!rl&&r
0208298
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
328 298 eval {
329 298 ▶ $self->{client_host} = $handle->peerhost // '127.0.0.1';
Condition100%2/2
$handle->peerhost // "127.0.0.1"
l!l
2971
MC/DC100%1/1
$handle->peerhost // "127.0.0.1"
$handle->peerhost
Truth table100%2/2
A
A= $handle->peerhost
Aresult
11
00
330 298 ▶ $self->{client_port} = $handle->peerport // 0;
Condition100%2/2
$handle->peerport // 0
l!l
2971
MC/DC100%1/1
$handle->peerport // 0
$handle->peerport
Truth table100%2/2
A
A= $handle->peerport
Aresult
11
00
331 298 ▶ $self->{server_host} = $handle->sockhost // '127.0.0.1';
Condition50%1/2
$handle->sockhost // "127.0.0.1"
l!l
2980
MC/DC0%0/1
$handle->sockhost // "127.0.0.1"
$handle->sockhost
Truth table50%1/2
A
A= $handle->sockhost
Aresult
11
00
332 298 ▶ $self->{server_port} = $handle->sockport // 5000;
Condition50%1/2
$handle->sockport // 5000
l!l
2980
MC/DC0%0/1
$handle->sockport // 5000
$handle->sockport
Truth table50%1/2
A
A= $handle->sockport
Aresult
11
00
333 };
334 # Ignore errors - keep defaults if extraction fails
335 }
336  
337 # Detect HTTP/2 via ALPN negotiation
338 511 ▶ 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 449 511
Condition83%5/6
$self->{"alpn_protocol"} and $self->{"alpn_protocol"} eq "h2" and $self->{"h2_protocol"}
!ll&&!rl&&r
449062
$self->{"alpn_protocol"} and $self->{"alpn_protocol"} eq "h2"
!ll&&!rl&&r
448162
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
339 62 $self->_init_h2_session;
340 }
341  
342 # Set up idle timeout timer
343 511 $self->_start_idle_timer;
344  
345 # Set up read handler
346 $stream->configure(
347 1166 ▶ on_read => sub {
Subroutine __ANON__: called CC=15 SCAR=27.3
348 1166 my ($s, $buffref, $eof) = @_;
349 1166 ▶ return 0 unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1166 1166
350  
351 # Reset idle timer on any read activity
352 1166 $weak_self->_reset_idle_timer;
353  
354 # Reset stall timer on read activity (if handling a request)
355 1166 ▶ $weak_self->_reset_stall_timer if $weak_self->{handling_request};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"handling_request"} 79 1087 1166
356  
357 1166 $weak_self->{buffer} .= $$buffref;
358 1166 $$buffref = '';
359  
360 1166 ▶ if ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 38 1128 1166
361 # EOF means client closed - handle disconnect and cleanup
362 38 $weak_self->_handle_disconnect_and_close('client_closed');
363 38 return 0;
364 }
365  
366 # h2c detection: check if cleartext connection starts with HTTP/2 preface
367 1128 ▶ 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 985 1128
Condition66%2/3
$weak_self->{"h2c_enabled"} and not $weak_self->{"is_h2"}
!ll&&!rl&&r
9850143
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
368 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
369 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
370 142 $weak_self->_init_h2_session;
371 142 $weak_self->{h2c_enabled} = 0; # Detection done
372 } else {
373 1 $weak_self->{h2c_enabled} = 0; # Not h2c, stop checking
374 }
375 } else {
376 # Not enough data yet to determine protocol, wait for more
377 0 return 0;
378 }
379 }
380  
381 # Wrap processing in eval to prevent exceptions from crashing the event loop
382 # This is critical - Protocol::WebSocket::Frame can throw exceptions for
383 # oversized payloads, and other parsing code may throw as well
384 1128 eval {
385 # HTTP/2: feed data to session for frame processing
386 1128 ▶ if ($weak_self->{is_h2}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"is_h2"}) 739 389 1128
387 739 $weak_self->_h2_process_data;
388 738 return;
389 }
390  
391 # If in WebSocket mode, process WebSocket frames
392 389 ▶ if ($weak_self->{websocket_mode}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"websocket_mode"}) 42 347 389
393 42 $weak_self->_process_websocket_frames;
394 41 return;
395 }
396  
397 # If we're waiting for body data, notify the receive handler
398 347 ▶ 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 332 347
Condition66%2/3
$weak_self->{"receive_pending"} and not $weak_self->{"receive_pending"}->is_ready
!ll&&!rl&&r
332015
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
399 15 my $f = $weak_self->{receive_pending};
400 15 $weak_self->{receive_pending} = undef;
401 15 $f->done;
402 }
403  
404 347 $weak_self->_try_handle_request;
405 };
406 1128 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 2 1126 1128
407 # Log the error and close the connection gracefully
408 2 $self->_log(error => "PAGI connection error: $error");
409 2 ▶ return 0 unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
410 2 $weak_self->_handle_disconnect_and_close('server_error');
411 }
412 1128 return 0;
413 },
414 504 ▶ on_closed => sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
415 504 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 504 504
416 # Stream closed - handle disconnect and remove from connections hash
417 504 $weak_self->_handle_disconnect_and_close('client_closed');
418 },
419 # Without these, IO::Async::Stream's own contract applies: "If an
420 # error occurs when the corresponding error callback is not
421 # supplied, ... the close method is called instead" -- i.e. it would
422 # call close_now itself and (via on_closed above) report every
423 # socket error as client_closed, indistinguishable from an ordinary
424 # peer disconnect. Registering a handler here -- regardless of what
425 # it returns -- is sufficient by itself to suppress that close_now
426 # (maybe_invoke_event always returns a truthy value once any handler
427 # exists), so there is no double-teardown risk from IO::Async's
428 # side; _handle_disconnect_and_close's own _disconnect_handled guard
429 # covers the (harmless, pre-existing) case where on_closed also
430 # fires afterward once the socket actually finishes closing.
431 6 ▶ on_read_error => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
432 6 my ($s, $errno) = @_;
433 6 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 6 6
434 6 $weak_self->_handle_disconnect_and_close('read_error');
435 },
436 5 ▶ on_write_error => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
437 5 my ($s, $errno) = @_;
438 5 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 5 5
439 5 $weak_self->_handle_disconnect_and_close('write_error');
440 },
441 511 );
442 }
443  
444 # Arm the idle timeout. Called once at connection setup (before any request
445 # has completed on this connection) and again whenever a long-lived mode
446 # that removed the timer (SSE) hands the connection back to ordinary
447 # keep-alive request handling, or a plain request completes and the
448 # connection stays open awaiting the next one. The same timer instance
449 # serves both cases (it is only reset, never re-created, by ordinary reads);
450 # on_expire decides its reason token at fire time from _served_a_request,
451 # per the spec's split between idle_timeout (nothing has arrived yet) and
452 # keepalive_timeout (a request already completed on this connection).
453 536 ▶sub _start_idle_timer {
Subroutine _start_idle_timer: called CC=5 SCAR=16.4
454 536 my ($self) = @_;
455  
456 536 ▶ return if $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"} 0 536 536
457 536 ▶ return unless $self->{timeout} && $self->{timeout} > 0 && $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"timeout"} and $self->{"timeout"} > 0 and $self->{"server"} 3 533 536
Condition66%4/6
$self->{"timeout"} and $self->{"timeout"} > 0 and $self->{"server"}
!ll&&!rl&&r
30533
$self->{"timeout"} and $self->{"timeout"} > 0
!ll&&!rl&&r
30533
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
458  
459 533 weaken(my $weak_self = $self);
460  
461 my $timer = IO::Async::Timer::Countdown->new(
462 delay => $self->{timeout},
463 2 ▶ on_expire => sub {
Subroutine __ANON__: called CC=4 SCAR=14.2
464 2 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
465 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
466 # Close idle connection
467 2 ▶ my $reason = $weak_self->{_served_a_request} ? 'keepalive_timeout' : 'idle_timeout';
Branch: 1 branch
BranchTrueFalseTotal
$weak_self->{'_served_a_request'} ? : 1 1 2
468 2 $weak_self->_handle_disconnect_and_close($reason);
469 },
470 533 );
471 533 $self->{idle_timer} = $timer;
472 533 $self->{server}->add_child($timer);
473 533 $timer->start;
474 }
475  
476 1166 ▶sub _reset_idle_timer {
Subroutine _reset_idle_timer: called CC=5 SCAR=16.1
477 1166 my ($self) = @_;
478  
479 1166 ▶ return unless $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_timer"} 62 1104 1166
480  
481 # Debounce: rescheduling the IO::Async countdown on every read is costly
482 # under keep-alive load -- it re-enqueues a loop timer each time. Reset at
483 # most ~20x/second; this coarsens the idle timeout by at most ~50ms, which is
484 # immaterial for a multi-second idle timeout but cuts the per-request timer
485 # churn dramatically under load.
486 1104 my $now = Time::HiRes::time();
487 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" 386 718 1104
Condition100%3/3
defined $self->{"_idle_reset_at"} and $now - $self->{"_idle_reset_at"} < "0.05"
!ll&&!rl&&r
501217386
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
488 718 $self->{_idle_reset_at} = $now;
489  
490 718 $self->{idle_timer}->reset;
491 718 ▶ $self->{idle_timer}->start unless $self->{idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_timer"}->is_running 0 718 718
492 }
493  
494 601 ▶sub _stop_idle_timer {
Subroutine _stop_idle_timer: called CC=4 SCAR=13.9
495 601 my ($self) = @_;
496  
497 601 ▶ return unless $self->{idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"idle_timer"} 70 531 601
498 531 ▶ $self->{idle_timer}->stop if $self->{idle_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"idle_timer"}->is_running 529 2 531
499 # Remove timer completely so _reset_idle_timer won't restart it
500 # This is important for long-lived connections (WebSocket, SSE)
501 531 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 531 0 531
502 531 $self->{server}->remove_child($self->{idle_timer});
503 }
504 531 $self->{idle_timer} = undef;
505 }
506  
507 # =============================================================================
508 # HTTP/2 Session Initialization
509 # =============================================================================
510  
511 204 ▶sub _init_h2_session {
Subroutine _init_h2_session: called CC=1 SCAR=0.0
512 204 my ($self) = @_;
513  
514 204 $self->{is_h2} = 1;
515  
516 204 weaken(my $weak_self = $self);
517  
518 $self->{h2_session} = $self->{h2_protocol}->create_session(
519 209 ▶ on_request => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
520 209 my ($stream_id, $pseudo, $headers, $has_body) = @_;
521 209 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 209 209
522 209 $weak_self->_h2_on_request($stream_id, $pseudo, $headers, $has_body);
523 },
524 85 ▶ on_body => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
525 85 my ($stream_id, $data, $eof) = @_;
526 85 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 85 85
527 85 $weak_self->_h2_on_body($stream_id, $data, $eof);
528 },
529 140 ▶ on_close => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
530 140 my ($stream_id, $error_code) = @_;
531 140 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 140 140
532 140 $weak_self->_h2_on_close($stream_id, $error_code);
533 },
534 2 ▶ on_header_overflow => sub {
Subroutine __ANON__: called CC=2 SCAR=7.1
535 2 my ($stream_id) = @_;
536 2 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
537 2 $weak_self->_h2_on_header_overflow($stream_id);
538 },
539 204 );
540  
541 # Send initial SETTINGS to client
542 204 $self->_h2_write_pending;
543 }
544  
545 740 ▶sub _h2_process_data {
Subroutine _h2_process_data: called CC=5 SCAR=16.2
546 740 my ($self) = @_;
547 740 ▶ return unless $self->{h2_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"h2_session"} 0 740 740
548  
549 740 ▶ if (length($self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} > 0) 739 1 740
550 739 $self->{h2_session}->feed($self->{buffer});
551 738 $self->{buffer} = '';
552 }
553  
554 739 $self->_h2_write_pending;
555  
556 # Close connection when session is done (GOAWAY received or sent)
557 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
558 2 $self->_h2_write_pending; # Flush any remaining output
559 2 $self->_handle_disconnect_and_close;
560 }
561 }
562  
563 1427 ▶sub _h2_write_pending {
Subroutine _h2_write_pending: called CC=4 SCAR=14.0
564 1427 my ($self) = @_;
565 1427 ▶ return unless $self->{h2_session};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"h2_session"} 0 1427 1427
566 1427 while (1) {
567 2305 my $data = $self->{h2_session}->extract;
568 2293 ▶ last unless defined $data && length($data) > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $data and length $data > 0 1415 878 2293
Condition66%2/3
defined $data and length $data > 0
!ll&&!rl&&r
01415878
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
569 878 $self->{stream}->write($data);
570 }
571 }
572  
573 # =============================================================================
574 # HTTP/2 Stream Callbacks
575 # =============================================================================
576  
577 # RFC 9113 section 10.5.1: "a server that receives a larger header block
578 # than it is willing to handle can send an HTTP 431". Fired by the protocol
579 # layer (PAGI::Server::Protocol::HTTP2) instead of on_request when a
580 # request's HEADERS block exceeds max_header_list_size -- no request state
581 # was ever dispatched (HTTP2.pm never called on_request for this stream),
582 # so there is nothing in {h2_streams} to initialize or clean up here.
583 # Mirrors the plain-CONNECT-501 and content-length-413 idiom below: defer
584 # the response to avoid re-entrant nghttp2 calls (we're inside feed/mem_recv).
585 2 ▶sub _h2_on_header_overflow {
Subroutine _h2_on_header_overflow: called CC=1 SCAR=0.1
586 2 my ($self, $stream_id) = @_;
587  
588 2 weaken(my $ws = $self);
589 2 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
590 2 ▶ return unless $ws;
Branch: 1 branch
BranchTrueFalseTotal
unless $ws 0 2 2
591 2 ▶ return if $ws->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"closed"} 0 2 2
592 $ws->{h2_session}->submit_response($stream_id,
593 status => 431,
594 headers => [
595 ['content-type', 'text/plain'],
596 2 ['date', $ws->{protocol}->format_date],
597 ],
598 body => "Request Header Fields Too Large\n",
599 );
600 2 $ws->_h2_write_pending;
601 2 });
602 }
603  
604 210 ▶sub _h2_on_request {
Subroutine _h2_on_request: called CC=12 SCAR=25.5
605 210 my ($self, $stream_id, $pseudo, $headers, $has_body) = @_;
606  
607 # Defensive second layer (belt under the protocol layer's own
608 # suspenders, PAGI::Server::Protocol::HTTP2's HEADERS-block
609 # classification): a live in-flight stream must never be overwritten
610 # by a duplicate dispatch. This should be unreachable now that the
611 # protocol layer classifies received HEADERS blocks by category and
612 # only calls on_request for NGHTTP2_HCAT_REQUEST -- it exists so a
613 # future protocol-layer regression can't silently destroy an
614 # in-flight request's accumulated state (body, receive_queue,
615 # connection_state, seq_state).
616 210 ▶ if ($self->{h2_streams}{$stream_id}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_streams"}{$stream_id}) 0 210 210
617 0 $self->_log(warn => "PAGI::Server::Connection: ignoring duplicate HTTP/2 request dispatch for stream $stream_id (existing in-flight request would have been destroyed)");
618 0 return;
619 }
620  
621 # Detect CONNECT method
622 210 my $is_websocket = 0;
623 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
624 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
625 # Extended CONNECT for WebSocket (RFC 8441)
626 51 $is_websocket = 1;
627 } else {
628 # Plain CONNECT not supported — defer response to avoid
629 # re-entrant nghttp2 calls (we're inside feed/mem_recv)
630 1 weaken(my $ws = $self);
631 1 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
632 1 ▶ return unless $ws;
Branch: 1 branch
BranchTrueFalseTotal
unless $ws 0 1 1
633 1 ▶ return if $ws->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"closed"} 0 1 1
634 $ws->{h2_session}->submit_response($stream_id,
635 status => 501,
636 headers => [
637 ['content-type', 'text/plain'],
638 1 ['date', $ws->{protocol}->format_date],
639 ],
640 body => "CONNECT method not supported\n",
641 );
642 1 $ws->_h2_write_pending;
643 1 });
644 1 return;
645 }
646 }
647  
648 # Detect SSE (Accept: text/event-stream)
649 209 my $is_sse = 0;
650 209 ▶ if (!$is_websocket) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($is_websocket) 158 51 209
651 158 $is_sse = _accept_signals_sse($headers);
652 }
653  
654 # Initialize per-stream state
655 209 $self->{h2_streams}{$stream_id} = {
656 pseudo => $pseudo,
657 headers => $headers,
658 has_body => $has_body,
659 body => '',
660 body_complete => !$has_body,
661 body_pending => undef, # Future for body availability
662 receive_queue => [],
663 response_started => 0,
664 seq_state => 'initial',
665 is_websocket => $is_websocket,
666 is_sse => $is_sse,
667 ws_accepted => 0,
668 ws_frame => undef, # Protocol::WebSocket::Frame for parsing
669 ws_connect_sent => 0,
670 ws_disconnect_delivered => 0, # True once the scope's single websocket.disconnect has been queued
671 };
672  
673 # Check Content-Length against max_body_size limit before dispatching
674 # (after stream init so _h2_on_body/_h2_on_close can find the stream)
675 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
676 37 for my $h (@$headers) {
677 73 ▶ if ($h->[0] eq 'content-length') {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->[0] eq "content-length") 2 71 73
678 2 ▶ if ($h->[1] > $self->{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($h->[1] > $self->{"max_body_size"}) 2 0 2
679 # Defer response to avoid re-entrant nghttp2 calls
680 2 weaken(my $ws = $self);
681 2 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
682 2 ▶ return unless $ws;
Branch: 1 branch
BranchTrueFalseTotal
unless $ws 0 2 2
683 2 ▶ return if $ws->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ws->{"closed"} 0 2 2
684 $ws->{h2_session}->submit_response($stream_id,
685 status => 413,
686 headers => [
687 ['content-type', 'text/plain'],
688 2 ['date', $ws->{protocol}->format_date],
689 ],
690 body => "Payload Too Large\n",
691 );
692 2 $ws->_h2_write_pending;
693 2 });
694 2 return;
695 }
696 0 last;
697 }
698 }
699 }
700  
701 # Defer dispatch to next event loop tick to prevent re-entrant nghttp2 calls
702 207 weaken(my $weak_self = $self);
703 207 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
704 207 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 207 207
705 207 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 207 207
706 207 $weak_self->_h2_dispatch_stream($stream_id);
707 207 });
708 }
709  
710 85 ▶sub _h2_on_body {
Subroutine _h2_on_body: called CC=15 SCAR=27.1
711 85 my ($self, $stream_id, $data, $eof) = @_;
712  
713 85 my $stream = $self->{h2_streams}{$stream_id};
714 85 ▶ return unless $stream;
Branch: 1 branch
BranchTrueFalseTotal
unless $stream 4 81 85
715  
716 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
717 # WebSocket: DATA frames contain raw WebSocket frames
718 58 ▶ $self->_h2_process_ws_frames($stream_id, $stream, $data) if length($data);
Branch: 1 branch
BranchTrueFalseTotal
if length $data 55 3 58
719  
720 58 ▶ if ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 3 55 58
721 # END_STREAM with no close handshake (bare END_STREAM): abnormal
722 # closure per RFC 6455 (Www.pod "Disconnect - receive event").
723 3 $self->_h2_ws_enqueue_disconnect($stream, 1006, 'client_closed');
724 }
725 58 return;
726 }
727  
728 23 ▶ if (length($data) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data > 0) 17 6 23
729 17 $stream->{body} .= $data;
730  
731 # Enforce max_body_size (0 = unlimited)
732 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
733 $self->{h2_session}->submit_response($stream_id,
734 status => 413,
735 headers => [
736 ['content-type', 'text/plain'],
737 7 ['date', $self->{protocol}->format_date],
738 ],
739 body => 'Payload Too Large',
740 );
741 # No _h2_write_pending here — we're inside feed(); _h2_process_data
742 # flushes after feed() returns
743 6 $self->_h2_resolve_stream_drain_waiters($stream);
744 6 $self->_h2_resolve_stream_trailer_wait($stream);
745 # Drop (don't fire) the app's on_drain fires: the stream is closing,
746 # not draining, and the transport handle is going away. Also break
747 # the $stream <-> transport_state cycle (the handle's measure/arm
748 # closures hold $stream strongly), or the stream state leaks for the
749 # life of the process once h2_streams drops its external ref.
750 6 $stream->{transport_drain_fires} = [];
751 6 delete $stream->{transport_state};
752 # This stream is going away here too -- stop its keepalive (and,
753 # for SSE, idle) timers before dropping the hash entry, the same
754 # as _h2_on_close does. Those timers are add_child'ed to the
755 # SERVER, not to this stream state, so without this the deleted
756 # entry below leaves them running for the life of the process:
757 # _h2_on_close never runs for this path (no h2-level stream close
758 # event fires here), and the connection's own close-time sweep
759 # only iterates h2_streams, which no longer lists this stream.
760 6 ▶ $self->_h2_stop_ws_keepalive($stream) if $stream->{is_websocket};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"is_websocket"} 1 5 6
761 6 ▶ if ($stream->{is_sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_sse"}) 1 5 6
762 1 $self->_h2_stop_sse_keepalive($stream);
763 1 $self->_h2_stop_sse_idle_timer($stream);
764 }
765  
766 # Unblock a pending receive() instead of leaving it hanging
767 # forever: mark the body complete, queue this scope's disconnect
768 # event, drive connection_state (http scopes only -- sse/ws
769 # scopes never attach one, per spec), then wake body_pending.
770 # Order matters: the queued event must land BEFORE the wake so a
771 # parked receive() sees it (both h2 receive closures check the
772 # queue first on resume), and all of this must happen BEFORE the
773 # delete below, after which the stream state is unreachable.
774 6 $stream->{body_complete} = 1;
775 6 ▶ if ($stream->{is_sse}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($stream->{'is_sse'}) { } 1 5 6
elsif ($stream->{'is_websocket'}) { } 1 4 5
776 1 push @{$stream->{receive_queue}}, {
777 type => 'sse.disconnect',
778 reason => 'body_too_large',
779 };
780 } elsif ($stream->{is_websocket}) {
781 # An accepted ws stream returns early at the top of this sub
782 # (the ws_accepted guard above), so is_websocket true here
783 # always means pre-accept. Deliver the scope's single
784 # websocket.disconnect (Www.pod "Disconnect - receive
785 # event": server-detected abnormal close is code 1006 plus
786 # the matching Standard Disconnect Reasons token, and
787 # body_too_large is one). Pushed directly rather than
788 # through _h2_ws_enqueue_disconnect: that helper also calls
789 # _h2_wake_pending, but the wake here must wait until
790 # h2_closed is set below (same ordering the sse/http arms
791 # rely on -- see the comment above h2_closed). Still honor
792 # the single-delivery contract so a later delivery attempt
793 # for this (about-to-be-deleted) stream is a no-op.
794 1 $stream->{ws_disconnect_delivered}++;
795 1 push @{$stream->{receive_queue}}, {
796 type => 'websocket.disconnect',
797 code => 1006,
798 reason => 'body_too_large',
799 };
800 } else {
801 4 push @{$stream->{receive_queue}}, { type => 'http.disconnect' };
802 }
803 $stream->{connection_state}->_mark_disconnected('body_too_large')
804 6 ▶ if $stream->{connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"connection_state"} 2 4 6
805 # Mark death BEFORE the wake, mirroring _h2_on_close's own
806 # h2_closed marker (see its comment): the wake below can resume
807 # the app's async sub synchronously, and a resumed app may call
808 # $send before this function reaches its own delete further
809 # down -- $ss would still be a live h2_streams entry at that
810 # point (STREAM_GONE / already-closed carve-outs key off entry
811 # existence). h2_closed lets every send closure recognize a
812 # doomed-but-still-present entry and no-op on it, same as an
813 # absent one, per the post-close contract (design §6.2 / §21
814 # item 1).
815 6 $stream->{h2_closed} = 1;
816 6 $self->_h2_wake_pending($stream);
817  
818 6 delete $self->{h2_streams}{$stream_id};
819 6 return;
820 }
821 }
822  
823 16 ▶ if ($eof) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof) 6 10 16
824 6 $stream->{body_complete} = 1;
825 }
826  
827 16 $self->_h2_wake_pending($stream);
828 }
829  
830 216 ▶sub _h2_wake_pending {
Subroutine _h2_wake_pending: called CC=3 SCAR=11.0
831 216 my ($self, $stream) = @_;
832 216 ▶ if ($stream->{body_pending} && !$stream->{body_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready) 70 146 216
Condition66%2/3
$stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready
!ll&&!rl&&r
146070
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
833 70 my $f = $stream->{body_pending};
834 70 $stream->{body_pending} = undef;
835 70 $f->done;
836 }
837 }
838  
839 # Enqueue the scope's single websocket.disconnect event (PAGI: exactly one
840 # per WebSocket scope). Every h2 delivery site MUST come through here.
841 31 ▶sub _h2_ws_enqueue_disconnect {
Subroutine _h2_ws_enqueue_disconnect: called CC=2 SCAR=6.9
842 31 my ($self, $stream, $code, $reason) = @_;
843 31 ▶ return if $stream->{ws_disconnect_delivered}++;
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"ws_disconnect_delivered"}++ 12 19 31
844 19 push @{$stream->{receive_queue}}, {
845 type => 'websocket.disconnect',
846 code => $code,
847 reason => $reason,
848 };
849 19 $self->_h2_wake_pending($stream);
850 }
851  
852 140 ▶sub _h2_on_close {
Subroutine _h2_on_close: called CC=14 SCAR=26.4
853 140 my ($self, $stream_id, $error_code) = @_;
854  
855 140 my $stream = $self->{h2_streams}{$stream_id};
856 140 ▶ return unless $stream;
Branch: 1 branch
BranchTrueFalseTotal
unless $stream 5 135 140
857  
858 # Record death at the earliest possible moment -- before any of the
859 # deferred work below (including this function's own loop->later
860 # delete of the h2_streams entry further down). nghttp2 has already
861 # forgotten this stream by the time this callback fires, but the
862 # entry stays in h2_streams for one more tick so pending futures can
863 # resolve. The dispatch wrapper's liveness check may run nested
864 # inside this very call (a woken receive() future can resume an
865 # app's async sub synchronously), so it needs a fact that flips true
866 # HERE, not one that only becomes true once the deferred delete runs.
867 135 $stream->{h2_closed} = 1;
868  
869 # This stream is going away one way or another -- stop its keepalive
870 # (and, for SSE, idle) timers so they don't fire (or leak) after the
871 # stream state is reclaimed.
872 135 ▶ $self->_h2_stop_ws_keepalive($stream) if $stream->{is_websocket};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"is_websocket"} 8 127 135
873 135 ▶ if ($stream->{is_sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_sse"}) 20 115 135
874 20 $self->_h2_stop_sse_keepalive($stream);
875 20 $self->_h2_stop_sse_idle_timer($stream);
876 }
877  
878 # Drive this stream's own connection_state to its terminal state exactly
879 # once. Three outcomes, and the h2 error code alone does not separate
880 # them -- a server-sent END_STREAM closes a stream with error code 0 just
881 # as a client's clean close does:
882 #
883 # 1. seq_state 'complete' and no error code -- the whole response went
884 # out and the stream ended cleanly: a completion, not a disconnect.
885 # 2. no error code but the response never reached 'complete' -- the
886 # stream ended early with no h2-level error, which on this side only
887 # the server can cause. (A declared-but-unsent-trailers response, or
888 # any other response left started-but-incomplete, does NOT land
889 # here today: the dispatch wrapper resets it with RST_STREAM
890 # INTERNAL_ERROR -- a NONZERO code -- so that case falls into
891 # outcome 3 below. This branch is kept for any other server-caused
892 # clean end that leaves seq_state short of 'complete'.) An early
893 # end to an unfinished response is an incomplete response per the
894 # PAGI spec, and the fault is the server's: the client did nothing
895 # and must not be blamed with 'client_closed'.
896 # 3. a nonzero error code -- the peer reset the stream (CANCEL,
897 # INTERNAL_ERROR, ...): the client went away.
898 #
899 # Both marks are idempotent, so a stream the dispatch wrapper already
900 # marked (e.g. server_error before its own RST) keeps that first reason.
901 #
902 # server_close_reason: a server-initiated per-stream teardown (idle
903 # timeout, keepalive timeout, ...) records its own token here BEFORE
904 # driving the close, so it takes precedence over the generic
905 # 'client_closed' fallback below in the queued disconnect events pushed
906 # further down -- that part is operative today, since WebSocket
907 # keepalive timeout and SSE idle timeout are exactly the writers of this
908 # token and both stream types push a queued disconnect. The
909 # nonzero-error-code $cs mark below also consults $reason, but that arm
910 # is a forward guard, not yet operative: WebSocket/SSE streams (this
911 # token's only current writers) never attach a connection_state, so no
912 # $cs-bearing stream sets server_close_reason today -- this exists for
913 # when a server-initiated per-stream teardown reaches a stream that does
914 # carry one. The zero-error-code arms above are untouched either way:
915 # they distinguish a clean completion from an incomplete response, not
916 # a server-initiated abnormal close, so they never consult this token.
917 135 my $reason = $stream->{server_close_reason};
918 135 ▶ if (my $cs = $stream->{connection_state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cs = $stream->{"connection_state"}) 107 28 135
919 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
920 87 $cs->_mark_complete;
921 } elsif (!$error_code) {
922 4 $cs->_mark_disconnected('server_error');
923 } else {
924 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
925 }
926 }
927  
928 # Mark body complete to unblock any pending receive
929 135 $stream->{body_complete} = 1;
930  
931 # Enqueue disconnect event
932 135 ▶ if ($stream->{is_websocket}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($stream->{'is_websocket'}) { } 8 127 135
elsif ($stream->{'is_sse'}) { } 20 107 127
933 # Close without a WebSocket close handshake (RST_STREAM, timeout, ...):
934 # abnormal closure per RFC 6455. Deduped -- a no-op if the close-frame
935 # or bare-END_STREAM path already delivered the scope's one disconnect.
936 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
937 } elsif ($stream->{is_sse}) {
938 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
939 type => 'sse.disconnect',
940 reason => $reason // 'client_closed',
941 };
942 } else {
943 107 push @{$stream->{receive_queue}}, { type => 'http.disconnect' };
944 }
945  
946 135 $self->_h2_wake_pending($stream);
947  
948 # Release any producer blocked on this stream's backpressure drain — the
949 # stream is closing, so it must not hang waiting for a queue that will
950 # never drain.
951 135 $self->_h2_resolve_stream_drain_waiters($stream);
952 # Same for a send() parked awaiting the data callback's own terminal
953 # invocation to submit its staged trailers (h2_closed carve-out: a
954 # trailers send racing a disconnect resolves as a successful no-op,
955 # same as every other post-close send).
956 135 $self->_h2_resolve_stream_trailer_wait($stream);
957 # Drop (don't fire) the app's on_drain fires: this is a close, not a drain.
958 # Also break the $stream <-> transport_state cycle so the stream state can be
959 # collected once the deferred delete below drops h2_streams' external ref.
960 135 $stream->{transport_drain_fires} = [];
961 135 delete $stream->{transport_state};
962  
963 # Clean up after a delay (let any pending futures resolve)
964 135 weaken(my $weak_self = $self);
965 135 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=7.2
966 135 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 135 135
967 135 delete $weak_self->{h2_streams}{$stream_id};
968 135 });
969 }
970  
971 # =============================================================================
972 # HTTP/2 Stream Dispatch (scope/receive/send creation)
973 # =============================================================================
974  
975 207 ▶sub _h2_dispatch_stream {
Subroutine _h2_dispatch_stream: called CC=4 SCAR=13.9
976 207 my ($self, $stream_id) = @_;
977  
978 207 my $stream_state = $self->{h2_streams}{$stream_id};
979 207 ▶ return unless $stream_state;
Branch: 1 branch
BranchTrueFalseTotal
unless $stream_state 2 205 207
980  
981 205 my ($scope, $receive, $send);
982  
983 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
984 51 $scope = $self->_h2_create_websocket_scope($stream_id, $stream_state);
985 51 $receive = $self->_h2_create_websocket_receive($stream_id, $stream_state);
986 51 $send = $self->_h2_create_websocket_send($stream_id, $stream_state);
987 } elsif ($stream_state->{is_sse}) {
988 42 $scope = $self->_h2_create_sse_scope($stream_id, $stream_state);
989 42 $receive = $self->_h2_create_sse_receive($stream_id, $stream_state);
990 42 $send = $self->_h2_create_sse_send($stream_id, $stream_state);
991 } else {
992 112 $scope = $self->_h2_create_scope($stream_id, $stream_state);
993 112 $receive = $self->_h2_create_receive($stream_id, $stream_state);
994 112 $send = $self->_h2_create_send($stream_id, $stream_state);
995 }
996  
997 205 weaken(my $weak_self = $self);
998  
999 205 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=20 SCAR=30.2
1000 205 eval {
1001 205 await $weak_self->{app}->($scope, $receive, $send);
1002 };
1003 202 my $error = $@;
1004  
1005 202 ▶ if ($weak_self) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self) 202 0 202
1006 202 my $cs = $stream_state->{connection_state};
1007  
1008 # Client-already-gone carve-out: if the client reset this stream
1009 # (or the whole connection tore down) while the app's Future was
1010 # still pending, _h2_on_close already ran and drove $cs to an
1011 # ABNORMAL terminal state. There is then nothing left to report:
1012 # no synthesized 500, no incomplete-response RST, no warning
1013 # about a stream the client no longer cares about.
1014 #
1015 # The test is "abnormal", not merely "terminal": a clean
1016 # _mark_complete also leaves $cs disconnected, and it happens
1017 # routinely BEFORE the app returns (the send closure flushes
1018 # END_STREAM synchronously, so _h2_on_close -> _mark_complete
1019 # normally runs inside the app's final await). Keying off
1020 # is_connected would swallow every exception thrown after a
1021 # fully-delivered response. An abnormal end has a
1022 # disconnect_reason; a clean completion leaves it undef.
1023 # Streams with no connection_state (WebSocket/SSE) fall back to
1024 # a liveness fact ($stream_alive below) that is true if and
1025 # only if nghttp2 still owns the stream.
1026 #
1027 # A recorded reason of 'server_error' is NOT a client-gone signal:
1028 # it means the SERVER caused the abnormal end (e.g. this very
1029 # dispatch wrapper's own incomplete-response branch below marks
1030 # server_error before resetting the stream with RST_STREAM
1031 # INTERNAL_ERROR for a response left started-but-unfinished,
1032 # including a trailers-declared response that never sent its
1033 # trailers). Per the PAGI spec's incomplete-response section, the
1034 # log carve-out exists only for "the client had already
1035 # disconnected" -- so server-caused ends must still warn.
1036 #
1037 # $stream_alive is entry-exists-AND-not-yet-closed, not merely
1038 # entry-exists: _h2_on_close marks $stream->{h2_closed} the
1039 # instant it runs, but its h2_streams delete is deferred one
1040 # tick (loop->later) so pending futures can resolve. Waking
1041 # this very Future is one of those pending resolutions -- a
1042 # receive() blocked on body_pending can be woken by
1043 # _h2_on_close and resume this app synchronously, landing here
1044 # before that deferred delete has run. Keying liveness off
1045 # entry-existence alone (as before) missed exactly that
1046 # window: nghttp2 had already forgotten the stream, but
1047 # h2_streams still had it, so the carve-out below saw a "live"
1048 # stream and went on to call submit_response/submit_rst_stream
1049 # on a stream id nghttp2 no longer tracks -- undefined
1050 # behavior at the C level, not something the surrounding eval
1051 # can catch.
1052 my $stream_alive = $weak_self->{h2_streams}{$stream_id}
1053 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
611482
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
1054 202 ▶ my $reason = $cs ? $cs->disconnect_reason : undef;
Branch: 1 branch
BranchTrueFalseTotal
$cs ? : 109 93 202
1055 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
1056 : !$stream_alive;
1057  
1058 202 ▶ if ($client_gone) {
Branch: 4 branches
BranchTrueFalseTotal
if ($client_gone) { } 38 164 202
elsif (not $stream_state->{'response_started'}) { } 7 157 164
elsif ($cs and ($stream_state->{'seq_state'} // 'complete') ne 'complete') { } 6 151 157
elsif ($error) { } 13 138 151
1059 # Nothing to do.
1060 }
1061 elsif (!$stream_state->{response_started}) {
1062 # If the application failed, OR returned without starting a
1063 # response, synthesize a 500 (only possible while no response
1064 # has begun). A clean return that produced no response is a
1065 # protocol error, same as a throw.
1066 7 ▶ $self->_log(error => $error
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 2 5 7
1067 ? "PAGI application error (HTTP/2 stream $stream_id): $error"
1068 : "PAGI application returned without starting a response (HTTP/2 stream $stream_id)");
1069 # Mark BEFORE the response settles: submitting it (below) can
1070 # complete the stream synchronously once flushed, and
1071 # _h2_on_close would then mark this same connection_state
1072 # terminal if it got there first. _mark_disconnected is
1073 # idempotent -- first mark wins -- so marking here first
1074 # guarantees the app observes server_error. The synthesized
1075 # 500 is this stream's response (spec section 9.1), so mark
1076 # it started FIRST: _mark_disconnected fires on_disconnect
1077 # callbacks synchronously, and they must observe
1078 # response_started true.
1079 7 ▶ $cs->_mark_response_started if $cs;
Branch: 1 branch
BranchTrueFalseTotal
if $cs 4 3 7
1080 7 ▶ $cs->_mark_disconnected('server_error') if $cs;
Branch: 1 branch
BranchTrueFalseTotal
if $cs 4 3 7
1081 7 eval {
1082 $weak_self->{h2_session}->submit_response($stream_id,
1083 status => 500,
1084 headers => [
1085 ['content-type', 'text/plain'],
1086 7 ['date', $weak_self->{protocol}->format_date],
1087 ],
1088 body => "Internal Server Error\n",
1089 );
1090 4 $weak_self->_h2_write_pending;
1091 };
1092 }
1093 ▶ elsif ($cs && (($stream_state->{seq_state} // 'complete') ne 'complete')) {
Condition80%4/5
$cs and ($stream_state->{"seq_state"} // "complete") ne "complete"
!ll&&!rl&&r
64876
$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
1094 # Response started but never finished: the app either
1095 # returned cleanly without sending the terminal body/file/fh
1096 # (or trailers), or threw after starting. Either way the
1097 # stream is framed but unterminated -- there is no way to
1098 # synthesize END_STREAM without lying about the body, so
1099 # reset the stream instead. (Only plain HTTP streams reach
1100 # here: WebSocket/SSE never attach a connection_state, so
1101 # $cs guards them out -- their seq_state is never tracked
1102 # and would otherwise misread as permanently incomplete.)
1103 # Trailers-specific parenthetical mirrors the h1 wording (see
1104 # _handle_request's incomplete branch) -- appended after the
1105 # stream-id parenthetical so t/http2/24-incomplete-response.t's
1106 # "...incomplete response (HTTP/2 stream $stream_id)" pin
1107 # still matches as a contiguous substring.
1108 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
1109 ? ' (trailers were declared but never sent)' : '';
1110 6 ▶ $self->_log(error => $error
Branch: 1 branch
BranchTrueFalseTotal
$error ? : 1 5 6
1111 ? "PAGI application error after response started (HTTP/2 stream $stream_id): $error"
1112 : "PAGI application returned with an incomplete response (HTTP/2 stream $stream_id)$trailers_note");
1113 # Mark BEFORE the RST. _h2_on_close fires for our own RST
1114 # too (as an abnormal close, since seq_state never reached
1115 # 'complete') and would mark this same connection_state
1116 # 'client_closed' if it got there first. _mark_disconnected
1117 # is idempotent -- first mark wins -- so marking here first
1118 # guarantees the app observes server_error.
1119 6 $cs->_mark_disconnected('server_error');
1120 6 eval {
1121 $weak_self->{h2_session}->submit_rst_stream(
1122 6 $stream_id, _h2_rst_error_code());
1123 6 $weak_self->_h2_write_pending;
1124 };
1125 }
1126 elsif ($error) {
1127 # Response already complete; cannot send a 500 or usefully
1128 # reset a finished stream. Log only.
1129 13 $self->_log(error => "PAGI application error after response started (HTTP/2 stream $stream_id): $error");
1130 }
1131 }
1132  
1133 # Notify server that request completed (for max_requests tracking)
1134 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
1135 205 })->();
1136  
1137 205 $self->{server}->adopt_future($future);
1138 }
1139  
1140 # HTTP/2 error code for the RST_STREAM sent when a response is left started
1141 # but incomplete (see _h2_dispatch_stream above). NGHTTP2_INTERNAL_ERROR
1142 # (RFC 9113 section 7, code 0x2) is exported by Net::HTTP2::nghttp2.
1143 6 ▶sub _h2_rst_error_code {
Subroutine _h2_rst_error_code: called CC=1 SCAR=0.0
1144 6 return Net::HTTP2::nghttp2::NGHTTP2_INTERNAL_ERROR();
1145 }
1146  
1147 # RST_STREAM error code for a stream the server no longer needs but that is
1148 # nobody's fault -- RFC 9113 section 7 CANCEL. NGHTTP2_CANCEL is exported by
1149 # Net::HTTP2::nghttp2.
1150 2 ▶sub _h2_rst_cancel_code {
Subroutine _h2_rst_cancel_code: called CC=1 SCAR=0.0
1151 2 return Net::HTTP2::nghttp2::NGHTTP2_CANCEL();
1152 }
1153  
1154 115 ▶sub _h2_create_scope {
Subroutine _h2_create_scope: called CC=8 SCAR=22.8
1155 115 my ($self, $stream_id, $stream_state) = @_;
1156  
1157 115 my $pseudo = $stream_state->{pseudo};
1158 115 my $headers = $stream_state->{headers};
1159  
1160 # Parse path and query string from :path pseudo-header
1161 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
1162 115 my ($path, $query_string) = split(/\?/, $full_path, 2);
1163 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
1164  
1165 # Decode percent-encoded path for scope (keep raw_path as-is)
1166 # Match HTTP/1.1 pipeline: URI::Escape + UTF-8 decode with fallback
1167 115 my $unescaped = uri_unescape($path);
1168 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
1169 // $unescaped;
1170  
1171 my $connection_state = PAGI::Server::ConnectionState->new(
1172 connection => $self,
1173 server => $self->{server},
1174 115 );
1175 # Store on the stream-state so the send path can mark response_started on
1176 # this stream's own connection object (h2 multiplexes many streams).
1177 115 $stream_state->{connection_state} = $connection_state;
1178  
1179 return {
1180 type => 'http',
1181 pagi => {
1182 version => '0.5',
1183 spec_version => '0.5',
1184 },
1185 http_version => '2',
1186 method => $pseudo->{':method'} // 'GET',
1187 scheme => $pseudo->{':scheme'} // $self->_get_scheme,
1188 path => $decoded_path,
1189 raw_path => $path,
1190 query_string => $query_string,
1191 root_path => '',
1192 headers => $headers,
1193 (defined $self->{client_host}
1194 ? (client => [$self->{client_host}, $self->{client_port}])
1195 : ()
1196 ),
1197 server => [$self->{server_host}, $self->{server_port}],
1198 0 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
1199 extensions => $self->_get_extensions_for_scope,
1200 'pagi.connection' => $connection_state,
1201 # h2 transport handle measures THIS stream's send queue (per-stream),
1202 # stored on the stream state rather than $self->{current_transport_state}
1203 # because h2 multiplexes many concurrent streams over one connection.
1204 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
1205 };
1206 }
1207  
1208 112 ▶sub _h2_create_receive {
Subroutine _h2_create_receive: called CC=1 SCAR=0.4
1209 112 my ($self, $stream_id, $stream_state) = @_;
1210  
1211 112 weaken(my $weak_self = $self);
1212  
1213 110 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=15.6
1214 110 ▶ return Future->done({ type => 'http.disconnect' }) unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 110 110
1215 110 ▶ return Future->done({ type => 'http.disconnect' }) if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 110 110
1216  
1217 110 my $ss = $weak_self->{h2_streams}{$stream_id};
1218 110 ▶ return Future->done({ type => 'http.disconnect' }) unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 110 110
1219  
1220 110 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=12 SCAR=30.1
1221 110 ▶ return { type => 'http.disconnect' } unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 110 110
1222  
1223 110 my $ss = $weak_self->{h2_streams}{$stream_id};
1224 110 ▶ return { type => 'http.disconnect' } unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 110 110
1225  
1226 # Check queue first
1227 110 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 110 110
1228 0 return shift @{$ss->{receive_queue}};
1229 }
1230  
1231 # If body is already complete, return the final body event --
1232 # once. A receive called after the terminal event parks in the
1233 # wait loop below until the stream ends, matching h1's
1234 # post-request receive contract (stream close queues
1235 # http.disconnect and wakes body_pending). Same one-shot
1236 # discipline as the SSE closure's sse_request_sent.
1237 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
1238 103 $ss->{final_request_delivered} = 1;
1239 103 my $body = $ss->{body};
1240 103 $ss->{body} = '';
1241 return {
1242 103 type => 'http.request',
1243 body => $body,
1244 more => 0,
1245 };
1246 }
1247  
1248 7 while (1) {
1249 # Wait for body data (or, once the request has been fully
1250 # delivered, for the stream to end)
1251 7 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 7 0 7
1252 7 $ss->{body_pending} = Future->new;
1253 }
1254 7 await $ss->{body_pending};
1255  
1256 # Re-fetch stream state (may have changed)
1257 7 $ss = $weak_self->{h2_streams}{$stream_id};
1258 7 ▶ return { type => 'http.disconnect' } unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 7 7
1259  
1260 # Check queue after waking -- a queued event wins over the
1261 # body fallthrough (a close can set body_complete AND queue
1262 # http.disconnect on the same wake)
1263 7 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 7 0 7
1264 7 return shift @{$ss->{receive_queue}};
1265 }
1266  
1267 # Terminal event already delivered: this wake brought
1268 # nothing for the application -- park again rather than
1269 # re-synthesize the final body event.
1270 0 ▶ next if $ss->{final_request_delivered};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"final_request_delivered"} 0 0 0
1271  
1272 0 ▶ my $more = $ss->{body_complete} ? 0 : 1;
Branch: 1 branch
BranchTrueFalseTotal
$ss->{'body_complete'} ? : 0 0 0
1273 0 ▶ $ss->{final_request_delivered} = 1 unless $more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 0 0 0
1274 0 my $body = $ss->{body};
1275 0 $ss->{body} = '';
1276 return {
1277 0 type => 'http.request',
1278 body => $body,
1279 more => $more,
1280 };
1281 }
1282 110 })->();
1283  
1284 110 return $future;
1285 112 };
1286 }
1287  
1288 112 ▶sub _h2_create_send {
Subroutine _h2_create_send: called CC=2 SCAR=7.0
1289 112 my ($self, $stream_id, $stream_state) = @_;
1290  
1291 112 weaken(my $weak_self = $self);
1292  
1293 112 my $status;
1294 my @response_headers;
1295  
1296 # Streaming state for deferred data provider pattern.
1297 # The send queue lives on per-stream state ($ss->{send_queue} /
1298 # $ss->{send_queue_bytes}) so the h2 transport handle can measure it;
1299 # $eof_pending / $streaming_started stay closure-local.
1300 112 my $eof_pending = 0;
1301 112 my $streaming_started = 0;
1302 # Mirrors the stream state's own starting point (see the seq_state =>
1303 # 'initial' initializer in _h2_on_request); the two must stay in step.
1304 112 my $seq = 'initial';
1305 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
1306 # Set once, from http.response.start's own 'trailers' flag (section 6
1307 # below), and never changed again. $data_callback's no_end computation
1308 # MUST key off this rather than $ss->{seq_state}: the trailers arm
1309 # advances that mirror to 'complete' as soon as the app's send() call
1310 # is made, which can be BEFORE the data provider has actually drained
1311 # (deferred submit, see below) -- keying off seq_state there raced the
1312 # mirror update and let END_STREAM land back on the DATA frame.
1313 112 my $trailers_declared = 0;
1314  
1315 # Trailers-vs-data-provider handshake (design §8.3). Confirmed
1316 # empirically: calling submit_trailer() BEFORE the data provider has
1317 # actually handed nghttp2 its terminal (eof=1) chunk silently abandons
1318 # any DATA nghttp2 has not yet pulled through $data_callback (observed
1319 # under real per-stream flow control -- the still-queued tail of a
1320 # file/fh body never reached the wire, yet the stream closed "cleanly"
1321 # with the trailer -- a DEFERRED data-provider item is detached from
1322 # nghttp2's own outbound queue, so an early trailing HEADERS orphans
1323 # it). The Net::HTTP2::nghttp2 binding's own POD says submit_trailer()
1324 # "can be called inside" the data-provider callback OR after it
1325 # returns -- it does not say "at any later, unrelated time" -- so the
1326 # invariant this handshake actually enforces is narrower and stricter:
1327 # never BEFORE the provider has delivered its terminal EOF. The
1328 # trailers arm below submits directly ONLY once $data_eof_delivered is
1329 # already true (no further callback invocation will occur for this
1330 # stream); otherwise it stages the headers here and PARKS the send()
1331 # until the callback's own terminal invocation submits them.
1332 #
1333 # Contract note (flag for Task 6 / Compliance.pod): this means a
1334 # trailers send() can now block for as long as the peer withholds
1335 # flow-control window on a still-draining body -- new, unbounded-in-
1336 # the-app's-view blocking that a pre-Task-4 (stub) reading of the spec
1337 # would not have anticipated. This is arguably MORE correct, not a
1338 # regression: trailers now participate in the same backpressure body
1339 # sends already do, rather than racing ahead of undelivered DATA.
1340 112 my $data_eof_delivered = 0;
1341 112 my $pending_trailer_headers;
1342  
1343 # Called by $data_callback at the exact point it hands nghttp2 the
1344 # terminal (eof=1) chunk. If a trailers send() is waiting on this
1345 # (staged $pending_trailer_headers), submits it HERE -- synchronously,
1346 # from inside the data-provider callback, per nghttp2's own sanctioned
1347 # pattern -- then wakes the waiting send() on the next loop tick (never
1348 # resolve an app Future from inside a native nghttp2 callback -- same
1349 # discipline as the drain waiters above).
1350 34 ▶ my $deliver_trailer_eof = sub {
Subroutine __ANON__: called CC=7 SCAR=20.5
1351 34 $data_eof_delivered = 1;
1352 34 ▶ return unless defined $pending_trailer_headers;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pending_trailer_headers 32 2 34
1353 2 my $headers = $pending_trailer_headers;
1354 2 $pending_trailer_headers = undef;
1355 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
1356 # Dead-stream invariant, kept local here rather than inferred from
1357 # the doomed-but-still-present carve-out pattern used across this
1358 # file (h2_closed set, entry not yet reclaimed): don't reach
1359 # nghttp2 a second time on a stream id it may already be tearing
1360 # down. Two close paths, two mechanisms, same outcome -- there's
1361 # nothing left to do here either way: _h2_on_close and the 413
1362 # early-close branch set h2_closed on the still-present entry
1363 # (caught by the check below), while a whole-connection _close
1364 # deletes the h2_streams entry outright (so $ss2 comes back undef
1365 # here) and releases trailer_wait itself via its own sweep. Either
1366 # way, whichever close path is running has already released -- or
1367 # is about to release -- trailer_wait.
1368 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
1369 2 my $ok = eval {
1370 2 $weak_self->{h2_session}->submit_trailer($stream_id, headers => $headers);
1371 1 1;
1372 };
1373 2 my $err = $@;
1374 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
1375 2 ▶ return unless $f;
Branch: 1 branch
BranchTrueFalseTotal
unless $f 0 2 2
1376 2 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=3 SCAR=11.0
1377 2 ▶ return if $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $f->is_ready 0 2 2
1378 2 ▶ if ($ok) { $f->done(1) } else { $f->fail($err) }
Branch: 1 branch
BranchTrueFalseTotal
if ($ok) { } 1 1 2
1379 2 });
1380 112 };
1381  
1382 # Data callback for nghttp2's streaming response.
1383 # Returns ($data, $eof) when data is available, or undef to defer.
1384 321 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=20 SCAR=30.1
1385 321 my ($cb_stream_id, $max_len) = @_;
1386  
1387 321 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
00321
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
1388 321 ▶ return undef unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 321 321
1389 321 ▶ my $q = $ss->{send_queue} ||= [];
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
3210
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
1390  
1391 321 ▶ if (@$q) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$q) 239 82 321
1392 239 my $chunk = shift @$q;
1393 # Respect max_len — XS truncates without preserving remainder
1394 239 ▶ if (length($chunk) > $max_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk > $max_len) 108 131 239
1395 108 unshift @$q, substr($chunk, $max_len);
1396 108 $chunk = substr($chunk, 0, $max_len);
1397 }
1398 239 $ss->{send_queue_bytes} -= length($chunk);
1399  
1400 # Per-stream backpressure: once this stream's queue falls below the
1401 # low watermark, release any producer blocked in
1402 # _h2_wait_for_stream_drain. This callback runs inside nghttp2's
1403 # extract(), so resolve on the next loop tick — completing the Future
1404 # resumes the awaiting producer synchronously, and it must not call
1405 # resume_stream/_h2_write_pending re-entrantly into nghttp2.
1406 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
1219721
$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
1407 21 && $ss->{stream_drain_waiters} && @{$ss->{stream_drain_waiters}}) {
1408 10 my @waiters = splice @{$ss->{stream_drain_waiters}};
1409 10 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1410 10 $_->done for grep { !$_->is_ready } @waiters;
1411 10 });
1412 }
1413  
1414 # Fire the app's on_drain hysteresis callbacks once this stream's
1415 # queue falls below the low watermark. Like the waiters above, this
1416 # runs inside nghttp2's extract(), and an on_drain callback may call
1417 # $send to resume its source — which would re-enter nghttp2. Splice
1418 # the fires out first (so they can't double-fire), then invoke them on
1419 # the next loop tick.
1420 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
1923017
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"}
!ll&&!rl&&r
1217147
$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
1421 47 && $ss->{transport_drain_fires} && @{$ss->{transport_drain_fires}}) {
1422 17 my @fires = splice @{$ss->{transport_drain_fires}};
1423 17 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
1424 17 $_->() for @fires;
1425 17 });
1426 }
1427  
1428 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
1615424
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
1429 # Trailers declared: reserve END_STREAM for the trailing
1430 # HEADERS block (design §8.3) instead of letting it land on
1431 # this DATA frame. Has no effect unless $eof is also true
1432 # (Net::HTTP2::nghttp2's own contract), so it is safe to key
1433 # off $trailers_declared unconditionally here rather than the
1434 # $ss->{seq_state} mirror, which the trailers arm may have
1435 # already advanced past 'awaiting_trailers' by this point.
1436 239 ▶ my $no_end = $trailers_declared ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$trailers_declared ? : 49 190 239
1437 239 ▶ $deliver_trailer_eof->() if $eof;
Branch: 1 branch
BranchTrueFalseTotal
if $eof 24 215 239
1438 239 return ($chunk, $eof, $no_end);
1439 }
1440  
1441 # Queue empty but EOF pending — signal end of stream
1442 82 ▶ if ($eof_pending) {
Branch: 1 branch
BranchTrueFalseTotal
if ($eof_pending) 10 72 82
1443 10 ▶ my $no_end = $trailers_declared ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$trailers_declared ? : 2 8 10
1444 10 $deliver_trailer_eof->();
1445 10 return ('', 1, $no_end);
1446 }
1447  
1448 # Queue empty, more data expected — defer (NGHTTP2_ERR_DEFERRED in C layer)
1449 72 return undef;
1450 112 };
1451  
1452 # Shared file/fh chunk pump: pushes produced chunks into this stream's
1453 # send queue under the per-stream watermark, then marks EOF. The producer
1454 # is an async sub that receives an async "emit" callback and must await it
1455 # per chunk; emit dies with the sentinel below if the stream vanishes
1456 # (client reset) so the pump stops reading without treating it as an error.
1457 112 my $STREAM_GONE = "PAGI::h2 stream gone\n";
1458 39 ▶ my $emit_chunk = async sub {
Subroutine __ANON__: called CC=13 SCAR=27.5
1459 39 my ($chunk) = @_;
1460 39 ▶ my $ss = $weak_self ? $weak_self->{h2_streams}{$stream_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 39 0 39
1461 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
1462 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
1463 6 await $weak_self->_h2_wait_for_stream_drain($stream_id);
1464 6 ▶ $ss = $weak_self ? $weak_self->{h2_streams}{$stream_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 6 0 6
1465 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
1466 }
1467 38 ▶ if (length $chunk) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk) 37 1 38
1468 37 push @{$ss->{send_queue}}, $chunk;
1469 37 $ss->{send_queue_bytes} += length $chunk;
1470 }
1471 38 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 38 0 38
1472 38 $weak_self->{h2_session}->resume_stream($stream_id);
1473 38 $weak_self->_h2_write_pending;
1474 38 return;
1475 112 };
1476  
1477 # Shared tail for the file/fh arms below: mark EOF pending and resume the
1478 # stream once the read loop finishes without error. A no-op if the stream
1479 # vanished (client reset) while the last chunk was in flight.
1480 13 ▶ my $finish_body_stream = sub {
Subroutine __ANON__: called CC=3 SCAR=11.3
1481 13 $eof_pending = 1;
1482 13 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 13 13
1483 13 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 13 13
1484 13 $weak_self->{h2_session}->resume_stream($stream_id);
1485 13 $weak_self->_h2_write_pending;
1486 112 };
1487  
1488 # Shared preamble for the file/fh body arms below (extraction, not a
1489 # redesign -- see the arms themselves for why each piece sits where it
1490 # does). Split in two because the two pieces cross the arms' own
1491 # eval boundary: the file arm must report an illegal-sequence error
1492 # (from advance_http) ahead of a misleading "File not found" from its
1493 # own -f/-r checks, but must NOT have submitted response headers to the
1494 # client before those checks pass -- so the sequence advance runs
1495 # BEFORE the arm's eval (a comment-preserving-only move: advance_http
1496 # is a pure function, and a caught vs. uncaught throw here already
1497 # behaved identically before this extraction, since $seq is simply
1498 # never reassigned on a throw either way), while the streaming-start
1499 # call must stay INSIDE the eval, at each arm's own correct position
1500 # relative to its own pre-checks, so a failure there still rolls back
1501 # via the shared tail below instead of leaking a submitted-but-broken
1502 # response.
1503  
1504 # Outside-eval half: snapshot+advance+mirror the sequence state ahead
1505 # of either arm's own validity checks. Returns the pre-advance $seq so
1506 # the tail helper below can roll back to it on failure.
1507 19 ▶ my $advance_seq_for_body = sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
1508 19 my ($ss, $event) = @_;
1509 19 my $seq_before = $seq;
1510 19 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1511 17 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 17 0 17
1512 17 return $seq_before;
1513 112 };
1514  
1515 # Inside-eval half: submit the streaming response exactly once, the
1516 # first time either arm actually has a chunk ready to send. Each arm
1517 # calls this at its own correct point (after its own pre-checks, so a
1518 # failed check never causes headers to reach the client for a response
1519 # that goes on to fail).
1520 16 ▶ my $ensure_h2_streaming_started = sub {
Subroutine __ANON__: called CC=4 SCAR=14.3
1521 16 my ($ss) = @_;
1522 16 ▶ return if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 0 16 16
1523 16 $streaming_started = 1;
1524 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
1525 $weak_self->{h2_session}->submit_response_streaming(
1526 16 $stream_id,
1527 status => $status, headers => \@response_headers,
1528 data_callback => $data_callback,
1529 );
1530 16 $weak_self->_h2_write_pending;
1531 112 };
1532  
1533 # Shared failure-rollback-or-finish tail for the file/fh body arms:
1534 # given the arm's own eval result, either rolls $seq back to its
1535 # pre-event value and re-raises (recoverable per contract, unless the
1536 # stream is simply gone -- a quiet no-op), or marks the body stream's
1537 # EOF pending on success. Mirrors h1's D1 advance-then-rollback pattern.
1538 17 ▶ my $finish_or_rollback_body_send = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
1539 17 my ($ok, $err, $ss, $seq_before) = @_;
1540 17 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 4 13 17
1541 4 ▶ return if $err eq $STREAM_GONE; # client reset: quiet no-op
Branch: 1 branch
BranchTrueFalseTotal
if $err eq $STREAM_GONE 1 3 4
1542 3 $seq = $seq_before; # recoverable, per contract
1543 3 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 3 0 3
1544 3 die $err;
1545 }
1546 13 $finish_body_stream->();
1547 112 };
1548  
1549 316 ▶ return async sub {
Subroutine __ANON__: called CC=90 SCAR=47.8
1550 316 my ($event) = @_;
1551 316 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 316 316
1552  
1553 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
1554  
1555 # Once the machine has recorded the response complete, the machine
1556 # decides what happens next -- 'complete' has no idempotent case, so
1557 # any further send always raises -- not the stream-gone check below.
1558 # h2_streams entries for a finished stream are reclaimed
1559 # asynchronously by _h2_on_close, so by the time a post-complete send
1560 # arrives $ss may already be gone.
1561 316 my $already_closed = ($seq eq 'complete');
1562  
1563 316 my $ss = $weak_self->{h2_streams}{$stream_id};
1564 # A doomed-but-still-present entry (h2_closed set but not yet
1565 # deleted -- see the 413-overrun branch in _h2_on_body) is treated
1566 # the same as an absent one: both are post-close sends and must
1567 # silently no-op, not reach nghttp2 a second time on this stream id.
1568 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
1569  
1570 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
1571  
1572 # 1. Shape validation (mandatory)
1573 PAGI::Server::EventValidator::validate_http_send(
1574 310 $event, { extensions => $weak_self->{extensions} });
1575  
1576 # 2. HEAD: the server suppresses the body (PAGI Www.pod "HEAD Requests").
1577 # The app responds exactly as for GET; we discard payloads, never open
1578 # file/fh, and accept-and-discard trailers. Sequence state still
1579 # advances so the lifecycle (completion, post-complete raises) matches GET.
1580 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
29179
$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
1581 9 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1582 9 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 9 0 9
1583 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
1584 7 $ss->{h2_head_finished} = 1;
1585 7 $weak_self->{h2_session}->submit_response($stream_id,
1586 status => $status,
1587 headers => \@response_headers,
1588 body => '',
1589 );
1590 7 $weak_self->_h2_write_pending;
1591 }
1592 9 return;
1593 }
1594  
1595 # 3. http.response.trailers (design §8.3): submits the trailing
1596 # HEADERS block with END_STREAM, completing a response that declared
1597 # trailers at start. advance-then-rollback (h1 D1 pattern, mirrored
1598 # from _create_send's chunked-framing check): the sequence machine
1599 # and its $ss mirror advance FIRST, then the native submit is
1600 # attempted (directly here, or via $deliver_trailer_eof above --
1601 # see the closure-top comment for why). advance_http itself may
1602 # croak here (trailers undeclared or body not yet complete) -- that
1603 # propagates unrolled-back, same as validate_http_send's shape
1604 # check above, since $seq was never reassigned in that case. If
1605 # submit_trailer throws, both are rolled back to their pre-event
1606 # value and the error propagates: the app's return then lands in
1607 # the existing incomplete-response arm (RST NGHTTP2_INTERNAL_ERROR)
1608 # -- the same machinery a dropped body chunk already relies on, not
1609 # duplicated here.
1610 298 ▶ if ($type eq 'http.response.trailers') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "http.response.trailers") 11 287 298
1611 11 my $seq_before = $seq;
1612 11 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1613 10 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 10 0 10
1614  
1615 # Empty/absent headers still calls submit_trailer with [] --
1616 # trailers were declared and must still terminate the response.
1617 my $trailer_headers = [
1618 16 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
1619 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
1620 ];
1621 # RFC 9110 6.6.2 / design 13.3 -- an app-supplied connection,
1622 # transfer-encoding, etc. in a trailer block corrupts it at the
1623 # framing layer exactly like a response header: nghttp2 rejects
1624 # the whole trailer HEADERS block, so the peer sees zero
1625 # trailing HEADERS (on_stream_close never fires) even though
1626 # submit_trailer below reports success. Strip before submission,
1627 # same as every response-header path; $in_trailers=1 drops the
1628 # response-only 'te: trailers' carve-out (RFC 9110 6.6.2 bans
1629 # connection-specific fields from trailers outright).
1630 10 $trailer_headers = $weak_self->_h2_strip_connection_headers($trailer_headers, 1);
1631  
1632 10 my $ok;
1633 10 ▶ if ($data_eof_delivered) {
Branch: 1 branch
BranchTrueFalseTotal
if ($data_eof_delivered) { } 6 4 10
1634 # The data provider already handed nghttp2 its terminal
1635 # chunk -- no further $data_callback invocation will occur
1636 # for this stream, so it is safe to submit directly here.
1637 6 $ok = eval {
1638 $weak_self->{h2_session}->submit_trailer(
1639 6 $stream_id, headers => $trailer_headers);
1640 5 1;
1641 };
1642 } else {
1643 # The data provider has not yet delivered EOF to nghttp2
1644 # (still mid-transfer, possibly blocked on real per-stream
1645 # flow control). Stage the headers for $deliver_trailer_eof
1646 # to submit from inside the callback's own terminal
1647 # invocation, and await that -- resolving this send() any
1648 # earlier would let submit_trailer race ahead of not-yet-
1649 # extracted DATA (see the closure-top comment). This PARKS
1650 # the send() until the body actually finishes draining --
1651 # e.g. until the peer grants enough flow-control window --
1652 # which can be a real, unbounded wait from the app's point
1653 # of view (closure-top comment has the full contract note).
1654 4 $pending_trailer_headers = $trailer_headers;
1655 4 my $f = $weak_self->{server}->loop->new_future;
1656 4 $ss->{trailer_wait} = $f;
1657 4 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 4 0 4
1658 4 $weak_self->_h2_write_pending;
1659 # eval wraps the await (not just a plain assignment) so a
1660 # failed $f (native rejection, via $deliver_trailer_eof's
1661 # own $f->fail) is caught into $@ and folds into the same
1662 # $ok/rollback handling the direct branch above uses.
1663 4 $ok = eval { await $f; 1 };
1664 # $f resolves DONE (not fail) on a whole-connection teardown
1665 # too (_close's own sweep releases trailer_wait -- see
1666 # _h2_resolve_stream_trailer_wait) -- the h2_closed carve-
1667 # out's "successful no-op" contract, same discipline as the
1668 # body arms' own post-drain-wait liveness re-check
1669 # (:1616-1619 / :1635-1638 above). Without this, a
1670 # connection that died while we awaited would leave
1671 # $weak_self->{h2_session} undef and the shared tail below
1672 # would call a method on it.
1673 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
1674 }
1675 9 ▶ if (!$ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 2 7 9
1676 2 my $err = $@;
1677 2 $seq = $seq_before;
1678 2 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 2 0 2
1679 2 die $err;
1680 }
1681  
1682 # Stream-existence re-check, same discipline as every sibling
1683 # await site's own $ss re-fetch (e.g. $emit_chunk above): the
1684 # connection-liveness check at :1524 only covers the deferred
1685 # branch and only the connection, not this stream specifically.
1686 # Placed AFTER the rollback above (not folded into :1524) so a
1687 # deferred native failure still reaches its rollback+die even if
1688 # the stream looks gone by the time we get here -- only the
1689 # success-path tail below, which is about to call resume_stream/
1690 # _h2_write_pending on this stream id again, needs the guard.
1691 # A gone stream here is the h2_closed carve-out's ordinary
1692 # "successful no-op" case: the trailers already landed (ok=1)
1693 # before the stream went away, so returning quietly is correct,
1694 # not a swallowed error.
1695 7 ▶ $ss = $weak_self ? $weak_self->{h2_streams}{$stream_id} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$weak_self ? : 7 0 7
1696 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
1697  
1698 # Flush any still-queued DATA before the trailing HEADERS --
1699 # nghttp2 orders trailers after queued data on its own, but the
1700 # stream must be resumed if the data callback had deferred.
1701 5 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 5 0 5
1702 5 $weak_self->_h2_write_pending;
1703 5 return;
1704 }
1705  
1706 # 4. file body: streamed through the send queue via $emit_chunk, one
1707 # chunk at a time, under this stream's own backpressure. The type
1708 # guard (not just "defined $event->{file}") keeps a nonconforming
1709 # http.response.start carrying a stray 'file' key from being
1710 # misrouted into this arm.
1711 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
1712 10 my $file = $event->{file};
1713 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
1714 10 my $length = $event->{length};
1715  
1716 # Snapshot+advance BEFORE the -f/-r checks (and the checks live
1717 # inside the eval below) so a file event arriving in an illegal
1718 # sequence state reports the SEQUENCE error, not a misleading
1719 # "File not found" -- h1 parity. A failed file send must NOT
1720 # mark the response complete, so on failure $seq rolls back to
1721 # $seq_before exactly as the h1 twin in _create_send does.
1722 10 my $seq_before = $advance_seq_for_body->($ss, $event);
1723  
1724 8 my $ok = eval {
1725 8 ▶ die "File not found: $file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 7 8
1726 7 ▶ die "Cannot read file: $file\n" unless -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $file 0 7 7
1727  
1728 7 $ensure_h2_streaming_started->($ss);
1729  
1730 # Mirror h1's effective-length computation (_send_file_response)
1731 # so the sync-vs-async choice below sees the same number h1
1732 # would, including the Www.pod rule that an offset past EOF
1733 # clamps to zero bytes rather than failing.
1734 7 my $file_size = -s $file;
1735 7 ▶ die "Cannot stat file $file: $!\n" unless defined $file_size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_size 0 7 7
1736 7 ▶ my $effective_length = $length // ($file_size - $offset);
Condition100%2/2
$length // $file_size - $offset
l!l
16
MC/DC100%1/1
$length // $file_size - $offset
$length
Truth table100%2/2
A
A= $length
Aresult
11
00
1737 7 ▶ $effective_length = 0 if $effective_length < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $effective_length < 0 1 6 7
1738  
1739 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
1740 && $effective_length <= $weak_self->{sync_file_threshold}) {
1741 # Small-file fast path (parity with h1's sync_file_threshold):
1742 # a file at or under the threshold is read synchronously,
1743 # in-process, as ONE queue chunk -- avoiding a worker-pool
1744 # round trip for a body small enough that it costs more
1745 # than it saves. The no-slurp rule targets large files.
1746 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" 4 0 4
1747 4 ▶ seek($fh, $offset, 0) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 2 2 4
1748 4 my $bytes_read = read($fh, my $data, $effective_length);
1749 4 ▶ die "Failed to read file $file: $!\n" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 0 4 4
1750 4 close $fh;
1751 4 await $emit_chunk->($data);
1752 }
1753 else {
1754 3 my $loop = $weak_self->{server}->loop;
1755 3 ▶ await PAGI::Server::AsyncFile->read_file_chunked(
Branch: 1 branch
BranchTrueFalseTotal
defined $length ? : 0 3 3
1756 $loop, $file, $emit_chunk,
1757 offset => $offset,
1758 (defined $length ? (length => $length) : ()),
1759 chunk_size => FILE_CHUNK_SIZE,
1760 );
1761 }
1762 6 1;
1763 };
1764 8 $finish_or_rollback_body_send->($ok, $@, $ss, $seq_before);
1765 7 return;
1766 }
1767  
1768 # 5. fh body: streamed through the send queue via $emit_chunk, one
1769 # chunk at a time, under this stream's own backpressure. The
1770 # application owns $fh (opened before the send, closed or not by the
1771 # app afterward) -- the server never closes it. Mirrors the file arm
1772 # above; the read loop is adapted from h1's _send_fh_response. The
1773 # type guard mirrors the file arm's M1 fix above.
1774 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
1775 9 my $fh = $event->{fh};
1776  
1777 9 my $seq_before = $advance_seq_for_body->($ss, $event);
1778  
1779 9 my $ok = eval {
1780 9 $ensure_h2_streaming_started->($ss);
1781 9 ▶ if (my $off = $event->{offset}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $off = $event->{"offset"}) 3 6 9
1782 3 ▶ seek($fh, $off, 0) or die "Cannot seek: $!\n";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $off, 0 or die "Cannot seek: $!\n" 2 1 3
1783 }
1784 8 my $remaining = $event->{length};
1785 8 while (1) {
1786 30 my $to_read = FILE_CHUNK_SIZE;
1787 30 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 2 28 30
1788 2 ▶ $to_read = $remaining if $remaining < $to_read;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining < $to_read 2 0 2
1789 2 ▶ last if $to_read <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $to_read <= 0 1 1 2
1790 }
1791 # The bare block scopes only the 'closed' warning
1792 # suppression around read() -- a bare block is itself a
1793 # one-iteration loop, so die/last/await must live outside
1794 # it or 'last' would only exit the block, not this while.
1795 29 my ($bytes_read, $chunk);
1796 156 ▶ { no warnings 'closed';
Subroutine BEGIN: called CC=1 SCAR=0.0
1797 29 $bytes_read = read($fh, $chunk, $to_read);
1798 }
1799 29 ▶ die "Failed to read filehandle: $!\n" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 1 28 29
1800 28 ▶ last if $bytes_read == 0;
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_read == 0 6 22 28
1801 22 await $emit_chunk->($chunk);
1802 22 ▶ $remaining -= $bytes_read if defined $remaining;
Branch: 1 branch
BranchTrueFalseTotal
if defined $remaining 1 21 22
1803 }
1804 7 1;
1805 };
1806 9 $finish_or_rollback_body_send->($ok, $@, $ss, $seq_before);
1807 7 return;
1808 }
1809  
1810 # 6. Sequence enforcement (start / plain body / fullflush). advance_http
1811 # is deliberately called from four places in this sub — the HEAD
1812 # block above, the file arm, the fh arm, and here — each has
1813 # different pre/post-state needs; do not consolidate them.
1814 268 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
1815 265 ▶ $ss->{seq_state} = $seq if $ss;
Branch: 1 branch
BranchTrueFalseTotal
if $ss 265 0 265
1816  
1817 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
1818 101 $ss->{response_started} = 1;
1819 101 ▶ $ss->{connection_state}->_mark_response_started if $ss->{connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"connection_state"} 101 0 101
1820 101 ▶ $trailers_declared = 1 if $event->{trailers};
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"trailers"} 14 87 101
1821  
1822 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
1823 @response_headers = map {
1824 113 [_validate_header_name($_->[0]), _validate_header_value($_->[1])]
1825 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
1826 # RFC 9113 8.2.2 / design 13.3 — strips app-supplied connection,
1827 # transfer-encoding, etc. before this list reaches nghttp2 (also
1828 # covers the HEAD path below, which submits this same array).
1829 101 @response_headers = @{ $weak_self->_h2_strip_connection_headers(\@response_headers) };
1830 # Server-supplied Date header (HTTP/1.1 parity) — add if the app didn't.
1831 101 ▶ unless (grep { lc($_->[0]) eq 'date' } @response_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @response_headers) 101 0 101
1832 101 push @response_headers, ['date', $weak_self->{protocol}->format_date];
1833 }
1834 }
1835 elsif ($type eq 'http.response.body') {
1836 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
1837 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
1838  
1839 163 ▶ if ($more) {
Branch: 1 branch
BranchTrueFalseTotal
if ($more) { } 89 74 163
1840 89 ▶ if (!$streaming_started) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $streaming_started) { } 20 69 89
1841 # First streaming chunk — submit with data callback
1842 20 $streaming_started = 1;
1843 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
1844 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
1845 20 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 20 0 20
1846 20 push @{$ss->{send_queue}}, $body;
1847 20 $ss->{send_queue_bytes} += length $body;
1848 }
1849 # Synchronous: we're in the app's send path (not nghttp2's
1850 # extract), so on_high_water can fire here to tell the app to
1851 # pause its source.
1852 20 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 20 0 20
1853 $weak_self->{h2_session}->submit_response_streaming(
1854 20 $stream_id,
1855 status => $status,
1856 headers => \@response_headers,
1857 data_callback => $data_callback,
1858 );
1859 20 $weak_self->_h2_write_pending;
1860 } else {
1861 # Subsequent chunk — backpressure check then push and resume.
1862 # Bound on THIS stream's send queue (per-stream), not the
1863 # shared TCP buffer which is meaningless across multiplexed
1864 # streams.
1865 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
1866 6 await $weak_self->_h2_wait_for_stream_drain($stream_id);
1867 6 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 6 6
1868 6 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 6 6
1869 6 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 6 6
1870 }
1871 69 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 69 0 69
1872 69 push @{$ss->{send_queue}}, $body;
1873 69 $ss->{send_queue_bytes} += length $body;
1874 }
1875 # Synchronous — app send path, not nghttp2 extract.
1876 69 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 68 1 69
1877 69 $weak_self->{h2_session}->resume_stream($stream_id);
1878 69 $weak_self->_h2_write_pending;
1879 }
1880 } else {
1881 74 ▶ if ($streaming_started) {
Branch: 2 branches
BranchTrueFalseTotal
if ($streaming_started) { } 16 58 74
elsif ($seq eq 'awaiting_trailers') { } 7 51 58
1882 # Final chunk on an already-streaming response. Bound on THIS
1883 # stream's send queue (per-stream), not the shared TCP buffer.
1884 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
1885 0 await $weak_self->_h2_wait_for_stream_drain($stream_id);
1886 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
1887 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
1888 0 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 0 0
1889 }
1890 16 $eof_pending = 1;
1891 16 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 14 2 16
1892 14 push @{$ss->{send_queue}}, $body;
1893 14 $ss->{send_queue_bytes} += length $body;
1894 }
1895 # Synchronous — app send path, not nghttp2 extract.
1896 16 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 16 0 16
1897 16 $weak_self->{h2_session}->resume_stream($stream_id);
1898 16 $weak_self->_h2_write_pending;
1899 } elsif ($seq eq 'awaiting_trailers') {
1900 # Trailers were declared and this is the (single-shot)
1901 # terminal body event: a plain submit_response would set
1902 # END_STREAM immediately, ending the stream before the
1903 # trailers arrive -- design §8.3 forbids that. Route
1904 # through the streaming path instead, mirroring the
1905 # file/fh arms' $streaming_started idiom; the data
1906 # callback above already reserves END_STREAM for the
1907 # trailing HEADERS block once it observes
1908 # 'awaiting_trailers'.
1909 7 $streaming_started = 1;
1910 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
1911 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
1912 7 $eof_pending = 1;
1913 7 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 5 2 7
1914 5 push @{$ss->{send_queue}}, $body;
1915 5 $ss->{send_queue_bytes} += length $body;
1916 }
1917 7 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 7 0 7
1918 $weak_self->{h2_session}->submit_response_streaming(
1919 7 $stream_id,
1920 status => $status,
1921 headers => \@response_headers,
1922 data_callback => $data_callback,
1923 );
1924 7 $weak_self->_h2_write_pending;
1925 } else {
1926 # Non-streaming: single response (unchanged one-shot path)
1927 51 $weak_self->{h2_session}->submit_response($stream_id,
1928 status => $status,
1929 headers => \@response_headers,
1930 body => $body,
1931 );
1932 51 $weak_self->_h2_write_pending;
1933 }
1934 }
1935 }
1936 elsif ($type eq 'http.fullflush') {
1937 # Hand any pending frames to the session's write path (design §8.4).
1938 1 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 1 0 1
1939 1 $weak_self->_h2_write_pending;
1940 }
1941 112 };
1942 }
1943  
1944 # =============================================================================
1945 # HTTP/2 WebSocket over HTTP/2 (RFC 8441)
1946 # =============================================================================
1947  
1948 53 ▶sub _h2_create_websocket_scope {
Subroutine _h2_create_websocket_scope: called CC=9 SCAR=22.6
1949 53 my ($self, $stream_id, $stream_state) = @_;
1950  
1951 53 my $pseudo = $stream_state->{pseudo};
1952 53 my $headers = $stream_state->{headers};
1953  
1954 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
1955 53 my ($path, $query_string) = split(/\?/, $full_path, 2);
1956 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
1957  
1958 # Match HTTP/1.1 pipeline: URI::Escape + UTF-8 decode with fallback
1959 53 my $unescaped = uri_unescape($path);
1960 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
1961 // $unescaped;
1962  
1963 # Extract subprotocols from headers
1964 53 my @subprotocols;
1965 53 for my $header (@$headers) {
1966 104 my ($name, $value) = @$header;
1967 104 ▶ if ($name eq 'sec-websocket-protocol') {
Branch: 1 branch
BranchTrueFalseTotal
if ($name eq "sec-websocket-protocol") 1 103 104
1968 1 push @subprotocols, map { s/^\s+|\s+$//gr } split /,/, $value;
1969 }
1970 }
1971  
1972 return {
1973 type => 'websocket',
1974 pagi => {
1975 version => '0.5',
1976 spec_version => '0.5',
1977 },
1978 http_version => '2',
1979 scheme => $self->_get_ws_scheme,
1980 path => $decoded_path,
1981 raw_path => $path,
1982 query_string => $query_string,
1983 root_path => '',
1984 headers => $headers,
1985 (defined $self->{client_host}
1986 ? (client => [$self->{client_host}, $self->{client_port}])
1987 : ()
1988 ),
1989 server => [$self->{server_host}, $self->{server_port}],
1990 subprotocols => \@subprotocols,
1991 0 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
1992 extensions => do {
1993 53 my %ext = (%{$self->_get_extensions_for_scope}, 'websocket.http.response' => {});
1994 # fullflush has no validate_websocket_send arm; advertising it here
1995 # would lie to the app (design 13.2).
1996 53 delete $ext{fullflush};
1997 53 ▶ \%ext;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'max_ws_frame_size'} ? : 50 3 53
1998 },
1999 # max_frame_size: omitted when unenforced (max_ws_frame_size 0/undef
2000 # means unlimited, per Protocol::WebSocket::Frame's max_payload_size
2001 # semantics -- a server that does not enforce a cap must not
2002 # advertise one). max_receive_queue has no unlimited mode (a hard,
2003 # always-enforced cap), so it is always present.
2004 ($self->{max_ws_frame_size}
2005 ? (max_frame_size => $self->{max_ws_frame_size})
2006 : ()
2007 ),
2008 max_receive_queue => $self->{max_receive_queue},
2009 # Per-stream outbound flow-control handle. Like the h2 sse/streaming
2010 # scopes, it measures THIS stream's send queue (h2 multiplexes many
2011 # streams over one connection, so the shared TCP buffer is
2012 # meaningless per stream). Gives WebSocket-over-h2 the same
2013 # pagi.transport surface HTTP/1.1 WebSocket already provides.
2014 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
2015 };
2016 }
2017  
2018 53 ▶sub _h2_create_websocket_receive {
Subroutine _h2_create_websocket_receive: called CC=1 SCAR=0.0
2019 53 my ($self, $stream_id, $stream_state) = @_;
2020  
2021 53 weaken(my $weak_self = $self);
2022  
2023 # Fallback disconnect for a receive() that resolves after this stream is
2024 # gone or the connection is closed: 1006/'' by default (RFC 6455
2025 # abnormal closure, no reason available), but prefers the per-stream
2026 # server_close_reason token when the stream's own state is still
2027 # reachable in h2_streams -- a server-initiated teardown (idle timeout,
2028 # keepalive timeout, ...) records that token there before tearing the
2029 # stream down, so a receive() racing that teardown still reports why.
2030 11 ▶ my $fallback_disconnect = sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
2031 11 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition66%2/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
0110
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
2032 return {
2033 type => 'websocket.disconnect',
2034 code => 1006,
2035 11 ▶ reason => ($ss && $ss->{server_close_reason}) // '',
Condition100%5/5
$ss && $ss->{"server_close_reason"} // ""
l!l
110
$ss and $ss->{"server_close_reason"}
!ll&&!rl&&r
191
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
2036 };
2037 53 };
2038  
2039 105 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=14.1
2040 105 ▶ return Future->done($fallback_disconnect->())
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 105 105
2041 unless $weak_self;
2042 return Future->done($fallback_disconnect->())
2043 105 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 2 103 105
2044  
2045 103 my $ss = $weak_self->{h2_streams}{$stream_id};
2046 103 ▶ return Future->done($fallback_disconnect->())
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 103 103
2047 unless $ss;
2048  
2049 103 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=9 SCAR=22.5
2050 103 ▶ return $fallback_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 103 103
2051 unless $weak_self;
2052  
2053 103 my $ss = $weak_self->{h2_streams}{$stream_id};
2054 103 ▶ return $fallback_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 103 103
2055 unless $ss;
2056  
2057 # Check queue first
2058 103 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 103 103
2059 0 return shift @{$ss->{receive_queue}};
2060 }
2061  
2062 # First call returns websocket.connect
2063 103 ▶ if (!$ss->{ws_connect_sent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"ws_connect_sent"}) 47 56 103
2064 47 $ss->{ws_connect_sent} = 1;
2065 47 return { type => 'websocket.connect' };
2066 }
2067  
2068 # Wait for events
2069 56 while (1) {
2070 122 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 40 82 122
2071 40 return shift @{$ss->{receive_queue}};
2072 }
2073  
2074 return $fallback_disconnect->()
2075 82 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 9 73 82
2076  
2077 73 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 73 0 73
2078 73 $ss->{body_pending} = Future->new;
2079 }
2080 73 await $ss->{body_pending};
2081  
2082 66 $ss = $weak_self->{h2_streams}{$stream_id};
2083 66 ▶ return $fallback_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 66 66
2084 unless $ss;
2085 }
2086 103 })->();
2087  
2088 103 return $future;
2089 53 };
2090 }
2091  
2092 51 ▶sub _h2_create_websocket_send {
Subroutine _h2_create_websocket_send: called CC=1 SCAR=0.2
2093 51 my ($self, $stream_id, $stream_state) = @_;
2094  
2095 51 weaken(my $weak_self = $self);
2096 51 my $seq = 'connecting';
2097  
2098 # Data callback for nghttp2's streaming response (the same pull-based
2099 # data-provider model _h2_create_send/_h2_create_sse_send already use).
2100 # Pulls raw WS frame bytes from the per-stream queue -- app messages,
2101 # protocol replies (pong, close-echo), and this stream's own keepalive
2102 # ping are all pushed there in call order, so FIFO ordering on the wire
2103 # is preserved exactly as it was under direct submit_data calls.
2104 #
2105 # $ss->{ws_eof_pending} lives on the stream state (not a closure-local,
2106 # unlike the http streaming callback's $eof_pending) because it is set
2107 # from other subs entirely -- _h2_ws_close and the close-frame arm of
2108 # _h2_process_ws_frames -- not just from this closure. When set, it
2109 # merges END_STREAM onto the LAST queued chunk (the close frame itself)
2110 # rather than emitting a separate empty terminal frame, matching the
2111 # previous submit_data($id, $close_frame_bytes, 1) behavior exactly.
2112 183 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=17 SCAR=31.0
2113 183 my ($cb_stream_id, $max_len) = @_;
2114  
2115 183 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
00183
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
2116 183 ▶ return undef unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 183 183
2117 183 ▶ my $q = $ss->{send_queue} ||= [];
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
1830
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2118  
2119 183 ▶ if (@$q) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$q) 87 96 183
2120 87 my $chunk = shift @$q;
2121 # Respect max_len — XS truncates without preserving remainder
2122 87 ▶ if (length($chunk) > $max_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk > $max_len) 17 70 87
2123 17 unshift @$q, substr($chunk, $max_len);
2124 17 $chunk = substr($chunk, 0, $max_len);
2125 }
2126 87 $ss->{send_queue_bytes} -= length($chunk);
2127  
2128 # Per-stream backpressure: once this stream's queue falls below the
2129 # low watermark, release any producer blocked in
2130 # _h2_wait_for_stream_drain. This runs inside nghttp2's extract(), so
2131 # resolve on the next loop tick — completing the Future resumes the
2132 # awaiting producer synchronously, and it must not re-enter nghttp2.
2133 87 ▶ 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 87 87
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
8700
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
12750
$ss->{"send_queue_bytes"} // 0
l!l
870
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
2134 0 && $ss->{stream_drain_waiters} && @{$ss->{stream_drain_waiters}}) {
2135 0 my @waiters = splice @{$ss->{stream_drain_waiters}};
2136 0 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2137 0 $_->done for grep { !$_->is_ready } @waiters;
2138 0 });
2139 }
2140  
2141 # Fire the app's on_drain hysteresis callbacks once this stream's
2142 # queue falls below the low watermark. Deferred for the same reason:
2143 # an on_drain callback may call $send, which would re-enter nghttp2.
2144 87 ▶ 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"};}) 6 81 87
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
7836
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"}
!ll&&!rl&&r
12669
$ss->{"send_queue_bytes"} // 0
l!l
870
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
2145 9 && $ss->{transport_drain_fires} && @{$ss->{transport_drain_fires}}) {
2146 6 my @fires = splice @{$ss->{transport_drain_fires}};
2147 6 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2148 6 $_->() for @fires;
2149 6 });
2150 }
2151  
2152 87 ▶ my $eof = (!@$q && $ss->{ws_eof_pending}) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
!@$q && $ss->{'ws_eof_pending'} ? : 16 71 87
Condition100%3/3
not @$q and $ss->{"ws_eof_pending"}
!ll&&!rl&&r
175416
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
2153 87 return ($chunk, $eof);
2154 }
2155  
2156 # Queue empty but EOF pending (a close frame already delivered as
2157 # the terminal chunk above) — signal end of stream.
2158 96 ▶ return ('', 1) if $ss->{ws_eof_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_eof_pending"} 0 96 96
2159  
2160 # Queue empty, more data expected — defer (NGHTTP2_ERR_DEFERRED in C layer)
2161 96 return undef;
2162 51 };
2163  
2164 86 ▶ return async sub {
Subroutine __ANON__: called CC=47 SCAR=46.4
2165 86 my ($event) = @_;
2166 86 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 86 86
2167  
2168 86 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
860
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
2169  
2170 # Once the machine has recorded the connection closed or the denial
2171 # response complete, the machine decides what happens next -- both
2172 # 'closed' and 'denial_complete' have no idempotent case, so any
2173 # further send always raises -- not the stream-gone check below.
2174 # h2_streams entries for a finished stream are reclaimed
2175 # asynchronously by _h2_on_close (websocket.close itself triggers
2176 # this via END_STREAM, same mechanism as the h2 HTTP/SSE closures),
2177 # so by the time a post-close send arrives $ss may already be gone.
2178 86 ▶ 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
1184
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
2179  
2180 86 my $ss = $weak_self->{h2_streams}{$stream_id};
2181 # A doomed-but-still-present entry (h2_closed set but not yet
2182 # deleted -- see the 413-overrun branch in _h2_on_body) is treated
2183 # the same as an absent one: both are post-close sends and must
2184 # silently no-op, not reach nghttp2 a second time on this stream id.
2185 86 ▶ return if (!$ss || $ss->{h2_closed}) && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if !$ss || $ss->{"h2_closed"} and not $already_closed 0 86 86
Condition33%2/6
!$ss || $ss->{"h2_closed"} and not $already_closed
!ll&&!rl&&r
8600
not $ss or $ss->{"h2_closed"}
l!l&&r!l&&!r
0086
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
2186  
2187 86 ▶ return if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 0 86 86
Condition33%1/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
8600
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
2188  
2189 # websocket.http.response is always available on this path (the
2190 # scope advertises it unconditionally; see
2191 # _h2_create_websocket_scope), unlike connection-level extensions
2192 # such as fullflush.
2193 PAGI::Server::EventValidator::validate_websocket_send(
2194 86 $event, { extensions => { %{$weak_self->{extensions}}, 'websocket.http.response' => {} } });
2195 86 $seq = PAGI::Server::EventValidator::advance_websocket($seq, $event);
2196  
2197 84 ▶ if ($type eq 'websocket.accept') {
Branch: 6 branches
BranchTrueFalseTotal
if ($type eq 'websocket.accept') { } 42 42 84
elsif ($type eq 'websocket.send') { } 13 29 42
elsif ($type eq 'websocket.http.response.start') { } 5 24 29
elsif ($type eq 'websocket.http.response.body') { } 6 18 24
elsif ($type eq 'websocket.close') { } 7 11 18
elsif ($type eq 'websocket.keepalive') { } 11 0 11
2198 # A duplicate accept is already rejected by advance_websocket.
2199  
2200 # HTTP/2 WebSocket: respond with 200 (not 101)
2201 42 my @headers;
2202 42 ▶ if (my $subprotocol = $event->{subprotocol}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $subprotocol = $event->{"subprotocol"}) 0 42 42
2203 0 $subprotocol = _validate_subprotocol($subprotocol);
2204 0 push @headers, ['sec-websocket-protocol', $subprotocol];
2205 }
2206 42 ▶ if (my $extra = $event->{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $extra = $event->{"headers"}) 1 41 42
2207 push @headers, map {
2208 1 [_validate_header_name($_->[0]), _validate_header_value($_->[1])]
2209 } @$extra;
2210 }
2211 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2212 # transfer-encoding, etc. before submission.
2213 42 @headers = @{ $weak_self->_h2_strip_connection_headers(\@headers) };
2214  
2215 42 $ss->{ws_accepted} = 1;
2216 42 $ss->{response_started} = 1;
2217 $ss->{ws_frame} = Protocol::WebSocket::Frame->new(
2218 max_payload_size => $weak_self->{max_ws_frame_size},
2219 42 );
2220  
2221 # Submit 200 response with a pull-based data provider (same
2222 # model as h2 streaming/SSE): frames are pushed onto
2223 # $ss->{send_queue} and pulled by $data_callback as nghttp2's
2224 # per-stream flow-control window allows.
2225 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
2226 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
2227 42 $weak_self->{h2_session}->submit_response_streaming($stream_id,
2228 status => 200,
2229 headers => \@headers,
2230 data_callback => $data_callback,
2231 );
2232 42 $weak_self->_h2_write_pending;
2233  
2234 # Process any data that arrived before accept
2235 42 ▶ if (length($ss->{body}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $ss->{"body"} > 0) 0 42 42
2236 0 my $buffered = $ss->{body};
2237 0 $ss->{body} = '';
2238 0 $weak_self->_h2_process_ws_frames($stream_id, $ss, $buffered);
2239 }
2240 }
2241 elsif ($type eq 'websocket.send') {
2242 13 ▶ return unless $ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_accepted"} 0 13 13
2243  
2244 13 my $frame;
2245 13 ▶ if (defined $event->{text}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $event->{'text'}) { } 12 1 13
elsif (defined $event->{'bytes'}) { } 1 0 1
2246 $frame = Protocol::WebSocket::Frame->new(
2247 buffer => $event->{text},
2248 12 type => 'text',
2249 );
2250 }
2251 elsif (defined $event->{bytes}) {
2252 $frame = Protocol::WebSocket::Frame->new(
2253 buffer => $event->{bytes},
2254 1 type => 'binary',
2255 );
2256 }
2257 else {
2258 0 return;
2259 }
2260  
2261 13 my $bytes = $frame->to_bytes;
2262  
2263 # Per-stream backpressure: bound on THIS stream's queue, not the
2264 # shared TCP buffer (meaningless across multiplexed h2 streams).
2265 13 ▶ 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 13 13
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
130
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
2266 0 await $weak_self->_h2_wait_for_stream_drain($stream_id);
2267 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
2268 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
2269 # Refetch (same idiom as emit_chunk, :1374-1375): a stream
2270 # can close while this send was parked.
2271 0 $ss = $weak_self->{h2_streams}{$stream_id};
2272 0 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 0 0
2273 0 ▶ return if $ss->{h2_closed};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"h2_closed"} 0 0 0
2274 # This send can wake AFTER this stream's close frame was
2275 # already queued (window opened below the low watermark
2276 # while ws_eof_pending was set) -- pushing app data now would
2277 # land it BEHIND the close frame: Close would ship without
2278 # END_STREAM and a Text/Binary frame would follow it,
2279 # violating RFC 6455 5.5.1. Same post-close no-op contract
2280 # as the top-of-closure $already_closed check.
2281 0 ▶ return if $ss->{ws_eof_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_eof_pending"} 0 0 0
2282 }
2283  
2284 13 push @{$ss->{send_queue}}, $bytes;
2285 13 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
130
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
2286 # Synchronous — app send path, not nghttp2 extract — so on_high_water
2287 # may fire here to tell the app to pause its source.
2288 13 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 13 0 13
2289 13 $weak_self->{h2_session}->resume_stream($stream_id);
2290 13 $weak_self->_h2_write_pending;
2291 }
2292 elsif ($type eq 'websocket.http.response.start') {
2293 5 ▶ return if $ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_accepted"} 0 5 5
2294 5 ▶ return if $ss->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_denial_started"} 0 5 5
2295 5 $ss->{ws_denial_started} = 1;
2296 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
2297 $ss->{ws_denial_headers} = [
2298 7 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
2299 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
2300 ];
2301 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2302 # transfer-encoding, etc. before submission.
2303 5 $ss->{ws_denial_headers} = $weak_self->_h2_strip_connection_headers($ss->{ws_denial_headers});
2304 5 $ss->{ws_denial_body} = '';
2305 }
2306 elsif ($type eq 'websocket.http.response.body') {
2307 6 ▶ return unless $ss->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_denial_started"} 0 6 6
2308 6 ▶ return if $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"response_started"} 0 6 6
2309 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
2310 6 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 1 5 6
2311  
2312 5 $ss->{response_started} = 1;
2313 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
2314 5 push @{$ss->{ws_denial_headers}}, ['date', $weak_self->{protocol}->format_date];
2315 }
2316 $weak_self->{h2_session}->submit_response($stream_id,
2317 status => $ss->{ws_denial_status},
2318 headers => $ss->{ws_denial_headers},
2319 body => $ss->{ws_denial_body},
2320 5 );
2321 5 $weak_self->_h2_write_pending;
2322 }
2323 elsif ($type eq 'websocket.close') {
2324 7 ▶ if (!$ss->{ws_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"ws_accepted"}) 3 4 7
2325 # Reject: send 403
2326 $weak_self->{h2_session}->submit_response($stream_id,
2327 status => 403,
2328 headers => [
2329 ['content-type', 'text/plain'],
2330 3 ['date', $weak_self->{protocol}->format_date],
2331 ],
2332 body => 'Forbidden',
2333 );
2334 3 $weak_self->_h2_write_pending;
2335 3 return;
2336 }
2337  
2338 # Close frame + END_STREAM, and release this stream's keepalive
2339 # (_h2_ws_close does both). Runs outside feed(), so flush here.
2340 $weak_self->_h2_ws_close($stream_id,
2341 4 ▶ $event->{code} // 1000, $event->{reason} // '');
Condition100%4/4
$event->{"code"} // 1000
l!l
31
$event->{"reason"} // ""
l!l
31
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
2342 4 $weak_self->_h2_write_pending;
2343 }
2344 elsif ($type eq 'websocket.keepalive') {
2345 11 ▶ return unless $ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_accepted"} 0 11 11
2346  
2347 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
2348 11 my $timeout = $event->{timeout};
2349  
2350 11 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 10 1 11
2351 10 $weak_self->_h2_start_ws_keepalive($stream_id, $ss, $interval, $timeout);
2352 }
2353 else {
2354 1 $weak_self->_h2_stop_ws_keepalive($ss);
2355 }
2356 }
2357  
2358 69 return;
2359 51 };
2360 }
2361  
2362 # =============================================================================
2363 # HTTP/2 SSE (Server-Sent Events over HTTP/2)
2364 # =============================================================================
2365  
2366 43 ▶sub _h2_create_sse_scope {
Subroutine _h2_create_sse_scope: called CC=8 SCAR=23.9
2367 43 my ($self, $stream_id, $stream_state) = @_;
2368  
2369 43 my $pseudo = $stream_state->{pseudo};
2370 43 my $headers = $stream_state->{headers};
2371  
2372 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
2373 43 my ($path, $query_string) = split(/\?/, $full_path, 2);
2374 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
2375  
2376 # Match HTTP/1.1 pipeline: URI::Escape + UTF-8 decode with fallback
2377 43 my $unescaped = uri_unescape($path);
2378 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
2379 // $unescaped;
2380  
2381 return {
2382 type => 'sse',
2383 pagi => {
2384 version => '0.5',
2385 spec_version => '0.5',
2386 },
2387 http_version => '2',
2388 method => $pseudo->{':method'} // 'GET',
2389 scheme => $pseudo->{':scheme'} // $self->_get_scheme,
2390 path => $decoded_path,
2391 raw_path => $path,
2392 query_string => $query_string,
2393 root_path => '',
2394 headers => $headers,
2395 (defined $self->{client_host}
2396 ? (client => [$self->{client_host}, $self->{client_port}])
2397 : ()
2398 ),
2399 server => [$self->{server_host}, $self->{server_port}],
2400 0 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
2401 extensions => $self->_get_extensions_for_scope,
2402 # Per-stream outbound flow-control handle. Like the h2 streaming scope,
2403 # it measures THIS stream's send queue (h2 multiplexes many streams over
2404 # one connection, so the shared TCP buffer is meaningless per stream).
2405 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
2406 };
2407 }
2408  
2409 42 ▶sub _h2_create_sse_receive {
Subroutine _h2_create_sse_receive: called CC=1 SCAR=0.1
2410 42 my ($self, $stream_id, $stream_state) = @_;
2411  
2412 42 weaken(my $weak_self = $self);
2413  
2414 3 ▶ my $sse_disconnect = sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
2415 return {
2416 3 type => 'sse.disconnect',
2417 reason => 'client_closed',
2418 };
2419 42 };
2420  
2421 32 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=14.2
2422 32 ▶ return Future->done($sse_disconnect->()) unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 32 32
2423 32 ▶ return Future->done($sse_disconnect->()) if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 32 32
2424  
2425 32 my $ss = $weak_self->{h2_streams}{$stream_id};
2426 32 ▶ return Future->done($sse_disconnect->()) unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 32 32
2427  
2428 32 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=15 SCAR=28.2
2429 32 ▶ return $sse_disconnect->() unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 32 32
2430  
2431 32 my $ss = $weak_self->{h2_streams}{$stream_id};
2432 32 ▶ return $sse_disconnect->() unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 32 32
2433  
2434 # Check queue first
2435 32 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 32 32
2436 0 return shift @{$ss->{receive_queue}};
2437 }
2438  
2439 # First call returns sse.request once the full body has arrived.
2440 # A POST body still streaming across DATA frames must not be
2441 # truncated behind a truthful more=>0 -- wait for body_complete
2442 # (set on END_STREAM or stream close, see _h2_on_body/_h2_on_close)
2443 # before delivering it as a single terminal event. This is the
2444 # smaller change relative to reworking sse.request into a
2445 # truthful multi-chunk stream: the wire shape here was already
2446 # one-shot, so completing that contract fixes the dispatch-timing
2447 # bug (design section 11.1) without touching the event shape.
2448 32 ▶ if (!$ss->{sse_request_sent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"sse_request_sent"}) 27 5 32
2449 27 ▶ while (!$ss->{body_complete}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_complete"}) 4 27 31
2450 4 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 0 4 4
2451 0 return shift @{$ss->{receive_queue}};
2452 }
2453  
2454 4 ▶ return $sse_disconnect->() if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 4 4
2455  
2456 4 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 4 0 4
2457 4 $ss->{body_pending} = Future->new;
2458 }
2459 4 await $ss->{body_pending};
2460  
2461 4 $ss = $weak_self->{h2_streams}{$stream_id};
2462 4 ▶ return $sse_disconnect->() unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 4 4
2463 }
2464  
2465 # body_complete can flip true on the very wake that also
2466 # queued a terminal event -- e.g. _h2_on_close sets
2467 # body_complete AND pushes sse.disconnect before waking
2468 # body_pending. That queued event must win over delivering
2469 # a (possibly truncated) body: the loop's own queue check
2470 # only runs at the top of an iteration, so a queue entry
2471 # that arrives on the wake that also satisfies the while
2472 # condition is never seen there.
2473 27 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 2 25 27
2474 2 return shift @{$ss->{receive_queue}};
2475 }
2476  
2477 25 $ss->{sse_request_sent} = 1;
2478 return {
2479 type => 'sse.request',
2480 body => $ss->{body},
2481 25 more => 0,
2482 };
2483 }
2484  
2485 # Wait for disconnect
2486 5 while (1) {
2487 10 ▶ if (@{$ss->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$ss->{"receive_queue"};}) 2 8 10
2488 2 return shift @{$ss->{receive_queue}};
2489 }
2490  
2491 return $sse_disconnect->()
2492 8 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 3 5 8
2493  
2494 5 ▶ if (!$ss->{body_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ss->{"body_pending"}) 5 0 5
2495 5 $ss->{body_pending} = Future->new;
2496 }
2497 5 await $ss->{body_pending};
2498  
2499 5 $ss = $weak_self->{h2_streams}{$stream_id};
2500 5 ▶ return $sse_disconnect->() unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 5 5
2501 }
2502 32 })->();
2503  
2504 32 return $future;
2505 42 };
2506 }
2507  
2508 42 ▶sub _h2_create_sse_send {
Subroutine _h2_create_sse_send: called CC=1 SCAR=0.1
2509 42 my ($self, $stream_id, $stream_state) = @_;
2510  
2511 42 weaken(my $weak_self = $self);
2512 42 my $seq = 'initial';
2513  
2514 # Streaming state for the data-provider pull pattern. The send queue lives on
2515 # per-stream state ($ss->{send_queue} / $ss->{send_queue_bytes}) so the
2516 # pagi.transport handle can measure THIS stream's backlog. $streaming_started
2517 # stays closure-local.
2518 42 my $streaming_started = 0;
2519  
2520 # Data callback for nghttp2's streaming response. Pulls from the per-stream
2521 # queue; SSE responses stay open, so this never signals EOF (returns eof=0),
2522 # or undef to defer when the queue is empty.
2523 161 ▶ my $data_callback = sub {
Subroutine __ANON__: called CC=15 SCAR=30.1
2524 161 my ($cb_stream_id, $max_len) = @_;
2525  
2526 161 ▶ my $ss = $weak_self && $weak_self->{h2_streams}{$stream_id};
Condition33%1/3
$weak_self && $weak_self->{'h2_streams'}{$stream_id}
!ll&&!rl&&r
00161
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
2527 161 ▶ return undef unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 161 161
2528 161 ▶ my $q = $ss->{send_queue} ||= [];
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
1610
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2529  
2530 161 ▶ if (@$q) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$q) 64 97 161
2531 64 my $chunk = shift @$q;
2532 # Respect max_len — XS truncates without preserving remainder
2533 64 ▶ if (length($chunk) > $max_len) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $chunk > $max_len) 4 60 64
2534 4 unshift @$q, substr($chunk, $max_len);
2535 4 $chunk = substr($chunk, 0, $max_len);
2536 }
2537 64 $ss->{send_queue_bytes} -= length($chunk);
2538  
2539 # Per-stream backpressure: once this stream's queue falls below the
2540 # low watermark, release any producer blocked in
2541 # _h2_wait_for_stream_drain. This runs inside nghttp2's extract(), so
2542 # resolve on the next loop tick — completing the Future resumes the
2543 # awaiting producer synchronously, and it must not re-enter nghttp2.
2544 64 ▶ 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 64 64
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
6400
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
3610
$ss->{"send_queue_bytes"} // 0
l!l
640
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
2545 0 && $ss->{stream_drain_waiters} && @{$ss->{stream_drain_waiters}}) {
2546 0 my @waiters = splice @{$ss->{stream_drain_waiters}};
2547 0 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
2548 0 $_->done for grep { !$_->is_ready } @waiters;
2549 0 });
2550 }
2551  
2552 # Fire the app's on_drain hysteresis callbacks once this stream's
2553 # queue falls below the low watermark. Deferred for the same reason:
2554 # an on_drain callback may call $send, which would re-enter nghttp2.
2555 64 ▶ 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 63 64
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
6301
($ss->{"send_queue_bytes"} // 0) < $weak_self->{"write_low_watermark"} and $ss->{"transport_drain_fires"}
!ll&&!rl&&r
3601
$ss->{"send_queue_bytes"} // 0
l!l
640
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
2556 1 && $ss->{transport_drain_fires} && @{$ss->{transport_drain_fires}}) {
2557 1 my @fires = splice @{$ss->{transport_drain_fires}};
2558 1 ▶ $weak_self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
2559 1 $_->() for @fires;
2560 1 });
2561 }
2562  
2563 64 return ($chunk, 0); # SSE streams never EOF via data_callback
2564 }
2565  
2566 # Queue empty. If the application closed this stream (sse.close), emit a
2567 # final empty DATA frame with END_STREAM to terminate it; otherwise defer.
2568 97 ▶ return ('', 1) if $ss->{sse_closing};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_closing"} 7 90 97
2569  
2570 # Queue empty — defer (NGHTTP2_ERR_DEFERRED in the C layer)
2571 90 return undef;
2572 42 };
2573  
2574 114 ▶ return async sub {
Subroutine __ANON__: called CC=57 SCAR=44.5
2575 114 my ($event) = @_;
2576 114 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 114 114
2577  
2578 114 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
1140
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
2579  
2580 # Once the machine has already recorded this stream as closed --
2581 # either an app-initiated sse.close or a completed decline response
2582 # -- the machine, not the stream-gone check below, decides what
2583 # happens next: idempotent no-op for a repeat sse.close, croak for
2584 # anything else (decline_complete has no idempotent case; it croaks
2585 # unconditionally). h2_streams entries for a closed stream are
2586 # reclaimed asynchronously by _h2_on_close, so by the time a
2587 # post-close send arrives $ss may already be gone.
2588 114 ▶ 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
21111
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
2589  
2590 114 my $ss = $weak_self->{h2_streams}{$stream_id};
2591 # A doomed-but-still-present entry (h2_closed set but not yet
2592 # deleted -- see the 413-overrun branch in _h2_on_body) is treated
2593 # the same as an absent one: both are post-close sends and must
2594 # silently no-op, not reach nghttp2 a second time on this stream id.
2595 114 ▶ return if (!$ss || $ss->{h2_closed}) && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if !$ss || $ss->{"h2_closed"} and not $already_closed 1 113 114
Condition83%5/6
!$ss || $ss->{"h2_closed"} and not $already_closed
!ll&&!rl&&r
11031
not $ss or $ss->{"h2_closed"}
l!l&&r!l&&!r
04110
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
2596  
2597 113 ▶ return if $weak_self->{closed} && !$already_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} and not $already_closed 0 113 113
Condition33%1/3
$weak_self->{"closed"} and not $already_closed
!ll&&!rl&&r
11300
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
2598  
2599 # Reset THIS stream's SSE idle timer on send activity (skip once fully closed)
2600 113 ▶ $weak_self->_h2_reset_sse_idle_timer($ss) unless $already_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $already_closed 110 3 113
2601  
2602 # Mandatory event validation and sequencing (PAGI spec compliance).
2603 PAGI::Server::EventValidator::validate_sse_send(
2604 113 $event, { extensions => $weak_self->{extensions} });
2605 113 $seq = PAGI::Server::EventValidator::advance_sse($seq, $event);
2606  
2607 108 ▶ if ($type eq 'sse.start') {
Branch: 8 branches
BranchTrueFalseTotal
if ($type eq 'sse.start') { } 29 79 108
elsif ($type eq 'sse.send') { } 42 37 79
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
2608 29 ▶ return if $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"response_started"} 0 29 29
2609 29 $ss->{response_started} = 1;
2610  
2611 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
2612 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
2613  
2614 # Ensure Content-Type is text/event-stream
2615 29 my $has_content_type = 0;
2616 29 for my $h (@$headers) {
2617 4 ▶ if (lc($h->[0]) eq 'content-type') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-type") 1 3 4
2618 1 $has_content_type = 1;
2619 1 last;
2620 }
2621 }
2622  
2623 29 my @final_headers;
2624 29 for my $h (@$headers) {
2625 6 push @final_headers, [_validate_header_name($h->[0]), _validate_header_value($h->[1])];
2626 }
2627 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2628 # transfer-encoding, etc. before submission.
2629 29 @final_headers = @{ $weak_self->_h2_strip_connection_headers(\@final_headers) };
2630 29 ▶ if (!$has_content_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_type) 28 1 29
2631 28 push @final_headers, ['content-type', 'text/event-stream'];
2632 }
2633 # Cache-Control and Date: server-supplied only when the app didn't
2634 # supply them (design doc section 11.4).
2635 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
2636 28 push @final_headers, ['cache-control', 'no-cache'];
2637 }
2638 # Server-supplied Date header (HTTP/1.1 parity) — the h1 SSE path adds
2639 # this too; add it unless the app supplied one.
2640 29 ▶ unless (grep { lc($_->[0]) eq 'date' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @final_headers) 28 1 29
2641 28 push @final_headers, ['date', $weak_self->{protocol}->format_date];
2642 }
2643  
2644 29 $streaming_started = 1;
2645 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
2646 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
2647 $weak_self->{h2_session}->submit_response_streaming(
2648 29 $stream_id,
2649 status => $status,
2650 headers => \@final_headers,
2651 data_callback => $data_callback,
2652 );
2653 29 $weak_self->_h2_write_pending;
2654  
2655 # Protocol-specific keepalive writer (HTTP/2 DATA frames), scoped to
2656 # THIS stream (design section 11.3): a second multiplexed SSE stream
2657 # must not steal or replace this one's writer. Keepalive bytes are
2658 # counted in the per-stream backlog so buffered_amount stays
2659 # accurate, but they do not poke the watermark callbacks — a server
2660 # heartbeat is not an application send.
2661 18 ▶ $ss->{sse_ka_writer} = sub {
Subroutine __ANON__: called CC=7 SCAR=20.5
2662 18 my ($text) = @_;
2663 18 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 18 18
2664 18 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 18 18
2665 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 18 0 18
2666 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at
2667 # the wire boundary — all queue-length math below is on the
2668 # resulting BYTE string.
2669 18 my $bytes = eval { Encode::encode('UTF-8', $text, Encode::FB_CROAK) };
2670 18 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 18 18
2671 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
2672 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
2673 18 $weak_self->{h2_session}->resume_stream($stream_id);
2674 18 $weak_self->_h2_write_pending;
2675 28 };
2676  
2677 # Start THIS stream's SSE idle timer if configured
2678 28 $weak_self->_h2_start_sse_idle_timer($stream_id, $ss);
2679 }
2680 elsif ($type eq 'sse.send') {
2681 42 ▶ return unless $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"response_started"} 0 42 42
2682  
2683 # Per-stream backpressure: bound on THIS stream's queue, not the
2684 # shared TCP buffer (meaningless across multiplexed h2 streams).
2685 42 ▶ 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 42 42
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
2686 0 await $weak_self->_h2_wait_for_stream_drain($stream_id);
2687 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
2688 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
2689 0 ▶ return unless $weak_self->{h2_streams}{$stream_id};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"h2_streams"}{$stream_id} 0 0 0
2690 }
2691  
2692 42 my $sse_data = _format_sse_event($event);
2693 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at the
2694 # wire boundary — a failed encode fails this send's Future.
2695 42 my $bytes = eval { Encode::encode('UTF-8', $sse_data, Encode::FB_CROAK) };
2696 42 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 1 41 42
2697 41 ▶ push @{$ss->{send_queue} ||= []}, $bytes;
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
410
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
2698 41 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
410
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
2699 # Synchronous — app send path, not nghttp2 extract — so on_high_water
2700 # may fire here to tell the app to pause its source.
2701 41 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 41 0 41
2702 41 $weak_self->{h2_session}->resume_stream($stream_id);
2703 41 $weak_self->_h2_write_pending;
2704 }
2705 elsif ($type eq 'sse.comment') {
2706 2 ▶ return unless $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"response_started"} 0 2 2
2707  
2708 2 my $comment = _format_sse_comment($event);
2709 2 my $bytes = eval { Encode::encode('UTF-8', $comment, Encode::FB_CROAK) };
2710 2 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 2 2
2711 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
2712 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
2713 2 ▶ $ss->{transport_state}->_check_watermarks if $ss->{transport_state};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"transport_state"} 2 0 2
2714 2 $weak_self->{h2_session}->resume_stream($stream_id);
2715 2 $weak_self->_h2_write_pending;
2716 }
2717 elsif ($type eq 'sse.keepalive') {
2718 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
2719 6 my $comment = $event->{comment};
2720  
2721 6 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 6 0 6
2722 6 $weak_self->_h2_start_sse_keepalive($stream_id, $ss, $interval, $comment);
2723 }
2724 else {
2725 0 $weak_self->_h2_stop_sse_keepalive($ss);
2726 }
2727 }
2728 elsif ($type eq 'sse.close') {
2729 # A repeat sse.close after the stream's h2_streams entry has
2730 # already been reclaimed (see the already-closed comment above)
2731 # is the idempotent no-op advance_sse just allowed; nothing left
2732 # to do.
2733 5 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 5 5
2734  
2735 # This stream is ending -- stop its keepalive and idle timers so
2736 # neither fires (or leaks) after the stream is reclaimed.
2737 5 $weak_self->_h2_stop_sse_keepalive($ss);
2738 5 $weak_self->_h2_stop_sse_idle_timer($ss);
2739  
2740 # End THIS HTTP/2 stream now: flush remaining queued events, then the
2741 # data_callback emits a final END_STREAM frame. `reason` is
2742 # server-side only and is never written to the wire.
2743 5 $ss->{sse_close_sent} = 1;
2744 5 $ss->{sse_closing} = 1;
2745 $weak_self->{sse_disconnect_reason} = $event->{reason}
2746 5 ▶ if defined $event->{reason};
Branch: 1 branch
BranchTrueFalseTotal
if defined $event->{"reason"} 1 4 5
2747 5 $weak_self->{h2_session}->resume_stream($stream_id);
2748 5 $weak_self->_h2_write_pending;
2749 }
2750 elsif ($type eq 'sse.http.response.start') {
2751 # A decline-after-start attempt is already rejected by advance_sse.
2752 11 ▶ return if $ss->{sse_decline_started}; # idempotent
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_decline_started"} 0 11 11
2753 11 $ss->{sse_decline_started} = 1;
2754 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
2755 $ss->{sse_decline_headers} = [
2756 7 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
2757 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
2758 ];
2759 # RFC 9113 8.2.2 / design 13.3 — strip app-supplied connection,
2760 # transfer-encoding, etc. before submission.
2761 11 $ss->{sse_decline_headers} = $weak_self->_h2_strip_connection_headers($ss->{sse_decline_headers});
2762 11 $ss->{sse_decline_body} = '';
2763 }
2764 elsif ($type eq 'sse.http.response.body') {
2765 12 ▶ return unless $ss->{sse_decline_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"sse_decline_started"} 0 12 12
2766 12 ▶ return if $ss->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"response_started"} 0 12 12
2767 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
2768 12 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 1 11 12
2769  
2770 # Defensive: the send-sequence state machine never permits
2771 # sse.keepalive before sse.start, so neither timer can actually be
2772 # armed here -- stopped anyway for the same every-closure-path
2773 # discipline the other SSE/WS stop sites follow.
2774 11 $weak_self->_h2_stop_sse_keepalive($ss);
2775 11 $weak_self->_h2_stop_sse_idle_timer($ss);
2776  
2777 11 $ss->{response_started} = 1;
2778 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
2779 11 push @{$ss->{sse_decline_headers}}, ['date', $weak_self->{protocol}->format_date];
2780 }
2781 $weak_self->{h2_session}->submit_response($stream_id,
2782 status => $ss->{sse_decline_status},
2783 headers => $ss->{sse_decline_headers},
2784 body => $ss->{sse_decline_body},
2785 11 );
2786 11 $weak_self->_h2_write_pending;
2787 }
2788 elsif ($type eq 'http.fullflush') {
2789 # Hand any pending frames to the session's write path (design §8.4).
2790 1 ▶ $weak_self->{h2_session}->resume_stream($stream_id) if $streaming_started;
Branch: 1 branch
BranchTrueFalseTotal
if $streaming_started 1 0 1
2791 1 $weak_self->_h2_write_pending;
2792 }
2793  
2794 105 return;
2795 42 };
2796 }
2797  
2798 55 ▶sub _h2_process_ws_frames {
Subroutine _h2_process_ws_frames: called CC=40 SCAR=38.0
2799 55 my ($self, $stream_id, $stream, $data) = @_;
2800  
2801 55 my $frame = $stream->{ws_frame};
2802 55 ▶ return unless $frame;
Branch: 1 branch
BranchTrueFalseTotal
unless $frame 0 55 55
2803  
2804 55 $frame->append($data);
2805  
2806 55 ▶ while (defined(my $bytes = $frame->next_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $bytes = $frame->next_bytes)) 49 40 89
2807 49 my $opcode = $frame->opcode;
2808  
2809 # RFC 6455 Section 5.2: RSV1-3 MUST be 0 unless extension defines
2810 # meaning. PAGI doesn't support compression extensions, so RSV must
2811 # always be 0. Same enforcement as h1's _process_websocket_frames
2812 # (Www.pod: transport-agnostic framing enforcement, and RFC 8441's
2813 # "identical to HTTP/1.1" claim).
2814 49 my $rsv = $frame->rsv;
2815 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
2816 49 ▶ if (grep { $_ } @$rsv) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_;} @$rsv) 1 48 49
2817 1 $self->_h2_ws_close($stream_id, 1002, 'RSV bits must be 0');
2818 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2819 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2820 1 return;
2821 }
2822 }
2823  
2824 # RFC 6455 Section 5.2: Opcodes 3-7 and 11-15 (0xB-0xF) are reserved.
2825 # Must fail connection with 1002 Protocol Error.
2826 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/DC50%2/4
$opcode >= 3 and $opcode <= 7 or $opcode >= 11 and $opcode <= 15
$opcode >= 3 $opcode <= 7 $opcode >= 11 $opcode <= 15
Truth table42%3/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
2827 1 $self->_h2_ws_close($stream_id, 1002, 'Reserved opcode');
2828 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2829 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2830 1 return;
2831 }
2832  
2833 # RFC 6455 Section 5.5: Control frames (close/ping/pong) MUST have
2834 # payload length <= 125 bytes.
2835 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
2836 1 $self->_h2_ws_close($stream_id, 1002, 'Control frame too large');
2837 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2838 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2839 1 return;
2840 }
2841  
2842 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
2843 # Text frame
2844 33 my $text = eval { Encode::decode('UTF-8', $bytes, Encode::FB_CROAK) };
2845 33 ▶ unless (defined $text) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $text) 2 31 33
2846 2 $self->_h2_ws_close($stream_id, 1007, 'Invalid UTF-8');
2847 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2848 2 $self->_h2_ws_enqueue_disconnect($stream, 1007, 'protocol_error');
2849 2 return;
2850 }
2851 # Check queue limit before adding (DoS protection) -- same cap
2852 # and pairing h1 enforces (Www.pod pins 1008 <-> queue_overflow).
2853 31 ▶ if (@{$stream->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stream->{"receive_queue"};} >= $self->{"max_receive_queue"}) 7 24 31
2854 7 $self->_h2_ws_close($stream_id, 1008, 'Message queue overflow');
2855 7 $self->_h2_ws_enqueue_disconnect($stream, 1008, 'queue_overflow');
2856 7 return;
2857 }
2858 24 push @{$stream->{receive_queue}}, {
2859 type => 'websocket.receive',
2860 text => $text,
2861 };
2862 }
2863 elsif ($opcode == 2) {
2864 # Binary frame
2865 # Check queue limit before adding (DoS protection) -- same cap
2866 # and pairing h1 enforces (Www.pod pins 1008 <-> queue_overflow).
2867 1 ▶ if (@{$stream->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$stream->{"receive_queue"};} >= $self->{"max_receive_queue"}) 0 1 1
2868 0 $self->_h2_ws_close($stream_id, 1008, 'Message queue overflow');
2869 0 $self->_h2_ws_enqueue_disconnect($stream, 1008, 'queue_overflow');
2870 0 return;
2871 }
2872 1 push @{$stream->{receive_queue}}, {
2873 type => 'websocket.receive',
2874 bytes => $bytes,
2875 };
2876 }
2877 elsif ($opcode == 8) {
2878 # Close frame -- the WS session on this stream is ending, one way
2879 # or another (a validation failure below closes it too), so stop
2880 # this stream's keepalive up front.
2881 6 $self->_h2_stop_ws_keepalive($stream);
2882  
2883 6 my ($code, $reason) = (1005, '');
2884  
2885 # RFC 6455 Section 5.5.1: Close frame payload is 0 or >=2 bytes
2886 6 ▶ if (length($bytes) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes == 1) 1 5 6
2887 1 $self->_h2_ws_close($stream_id, 1002, 'Invalid close frame');
2888 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2889 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2890 1 return;
2891 }
2892  
2893 5 ▶ if (length($bytes) >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes >= 2) 4 1 5
2894 4 $code = unpack('n', substr($bytes, 0, 2));
2895 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
2896  
2897 # RFC 6455 Section 7.4.1: Validate close code
2898 4 my $valid_code = 0;
2899 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
2900 2 $valid_code = 1;
2901 }
2902 ▶ 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
2903 0 $valid_code = 1;
2904 }
2905 ▶ 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
2906 1 $valid_code = 1;
2907 }
2908 4 ▶ unless ($valid_code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid_code) 1 3 4
2909 1 $self->_h2_ws_close($stream_id, 1002, 'Invalid close code');
2910 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2911 1 $self->_h2_ws_enqueue_disconnect($stream, 1002, 'protocol_error');
2912 1 return;
2913 }
2914  
2915 # RFC 6455: Close reason must be valid UTF-8
2916 3 ▶ if (length($reason) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $reason > 0) 3 0 3
2917 3 my $reason_copy = $reason;
2918 3 my $decoded = eval { Encode::decode('UTF-8', $reason_copy, Encode::FB_CROAK) };
2919 3 ▶ unless (defined $decoded) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $decoded) 1 2 3
2920 1 $self->_h2_ws_close($stream_id, 1007, 'Invalid UTF-8 in close reason');
2921 # Server-initiated protocol close (Www.pod: RFC code + 'protocol_error').
2922 1 $self->_h2_ws_enqueue_disconnect($stream, 1007, 'protocol_error');
2923 1 return;
2924 }
2925 }
2926 }
2927  
2928 # Send close frame back + END_STREAM. Queued (not submit_data)
2929 # so the data_callback's own eof_pending merge puts END_STREAM on
2930 # this exact chunk, same as the previous submit_data(..., 1) did.
2931 # Not an application send — no transport_state->_check_watermarks.
2932 3 my $close_frame = Protocol::WebSocket::Frame->new(
2933 type => 'close',
2934 buffer => pack('n', $code) . $reason,
2935 );
2936 3 my $close_bytes = $close_frame->to_bytes;
2937 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
2938 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
2939 3 $stream->{ws_eof_pending} = 1;
2940 3 $self->{h2_session}->resume_stream($stream_id);
2941 # No _h2_write_pending — inside feed(); flushed by _h2_process_data
2942  
2943 # Peer's Close frame: its own code (1005 default when the frame
2944 # carried none) and reason text (Www.pod "Disconnect - receive event").
2945 3 $self->_h2_ws_enqueue_disconnect($stream, $code, $reason);
2946 }
2947 elsif ($opcode == 9) {
2948 # Ping — respond with pong. Queued, not an application send.
2949 1 my $pong = Protocol::WebSocket::Frame->new(
2950 type => 'pong',
2951 buffer => $bytes,
2952 );
2953 1 my $pong_bytes = $pong->to_bytes;
2954 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
2955 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
2956 1 $self->{h2_session}->resume_stream($stream_id);
2957 # No _h2_write_pending — inside feed(); flushed by _h2_process_data
2958 }
2959 elsif ($opcode == 10) {
2960 # Pong — clear this stream's keepalive wait flag (response to
2961 # our own ping); cancel only the per-stream pong-timeout
2962 # Countdown, not the periodic ping timer itself.
2963 5 $self->_h2_cancel_ws_pong_timeout($stream);
2964 }
2965 }
2966  
2967 40 $self->_h2_wake_pending($stream);
2968 }
2969  
2970 # Send a Close frame with END_STREAM on one h2 WebSocket stream. The WS
2971 # session on that stream is over once this returns, so this is also where
2972 # the stream's keepalive is released -- every closure path funnels through
2973 # here, and releasing it at the funnel is what keeps a ping timer from
2974 # outliving its stream (it would otherwise keep pinging a half-closed
2975 # stream for the life of the connection).
2976 #
2977 # Callers inside feed() need no flush (_h2_process_data flushes after
2978 # feed() returns); callers outside it must call _h2_write_pending
2979 # themselves.
2980 19 ▶sub _h2_ws_close {
Subroutine _h2_ws_close: called CC=6 SCAR=18.3
2981 19 my ($self, $stream_id, $code, $reason) = @_;
2982  
2983 19 my $ss = $self->{h2_streams}{$stream_id};
2984 19 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 19 19
2985  
2986 # Idempotency guard: a stream already closing (a Close frame already
2987 # queued, ws_eof_pending true) must not queue a second one. Without
2988 # this, a burst of several frames that each independently warrant
2989 # closure -- e.g. more inbound messages than max_receive_queue allows,
2990 # already buffered in the parser before the first violation's `return`
2991 # unwinds -- re-enters this sub once per remaining buffered frame (each
2992 # later call to _h2_process_ws_frames resumes parsing where the last
2993 # one left off) and would otherwise queue one Close frame per frame
2994 # instead of the one the wire is supposed to see.
2995 19 ▶ return if $ss->{ws_eof_pending};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_eof_pending"} 6 13 19
2996  
2997 13 $self->_h2_stop_ws_keepalive($ss);
2998  
2999 # Queued (not submit_data) so the data_callback's own eof_pending merge
3000 # puts END_STREAM on this exact chunk, same as the previous
3001 # submit_data(..., 1) did.
3002 13 ▶ my $frame = Protocol::WebSocket::Frame->new(
Condition50%1/2
$reason // ""
l!l
130
MC/DC0%0/1
$reason // ""
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
3003 type => 'close',
3004 buffer => pack('n', $code) . ($reason // ''),
3005 );
3006 13 my $bytes = $frame->to_bytes;
3007 13 ▶ push @{$ss->{send_queue} ||= []}, $bytes;
Condition50%1/2
$ss->{"send_queue"} ||= []
l!l
130
MC/DC0%0/1
$ss->{"send_queue"} ||= []
$ss->{"send_queue"}
Truth table50%1/2
A
A= $ss->{"send_queue"}
Aresult
11
00
3008 13 ▶ $ss->{send_queue_bytes} = ($ss->{send_queue_bytes} // 0) + length $bytes;
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
130
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
3009 13 $ss->{ws_eof_pending} = 1;
3010 13 $self->{h2_session}->resume_stream($stream_id);
3011 }
3012  
3013 # HTTP/2 per-stream WebSocket keepalive (design section 10.2 -- the h2
3014 # analogue of _start_ws_keepalive/_stop_ws_keepalive). h1 shares one TCP
3015 # stream per connection, so its keepalive state and timers live on $self;
3016 # h2 multiplexes many WebSocket streams per connection, so this state and
3017 # these timers live on the per-stream hash ($ss, aka $self->{h2_streams}
3018 # {$stream_id}) and the ping is delivered as an h2 DATA frame via the
3019 # stream's own send queue + data-provider callback, same as every other
3020 # ws frame on this stream, rather than a raw stream write.
3021 10 ▶sub _h2_start_ws_keepalive {
Subroutine _h2_start_ws_keepalive: called CC=5 SCAR=16.5
3022 10 my ($self, $stream_id, $ss, $interval, $timeout) = @_;
3023  
3024 # Last event wins: stop whatever was running before applying new settings.
3025 10 $self->_h2_stop_ws_keepalive($ss);
3026  
3027 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
3028 10 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 10 10
3029  
3030 10 $ss->{ws_ka_interval} = $interval;
3031 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
3032  
3033 10 weaken(my $weak_self = $self);
3034 10 weaken(my $weak_ss = $ss);
3035  
3036 my $timer = IO::Async::Timer::Periodic->new(
3037 interval => $interval,
3038 40 ▶ on_tick => sub {
Subroutine __ANON__: called CC=8 SCAR=21.6
3039 40 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 40 40
3040 40 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 40 40
3041 40 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 40 40
3042 40 ▶ return unless $weak_ss->{ws_accepted};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss->{"ws_accepted"} 0 40 40
3043  
3044 # Queued, not an application send (no transport_state watermark
3045 # poke) -- this timer callback runs outside feed(), so resume
3046 # AND flush explicitly, unlike the in-feed() queue pushes above.
3047 40 my $ping = Protocol::WebSocket::Frame->new(
3048 type => 'ping',
3049 buffer => '',
3050 );
3051 40 my $ping_bytes = $ping->to_bytes;
3052 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
3053 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
3054 40 $weak_self->{h2_session}->resume_stream($stream_id);
3055 40 $weak_self->_h2_write_pending;
3056  
3057 # Start pong timeout if configured
3058 40 ▶ if ($weak_ss->{ws_ka_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_ss->{"ws_ka_timeout"} > 0) 10 30 40
3059 10 $weak_ss->{ws_ka_waiting_pong} = 1;
3060 10 $weak_self->_h2_start_ws_pong_timeout($stream_id, $weak_ss);
3061 }
3062 },
3063 10 );
3064  
3065 10 $ss->{ws_ka_timer} = $timer;
3066 10 $self->{server}->add_child($timer);
3067 10 $timer->start;
3068 }
3069  
3070 10 ▶sub _h2_start_ws_pong_timeout {
Subroutine _h2_start_ws_pong_timeout: called CC=4 SCAR=14.3
3071 10 my ($self, $stream_id, $ss) = @_;
3072  
3073 # Don't start another timeout if one is running
3074 10 ▶ return if $ss->{ws_ka_pong_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"ws_ka_pong_timer"} 2 8 10
3075 8 ▶ return unless $ss->{ws_ka_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_ka_timeout"} > 0 0 8 8
3076 8 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 8 8
3077  
3078 8 weaken(my $weak_self = $self);
3079 8 weaken(my $weak_ss = $ss);
3080  
3081 my $timer = IO::Async::Timer::Countdown->new(
3082 delay => $ss->{ws_ka_timeout},
3083 2 ▶ on_expire => sub {
Subroutine __ANON__: called CC=7 SCAR=21.1
3084 2 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
3085 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
3086 2 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 2 2
3087  
3088 2 ▶ if ($weak_ss->{ws_ka_waiting_pong}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_ss->{"ws_ka_waiting_pong"}) 2 0 2
3089 # No pong received within timeout - close only THIS stream.
3090 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
3091 2 $weak_self->{server}->_log(warn =>
3092 "HTTP/2 WebSocket stream $stream_id keepalive timeout - no pong received within $weak_ss->{ws_ka_timeout}s");
3093 }
3094  
3095 2 $weak_self->_h2_stop_ws_keepalive($weak_ss);
3096  
3097 # Record why this stream is ending BEFORE the teardown: this
3098 # is a server-initiated close, not the client going away, and
3099 # _h2_on_close prefers this token over its hardcoded fallback
3100 # for the $cs marking (the queued disconnect event below is
3101 # already correct via the first-wins dedup, but the $cs mark
3102 # only happens in _h2_on_close, downstream of this RST).
3103 2 $weak_ss->{server_close_reason} = 'keepalive_timeout';
3104  
3105 # RFC 6455 section 7.4.1: 1006 MUST NOT be set as the status
3106 # code of a Close control frame -- it means "the connection
3107 # dropped with no close handshake". So a keepalive timeout
3108 # does not send a Close frame at all: it tears the stream
3109 # down with RST_STREAM, the HTTP/2 analogue of h1 dropping
3110 # the transport. The app still sees 1006/'keepalive_timeout'.
3111 #
3112 # Order dependency: the enqueue MUST precede the flush. The
3113 # flush is the only call here that can synchronously drive
3114 # on_stream_close (which enqueues the generic 1006/
3115 # 'client_closed'), and the enqueue is first-wins-deduped, so
3116 # enqueueing first is what makes 'keepalive_timeout' the
3117 # reason the app observes. Do not hoist _h2_write_pending.
3118 2 $weak_self->_h2_ws_enqueue_disconnect($weak_ss, 1006, 'keepalive_timeout');
3119 $weak_self->{h2_session}->submit_rst_stream(
3120 2 $stream_id, _h2_rst_cancel_code());
3121 # This runs outside feed() (async timer callback), so flush
3122 # explicitly.
3123 2 $weak_self->_h2_write_pending;
3124 }
3125 },
3126 8 );
3127  
3128 8 $ss->{ws_ka_pong_timer} = $timer;
3129 8 $self->{server}->add_child($timer);
3130 8 $timer->start;
3131 }
3132  
3133 88 ▶sub _h2_cancel_ws_pong_timeout {
Subroutine _h2_cancel_ws_pong_timeout: called CC=5 SCAR=16.2
3134 88 my ($self, $ss) = @_;
3135 88 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 88 88
3136  
3137 88 $ss->{ws_ka_waiting_pong} = 0;
3138  
3139 88 ▶ return unless $ss->{ws_ka_pong_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_ka_pong_timer"} 80 8 88
3140 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
3141 8 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 8 0 8
3142 8 $self->{server}->remove_child($ss->{ws_ka_pong_timer});
3143 }
3144 8 $ss->{ws_ka_pong_timer} = undef;
3145 }
3146  
3147 83 ▶sub _h2_stop_ws_keepalive {
Subroutine _h2_stop_ws_keepalive: called CC=5 SCAR=16.3
3148 83 my ($self, $ss) = @_;
3149 83 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 83 83
3150  
3151 # Stop pong timeout first
3152 83 $self->_h2_cancel_ws_pong_timeout($ss);
3153  
3154 83 ▶ return unless $ss->{ws_ka_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"ws_ka_timer"} 73 10 83
3155 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
3156 10 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 10 0 10
3157 10 $self->{server}->remove_child($ss->{ws_ka_timer});
3158 }
3159 10 $ss->{ws_ka_timer} = undef;
3160 10 $ss->{ws_ka_interval} = 0;
3161 10 $ss->{ws_ka_timeout} = 0;
3162 }
3163  
3164 # HTTP/2 per-stream SSE keepalive and idle timeout (design section 11.3 --
3165 # the h2 analogue of _start_sse_keepalive/_stop_sse_keepalive and
3166 # _start_sse_idle_timer/_reset_sse_idle_timer/_stop_sse_idle_timer). HTTP/1
3167 # carries only one long-lived scope per connection, so its keepalive/idle
3168 # state and timers stay on $self; HTTP/2 multiplexes many SSE streams per
3169 # connection, so this state and these timers live on the per-stream hash
3170 # ($ss, aka $self->{h2_streams}{$stream_id}) instead -- starting or updating
3171 # keepalive on one stream must never stop, replace, or redirect another
3172 # stream's timer or writer.
3173 6 ▶sub _h2_start_sse_keepalive {
Subroutine _h2_start_sse_keepalive: called CC=5 SCAR=16.9
3174 6 my ($self, $stream_id, $ss, $interval, $comment) = @_;
3175  
3176 # Last event wins: stop whatever was running before applying new settings.
3177 6 $self->_h2_stop_sse_keepalive($ss);
3178  
3179 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
3180 6 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 6 6
3181  
3182 6 $ss->{sse_ka_interval} = $interval;
3183 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
3184  
3185 6 weaken(my $weak_self = $self);
3186 6 weaken(my $weak_ss = $ss);
3187  
3188 my $timer = IO::Async::Timer::Periodic->new(
3189 interval => $interval,
3190 18 ▶ on_tick => sub {
Subroutine __ANON__: called CC=6 SCAR=19.1
3191 18 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 18 18
3192 18 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 18 18
3193 18 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 18 18
3194  
3195 18 my $text = $weak_ss->{sse_ka_comment};
3196 18 ▶ $text = ":$text" unless $text =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /^:/ 18 0 18
3197 18 my $formatted = "$text\n\n";
3198  
3199 18 ▶ if (my $writer = $weak_ss->{sse_ka_writer}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $writer = $weak_ss->{"sse_ka_writer"}) 18 0 18
3200 18 $writer->($formatted);
3201 }
3202 },
3203 6 );
3204  
3205 6 $ss->{sse_ka_timer} = $timer;
3206 6 $self->{server}->add_child($timer);
3207 6 $timer->start;
3208 }
3209  
3210 66 ▶sub _h2_stop_sse_keepalive {
Subroutine _h2_stop_sse_keepalive: called CC=5 SCAR=16.4
3211 66 my ($self, $ss) = @_;
3212 66 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 66 66
3213  
3214 66 ▶ return unless $ss->{sse_ka_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss->{"sse_ka_timer"} 60 6 66
3215 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
3216 6 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 6 0 6
3217 6 $self->{server}->remove_child($ss->{sse_ka_timer});
3218 }
3219 6 $ss->{sse_ka_timer} = undef;
3220 6 $ss->{sse_ka_interval} = 0;
3221 6 $ss->{sse_ka_comment} = '';
3222 }
3223  
3224 # Per-stream SSE idle timeout: resets on send activity (design section
3225 # 11.3's "idle timer and activity reset"). On expiry, only THIS stream ends
3226 # -- mirroring an app-initiated sse.close server-side -- so a stalled SSE
3227 # stream cannot take down sibling streams multiplexed on the same h2
3228 # connection.
3229 28 ▶sub _h2_start_sse_idle_timer {
Subroutine _h2_start_sse_idle_timer: called CC=5 SCAR=16.6
3230 28 my ($self, $stream_id, $ss) = @_;
3231  
3232 28 ▶ 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 25 3 28
Condition66%2/3
$self->{"sse_idle_timeout"} and $self->{"sse_idle_timeout"} > 0
!ll&&!rl&&r
2503
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
3233 3 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 3 3
3234 3 ▶ return if $ss->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $ss->{"sse_idle_timer"} 0 3 3
3235  
3236 3 weaken(my $weak_self = $self);
3237 3 weaken(my $weak_ss = $ss);
3238  
3239 my $timer = IO::Async::Timer::Countdown->new(
3240 delay => $self->{sse_idle_timeout},
3241 2 ▶ on_expire => sub {
Subroutine __ANON__: called CC=7 SCAR=20.7
3242 2 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
3243 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
3244 2 ▶ return unless $weak_ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_ss 0 2 2
3245 2 ▶ return if $weak_ss->{sse_closing}; # already ending some other way
Branch: 1 branch
BranchTrueFalseTotal
if $weak_ss->{"sse_closing"} 0 2 2
3246  
3247 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
3248 2 $weak_self->{server}->_log(warn =>
3249 "HTTP/2 SSE stream $stream_id idle timeout ($weak_self->{sse_idle_timeout}s) - closing stream");
3250 }
3251  
3252 2 $weak_self->_h2_stop_sse_keepalive($weak_ss);
3253 2 $weak_self->_h2_stop_sse_idle_timer($weak_ss);
3254  
3255 # Record why this stream is ending BEFORE the teardown: this is a
3256 # server-initiated close, not the client going away, and
3257 # _h2_on_close prefers this token over its hardcoded fallback for
3258 # both the $cs marking and the queued sse.disconnect event.
3259 2 $weak_ss->{server_close_reason} = 'idle_timeout';
3260  
3261 # End THIS stream only, the same way an app-initiated sse.close
3262 # does: mark it closing so the data_callback emits the final
3263 # END_STREAM frame once the queue drains. _h2_on_close delivers
3264 # the app-facing sse.disconnect once the h2 layer reports the
3265 # stream fully closed -- sibling streams on this connection are
3266 # unaffected.
3267 2 $weak_ss->{sse_close_sent} = 1;
3268 2 $weak_ss->{sse_closing} = 1;
3269 2 $weak_self->{h2_session}->resume_stream($stream_id);
3270 2 $weak_self->_h2_write_pending;
3271 },
3272 3 );
3273  
3274 3 $ss->{sse_idle_timer} = $timer;
3275 3 $self->{server}->add_child($timer);
3276 3 $timer->start;
3277 }
3278  
3279 110 ▶sub _h2_reset_sse_idle_timer {
Subroutine _h2_reset_sse_idle_timer: called CC=4 SCAR=14.1
3280 110 my ($self, $ss) = @_;
3281 110 ▶ return unless $ss && $ss->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and $ss->{"sse_idle_timer"} 101 9 110
Condition66%2/3
$ss and $ss->{"sse_idle_timer"}
!ll&&!rl&&r
01019
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
3282 9 $ss->{sse_idle_timer}->reset;
3283 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
3284 }
3285  
3286 60 ▶sub _h2_stop_sse_idle_timer {
Subroutine _h2_stop_sse_idle_timer: called CC=5 SCAR=16.2
3287 60 my ($self, $ss) = @_;
3288 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
3289 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
3290 3 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 3 0 3
3291 3 $self->{server}->remove_child($ss->{sse_idle_timer});
3292 }
3293 3 $ss->{sse_idle_timer} = undef;
3294 }
3295  
3296 # Request stall timeout - closes connection if no I/O activity during request processing
3297 234 ▶sub _start_stall_timer {
Subroutine _start_stall_timer: called CC=5 SCAR=30.8
3298 234 my ($self) = @_;
3299  
3300 234 ▶ return unless $self->{request_timeout} && $self->{request_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"request_timeout"} and $self->{"request_timeout"} > 0 234 0 234
Condition33%1/3
$self->{"request_timeout"} and $self->{"request_timeout"} > 0
!ll&&!rl&&r
23400
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
3301 0 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 0 0
3302 0 ▶ return if $self->{stall_timer}; # Already running
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stall_timer"} 0 0 0
3303  
3304 0 weaken(my $weak_self = $self);
3305  
3306 my $timer = IO::Async::Timer::Countdown->new(
3307 delay => $self->{request_timeout},
3308 0 ▶ on_expire => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
3309 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3310 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
3311 # Log the timeout
3312 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
3313 0 $weak_self->{server}->_log(warn =>
3314 "Request stall timeout ($weak_self->{request_timeout}s) - closing connection");
3315 }
3316 0 $weak_self->_handle_disconnect_and_close('client_timeout');
3317 },
3318 0 );
3319 0 $self->{stall_timer} = $timer;
3320 0 $self->{server}->add_child($timer);
3321 0 $timer->start;
3322 }
3323  
3324 544 ▶sub _reset_stall_timer {
Subroutine _reset_stall_timer: called CC=3 SCAR=16.5
3325 544 my ($self) = @_;
3326  
3327 544 ▶ return unless $self->{stall_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stall_timer"} 544 0 544
3328 0 $self->{stall_timer}->reset;
3329 0 ▶ $self->{stall_timer}->start unless $self->{stall_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stall_timer"}->is_running 0 0 0
3330 }
3331  
3332 716 ▶sub _stop_stall_timer {
Subroutine _stop_stall_timer: called CC=4 SCAR=23.7
3333 716 my ($self) = @_;
3334  
3335 716 ▶ return unless $self->{stall_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stall_timer"} 716 0 716
3336 0 ▶ $self->{stall_timer}->stop if $self->{stall_timer}->is_running;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"stall_timer"}->is_running 0 0 0
3337 0 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 0 0 0
3338 0 $self->{server}->remove_child($self->{stall_timer});
3339 }
3340 0 $self->{stall_timer} = undef;
3341 }
3342  
3343 # WebSocket idle timeout - closes connection if no activity
3344 34 ▶sub _start_ws_idle_timer {
Subroutine _start_ws_idle_timer: called CC=5 SCAR=30.8
3345 34 my ($self) = @_;
3346  
3347 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
3348 0 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 0 0
3349 0 ▶ return if $self->{ws_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_idle_timer"} 0 0 0
3350  
3351 0 weaken(my $weak_self = $self);
3352  
3353 my $timer = IO::Async::Timer::Countdown->new(
3354 delay => $self->{ws_idle_timeout},
3355 0 ▶ on_expire => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
3356 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3357 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
3358 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
3359 0 $weak_self->{server}->_log(warn =>
3360 "WebSocket idle timeout ($weak_self->{ws_idle_timeout}s) - closing connection");
3361 }
3362 0 $weak_self->_handle_disconnect_and_close('idle_timeout');
3363 },
3364 0 );
3365 0 $self->{ws_idle_timer} = $timer;
3366 0 $self->{server}->add_child($timer);
3367 0 $timer->start;
3368 }
3369  
3370 112 ▶sub _reset_ws_idle_timer {
Subroutine _reset_ws_idle_timer: called CC=3 SCAR=16.5
3371 112 my ($self) = @_;
3372  
3373 112 ▶ return unless $self->{ws_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_idle_timer"} 112 0 112
3374 0 $self->{ws_idle_timer}->reset;
3375 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
3376 }
3377  
3378 509 ▶sub _stop_ws_idle_timer {
Subroutine _stop_ws_idle_timer: called CC=4 SCAR=23.7
3379 509 my ($self) = @_;
3380  
3381 509 ▶ return unless $self->{ws_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_idle_timer"} 509 0 509
3382 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
3383 0 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 0 0 0
3384 0 $self->{server}->remove_child($self->{ws_idle_timer});
3385 }
3386 0 $self->{ws_idle_timer} = undef;
3387 }
3388  
3389 # SSE idle timeout - closes connection if no activity
3390 58 ▶sub _start_sse_idle_timer {
Subroutine _start_sse_idle_timer: called CC=5 SCAR=30.9
3391 58 my ($self) = @_;
3392  
3393 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
3394 0 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 0 0
3395 0 ▶ return if $self->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse_idle_timer"} 0 0 0
3396  
3397 0 weaken(my $weak_self = $self);
3398  
3399 my $timer = IO::Async::Timer::Countdown->new(
3400 delay => $self->{sse_idle_timeout},
3401 0 ▶ on_expire => sub {
Subroutine __ANON__: not called CC=5 SCAR=34.0
3402 0 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 0 0
3403 0 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 0 0
3404 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
3405 0 $weak_self->{server}->_log(warn =>
3406 "SSE idle timeout ($weak_self->{sse_idle_timeout}s) - closing connection");
3407 }
3408 0 $weak_self->{sse_disconnect_reason} = 'idle_timeout';
3409 0 $weak_self->_handle_disconnect_and_close('idle_timeout');
3410 },
3411 0 );
3412 0 $self->{sse_idle_timer} = $timer;
3413 0 $self->{server}->add_child($timer);
3414 0 $timer->start;
3415 }
3416  
3417 141 ▶sub _reset_sse_idle_timer {
Subroutine _reset_sse_idle_timer: called CC=3 SCAR=16.5
3418 141 my ($self) = @_;
3419  
3420 141 ▶ return unless $self->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timer"} 141 0 141
3421 0 $self->{sse_idle_timer}->reset;
3422 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
3423 }
3424  
3425 592 ▶sub _stop_sse_idle_timer {
Subroutine _stop_sse_idle_timer: called CC=4 SCAR=23.7
3426 592 my ($self) = @_;
3427  
3428 592 ▶ return unless $self->{sse_idle_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_idle_timer"} 592 0 592
3429 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
3430 0 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 0 0 0
3431 0 $self->{server}->remove_child($self->{sse_idle_timer});
3432 }
3433 0 $self->{sse_idle_timer} = undef;
3434 }
3435  
3436 # ============================================================================
3437 # Send-side backpressure support
3438 # ============================================================================
3439 #
3440 # Prevents unbounded memory growth when apps send faster than slow clients
3441 # can receive. Uses watermark-based flow control:
3442 # - High watermark (default 1MB): pause sending when buffer exceeds this
3443 # - Low watermark (default 256KB): resume sending when buffer drops below this
3444 #
3445 # The $send->() Future will block (await) when high watermark is exceeded,
3446 # and resolve when buffer drains below low watermark.
3447  
3448 581 ▶sub _get_write_buffer_size {
Subroutine _get_write_buffer_size: called CC=6 SCAR=19.1
3449 581 my ($self) = @_;
3450  
3451 581 ▶ return 0 unless $self->{stream};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream"} 0 581 581
3452  
3453 # Access IO::Async::Stream's internal write queue
3454 # IO::Async doesn't expose a public API for buffer size, so we access internals
3455 581 ▶ my $queue = $self->{stream}{writequeue} // [];
Condition50%1/2
$self->{"stream"}{"writequeue"} // []
l!l
5810
MC/DC0%0/1
$self->{"stream"}{"writequeue"} // []
$self->{"stream"}{"writequeue"}
Truth table50%1/2
A
A= $self->{"stream"}{"writequeue"}
Aresult
11
00
3456 581 my $total = 0;
3457  
3458 581 for my $writer (@$queue) {
3459 424 my $data = $writer->data;
3460 424 ▶ if (defined $data && !ref $data) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $data and not ref $data) 424 0 424
Condition33%1/3
defined $data and not ref $data
!ll&&!rl&&r
00424
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
3461 424 $total += length($data);
3462 }
3463 }
3464  
3465 581 return $total;
3466 }
3467  
3468 # HTTP/1.1: the transport handle reads the shared TCP write buffer. One
3469 # connection is one stream here, so the IO::Async write queue is the per-stream
3470 # backlog. The connection is held weakly so the handle never keeps it alive.
3471 # arm_drain parks the $fire callback in _drain_fires, deliberately separate
3472 # from _drain_waiters (blocking producer Futures, see _wait_for_drain) --
3473 # teardown (_cancel_drain_waiters) resumes the latter but drops the former
3474 # unfired, the same split h2 keeps between stream_drain_waiters and
3475 # transport_drain_fires: the connection going away is not a drain.
3476 329 ▶sub _h1_transport_state {
Subroutine _h1_transport_state: called CC=1 SCAR=0.1
3477 329 my ($self) = @_;
3478 329 weaken(my $w = $self);
3479 return PAGI::Server::TransportState->new(
3480 279 ▶ measure => sub { $w ? $w->_get_write_buffer_size : 0 },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 279 0 279
3481 275 ▶ high => sub { $w ? $w->{write_high_watermark} : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 275 0 275
3482 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
3483 8 ▶ arm_drain => sub {
Subroutine __ANON__: called CC=2 SCAR=7.0
3484 8 my $fire = shift;
3485 8 ▶ return unless $w;
Branch: 1 branch
BranchTrueFalseTotal
unless $w 0 8 8
3486 8 push @{$w->{_drain_fires}}, $fire;
3487 8 $w->_setup_drain_detection;
3488 },
3489 329 );
3490 }
3491  
3492 # HTTP/2: the transport handle reads this stream's send queue, not the shared
3493 # TCP write buffer — under h2, N streams multiplex one connection, so that
3494 # buffer is the whole connection's backlog (meaningless per stream). $ss is the
3495 # per-stream state hashref; it's held directly (it is the stream's own state),
3496 # while $self is weakened so the handle never keeps the connection alive.
3497 # arm_drain parks the $fire callback on the stream; the data_callback pull fires
3498 # it (deferred) when the queue crosses below the low watermark. Kept separate
3499 # from stream_drain_waiters: those are Futures for blocking backpressure, these
3500 # are the on_drain hysteresis fires.
3501 209 ▶sub _h2_transport_state {
Subroutine _h2_transport_state: called CC=1 SCAR=0.0
3502 209 my ($self, $ss) = @_;
3503 209 weaken(my $w = $self);
3504 return PAGI::Server::TransportState->new(
3505 199 ▶ 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
1927
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
3506 190 ▶ high => sub { $w ? $w->{write_high_watermark} : undef },
Subroutine __ANON__: called CC=2 SCAR=7.6
Branch: 1 branch
BranchTrueFalseTotal
$w ? : 190 0 190
3507 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
3508 26 ▶ arm_drain => sub { my $fire = shift; push @{$ss->{transport_drain_fires}}, $fire },
Subroutine __ANON__: called CC=1 SCAR=0.0
3509 209 );
3510 }
3511  
3512 # Notify the current transport-state handle after an application write so its
3513 # backpressure callbacks (on_high_water/on_drain) can fire on a watermark cross.
3514 265 ▶sub _notify_transport_write {
Subroutine _notify_transport_write: called CC=2 SCAR=7.1
3515 265 my ($self) = @_;
3516 265 my $ts = $self->{current_transport_state};
3517 265 ▶ $ts->_check_watermarks if $ts;
Branch: 1 branch
BranchTrueFalseTotal
if $ts 265 0 265
3518 }
3519  
3520 4 ▶sub _check_drain_waiters {
Subroutine _check_drain_waiters: called CC=8 SCAR=21.3
3521 4 my ($self) = @_;
3522  
3523 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
3524 4 ▶ return unless $self->{stream};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream"} 0 4 4
3525  
3526 4 my $buffered = $self->_get_write_buffer_size;
3527  
3528 # Resolve/fire everyone once we've drained below low watermark: blocking
3529 # producer Futures resolve, and arm_drain's on_drain hysteresis callbacks
3530 # fire -- this IS an actual drain, unlike teardown (_cancel_drain_waiters).
3531 4 ▶ if ($buffered < $self->{write_low_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffered < $self->{"write_low_watermark"}) 4 0 4
3532 4 my @waiters = splice @{$self->{_drain_waiters}};
3533 4 for my $f (@waiters) {
3534 1 ▶ $f->done unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 1 0 1
3535 }
3536 4 my @fires = splice @{$self->{_drain_fires}};
3537 4 $_->() for @fires;
3538 # Disable drain checking until next high watermark hit
3539 4 $self->{_drain_check_active} = 0;
3540 }
3541 }
3542  
3543 13 ▶sub _setup_drain_detection {
Subroutine _setup_drain_detection: called CC=2 SCAR=7.0
3544 13 my ($self) = @_;
3545  
3546 # Avoid redundant setup
3547 13 ▶ return if $self->{_drain_check_active};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_drain_check_active"} 5 8 13
3548 8 $self->{_drain_check_active} = 1;
3549  
3550 8 weaken(my $weak_self = $self);
3551  
3552 # Primary mechanism: check when write queue empties
3553 # This guarantees we notice drain even for fast-draining connections
3554 # Store previous handler to chain if needed
3555 8 my $prev_on_empty = $self->{_prev_on_outgoing_empty};
3556  
3557 $self->{stream}->configure(
3558 3 ▶ on_outgoing_empty => sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
3559 3 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 3 3
3560 3 $weak_self->_check_drain_waiters;
3561 # Call previous handler if any
3562 3 ▶ $prev_on_empty->(@_) if $prev_on_empty;
Branch: 1 branch
BranchTrueFalseTotal
if $prev_on_empty 0 3 3
3563 },
3564 8 );
3565 }
3566  
3567 5 ▶sub _wait_for_drain {
Subroutine _wait_for_drain: called CC=2 SCAR=7.1
3568 5 my ($self) = @_;
3569  
3570 # Fast path: already below low watermark
3571 5 my $buffered = $self->_get_write_buffer_size;
3572 5 ▶ if ($buffered < $self->{write_low_watermark}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($buffered < $self->{"write_low_watermark"}) 0 5 5
3573 0 return Future->done;
3574 }
3575  
3576 # Create Future to be resolved when drained
3577 5 my $f = $self->{server}->loop->new_future;
3578 5 push @{$self->{_drain_waiters}}, $f;
3579  
3580 # Ensure drain detection is active
3581 5 $self->_setup_drain_detection;
3582  
3583 5 return $f;
3584 }
3585  
3586 1019 ▶sub _cancel_drain_waiters {
Subroutine _cancel_drain_waiters: called CC=4 SCAR=14.0
3587 1019 my ($self, $reason) = @_;
3588 1019 ▶ $reason //= 'connection closed';
Condition50%1/2
$reason //= "connection closed"
l!l
10190
MC/DC0%0/1
$reason //= "connection closed"
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
3589  
3590 1019 my @waiters = splice @{$self->{_drain_waiters}};
3591 1019 for my $f (@waiters) {
3592 # Resolve (not fail) - app should check connection state after await
3593 5 ▶ $f->done unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 5 0 5
3594 }
3595 # Drop (don't fire) the app's on_drain fires: the connection is going
3596 # away, not draining -- matches h2's teardown handling of
3597 # transport_drain_fires. The blocking waiters above still resume (so no
3598 # coroutine leak), but on_drain is a hysteresis signal for a buffer that
3599 # actually fell back below the low mark, which never happened here.
3600 1019 $self->{_drain_fires} = [];
3601 1019 $self->{_drain_check_active} = 0;
3602 }
3603  
3604 # HTTP/2 per-stream backpressure: the h2 analogue of _wait_for_drain. Resolves
3605 # when this stream's send queue falls below the low watermark. Each multiplexed
3606 # stream is bounded independently, so a quiet TCP buffer can't let one stream's
3607 # queue grow without limit.
3608 12 ▶sub _h2_wait_for_stream_drain {
Subroutine _h2_wait_for_stream_drain: called CC=5 SCAR=16.8
3609 12 my ($self, $stream_id) = @_;
3610  
3611 12 ▶ 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 12 0 12
3612  
3613 # Fast path: already below low watermark
3614 12 ▶ 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 12 12
Condition50%1/2
$ss->{"send_queue_bytes"} // 0
l!l
120
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
3615 0 return Future->done;
3616 }
3617  
3618 # Create Future to be resolved when this stream's queue drains (in the
3619 # data_callback pull) or when the stream is torn down.
3620 12 my $f = $self->{server}->loop->new_future;
3621 12 ▶ push @{$ss->{stream_drain_waiters} //= []}, $f;
Condition100%2/2
$ss->{"stream_drain_waiters"} //= []
l!l
75
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
3622  
3623 12 return $f;
3624 }
3625  
3626 # Release any producer blocked on _h2_wait_for_stream_drain for a stream that
3627 # is being torn down (close/RST/connection shutdown). Resolve, never fail - the
3628 # producer rechecks connection/stream state after the await. Some teardown
3629 # sites run inside nghttp2's feed() (e.g. the oversize-body 413 path); completing
3630 # a waiter resumes the producer synchronously, so defer to the next loop tick to
3631 # keep the resumed producer out of a re-entrant nghttp2 call.
3632 212 ▶sub _h2_resolve_stream_drain_waiters {
Subroutine _h2_resolve_stream_drain_waiters: called CC=4 SCAR=13.9
3633 212 my ($self, $ss) = @_;
3634 212 ▶ return unless $ss && $ss->{stream_drain_waiters};
Branch: 1 branch
BranchTrueFalseTotal
unless $ss and $ss->{"stream_drain_waiters"} 207 5 212
Condition66%2/3
$ss and $ss->{"stream_drain_waiters"}
!ll&&!rl&&r
02075
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
3635 5 my @waiters = splice @{$ss->{stream_drain_waiters}};
3636 5 ▶ return unless @waiters;
Branch: 1 branch
BranchTrueFalseTotal
unless @waiters 3 2 5
3637 2 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
3638 2 $_->done for grep { !$_->is_ready } @waiters;
3639 2 });
3640 }
3641  
3642 # Release a send() parked in the http.response.trailers arm awaiting
3643 # $deliver_trailer_eof (the data callback's own terminal invocation) for a
3644 # stream that is being torn down before that ever happens. Resolve, never
3645 # fail -- same h2_closed carve-out contract as every other post-close send
3646 # (design §6.2 / §21 item 1): a trailers send racing a disconnect is a
3647 # successful no-op, not an error the app must handle. Same re-entrancy
3648 # discipline as _h2_resolve_stream_drain_waiters above (deferred one loop
3649 # tick -- some teardown sites run inside nghttp2's feed()).
3650 211 ▶sub _h2_resolve_stream_trailer_wait {
Subroutine _h2_resolve_stream_trailer_wait: called CC=3 SCAR=11.1
3651 211 my ($self, $ss) = @_;
3652 211 ▶ return unless $ss;
Branch: 1 branch
BranchTrueFalseTotal
unless $ss 0 211 211
3653 211 my $f = delete $ss->{trailer_wait};
3654 211 ▶ return unless $f;
Branch: 1 branch
BranchTrueFalseTotal
unless $f 209 2 211
3655 2 ▶ $self->{server}->loop->later(sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
3656 2 ▶ $f->done unless $f->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
unless $f->is_ready 2 0 2
3657 2 });
3658 }
3659  
3660 # ============================================================================
3661  
3662 # WebSocket keepalive - sends protocol-level ping frames (RFC 6455)
3663 1 ▶sub _start_ws_keepalive {
Subroutine _start_ws_keepalive: called CC=5 SCAR=16.8
3664 1 my ($self, $interval, $timeout) = @_;
3665  
3666 # Stop existing timers first
3667 1 $self->_stop_ws_keepalive;
3668  
3669 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
3670 1 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 1 1
3671  
3672 1 $self->{ws_keepalive_interval} = $interval;
3673 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
3674  
3675 1 weaken(my $weak_self = $self);
3676  
3677 my $timer = IO::Async::Timer::Periodic->new(
3678 interval => $interval,
3679 2 ▶ on_tick => sub {
Subroutine __ANON__: called CC=5 SCAR=16.8
3680 2 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 2 2
3681 2 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 2 2
3682 2 ▶ return unless $weak_self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"websocket_mode"} 0 2 2
3683  
3684 # Send ping frame
3685 2 my $ping = Protocol::WebSocket::Frame->new(
3686 type => 'ping',
3687 buffer => '',
3688 );
3689 2 $weak_self->{stream}->write($ping->to_bytes);
3690  
3691 # Start pong timeout if configured
3692 2 ▶ if ($weak_self->{ws_keepalive_timeout} > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"ws_keepalive_timeout"} > 0) 2 0 2
3693 2 $weak_self->{ws_waiting_pong} = 1;
3694 2 $weak_self->_start_ws_pong_timeout;
3695 }
3696 },
3697 1 );
3698  
3699 1 $self->{ws_keepalive_timer} = $timer;
3700 1 $self->{server}->add_child($timer);
3701 1 $timer->start;
3702 }
3703  
3704 2 ▶sub _start_ws_pong_timeout {
Subroutine _start_ws_pong_timeout: called CC=4 SCAR=14.5
3705 2 my ($self) = @_;
3706  
3707 # Don't start another timeout if one is running
3708 2 ▶ return if $self->{ws_pong_timeout};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"ws_pong_timeout"} 1 1 2
3709 1 ▶ return unless $self->{ws_keepalive_timeout} > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_keepalive_timeout"} > 0 0 1 1
3710 1 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 1 1
3711  
3712 1 weaken(my $weak_self = $self);
3713  
3714 my $timer = IO::Async::Timer::Countdown->new(
3715 delay => $self->{ws_keepalive_timeout},
3716 1 ▶ on_expire => sub {
Subroutine __ANON__: called CC=6 SCAR=20.3
3717 1 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
3718 1 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 1 1
3719  
3720 1 ▶ if ($weak_self->{ws_waiting_pong}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"ws_waiting_pong"}) 1 0 1
3721 # No pong received within timeout - close connection
3722 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
3723 1 $weak_self->{server}->_log(warn =>
3724 "WebSocket keepalive timeout - no pong received within $weak_self->{ws_keepalive_timeout}s");
3725 }
3726 1 $weak_self->_handle_disconnect_and_close('keepalive_timeout');
3727 }
3728 },
3729 1 );
3730  
3731 1 $self->{ws_pong_timeout} = $timer;
3732 1 $self->{server}->add_child($timer);
3733 1 $timer->start;
3734 }
3735  
3736 510 ▶sub _cancel_ws_pong_timeout {
Subroutine _cancel_ws_pong_timeout: called CC=4 SCAR=14.0
3737 510 my ($self) = @_;
3738  
3739 510 $self->{ws_waiting_pong} = 0;
3740  
3741 510 ▶ return unless $self->{ws_pong_timeout};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_pong_timeout"} 509 1 510
3742 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
3743 1 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 1 0 1
3744 1 $self->{server}->remove_child($self->{ws_pong_timeout});
3745 }
3746 1 $self->{ws_pong_timeout} = undef;
3747 }
3748  
3749 510 ▶sub _stop_ws_keepalive {
Subroutine _stop_ws_keepalive: called CC=4 SCAR=14.0
3750 510 my ($self) = @_;
3751  
3752 # Stop pong timeout first
3753 510 $self->_cancel_ws_pong_timeout;
3754  
3755 510 ▶ return unless $self->{ws_keepalive_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"ws_keepalive_timer"} 509 1 510
3756 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
3757 1 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 1 0 1
3758 1 $self->{server}->remove_child($self->{ws_keepalive_timer});
3759 }
3760 1 $self->{ws_keepalive_timer} = undef;
3761 1 $self->{ws_keepalive_interval} = 0;
3762 1 $self->{ws_keepalive_timeout} = 0;
3763 }
3764  
3765 # SSE keepalive - sends comment lines to prevent proxy timeouts
3766 4 ▶sub _start_sse_keepalive {
Subroutine _start_sse_keepalive: called CC=5 SCAR=17.0
3767 4 my ($self, $interval, $comment) = @_;
3768  
3769 # Stop existing timer first
3770 4 $self->_stop_sse_keepalive;
3771  
3772 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
3773 4 ▶ return unless $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"server"} 0 4 4
3774  
3775 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
3776  
3777 4 weaken(my $weak_self = $self);
3778  
3779 my $timer = IO::Async::Timer::Periodic->new(
3780 interval => $interval,
3781 9 ▶ on_tick => sub {
Subroutine __ANON__: called CC=5 SCAR=17.0
3782 9 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 9 9
3783 9 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 9 9
3784  
3785 9 my $text = $weak_self->{sse_keepalive_comment};
3786 9 ▶ $text = ":$text" unless $text =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $text =~ /^:/ 9 0 9
3787 9 my $formatted = "$text\n\n";
3788  
3789 9 ▶ if (my $writer = $weak_self->{sse_keepalive_writer}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $writer = $weak_self->{"sse_keepalive_writer"}) 9 0 9
3790 9 $writer->($formatted);
3791 }
3792 },
3793 4 );
3794  
3795 4 $self->{sse_keepalive_timer} = $timer;
3796 4 $self->{server}->add_child($timer);
3797 4 $timer->start;
3798 }
3799  
3800 596 ▶sub _stop_sse_keepalive {
Subroutine _stop_sse_keepalive: called CC=4 SCAR=14.0
3801 596 my ($self) = @_;
3802  
3803 596 ▶ return unless $self->{sse_keepalive_timer};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"sse_keepalive_timer"} 592 4 596
3804 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
3805 4 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 4 0 4
3806 4 $self->{server}->remove_child($self->{sse_keepalive_timer});
3807 }
3808 4 $self->{sse_keepalive_timer} = undef;
3809 4 $self->{sse_keepalive_comment} = '';
3810 }
3811  
3812 348 ▶sub _try_handle_request {
Subroutine _try_handle_request: called CC=11 SCAR=24.0
3813 348 my ($self) = @_;
3814  
3815 348 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 348 348
3816 348 ▶ return if $self->{handling_request};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"handling_request"} 14 334 348
3817  
3818 # Try to parse a request from the buffer
3819 334 my ($request, $consumed) = $self->{protocol}->parse_request($self->{buffer});
3820  
3821 334 ▶ return unless $request;
Branch: 1 branch
BranchTrueFalseTotal
unless $request 2 332 334
3822  
3823 # Remove consumed bytes from buffer
3824 332 substr($self->{buffer}, 0, $consumed) = '';
3825  
3826 # Handle parse errors (malformed request, header too large)
3827 332 ▶ if ($request->{error}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"error"}) 5 327 332
3828 # Mark connection as disconnected with protocol_error reason (PAGI spec compliance)
3829 5 $self->_handle_disconnect('protocol_error');
3830 5 $self->_send_error_response($request->{error}, $request->{message});
3831 5 $self->_close;
3832 5 return;
3833 }
3834  
3835 # Check Content-Length against max_body_size limit (0 = unlimited)
3836 327 ▶ if ($self->{max_body_size} && defined $request->{content_length}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"max_body_size"} and defined $request->{"content_length"}) 9 318 327
Condition100%3/3
$self->{"max_body_size"} and defined $request->{"content_length"}
!ll&&!rl&&r
23169
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
3837 9 ▶ if ($request->{content_length} > $self->{max_body_size}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($request->{"content_length"} > $self->{"max_body_size"}) 1 8 9
3838 1 $self->_handle_disconnect('body_too_large');
3839 1 $self->_send_error_response(413, 'Payload Too Large');
3840 1 $self->_close;
3841 1 return;
3842 }
3843 }
3844  
3845 # Check if this is a WebSocket upgrade request
3846 326 my $is_websocket = $self->_is_websocket_upgrade($request);
3847  
3848 # Check if this is an SSE request
3849 326 ▶ my $is_sse = !$is_websocket && $self->_is_sse_request($request);
Condition100%3/3
!$is_websocket && $self->_is_sse_request($request)
!ll&&!rl&&r
3423458
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
3850  
3851 # Handle the request - store the Future to prevent "lost future" warning
3852 326 $self->{handling_request} = 1;
3853 326 $self->{request_start} = [gettimeofday];
3854 326 $self->{current_request} = $request; # Store for access logging
3855  
3856 326 ▶ if ($is_websocket) {
Branch: 2 branches
BranchTrueFalseTotal
if ($is_websocket) { } 34 292 326
elsif ($is_sse) { } 58 234 292
3857 34 $self->{request_future} = $self->_handle_websocket_request($request);
3858 } elsif ($is_sse) {
3859 58 $self->{request_future} = $self->_handle_sse_request($request);
3860 } else {
3861 # Start stall timer for HTTP requests (WebSocket/SSE have their own handling)
3862 234 $self->_start_stall_timer;
3863 234 $self->{request_future} = $self->_handle_request($request);
3864 }
3865  
3866 # Use adopt_future for proper error tracking instead of retain
3867 # This ensures errors are propagated to the server's error handling
3868 326 $self->{server}->adopt_future($self->{request_future});
3869 }
3870  
3871 326 ▶sub _is_websocket_upgrade {
Subroutine _is_websocket_upgrade: called CC=9 SCAR=22.1
3872 326 my ($self, $request) = @_;
3873  
3874 # Check for WebSocket upgrade headers
3875 326 my $has_upgrade = 0;
3876 326 my $has_connection_upgrade = 0;
3877 326 my $has_ws_key = 0;
3878  
3879 326 for my $header (@{$request->{headers}}) {
3880 940 my ($name, $value) = @$header;
3881 940 ▶ if ($name eq 'upgrade' && lc($value) eq 'websocket') {
Branch: 3 branches
BranchTrueFalseTotal
if ($name eq 'upgrade' and lc $value eq 'websocket') { } 34 906 940
elsif ($name eq 'connection') { } 250 656 906
elsif ($name eq 'sec-websocket-key') { } 34 622 656
Condition66%2/3
$name eq "upgrade" and lc $value eq "websocket"
!ll&&!rl&&r
906034
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
3882 34 $has_upgrade = 1;
3883 }
3884 elsif ($name eq 'connection') {
3885 # Connection header can have multiple values
3886 250 ▶ $has_connection_upgrade = 1 if lc($value) =~ /upgrade/;
Branch: 1 branch
BranchTrueFalseTotal
if lc($value) =~ /upgrade/ 34 216 250
3887 }
3888 elsif ($name eq 'sec-websocket-key') {
3889 34 $has_ws_key = 1;
3890 }
3891 }
3892  
3893 326 ▶ return $has_upgrade && $has_connection_upgrade && $has_ws_key;
Condition66%4/6
$has_upgrade && $has_connection_upgrade && $has_ws_key
!ll&&!rl&&r
292034
$has_upgrade and $has_connection_upgrade
!ll&&!rl&&r
292034
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
3894 }
3895  
3896 292 ▶sub _is_sse_request {
Subroutine _is_sse_request: called CC=1 SCAR=0.0
3897 292 my ($self, $request) = @_;
3898  
3899 # SSE detection per spec (see _accept_signals_sse above).
3900 # Request has not been upgraded to WebSocket (already checked).
3901 # Note: SSE works with any HTTP method (GET, POST, etc.) to support
3902 # modern patterns like htmx 4 and datastar using fetch-event-source
3903  
3904 292 return _accept_signals_sse($request->{headers});
3905 }
3906  
3907 234 ▶async sub _handle_request {
Subroutine _handle_request: called CC=23 SCAR=31.6
3908 234 my ($self, $request) = @_;
3909  
3910 234 my $scope = $self->_create_scope($request);
3911 234 my $receive = $self->_create_receive($request);
3912 234 my $send = $self->_create_send($request);
3913  
3914 234 eval {
3915 234 await $self->{app}->($scope, $receive, $send);
3916 };
3917  
3918 233 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 17 216 233
3919 # Delivery defines completion (Www.pod:1156-1165): if the terminal
3920 # response event already went out, an exception thrown afterward is
3921 # not a disconnect. Fire on_complete (never on_disconnect), leave
3922 # disconnect_reason() undef, still warn (SHOULD log), and still
3923 # close (MAY close) -- mirrors _h2_dispatch_stream's own log-only
3924 # branch for an error after the response is already complete: that
3925 # stream's connection_state is likewise marked complete before the
3926 # exception is even observed there.
3927 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
3928 1 $self->_log(error => "PAGI application error (after response complete): $error");
3929 1 $self->_write_access_log;
3930 1 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 1 0 1
3931 1 ▶ if (my $conn_state = $self->{current_connection_state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn_state = $self->{"current_connection_state"}) 1 0 1
3932 1 $conn_state->_mark_complete;
3933 }
3934 1 $self->_close;
3935 1 return;
3936 }
3937  
3938 # Handle application error - always close connection after exception
3939 # If response already started, we can't send error page (3.17)
3940 16 ▶ if ($self->{response_started}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'response_started'}) { } 1 15 16
3941 1 $self->_flush_pending_headers; # don't lose a started response's headers
3942 1 $self->_log(error => "PAGI application error (after response started): $error");
3943 } else {
3944 15 $self->_send_error_response(500, "Internal Server Error");
3945 15 $self->_log(error => "PAGI application error: $error");
3946 }
3947 # Write access log before closing
3948 16 $self->_write_access_log;
3949 # Notify server that request completed (for max_requests tracking)
3950 16 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 16 0 16
3951 # Always close connection after exception (3.2) - don't try keep-alive
3952 16 $self->_handle_disconnect('server_error');
3953 16 $self->_close;
3954 16 return;
3955 }
3956  
3957 # The application returned without starting a response. An incomplete
3958 # response is a protocol error: if the client is still connected, synthesize
3959 # a 500; either way do not keep-alive a connection on which no response was
3960 # written (that would hang the client, which is waiting for a response). A
3961 # response that was started but not completed is handled by the body-framing
3962 # and keep-alive logic below.
3963 216 ▶ if (!$self->{response_started}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"response_started"}) 4 212 216
3964 4 ▶ unless ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"closed"}) 1 3 4
3965 1 $self->_log(error => "PAGI application returned without starting a response");
3966 1 $self->_send_error_response(500, "Internal Server Error");
3967 }
3968 4 $self->_write_access_log;
3969 4 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 4 0 4
3970 4 $self->_handle_disconnect('server_error');
3971 4 $self->_close;
3972 4 return;
3973 }
3974  
3975 # The application resolved with a started but incomplete response
3976 # (terminal body/file/fh — or promised trailers — never sent). Per the
3977 # PAGI spec this is an abnormal end: never synthesize the terminal
3978 # framing, never keep the connection alive, and report server_error
3979 # through on_disconnect — a truncated response must be observable as
3980 # truncated.
3981 212 ▶ 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 207 212
Condition60%3/5
$self->{"response_started"} and ($self->{"h1_seq"} // "complete") ne "complete"
!ll&&!rl&&r
02075
$self->{"h1_seq"} // "complete"
l!l
2120
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
3982 5 $self->_flush_pending_headers; # headers may still be buffered; no terminator follows
3983 5 ▶ unless ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"closed"}) 4 1 5
3984 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
3985 ? "PAGI application returned with an incomplete response (trailers were declared but never sent)\n"
3986 : "PAGI application returned with an incomplete response\n");
3987 }
3988 5 $self->_write_access_log;
3989 5 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 5 0 5
3990 5 $self->_handle_disconnect_and_close('server_error');
3991 5 return;
3992 }
3993  
3994 # Flush any headers buffered by response.start that were never paired with a
3995 # body write (a started-but-bodyless response).
3996 207 $self->_flush_pending_headers;
3997  
3998 # Write access log entry
3999 207 $self->_write_access_log;
4000  
4001 # Notify server that request completed (for max_requests tracking)
4002 207 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 207 0 207
4003  
4004 # Stop stall timer - request completed successfully
4005 207 $self->_stop_stall_timer;
4006  
4007 # Request finished cleanly: fire on_complete (not on_disconnect) on the
4008 # HTTP connection-state object. Must happen on BOTH the keep-alive and
4009 # close paths, and before the keep-alive branch clears the state below.
4010 # Once marked complete, the non-keep-alive _handle_disconnect_and_close
4011 # call below no-ops the state transition, so on_disconnect never fires for
4012 # a completed request.
4013 207 ▶ if (my $conn_state = $self->{current_connection_state}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $conn_state = $self->{"current_connection_state"}) 207 0 207
4014 207 $conn_state->_mark_complete;
4015 }
4016  
4017 # A request has now completed on this connection: the idle timer's next
4018 # expiry (if the connection stays open awaiting another request) reports
4019 # keepalive_timeout rather than idle_timeout.
4020 207 $self->{_served_a_request} = 1;
4021  
4022 # Determine if we should keep the connection alive
4023 207 my $keep_alive = $self->_should_keep_alive($request);
4024  
4025 207 ▶ if ($keep_alive) {
Branch: 1 branch
BranchTrueFalseTotal
if ($keep_alive) { } 183 24 207
4026 # Reset for next request
4027 183 $self->{handling_request} = 0;
4028 183 $self->{response_started} = 0;
4029 183 $self->{h1_seq} = 'initial';
4030 183 $self->{_resp_pending} = undef;
4031 183 $self->{response_status} = undef;
4032 183 $self->{_response_size} = 0;
4033 183 $self->{request_start} = undef;
4034 183 $self->{current_request} = undef;
4035 183 $self->{request_future} = undef;
4036 183 $self->{current_connection_state} = undef; # Clear for next request
4037 183 $self->{current_transport_state} = undef; # New request gets a fresh handle
4038  
4039 # Check if there's more data in the buffer (pipelining)
4040 183 ▶ if (length($self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} > 0) 1 182 183
4041 1 $self->_try_handle_request;
4042 }
4043 } else {
4044 # Not keeping alive - close connection
4045 24 $self->_handle_disconnect_and_close('request_complete');
4046 }
4047 156 }
4048  
4049 241 ▶sub _should_keep_alive {
Subroutine _should_keep_alive: called CC=10 SCAR=23.2
4050 241 my ($self, $request) = @_;
4051  
4052 241 ▶ my $http_version = $request->{http_version} // '1.1';
Condition50%1/2
$request->{"http_version"} // "1.1"
l!l
2410
MC/DC0%0/1
$request->{"http_version"} // "1.1"
$request->{"http_version"}
Truth table50%1/2
A
A= $request->{"http_version"}
Aresult
11
00
4053  
4054 # Check for Connection header
4055 241 my $connection_header;
4056 241 for my $header (@{$request->{headers}}) {
4057 443 ▶ if ($header->[0] eq 'connection') {
Branch: 1 branch
BranchTrueFalseTotal
if ($header->[0] eq "connection") 194 249 443
4058 194 $connection_header = lc($header->[1]);
4059 194 last;
4060 }
4061 }
4062  
4063 # HTTP/1.1: keep-alive by default unless Connection: close
4064 241 ▶ if ($http_version eq '1.1') {
Branch: 1 branch
BranchTrueFalseTotal
if ($http_version eq "1.1") 237 4 241
4065 237 ▶ return 0 if $connection_header && $connection_header =~ /close/;
Branch: 1 branch
BranchTrueFalseTotal
if $connection_header and $connection_header =~ /close/ 30 207 237
Condition100%3/3
$connection_header and $connection_header =~ /close/
!ll&&!rl&&r
4416330
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
4066 207 return 1;
4067 }
4068  
4069 # HTTP/1.0: close by default unless Connection: keep-alive
4070 4 ▶ if ($http_version eq '1.0') {
Branch: 1 branch
BranchTrueFalseTotal
if ($http_version eq "1.0") 4 0 4
4071 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
4072 3 return 0;
4073 }
4074  
4075 # Unknown version: close connection
4076 0 return 0;
4077 }
4078  
4079 234 ▶sub _create_scope {
Subroutine _create_scope: called CC=3 SCAR=11.0
4080 234 my ($self, $request) = @_;
4081  
4082 # Create connection state object for disconnect tracking
4083 # Uses lazy Future creation - Future only allocated if disconnect_future() is called
4084 my $connection_state = PAGI::Server::ConnectionState->new(
4085 connection => $self,
4086 server => $self->{server},
4087 234 );
4088 234 $self->{current_connection_state} = $connection_state;
4089  
4090 my $scope = {
4091 type => 'http',
4092 pagi => {
4093 version => '0.5',
4094 spec_version => '0.5',
4095 },
4096 http_version => $request->{http_version},
4097 method => $request->{method},
4098 scheme => $self->_get_scheme,
4099 path => $request->{path},
4100 raw_path => $request->{raw_path},
4101 query_string => $request->{query_string},
4102 root_path => '',
4103 headers => $request->{headers},
4104 (defined $self->{client_host}
4105 ? (client => [$self->{client_host}, $self->{client_port}])
4106 : ()
4107 ),
4108 server => [$self->{server_host}, $self->{server_port}],
4109 # Optimized: avoid hash copy when state is empty (common case)
4110 234 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
4111 extensions => $self->_get_extensions_for_scope,
4112 # Connection state for non-destructive disconnect detection
4113 'pagi.connection' => $connection_state,
4114 # Outbound flow-control introspection (buffered_amount, watermarks,
4115 # on_high_water/on_drain). Stashed on the connection too, so the send
4116 # path can poke _check_watermarks after each write.
4117 234 ▶ 'pagi.transport' => ($self->{current_transport_state} = $self->_h1_transport_state),
Branch: 2 branches
BranchTrueFalseTotal
defined $self->{'client_host'} ? : 232 2 234
keys %{$$self{'state'};} ? : 3 231 234
4118 };
4119  
4120 234 return $scope;
4121 }
4122  
4123 # Shared by _create_receive (http.request) and _create_sse_receive
4124 # (sse.request): parses one attempt's worth of a chunked Transfer-Encoding
4125 # request body out of $self->{buffer}, waiting for more bytes if none are
4126 # available yet. Returns the next event for the caller's receive() closure
4127 # to return directly -- a body event (event_type/body/more), the caller's
4128 # disconnect event (via $make_disconnect on a protocol error, an oversized
4129 # body, or the connection closing), or a truthful more=>1 placeholder when
4130 # a receive_pending wake produced no parseable chunk yet.
4131 #
4132 # $body_complete_ref/$bytes_read_ref are scalar refs into the caller's own
4133 # closure-local state so it persists across receive() calls; $event_type
4134 # is 'http.request' or 'sse.request'; $make_disconnect is a coderef
4135 # producing this scope's disconnect event ({type=>'http.disconnect'} or
4136 # the SSE closure's sse.disconnect constructor).
4137 2 ▶async sub _read_chunked_body {
Subroutine _read_chunked_body: called CC=19 SCAR=47.8
4138 2 my ($self, $event_type, $make_disconnect, $body_complete_ref, $bytes_read_ref) = @_;
4139  
4140 # Wait for data if buffer is empty
4141 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
4142 0 ▶ if (!$self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"receive_pending"}) 0 0 0
4143 0 $self->{receive_pending} = Future->new;
4144 }
4145 0 await $self->{receive_pending};
4146 0 $self->{receive_pending} = undef;
4147  
4148 # Check queue after waiting
4149 0 ▶ if (@{$self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"receive_queue"};}) 0 0 0
4150 0 return shift @{$self->{receive_queue}};
4151 }
4152 }
4153  
4154 return $make_disconnect->()
4155 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
4156  
4157 # Try to parse chunked data
4158 2 my ($data, $consumed, $complete) = $self->{protocol}->parse_chunked_body($self->{buffer});
4159  
4160 # Check for parse error (invalid chunk size)
4161 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
4162 0 $self->_handle_disconnect('protocol_error');
4163 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
4164 0 $self->_close;
4165 0 return $make_disconnect->();
4166 }
4167  
4168 2 ▶ if ($consumed > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($consumed > 0) 2 0 2
4169 2 substr($self->{buffer}, 0, $consumed) = '';
4170  
4171 # Track total bytes read for max_body_size check
4172 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
4173  
4174 # Check max_body_size for chunked requests (0 = unlimited)
4175 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
4176 # Body too large - close connection
4177 0 $self->_send_error_response(413, 'Payload Too Large');
4178 0 $self->_handle_disconnect('body_too_large');
4179 0 $self->_close;
4180 0 return $make_disconnect->();
4181 }
4182  
4183 2 ▶ if ($complete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($complete) 2 0 2
4184 2 $$body_complete_ref = 1;
4185 }
4186  
4187 return {
4188 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
4189 body => $data // '',
4190 more => $complete ? 0 : 1,
4191 };
4192 }
4193  
4194 # Need more data - wait for it
4195 0 ▶ if (!$self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"receive_pending"}) 0 0 0
4196 0 $self->{receive_pending} = Future->new;
4197 }
4198 0 await $self->{receive_pending};
4199 0 $self->{receive_pending} = undef;
4200  
4201 # Recursive call to re-process - but we can't use __SUB__ in nested async
4202 # Just return disconnect if closed
4203 0 ▶ return $make_disconnect->() if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 0 0
4204 # This shouldn't happen often - caller should retry
4205 0 return { type => $event_type, body => '', more => 1 };
4206 156 }
4207  
4208 234 ▶sub _create_receive {
Subroutine _create_receive: called CC=5 SCAR=17.1
4209 234 my ($self, $request) = @_;
4210  
4211 234 my $content_length = $request->{content_length};
4212 234 ▶ my $is_chunked = $request->{chunked} // 0;
Condition50%1/2
$request->{"chunked"} // 0
l!l
2340
MC/DC0%0/1
$request->{"chunked"} // 0
$request->{"chunked"}
Truth table50%1/2
A
A= $request->{"chunked"}
Aresult
11
00
4213 234 ▶ my $expect_continue = $request->{expect_continue} // 0;
Condition50%1/2
$request->{"expect_continue"} // 0
l!l
2340
MC/DC0%0/1
$request->{"expect_continue"} // 0
$request->{"expect_continue"}
Truth table50%1/2
A
A= $request->{"expect_continue"}
Aresult
11
00
4214 234 my $continue_sent = 0;
4215 234 my $body_complete = 0;
4216 234 my $bytes_read = 0;
4217 234 my $chunk_size = 65536; # 64KB chunks for large bodies
4218  
4219 # For requests without Content-Length and not chunked, treat as no body
4220 234 ▶ 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
61227
defined $content_length and $content_length > 0
!ll&&!rl&&r
22806
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
4221  
4222 234 weaken(my $weak_self = $self);
4223  
4224 # Return a wrapper that tracks the Future from the async receive
4225 104 ▶ return sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
4226 104 ▶ return Future->done({ type => 'http.disconnect' }) unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 104 104
4227 104 ▶ return Future->done({ type => 'http.disconnect' }) if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 104 104
4228  
4229 # The actual async implementation
4230 104 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=24 SCAR=37.5
4231 104 ▶ return { type => 'http.disconnect' } unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 104 104
4232 104 ▶ return { type => 'http.disconnect' } if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 104 104
4233  
4234 # Check queue first - events from disconnect handler
4235 104 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 104 104
4236 0 return shift @{$weak_self->{receive_queue}};
4237 }
4238  
4239 # If body is already complete, wait for disconnect
4240 104 ▶ if ($body_complete) {
Branch: 1 branch
BranchTrueFalseTotal
if ($body_complete) 4 100 104
4241 4 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 4 0 4
4242 4 $weak_self->{receive_pending} = Future->new;
4243 }
4244  
4245 4 ▶ if ($weak_self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"closed"}) 0 4 4
4246 0 $weak_self->{receive_pending} = undef;
4247 0 return { type => 'http.disconnect' };
4248 }
4249  
4250 4 my $result = await $weak_self->{receive_pending};
4251 # receive_pending may be completed with a value (disconnect event)
4252 # or just done() as a signal
4253 4 ▶ return $result if ref $result eq 'HASH';
Branch: 1 branch
BranchTrueFalseTotal
if ref $result eq "HASH" 4 0 4
4254 # If no value, check queue
4255 0 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 0 0
4256 0 return shift @{$weak_self->{receive_queue}};
4257 }
4258 0 return { type => 'http.disconnect' };
4259 }
4260  
4261 # For requests without body, return empty body immediately
4262 100 ▶ if (!$has_body) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_body) 82 18 100
4263 82 $body_complete = 1;
4264 return {
4265 82 type => 'http.request',
4266 body => '',
4267 more => 0,
4268 };
4269 }
4270  
4271 # Send 100 Continue if client expects it (before reading body)
4272 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
4273 0 $continue_sent = 1;
4274 0 $weak_self->{stream}->write($weak_self->{protocol}->serialize_continue);
4275 }
4276  
4277 # Handle chunked Transfer-Encoding
4278 18 ▶ if ($is_chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_chunked) 1 17 18
4279 return await $weak_self->_read_chunked_body(
4280 'http.request',
4281 0 ▶ sub { { type => 'http.disconnect' } },
Subroutine __ANON__: not called CC=1 SCAR=6.9
4282 1 \$body_complete,
4283 \$bytes_read,
4284 );
4285 }
4286  
4287 # Handle Content-Length based body reading
4288 17 my $remaining = $content_length - $bytes_read;
4289  
4290 17 ▶ if ($remaining <= 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($remaining <= 0) 0 17 17
4291 0 $body_complete = 1;
4292 return {
4293 0 type => 'http.request',
4294 body => '',
4295 more => 0,
4296 };
4297 }
4298  
4299 # Wait for data if buffer is empty
4300 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
4301 13 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 13 0 13
4302 13 $weak_self->{receive_pending} = Future->new;
4303 }
4304 13 await $weak_self->{receive_pending};
4305 13 $weak_self->{receive_pending} = undef;
4306  
4307 # Check queue after waiting
4308 13 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 1 12 13
4309 1 return shift @{$weak_self->{receive_queue}};
4310 }
4311 }
4312  
4313 # Return disconnect if closed while waiting
4314 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
4315 0 return { type => 'http.disconnect' };
4316 }
4317  
4318 # Read up to chunk_size or remaining bytes, whichever is smaller
4319 16 ▶ my $to_read = $remaining < $chunk_size ? $remaining : $chunk_size;
Branch: 1 branch
BranchTrueFalseTotal
$remaining < $chunk_size ? : 11 5 16
4320 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
4321  
4322 16 my $body = substr($weak_self->{buffer}, 0, $to_read, '');
4323 16 $bytes_read += length($body);
4324  
4325 # Check if we've read all the body
4326 16 ▶ my $more = ($bytes_read < $content_length) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$bytes_read < $content_length ? : 12 4 16
4327  
4328 16 ▶ if (!$more) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($more) 4 12 16
4329 4 $body_complete = 1;
4330 }
4331  
4332 return {
4333 16 type => 'http.request',
4334 body => $body,
4335 more => $more,
4336 };
4337 104 })->();
4338  
4339 # Track this Future so we can cancel it on close
4340 104 push @{$weak_self->{receive_futures}}, $future;
4341  
4342 # Clean up completed futures from the list
4343 104 @{$weak_self->{receive_futures}} = grep { !$_->is_ready } @{$weak_self->{receive_futures}};
4344  
4345 104 return $future;
4346 234 };
4347 }
4348  
4349 234 ▶sub _create_send {
Subroutine _create_send: called CC=7 SCAR=19.5
4350 234 my ($self, $request) = @_;
4351  
4352 234 my $chunked = 0;
4353 234 my $expects_trailers = 0;
4354 234 my $seq = 'initial';
4355 # Publish the closure-local $seq on $self so the app-return path in
4356 # _handle_request can tell a completed response from one the app left
4357 # incomplete (see the mirror contract at every $seq assignment below).
4358 234 $self->{h1_seq} = $seq;
4359 234 ▶ my $is_head_request = ($request->{method} // '') eq 'HEAD';
Condition50%1/2
$request->{"method"} // ""
l!l
2340
MC/DC0%0/1
$request->{"method"} // ""
$request->{"method"}
Truth table50%1/2
A
A= $request->{"method"}
Aresult
11
00
4360 234 ▶ my $http_version = $request->{http_version} // '1.1';
Condition50%1/2
$request->{"http_version"} // "1.1"
l!l
2340
MC/DC0%0/1
$request->{"http_version"} // "1.1"
$request->{"http_version"}
Truth table50%1/2
A
A= $request->{"http_version"}
Aresult
11
00
4361 234 my $is_http10 = ($http_version eq '1.0');
4362  
4363 # Check if HTTP/1.0 client requested keep-alive
4364 234 my $client_wants_keepalive = 0;
4365 234 ▶ if ($is_http10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_http10) 3 231 234
4366 3 for my $h (@{$request->{headers}}) {
4367 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
4368 1 $client_wants_keepalive = 1;
4369 1 last;
4370 }
4371 }
4372 }
4373  
4374 234 weaken(my $weak_self = $self);
4375  
4376 466 ▶ return async sub {
Subroutine __ANON__: called CC=49 SCAR=39.1
4377 466 my ($event) = @_;
4378 466 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 466 466
4379 466 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 465 466
4380  
4381 # Reset stall timer on write activity
4382 465 $weak_self->_reset_stall_timer;
4383  
4384 465 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
4650
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
4385  
4386 # Mandatory event validation and sequencing (PAGI spec compliance).
4387 # Order per spec: transport-closed no-op check above runs first.
4388 PAGI::Server::EventValidator::validate_http_send(
4389 465 $event, { extensions => $weak_self->{extensions} });
4390 459 my $seq_before_advance = $seq;
4391 459 $seq = PAGI::Server::EventValidator::advance_http($seq, $event);
4392 454 $weak_self->{h1_seq} = $seq;
4393  
4394 454 ▶ if ($type eq 'http.response.start') {
Branch: 4 branches
BranchTrueFalseTotal
if ($type eq 'http.response.start') { } 215 239 454
elsif ($type eq 'http.response.body') { } 229 10 239
elsif ($type eq 'http.response.trailers') { } 8 2 10
elsif ($type eq 'http.fullflush') { } 2 0 2
4395 215 $weak_self->{response_started} = 1;
4396 $weak_self->{current_connection_state}->_mark_response_started
4397 215 ▶ if $weak_self->{current_connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"current_connection_state"} 215 0 215
4398 215 ▶ $weak_self->{response_status} = $event->{status} // 200; # Track for logging
Condition50%1/2
$event->{"status"} // 200
l!l
2150
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
4399 215 ▶ $expects_trailers = $event->{trailers} // 0;
Condition100%2/2
$event->{"trailers"} // 0
l!l
9206
MC/DC100%1/1
$event->{"trailers"} // 0
$event->{"trailers"}
Truth table100%2/2
A
A= $event->{"trailers"}
Aresult
11
00
4400  
4401 215 ▶ my $status = $event->{status} // 200;
Condition50%1/2
$event->{"status"} // 200
l!l
2150
MC/DC0%0/1
$event->{"status"} // 200
$event->{"status"}
Truth table50%1/2
A
A= $event->{"status"}
Aresult
11
00
4402 215 ▶ my $headers = $event->{headers} // [];
Condition50%1/2
$event->{"headers"} // []
l!l
2150
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
4403 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
4404 # strip any app-supplied values before they reach the wire.
4405 215 $headers = $weak_self->_h1_strip_connection_headers($headers);
4406  
4407 # Check if we need chunked encoding (no Content-Length)
4408 215 my $has_content_length = 0;
4409 215 for my $h (@$headers) {
4410 235 ▶ if (lc($h->[0]) eq 'content-length') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-length") 31 204 235
4411 31 $has_content_length = 1;
4412 31 last;
4413 }
4414 }
4415  
4416 # Add Date header, but only if the app didn't already supply one.
4417 215 my @final_headers = @$headers;
4418 215 ▶ unless (grep { lc($_->[0]) eq 'date' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @final_headers) 214 1 215
4419 214 push @final_headers, ['date', $weak_self->{protocol}->format_date];
4420 }
4421  
4422 # PAGI spec Upgrade companion rule: over HTTP/1.1, a response
4423 # carrying an app-supplied Upgrade header (e.g. 426 Upgrade
4424 # Required) must also carry 'upgrade' among the server-supplied
4425 # Connection tokens -- RFC 9110 requires the pair from any
4426 # Upgrade sender, and the app's own Connection header was
4427 # stripped above. HTTP/1.0 has no upgrade mechanism.
4428 215 ▶ 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 214 215
Condition100%3/3
not $is_http10 and grep {lc $_->[0] eq "upgrade";} @final_headers
!ll&&!rl&&r
32111
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
4429 1 push @final_headers, ['connection', 'upgrade'];
4430 }
4431  
4432 # For HEAD requests, don't use chunked encoding (no body will be sent)
4433 # For HTTP/1.0, don't use chunked encoding - use Connection: close instead
4434 215 ▶ if ($is_head_request || $is_http10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head_request or $is_http10) { } 7 208 215
Condition100%3/3
$is_head_request or $is_http10
l!l&&r!l&&!r
43208
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
4435 7 $chunked = 0;
4436 7 ▶ if ($is_http10) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_http10) 3 4 7
4437 3 ▶ if (!$has_content_length) {
Branch: 2 branches
BranchTrueFalseTotal
if (not $has_content_length) { } 1 2 3
elsif ($client_wants_keepalive) { } 1 1 2
4438 # No Content-Length means we can't do keep-alive
4439 1 push @final_headers, ['connection', 'close'];
4440 } elsif ($client_wants_keepalive) {
4441 # HTTP/1.0 client requested keep-alive and we can honor it
4442 # Must explicitly acknowledge with Connection: keep-alive
4443 1 push @final_headers, ['connection', 'keep-alive'];
4444 }
4445 }
4446 } else {
4447 208 $chunked = !$has_content_length;
4448 }
4449  
4450 my $response = $weak_self->{protocol}->serialize_response_start(
4451 215 $status, \@final_headers, $chunked, $http_version
4452 );
4453  
4454 # Buffer the headers instead of writing them now; they are flushed
4455 # together with the first body write (or at finalization). This
4456 # coalesces the common "start + complete body" case into a single
4457 # stream write instead of one per headers/chunk/terminator.
4458 215 $weak_self->{_resp_pending} = $response;
4459 }
4460 elsif ($type eq 'http.response.body') {
4461 # For HEAD requests, suppress the body
4462 229 ▶ if ($is_head_request) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head_request) 4 225 229
4463 # HEAD has headers but no body, so flush the buffered headers now.
4464 4 $weak_self->_flush_pending_headers;
4465 4 return; # Don't send any body for HEAD
4466 }
4467  
4468 # --- BACKPRESSURE CHECK ---
4469 # Wait for buffer to drain if we're above high watermark
4470 # This prevents unbounded memory growth with slow clients
4471 225 ▶ 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 224 225
4472 1 await $weak_self->_wait_for_drain;
4473 # Re-check connection state after await
4474 1 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
4475 1 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 0 1
4476 }
4477 # --- END BACKPRESSURE CHECK ---
4478  
4479 # Determine body source: body, file, or fh (mutually exclusive)
4480 224 my $body = $event->{body};
4481 224 my $file = $event->{file};
4482 224 my $fh = $event->{fh};
4483 224 ▶ my $offset = $event->{offset} // 0;
Condition100%2/2
$event->{"offset"} // 0
l!l
7217
MC/DC100%1/1
$event->{"offset"} // 0
$event->{"offset"}
Truth table100%2/2
A
A= $event->{"offset"}
Aresult
11
00
4484 224 my $length = $event->{length};
4485  
4486 224 ▶ if (defined $file) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $file) { } 15 209 224
elsif (defined $fh) { } 9 200 209
4487 # File path response - stream from file (async, non-blocking)
4488 # File responses are implicitly complete (more is ignored) on
4489 # success. A failed file/fh send must NOT mark the response
4490 # complete: advance_http already advanced $seq to a terminal
4491 # state before we got here (it can't know the read will fail),
4492 # so on failure we roll $seq back to its pre-event value. That
4493 # lets a conforming app recover with a normal error body
4494 # instead of being permanently locked out by "response already
4495 # complete" for a body that was never actually sent.
4496 15 $weak_self->_flush_pending_headers; # headers before the file body
4497 eval {
4498 # h2 parity (Connection.pm _h2_create_send file arm): fail
4499 # fast on a missing/unreadable file with the same messages,
4500 # ahead of _send_file_response's own -s/open, which would
4501 # otherwise report a less specific error for the same fault.
4502 15 ▶ die "File not found: $file\n" unless -f $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -f $file 1 14 15
4503 14 ▶ die "Cannot read file: $file\n" unless -r $file;
Branch: 1 branch
BranchTrueFalseTotal
unless -r $file 1 13 14
4504  
4505 13 await $weak_self->_send_file_response($file, $offset, $length, $chunked);
4506 13 1;
4507 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; <custom op await>; 1 } } or do { my $error = $@; $seq = $seq_before_advance; $weak_self->{"h1_seq"} = $seq; die $error } 13 2 15
4508 2 my $error = $@;
4509 2 $seq = $seq_before_advance;
4510 2 $weak_self->{h1_seq} = $seq;
4511 2 die $error;
4512 };
4513 }
4514 elsif (defined $fh) {
4515 # Filehandle response - stream from handle (async, non-blocking)
4516 # Filehandle responses are implicitly complete (more is ignored)
4517 # on success; see the file-path comment above for why a failed
4518 # send must roll $seq back instead of leaving it 'complete'.
4519 9 $weak_self->_flush_pending_headers; # headers before the fh body
4520 eval {
4521 9 await $weak_self->_send_fh_response($fh, $offset, $length, $chunked);
4522 7 1;
4523 9 ▶ } or do {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { <custom op await>; 1 } } or do { my $error = $@; $seq = $seq_before_advance; $weak_self->{"h1_seq"} = $seq; die $error } 7 2 9
4524 2 my $error = $@;
4525 2 $seq = $seq_before_advance;
4526 2 $weak_self->{h1_seq} = $seq;
4527 2 die $error;
4528 };
4529 }
4530 else {
4531 # Traditional body response
4532 200 ▶ $body //= '';
Condition50%1/2
$body //= ""
l!l
2000
MC/DC0%0/1
$body //= ""
$body
Truth table50%1/2
A
A= $body
Aresult
11
00
4533 200 ▶ my $more = $event->{more} // 0;
Condition100%2/2
$event->{"more"} // 0
l!l
17921
MC/DC100%1/1
$event->{"more"} // 0
$event->{"more"}
Truth table100%2/2
A
A= $event->{"more"}
Aresult
11
00
4534  
4535 200 $weak_self->{_response_size} += length($body);
4536  
4537 # Coalesce any buffered headers, the body (chunk framing if
4538 # chunked), and the final terminator into a single stream write.
4539 # The common start + complete-body response becomes one write
4540 # rather than three.
4541 200 my $out = $weak_self->{_resp_pending};
4542 200 ▶ $out = '' unless defined $out;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $out 14 186 200
4543 200 $weak_self->{_resp_pending} = undef;
4544  
4545 200 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 183 17 200
4546 183 ▶ if (length $body) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $body) 182 1 183
4547 182 my $len = sprintf("%x", length($body));
4548 182 $out .= "$len\r\n$body\r\n";
4549 }
4550 183 ▶ if (!$more && !$expects_trailers) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($more or $expects_trailers) 163 20 183
Condition100%3/3
$more or $expects_trailers
l!l&&r!l&&!r
137163
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
4551 163 $out .= "0\r\n\r\n";
4552 }
4553 }
4554 else {
4555 17 $out .= $body;
4556 }
4557  
4558 200 ▶ $weak_self->{stream}->write($out) if length $out;
Branch: 1 branch
BranchTrueFalseTotal
if length $out 200 0 200
4559 200 $weak_self->_notify_transport_write;
4560 }
4561 }
4562 elsif ($type eq 'http.response.trailers') {
4563 # No "return unless $expects_trailers" guard here: advance_http
4564 # (called unconditionally above, line ~2886) already croaks for
4565 # undeclared trailers -- "cannot send http.response.trailers:
4566 # trailers were not declared or body is not complete" -- before
4567 # execution ever reaches this branch, so the guard was dead code.
4568  
4569 8 ▶ if ($is_head_request) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_head_request) 1 7 8
4570 # HEAD: accept-and-discard, per PAGI Www.pod's HEAD rule
4571 # (mirrors the h2 HEAD block from Phase 2 Task 1). The
4572 # generic advance_http call above already advanced the
4573 # machine; transmit nothing.
4574 1 return;
4575 }
4576  
4577 7 ▶ unless ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($chunked) 1 6 7
4578 # Trailers ride chunked framing only (RFC 7230); a
4579 # content-length response has no place to put them, and
4580 # silently dropping promised trailers lies to the
4581 # application. advance_http already advanced $seq to
4582 # 'complete' generically above (it can't know the framing
4583 # can't carry trailers) -- roll it back to its pre-event
4584 # value, same guard/hoist pattern used by the file/fh arms
4585 # above, so the machine stays 'awaiting_trailers' and never
4586 # claims a response completed that never actually went out.
4587 # advance_http is a pure function with no side effects beyond
4588 # its return value, which is what makes advance-then-rollback
4589 # safe.
4590 1 $seq = $seq_before_advance;
4591 1 $weak_self->{h1_seq} = $seq;
4592 1 die "http.response.trailers requires chunked framing (response declared content-length)\n";
4593 }
4594  
4595 # RFC 9110 section 6.5.1 additionally forbids connection-specific/
4596 # framing fields in trailers outright, on any HTTP version -- not
4597 # just the PAGI spec's h1 response-header rule this strip
4598 # otherwise exists for. Strip at ingestion, same placement as
4599 # every h1 response-header site above.
4600 6 ▶ my $trailer_headers = $weak_self->_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
4601  
4602 # Send final chunk + trailers (prepend any still-buffered headers).
4603 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
4604 6 $weak_self->{_resp_pending} = undef;
4605 6 $trailers .= "0\r\n";
4606  
4607 6 my @validated_trailers;
4608 6 for my $header (@$trailer_headers) {
4609 3 my ($name, $value) = @$header;
4610 3 $name = _validate_header_name($name);
4611 3 $value = _validate_header_value($value);
4612 3 push @validated_trailers, [$name, $value];
4613 }
4614 6 $trailers .= $weak_self->{protocol}->serialize_trailers(\@validated_trailers);
4615  
4616 6 $weak_self->{stream}->write($trailers);
4617 }
4618 elsif ($type eq 'http.fullflush') {
4619 # Fullflush extension - force immediate TCP buffer flush.
4620 # validate_http_send (called above, unconditionally) already
4621 # croaks "Extension not enabled: fullflush" when the extension
4622 # isn't advertised, so no re-check is needed here.
4623  
4624 # Force flush by ensuring TCP_NODELAY and flushing any pending writes
4625 2 my $handle = $weak_self->{stream}->write_handle;
4626 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
4627 # Ensure TCP_NODELAY is set to disable Nagle buffering
4628 2 require Socket;
4629 2 $handle->setsockopt(Socket::IPPROTO_TCP(), Socket::TCP_NODELAY(), 1);
4630 }
4631  
4632 # In IO::Async, writes are queued and sent when the event loop allows.
4633 # The above TCP_NODELAY ensures no Nagle buffering delays.
4634 # For this reference implementation, we return immediately as the
4635 # write buffer will be flushed by the event loop.
4636 }
4637  
4638 443 return;
4639 234 };
4640 }
4641  
4642 # Flush any response headers buffered by http.response.start that were not yet
4643 # paired with a body write (HEAD/file/fh paths, started-but-incomplete responses).
4644 241 ▶sub _flush_pending_headers {
Subroutine _flush_pending_headers: called CC=3 SCAR=11.0
4645 241 my ($self) = @_;
4646 241 my $pending = $self->{_resp_pending};
4647 241 ▶ return unless defined $pending && length $pending;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $pending and length $pending 212 29 241
Condition66%2/3
defined $pending and length $pending
!ll&&!rl&&r
212029
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
4648 29 $self->{_resp_pending} = undef;
4649 29 $self->{stream}->write($pending);
4650 }
4651  
4652 27 ▶sub _send_error_response {
Subroutine _send_error_response: called CC=4 SCAR=13.9
4653 27 my ($self, $status, $message) = @_;
4654  
4655 27 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 27 27
4656 27 ▶ return if $self->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"response_started"} 0 27 27
4657  
4658 27 my $body = $message;
4659 my $headers = [
4660 ['content-type', 'text/plain'],
4661 ['content-length', length($body)],
4662 27 ['date', $self->{protocol}->format_date],
4663 ];
4664  
4665 27 my $response = $self->{protocol}->serialize_response_start($status, $headers, 0);
4666 27 $response .= $body;
4667  
4668 27 $self->{stream}->write($response);
4669 27 $self->{response_started} = 1;
4670 # A server-synthesized response is still "this request's response started".
4671 $self->{current_connection_state}->_mark_response_started
4672 27 ▶ if $self->{current_connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"current_connection_state"} 16 11 27
4673 27 $self->{response_status} = $status; # Track for logging
4674 }
4675  
4676 323 ▶sub _write_access_log {
Subroutine _write_access_log: called CC=16 SCAR=33.0
4677 323 my ($self) = @_;
4678  
4679 323 ▶ return unless $self->{access_log};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"access_log"} 12 311 323
4680 311 ▶ return unless $self->{current_request};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"current_request"} 0 311 311
4681  
4682 311 my $request = $self->{current_request};
4683  
4684 # Calculate request duration
4685 311 my $duration = 0;
4686 311 ▶ if ($self->{request_start}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"request_start"}) 311 0 311
4687 311 $duration = tv_interval($self->{request_start});
4688 }
4689  
4690 # Per-second cached CLF timestamp
4691 311 my $now = time();
4692 311 ▶ if ($now != $_cached_log_time) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now != $_cached_log_time) 100 211 311
4693 100 $_cached_log_time = $now;
4694 100 my @gmt = gmtime($now);
4695 100 my @months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
4696 100 $_cached_log_timestamp = sprintf("%02d/%s/%04d:%02d:%02d:%02d +0000",
4697 $gmt[3], $months[$gmt[4]], $gmt[5] + 1900,
4698 $gmt[2], $gmt[1], $gmt[0]);
4699 }
4700  
4701 my $info = {
4702 client_ip => $self->{client_host} // ($self->{transport_type} eq 'unix' ? 'unix' : '-'),
4703 timestamp => $_cached_log_timestamp,
4704 method => $request->{method} // '-',
4705 path => $request->{raw_path} // '/',
4706 query => $request->{query_string},
4707 http_version => $request->{http_version} // '1.1',
4708 status => $self->{response_status} // '-',
4709 size => $self->{_response_size} // 0,
4710 duration => $duration,
4711 311 ▶ request_headers => $request->{headers} // [],
Branch: 1 branch
BranchTrueFalseTotal
$self->{'transport_type'} eq 'unix' ? : 2 0 2
Condition64%9/14
$self->{"client_host"} // ($self->{"transport_type"} eq "unix" ? "unix" : "-")
l!l
3092
$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/DC100%1/1
$self->{"client_host"} // ($self->{"transport_type"} eq "unix" ? "unix" : "-")
$self->{"client_host"}
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 table100%2/2
A
A= $self->{"client_host"}
Aresult
11
00
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
4712 };
4713  
4714 311 my $formatter = $self->{_access_log_formatter};
4715 311 ▶ if ($formatter) {
Branch: 1 branch
BranchTrueFalseTotal
if ($formatter) { } 311 0 311
4716 311 print {$self->{access_log}} $formatter->($info), "\n";
4717 }
4718 else {
4719 # Fallback (should not happen with properly initialized server)
4720 0 my $path = $info->{path};
4721 0 my $query = $info->{query};
4722 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
4723 0 print {$self->{access_log}} "$info->{client_ip} - - [$info->{timestamp}] \"$info->{method} $path\" $info->{status} $info->{duration}s\n";
4724 }
4725 }
4726  
4727 # Reasons passed to _handle_disconnect only for teardown after a clean finish
4728 # (the app has already returned). They are completions, not abnormal disconnects,
4729 # and must not surface as a disconnect reason to the application.
4730 156 my %COMPLETION_REASON = map { ($_ => 1) } qw(
4731 request_complete
4732 stream_complete
4733 session_complete
4734 );
4735  
4736 # Build the app-facing websocket.disconnect event for a server-detected close.
4737 # The code and reason come from the close the server initiated; the defaults are
4738 # the RFC 6455 "abnormal closure, no status received" pair (1006 / empty), used
4739 # when the connection dropped with no close handshake (timeout, TCP FIN).
4740 56 ▶sub _ws_disconnect_event {
Subroutine _ws_disconnect_event: called CC=3 SCAR=11.0
4741 56 my ($self) = @_;
4742 return {
4743 type => 'websocket.disconnect',
4744 code => $self->{ws_disconnect_code} // 1006,
4745 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
4746 };
4747 }
4748  
4749 880 ▶sub _handle_disconnect {
Subroutine _handle_disconnect: called CC=25 SCAR=32.5
4750 880 my ($self, $reason) = @_;
4751  
4752 # Idempotency guard - prevent duplicate disconnect handling
4753 # Multiple paths can trigger disconnect (timeout, protocol error, session end)
4754 880 ▶ return if $self->{_disconnect_handled};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_disconnect_handled"} 371 509 880
4755 509 $self->{_disconnect_handled} = 1;
4756  
4757 # Auto-detect server shutdown (PAGI spec compliance)
4758 # If no explicit reason and server is shutting down, use server_shutdown
4759 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
4760 0 $reason = 'server_shutdown';
4761 }
4762  
4763 # Default reason is client_closed (TCP FIN received)
4764 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
4765  
4766 # A clean completion is not an abnormal disconnect: don't surface its reason.
4767 509 my $is_completion = $COMPLETION_REASON{$reason};
4768  
4769 # Mark HTTP connection state as disconnected (abnormal only).
4770 # Only for HTTP - WebSocket/SSE have their own patterns.
4771 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"}) 54 455 509
Condition66%4/6
$self->{"current_connection_state"} and not $self->{"websocket_mode"} and not $self->{"sse_mode"}
!ll&&!rl&&r
455054
$self->{"current_connection_state"} and not $self->{"websocket_mode"}
!ll&&!rl&&r
455054
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
4772 54 ▶ $self->{current_connection_state}->_mark_disconnected($reason)
Branch: 1 branch
BranchTrueFalseTotal
unless $is_completion 30 24 54
4773 unless $is_completion;
4774 }
4775  
4776 # HTTP/2: connection-level teardown (server shutdown, socket error, ...)
4777 # sweeps every open stream's own connection_state with this reason, so a
4778 # stream still mid-response when the whole connection dies still reports
4779 # why. _mark_disconnected is idempotent -- a stream _h2_on_close already
4780 # took to a terminal state (complete, or its own client_closed/server_error)
4781 # keeps that first reason; only still-open streams pick this one up.
4782 # WebSocket/SSE streams never attach a connection_state (N/A per spec),
4783 # so the guard on $stream->{connection_state} skips them naturally.
4784 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
4785 200 for my $stream (values %{$self->{h2_streams}}) {
4786 $stream->{connection_state}->_mark_disconnected($reason)
4787 70 ▶ if $stream->{connection_state};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"connection_state"} 5 65 70
4788 }
4789 }
4790  
4791 # Cancel any pending drain waiters (backpressure) AFTER connection state
4792 # is marked above: resolving a parked waiter can synchronously resume an
4793 # awaiting app coroutine (Future::AsyncAwait resumes inline off ->done),
4794 # and that resumed app's first act may be to read is_connected() /
4795 # disconnect_reason() -- those must already reflect this disconnect, not
4796 # a stale "still connected" snapshot from before it was detected.
4797 509 $self->_cancel_drain_waiters($reason);
4798  
4799 # Record the abnormal reason so the WebSocket disconnect event reports it
4800 # (instead of the old empty string). SSE tracks its own reason at the
4801 # detection sites via sse_disconnect_reason.
4802 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
4803 22 $self->{ws_disconnect_reason} = $reason;
4804 }
4805  
4806 # Determine disconnect event type based on mode
4807 509 my $disconnect_event;
4808 509 ▶ if ($self->{websocket_mode}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'websocket_mode'}) { } 26 483 509
elsif ($self->{'sse_mode'}) { } 33 450 483
4809 26 $disconnect_event = $self->_ws_disconnect_event;
4810 } elsif ($self->{sse_mode}) {
4811 # A completed decline is not an abnormal end -- the spec says a
4812 # decline delivers no events at all, so leave $disconnect_event
4813 # unset rather than synthesizing sse.disconnect for it.
4814 $disconnect_event = {
4815 type => 'sse.disconnect',
4816 reason => $self->{sse_disconnect_reason} // 'client_closed',
4817 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
4818 } else {
4819 450 $disconnect_event = { type => 'http.disconnect' };
4820 }
4821  
4822 # Queue disconnect event (do this even if already closed)
4823 509 ▶ push @{$self->{receive_queue}}, $disconnect_event if $disconnect_event;
Branch: 1 branch
BranchTrueFalseTotal
if $disconnect_event 496 13 509
4824  
4825 # Complete any pending receive
4826 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
4827 29 $self->{receive_pending}->done($disconnect_event);
4828 29 $self->{receive_pending} = undef;
4829 }
4830 }
4831  
4832 # Send a WebSocket close frame with status code and optional reason
4833 # Per RFC 6455 Section 7.4, common codes:
4834 # 1000 - Normal closure
4835 # 1007 - Invalid frame payload data (e.g., invalid UTF-8)
4836 # 1009 - Message too big
4837 # 1011 - Unexpected condition
4838 4 ▶sub _send_close_frame {
Subroutine _send_close_frame: called CC=4 SCAR=14.2
4839 4 my ($self, $code, $reason) = @_;
4840 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
4841  
4842 4 ▶ return unless $self->{stream};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"stream"} 0 4 4
4843 4 ▶ return if $self->{close_sent};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"close_sent"} 0 4 4
4844  
4845 # Remember the wire code so the app-facing websocket.disconnect event reports
4846 # the same code the peer received, rather than the 1006 abnormal-close default.
4847 4 $self->{ws_disconnect_code} = $code;
4848  
4849 4 my $frame = Protocol::WebSocket::Frame->new(
4850 type => 'close',
4851 buffer => pack('n', $code) . $reason,
4852 );
4853  
4854 4 $self->{stream}->write($frame->to_bytes);
4855 4 $self->{close_sent} = 1;
4856 }
4857  
4858 881 ▶sub _close {
Subroutine _close: called CC=23 SCAR=31.5
4859 881 my ($self) = @_;
4860  
4861 # Idempotency guard for cleanup, kept separate from the "closed" flag
4862 # itself: _handle_disconnect_and_close may already have set {closed} = 1
4863 # before calling here, so the send-side closed-check sees it early.
4864 881 ▶ return if $self->{_cleanup_done};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_cleanup_done"} 372 509 881
4865 509 $self->{_cleanup_done} = 1;
4866 509 $self->{closed} = 1;
4867  
4868 # Cancel pending drain waiters early (before other cleanup)
4869 509 $self->_cancel_drain_waiters('connection closing');
4870  
4871 # Clean up HTTP/2 per-stream state
4872 509 ▶ if ($self->{h2_streams}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_streams"}) 509 0 509
4873 509 for my $stream (values %{$self->{h2_streams}}) {
4874 # Whole connection is going away -- stop every WS/SSE stream's
4875 # keepalive (and SSE idle) timers so none leak past this teardown
4876 # sweep.
4877 70 ▶ $self->_h2_stop_ws_keepalive($stream) if $stream->{is_websocket};
Branch: 1 branch
BranchTrueFalseTotal
if $stream->{"is_websocket"} 42 28 70
4878 70 ▶ if ($stream->{is_sse}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"is_sse"}) 21 49 70
4879 21 $self->_h2_stop_sse_keepalive($stream);
4880 21 $self->_h2_stop_sse_idle_timer($stream);
4881 }
4882  
4883 70 ▶ if ($stream->{body_pending} && !$stream->{body_pending}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready) 12 58 70
Condition100%3/3
$stream->{"body_pending"} and not $stream->{"body_pending"}->is_ready
!ll&&!rl&&r
54412
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
4884 my $event = $stream->{is_sse}
4885 12 ▶ ? { type => 'sse.disconnect', reason => 'client_closed' }
Branch: 1 branch
BranchTrueFalseTotal
$stream->{'is_sse'} ? : 3 9 12
4886 : { type => 'http.disconnect' };
4887 12 $stream->{body_pending}->done($event);
4888 }
4889 # Release producers blocked on per-stream backpressure so they
4890 # don't hang on a connection that is going away.
4891 70 $self->_h2_resolve_stream_drain_waiters($stream);
4892 # Same for a send() parked in the deferred trailers branch --
4893 # without this, a peer that just drops the TCP connection (FIN,
4894 # idle timeout, shutdown) never fires on_stream_close (no h2
4895 # protocol event at all), so _h2_on_close's own release never
4896 # runs, and the parked send hangs forever.
4897 70 $self->_h2_resolve_stream_trailer_wait($stream);
4898 # Drop (don't fire) the app's on_drain fires: the connection is going
4899 # away, not draining. Also break the $stream <-> transport_state cycle
4900 # so the stream state is freed when h2_streams is deleted below.
4901 70 $stream->{transport_drain_fires} = [];
4902 70 delete $stream->{transport_state};
4903 }
4904 509 delete $self->{h2_streams};
4905 }
4906 509 ▶ if ($self->{h2_session}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"h2_session"}) 202 307 509
4907 202 eval { $self->{h2_session}->terminate(0) };
4908 202 delete $self->{h2_session};
4909 }
4910  
4911 # Clean up WebSocket frame parser to free memory immediately
4912 509 delete $self->{websocket_frame};
4913  
4914 # Remove from server's connection list (O(1) hash delete)
4915 509 ▶ if ($self->{server}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"server"}) 509 0 509
4916 509 delete $self->{server}{connections}{refaddr($self)};
4917  
4918 # Signal drain complete if this was the last connection during shutdown
4919 509 ▶ 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 508 509
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
50801
$self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0 and $self->{"server"}{"drain_complete"}
!ll&&!rl&&r
3451631
$self->{"server"}{"shutting_down"} and keys %{$$self{"server"}{"connections"};} == 0
!ll&&!rl&&r
33114164
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
4920 178 keys %{$self->{server}{connections}} == 0 &&
4921 $self->{server}{drain_complete} &&
4922 !$self->{server}{drain_complete}->is_ready) {
4923 1 $self->{server}{drain_complete}->done;
4924 }
4925 }
4926  
4927 # Stop idle timer
4928 509 $self->_stop_idle_timer;
4929  
4930 # Stop stall timer
4931 509 $self->_stop_stall_timer;
4932  
4933 # Stop WS/SSE idle timers
4934 509 $self->_stop_ws_idle_timer;
4935 509 $self->_stop_sse_idle_timer;
4936  
4937 # Stop keepalive timers
4938 509 $self->_stop_ws_keepalive;
4939 509 $self->_stop_sse_keepalive;
4940  
4941 # Note: _close is resource cleanup ONLY. Callers should use
4942 # _handle_disconnect_and_close() which handles both protocol
4943 # notification and cleanup.
4944  
4945 # Determine disconnect event type based on mode
4946 509 my $disconnect_event;
4947 509 ▶ if ($self->{websocket_mode}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'websocket_mode'}) { } 27 482 509
elsif ($self->{'sse_mode'}) { } 33 449 482
4948 27 $disconnect_event = $self->_ws_disconnect_event;
4949 } elsif ($self->{sse_mode}) {
4950 # See _handle_disconnect: a completed decline delivers no events.
4951 $disconnect_event = {
4952 type => 'sse.disconnect',
4953 reason => $self->{sse_disconnect_reason} // 'client_closed',
4954 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
4955 } else {
4956 449 $disconnect_event = { type => 'http.disconnect' };
4957 }
4958  
4959 # Cancel any tracked receive Futures that are still pending
4960 509 ▶ if ($disconnect_event) {
Branch: 1 branch
BranchTrueFalseTotal
if ($disconnect_event) 496 13 509
4961 496 for my $future (@{$self->{receive_futures}}) {
4962 31 ▶ if (!$future->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($future->is_ready) 0 31 31
4963 # Complete with disconnect event instead of cancelling
4964 # This allows the async sub to complete cleanly
4965 0 $future->done($disconnect_event);
4966 }
4967 }
4968 }
4969 509 $self->{receive_futures} = [];
4970  
4971 509 ▶ if ($self->{stream}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"stream"}) 509 0 509
4972 509 $self->{stream}->close_when_empty;
4973 }
4974 }
4975  
4976 # Combined disconnect and close - use this from callbacks where $weak_self may
4977 # become undefined after _handle_disconnect completes its Future callbacks.
4978 # This method holds a strong reference to $self throughout the operation.
4979 852 ▶sub _handle_disconnect_and_close {
Subroutine _handle_disconnect_and_close: called CC=1 SCAR=0.0
4980 852 my ($self, $reason) = @_;
4981  
4982 # Mark the transport closed before notifying: _handle_disconnect below
4983 # completes any pending receive(), which can synchronously resume the
4984 # app coroutine (it may run straight through a subsequent send()), so
4985 # the send-side closed-check needs "closed" to already be true at that
4986 # point (spec order: closed-check precedes validation). Resource
4987 # cleanup itself still happens in _close, gated by its own idempotency
4988 # flag so it isn't skipped by this early flip.
4989 852 $self->{closed} = 1;
4990  
4991 852 $self->_handle_disconnect($reason);
4992 852 $self->_close;
4993 }
4994  
4995 #
4996 # TLS Support Methods
4997 #
4998  
4999 45 ▶sub _extract_tls_info {
Subroutine _extract_tls_info: called CC=17 SCAR=32.3
5000 45 my ($self) = @_;
5001  
5002 45 my $stream = $self->{stream};
5003 45 my $handle = $stream->read_handle;
5004  
5005 # Check if handle is an IO::Socket::SSL
5006 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
5007  
5008 45 my $tls_info = {
5009 server_cert => undef,
5010 client_cert_chain => [],
5011 client_cert_name => undef,
5012 client_cert_error => undef,
5013 tls_version => undef,
5014 cipher_suite => undef,
5015 };
5016  
5017 # Get TLS version - IO::Socket::SSL returns something like 'TLSv1_3'
5018 45 ▶ if (my $version_str = $handle->get_sslversion) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $version_str = $handle->get_sslversion) 45 0 45
5019 # Map version string to numeric value per TLS spec
5020 45 my %version_map = (
5021 'SSLv3' => 0x0300,
5022 'TLSv1' => 0x0301,
5023 'TLSv1_1' => 0x0302,
5024 'TLSv1_2' => 0x0303,
5025 'TLSv1_3' => 0x0304,
5026 );
5027 45 $tls_info->{tls_version} = $version_map{$version_str};
5028 }
5029  
5030 # Cipher suite (numeric IANA id). Net::SSLeay/IO::Socket::SSL expose only the
5031 # cipher *name*, not the 16-bit id the spec asks for. For TLS 1.3 the OpenSSL
5032 # name IS the IANA name and the registry is frozen at five suites, so we map
5033 # those exactly. For TLS 1.2 the names are OpenSSL-specific (a large, shifting
5034 # set), so we leave cipher_suite undef -- the spec permits undef when the
5035 # server cannot determine the value.
5036 45 ▶ if (my $cipher_name = $handle->get_cipher) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $cipher_name = $handle->get_cipher) 45 0 45
5037 45 my %tls13_cipher_suites = (
5038 'TLS_AES_128_GCM_SHA256' => 0x1301,
5039 'TLS_AES_256_GCM_SHA384' => 0x1302,
5040 'TLS_CHACHA20_POLY1305_SHA256' => 0x1303,
5041 'TLS_AES_128_CCM_SHA256' => 0x1304,
5042 'TLS_AES_128_CCM_8_SHA256' => 0x1305,
5043 );
5044 $tls_info->{cipher_suite} = $tls13_cipher_suites{$cipher_name}
5045 45 ▶ if exists $tls13_cipher_suites{$cipher_name};
Branch: 1 branch
BranchTrueFalseTotal
if exists $tls13_cipher_suites{$cipher_name} 45 0 45
5046 }
5047  
5048 # Get server certificate (our certificate)
5049 # IO::Socket::SSL uses sock_certificate() for the server's own cert
5050 45 eval {
5051 45 my $cert = $handle->sock_certificate;
5052 45 ▶ if ($cert) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cert) 45 0 45
5053 45 require Net::SSLeay;
5054 45 $tls_info->{server_cert} = Net::SSLeay::PEM_get_string_X509($cert);
5055 }
5056 };
5057 45 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 45 45
5058 0 $self->_log(warn => "TLS server certificate extraction error: $@");
5059 }
5060  
5061 # Get client certificate if provided
5062 45 eval {
5063 45 my $client_cert = $handle->peer_certificate;
5064 45 ▶ if ($client_cert) {
Branch: 1 branch
BranchTrueFalseTotal
if ($client_cert) 8 37 45
5065 8 require Net::SSLeay;
5066  
5067 # Get client cert chain
5068 8 my @chain;
5069 8 push @chain, Net::SSLeay::PEM_get_string_X509($client_cert);
5070  
5071 # Try to get additional certs in chain
5072 8 ▶ if (my $ssl = $handle->_get_ssl_object) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ssl = $handle->_get_ssl_object) 8 0 8
5073 8 my $chain_obj = Net::SSLeay::get_peer_cert_chain($ssl);
5074 8 ▶ if ($chain_obj) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chain_obj) 0 8 8
5075 0 for my $i (0 .. Net::SSLeay::sk_X509_num($chain_obj) - 1) {
5076 0 my $cert = Net::SSLeay::sk_X509_value($chain_obj, $i);
5077 0 ▶ push @chain, Net::SSLeay::PEM_get_string_X509($cert) if $cert;
Branch: 1 branch
BranchTrueFalseTotal
if $cert 0 0 0
5078 }
5079 }
5080 }
5081 8 $tls_info->{client_cert_chain} = \@chain;
5082  
5083 # Get client cert DN (Subject)
5084 8 my $subject = Net::SSLeay::X509_NAME_oneline(
5085 Net::SSLeay::X509_get_subject_name($client_cert)
5086 );
5087 8 ▶ $tls_info->{client_cert_name} = $subject if $subject;
Branch: 1 branch
BranchTrueFalseTotal
if $subject 8 0 8
5088  
5089 # Check for verification errors
5090 8 my $verify_result = $handle->get_sslversion_int;
5091 # Actually, use verify_result
5092 8 ▶ if (my $ssl = $handle->_get_ssl_object) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $ssl = $handle->_get_ssl_object) 8 0 8
5093 8 my $result = Net::SSLeay::get_verify_result($ssl);
5094 8 ▶ if ($result != 0) { # X509_V_OK = 0
Branch: 1 branch
BranchTrueFalseTotal
if ($result != 0) 0 8 8
5095 0 $tls_info->{client_cert_error} = Net::SSLeay::X509_verify_cert_error_string($result);
5096 }
5097 }
5098 }
5099 };
5100 45 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 45 45
5101 0 $self->_log(warn => "TLS client certificate extraction error: $@");
5102 }
5103  
5104 45 $self->{tls_info} = $tls_info;
5105 }
5106  
5107 292 ▶sub _get_scheme {
Subroutine _get_scheme: called CC=2 SCAR=6.9
5108 292 my ($self) = @_;
5109  
5110 292 ▶ return $self->{tls_enabled} ? 'https' : 'http';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tls_enabled'} ? : 44 248 292
5111 }
5112  
5113 88 ▶sub _get_ws_scheme {
Subroutine _get_ws_scheme: called CC=2 SCAR=7.2
5114 88 my ($self) = @_;
5115  
5116 88 ▶ return $self->{tls_enabled} ? 'wss' : 'ws';
Branch: 1 branch
BranchTrueFalseTotal
$self->{'tls_enabled'} ? : 0 88 88
5117 }
5118  
5119 536 ▶sub _get_extensions_for_scope {
Subroutine _get_extensions_for_scope: called CC=4 SCAR=14.0
5120 536 my ($self) = @_;
5121  
5122 536 my %extensions = %{$self->{extensions}};
5123  
5124 # Add TLS info to extensions if this is a TLS connection
5125 536 ▶ if ($self->{tls_enabled} && $self->{tls_info}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($self->{'tls_enabled'} and $self->{'tls_info'}) { } 45 491 536
elsif (not $self->{'tls_enabled'}) { } 491 0 491
Condition66%2/3
$self->{"tls_enabled"} and $self->{"tls_info"}
!ll&&!rl&&r
491045
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
5126 45 $extensions{tls} = $self->{tls_info};
5127 }
5128 # Remove tls extension if not a TLS connection (per spec)
5129 elsif (!$self->{tls_enabled}) {
5130 491 delete $extensions{tls};
5131 }
5132  
5133 536 return \%extensions;
5134 }
5135  
5136 #
5137 # SSE (Server-Sent Events) Support Methods
5138 #
5139  
5140 58 ▶async sub _handle_sse_request {
Subroutine _handle_sse_request: called CC=12 SCAR=26.0
5141 58 my ($self, $request) = @_;
5142  
5143 58 $self->{sse_mode} = 1;
5144 58 $self->_stop_idle_timer; # SSE connections are long-lived
5145 58 $self->_start_sse_idle_timer; # Start SSE-specific idle timer if configured
5146  
5147 58 my $scope = $self->_create_sse_scope($request);
5148 58 my $receive = $self->_create_sse_receive($request);
5149 58 my $send = $self->_create_sse_send($request);
5150  
5151 58 my $app_failed = 0;
5152 58 eval {
5153 58 await $self->{app}->($scope, $receive, $send);
5154 };
5155  
5156 58 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 0 58 58
5157 # If SSE not yet started, send HTTP error
5158 0 ▶ if (!$self->{sse_started}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"sse_started"}) 0 0 0
5159 0 $self->_send_error_response(500, "Internal Server Error");
5160 }
5161 0 $self->_log(error => "PAGI application error (SSE): $error");
5162 # An exception is not a clean end -- never keep the connection alive
5163 # after one, exactly as the plain HTTP request path does.
5164 0 $app_failed = 1;
5165 }
5166  
5167 # End the stream (no-op if an explicit sse.close already finished it).
5168 58 $self->_finish_sse_stream('stream_complete');
5169  
5170 # The application produced no response at all: no sse.start, and no
5171 # completed decline. That is the same protocol error the plain HTTP path
5172 # reports, and it must never reach the keep-alive branch below -- the
5173 # client is still waiting for a response, so handing it back a connection
5174 # with zero bytes written would hang it until the idle timeout, or forever
5175 # when timeout => 0. A COMPLETED decline set response_started and closed
5176 # the connection itself, so it never lands here; a decline that started
5177 # but never sent its terminal body does, and its buffered headers are
5178 # about to be discarded, so it is equally unanswerable.
5179 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
5180 2 ▶ unless ($self->{closed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"closed"}) 2 0 2
5181 2 $self->_log(error => "PAGI application returned without starting an SSE stream or a response");
5182 2 $self->_send_error_response(500, "Internal Server Error");
5183 }
5184 2 $self->_write_access_log;
5185 # Notify server that request completed (for max_requests tracking)
5186 2 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 2 0 2
5187 2 $self->_handle_disconnect_and_close('server_error');
5188 2 return;
5189 }
5190  
5191 # Write access log entry (logs at stream end with total duration). Must
5192 # precede the reset below, which clears the request it logs.
5193 56 $self->_write_access_log;
5194  
5195 # Notify server that request completed (for max_requests tracking). One
5196 # call site covers both fates below (keep-alive and close) -- the SSE
5197 # "request" completes here, when the stream ends, not at sse.start.
5198 56 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 56 0 56
5199  
5200 # Design section 11.6: a CLEAN end (the application returned, or it sent
5201 # sse.close) honors the "Connection: keep-alive" header the server itself
5202 # emitted on sse.start -- the terminator is written above and the
5203 # connection returns to ordinary request handling. Keep-alive still yields
5204 # to the usual overrides: an application exception, a transport already
5205 # gone (client disconnect, timeout, write error, server shutdown), a
5206 # client "Connection: close", and HTTP/1.0 semantics.
5207 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
5208 25 $self->_reset_after_sse_stream;
5209 25 return;
5210 }
5211  
5212 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
5213 156 }
5214  
5215 # Idempotently end an SSE stream: write the chunked terminator (HTTP/1.1) and
5216 # release the stream's timers so nothing can write after the terminator.
5217 # Called both by the on-return path above and by an explicit sse.close event
5218 # (which ends the stream while the application is still running), so it must
5219 # run exactly once and must NOT decide the connection's fate -- that decision
5220 # belongs to _handle_sse_request, once the application has actually returned.
5221 69 ▶sub _finish_sse_stream {
Subroutine _finish_sse_stream: called CC=6 SCAR=18.0
5222 69 my ($self, $reason) = @_;
5223 69 ▶ return if $self->{sse_finished};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"sse_finished"} 11 58 69
5224 58 $self->{sse_finished} = 1;
5225 58 $self->{sse_finish_reason} = $reason;
5226  
5227 # Nothing may reach the wire after the terminating chunk.
5228 58 $self->_stop_sse_keepalive;
5229 58 $self->_stop_sse_idle_timer;
5230  
5231 # Send chunked terminator if SSE was started and the stream is still writable
5232 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
5233 $self->{stream} && $self->{stream}->write_handle) {
5234 35 $self->{stream}->write("0\r\n\r\n");
5235 }
5236 }
5237  
5238 # Per-request state that must not survive a kept-alive HTTP/1.1 SSE stream
5239 # (design section 11.6). The connection is about to serve an ordinary request
5240 # on the same socket, so every field the stream touched has to be back at its
5241 # constructor value. Inventory, as a constraint list:
5242 #
5243 # SSE stream flags sse_mode, sse_started, sse_finished, sse_finish_reason,
5244 # sse_close_sent, sse_disconnect_reason
5245 # SSE decline state sse_decline_started/status/headers/body
5246 # SSE timers/writer sse_keepalive_timer + comment, sse_idle_timer,
5247 # sse_keepalive_writer (closes over this stream's framing)
5248 # Response state handling_request, response_started, h1_seq,
5249 # _resp_pending, response_status, _response_size
5250 # Request state request_start, current_request, request_future,
5251 # current_connection_state, current_transport_state
5252 # Receive state receive_queue, receive_pending, receive_futures
5253 # Idle timeout the between-requests idle timer, removed when the
5254 # stream started, must be re-armed
5255 #
5256 # The send closure's own $seq is per-request by construction (a new closure is
5257 # built per request), so the post-sse.close raise contract survives untouched.
5258 #
5259 # _disconnect_handled is deliberately NOT reset: every _handle_disconnect pairs
5260 # with _close (and so with {closed}), which the keep-alive branch excludes, so
5261 # reaching here means no disconnect was ever handled and the flag is still 0.
5262 25 ▶sub _reset_after_sse_stream {
Subroutine _reset_after_sse_stream: called CC=2 SCAR=6.9
5263 25 my ($self) = @_;
5264  
5265 25 $self->_stop_sse_keepalive;
5266 25 $self->_stop_sse_idle_timer;
5267 25 delete $self->{sse_keepalive_writer};
5268  
5269 25 $self->{sse_mode} = 0;
5270 25 $self->{sse_started} = 0;
5271 25 $self->{sse_finished} = 0;
5272 25 $self->{sse_finish_reason} = undef;
5273 25 $self->{sse_close_sent} = 0;
5274 25 $self->{sse_disconnect_reason} = undef;
5275 25 delete @{$self}{qw(
5276 sse_decline_started sse_decline_status sse_decline_headers sse_decline_body
5277 )};
5278  
5279 # Mirrors the keep-alive reset in _handle_request.
5280 25 $self->{handling_request} = 0;
5281 25 $self->{response_started} = 0;
5282 25 $self->{h1_seq} = 'initial';
5283 25 $self->{_resp_pending} = undef;
5284 25 $self->{response_status} = undef;
5285 25 $self->{_response_size} = 0;
5286 25 $self->{request_start} = undef;
5287 25 $self->{current_request} = undef;
5288 25 $self->{request_future} = undef;
5289 25 $self->{current_connection_state} = undef;
5290 25 $self->{current_transport_state} = undef;
5291  
5292 # The finished stream's receive bookkeeping never belongs to the next
5293 # request. The application has returned, so nothing is awaiting these.
5294 25 $self->{receive_queue} = [];
5295 25 $self->{receive_pending} = undef;
5296 25 $self->{receive_futures} = [];
5297  
5298 # The SSE stream that just ended completed a request on this connection,
5299 # same as the plain HTTP path: the next idle expiry reports
5300 # keepalive_timeout rather than idle_timeout.
5301 25 $self->{_served_a_request} = 1;
5302  
5303 # SSE removed the between-requests idle timer as a long-lived mode; an
5304 # ordinary keep-alive connection must not sit open forever.
5305 25 $self->_start_idle_timer;
5306  
5307 # Check if there's more data in the buffer (pipelining)
5308 25 ▶ if (length($self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $self->{"buffer"} > 0) 0 25 25
5309 0 $self->_try_handle_request;
5310 }
5311 }
5312  
5313 58 ▶sub _create_sse_scope {
Subroutine _create_sse_scope: called CC=3 SCAR=12.0
5314 58 my ($self, $request) = @_;
5315  
5316 my $scope = {
5317 type => 'sse',
5318 pagi => {
5319 version => '0.5',
5320 spec_version => '0.5',
5321 },
5322 http_version => $request->{http_version},
5323 method => $request->{method},
5324 scheme => $self->_get_scheme,
5325 path => $request->{path},
5326 raw_path => $request->{raw_path},
5327 query_string => $request->{query_string},
5328 root_path => '',
5329 headers => $request->{headers},
5330 (defined $self->{client_host}
5331 ? (client => [$self->{client_host}, $self->{client_port}])
5332 : ()
5333 ),
5334 server => [$self->{server_host}, $self->{server_port}],
5335 # Optimized: avoid hash copy when state is empty (common case)
5336 0 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
5337 extensions => $self->_get_extensions_for_scope,
5338 # Outbound flow-control introspection (buffered_amount, watermarks,
5339 # on_high_water/on_drain). Stashed on the connection too, so the send
5340 # path can poke _check_watermarks after each write.
5341 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
5342 };
5343  
5344 58 return $scope;
5345 }
5346  
5347 58 ▶sub _create_sse_receive {
Subroutine _create_sse_receive: called CC=5 SCAR=16.3
5348 58 my ($self, $request) = @_;
5349  
5350 58 my $content_length = $request->{content_length};
5351 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
5352 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
5353 58 my $continue_sent = 0;
5354 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
5355 58 my $body_complete = 0;
5356 58 my $bytes_read = 0;
5357  
5358 58 weaken(my $weak_self = $self);
5359  
5360 # Helper to create SSE disconnect event with reason
5361 1 ▶ my $sse_disconnect = sub {
Subroutine __ANON__: called CC=3 SCAR=12.7
5362 return {
5363 type => 'sse.disconnect',
5364 1 ▶ reason => ($weak_self ? $weak_self->{sse_disconnect_reason} : undef) // 'client_closed',
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
5365 };
5366 58 };
5367  
5368 # The stream is over -- either the transport is gone, or the application
5369 # ended it with sse.close and is still running (the connection stays open
5370 # for keep-alive, design section 11.6). Nothing more will ever arrive
5371 # on this scope, so answer immediately instead of blocking forever. This
5372 # answers a receive() the application chose to make; it is not a disconnect
5373 # fired at the application because the stream ended.
5374 48 ▶ my $stream_over = sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
5375 48 ▶ return 1 unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 48 48
5376 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
5377 58 };
5378  
5379 25 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=14.0
5380 25 ▶ if ($stream_over->()) {
Branch: 1 branch
BranchTrueFalseTotal
if (&$stream_over()) 2 23 25
5381 # A completed decline delivers no events at all (spec): a
5382 # receive() call made after the decline response has already
5383 # finished must not be answered with a synthesized
5384 # sse.disconnect -- nothing abnormal happened. Park instead;
5385 # the app has already gotten its answer (the decline response)
5386 # and has nothing further to receive.
5387 return $weak_self->{server}->loop->new_future
5388 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
5389 1 return Future->done($sse_disconnect->());
5390 }
5391  
5392 23 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=21 SCAR=31.5
5393 23 ▶ return $sse_disconnect->()
Branch: 1 branch
BranchTrueFalseTotal
if &$stream_over() 0 23 23
5394 if $stream_over->();
5395  
5396 # Check queue first
5397 23 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 23 23
5398 0 return shift @{$weak_self->{receive_queue}};
5399 }
5400  
5401 # Handle request body for POST/PUT SSE requests
5402 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
5403 # Send 100 Continue if client expects it (before reading body)
5404 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
5405 1 $continue_sent = 1;
5406 1 $weak_self->{stream}->write($weak_self->{protocol}->serialize_continue);
5407 }
5408  
5409 5 ▶ if ($is_chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_chunked) 1 4 5
5410 1 return await $weak_self->_read_chunked_body(
5411 'sse.request',
5412 $sse_disconnect,
5413 \$body_complete,
5414 \$bytes_read,
5415 );
5416 }
5417  
5418 4 my $remaining = $content_length - $bytes_read;
5419  
5420 # Wait for data if buffer is empty
5421 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
5422 3 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 3 0 3
5423 3 $weak_self->{receive_pending} = Future->new;
5424 }
5425 3 await $weak_self->{receive_pending};
5426 3 $weak_self->{receive_pending} = undef;
5427  
5428 3 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 3 3
5429 0 return shift @{$weak_self->{receive_queue}};
5430 }
5431 }
5432  
5433 4 ▶ return $sse_disconnect->() if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 4 4
5434  
5435 # Read available data up to remaining
5436 my $to_read = $remaining < length($weak_self->{buffer})
5437 ? $remaining
5438 4 ▶ : length($weak_self->{buffer});
Branch: 1 branch
BranchTrueFalseTotal
$remaining < length $weak_self->{'buffer'} ? : 0 4 4
5439  
5440 4 my $chunk = substr($weak_self->{buffer}, 0, $to_read, '');
5441 4 $bytes_read += length($chunk);
5442  
5443 4 ▶ my $more = ($bytes_read < $content_length) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$bytes_read < $content_length ? : 1 3 4
5444 4 ▶ $body_complete = 1 if !$more;
Branch: 1 branch
BranchTrueFalseTotal
unless $more 3 1 4
5445  
5446 return {
5447 4 type => 'sse.request',
5448 body => $chunk,
5449 more => $more,
5450 };
5451 }
5452  
5453 # No body or body complete - return empty body if not yet returned
5454 18 ▶ if (!$body_complete) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($body_complete) 10 8 18
5455 10 $body_complete = 1;
5456 return {
5457 10 type => 'sse.request',
5458 body => '',
5459 more => 0,
5460 };
5461 }
5462  
5463 # Wait for disconnect
5464 8 while (1) {
5465 15 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 7 8 15
5466 7 return shift @{$weak_self->{receive_queue}};
5467 }
5468  
5469 return $sse_disconnect->()
5470 8 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 8 8
5471  
5472 8 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 8 0 8
5473 8 $weak_self->{receive_pending} = Future->new;
5474 }
5475 8 await $weak_self->{receive_pending};
5476 7 $weak_self->{receive_pending} = undef;
5477 }
5478 23 })->();
5479  
5480 # Track this Future
5481 23 push @{$weak_self->{receive_futures}}, $future;
5482 23 @{$weak_self->{receive_futures}} = grep { !$_->is_ready } @{$weak_self->{receive_futures}};
5483  
5484 23 return $future;
5485 58 };
5486 }
5487  
5488 97 ▶sub _format_sse_event {
Subroutine _format_sse_event: called CC=11 SCAR=24.0
5489 97 my ($event) = @_;
5490 97 my $sse_data = '';
5491  
5492 97 ▶ if (defined $event->{event} && length $event->{event}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event->{"event"} and length $event->{"event"}) 30 67 97
Condition66%2/3
defined $event->{"event"} and length $event->{"event"}
!ll&&!rl&&r
67030
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
5493 die "Invalid SSE event name: contains newline\n"
5494 30 ▶ if $event->{event} =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"event"} =~ /[\r\n]/ 1 29 30
5495 29 $sse_data .= "event: $event->{event}\n";
5496 }
5497  
5498 96 ▶ my $data = $event->{data} // '';
Condition50%1/2
$event->{"data"} // ""
l!l
960
MC/DC0%0/1
$event->{"data"} // ""
$event->{"data"}
Truth table50%1/2
A
A= $event->{"data"}
Aresult
11
00
5499 96 for my $line (split /\r?\n|\r/, $data, -1) {
5500 111 $sse_data .= "data: $line\n";
5501 }
5502  
5503 96 ▶ if (defined $event->{id} && length $event->{id}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event->{"id"} and length $event->{"id"}) 9 87 96
Condition66%2/3
defined $event->{"id"} and length $event->{"id"}
!ll&&!rl&&r
8709
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
5504 die "Invalid SSE id: contains newline\n"
5505 9 ▶ if $event->{id} =~ /[\r\n]/;
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"id"} =~ /[\r\n]/ 1 8 9
5506 8 $sse_data .= "id: $event->{id}\n";
5507 }
5508  
5509 95 ▶ if (defined $event->{retry}) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $event->{"retry"}) 7 88 95
5510 die "Invalid SSE retry: must be a non-negative integer\n"
5511 7 ▶ unless $event->{retry} =~ /\A[0-9]+\z/;
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"retry"} =~ /\A[0-9]+\z/ 2 5 7
5512 5 $sse_data .= "retry: $event->{retry}\n";
5513 }
5514  
5515 93 $sse_data .= "\n";
5516 93 return $sse_data;
5517 }
5518  
5519 7 ▶sub _format_sse_comment {
Subroutine _format_sse_comment: called CC=4 SCAR=13.9
5520 7 my ($event) = @_;
5521 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
5522 7 my $formatted = '';
5523 7 for my $line (split /\r?\n|\r/, $text, -1) {
5524 11 ▶ $line = ":$line" unless $line =~ /^:/;
Branch: 1 branch
BranchTrueFalseTotal
unless $line =~ /^:/ 10 1 11
5525 11 $formatted .= "$line\n";
5526 }
5527 7 $formatted .= "\n";
5528 7 return $formatted;
5529 }
5530  
5531 58 ▶sub _create_sse_send {
Subroutine _create_sse_send: called CC=1 SCAR=0.0
5532 58 my ($self, $request) = @_;
5533  
5534 58 weaken(my $weak_self = $self);
5535 58 my $seq = 'initial';
5536  
5537 543 ▶ return async sub {
Subroutine __ANON__: called CC=44 SCAR=38.7
5538 543 my ($event) = @_;
5539 543 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 543 543
5540  
5541 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
5542  
5543 # Once the machine has already recorded this stream as closed --
5544 # either an app-initiated sse.close (which closes the transport as a
5545 # side effect of ending the stream) or a completed decline response
5546 # (whose finalize branch also closes the transport as a side
5547 # effect) -- the machine, not the transport-closed check below,
5548 # decides what happens next: idempotent no-op for a repeat
5549 # sse.close, croak for anything else (decline_complete has no
5550 # idempotent case; it croaks unconditionally).
5551 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
5552  
5553 # Transport already gone for reasons other than our own close (a real
5554 # client disconnect): sends are a silent no-op.
5555 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
5556  
5557 # Reset SSE idle timer on send activity (skip once fully closed)
5558 145 ▶ $weak_self->_reset_sse_idle_timer unless $already_closed;
Branch: 1 branch
BranchTrueFalseTotal
unless $already_closed 141 4 145
5559  
5560 # Mandatory event validation and sequencing (PAGI spec compliance).
5561 # Order per spec: transport-closed no-op check above runs first.
5562 PAGI::Server::EventValidator::validate_sse_send(
5563 145 $event, { extensions => $weak_self->{extensions} });
5564 142 $seq = PAGI::Server::EventValidator::advance_sse($seq, $event);
5565  
5566 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
5567 43 ▶ return if $weak_self->{sse_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"sse_started"} 0 43 43
5568 43 $weak_self->{sse_started} = 1;
5569 43 $weak_self->{response_started} = 1;
5570  
5571 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
5572 43 $weak_self->{response_status} = $status; # Track for access logging
5573 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
5574 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
5575 # strip any app-supplied values before they reach the wire.
5576 43 $headers = $weak_self->_h1_strip_connection_headers($headers);
5577  
5578 # Ensure Content-Type is text/event-stream
5579 43 my $has_content_type = 0;
5580 43 for my $h (@$headers) {
5581 19 ▶ if (lc($h->[0]) eq 'content-type') {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $h->[0] eq "content-type") 18 1 19
5582 18 $has_content_type = 1;
5583 18 last;
5584 }
5585 }
5586  
5587 43 my @final_headers = @$headers;
5588 43 ▶ if (!$has_content_type) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($has_content_type) 25 18 43
5589 25 push @final_headers, ['content-type', 'text/event-stream'];
5590 }
5591  
5592 # Cache-Control and Date: server-supplied only when the app didn't
5593 # supply them (design doc section 11.4). Connection is a framing
5594 # header the protocol requires the server to control, so it is
5595 # always advertised regardless of what the app sent.
5596 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
5597 42 push @final_headers, ['cache-control', 'no-cache'];
5598 }
5599 43 push @final_headers, ['connection', 'keep-alive'];
5600 43 ▶ unless (grep { lc($_->[0]) eq 'date' } @final_headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @final_headers) 42 1 43
5601 42 push @final_headers, ['date', $weak_self->{protocol}->format_date];
5602 }
5603  
5604 # SSE uses chunked encoding implicitly (no Content-Length)
5605 my $response = $weak_self->{protocol}->serialize_response_start(
5606 43 $status, \@final_headers, 1 # chunked = 1
5607 );
5608  
5609 43 $weak_self->{stream}->write($response);
5610  
5611 # Set protocol-specific keepalive writer (HTTP/1.1 chunked)
5612 9 ▶ $weak_self->{sse_keepalive_writer} = sub {
Subroutine __ANON__: called CC=4 SCAR=14.2
5613 9 my ($text) = @_;
5614 9 ▶ return unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 9 9
5615 9 ▶ return if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 9 9
5616 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at
5617 # the wire boundary — the chunk-size prefix below is on the
5618 # resulting BYTE string.
5619 9 my $bytes = eval { Encode::encode('UTF-8', $text, Encode::FB_CROAK) };
5620 9 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 9 9
5621 9 my $len = sprintf("%x", length($bytes));
5622 9 $weak_self->{stream}->write("$len\r\n$bytes\r\n");
5623 43 };
5624 }
5625 elsif ($type eq 'sse.send') {
5626 46 ▶ return unless $weak_self->{sse_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"sse_started"} 0 46 46
5627  
5628 # --- BACKPRESSURE CHECK ---
5629 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
5630 1 await $weak_self->_wait_for_drain;
5631 1 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
5632 1 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 0 1
5633 }
5634 # --- END BACKPRESSURE CHECK ---
5635  
5636 45 my $sse_data = _format_sse_event($event);
5637 # PAGI Www.pod "Send SSE": encode to UTF-8 exactly once, at the
5638 # wire boundary — a failed encode fails this send's Future.
5639 45 my $bytes = eval { Encode::encode('UTF-8', $sse_data, Encode::FB_CROAK) };
5640 45 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 1 44 45
5641  
5642 # Send as chunked data
5643 44 my $len = sprintf("%x", length($bytes));
5644 44 $weak_self->{stream}->write("$len\r\n$bytes\r\n");
5645 44 $weak_self->_notify_transport_write;
5646 }
5647 elsif ($type eq 'sse.comment') {
5648 3 ▶ return unless $weak_self->{sse_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"sse_started"} 0 3 3
5649  
5650 3 my $comment = _format_sse_comment($event);
5651 3 my $bytes = eval { Encode::encode('UTF-8', $comment, Encode::FB_CROAK) };
5652 3 ▶ die "sse payload is not encodable as UTF-8: $@" unless defined $bytes;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes 0 3 3
5653  
5654 3 my $len = sprintf("%x", length($bytes));
5655 3 $weak_self->{stream}->write("$len\r\n$bytes\r\n");
5656 }
5657 elsif ($type eq 'sse.keepalive') {
5658 # SSE keepalive - starts/stops periodic comment timer
5659 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
5660 4 my $comment = $event->{comment};
5661  
5662 4 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 4 0 4
5663 4 $weak_self->_start_sse_keepalive($interval, $comment);
5664 }
5665 else {
5666 0 $weak_self->_stop_sse_keepalive;
5667 }
5668 }
5669 elsif ($type eq 'sse.close') {
5670 # Explicit application-initiated end of the SSE stream. End it now,
5671 # decoupled from the application returning: the terminator goes out
5672 # here, but the connection's fate is settled by _handle_sse_request
5673 # once the application has actually returned (design section 11.6),
5674 # so the application keeps running against a live transport and its
5675 # further sends are rejected by the sequence machine, not by a
5676 # closed check. `reason` is server-side metadata only and is never
5677 # written to the wire. Idempotency for a repeat sse.close is handled
5678 # by advance_sse (the 'closed' state accepts another sse.close as a
5679 # no-op).
5680 11 $weak_self->{sse_close_sent} = 1;
5681 $weak_self->{sse_disconnect_reason} = $event->{reason}
5682 11 ▶ if defined $event->{reason};
Branch: 1 branch
BranchTrueFalseTotal
if defined $event->{"reason"} 1 10 11
5683 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
5684 }
5685 elsif ($type eq 'sse.http.response.start') {
5686 # Decline the SSE stream and return a normal HTTP response. Valid only
5687 # before sse.start; namespaced under sse. (mirrors websocket.http.response.*).
5688 # A decline-after-start attempt, and a repeat sse.http.response.start,
5689 # are already rejected by advance_sse (the 'declining' state only
5690 # accepts sse.http.response.body).
5691 14 $weak_self->{sse_decline_started} = 1;
5692 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
5693 $weak_self->{sse_decline_headers} = [
5694 8 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
5695 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
5696 ];
5697 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
5698 # strip any app-supplied values before submission.
5699 14 $weak_self->{sse_decline_headers} = $weak_self->_h1_strip_connection_headers($weak_self->{sse_decline_headers});
5700 14 $weak_self->{sse_decline_body} = '';
5701 }
5702 elsif ($type eq 'sse.http.response.body') {
5703 13 ▶ return unless $weak_self->{sse_decline_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"sse_decline_started"} 0 13 13
5704 13 ▶ return if $weak_self->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"response_started"} 0 13 13
5705 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
5706 13 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 0 13 13
5707  
5708 13 my $status = $weak_self->{sse_decline_status};
5709 13 my $body = $weak_self->{sse_decline_body};
5710 my @headers = (
5711 13 @{$weak_self->{sse_decline_headers}},
5712 ['content-length', length $body],
5713 );
5714 13 ▶ unless (grep { lc($_->[0]) eq 'date' } @headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @headers) 12 1 13
5715 12 push @headers, ['date', $weak_self->{protocol}->format_date];
5716 }
5717 # This response is always followed by closing the connection; tell
5718 # a keep-alive-pooling client so it doesn't reuse a dead socket.
5719 13 ▶ unless (grep { lc($_->[0]) eq 'connection' } @headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "connection";} @headers) 13 0 13
5720 13 push @headers, ['connection', 'close'];
5721 }
5722 13 my $response = $weak_self->{protocol}->serialize_response_start($status, \@headers, 0);
5723 13 $response .= $body;
5724 13 $weak_self->{stream}->write($response);
5725 13 $weak_self->{response_started} = 1;
5726 13 $weak_self->{response_status} = $status; # access log
5727 # Declined: close the connection (no event stream was started).
5728 # Marked BEFORE teardown so _handle_disconnect and a later
5729 # receive() both know this closure is a completed decline, not
5730 # an abnormal end -- per the spec, a decline delivers no events
5731 # at all, so neither may synthesize sse.disconnect for it.
5732 13 $weak_self->{sse_decline_completed} = 1;
5733 13 $weak_self->_handle_disconnect_and_close('client_closed');
5734 }
5735 elsif ($type eq 'http.fullflush') {
5736 # Fullflush extension - force immediate TCP buffer flush.
5737 # validate_sse_send (called above, unconditionally) already
5738 # croaks "Extension not enabled: fullflush" when the extension
5739 # isn't advertised, so no re-check is needed here.
5740  
5741 # Force flush by ensuring TCP_NODELAY
5742 1 my $handle = $weak_self->{stream}->write_handle;
5743 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
5744 1 require Socket;
5745 1 $handle->setsockopt(Socket::IPPROTO_TCP(), Socket::TCP_NODELAY(), 1);
5746 }
5747 }
5748  
5749 133 return;
5750 58 };
5751 }
5752  
5753 #
5754 # WebSocket Support Methods
5755 #
5756  
5757 # WebSocket handshake magic GUID per RFC 6455
5758 156 ▶use constant WS_GUID => '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
Subroutine BEGIN: called CC=1 SCAR=0.0
5759  
5760 34 ▶async sub _handle_websocket_request {
Subroutine _handle_websocket_request: called CC=4 SCAR=13.9
5761 34 my ($self, $request) = @_;
5762  
5763 34 $self->_stop_idle_timer; # WebSocket connections are long-lived
5764 34 $self->_start_ws_idle_timer; # Start WebSocket-specific idle timer if configured
5765  
5766 34 my $scope = $self->_create_websocket_scope($request);
5767 34 my $receive = $self->_create_websocket_receive($request);
5768 34 my $send = $self->_create_websocket_send($request);
5769  
5770 34 eval {
5771 34 await $self->{app}->($scope, $receive, $send);
5772 };
5773  
5774 32 ▶ if (my $error = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $error = $@) 2 30 32
5775 # If handshake not yet done, send HTTP error
5776 2 ▶ if (!$self->{websocket_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"websocket_accepted"}) 2 0 2
5777 2 $self->_send_error_response(500, "Internal Server Error");
5778 }
5779 2 $self->_log(error => "PAGI application error (WebSocket): $error");
5780 }
5781  
5782 # Write access log entry (logs at connection close with total duration)
5783 32 $self->_write_access_log;
5784  
5785 # Notify server that request completed (for max_requests tracking)
5786 32 ▶ $self->{server}->_on_request_complete if $self->{server};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"server"} 32 0 32
5787  
5788 # Close connection after WebSocket session ends
5789 32 $self->_handle_disconnect_and_close('session_complete');
5790 156 }
5791  
5792 35 ▶sub _create_websocket_scope {
Subroutine _create_websocket_scope: called CC=7 SCAR=19.5
5793 35 my ($self, $request) = @_;
5794  
5795 # Extract WebSocket key and subprotocols from headers
5796 35 my $ws_key;
5797 my @subprotocols;
5798  
5799 35 for my $header (@{$request->{headers}}) {
5800 184 my ($name, $value) = @$header;
5801 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
5802 34 $ws_key = $value;
5803 }
5804 elsif ($name eq 'sec-websocket-protocol') {
5805 # Parse comma-separated list of subprotocols
5806 2 push @subprotocols, map { s/^\s+|\s+$//gr } split /,/, $value;
5807 }
5808 }
5809  
5810 # Store ws_key for handshake response
5811 35 $self->{ws_key} = $ws_key;
5812  
5813 my $scope = {
5814 type => 'websocket',
5815 pagi => {
5816 version => '0.5',
5817 spec_version => '0.5',
5818 },
5819 http_version => $request->{http_version},
5820 scheme => $self->_get_ws_scheme,
5821 path => $request->{path},
5822 raw_path => $request->{raw_path},
5823 query_string => $request->{query_string},
5824 root_path => '',
5825 headers => $request->{headers},
5826 (defined $self->{client_host}
5827 ? (client => [$self->{client_host}, $self->{client_port}])
5828 : ()
5829 ),
5830 server => [$self->{server_host}, $self->{server_port}],
5831 subprotocols => \@subprotocols,
5832 # Optimized: avoid hash copy when state is empty (common case)
5833 0 state => keys %{$self->{state}} ? { %{$self->{state}} } : {},
5834 extensions => do {
5835 35 my %ext = (%{$self->_get_extensions_for_scope}, 'websocket.http.response' => {});
5836 # fullflush has no validate_websocket_send arm; advertising it here
5837 # would lie to the app (design 13.2).
5838 35 delete $ext{fullflush};
5839 35 ▶ \%ext;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'max_ws_frame_size'} ? : 33 2 35
5840 },
5841 # max_frame_size: omitted when unenforced (max_ws_frame_size 0/undef
5842 # means unlimited, per Protocol::WebSocket::Frame's max_payload_size
5843 # semantics -- a server that does not enforce a cap must not
5844 # advertise one). max_receive_queue has no unlimited mode (a hard,
5845 # always-enforced cap), so it is always present.
5846 ($self->{max_ws_frame_size}
5847 ? (max_frame_size => $self->{max_ws_frame_size})
5848 : ()
5849 ),
5850 max_receive_queue => $self->{max_receive_queue},
5851 # Outbound flow-control introspection (buffered_amount, watermarks,
5852 # on_high_water/on_drain). Stashed on the connection too, so the send
5853 # path can poke _check_watermarks after each write.
5854 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
5855 };
5856  
5857 35 return $scope;
5858 }
5859  
5860 36 ▶sub _create_websocket_receive {
Subroutine _create_websocket_receive: called CC=1 SCAR=0.3
5861 36 my ($self, $request) = @_;
5862  
5863 36 my $connect_sent = 0;
5864 36 weaken(my $weak_self = $self);
5865  
5866 175 ▶ return sub {
Subroutine __ANON__: called CC=4 SCAR=15.1
5867 175 ▶ return Future->done({ type => 'websocket.disconnect', code => 1006, reason => '' })
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 175 175
5868 unless $weak_self;
5869  
5870 # Check queue first - drain queued messages even if closed
5871 175 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 113 62 175
5872 113 return Future->done(shift @{$weak_self->{receive_queue}});
5873 }
5874  
5875 # $weak_self is known live here, so the fallback can report the
5876 # abnormal reason a server-initiated close recorded (idle timeout,
5877 # queue overflow, ...) instead of an always-empty ''.
5878 return Future->done($weak_self->_ws_disconnect_event)
5879 62 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 3 59 62
5880  
5881 59 ▶ my $future = (async sub {
Subroutine __ANON__: called CC=13 SCAR=32.3
5882 59 ▶ return { type => 'websocket.disconnect', code => 1006, reason => '' }
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 59 59
5883 unless $weak_self;
5884  
5885 # Check queue first - drain queued messages even if closed
5886 59 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 59 59
5887 0 return shift @{$weak_self->{receive_queue}};
5888 }
5889  
5890 return $weak_self->_ws_disconnect_event
5891 59 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 59 59
5892  
5893 # First call returns websocket.connect
5894 59 ▶ if (!$connect_sent) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($connect_sent) 30 29 59
5895 30 $connect_sent = 1;
5896 30 return { type => 'websocket.connect' };
5897 }
5898  
5899 # If not in WebSocket mode yet (waiting for accept), wait
5900 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
5901 0 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 0 0 0
5902 0 $weak_self->{receive_pending} = Future->new;
5903 }
5904 0 await $weak_self->{receive_pending};
5905 0 $weak_self->{receive_pending} = undef;
5906  
5907 0 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 0 0 0
5908 0 return shift @{$weak_self->{receive_queue}};
5909 }
5910 }
5911  
5912 return $weak_self->_ws_disconnect_event
5913 29 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 29 29
5914  
5915 # Wait for events from frame processing
5916 29 while (1) {
5917 58 ▶ if (@{$weak_self->{receive_queue}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$weak_self->{"receive_queue"};}) 29 29 58
5918 29 return shift @{$weak_self->{receive_queue}};
5919 }
5920  
5921 return $weak_self->_ws_disconnect_event
5922 29 ▶ if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 0 29 29
5923  
5924 29 ▶ if (!$weak_self->{receive_pending}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"receive_pending"}) 29 0 29
5925 29 $weak_self->{receive_pending} = Future->new;
5926 }
5927 29 await $weak_self->{receive_pending};
5928 29 $weak_self->{receive_pending} = undef;
5929 }
5930 59 })->();
5931  
5932 # Track this Future
5933 59 push @{$weak_self->{receive_futures}}, $future;
5934 59 @{$weak_self->{receive_futures}} = grep { !$_->is_ready } @{$weak_self->{receive_futures}};
5935  
5936 59 return $future;
5937 36 };
5938 }
5939  
5940 34 ▶sub _create_websocket_send {
Subroutine _create_websocket_send: called CC=1 SCAR=0.1
5941 34 my ($self, $request) = @_;
5942  
5943 34 weaken(my $weak_self = $self);
5944 34 my $seq = 'connecting';
5945  
5946 468 ▶ return async sub {
Subroutine __ANON__: called CC=41 SCAR=39.4
5947 468 my ($event) = @_;
5948 468 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 468 468
5949  
5950 # Once the machine has recorded the connection closed or the denial
5951 # response complete, the machine decides what happens next -- both
5952 # 'closed' and 'denial_complete' have no idempotent case, so any
5953 # further send always raises -- not the transport-closed check below.
5954 # Only app-initiated terminals get this carve-out: websocket.close
5955 # itself flips {closed} synchronously via _handle_disconnect_and_close
5956 # when the client had already sent its own close frame first, but
5957 # that's still the app's own logical close (it chose to answer with
5958 # websocket.close), so a post-close send from the app is a protocol
5959 # violation, not a benign transport no-op. A real client disconnect
5960 # with no app-initiated terminal in play still falls through to the
5961 # plain no-op below.
5962 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
5963  
5964 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
5965  
5966 # Reset WebSocket idle timer on send activity
5967 70 $weak_self->_reset_ws_idle_timer;
5968  
5969 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
5970  
5971 # Mandatory event validation and sequencing (PAGI spec compliance).
5972 # Order per spec: transport-closed no-op check above runs first.
5973 # websocket.http.response is always available on this path (the scope
5974 # advertises it unconditionally; see _create_websocket_scope), unlike
5975 # connection-level extensions such as fullflush.
5976 PAGI::Server::EventValidator::validate_websocket_send(
5977 70 $event, { extensions => { %{$weak_self->{extensions}}, 'websocket.http.response' => {} } });
5978 68 $seq = PAGI::Server::EventValidator::advance_websocket($seq, $event);
5979  
5980 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
5981 # A duplicate accept is already rejected by advance_websocket.
5982  
5983 # Complete the WebSocket handshake
5984 28 my $ws_key = $weak_self->{ws_key};
5985 28 my $accept_key = sha1_base64($ws_key . WS_GUID);
5986 # sha1_base64 doesn't add padding, but WebSocket requires it
5987 28 ▶ $accept_key .= '=' while length($accept_key) % 4;
Branch: 1 branch
BranchTrueFalseTotal
length($accept_key) % 4 and do { $accept_key .= '=' } 28 28 56
5988  
5989 28 my @headers = (
5990 "HTTP/1.1 101 Switching Protocols\r\n",
5991 "Upgrade: websocket\r\n",
5992 "Connection: Upgrade\r\n",
5993 "Sec-WebSocket-Accept: $accept_key\r\n",
5994 );
5995  
5996 # Add subprotocol if specified (with validation)
5997 28 ▶ if (my $subprotocol = $event->{subprotocol}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $subprotocol = $event->{"subprotocol"}) 1 27 28
5998 1 $subprotocol = _validate_subprotocol($subprotocol);
5999 0 push @headers, "Sec-WebSocket-Protocol: $subprotocol\r\n";
6000 }
6001  
6002 # Add custom headers if specified (with CRLF injection validation).
6003 # The server's own "Connection: Upgrade" line above is untouched
6004 # (RFC 6455 requires it) -- strip the app's extra headers the same
6005 # way every other h1 response-header path already does, so an
6006 # app-supplied connection/transfer-encoding value can't duplicate
6007 # or contradict it on the wire.
6008 27 ▶ if (my $extra_headers = $event->{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $extra_headers = $event->{"headers"}) 1 26 27
6009 1 $extra_headers = $weak_self->_h1_strip_connection_headers($extra_headers);
6010 1 for my $h (@$extra_headers) {
6011 1 my ($name, $value) = @$h;
6012 1 $name = _validate_header_name($name);
6013 1 $value = _validate_header_value($value);
6014 1 push @headers, "$name: $value\r\n";
6015 }
6016 }
6017  
6018 27 push @headers, "\r\n";
6019  
6020 27 $weak_self->{stream}->write(join('', @headers));
6021  
6022 # Switch to WebSocket mode
6023 27 $weak_self->{websocket_mode} = 1;
6024 27 $weak_self->{websocket_accepted} = 1;
6025 $weak_self->{websocket_frame} = Protocol::WebSocket::Frame->new(
6026 max_payload_size => $weak_self->{max_ws_frame_size},
6027 27 );
6028 27 $weak_self->{response_status} = 101; # Track for access logging
6029  
6030 # Notify any waiting receive
6031 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
6032 0 my $f = $weak_self->{receive_pending};
6033 0 $weak_self->{receive_pending} = undef;
6034 0 $f->done;
6035 }
6036  
6037 # Process any data that arrived before accept
6038 27 ▶ if (length($weak_self->{buffer}) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $weak_self->{"buffer"} > 0) 0 27 27
6039 0 $weak_self->_process_websocket_frames;
6040 }
6041 }
6042 elsif ($type eq 'websocket.send') {
6043 22 ▶ return unless $weak_self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"websocket_mode"} 0 22 22
6044  
6045 # --- BACKPRESSURE CHECK ---
6046 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
6047 1 await $weak_self->_wait_for_drain;
6048 1 ▶ return Future->done unless $weak_self;
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self 0 1 1
6049 1 ▶ return Future->done if $weak_self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"closed"} 1 0 1
6050 }
6051 # --- END BACKPRESSURE CHECK ---
6052  
6053 21 my $frame;
6054 21 ▶ if (defined $event->{text}) {
Branch: 2 branches
BranchTrueFalseTotal
if (defined $event->{'text'}) { } 18 3 21
elsif (defined $event->{'bytes'}) { } 3 0 3
6055 $frame = Protocol::WebSocket::Frame->new(
6056 buffer => $event->{text},
6057 18 type => 'text',
6058 );
6059 }
6060 elsif (defined $event->{bytes}) {
6061 $frame = Protocol::WebSocket::Frame->new(
6062 buffer => $event->{bytes},
6063 3 type => 'binary',
6064 );
6065 }
6066 else {
6067 0 return; # Nothing to send
6068 }
6069  
6070 21 my $bytes = $frame->to_bytes;
6071 21 $weak_self->{stream}->write($bytes);
6072 21 $weak_self->_notify_transport_write;
6073 }
6074 elsif ($type eq 'websocket.http.response.start') {
6075 # Custom handshake denial (websocket.http.response extension). Only
6076 # valid before accept; buffer the response head until the body
6077 # arrives.
6078 4 ▶ return if $weak_self->{websocket_accepted};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"websocket_accepted"} 0 4 4
6079 4 ▶ return if $weak_self->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"ws_denial_started"} 0 4 4
6080 4 $weak_self->{ws_denial_started} = 1;
6081 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
6082 $weak_self->{ws_denial_headers} = [
6083 8 map { [_validate_header_name($_->[0]), _validate_header_value($_->[1])] }
6084 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
6085 ];
6086 # PAGI spec — HTTP/1.1 owns Transfer-Encoding and Connection;
6087 # strip any app-supplied values before submission.
6088 4 $weak_self->{ws_denial_headers} = $weak_self->_h1_strip_connection_headers($weak_self->{ws_denial_headers});
6089 4 $weak_self->{ws_denial_body} = '';
6090 }
6091 elsif ($type eq 'websocket.http.response.body') {
6092 4 ▶ return unless $weak_self->{ws_denial_started};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"ws_denial_started"} 0 4 4
6093 4 ▶ return if $weak_self->{response_started};
Branch: 1 branch
BranchTrueFalseTotal
if $weak_self->{"response_started"} 0 4 4
6094 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
6095 4 ▶ return if $event->{more}; # more chunks coming — keep buffering
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"more"} 0 4 4
6096  
6097 4 my $status = $weak_self->{ws_denial_status};
6098 4 my $body = $weak_self->{ws_denial_body};
6099 my @headers = (
6100 4 @{$weak_self->{ws_denial_headers}},
6101 ['content-length', length $body],
6102 );
6103 4 ▶ unless (grep { lc($_->[0]) eq 'date' } @headers) {
Branch: 1 branch
BranchTrueFalseTotal
unless (grep {lc $_->[0] eq "date";} @headers) 3 1 4
6104 3 push @headers, ['date', $weak_self->{protocol}->format_date];
6105 }
6106 4 my $response = $weak_self->{protocol}->serialize_response_start($status, \@headers, 0);
6107 4 $response .= $body;
6108 4 $weak_self->{stream}->write($response);
6109 4 $weak_self->{response_started} = 1;
6110 4 $weak_self->{response_status} = $status; # access log
6111 # Handshake rejected: close like the bare-403 path (no upgrade).
6112 4 $weak_self->_handle_disconnect_and_close('client_closed');
6113 }
6114 elsif ($type eq 'websocket.close') {
6115 # If not accepted yet, send 403 Forbidden
6116 6 ▶ if (!$weak_self->{websocket_accepted}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($weak_self->{"websocket_accepted"}) 1 5 6
6117 1 $weak_self->_send_error_response(403, 'Forbidden');
6118 1 return;
6119 }
6120  
6121 # Send close frame
6122 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
6123 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
6124  
6125 5 my $frame = Protocol::WebSocket::Frame->new(
6126 type => 'close',
6127 buffer => pack('n', $code) . $reason,
6128 );
6129  
6130 5 $weak_self->{stream}->write($frame->to_bytes);
6131 5 $weak_self->{close_sent} = 1;
6132  
6133 # If we received a close frame, close immediately
6134 # Otherwise wait for close from client (handled in frame processing)
6135 5 ▶ if ($weak_self->{close_received}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self->{"close_received"}) 0 5 5
6136 0 $weak_self->_handle_disconnect_and_close('client_closed');
6137 }
6138 }
6139 elsif ($type eq 'websocket.keepalive') {
6140 1 ▶ return unless $weak_self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $weak_self->{"websocket_mode"} 0 1 1
6141  
6142 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
6143 1 my $timeout = $event->{timeout};
6144  
6145 1 ▶ if ($interval > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($interval > 0) { } 1 0 1
6146 1 $weak_self->_start_ws_keepalive($interval, $timeout);
6147 }
6148 else {
6149 0 $weak_self->_stop_ws_keepalive;
6150 }
6151 }
6152  
6153 62 return;
6154 34 };
6155 }
6156  
6157 42 ▶sub _process_websocket_frames {
Subroutine _process_websocket_frames: called CC=41 SCAR=50.6
6158 42 my ($self) = @_;
6159  
6160 42 ▶ return unless $self->{websocket_mode};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"websocket_mode"} 0 42 42
6161 42 ▶ return if $self->{closed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"closed"} 0 42 42
6162  
6163 # Reset WebSocket idle timer on receive activity
6164 42 $self->_reset_ws_idle_timer;
6165  
6166 42 my $frame = $self->{websocket_frame};
6167  
6168 # Append buffer to frame parser
6169 42 $frame->append($self->{buffer});
6170 42 $self->{buffer} = '';
6171  
6172 # Process all complete frames - use next_bytes to get raw bytes
6173 # Protocol::WebSocket::Frame->next() decodes as UTF-8, which corrupts binary data
6174 42 ▶ while (defined(my $bytes = $frame->next_bytes)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $bytes = $frame->next_bytes)) 132 37 169
6175 132 my $opcode = $frame->opcode;
6176  
6177 # RFC 6455 Section 5.2: RSV1-3 MUST be 0 unless extension defines meaning
6178 # PAGI doesn't support compression extensions, so RSV must always be 0
6179 132 my $rsv = $frame->rsv;
6180 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
6181 132 ▶ if (grep { $_ } @$rsv) {
Branch: 1 branch
BranchTrueFalseTotal
if (grep {$_;} @$rsv) 0 132 132
6182 0 $self->_send_close_frame(1002, 'RSV bits must be 0');
6183 0 $self->_handle_disconnect_and_close('protocol_error');
6184 0 return;
6185 }
6186 }
6187  
6188 # RFC 6455 Section 5.2: Opcodes 3-7 and 11-15 (0xB-0xF) are reserved
6189 # Must fail connection with 1002 Protocol Error
6190 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 table28%2/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
6191 0 $self->_send_close_frame(1002, 'Reserved opcode');
6192 0 $self->_handle_disconnect_and_close('protocol_error');
6193 0 return;
6194 }
6195  
6196 # RFC 6455 Section 5.5: Control frames (close/ping/pong) MUST have
6197 # payload length <= 125 bytes
6198 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
6199 0 $self->_send_close_frame(1002, 'Control frame too large');
6200 0 $self->_handle_disconnect_and_close('protocol_error');
6201 0 return;
6202 }
6203  
6204 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
6205 # Text frame - decode as UTF-8
6206 130 my $text = eval { Encode::decode('UTF-8', $bytes, Encode::FB_CROAK) };
6207 130 ▶ unless (defined $text) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $text) 2 128 130
6208 # Invalid UTF-8 - close with 1007 per RFC 6455
6209 2 $self->_send_close_frame(1007, 'Invalid UTF-8');
6210 2 $self->_handle_disconnect_and_close('protocol_error');
6211 2 return;
6212 }
6213 # Check queue limit before adding (DoS protection)
6214 128 ▶ if (@{$self->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"receive_queue"};} >= $self->{"max_receive_queue"}) 2 126 128
6215 2 $self->_send_close_frame(1008, 'Message queue overflow');
6216 2 $self->_handle_disconnect_and_close('queue_overflow');
6217 2 return;
6218 }
6219 126 push @{$self->{receive_queue}}, {
6220 type => 'websocket.receive',
6221 text => $text,
6222 };
6223 }
6224 elsif ($opcode == 2) {
6225 # Binary frame - keep as raw bytes
6226 # Check queue limit before adding (DoS protection)
6227 1 ▶ if (@{$self->{receive_queue}} >= $self->{max_receive_queue}) {
Branch: 1 branch
BranchTrueFalseTotal
if (@{$self->{"receive_queue"};} >= $self->{"max_receive_queue"}) 0 1 1
6228 0 $self->_send_close_frame(1008, 'Message queue overflow');
6229 0 $self->_handle_disconnect_and_close('queue_overflow');
6230 0 return;
6231 }
6232 1 push @{$self->{receive_queue}}, {
6233 type => 'websocket.receive',
6234 bytes => $bytes,
6235 };
6236 }
6237 elsif ($opcode == 8) {
6238 # Close frame
6239 1 $self->{close_received} = 1;
6240 1 my ($code, $reason) = (1005, '');
6241  
6242 # RFC 6455 Section 5.5.1: Close frame payload is 0 or >=2 bytes
6243 # 1 byte is invalid
6244 1 ▶ if (length($bytes) == 1) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes == 1) 0 1 1
6245 0 $self->_send_close_frame(1002, 'Invalid close frame');
6246 0 $self->_handle_disconnect_and_close('protocol_error');
6247 0 return;
6248 }
6249  
6250 1 ▶ if (length($bytes) >= 2) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $bytes >= 2) 1 0 1
6251 1 $code = unpack('n', substr($bytes, 0, 2));
6252 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
6253  
6254 # RFC 6455 Section 7.4.1: Validate close code
6255 # Valid codes: 1000-1003, 1007-1011, 3000-4999
6256 # Invalid: 0-999, 1004-1006, 1012-2999, 5000+
6257 1 my $valid_code = 0;
6258 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
6259 1 $valid_code = 1;
6260 }
6261 ▶ 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
6262 0 $valid_code = 1;
6263 }
6264 ▶ 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
6265 0 $valid_code = 1;
6266 }
6267 1 ▶ unless ($valid_code) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($valid_code) 0 1 1
6268 0 $self->_send_close_frame(1002, 'Invalid close code');
6269 0 $self->_handle_disconnect_and_close('protocol_error');
6270 0 return;
6271 }
6272  
6273 # RFC 6455: Close reason must be valid UTF-8
6274 1 ▶ if (length($reason) > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $reason > 0) 1 0 1
6275 1 my $reason_copy = $reason;
6276 1 my $decoded = eval { Encode::decode('UTF-8', $reason_copy, Encode::FB_CROAK) };
6277 1 ▶ unless (defined $decoded) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $decoded) 0 1 1
6278 0 $self->_send_close_frame(1007, 'Invalid UTF-8 in close reason');
6279 0 $self->_handle_disconnect_and_close('protocol_error');
6280 0 return;
6281 }
6282 }
6283 }
6284  
6285 # If we haven't sent close yet, send it now
6286 1 ▶ if (!$self->{close_sent}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"close_sent"}) 1 0 1
6287 1 my $close_frame = Protocol::WebSocket::Frame->new(
6288 type => 'close',
6289 buffer => pack('n', $code) . $reason,
6290 );
6291 1 $self->{stream}->write($close_frame->to_bytes);
6292 1 $self->{close_sent} = 1;
6293 }
6294  
6295 1 push @{$self->{receive_queue}}, {
6296 type => 'websocket.disconnect',
6297 code => $code,
6298 reason => $reason,
6299 };
6300  
6301 # This is the scope's one and only websocket.disconnect: mark
6302 # disconnect-handled now (the same guard _handle_disconnect
6303 # checks) so a later TCP close (on_closed -> client_closed) or
6304 # the app's own session-complete teardown finds the guard
6305 # already set and delivers nothing further. Without this, either
6306 # of those paths queues a second, ghost disconnect event that
6307 # nobody asked for and nobody drains (h2's equivalent guard is
6308 # ws_disconnect_delivered / _h2_ws_enqueue_disconnect).
6309 1 $self->{_disconnect_handled} = 1;
6310 }
6311 elsif ($opcode == 9) {
6312 # Ping - respond with pong (transparent to app)
6313 0 my $pong = Protocol::WebSocket::Frame->new(
6314 type => 'pong',
6315 buffer => $bytes,
6316 );
6317 0 $self->{stream}->write($pong->to_bytes);
6318 }
6319 elsif ($opcode == 10) {
6320 # Pong - cancel any pending timeout (response to our ping)
6321 0 $self->_cancel_ws_pong_timeout;
6322 }
6323 }
6324  
6325 # Notify any waiting receive
6326 37 ▶ 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 25 37
Condition66%4/6
$self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready and @{$self->{"receive_queue"};}
!ll&&!rl&&r
25012
$self->{"receive_pending"} and not $self->{"receive_pending"}->is_ready
!ll&&!rl&&r
25012
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
6327 12 my $f = $self->{receive_pending};
6328 12 $self->{receive_pending} = undef;
6329 12 $f->done;
6330 }
6331 }
6332  
6333 # Async file response - prioritizes speed based on file size:
6334 # 1. Small files (<=64KB): direct in-process read (fastest for small files)
6335 # 2. Large files: async chunked reads via worker pool (non-blocking)
6336 13 ▶async sub _send_file_response {
Subroutine _send_file_response: called CC=14 SCAR=26.5
6337 13 my ($self, $file, $offset, $length, $chunked) = @_;
6338  
6339 # Get file size if length not specified
6340 13 my $file_size = -s $file;
6341 13 ▶ die "Cannot stat file $file: $!\n" unless defined $file_size;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $file_size 0 13 13
6342 13 ▶ $length //= $file_size - $offset;
Condition100%2/2
$length //= $file_size - $offset
l!l
112
MC/DC100%1/1
$length //= $file_size - $offset
$length
Truth table100%2/2
A
A= $length
Aresult
11
00
6343  
6344 # PAGI spec (Www.pod, Response Body validation): an offset past the end
6345 # of the file SHOULD send zero bytes rather than fail the response.
6346 13 ▶ $length = 0 if $length < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $length < 0 2 11 13
6347  
6348 13 $self->{_response_size} += $length;
6349  
6350 13 my $stream = $self->{stream};
6351  
6352 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
6353 # Small file fast path: read directly in-process
6354 # For files <= 64KB, a simple read() is fast and avoids async overhead
6355 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}: $!" 10 0 10
6356 10 ▶ seek($fh, $offset, 0) if $offset;
Branch: 1 branch
BranchTrueFalseTotal
if $offset 4 6 10
6357 10 my $bytes_read = read($fh, my $data, $length);
6358 10 close $fh;
6359  
6360 10 ▶ die "Failed to read file $file: $!" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 0 10 10
6361  
6362 10 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 2 8 10
6363 # A zero-length body IS the terminator chunk -- writing a
6364 # separate empty data chunk before it would send "0\r\n\r\n"
6365 # twice and desync the connection.
6366 2 ▶ if (length($data)) {
Branch: 1 branch
BranchTrueFalseTotal
if (length $data) 1 1 2
6367 1 my $len = sprintf("%x", length($data));
6368 1 $stream->write("$len\r\n$data\r\n");
6369 }
6370 2 $stream->write("0\r\n\r\n");
6371 }
6372 else {
6373 8 $stream->write($data);
6374 }
6375 }
6376 else {
6377 # Large file path: async chunked reads via worker pool
6378 3 ▶ my $loop = $self->{server} ? $self->{server}->loop : undef;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'server'} ? : 3 0 3
6379 3 ▶ die "No event loop available for async file I/O" unless $loop;
Branch: 1 branch
BranchTrueFalseTotal
unless $loop 0 3 3
6380  
6381 await PAGI::Server::AsyncFile->read_file_chunked(
6382 $loop, $file,
6383 6 ▶ sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
6384 6 my ($chunk) = @_;
6385 6 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 2 4 6
6386 2 my $len = sprintf("%x", length($chunk));
6387 2 $stream->write("$len\r\n$chunk\r\n");
6388 }
6389 else {
6390 4 $stream->write($chunk);
6391 }
6392 6 return; # Sync callback
6393 },
6394 3 offset => $offset,
6395 length => $length,
6396 chunk_size => FILE_CHUNK_SIZE,
6397 );
6398  
6399 # Send final chunk terminator if chunked
6400 3 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) 1 2 3
6401 1 $stream->write("0\r\n\r\n");
6402 }
6403 }
6404 156 }
6405  
6406 # Async filehandle response - synchronous chunked reads in the send loop
6407 # (the fh can't cross a fork into the worker pool; see below).
6408 # Note: Can't easily use sendfile for arbitrary filehandles (may not have fd,
6409 # may be pipes, may be in-memory). Falls back to chunked reads.
6410 9 ▶async sub _send_fh_response {
Subroutine _send_fh_response: called CC=12 SCAR=24.9
6411 9 my ($self, $fh, $offset, $length, $chunked) = @_;
6412  
6413 # Seek to offset if specified
6414 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
6415 3 ▶ seek($fh, $offset, 0) or die "Cannot seek: $!";
Branch: 1 branch
BranchTrueFalseTotal
seek $fh, $offset, 0 or die "Cannot seek: $!" 2 1 3
6416 }
6417  
6418 # For filehandles, we can't easily use the worker pool (can't pass fh across fork).
6419 # Use blocking reads in small chunks - not ideal but practical.
6420 # TODO: Consider IO::Async::FileStream for better event loop integration.
6421  
6422 8 my $remaining = $length; # undef means read to EOF
6423 8 my $stream = $self->{stream};
6424  
6425 8 while (1) {
6426 14 my $to_read = FILE_CHUNK_SIZE;
6427 14 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 5 9 14
6428 5 ▶ $to_read = $remaining if $remaining < $to_read;
Branch: 1 branch
BranchTrueFalseTotal
if $remaining < $to_read 5 0 5
6429 5 ▶ last if $to_read <= 0;
Branch: 1 branch
BranchTrueFalseTotal
if $to_read <= 0 2 3 5
6430 }
6431  
6432 12 my ($bytes_read, $chunk);
6433 {
6434 156 ▶ no warnings 'closed';
Subroutine BEGIN: called CC=1 SCAR=0.0
6435 12 $bytes_read = read($fh, $chunk, $to_read);
6436 }
6437  
6438 12 ▶ die "Failed to read filehandle: $!\n" unless defined $bytes_read;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $bytes_read 1 11 12
6439 11 ▶ last if $bytes_read == 0; # EOF
Branch: 1 branch
BranchTrueFalseTotal
if $bytes_read == 0 5 6 11
6440  
6441 6 $self->{_response_size} += $bytes_read;
6442  
6443 6 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) { } 3 3 6
6444 3 my $len = sprintf("%x", length($chunk));
6445 3 $stream->write("$len\r\n$chunk\r\n");
6446 }
6447 else {
6448 3 $stream->write($chunk);
6449 }
6450  
6451 6 ▶ if (defined $remaining) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $remaining) 2 4 6
6452 2 $remaining -= $bytes_read;
6453 }
6454 }
6455  
6456 # Send final chunk if chunked encoding
6457 7 ▶ if ($chunked) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chunked) 4 3 7
6458 4 $stream->write("0\r\n\r\n");
6459 }
6460 156 }
6461  
6462 # Diagnostics go through the server so log_level governs them and a replaced
6463 # sink sees them. A connection can outlive its server reference during
6464 # shutdown, so falling back to STDERR is a real path, not a formality.
6465 92 ▶sub _log {
Subroutine _log: called CC=2 SCAR=6.9
6466 92 my ($self, $level, $msg) = @_;
6467  
6468 92 my $server = $self->{server};
6469 92 ▶ return $server->_log($level, $msg, __PACKAGE__) if $server;
Branch: 1 branch
BranchTrueFalseTotal
if $server 91 1 92
6470  
6471 1 warn "$msg\n";
6472 1 return;
6473 }
6474  
6475 156 1;
6476  
6477 __END__
« blib/lib/PAGI/Server/AsyncFile.pm ↑ Summary blib/lib/PAGI/Server/Protocol/HTTP1.pm »