blib/lib/PAGI/SSE.pm

filter: Statementstmt 85.8% 333 / 388 Branchbran 66.4% 121 / 182 Conditioncond 52.8% 46 / 87 MC/DCmcdc 32.6% 16 / 49 Subroutinesub 90.7% 59 / 65 Podpod 91.4% 43 / 47 totaltotal 75.5% 618 / 818 CC 135 SCAR 26.5
CC
135
Cov
76%
every
88.4
__ANON__
72.0
query_params
13.5
CRAP 14.2
« lib/PAGI/App/Loader.pm ↑ Summary blib/lib/PAGI/Middleware/RequestId.pm »
1 package PAGI::SSE;
2 20 $PAGI::SSE::VERSION = '0.002000';
3 20 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 20 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 20 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
6 20 ▶use Hash::MultiValue;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 20 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 20 ▶use Future;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 20 ▶use JSON::MaybeXS ();
Subroutine BEGIN: called CC=1 SCAR=0.0
10 20 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 20 ▶use Encode qw(decode FB_CROAK FB_DEFAULT LEAVE_SRC);
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13  
14 sub new {
15 98 ▶ my ($class, $scope, $receive, $send) = @_;
Subroutine new: called CC=10 SCAR=23.4
Pod documented
16  
17 98 ▶ croak "PAGI::SSE requires scope hashref"
Branch: 1 branch
BranchTrueFalseTotal
unless $scope and ref $scope eq "HASH" 1 97 98
Condition66%2/3
$scope and ref $scope eq "HASH"
!ll&&!rl&&r
1097
MC/DC50%1/2
$scope and ref $scope eq "HASH"
$scope ref $scope eq "HASH"
Truth table66%2/3
A and B
A= $scopeB= ref $scope eq "HASH"
ABresult
0X0
100
111
18 unless $scope && ref($scope) eq 'HASH';
19 97 ▶ croak "PAGI::SSE requires receive coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless $receive and ref $receive eq "CODE" 1 96 97
Condition66%2/3
$receive and ref $receive eq "CODE"
!ll&&!rl&&r
1096
MC/DC50%1/2
$receive and ref $receive eq "CODE"
$receive ref $receive eq "CODE"
Truth table66%2/3
A and B
A= $receiveB= ref $receive eq "CODE"
ABresult
0X0
100
111
20 unless $receive && ref($receive) eq 'CODE';
21 96 ▶ croak "PAGI::SSE requires send coderef"
Branch: 1 branch
BranchTrueFalseTotal
unless $send and ref $send eq "CODE" 1 95 96
Condition66%2/3
$send and ref $send eq "CODE"
!ll&&!rl&&r
1095
MC/DC50%1/2
$send and ref $send eq "CODE"
$send ref $send eq "CODE"
Truth table66%2/3
A and B
A= $sendB= ref $send eq "CODE"
ABresult
0X0
100
111
22 unless $send && ref($send) eq 'CODE';
23 croak "PAGI::SSE requires scope type 'sse', got '$scope->{type}'"
24 95 ▶ unless ($scope->{type} // '') eq 'sse';
Branch: 1 branch
BranchTrueFalseTotal
unless ($scope->{"type"} // "") eq "sse" 1 94 95
Condition50%1/2
$scope->{"type"} // ""
l!l
950
MC/DC0%0/1
$scope->{"type"} // ""
$scope->{"type"}
Truth table50%1/2
A
A= $scope->{"type"}
Aresult
11
00
25  
26 # Return existing SSE object if one was already created for this scope
27 # This ensures consistent state (is_started, is_closed, callbacks) if
28 # multiple code paths create SSE objects from the same scope.
29 94 ▶ return $scope->{'pagi.sse'} if $scope->{'pagi.sse'};
Branch: 1 branch
BranchTrueFalseTotal
if $scope->{"pagi.sse"} 0 94 94
30  
31 94 my $self = bless {
32 scope => $scope,
33 receive => $receive,
34 send => $send,
35 _state => 'pending', # pending -> started -> closed
36 _on_close => [],
37 _on_error => [],
38 _disconnect_reason => undef, # Set when disconnect received
39 }, $class;
40  
41 # Cache in scope for reuse (weakened to avoid circular reference leak)
42 94 $scope->{'pagi.sse'} = $self;
43 94 Scalar::Util::weaken($scope->{'pagi.sse'});
44  
45 94 return $self;
46 }
47  
48 # Scope property accessors
49 5 ▶sub scope { shift->{scope} }
Subroutine scope: called CC=1 SCAR=0.0
Pod documented
50 2 ▶sub path { shift->{scope}{path} // '/' }
Subroutine path: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"scope"}{"path"} // "/"
l!l
20
MC/DC0%0/1
+(shift())->{"scope"}{"path"} // "/"
+(shift())->{"scope"}{"path"}
Truth table50%1/2
A
A= +(shift())->{"scope"}{"path"}
Aresult
11
00
51 0 ▶sub raw_path { my $s = shift; $s->{scope}{raw_path} // $s->{scope}{path} // '/' }
Subroutine raw_path: not called CC=3 SCAR=24.8
Pod documented
Condition0%0/5
($s->{"scope"}{"raw_path"} // $s->{"scope"}{"path"}) // "/"
l!l
00
$s->{"scope"}{"raw_path"} // $s->{"scope"}{"path"}
l!l&&r!l&&!r
000
MC/DC0%0/2
($s->{"scope"}{"raw_path"} // $s->{"scope"}{"path"}) // "/"
$s->{"scope"}{"raw_path"} $s->{"scope"}{"path"}
Truth table0%0/3
A // B
A= $s->{"scope"}{"raw_path"}B= $s->{"scope"}{"path"}
ABresult
1X1
011
000
52 5 ▶sub query_string { shift->{scope}{query_string} // '' }
Subroutine query_string: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"scope"}{"query_string"} // ""
l!l
50
MC/DC0%0/1
+(shift())->{"scope"}{"query_string"} // ""
+(shift())->{"scope"}{"query_string"}
Truth table50%1/2
A
A= +(shift())->{"scope"}{"query_string"}
Aresult
11
00
53  
54 # URL decode helper (handles + as space per application/x-www-form-urlencoded)
55 sub _url_decode {
56 12 ▶ my ($str) = @_;
Subroutine _url_decode: called CC=2 SCAR=7.0
57 12 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 12 12
58 12 $str =~ s/\+/ /g;
59 12 $str =~ s/%([0-9A-Fa-f]{2})/chr(hex($1))/ge;
60 12 return $str;
61 }
62  
63 # UTF-8 decode helper with strict/lenient mode
64 sub _decode_utf8 {
65 8 ▶ my ($str, $strict) = @_;
Subroutine _decode_utf8: called CC=3 SCAR=11.3
66 8 ▶ return '' unless defined $str;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $str 0 8 8
67 8 ▶ my $flag = $strict ? FB_CROAK : FB_DEFAULT;
Branch: 1 branch
BranchTrueFalseTotal
$strict ? : 0 8 8
68 8 $flag |= LEAVE_SRC;
69 8 return decode('UTF-8', $str, $flag);
70 }
71  
72 # Query params as Hash::MultiValue (cached in scope)
73 # Options: strict => 1 (croak on invalid UTF-8), raw => 1 (skip UTF-8 decoding)
74 sub query_params {
75 6 ▶ my ($self, %opts) = @_;
Subroutine query_params: called CC=13 SCAR=26.0
Pod documented
76 6 ▶ my $strict = delete $opts{strict} // 0;
Condition50%1/2
delete $opts{"strict"} // 0
l!l
06
MC/DC0%0/1
delete $opts{"strict"} // 0
delete $opts{"strict"}
Truth table50%1/2
A
A= delete $opts{"strict"}
Aresult
11
00
77 6 ▶ my $raw = delete $opts{raw} // 0;
Condition100%2/2
delete $opts{"raw"} // 0
l!l
24
MC/DC100%1/1
delete $opts{"raw"} // 0
delete $opts{"raw"}
Truth table100%2/2
A
A= delete $opts{"raw"}
Aresult
11
00
78 6 ▶ croak("Unknown options to query_params: " . join(', ', keys %opts)) if %opts;
Branch: 1 branch
BranchTrueFalseTotal
if %opts 0 6 6
79  
80 6 ▶ my $cache_key = $raw ? 'pagi.sse.query.raw' : ($strict ? 'pagi.sse.query.strict' : 'pagi.sse.query');
Branch: 2 branches
BranchTrueFalseTotal
$raw ? : 2 4 6
$strict ? : 0 4 4
81 6 ▶ return $self->{scope}{$cache_key} if $self->{scope}{$cache_key};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"scope"}{$cache_key} 2 4 6
82  
83 4 my $qs = $self->query_string;
84 4 my @pairs;
85  
86 4 for my $part (split /[&;]/, $qs) {
87 6 ▶ next unless length $part;
Branch: 1 branch
BranchTrueFalseTotal
unless length $part 0 6 6
88 6 my ($key, $val) = split /=/, $part, 2;
89 6 ▶ $key //= '';
Condition50%1/2
$key //= ""
l!l
60
MC/DC0%0/1
$key //= ""
$key
Truth table50%1/2
A
A= $key
Aresult
11
00
90 6 ▶ $val //= '';
Condition50%1/2
$val //= ""
l!l
60
MC/DC0%0/1
$val //= ""
$val
Truth table50%1/2
A
A= $val
Aresult
11
00
91  
92 # URL decode (handles + as space)
93 6 my $key_decoded = _url_decode($key);
94 6 my $val_decoded = _url_decode($val);
95  
96 # UTF-8 decode unless raw mode
97 6 ▶ my $key_final = $raw ? $key_decoded : _decode_utf8($key_decoded, $strict);
Branch: 1 branch
BranchTrueFalseTotal
$raw ? : 2 4 6
98 6 ▶ my $val_final = $raw ? $val_decoded : _decode_utf8($val_decoded, $strict);
Branch: 1 branch
BranchTrueFalseTotal
$raw ? : 2 4 6
99  
100 6 push @pairs, $key_final, $val_final;
101 }
102  
103 4 $self->{scope}{$cache_key} = Hash::MultiValue->new(@pairs);
104 4 return $self->{scope}{$cache_key};
105 }
106  
107 # Raw query params (no UTF-8 decoding)
108 sub raw_query_params {
109 1 ▶ my $self = shift;
Subroutine raw_query_params: called CC=1 SCAR=0.0
Pod documented
110 1 return $self->query_params(raw => 1);
111 }
112  
113 # Single query param accessor
114 sub query_param {
115 4 ▶ my ($self, $name, %opts) = @_;
Subroutine query_param: called CC=1 SCAR=0.0
Pod documented
116 4 return $self->query_params(%opts)->get($name);
117 }
118  
119 # Raw single query param
120 sub raw_query_param {
121 1 ▶ my ($self, $name) = @_;
Subroutine raw_query_param: called CC=1 SCAR=0.0
Pod documented
122 1 return $self->query_param($name, raw => 1);
123 }
124  
125 1 ▶sub scheme { shift->{scope}{scheme} // 'http' }
Subroutine scheme: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"scope"}{"scheme"} // "http"
l!l
10
MC/DC0%0/1
+(shift())->{"scope"}{"scheme"} // "http"
+(shift())->{"scope"}{"scheme"}
Truth table50%1/2
A
A= +(shift())->{"scope"}{"scheme"}
Aresult
11
00
126 1 ▶sub http_version { shift->{scope}{http_version} // '1.1' }
Subroutine http_version: called CC=2 SCAR=7.6
Pod documented
Condition50%1/2
+(shift())->{"scope"}{"http_version"} // "1.1"
l!l
10
MC/DC0%0/1
+(shift())->{"scope"}{"http_version"} // "1.1"
+(shift())->{"scope"}{"http_version"}
Truth table50%1/2
A
A= +(shift())->{"scope"}{"http_version"}
Aresult
11
00
127 0 ▶sub client { shift->{scope}{client} }
Subroutine client: not called CC=1 SCAR=6.9
Pod undocumented
128 0 ▶sub server { shift->{scope}{server} }
Subroutine server: not called CC=1 SCAR=6.9
Pod undocumented
129  
130  
131 # Application state (injected by PAGI::Lifespan, read-only)
132 sub state {
133 4 ▶ my $self = shift;
Subroutine state: called CC=2 SCAR=6.9
Pod documented
134 4 ▶ return $self->{scope}{state} // {};
Condition100%2/2
$self->{"scope"}{"state"} // {}
l!l
22
MC/DC100%1/1
$self->{"scope"}{"state"} // {}
$self->{"scope"}{"state"}
Truth table100%2/2
A
A= $self->{"scope"}{"state"}
Aresult
11
00
135 }
136  
137 # Path parameter accessors - captured from URL path by router
138 # Stored in scope->{path_params} for router-agnostic access
139 sub path_params {
140 2 ▶ my ($self) = @_;
Subroutine path_params: called CC=2 SCAR=6.9
Pod documented
141 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
142 }
143  
144 sub path_param {
145 6 ▶ my ($self, $name) = @_;
Subroutine path_param: called CC=2 SCAR=6.9
Pod documented
146 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
147 6 return $params->{$name};
148 }
149  
150 # Connection state accessors
151 4 ▶sub connection_state { shift->{_state} }
Subroutine connection_state: called CC=1 SCAR=0.0
Pod documented
152  
153 sub is_started {
154 114 ▶ my $self = shift;
Subroutine is_started: called CC=1 SCAR=0.0
Pod documented
155 114 return $self->{_state} eq 'started';
156 }
157  
158 sub is_closed {
159 127 ▶ my $self = shift;
Subroutine is_closed: called CC=1 SCAR=0.0
Pod documented
160 127 return $self->{_state} eq 'closed';
161 }
162  
163 # Disconnect reason - why the connection closed
164 # Common values: 'client_closed', 'write_error', 'send_timeout', 'idle_timeout'
165 sub disconnect_reason {
166 0 ▶ my $self = shift;
Subroutine disconnect_reason: not called CC=1 SCAR=6.9
Pod documented
167 0 return $self->{_disconnect_reason};
168 }
169  
170 # Outbound flow-control introspection (delegates to the pagi.transport handle)
171 sub buffered_amount {
172 2 ▶ my $self = shift;
Subroutine buffered_amount: called CC=2 SCAR=6.9
Pod documented
173 2 my $t = $self->{scope}{'pagi.transport'};
174 2 ▶ return 0 unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
175 1 return $t->buffered_amount;
176 }
177  
178 sub high_water_mark {
179 2 ▶ my $self = shift;
Subroutine high_water_mark: called CC=2 SCAR=6.9
Pod documented
180 2 my $t = $self->{scope}{'pagi.transport'};
181 2 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
182 1 return $t->high_water_mark;
183 }
184  
185 sub low_water_mark {
186 2 ▶ my $self = shift;
Subroutine low_water_mark: called CC=2 SCAR=6.9
Pod documented
187 2 my $t = $self->{scope}{'pagi.transport'};
188 2 ▶ return undef unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 1 2
189 1 return $t->low_water_mark;
190 }
191  
192 sub on_high_water {
193 2 ▶ my ($self, $cb) = @_;
Subroutine on_high_water: called CC=3 SCAR=11.0
Pod documented
194 2 my $t = $self->{scope}{'pagi.transport'};
195 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
196 2 return $self;
197 }
198  
199 sub on_drain {
200 2 ▶ my ($self, $cb) = @_;
Subroutine on_drain: called CC=3 SCAR=11.0
Pod documented
201 2 my $t = $self->{scope}{'pagi.transport'};
202 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
203 2 return $self;
204 }
205  
206 sub is_writable {
207 3 ▶ my $self = shift;
Subroutine is_writable: called CC=4 SCAR=13.9
Pod documented
208 3 my $t = $self->{scope}{'pagi.transport'};
209 3 ▶ return 1 unless $t;
Branch: 1 branch
BranchTrueFalseTotal
unless $t 1 2 3
210 2 my $high = $t->high_water_mark;
211 2 ▶ return 1 unless defined $high;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $high 0 2 2
212 2 ▶ return $t->buffered_amount < $high ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$t->buffered_amount < $high ? : 1 1 2
213 }
214  
215 # Internal state setters
216 sub _set_state {
217 54 ▶ my ($self, $state) = @_;
Subroutine _set_state: called CC=1 SCAR=0.0
218 54 $self->{_state} = $state;
219 }
220  
221 sub _set_closed {
222 24 ▶ my ($self) = @_;
Subroutine _set_closed: called CC=1 SCAR=0.0
223 24 $self->{_state} = 'closed';
224 }
225  
226 # Start the SSE stream
227 47 ▶async sub start {
Subroutine start: called CC=5 SCAR=16.1
Pod documented
228 47 my ($self, %opts) = @_;
229  
230 # Idempotent - don't start twice
231 47 ▶ return $self if $self->is_started || $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_started or $self->is_closed 2 45 47
Condition66%2/3
$self->is_started or $self->is_closed
l!l&&r!l&&!r
2045
MC/DC50%1/2
$self->is_started or $self->is_closed
$self->is_started $self->is_closed
Truth table66%2/3
A or B
A= $self->is_startedB= $self->is_closed
ABresult
1X1
011
000
232  
233 my $event = {
234 type => 'sse.start',
235 45 ▶ status => $opts{status} // 200,
Condition100%2/2
$opts{"status"} // 200
l!l
243
MC/DC100%1/1
$opts{"status"} // 200
$opts{"status"}
Truth table100%2/2
A
A= $opts{"status"}
Aresult
11
00
236 };
237 45 ▶ $event->{headers} = $opts{headers} if exists $opts{headers};
Branch: 1 branch
BranchTrueFalseTotal
if exists $opts{"headers"} 2 43 45
238  
239 45 await $self->{send}->($event);
240 45 $self->_set_state('started');
241  
242 45 return $self;
243 20 }
244  
245 # Enable keepalive - sends sse.keepalive event to server
246 # Server handles the timer; this is loop-agnostic
247 8 ▶async sub keepalive {
Subroutine keepalive: called CC=3 SCAR=11.0
Pod documented
248 8 my ($self, $interval, $comment) = @_;
249  
250 8 ▶ await $self->{send}->({
Condition75%3/4
$interval // 0
l!l
80
$comment // ""
l!l
26
MC/DC0%0/1
$interval // 0
$interval
MC/DC100%1/1
$comment // ""
$comment
Truth table50%1/2
A
A= $interval
Aresult
11
00
Truth table100%2/2
A
A= $comment
Aresult
11
00
251 type => 'sse.keepalive',
252 interval => $interval // 0,
253 comment => $comment // '',
254 });
255  
256 8 return $self;
257 20 }
258  
259 # Single header lookup (case-insensitive, returns last value)
260 sub header {
261 9 ▶ my ($self, $name) = @_;
Subroutine header: called CC=4 SCAR=13.9
Pod documented
262 9 $name = lc($name);
263 9 my $value;
264 9 ▶ for my $pair (@{$self->{scope}{headers} // []}) {
Condition50%1/2
$self->{"scope"}{"headers"} // []
l!l
90
MC/DC0%0/1
$self->{"scope"}{"headers"} // []
$self->{"scope"}{"headers"}
Truth table50%1/2
A
A= $self->{"scope"}{"headers"}
Aresult
11
00
265 15 ▶ if (lc($pair->[0]) eq $name) {
Branch: 1 branch
BranchTrueFalseTotal
if (lc $pair->[0] eq $name) 6 9 15
266 6 $value = $pair->[1];
267 }
268 }
269 9 return $value;
270 }
271  
272 # All headers as Hash::MultiValue (cached in scope)
273 sub headers {
274 2 ▶ my $self = shift;
Subroutine headers: called CC=4 SCAR=14.0
Pod documented
275 2 ▶ return $self->{scope}{'pagi.request.headers'} if $self->{scope}{'pagi.request.headers'};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"scope"}{"pagi.request.headers"} 0 2 2
276  
277 2 my @pairs;
278 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
279 5 push @pairs, lc($pair->[0]), $pair->[1];
280 }
281  
282 2 $self->{scope}{'pagi.request.headers'} = Hash::MultiValue->new(@pairs);
283 2 return $self->{scope}{'pagi.request.headers'};
284 }
285  
286 # All values for a header
287 sub header_all {
288 2 ▶ my ($self, $name) = @_;
Subroutine header_all: called CC=1 SCAR=0.0
Pod documented
289 2 return $self->headers->get_all(lc($name));
290 }
291  
292 # Get Last-Event-ID header from client (for reconnection)
293 sub last_event_id {
294 6 ▶ my ($self) = @_;
Subroutine last_event_id: called CC=1 SCAR=0.0
Pod documented
295 6 return $self->header('last-event-id');
296 }
297  
298 # Send data-only event
299 10 ▶async sub send {
Subroutine send: called CC=3 SCAR=11.0
Pod documented
300 10 my ($self, $data) = @_;
301  
302 10 ▶ croak "Cannot send on closed SSE connection" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 9 10
303  
304 # Auto-start if not started
305 9 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 2 7 9
306  
307 9 await $self->{send}->({
308 type => 'sse.send',
309 data => $data,
310 });
311  
312 9 return $self;
313 20 }
314  
315 # Send JSON-encoded data
316 5 ▶async sub send_json {
Subroutine send_json: called CC=3 SCAR=11.0
Pod documented
317 5 my ($self, $data) = @_;
318  
319 5 ▶ croak "Cannot send on closed SSE connection" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 5 5
320  
321 5 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 1 4 5
322  
323 5 my $json = JSON::MaybeXS::encode_json($data);
324  
325 5 await $self->{send}->({
326 type => 'sse.send',
327 data => $json,
328 });
329  
330 5 return $self;
331 20 }
332  
333 # Send full SSE event with all fields
334 15 ▶async sub send_event {
Subroutine send_event: called CC=8 SCAR=20.8
Pod documented
335 15 my ($self, %opts) = @_;
336  
337 15 ▶ croak "Cannot send on closed SSE connection" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 15 15
338 15 ▶ croak "send_event requires 'data' parameter" unless exists $opts{data};
Branch: 1 branch
BranchTrueFalseTotal
unless exists $opts{"data"} 0 15 15
339  
340 15 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 7 8 15
341  
342 # Auto-encode hashref/arrayref data as JSON
343 15 my $data = $opts{data};
344 15 ▶ if (ref $data) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data) 13 2 15
345 13 $data = JSON::MaybeXS::encode_json($data);
346 }
347  
348 15 my $event = {
349 type => 'sse.send',
350 data => $data,
351 };
352  
353 15 ▶ $event->{event} = $opts{event} if defined $opts{event};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"event"} 13 2 15
354 15 ▶ $event->{id} = "$opts{id}" if defined $opts{id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"id"} 9 6 15
355 15 ▶ $event->{retry} = int($opts{retry}) if defined $opts{retry};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"retry"} 3 12 15
356  
357 15 await $self->{send}->($event);
358  
359 15 return $self;
360 20 }
361  
362 # Safe send - returns bool instead of throwing
363 10 ▶async sub try_send {
Subroutine try_send: called CC=4 SCAR=13.9
Pod documented
364 10 my ($self, $data) = @_;
365 10 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 1 9 10
366  
367 9 eval {
368 9 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 0 9 9
369 9 await $self->{send}->({
370 type => 'sse.send',
371 data => $data,
372 });
373 };
374 9 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 7 2 9
375 7 $self->_set_closed;
376 7 await $self->_trigger_error($err);
377 7 return 0;
378 }
379 2 return 1;
380 20 }
381  
382 2 ▶async sub try_send_json {
Subroutine try_send_json: called CC=4 SCAR=15.2
Pod documented
383 2 my ($self, $data) = @_;
384 2 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 2 2
385  
386 2 eval {
387 2 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 0 2 2
388 2 my $json = JSON::MaybeXS::encode_json($data);
389 2 await $self->{send}->({
390 type => 'sse.send',
391 data => $json,
392 });
393 };
394 2 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 2 2
395 0 $self->_set_closed;
396 0 await $self->_trigger_error($err);
397 0 return 0;
398 }
399 2 return 1;
400 20 }
401  
402 # Send SSE comment (doesn't trigger onmessage in browser)
403 1 ▶async sub send_comment {
Subroutine send_comment: called CC=3 SCAR=11.2
Pod undocumented
404 1 my ($self, $comment) = @_;
405  
406 1 ▶ croak "Cannot send on closed SSE connection" if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 1 1
407  
408 1 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 0 1 1
409  
410 1 await $self->{send}->({
411 type => 'sse.comment',
412 comment => $comment,
413 });
414  
415 1 return $self;
416 20 }
417  
418 1 ▶async sub try_send_comment {
Subroutine try_send_comment: called CC=4 SCAR=15.5
Pod undocumented
419 1 my ($self, $comment) = @_;
420 1 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 1 1
421  
422 1 eval {
423 1 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 0 1 1
424 1 await $self->{send}->({
425 type => 'sse.comment',
426 comment => $comment,
427 });
428 };
429 1 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 1 1
430 0 $self->_set_closed;
431 0 await $self->_trigger_error($err);
432 0 return 0;
433 }
434 1 return 1;
435 20 }
436  
437 2 ▶async sub try_send_event {
Subroutine try_send_event: called CC=9 SCAR=25.3
Pod documented
438 2 my ($self, %opts) = @_;
439 2 ▶ return 0 if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 2 2
440  
441 2 eval {
442 2 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 0 2 2
443  
444 2 ▶ my $data = $opts{data} // '';
Condition50%1/2
$opts{"data"} // ""
l!l
20
MC/DC0%0/1
$opts{"data"} // ""
$opts{"data"}
Truth table50%1/2
A
A= $opts{"data"}
Aresult
11
00
445 2 ▶ if (ref $data) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $data) 0 2 2
446 0 $data = JSON::MaybeXS::encode_json($data);
447 }
448  
449 2 my $event = {
450 type => 'sse.send',
451 data => $data,
452 };
453 2 ▶ $event->{event} = $opts{event} if defined $opts{event};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"event"} 2 0 2
454 2 ▶ $event->{id} = "$opts{id}" if defined $opts{id};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"id"} 0 2 2
455 2 ▶ $event->{retry} = int($opts{retry}) if defined $opts{retry};
Branch: 1 branch
BranchTrueFalseTotal
if defined $opts{"retry"} 0 2 2
456  
457 2 await $self->{send}->($event);
458 };
459 2 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 2 2
460 0 $self->_set_closed;
461 0 await $self->_trigger_error($err);
462 0 return 0;
463 }
464 2 return 1;
465 20 }
466  
467 # Internal: trigger error callbacks
468 7 ▶async sub _trigger_error {
Subroutine _trigger_error: called CC=6 SCAR=17.9
469 7 my ($self, $error) = @_;
470  
471 7 for my $cb (@{$self->{_on_error}}) {
472 7 eval {
473 7 my $r = $cb->($self, $error);
474 6 ▶ if (blessed($r) && $r->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($r) and $r->isa("Future")) 2 4 6
Condition66%2/3
builtin::blessed($r) and $r->isa("Future")
!ll&&!rl&&r
402
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
475 2 await $r;
476 }
477 };
478 7 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 2 5 7
479 2 warn "PAGI::SSE on_error callback error: $@";
480 }
481 }
482  
483 # If no error handlers registered, warn
484 7 ▶ if (!@{$self->{_on_error}}) {
Branch: 1 branch
BranchTrueFalseTotal
if (not @{$self->{"_on_error"};}) 2 5 7
485 2 warn "PAGI::SSE error: $error";
486 }
487 20 }
488  
489 # Register close callback
490 sub on_close {
491 16 ▶ my ($self, $callback) = @_;
Subroutine on_close: called CC=1 SCAR=0.0
Pod documented
492 16 push @{$self->{_on_close}}, $callback;
493 16 return $self;
494 }
495  
496 # Register error callback
497 sub on_error {
498 8 ▶ my ($self, $callback) = @_;
Subroutine on_error: called CC=1 SCAR=0.0
Pod documented
499 8 push @{$self->{_on_error}}, $callback;
500 8 return $self;
501 }
502  
503 # Generic event dispatcher - dispatches to on_close or on_error
504 sub on {
505 4 ▶ my ($self, $event, $callback) = @_;
Subroutine on: called CC=3 SCAR=11.0
Pod documented
506 4 ▶ if ($event eq 'close') {
Branch: 2 branches
BranchTrueFalseTotal
if ($event eq 'close') { } 2 2 4
elsif ($event eq 'error') { } 1 1 2
507 2 return $self->on_close($callback);
508 }
509 elsif ($event eq 'error') {
510 1 return $self->on_error($callback);
511 }
512 else {
513 1 croak "Unknown event type: $event (expected close or error)";
514 }
515 }
516  
517 # Internal: run all on_close callbacks
518 14 ▶async sub _run_close_callbacks {
Subroutine _run_close_callbacks: called CC=7 SCAR=19.6
519 14 my ($self) = @_;
520  
521 # Only run once
522 14 ▶ return if $self->{_close_callbacks_ran};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"_close_callbacks_ran"} 0 14 14
523 14 $self->{_close_callbacks_ran} = 1;
524  
525 14 ▶ my $reason = $self->{_disconnect_reason} // 'unknown';
Condition100%2/2
$self->{"_disconnect_reason"} // "unknown"
l!l
113
MC/DC100%1/1
$self->{"_disconnect_reason"} // "unknown"
$self->{"_disconnect_reason"}
Truth table100%2/2
A
A= $self->{"_disconnect_reason"}
Aresult
11
00
526  
527 14 for my $cb (@{$self->{_on_close}}) {
528 13 eval {
529 13 my $r = $cb->($self, $reason);
530 13 ▶ if (blessed($r) && $r->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
if (builtin::blessed($r) and $r->isa("Future")) 1 12 13
Condition100%3/3
builtin::blessed($r) and $r->isa("Future")
!ll&&!rl&&r
1111
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
531 1 await $r;
532 }
533 };
534 13 ▶ if ($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 13 13
535 0 warn "PAGI::SSE on_close callback error: $@";
536 }
537 }
538  
539 # Clear all callback arrays to break any closure-based cycles
540 14 $self->{_on_close} = [];
541 14 $self->{_on_error} = [];
542 20 }
543  
544 # Close the connection
545 sub close {
546 3 ▶ my ($self) = @_;
Subroutine close: called CC=2 SCAR=7.0
Pod documented
547  
548 3 ▶ return $self if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 3 3
549  
550 3 $self->_set_closed;
551 3 $self->_run_close_callbacks->get;
552  
553 3 return $self;
554 }
555  
556 # Wait for disconnect
557 12 ▶async sub run {
Subroutine run: called CC=7 SCAR=19.7
Pod documented
558 12 my ($self) = @_;
559  
560 12 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 1 11 12
561  
562 12 ▶ while (!$self->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->is_closed) 12 0 12
563 12 my $event = eval { await $self->{receive}->() };
564 12 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 1 11 12
565 1 warn "PAGI::SSE receive error: $err";
566 1 last;
567 }
568  
569 11 ▶ my $type = $event->{type} // '';
Condition50%1/2
$event->{"type"} // ""
l!l
110
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table50%1/2
A
A= $event->{"type"}
Aresult
11
00
570  
571 11 ▶ if ($type eq 'sse.disconnect') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "sse.disconnect") 11 0 11
572 11 ▶ $self->{_disconnect_reason} = $event->{reason} // 'client_closed';
Condition50%1/2
$event->{"reason"} // "client_closed"
l!l
011
MC/DC0%0/1
$event->{"reason"} // "client_closed"
$event->{"reason"}
Truth table50%1/2
A
A= $event->{"reason"}
Aresult
11
00
573 11 $self->_set_closed;
574 11 await $self->_run_close_callbacks;
575 11 last;
576 }
577 }
578  
579 12 return;
580 20 }
581  
582 # Iterate over items and send events
583 4 ▶async sub each {
Subroutine each: called CC=10 SCAR=23.6
Pod documented
584 4 my ($self, $source, $callback) = @_;
585  
586 4 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 1 3 4
587  
588 4 my $index = 0;
589  
590 # Handle arrayref
591 4 ▶ if (ref $source eq 'ARRAY') {
Branch: 2 branches
BranchTrueFalseTotal
if (ref $source eq 'ARRAY') { } 3 1 4
elsif (ref $source eq 'CODE') { } 1 0 1
592 3 for my $item (@$source) {
593 7 ▶ last if $self->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if $self->is_closed 0 7 7
594  
595 7 my $result = await $callback->($item, $index++);
596  
597 # If callback returns a hashref, treat as event spec
598 7 ▶ if (ref $result eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq "HASH") 2 5 7
599 2 await $self->send_event(%$result);
600 }
601 }
602 }
603 # Handle coderef iterator
604 elsif (ref $source eq 'CODE') {
605 1 ▶ while (!$self->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->is_closed) 4 0 4
606 4 my $item = $source->();
607 4 ▶ last unless defined $item;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $item 1 3 4
608  
609 3 my $result = await $callback->($item, $index++);
610  
611 3 ▶ if (ref $result eq 'HASH') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $result eq "HASH") 0 3 3
612 0 await $self->send_event(%$result);
613 }
614 }
615 }
616 else {
617 0 croak "each() requires arrayref or coderef, got " . ref($source);
618 }
619  
620 4 return $self;
621 20 }
622  
623 # Periodic callback execution with interval delay
624 # Requires Future::IO to be installed
625 1 ▶async sub every {
Subroutine every: called CC=14 SCAR=44.8
Pod documented
626 1 my ($self, $interval, $callback) = @_;
627  
628 1 ▶ croak "every() requires interval" unless defined $interval && $interval > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $interval and $interval > 0 0 1 1
Condition33%1/3
defined $interval and $interval > 0
!ll&&!rl&&r
001
MC/DC0%0/2
defined $interval and $interval > 0
defined $interval $interval > 0
Truth table33%1/3
A and B
A= defined $intervalB= $interval > 0
ABresult
0X0
100
111
629 1 ▶ croak "every() requires callback coderef" unless ref $callback eq 'CODE';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $callback eq "CODE" 0 1 1
630  
631 # Future::IO is required for every() - fail clearly if not available
632 1 ▶ eval { require Future::IO; 1 }
Branch: 1 branch
BranchTrueFalseTotal
eval { do { require Future::IO; 1 } } or croak("every() requires Future::IO to be installed. Install it with: cpanm Future::IO") 0 1 1
633 or croak "every() requires Future::IO to be installed. "
634 . "Install it with: cpanm Future::IO";
635  
636 # Future::IO must be configured with a backend
637 20 ▶ no warnings 'once';
Subroutine BEGIN: called CC=1 SCAR=0.0
638 1 ▶ croak "Future::IO backend not configured. Add to your app.pl:\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $Future::IO::IMPL 1 0 1
639 . " use Future::IO::Impl::IOAsync;\n"
640 unless $Future::IO::IMPL;
641  
642 0 ▶ await $self->start unless $self->is_started;
Branch: 1 branch
BranchTrueFalseTotal
unless $self->is_started 0 0 0
643  
644 # Start background disconnect monitor
645 0 my $disconnect_future = $self->_watch_for_disconnect;
646  
647 0 ▶ while (!$self->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->is_closed) 0 0 0
648 # Execute the callback
649 0 my $ok = eval { await $callback->(); 1 };
650 0 ▶ unless ($ok) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($ok) 0 0 0
651 0 my $err = $@;
652 # Callback failed - connection likely closed or error occurred
653 0 $self->_set_closed;
654 0 await $self->_run_close_callbacks;
655 0 last;
656 }
657  
658 # Race between sleep and disconnect detection
659 0 my $sleep_future = Future::IO->sleep($interval);
660 0 my $winner = await Future->wait_any($sleep_future, $disconnect_future);
661  
662 # If disconnect won, exit the loop
663 0 ▶ if ($self->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_closed) 0 0 0
664 0 ▶ $sleep_future->cancel if $sleep_future->can('cancel') && !$sleep_future->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $sleep_future->can("cancel") and not $sleep_future->is_ready 0 0 0
Condition0%0/3
$sleep_future->can("cancel") and not $sleep_future->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$sleep_future->can("cancel") and not $sleep_future->is_ready
$sleep_future->can("cancel") not $sleep_future->is_ready
Truth table0%0/3
A and not(B)
A= $sleep_future->can("cancel")B= not $sleep_future->is_ready
ABresult
0X0
100
111
665 0 last;
666 }
667 }
668  
669 # Clean up disconnect monitor if still running
670 0 ▶ $disconnect_future->cancel if $disconnect_future->can('cancel') && !$disconnect_future->is_ready;
Branch: 1 branch
BranchTrueFalseTotal
if $disconnect_future->can("cancel") and not $disconnect_future->is_ready 0 0 0
Condition0%0/3
$disconnect_future->can("cancel") and not $disconnect_future->is_ready
!ll&&!rl&&r
000
MC/DC0%0/2
$disconnect_future->can("cancel") and not $disconnect_future->is_ready
$disconnect_future->can("cancel") not $disconnect_future->is_ready
Truth table0%0/3
A and not(B)
A= $disconnect_future->can("cancel")B= not $disconnect_future->is_ready
ABresult
0X0
100
111
671  
672 0 return $self;
673 20 }
674  
675 # Background future that completes when disconnect is detected
676 sub _watch_for_disconnect {
677 0 ▶ my ($self) = @_;
Subroutine _watch_for_disconnect: not called CC=1 SCAR=6.9
678  
679 0 my $receive = $self->{receive};
680 0 require Scalar::Util;
681 0 my $weak_self = $self;
682 0 Scalar::Util::weaken($weak_self);
683  
684 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=8 SCAR=42.8
685 0 ▶ while ($weak_self && !$weak_self->is_closed) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self and not $weak_self->is_closed) 0 0 0
Condition0%0/3
$weak_self and not $weak_self->is_closed
!ll&&!rl&&r
000
MC/DC0%0/2
$weak_self and not $weak_self->is_closed
$weak_self not $weak_self->is_closed
Truth table0%0/3
A and not(B)
A= $weak_selfB= not $weak_self->is_closed
ABresult
0X0
100
111
686 0 my $event = eval { await $receive->() };
687 0 ▶ last unless $event;
Branch: 1 branch
BranchTrueFalseTotal
unless $event 0 0 0
688  
689 0 ▶ my $type = $event->{type} // '';
Condition0%0/2
$event->{"type"} // ""
l!l
00
MC/DC0%0/1
$event->{"type"} // ""
$event->{"type"}
Truth table0%0/2
A
A= $event->{"type"}
Aresult
11
00
690 0 ▶ if ($type eq 'sse.disconnect') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "sse.disconnect") 0 0 0
691 0 ▶ if ($weak_self) {
Branch: 1 branch
BranchTrueFalseTotal
if ($weak_self) 0 0 0
692 0 ▶ $weak_self->{_disconnect_reason} = $event->{reason} // 'client_closed';
Condition0%0/2
$event->{"reason"} // "client_closed"
l!l
00
MC/DC0%0/1
$event->{"reason"} // "client_closed"
$event->{"reason"}
Truth table0%0/2
A
A= $event->{"reason"}
Aresult
11
00
693 0 $weak_self->_set_closed;
694 0 await $weak_self->_run_close_callbacks;
695 }
696 0 last;
697 }
698 }
699 0 })->();
700 }
701  
702 20 1;
703  
704 __END__
« lib/PAGI/App/Loader.pm ↑ Summary blib/lib/PAGI/Middleware/RequestId.pm »