blib/lib/PAGI/WebSocket.pm

filter: Statementstmt 100% 411 / 411 Branchbran 92.5% 137 / 148 Conditioncond 82.2% 65 / 79 MC/DCmcdc 66.6% 30 / 45 Subroutinesub 100% 79 / 79 Podpod 100% 58 / 58 totaltotal 95.1% 780 / 820 CC 115 SCAR 14.4
CC
115
Cov
96%
query_params
13.0
new
10.0
run
9.1
CRAP 4.2
« lib/PAGI/Middleware/SSE/Retry.pm ↑ Summary blib/lib/PAGI/Stash.pm »
1 package PAGI::WebSocket;
2 24 $PAGI::WebSocket::VERSION = '0.002002';
3 24 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 24 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 24 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 24 ▶use Encode qw(decode FB_CROAK FB_DEFAULT LEAVE_SRC);
Subroutine BEGIN: called CC=1 SCAR=0.0
7 24 ▶use Hash::MultiValue;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 24 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 24 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 24 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
11 24 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 171 ▶sub new {
Subroutine new: called CC=10 SCAR=23.1
Pod documented
15 171 my ($class, $scope, $receive, $send) = @_;
16  
17 171 ▶ croak "PAGI::WebSocket requires scope hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless $scope and ref $scope eq "HASH" 2 169 171
Condition100%3/3
$scope and ref $scope eq "HASH"
!ll&&!rl&&r
11169
MC/DC100%2/2
$scope and ref $scope eq "HASH"
$scope ref $scope eq "HASH"
Truth table100%3/3
A and B
A= $scopeB= ref $scope eq "HASH"
ABresult
0X0
100
111
18 unless $scope && ref($scope) eq 'HASH';
19 169 ▶ croak "PAGI::WebSocket requires receive coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless $receive and ref $receive eq "CODE" 2 167 169
Condition100%3/3
$receive and ref $receive eq "CODE"
!ll&&!rl&&r
11167
MC/DC100%2/2
$receive and ref $receive eq "CODE"
$receive ref $receive eq "CODE"
Truth table100%3/3
A and B
A= $receiveB= ref $receive eq "CODE"
ABresult
0X0
100
111
20 unless $receive && ref($receive) eq 'CODE';
21 167 ▶ croak "PAGI::WebSocket requires send coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless $send and ref $send eq "CODE" 2 165 167
Condition100%3/3
$send and ref $send eq "CODE"
!ll&&!rl&&r
11165
MC/DC100%2/2
$send and ref $send eq "CODE"
$send ref $send eq "CODE"
Truth table100%3/3
A and B
A= $sendB= ref $send eq "CODE"
ABresult
0X0
100
111
22 unless $send && ref($send) eq 'CODE';
23 croak "PAGI::WebSocket requires scope type 'websocket', got '$scope->{type}'"
24 165 ▶ unless ($scope->{type} // '') eq 'websocket';
Branch: 1 branch
BranchTrueFalseTotal
unless ($scope->{"type"} // "") eq "websocket" 1 164 165
Condition50%1/2
$scope->{"type"} // ""
l!l
1650
MC/DC0%0/1
$scope->{"type"} // ""
$scope->{"type"}
Truth table50%1/2
A
A= $scope->{"type"}
Aresult
11
00
25  
26 # Return existing WebSocket object if one was already created for this scope
27 # This ensures consistent state (is_connected, is_closed, callbacks) if
28 # multiple code paths create WebSocket objects from the same scope.
29 164 ▶ return $scope->{'pagi.websocket'} if $scope->{'pagi.websocket'};
Branch: 1 branch
BranchTrueFalseTotal
if $scope->{"pagi.websocket"} 0 164 164
30  
31 164 my $self = bless {
32 scope => $scope,
33 receive => $receive,
34 send => $send,
35 _state => 'connecting', # connecting -> connected -> closed
36 _close_code => undef,
37 _close_reason => undef,
38 _on_close => [],
39 _on_error => [],
40 _on_message => [],
41 }, $class;
42  
43 # Cache in scope for reuse (weakened to avoid circular reference leak)
44 164 $scope->{'pagi.websocket'} = $self;
45 164 Scalar::Util::weaken($scope->{'pagi.websocket'});
46  
47 164 return $self;
48 }
49  
50 # Scope property accessors
51 4 ▶sub scope { shift->{scope} }
Subroutine scope: called CC=1 SCAR=0.0
Pod documented
52 2 ▶sub path { shift->{scope}{path} }
Subroutine path: called CC=1 SCAR=0.0
Pod documented
53 2 ▶sub raw_path { my $s = shift; $s->{scope}{raw_path} // $s->{scope}{path} }
Subroutine raw_path: called CC=2 SCAR=7.1
Pod documented
Condition66%2/3
$s->{"scope"}{"raw_path"} // $s->{"scope"}{"path"}
l!l&&r!l&&!r
110
MC/DC0%0/2
$s->{"scope"}{"raw_path"} // $s->{"scope"}{"path"}
$s->{"scope"}{"raw_path"} $s->{"scope"}{"path"}
Truth table66%2/3
A // B
A= $s->{"scope"}{"raw_path"}B= $s->{"scope"}{"path"}
ABresult
1X1
011
000
54 19 ▶sub query_string { shift->{scope}{query_string} // '' }
Subroutine query_string: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
+(shift())->{"scope"}{"query_string"} // ""
l!l
181
MC/DC100%1/1
+(shift())->{"scope"}{"query_string"} // ""
+(shift())->{"scope"}{"query_string"}
Truth table100%2/2
A
A= +(shift())->{"scope"}{"query_string"}
Aresult
11
00
55 2 ▶sub scheme { shift->{scope}{scheme} // 'ws' }
Subroutine scheme: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
+(shift())->{"scope"}{"scheme"} // "ws"
l!l
11
MC/DC100%1/1
+(shift())->{"scope"}{"scheme"} // "ws"
+(shift())->{"scope"}{"scheme"}
Truth table100%2/2
A
A= +(shift())->{"scope"}{"scheme"}
Aresult
11
00
56 3 ▶sub http_version { shift->{scope}{http_version} // '1.1' }
Subroutine http_version: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
+(shift())->{"scope"}{"http_version"} // "1.1"
l!l
21
MC/DC100%1/1
+(shift())->{"scope"}{"http_version"} // "1.1"
+(shift())->{"scope"}{"http_version"}
Truth table100%2/2
A
A= +(shift())->{"scope"}{"http_version"}
Aresult
11
00
57 3 ▶sub subprotocols { shift->{scope}{subprotocols} // [] }
Subroutine subprotocols: called CC=2 SCAR=6.9
Pod documented
Condition100%2/2
+(shift())->{"scope"}{"subprotocols"} // []
l!l
21
MC/DC100%1/1
+(shift())->{"scope"}{"subprotocols"} // []
+(shift())->{"scope"}{"subprotocols"}
Truth table100%2/2
A
A= +(shift())->{"scope"}{"subprotocols"}
Aresult
11
00
58 1 ▶sub client { shift->{scope}{client} }
Subroutine client: called CC=1 SCAR=0.0
Pod documented
59 1 ▶sub server { shift->{scope}{server} }
Subroutine server: called CC=1 SCAR=0.0
Pod documented
60  
61  
62 # Application state (injected by PAGI::Lifespan, read-only)
63 6 ▶sub state {
Subroutine state: called CC=2 SCAR=6.9
Pod documented
64 6 my $self = shift;
65 6 ▶ return $self->{scope}{state} // {};
Condition100%2/2
$self->{"scope"}{"state"} // {}
l!l
42
MC/DC100%1/1
$self->{"scope"}{"state"} // {}
$self->{"scope"}{"state"}
Truth table100%2/2
A
A= $self->{"scope"}{"state"}
Aresult
11
00
66 }
67  
68 # Path parameter accessors - captured from URL path by router
69 # Stored in scope->{path_params} for router-agnostic access
70 2 ▶sub path_params {
Subroutine path_params: called CC=2 SCAR=6.9
Pod documented
71 2 my ($self) = @_;
72 2 ▶ return $self->{scope}{path_params} // {};
Condition100%2/2
$self->{"scope"}{"path_params"} // {}
l!l
11
MC/DC100%1/1
$self->{"scope"}{"path_params"} // {}
$self->{"scope"}{"path_params"}
Truth table100%2/2
A
A= $self->{"scope"}{"path_params"}
Aresult
11
00
73 }
74  
75 6 ▶sub path_param {
Subroutine path_param: called CC=2 SCAR=6.9
Pod documented
76 6 my ($self, $name) = @_;
77 6 ▶ my $params = $self->{scope}{path_params} // {};
Condition100%2/2
$self->{"scope"}{"path_params"} // {}
l!l
51
MC/DC100%1/1
$self->{"scope"}{"path_params"} // {}
$self->{"scope"}{"path_params"}
Truth table100%2/2
A
A= $self->{"scope"}{"path_params"}
Aresult
11
00
78 6 return $params->{$name};
79 }
80  
81 # Internal: URL decode a string (handles + as space)
82 58 ▶sub _url_decode {
Subroutine _url_decode: called CC=2 SCAR=7.0
83 58 my ($str) = @_;
84 58 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 58 58
85 58 $str =~ s/\+/ /g;
86 58 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
87 58 return $str;
88 }
89  
90 # Internal: Decode UTF-8 with replacement or croak in strict mode
91 50 ▶sub _decode_utf8 {
Subroutine _decode_utf8: called CC=3 SCAR=11.0
92 50 my ($str, $strict) = @_;
93 50 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 50 50
94 50 ▶ my $flag = $strict ? FB_CROAK : FB_DEFAULT;
Branch: 1 branch
BranchTrueFalseTotal
$strict ? : 2 48 50
95 50 $flag |= LEAVE_SRC;
96 50 return decode('UTF-8', $str, $flag);
97 }
98  
99 # Query params as Hash::MultiValue (cached in scope)
100 # Options: strict => 1 (croak on invalid UTF-8), raw => 1 (skip UTF-8 decoding)
101 32 ▶sub query_params {
Subroutine query_params: called CC=13 SCAR=25.7
Pod documented
102 32 my ($self, %opts) = @_;
103 32 ▶ my $strict = delete $opts{strict} // 0;
Condition100%2/2
delete $opts{"strict"} // 0
l!l
131
MC/DC100%1/1
delete $opts{"strict"} // 0
delete $opts{"strict"}
Truth table100%2/2
A
A= delete $opts{"strict"}
Aresult
11
00
104 32 ▶ my $raw = delete $opts{raw} // 0;
Condition100%2/2
delete $opts{"raw"} // 0
l!l
626
MC/DC100%1/1
delete $opts{"raw"} // 0
delete $opts{"raw"}
Truth table100%2/2
A
A= delete $opts{"raw"}
Aresult
11
00
105 32 ▶ croak("Unknown options to query_params: " . join(', ', keys %opts)) if %opts;
Branch: 1 branch
BranchTrueFalseTotal
if %opts 1 31 32
106  
107 31 ▶ my $cache_key = $raw ? 'pagi.websocket.query.raw' : ($strict ? 'pagi.websocket.query.strict' : 'pagi.websocket.query');
Branch: 2 branches
BranchTrueFalseTotal
$raw ? : 6 25 31
$strict ? : 1 24 25
108 31 ▶ return $self->{scope}{$cache_key} if $self->{scope}{$cache_key};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"scope"}{$cache_key} 14 17 31
109  
110 17 my $qs = $self->query_string;
111 17 my @pairs;
112  
113 17 for my $part (split /[&;]/, $qs) {
114 29 ▶ next unless length $part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $part 0 29 29
115 29 my ($key, $val) = split /=/, $part, 2;
116 29 ▶ $key //= '';
Condition50%1/2
$key //= ""
l!l
290
MC/DC0%0/1
$key //= ""
$key
Truth table50%1/2
A
A= $key
Aresult
11
00
117 29 ▶ $val //= '';
Condition100%2/2
$val //= ""
l!l
281
MC/DC100%1/1
$val //= ""
$val
Truth table100%2/2
A
A= $val
Aresult
11
00
118  
119 # URL decode (handles + as space)
120 29 my $key_decoded = _url_decode($key);
121 29 my $val_decoded = _url_decode($val);
122  
123 # UTF-8 decode unless raw mode
124 29 ▶ my $key_final = $raw ? $key_decoded : _decode_utf8($key_decoded, $strict);
Branch: 1 branch
BranchTrueFalseTotal
$raw ? : 4 25 29
125 29 ▶ my $val_final = $raw ? $val_decoded : _decode_utf8($val_decoded, $strict);
Branch: 1 branch
BranchTrueFalseTotal
$raw ? : 4 25 29
126  
127 28 push @pairs, $key_final, $val_final;
128 }
129  
130 16 $self->{scope}{$cache_key} = Hash::MultiValue->new(@pairs);
131 16 return $self->{scope}{$cache_key};
132 }
133  
134 # Raw query params (no UTF-8 decoding)
135 2 ▶sub raw_query_params {
Subroutine raw_query_params: called CC=1 SCAR=0.0
Pod documented
136 2 my $self = shift;
137 2 return $self->query_params(raw => 1);
138 }
139  
140 # Shortcut for single query param
141 23 ▶sub query {
Subroutine query: called CC=1 SCAR=0.0
Pod documented
142 23 my ($self, $name, %opts) = @_;
143 23 return $self->query_params(%opts)->get($name);
144 }
145  
146 # Raw single query param
147 2 ▶sub raw_query {
Subroutine raw_query: called CC=1 SCAR=0.0
Pod documented
148 2 my ($self, $name) = @_;
149 2 return $self->query($name, raw => 1);
150 }
151  
152 # Single header lookup (case-insensitive, returns last value)
153 4 ▶sub header {
Subroutine header: called CC=4 SCAR=13.9
Pod documented
154 4 my ($self, $name) = @_;
155 4 $name = lc($name);
156 4 my $value;
157 4 ▶ for my $pair (@{$self->{scope}{headers} // []}) {
Condition50%1/2
$self->{"scope"}{"headers"} // []
l!l
40
MC/DC0%0/1
$self->{"scope"}{"headers"} // []
$self->{"scope"}{"headers"}
Truth table50%1/2
A
A= $self->{"scope"}{"headers"}
Aresult
11
00
158 20 ▶ if (lc($pair->[0]) eq $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $pair->[0] eq $name) 4 16 20
159 4 $value = $pair->[1];
160 }
161 }
162 4 return $value;
163 }
164  
165 # All headers as Hash::MultiValue (cached in scope)
166 3 ▶sub headers {
Subroutine headers: called CC=4 SCAR=13.9
Pod documented
167 3 my $self = shift;
168 3 ▶ return $self->{scope}{'pagi.request.headers'} if $self->{scope}{'pagi.request.headers'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"scope"}{"pagi.request.headers"} 1 2 3
169  
170 2 my @pairs;
171 2 ▶ for my $pair (@{$self->{scope}{headers} // []}) {
Condition50%1/2
$self->{"scope"}{"headers"} // []
l!l
20
MC/DC0%0/1
$self->{"scope"}{"headers"} // []
$self->{"scope"}{"headers"}
Truth table50%1/2
A
A= $self->{"scope"}{"headers"}
Aresult
11
00
172 8 push @pairs, lc($pair->[0]), $pair->[1];
173 }
174  
175 2 $self->{scope}{'pagi.request.headers'} = Hash::MultiValue->new(@pairs);
176 2 return $self->{scope}{'pagi.request.headers'};
177 }
178  
179 # All values for a header
180 2 ▶sub header_all {
Subroutine header_all: called CC=1 SCAR=0.0
Pod documented
181 2 my ($self, $name) = @_;
182 2 return $self->headers->get_all(lc($name));
183 }
184  
185 # State accessors
186 4 ▶sub connection_state { shift->{_state} }
Subroutine connection_state: called CC=1 SCAR=0.0
Pod documented
187  
188 19 ▶sub is_connected {
Subroutine is_connected: called CC=1 SCAR=0.0
Pod documented
189 19 my $self = shift;
190 19 return $self->{_state} eq 'connected';
191 }
192  
193 151 ▶sub is_closed {
Subroutine is_closed: called CC=1 SCAR=0.0
Pod documented
194 151 my $self = shift;
195 151 return $self->{_state} eq 'closed';
196 }
197  
198 61 ▶sub close_code { shift->{_close_code} }
Subroutine close_code: called CC=1 SCAR=0.0
Pod documented
199 58 ▶sub close_reason { shift->{_close_reason} }
Subroutine close_reason: called CC=1 SCAR=0.0
Pod documented
200  
201 # Outbound flow-control introspection (delegates to the pagi.transport handle)
202 2 ▶sub buffered_amount {
Subroutine buffered_amount: called CC=2 SCAR=6.9
Pod documented
203 2 my $self = shift;
204 2 my $t = $self->{scope}{'pagi.transport'};
205 2 ▶ return 0 unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
206 1 return $t->buffered_amount;
207 }
208  
209 2 ▶sub high_water_mark {
Subroutine high_water_mark: called CC=2 SCAR=6.9
Pod documented
210 2 my $self = shift;
211 2 my $t = $self->{scope}{'pagi.transport'};
212 2 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
213 1 return $t->high_water_mark;
214 }
215  
216 2 ▶sub low_water_mark {
Subroutine low_water_mark: called CC=2 SCAR=6.9
Pod documented
217 2 my $self = shift;
218 2 my $t = $self->{scope}{'pagi.transport'};
219 2 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
220 1 return $t->low_water_mark;
221 }
222  
223 2 ▶sub on_high_water {
Subroutine on_high_water: called CC=3 SCAR=11.0
Pod documented
224 2 my ($self, $cb) = @_;
225 2 my $t = $self->{scope}{'pagi.transport'};
226 2 ▶ $t->on_high_water($cb) if $t && $t->can('on_high_water');
Branch: 1 branch
BranchTrueFalseTotal
if $t and $t->can("on_high_water") 1 1 2
Condition66%2/3
$t and $t->can("on_high_water")
!ll&&!rl&&r
011
MC/DC50%1/2
$t and $t->can("on_high_water")
$t $t->can("on_high_water")
Truth table66%2/3
A and B
A= $tB= $t->can("on_high_water")
ABresult
0X0
100
111
227 2 return $self;
228 }
229  
230 2 ▶sub on_drain {
Subroutine on_drain: called CC=3 SCAR=11.0
Pod documented
231 2 my ($self, $cb) = @_;
232 2 my $t = $self->{scope}{'pagi.transport'};
233 2 ▶ $t->on_drain($cb) if $t && $t->can('on_drain');
Branch: 1 branch
BranchTrueFalseTotal
if $t and $t->can("on_drain") 1 1 2
Condition66%2/3
$t and $t->can("on_drain")
!ll&&!rl&&r
011
MC/DC50%1/2
$t and $t->can("on_drain")
$t $t->can("on_drain")
Truth table66%2/3
A and B
A= $tB= $t->can("on_drain")
ABresult
0X0
100
111
234 2 return $self;
235 }
236  
237 3 ▶sub is_writable {
Subroutine is_writable: called CC=4 SCAR=13.9
Pod documented
238 3 my $self = shift;
239 3 my $t = $self->{scope}{'pagi.transport'};
240 3 ▶ return 1 unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 2 3
241 2 my $high = $t->high_water_mark;
242 2 ▶ return 1 unless defined $high;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $high 0 2 2
243 2 ▶ return $t->buffered_amount < $high ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$t->buffered_amount < $high ? : 1 1 2
244 }
245  
246 # Internal state setters
247 109 ▶sub _set_state {
Subroutine _set_state: called CC=1 SCAR=0.0
248 109 my ($self, $state) = @_;
249 109 $self->{_state} = $state;
250 }
251  
252 50 ▶sub _set_closed {
Subroutine _set_closed: called CC=3 SCAR=11.0
253 50 my ($self, $code, $reason) = @_;
254 50 $self->{_state} = 'closed';
255 50 ▶ $self->{_close_code} = $code // 1005;
Condition100%2/2
$code // 1005
l!l
491
MC/DC100%1/1
$code // 1005
$code
Truth table100%2/2
A
A= $code
Aresult
11
00
256 50 ▶ $self->{_close_reason} = $reason // '';
Condition100%2/2
$reason // ""
l!l
491
MC/DC100%1/1
$reason // ""
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
257 }
258  
259 # Register callback to run on disconnect/close
260 22 ▶sub on_close {
Subroutine on_close: called CC=1 SCAR=0.0
Pod documented
261 22 my ($self, $callback) = @_;
262 22 push @{$self->{_on_close}}, $callback;
263 22 return $self;
264 }
265  
266 # Internal: run all on_close callbacks exactly once
267 49 ▶async sub _run_close_callbacks {
Subroutine _run_close_callbacks: called CC=6 SCAR=17.9
268 49 my ($self) = @_;
269  
270 # Only run once
271 49 ▶ return if $self->{_close_callbacks_ran};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_close_callbacks_ran"} 0 49 49
272 49 $self->{_close_callbacks_ran} = 1;
273  
274 49 my $code = $self->close_code;
275 49 my $reason = $self->close_reason;
276  
277 49 for my $cb (@{$self->{_on_close}}) {
278 20 eval {
279 20 my $r = $cb->($code, $reason);
280 # Only await if callback returns a Future
281 20 ▶ if (blessed($r) && $r->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($r) and $r->isa("Future")) 14 6 20
Condition100%3/3
builtin::blessed($r) and $r->isa("Future")
!ll&&!rl&&r
5114
MC/DC100%2/2
builtin::blessed($r) and $r->isa("Future")
builtin::blessed($r) $r->isa("Future")
Truth table100%3/3
A and B
A= builtin::blessed($r)B= $r->isa("Future")
ABresult
0X0
100
111
282 14 await $r;
283 }
284 };
285 20 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 19 20
286 1 warn "PAGI::WebSocket on_close callback error: $@";
287 }
288 }
289  
290 # Clear all callback arrays to break any closure-based cycles
291 49 $self->{_on_close} = [];
292 49 $self->{_on_error} = [];
293 49 $self->{_on_message} = [];
294 24 }
295  
296 # Internal: mark closed and fire on_close callbacks for a disconnect that
297 # arrived directly off the wire (not via close()). Shared by receive()'s own
298 # disconnect handling and PAGI::Context::WebSocket's _sync_terminal_disconnect
299 # hook (fired when the disconnect is instead consumed via $ctx->run()). Does
300 # NOT send a websocket.close wire event -- the peer is already gone.
301 28 ▶async sub _note_disconnected {
Subroutine _note_disconnected: called CC=3 SCAR=11.0
302 28 my ($self, $code, $reason) = @_;
303  
304 # 1005 = No Status Rcvd (RFC 6455)
305 28 ▶ $self->_set_closed($code // 1005, $reason // '');
Condition100%4/4
$code // 1005
l!l
208
$reason // ""
l!l
523
MC/DC100%1/1
$code // 1005
$code
MC/DC100%1/1
$reason // ""
$reason
Truth table100%2/2
A
A= $code
Aresult
11
00
Truth table100%2/2
A
A= $reason
Aresult
11
00
306 28 await $self->_run_close_callbacks;
307 28 return;
308 24 }
309  
310 # Register callback to run on errors
311 10 ▶sub on_error {
Subroutine on_error: called CC=1 SCAR=0.0
Pod documented
312 10 my ($self, $callback) = @_;
313 10 push @{$self->{_on_error}}, $callback;
314 10 return $self;
315 }
316  
317 # Register callback to run on message receive
318 12 ▶sub on_message {
Subroutine on_message: called CC=1 SCAR=0.0
Pod documented
319 12 my ($self, $callback) = @_;
320 12 push @{$self->{_on_message}}, $callback;
321 12 return $self;
322 }
323  
324 # Generic event registration (Socket.IO style)
325 8 ▶sub on {
Subroutine on: called CC=4 SCAR=13.9
Pod documented
326 8 my ($self, $event, $callback) = @_;
327  
328 8 ▶ if ($event eq 'message') {
Branch: 3 branches
BranchTrueFalseTotal
if ($event eq 'message') { } 3 5 8
elsif ($event eq 'close') { } 2 3 5
elsif ($event eq 'error') { } 2 1 3
329 3 return $self->on_message($callback);
330 }
331 elsif ($event eq 'close') {
332 2 return $self->on_close($callback);
333 }
334 elsif ($event eq 'error') {
335 2 return $self->on_error($callback);
336 }
337 else {
338 1 croak "Unknown event type: $event (expected message, close, or error)";
339 }
340 }
341  
342 # Internal: trigger error callbacks
343 7 ▶async sub _trigger_error {
Subroutine _trigger_error: called CC=6 SCAR=17.9
344 7 my ($self, $error) = @_;
345  
346 7 for my $cb (@{$self->{_on_error}}) {
347 8 eval {
348 8 my $r = $cb->($error);
349 8 ▶ if (blessed($r) && $r->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($r) and $r->isa("Future")) 2 6 8
Condition66%2/3
builtin::blessed($r) and $r->isa("Future")
!ll&&!rl&&r
602
MC/DC50%1/2
builtin::blessed($r) and $r->isa("Future")
builtin::blessed($r) $r->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($r)B= $r->isa("Future")
ABresult
0X0
100
111
350 2 await $r;
351 }
352 };
353 8 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 1 7 8
354 1 warn "PAGI::WebSocket on_error callback error: $@";
355 }
356 }
357  
358 # If no error handlers registered, warn
359 7 ▶ if (!@{$self->{_on_error}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @{$self->{"_on_error"};}) 1 6 7
360 1 warn "PAGI::WebSocket error: $error";
361 }
362 24 }
363  
364 # Accept the WebSocket connection
365 100 ▶async sub accept {
Subroutine accept: called CC=3 SCAR=11.0
Pod documented
366 100 my ($self, %opts) = @_;
367  
368 100 my $event = {
369 type => 'websocket.accept',
370 };
371 100 ▶ $event->{subprotocol} = $opts{subprotocol} if exists $opts{subprotocol};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"subprotocol"} 2 98 100
372 100 ▶ $event->{headers} = $opts{headers} if exists $opts{headers};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"headers"} 2 98 100
373  
374 100 await $self->{send}->($event);
375 100 $self->_set_state('connected');
376  
377 100 return $self;
378 24 }
379  
380 # Close the WebSocket connection
381 19 ▶async sub close {
Subroutine close: called CC=4 SCAR=13.9
Pod documented
382 19 my ($self, $code, $reason) = @_;
383  
384 # Idempotent - don't send close twice
385 19 ▶ return if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 3 16 19
386  
387 16 ▶ $code //= 1000;
Condition100%2/2
$code //= 1000
l!l
313
MC/DC100%1/1
$code //= 1000
$code
Truth table100%2/2
A
A= $code
Aresult
11
00
388 16 ▶ $reason //= '';
Condition100%2/2
$reason //= ""
l!l
313
MC/DC100%1/1
$reason //= ""
$reason
Truth table100%2/2
A
A= $reason
Aresult
11
00
389  
390 16 await $self->{send}->({
391 type => 'websocket.close',
392 code => $code,
393 reason => $reason,
394 });
395  
396 16 $self->_set_closed($code, $reason);
397 16 await $self->_run_close_callbacks;
398  
399 16 return $self;
400 24 }
401  
402 # Whether the server advertised the WebSocket denial-response extension.
403 # See L<PAGI::Spec::Www/"WebSocket Denial Response">.
404 11 ▶sub supports_denial_response {
Subroutine supports_denial_response: called CC=2 SCAR=6.9
Pod documented
405 11 my $self = shift;
406 11 ▶ return $self->{scope}{extensions}{'websocket.http.response'} ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$self->{'scope'}{'extensions'}{'websocket.http.response'} ? : 5 6 11
407 }
408  
409 # Reject the handshake with a custom HTTP response (status/headers/body) instead
410 # of the bare 403. Falls back to a plain close when the server does not advertise
411 # the extension. Valid only before accept.
412 # See L<PAGI::Spec::Www/"WebSocket Denial Response">.
413 6 ▶async sub deny {
Subroutine deny: called CC=5 SCAR=16.1
Pod documented
414 6 my ($self, %opts) = @_;
415  
416 6 ▶ my $status = $opts{status} // 403;
Condition50%1/2
$opts{"status"} // 403
l!l
60
MC/DC0%0/1
$opts{"status"} // 403
$opts{"status"}
Truth table50%1/2
A
A= $opts{"status"}
Aresult
11
00
417 6 ▶ my $headers = $opts{headers} // [];
Condition100%2/2
$opts{"headers"} // []
l!l
15
MC/DC100%1/1
$opts{"headers"} // []
$opts{"headers"}
Truth table100%2/2
A
A= $opts{"headers"}
Aresult
11
00
418 6 ▶ my $body = defined $opts{body} ? $opts{body} : '';
Branch: 1 branch
BranchTrueFalseTotal
defined $opts{'body'} ? : 2 4 6
419  
420 6 ▶ if (!$self->supports_denial_response) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->supports_denial_response) 3 3 6
421 3 await $self->{send}->({ type => 'websocket.close', code => 1008, reason => '' });
422 3 $self->_set_closed(1008, '');
423 3 return $self;
424 }
425  
426 await $self->{send}->({
427 type => 'websocket.http.response.start',
428 status => $status,
429 headers => $headers,
430 3 });
431 3 await $self->{send}->({
432 type => 'websocket.http.response.body',
433 body => $body,
434 more => 0,
435 });
436  
437 # An HTTP denial sends a response, not a WebSocket close frame — there is no
438 # RFC6455 close code, so mark closed without recording one (close_code stays
439 # undef). The bare-403 fallback above DID send a real close frame and keeps
440 # its 1008 via _set_closed.
441 3 $self->{_state} = 'closed';
442 3 return $self;
443 24 }
444  
445 # Send text message
446 7 ▶async sub send_text {
Subroutine send_text: called CC=2 SCAR=6.9
Pod documented
447 7 my ($self, $text) = @_;
448  
449 7 ▶ croak "Cannot send on closed WebSocket" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 6 7
450  
451 6 await $self->{send}->({
452 type => 'websocket.send',
453 text => $text,
454 });
455  
456 6 return $self;
457 24 }
458  
459 # Send binary message
460 3 ▶async sub send_bytes {
Subroutine send_bytes: called CC=2 SCAR=6.9
Pod documented
461 3 my ($self, $bytes) = @_;
462  
463 3 ▶ croak "Cannot send on closed WebSocket" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 2 3
464  
465 2 await $self->{send}->({
466 type => 'websocket.send',
467 bytes => $bytes,
468 });
469  
470 2 return $self;
471 24 }
472  
473 # Send JSON-encoded message
474 6 ▶async sub send_json {
Subroutine send_json: called CC=2 SCAR=6.9
Pod documented
475 6 my ($self, $data) = @_;
476  
477 6 ▶ croak "Cannot send on closed WebSocket" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 5 6
478  
479 5 my $json = JSON::MaybeXS::encode_json($data);
480  
481 5 await $self->{send}->({
482 type => 'websocket.send',
483 text => $json,
484 });
485  
486 5 return $self;
487 24 }
488  
489 # Safe send methods - return bool instead of throwing
490  
491 8 ▶async sub try_send_text {
Subroutine try_send_text: called CC=3 SCAR=11.0
Pod documented
492 8 my ($self, $text) = @_;
493 8 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 2 6 8
494  
495 6 eval {
496 6 await $self->{send}->({
497 type => 'websocket.send',
498 text => $text,
499 });
500 };
501 # A failed send is not a disconnect (a send after close is a silent no-op per
502 # spec), so return false per the try_* contract without fabricating a 1006
503 # close or mutating connection state.
504 6 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 4 6
505 4 return 1;
506 24 }
507  
508 7 ▶async sub try_send_bytes {
Subroutine try_send_bytes: called CC=3 SCAR=11.0
Pod documented
509 7 my ($self, $bytes) = @_;
510 7 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 6 7
511  
512 6 eval {
513 6 await $self->{send}->({
514 type => 'websocket.send',
515 bytes => $bytes,
516 });
517 };
518 # A failed send is not a disconnect (a send after close is a silent no-op per
519 # spec), so return false per the try_* contract without fabricating a 1006
520 # close or mutating connection state.
521 6 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 4 6
522 4 return 1;
523 24 }
524  
525 7 ▶async sub try_send_json {
Subroutine try_send_json: called CC=3 SCAR=11.0
Pod documented
526 7 my ($self, $data) = @_;
527 7 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 6 7
528  
529 6 my $json = JSON::MaybeXS::encode_json($data);
530 6 eval {
531 6 await $self->{send}->({
532 type => 'websocket.send',
533 text => $json,
534 });
535 };
536 # A failed send is not a disconnect (a send after close is a silent no-op per
537 # spec), so return false per the try_* contract without fabricating a 1006
538 # close or mutating connection state.
539 6 ▶ return 0 if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 2 4 6
540 4 return 1;
541 24 }
542  
543 # Silent send methods - no-op when closed
544  
545 3 ▶async sub send_text_if_connected {
Subroutine send_text_if_connected: called CC=2 SCAR=6.9
Pod documented
546 3 my ($self, $text) = @_;
547 3 ▶ return unless $self->is_connected;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_connected 1 2 3
548 2 await $self->try_send_text($text);
549 2 return;
550 24 }
551  
552 3 ▶async sub send_bytes_if_connected {
Subroutine send_bytes_if_connected: called CC=2 SCAR=6.9
Pod documented
553 3 my ($self, $bytes) = @_;
554 3 ▶ return unless $self->is_connected;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_connected 1 2 3
555 2 await $self->try_send_bytes($bytes);
556 2 return;
557 24 }
558  
559 3 ▶async sub send_json_if_connected {
Subroutine send_json_if_connected: called CC=2 SCAR=6.9
Pod documented
560 3 my ($self, $data) = @_;
561 3 ▶ return unless $self->is_connected;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_connected 1 2 3
562 2 await $self->try_send_json($data);
563 2 return;
564 24 }
565  
566 # Receive methods
567  
568 73 ▶async sub receive {
Subroutine receive: called CC=5 SCAR=16.1
Pod documented
569 73 my ($self) = @_;
570  
571 73 ▶ return undef if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 5 68 73
572  
573 68 while (1) {
574 107 my $event = await $self->{receive}->();
575  
576 106 ▶ if (!defined($event) || $event->{type} eq 'websocket.disconnect') {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $event or $event->{"type"} eq "websocket.disconnect") 27 79 106
Condition66%2/3
not defined $event or $event->{"type"} eq "websocket.disconnect"
l!l&&r!l&&!r
02779
MC/DC50%1/2
not defined $event or $event->{"type"} eq "websocket.disconnect"
not defined $event $event->{"type"} eq "websocket.disconnect"
Truth table66%2/3
not(A) or B
A= not defined $eventB= $event->{"type"} eq "websocket.disconnect"
ABresult
1X1
011
000
577 27 await $self->_note_disconnected($event->{code}, $event->{reason});
578 27 return undef;
579 }
580  
581 # websocket.connect is a handshake event, not application data, so it is
582 # filtered out of the message stream here. PAGI's handshake contract: the
583 # server sends websocket.connect and waits for the app's reply; the app
584 # replies by sending accept()/close(). The app does not need to consume
585 # the connect event itself — this filter makes a stray one a no-op rather
586 # than surfacing it as a message. See accept() for the contract.
587 79 ▶ next if $event->{type} eq 'websocket.connect';
Branch: 1 branch
BranchTrueFalseTotal
if $event->{"type"} eq "websocket.connect" 39 40 79
588  
589 40 return $event;
590 }
591 24 }
592  
593 30 ▶async sub receive_text {
Subroutine receive_text: called CC=4 SCAR=13.9
Pod documented
594 30 my ($self) = @_;
595  
596 30 while (1) {
597 32 my $event = await $self->receive;
598 32 ▶ return undef unless $event;
Branch: 1 branch
BranchTrueFalseTotal
unless $event 10 22 32
599  
600 # Skip non-receive events and binary frames
601 22 ▶ next unless $event->{type} eq 'websocket.receive';
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"type"} eq "websocket.receive" 0 22 22
602 22 ▶ next unless exists $event->{text};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $event->{"text"} 2 20 22
603  
604 20 return $event->{text};
605 }
606 24 }
607  
608 6 ▶async sub receive_bytes {
Subroutine receive_bytes: called CC=4 SCAR=14.0
Pod documented
609 6 my ($self) = @_;
610  
611 6 while (1) {
612 6 my $event = await $self->receive;
613 6 ▶ return undef unless $event;
Branch: 1 branch
BranchTrueFalseTotal
unless $event 2 4 6
614  
615 # Skip non-receive events and text frames
616 4 ▶ next unless $event->{type} eq 'websocket.receive';
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"type"} eq "websocket.receive" 0 4 4
617 4 ▶ next unless exists $event->{bytes};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $event->{"bytes"} 0 4 4
618  
619 4 return $event->{bytes};
620 }
621 24 }
622  
623 4 ▶async sub receive_json {
Subroutine receive_json: called CC=2 SCAR=6.9
Pod documented
624 4 my ($self) = @_;
625  
626 4 my $text = await $self->receive_text;
627 4 ▶ return undef unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 1 3 4
628  
629 3 return JSON::MaybeXS::decode_json($text);
630 24 }
631  
632 # Iteration helpers
633  
634 # Internal: run one per-message callback, running on_close cleanup before
635 # re-raising if it dies (idempotent; _run_close_callbacks may already have run).
636 # Takes a thunk so each caller's varying callback arg list stays at the call
637 # site; awaits the thunk's Future and returns its value for callers that use it.
638 22 ▶async sub _guarded_dispatch {
Subroutine _guarded_dispatch: called CC=2 SCAR=6.9
639 22 my ($self, $thunk) = @_;
640  
641 22 my $result;
642 22 my $ok = eval { $result = await $thunk->(); 1 };
643 22 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 5 17 22
644 5 my $err = $@;
645 5 await $self->_run_close_callbacks; # idempotent; may already have run
646 5 die $err; # re-raise: caller still sees the error
647 }
648  
649 17 return $result;
650 24 }
651  
652 3 ▶async sub each_message {
Subroutine each_message: called CC=3 SCAR=11.0
Pod documented
653 3 my ($self, $callback) = @_;
654  
655 3 ▶ while (my $event = await $self->receive) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $event = <custom op await>) 6 2 8
656 6 ▶ next unless $event->{type} eq 'websocket.receive';
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"type"} eq "websocket.receive" 0 6 6
657 6 ▶ await $self->_guarded_dispatch(sub { $callback->($event) });
Subroutine __ANON__: called CC=1 SCAR=0.0
658 }
659  
660 2 return;
661 24 }
662  
663 7 ▶async sub each_text {
Subroutine each_text: called CC=2 SCAR=6.9
Pod documented
664 7 my ($self, $callback) = @_;
665  
666 7 ▶ while (my $text = await $self->receive_text) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $text = <custom op await>) 10 5 15
667 10 ▶ await $self->_guarded_dispatch(sub { $callback->($text) });
Subroutine __ANON__: called CC=1 SCAR=0.0
668 }
669  
670 5 return;
671 24 }
672  
673 2 ▶async sub each_bytes {
Subroutine each_bytes: called CC=2 SCAR=6.9
Pod documented
674 2 my ($self, $callback) = @_;
675  
676 2 ▶ while (my $bytes = await $self->receive_bytes) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $bytes = <custom op await>) 2 1 3
677 2 ▶ await $self->_guarded_dispatch(sub { $callback->($bytes) });
Subroutine __ANON__: called CC=1 SCAR=0.0
678 }
679  
680 1 return;
681 24 }
682  
683 4 ▶async sub each_json {
Subroutine each_json: called CC=2 SCAR=6.9
Pod documented
684 4 my ($self, $callback) = @_;
685  
686 4 while (1) {
687 7 my $text = await $self->receive_text;
688 7 ▶ last unless defined $text;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $text 3 4 7
689  
690 4 my $data = JSON::MaybeXS::decode_json($text);
691 4 ▶ await $self->_guarded_dispatch(sub { $callback->($data) });
Subroutine __ANON__: called CC=1 SCAR=0.0
692 }
693  
694 3 return;
695 24 }
696  
697 # Callback-based event loop (alternative to each_* iteration)
698 9 ▶async sub run {
Subroutine run: called CC=9 SCAR=22.1
Pod documented
699 9 my ($self) = @_;
700  
701 9 while (1) {
702 16 my $event = eval { await $self->receive };
703 16 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 1 15 16
704 1 warn "PAGI::WebSocket receive error: $err";
705 1 last;
706 }
707 15 ▶ last unless $event;
Branch: 1 branch
BranchTrueFalseTotal
unless $event 8 7 15
708  
709 7 ▶ next unless $event->{type} eq 'websocket.receive';
Branch: 1 branch
BranchTrueFalseTotal
unless $event->{"type"} eq "websocket.receive" 0 7 7
710  
711 7 ▶ my $data = $event->{text} // $event->{bytes};
Condition33%1/3
$event->{"text"} // $event->{"bytes"}
l!l&&r!l&&!r
700
MC/DC0%0/2
$event->{"text"} // $event->{"bytes"}
$event->{"text"} $event->{"bytes"}
Truth table33%1/3
A // B
A= $event->{"text"}B= $event->{"bytes"}
ABresult
1X1
011
000
712  
713 7 for my $cb (@{$self->{_on_message}}) {
714 8 eval {
715 8 my $r = $cb->($data, $event);
716 # Await if callback returns a Future
717 5 ▶ if (blessed($r) && $r->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($r) and $r->isa("Future")) 1 4 5
Condition66%2/3
builtin::blessed($r) and $r->isa("Future")
!ll&&!rl&&r
401
MC/DC50%1/2
builtin::blessed($r) and $r->isa("Future")
builtin::blessed($r) $r->isa("Future")
Truth table66%2/3
A and B
A= builtin::blessed($r)B= $r->isa("Future")
ABresult
0X0
100
111
718 1 await $r;
719 }
720 };
721 8 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 3 5 8
722 3 await $self->_trigger_error($err);
723 }
724 }
725 }
726  
727 9 return;
728 24 }
729  
730 # Keepalive support using WebSocket protocol-level ping/pong (RFC 6455)
731 # Sends websocket.keepalive event to server - loop-agnostic, server handles timers
732 6 ▶async sub keepalive {
Subroutine keepalive: called CC=3 SCAR=11.0
Pod documented
733 6 my ($self, $interval, $timeout) = @_;
734  
735 6 ▶ $interval //= 0;
Condition50%1/2
$interval //= 0
l!l
60
MC/DC0%0/1
$interval //= 0
$interval
Truth table50%1/2
A
A= $interval
Aresult
11
00
736  
737 6 my $event = {
738 type => 'websocket.keepalive',
739 interval => $interval,
740 };
741 6 ▶ $event->{timeout} = $timeout if defined $timeout;
Branch: 1 branch
BranchTrueFalseTotal
if defined $timeout 2 4 6
742  
743 6 await $self->{send}->($event);
744  
745 6 return $self;
746 24 }
747  
748 24 1;
749  
750 __END__
« lib/PAGI/Middleware/SSE/Retry.pm ↑ Summary blib/lib/PAGI/Stash.pm »