blib/lib/PAGI/Server/ConnectionState.pm

filter: Statementstmt 98.9% 96 / 97 Branchbran 89.4% 34 / 38 Conditioncond 63.6% 7 / 11 MC/DCmcdc 42.8% 3 / 7 Subroutinesub 100% 15 / 15 Podpod 100% 8 / 8 totaltotal 92.6% 163 / 176 CC 26 SCAR 14.5
CC
26
Cov
94%
disconnect_future
7.3
_mark_disconnected
7.0
on_complete
4.0
CRAP 4.3
« examples/08-tls-introspection/app.pl ↑ Summary bin/pagi-server »
1 package PAGI::Server::ConnectionState;
2  
3 157 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 157 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 157 our $VERSION = '0.002013';
7  
8 157 ▶use Scalar::Util qw(weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 =encoding utf8
11  
12 =head1 NAME
13  
14 PAGI::Server::ConnectionState - Connection state tracking for HTTP requests
15  
16 =head1 SYNOPSIS
17  
18 my $conn = $scope->{'pagi.connection'};
19  
20 # Synchronous, non-destructive check
21 if ($conn->is_connected) {
22 # Client still connected
23 }
24  
25 # Get disconnect reason (undef while connected)
26 my $reason = $conn->disconnect_reason;
27  
28 # Register a callback for an abnormal end (client gone, timeout, error)
29 $conn->on_disconnect(sub {
30 my ($reason) = @_;
31 rollback();
32 });
33  
34 # ...and its counterpart for a clean finish. Exactly one of the two fires.
35 $conn->on_complete(sub {
36 commit();
37 });
38  
39 # Await abnormal disconnect. Always a Future: it resolves on an
40 # abnormal end, and stays pending forever after a clean completion
41 # (use on_complete to observe that case instead).
42 my $reason = await $conn->disconnect_future;
43  
44 =head1 DESCRIPTION
45  
46 PAGI::Server::ConnectionState provides a mechanism for applications to detect
47 client disconnection without consuming messages from the receive queue.
48  
49 This addresses a fundamental limitation in the PAGI (and ASGI) model where
50 checking for disconnect via C<receive()> may inadvertently consume request
51 body data.
52  
53 The C<disconnect_future()> method lazily creates a Future only when called,
54 avoiding allocation overhead for simple request/response handlers that don't
55 need async disconnect detection.
56  
57 See the "Connection State" section in L<PAGI::Spec::Www> for the full
58 specification.
59  
60 =head1 METHODS
61  
62 =head2 new
63  
64 my $conn = PAGI::Server::ConnectionState->new(connection => $connection);
65  
66 Creates a new connection state object. The C<connection> argument provides
67 a reference to the parent Connection object for lazy Future creation.
68  
69 =cut
70  
71 385 ▶sub new {
Subroutine new: called CC=2 SCAR=6.9
Pod documented
72 385 my ($class, %args) = @_;
73  
74 385 my $connected = 1;
75 385 my $reason = undef;
76  
77 my $self = bless {
78 # Connection reference for lazy Future creation (will be weakened)
79 _connection => $args{connection},
80  
81 # Not weakened: diagnostics must survive the connection going away.
82 _server => $args{server},
83  
84 # State (scalar refs - for internal consistency)
85 385 _connected => \$connected,
86 _reason => \$reason,
87  
88 # Distinguishes the two terminal states once _connected is false:
89 # an abnormal disconnect (false) vs. a clean completion (true).
90 _completed => 0,
91  
92 # Response progress (HTTP): set when http.response.start is emitted.
93 _response_started => 0,
94  
95 # Lazy Future (only created if disconnect_future() called)
96 _future => undef,
97  
98 # Callbacks registered via on_disconnect()
99 _callbacks => [],
100  
101 # Callbacks registered via on_complete()
102 _complete_callbacks => [],
103 }, $class;
104  
105 # Weaken to avoid circular reference: Connection -> ConnectionState -> Connection
106 385 ▶ weaken($self->{_connection}) if $self->{_connection};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_connection"} 351 34 385
107  
108 385 return $self;
109 }
110  
111 =head2 is_connected
112  
113 my $connected = $conn->is_connected; # Boolean
114  
115 Returns true if the connection is still open, false if disconnected.
116  
117 This is a synchronous, non-destructive check that does not consume
118 messages from the receive queue.
119  
120 =cut
121  
122 22 ▶sub is_connected {
Subroutine is_connected: called CC=2 SCAR=6.9
Pod documented
123 22 my $self = shift;
124 22 ▶ return ${$self->{_connected}} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
${$self->{'_connected'};} ? : 8 14 22
125 }
126  
127 =head2 response_started
128  
129 my $started = $conn->response_started; # 0 or 1
130  
131 True once the server has started this request's response (C<http.response.start>
132 emitted -- by the application, a framework, a middleware, or a server-synthesized
133 error/backstop response). Server-owned; read-only to applications.
134  
135 =cut
136  
137 9 ▶sub response_started { return $_[0]->{_response_started} ? 1 : 0 }
Subroutine response_started: called CC=2 SCAR=6.9
Pod documented
Branch: 1 branch
BranchTrueFalseTotal
$_[0]{'_response_started'} ? : 5 4 9
138  
139 # Server-internal: called from the send path when http.response.start is emitted.
140 339 ▶sub _mark_response_started { $_[0]->{_response_started} = 1; return }
Subroutine _mark_response_started: called CC=1 SCAR=0.0
141  
142 =head2 response_complete
143  
144 my $done = $conn->response_complete; # undef = unsupported, else 0 or 1
145  
146 Returns true once this request's response body has been fully sent, false
147 while a response is still streaming or has not started, and C<undef> if the
148 server does not track completion. This server does not currently track
149 response-body completion, so this accessor always returns C<undef>. SHOULD-level
150 per L<PAGI::Spec::Www/"Connection State">; test C<defined> before relying on it.
151  
152 =cut
153  
154 1 ▶sub response_complete { return undef }
Subroutine response_complete: called CC=1 SCAR=0.0
Pod documented
155  
156 =head2 disconnect_reason
157  
158 my $reason = $conn->disconnect_reason; # String or undef
159  
160 Returns the disconnect reason string, or C<undef> if still connected B<or if the
161 request completed normally> -- every reason below describes an abnormal end.
162  
163 Standard reason strings:
164  
165 =over 4
166  
167 =item * C<client_closed> - Client initiated clean close (TCP FIN) mid-request
168  
169 =item * C<client_timeout> - Client stopped responding (read timeout)
170  
171 =item * C<idle_timeout> - Connection or stream idle too long, before a request arrived or mid-stream on a quiet WebSocket or SSE session
172  
173 =item * C<keepalive_timeout> - Keep-alive connection idled out between requests, or a WebSocket keepalive ping received no pong within its timeout
174  
175 =item * C<write_timeout> - Response write timed out
176  
177 =item * C<write_error> - Socket write failed (EPIPE, ECONNRESET)
178  
179 =item * C<read_error> - Socket read failed
180  
181 =item * C<protocol_error> - HTTP parse error, invalid request
182  
183 =item * C<server_shutdown> - Server shutting down gracefully
184  
185 =item * C<server_error> - Unhandled server-side error aborted the request
186  
187 =item * C<body_too_large> - Request body exceeded limit
188  
189 =item * C<queue_overflow> - A bounded server queue overflowed; connection dropped
190  
191 =back
192  
193 See L<PAGI::Spec::Www/"Standard Disconnect Reasons"> for the authoritative list.
194  
195 =cut
196  
197 137 ▶sub disconnect_reason {
Subroutine disconnect_reason: called CC=1 SCAR=0.0
Pod documented
198 137 my $self = shift;
199 137 return ${$self->{_reason}};
200 }
201  
202 =head2 disconnect_future
203  
204 my $future = $conn->disconnect_future; # always a Future
205 my $reason = await $future;
206  
207 Returns a Future that resolves when the connection closes B<abnormally>
208 (client disconnect, transport error). On a clean completion the connection
209 closes but this Future is deliberately left pending — use C<on_complete> to
210 observe normal completion.
211  
212 The Future is created lazily on first call, avoiding allocation overhead
213 for handlers that don't need async disconnect detection. Its behavior
214 depends on which of the three connection states is current at call time:
215  
216 =over 4
217  
218 =item * B<connected> — a fresh, pending Future is returned; it resolves
219 later if C<_mark_disconnected> occurs.
220  
221 =item * B<disconnected (abnormal)> — a Future already resolved with the
222 disconnect reason is returned.
223  
224 =item * B<completed (clean)> — a Future is returned and left pending
225 forever; the completion already happened and was not a disconnect, so
226 there is nothing for it to resolve with.
227  
228 =back
229  
230 The Future resolves with the disconnect reason string.
231  
232 Each call returns a B<cancellation-isolated> observer of one private
233 master future (per the PAGI spec's Connection State section): cancelling
234 a returned Future — directly, or implicitly as the losing component of a
235 combinator such as C<< Future->wait_any >> — never disturbs the
236 connection's disconnect processing or a Future returned by another call.
237 Take a fresh one for each race; a Future that lost one race cannot win a
238 later one.
239  
240 This is useful for racing against other async operations:
241  
242 await Future->wait_any($disconnect_future, $event_future);
243  
244 =cut
245  
246 14 ▶sub disconnect_future {
Subroutine disconnect_future: called CC=7 SCAR=19.9
Pod documented
247 14 my $self = shift;
248  
249 14 ▶ unless ($self->{_future}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_future"}) 9 5 14
250 # Create new Future (lazy)
251 9 my $conn = $self->{_connection};
252 9 ▶ my $loop = $conn && $conn->{server} ? $conn->{server}->loop : undef;
Branch: 1 branch
BranchTrueFalseTotal
$conn && $conn->{'server'} ? : 0 9 9
Condition33%1/3
$conn and $conn->{"server"}
!ll&&!rl&&r
900
MC/DC0%0/2
$conn and $conn->{"server"}
$conn $conn->{"server"}
Truth table33%1/3
A and B
A= $connB= $conn->{"server"}
ABresult
0X0
100
111
253  
254 9 ▶ if ($loop) {
Branch: 1 branch
BranchTrueFalseTotal
if ($loop) { } 0 9 9
255 0 $self->{_future} = $loop->new_future;
256 } else {
257 # Fallback if no loop available (shouldn't happen in practice)
258 9 require Future;
259 9 $self->{_future} = Future->new;
260 }
261  
262 # Resolve immediately only for an ABNORMAL end. After a clean completion
263 # the connection is closed but this Future is deliberately left pending —
264 # completion is not a disconnect (on_complete is the completion signal).
265 9 ▶ if (!${$self->{_connected}} && !$self->{_completed}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (${$self->{"_connected"};} or $self->{"_completed"}) 3 6 9
Condition100%3/3
${$self->{"_connected"};} or $self->{"_completed"}
l!l&&r!l&&!r
513
MC/DC100%2/2
${$self->{"_connected"};} or $self->{"_completed"}
${$self->{"_connected"};} $self->{"_completed"}
Truth table100%3/3
A or B
A= ${$self->{"_connected"};}B= $self->{"_completed"}
ABresult
1X1
011
000
266 3 $self->{_future}->done(${$self->{_reason}});
267 }
268 }
269  
270 # Cancellation-isolated observer per call (spec, Connection State):
271 # cancelling a returned future — e.g. as a wait_any loser — must never
272 # disturb the connection's signal or other consumers. The cached master
273 # stays private; it alone is resolved at transition step 3.
274 14 return $self->{_future}->without_cancel;
275 }
276  
277 =head2 on_disconnect
278  
279 $conn->on_disconnect(sub {
280 my ($reason) = @_;
281 # cleanup code
282 });
283  
284 Registers a callback to be invoked when disconnect occurs.
285  
286 =over 4
287  
288 =item * May be called multiple times to register multiple callbacks
289  
290 =item * Callbacks are invoked in registration order
291  
292 =item * Callbacks receive the disconnect reason as the first argument
293  
294 =item * If registered after disconnect already occurred, callback is
295 invoked immediately with the reason
296  
297 =item * One callback's failure does not prevent other callbacks from
298 being invoked
299  
300 =back
301  
302 =cut
303  
304 38 ▶sub on_disconnect {
Subroutine on_disconnect: called CC=4 SCAR=13.9
Pod documented
305 38 my ($self, $cb) = @_;
306  
307 # Still in flight: register for later.
308 38 ▶ if (${$self->{_connected}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (${$self->{"_connected"};}) 35 3 38
309 35 push @{$self->{_callbacks}}, $cb;
310 35 return;
311 }
312  
313 # Terminal: only fire if the request ended abnormally, not on clean
314 # completion (on_disconnect means "something went wrong").
315 3 ▶ return if $self->{_completed};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_completed"} 1 2 3
316  
317 2 eval { $cb->(${$self->{_reason}}) };
318 2 ▶ $self->_log(error => "on_disconnect callback error: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 1 2
319 }
320  
321 =head2 on_complete
322  
323 $conn->on_complete(sub {
324 # request finished cleanly
325 });
326  
327 Registers a callback invoked B<only when the request completes successfully>
328 (the response was fully delivered without the client disconnecting). It is the
329 counterpart to L</on_disconnect>: exactly one of the two fires for a given
330 request.
331  
332 =over 4
333  
334 =item * May be called multiple times to register multiple callbacks
335  
336 =item * Callbacks are invoked in registration order, with no arguments
337  
338 =item * If registered after the request already completed, the callback is
339 invoked immediately
340  
341 =item * If the request ended in an abnormal disconnect, the callback never fires
342  
343 =item * One callback's failure does not prevent other callbacks from being
344 invoked
345  
346 =back
347  
348 =cut
349  
350 34 ▶sub on_complete {
Subroutine on_complete: called CC=4 SCAR=13.9
Pod documented
351 34 my ($self, $cb) = @_;
352  
353 # Still in flight: register for later.
354 34 ▶ if (${$self->{_connected}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (${$self->{"_connected"};}) 33 1 34
355 33 push @{$self->{_complete_callbacks}}, $cb;
356 33 return;
357 }
358  
359 # Terminal: only fire on clean completion, not on abnormal disconnect.
360 1 ▶ return unless $self->{_completed};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"_completed"} 0 1 1
361  
362 1 eval { $cb->() };
363 1 ▶ $self->_log(error => "on_complete callback error: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 0 1 1
364 }
365  
366 =head2 _mark_disconnected
367  
368 $conn->_mark_disconnected($reason);
369  
370 B<Internal method> - Called by the server when disconnect is detected.
371  
372 Updates the connection state and invokes all registered callbacks.
373 Applications should not call this method directly.
374  
375 State transitions occur in this order:
376  
377 =over 4
378  
379 =item 1. C<is_connected()> returns false
380  
381 =item 2. C<disconnect_reason()> returns the reason string
382  
383 =item 3. C<disconnect_future()> resolves with the reason (if it was created)
384  
385 =item 4. C<on_disconnect> callbacks are invoked in registration order
386  
387 =back
388  
389 =cut
390  
391 90 ▶sub _mark_disconnected {
Subroutine _mark_disconnected: called CC=7 SCAR=19.5
392 90 my ($self, $reason) = @_;
393  
394 # Already disconnected - no-op (idempotent)
395 90 ▶ return unless ${$self->{_connected}};
Branch: 1 branch
BranchTrueFalseTotal
unless ${$self->{"_connected"};} 15 75 90
396  
397 # 1. Update state
398 75 ${$self->{_connected}} = 0;
399 75 ▶ ${$self->{_reason}} = $reason // 'unknown';
Condition50%1/2
$reason // "unknown"
l!l
750
MC/DC0%0/1
$reason // "unknown"
$reason
Truth table50%1/2
A
A= $reason
Aresult
11
00
400  
401 # 2. Resolve future if it exists (lazy - may not have been created)
402 75 ▶ if ($self->{_future} && !$self->{_future}->is_ready) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_future"} and not $self->{"_future"}->is_ready) 2 73 75
Condition66%2/3
$self->{"_future"} and not $self->{"_future"}->is_ready
!ll&&!rl&&r
7302
MC/DC50%1/2
$self->{"_future"} and not $self->{"_future"}->is_ready
$self->{"_future"} not $self->{"_future"}->is_ready
Truth table66%2/3
A and not(B)
A= $self->{"_future"}B= not $self->{"_future"}->is_ready
ABresult
0X0
100
111
403 2 $self->{_future}->done(${$self->{_reason}});
404 }
405  
406 # 3. Invoke callbacks
407 75 for my $cb (@{$self->{_callbacks}}) {
408 27 eval { $cb->(${$self->{_reason}}) };
409 27 ▶ $self->_log(error => "on_disconnect callback error: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 26 27
410 }
411  
412 # 4. Clear callbacks to release references. The request ended abnormally,
413 # so on_complete callbacks never run.
414 75 $self->{_callbacks} = [];
415 75 $self->{_complete_callbacks} = [];
416 }
417  
418 =head2 _mark_complete
419  
420 $conn->_mark_complete;
421  
422 B<Internal method> - Called by the server when the request completes
423 successfully (the response was fully delivered). Applications should not call
424 this method directly.
425  
426 Transitions to the C<completed> terminal state and invokes C<on_complete>
427 callbacks in registration order. Unlike L</_mark_disconnected>, it leaves
428 C<disconnect_reason()> as C<undef> and does B<not> resolve C<disconnect_future()>
429 or fire C<on_disconnect> callbacks -- a clean completion is not a disconnect.
430  
431 Idempotent, and a no-op once the connection has already reached a terminal
432 state (so a stray completion after an abnormal disconnect is ignored).
433  
434 =cut
435  
436 303 ▶sub _mark_complete {
Subroutine _mark_complete: called CC=4 SCAR=13.9
437 303 my ($self) = @_;
438  
439 # Already terminal (disconnected or completed) - no-op (idempotent).
440 303 ▶ return unless ${$self->{_connected}};
Branch: 1 branch
BranchTrueFalseTotal
unless ${$self->{"_connected"};} 2 301 303
441  
442 # Mark the completed terminal state. Reason stays undef; the disconnect
443 # Future is deliberately left pending (completion is not a disconnect).
444 301 ${$self->{_connected}} = 0;
445 301 $self->{_completed} = 1;
446  
447 # Invoke completion callbacks (no reason argument).
448 301 for my $cb (@{$self->{_complete_callbacks}}) {
449 15 eval { $cb->() };
450 15 ▶ $self->_log(error => "on_complete callback error: $@") if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 14 15
451 }
452  
453 # Clear both lists to release references.
454 301 $self->{_complete_callbacks} = [];
455 301 $self->{_callbacks} = [];
456 }
457  
458 # The server is passed in rather than reached for through _connection, which is
459 # weakened and may already be gone by the time a callback throws.
460 5 ▶sub _log {
Subroutine _log: called CC=2 SCAR=6.9
461 5 my ($self, $level, $msg) = @_;
462  
463 5 my $server = $self->{_server};
464 5 ▶ return $server->_log($level, $msg, __PACKAGE__) if $server;
Branch: 1 branch
BranchTrueFalseTotal
if $server 1 4 5
465  
466 4 warn "$msg\n";
467 4 return;
468 }
469  
470 157 1;
471  
472 __END__
« examples/08-tls-introspection/app.pl ↑ Summary bin/pagi-server »