FastAPI/Response/SSE.pm

filter: Statementstmt 94.7% 36 / 38 Branchbran 50.0% 3 / 6 Conditioncond 33.3% 1 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 100% 7 / 7 Podpod 100% 1 / 1 totaltotal 84.2% 48 / 57 CC 5 SCAR 11.6
CC
5
Cov
85%
dispatch
5.8
BEGIN
1.0
BEGIN
1.0
CRAP 3.2
« FastAPI/Middleware/BotProtection.pm ↑ Summary FastAPI/Queue/Driver/Memory.pm »
1 package PAGI::FastAPI::Response::SSE;
2  
3 24 ▶use v5.38;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 24 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
5 24 ▶use version;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 24 our $VERSION = qv('v1.7.3');
8 24 our $AUTHORITY = 'cpan:MANWAR';
9  
10 24 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 24 ▶use Scalar::Util qw(blessed);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 24 ▶use PAGI::SSE;
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 24 class PAGI::FastAPI::Response::SSE {
15 24 field $generator :param;
16 24 field $headers :param = [];
17 24 field $status :param = 200;
18  
19 3 ▶ async method dispatch ($scope, $receive, $send) {
Subroutine dispatch: called CC=5 SCAR=17.6
Pod documented
20 3 my $sse = PAGI::SSE->new($scope, $receive, $send);
21  
22 await $sse->start(
23 status => $status,
24 headers => [
25 ['x-accel-buffering' => 'no'],
26 3 @{$headers},
27 ],
28 );
29  
30 3 eval {
31 # generator must be an 'async sub ($sse)', per the constructor's
32 # documented contract, calling one always returns a Future.
33 # If it doesn't (a plain 'sub' was passed by mistake), awaiting
34 # it directly produces a confusing "Can't locate object method
35 # AWAIT_IS_READY" error that doesn't point at the real problem.
36 # Fail with a clear diagnostic instead: a non-async generator
37 # can't actually stream anything (its send_event/send_json
38 # calls would return unawaited Futures and silently never
39 # fire), so this must be a hard error, not a silent no-op.
40 3 my $gen_result = $generator->($sse);
41 3 ▶ unless (blessed($gen_result) && $gen_result->isa('Future')) {
Branch: 1 branch
BranchTrueFalseTotal
unless (builtin::blessed($gen_result) and $gen_result->isa("Future")) 0 3 3
Condition33%1/3
builtin::blessed($gen_result) and $gen_result->isa("Future")
!ll&&!rl&&r
003
MC/DC0%0/2
builtin::blessed($gen_result) and $gen_result->isa("Future")
builtin::blessed($gen_result) $gen_result->isa("Future")
Truth table33%1/3
A and B
A= builtin::blessed($gen_result)B= $gen_result->isa("Future")
ABresult
0X0
100
111
42 0 die "SSE generator must be an 'async sub (\$sse)', did you "
43 . "forget 'async'? A synchronous generator can't actually "
44 . "send any events.\n";
45 }
46 3 await $gen_result;
47 };
48 3 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 3 3
49 0 await $sse->_trigger_error($err);
50 }
51  
52 3 ▶ await $sse->run if !$sse->is_closed;
Branch: 1 branch
BranchTrueFalseTotal
if not $sse->is_closed 0 3 3
53 24 }
54 }
55  
56 =encoding utf-8
57  
58 =head1 NAME
59  
60 PAGI::FastAPI::Response::SSE - Server-Sent Events (SSE) Streaming Response for PAGI::FastAPI
61  
62 =head1 VERSION
63  
64 Version v1.7.3
65  
66 =head1 SYNOPSIS
67  
68 use PAGI::FastAPI;
69  
70 my $app = PAGI::FastAPI->new();
71  
72 $app->get('/api/v1/notifications', sub ($c) {
73 return $c->sse(async sub ($sse) {
74 # Enable keepalive comments every 20 seconds
75 await $sse->keepalive(20);
76  
77 # Replay missed messages on client reconnection
78 if (my $last_id = $sse->last_event_id) {
79 my @missed = get_events_since($last_id);
80 for my $event (@missed) {
81 await $sse->send_event(%$event);
82 }
83 }
84  
85 # Send a structured SSE event
86 await $sse->send_event(
87 event => 'notification',
88 id => 'evt-101',
89 data => { user => 'alice', status => 'online' },
90 );
91  
92 # Stream plain JSON messages
93 await $sse->send_json({ message => 'System operational' });
94  
95 # Close stream when done
96 await $sse->close(reason => 'complete');
97 });
98 });
99  
100 =head1 DESCRIPTION
101  
102 C<PAGI::FastAPI::Response::SSE> provides first-class, non-blocking
103 Server-Sent Events (SSE) streaming capabilities for L<PAGI::FastAPI>
104 applications by wrapping L<PAGI::SSE>.
105  
106 It automatically manages connection lifecycles, flow control/backpressure,
107 heartbeats, custom headers (such as disabling Nginx buffering via
108 C<X-Accel-Buffering: no>), and structured event formatting (JSON auto-encoding,
109 event IDs, retry intervals, and keepalive comments).
110  
111 =head1 CONSTRUCTOR
112  
113 =head2 C<new(%options)>
114  
115 Instantiates a new SSE response object. Accepts the following named parameters:
116  
117 =over 4
118  
119 =item * C<generator> (Required)
120  
121 An C<async sub ($sse)> reference containing the streaming loop or event
122 emitter. Receives a L<PAGI::SSE> instance as its sole argument.
123  
124 =item * C<headers> (Optional)
125  
126 An ArrayRef of header key-value pairs (e.g., C<< [ ['X-Custom-Header' => 'value'] ] >>)
127 to return with the initial HTTP response stream. Defaults to C<[]>.
128  
129 =item * C<status> (Optional)
130  
131 Integer HTTP status code for the initial handshake response. Defaults to C<200>.
132  
133 =back
134  
135 =head1 METHODS
136  
137 =head2 C<dispatch($scope, $receive, $send)>
138  
139 await $response->dispatch($scope, $receive, $send);
140  
141 Executes the SSE response lifecycle against the low-level PAGI connection.
142 This method initialises L<PAGI::SSE>, issues the initial C<sse.start> event
143 with default and custom HTTP headers, runs the C<generator> callback, and
144 waits on C<$sse->run> until client disconnect or stream closure.
145  
146 =head1 SEE ALSO
147  
148 L<PAGI::SSE>, L<PAGI::FastAPI::Context>, L<PAGI::FastAPI>
149  
150 =head1 AUTHOR
151  
152 Mohammad Sajid Anwar, C<< <mohammad.anwar at yahoo.com> >>
153  
154 =head1 REPOSITORY
155  
156 L<https://github.com/manwar/PAGI-FastAPI>
157  
158 =head1 BUGS
159  
160 Please report any bugs or feature requests through the web interface at L<https://github.com/manwar/PAGI-FastAPI/issues>.
161 I will be notified and then you'll automatically be notified of progress on your
162 bug as I make changes.
163  
164 =head1 SUPPORT
165  
166 You can find documentation for this module with the perldoc command.
167  
168 perldoc PAGI::FastAPI::Response::SSE
169  
170 You can also look for information at:
171  
172 =over 4
173  
174 =item * BUG Report
175  
176 L<https://github.com/manwar/PAGI-FastAPI/issues>
177  
178 =item * Search MetaCPAN
179  
180 L<https://metacpan.org/dist/PAGI-FastAPI/>
181  
182 =back
183  
184 =head1 LICENSE AND COPYRIGHT
185  
186 Copyright (C) 2026 Mohammad Sajid Anwar.
187  
188 This program is free software; you can redistribute it and/or modify it under
189 the terms of the Artistic License (2.0).
190  
191 =cut
192  
193 24 1; # End of PAGI::FastAPI::Response::SSE
« FastAPI/Middleware/BotProtection.pm ↑ Summary FastAPI/Queue/Driver/Memory.pm »