blib/lib/PAGI/Server/ConnectionState.pm

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