blib/lib/PAGI/App/SSE/Pubsub.pm untested

filter: Statementstmt 0.0% 0 / 111 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 20 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 7 totaltotal 0.0% 0 / 187 CC 20 SCAR 40.4
CC
20
Cov
0%
to_app
132.0
publish
30.0
client_count
12.0
CRAP 56.6
1 package PAGI::App::SSE::Pubsub;
2 $PAGI::App::SSE::Pubsub::VERSION = '0.002000';
3 use strict;
4 use warnings;
5 use Future::AsyncAwait;
6 use Future;
7  
8 =head1 NAME
9  
10 PAGI::App::SSE::Pubsub - Pub/sub Server-Sent Events
11  
12 =head1 SYNOPSIS
13  
14 use PAGI::App::SSE::Pubsub;
15  
16 my $app = PAGI::App::SSE::Pubsub->new->to_app;
17  
18 # From elsewhere, publish events
19 PAGI::App::SSE::Pubsub->publish('news', { data => 'Hello!' });
20  
21 =cut
22  
23 # Shared state
24 my %channels; # channel => { clients => { id => { send => cb, scope => scope } } }
25 my $next_id = 1;
26  
27 sub new {
28 my ($class, %args) = @_;
29  
30 return bless {
31 channel => $args{channel} // 'default',
32 retry => $args{retry},
33 on_connect => $args{on_connect},
34 on_close => $args{on_close},
35 history => $args{history} // 0,
36 headers => $args{headers} // [],
37 }, $class;
38 }
39  
40 # Class method to publish events
41 sub publish {
42 my ($class, $channel, $event) = @_;
43  
44 return unless $channels{$channel};
45  
46 my $data = _format_event($event);
47 my $clients = $channels{$channel}{clients};
48  
49 for my $id (keys %$clients) {
50 my $client = $clients->{$id};
51 eval {
52 $client->{send}->({
53 type => 'http.response.body',
54 body => $data,
55 more => 1,
56 });
57 };
58 if ($@) {
59 $client->{closed} = 1;
60 delete $clients->{$id};
61 }
62 }
63  
64 # Store in history if enabled
65 if ($channels{$channel}{history_size}) {
66 push @{$channels{$channel}{history}}, $event;
67 my $max = $channels{$channel}{history_size};
68 if (@{$channels{$channel}{history}} > $max) {
69 shift @{$channels{$channel}{history}};
70 }
71 }
72 }
73  
74 # Class method to get client count
75 sub client_count {
76 my ($class, $channel) = @_;
77 $channel //= undef;
78  
79 if ($channel) {
80 return 0 unless $channels{$channel};
81 return scalar keys %{$channels{$channel}{clients}};
82 }
83 my $total = 0;
84 $total += scalar keys %{$_->{clients}} for values %channels;
85 return $total;
86 }
87  
88 # Class method to list channels
89 sub list_channels {
90 my ($class) = @_;
91  
92 return keys %channels;
93 }
94  
95 sub to_app {
96 my ($self) = @_;
97  
98 my $channel = $self->{channel};
99 my $retry = $self->{retry};
100 my $on_connect = $self->{on_connect};
101 my $on_close = $self->{on_close};
102 my $history_size = $self->{history};
103 my $extra_headers = $self->{headers};
104  
105 return async sub {
106 my ($scope, $receive, $send) = @_;
107 die "Unsupported scope type: $scope->{type}" if $scope->{type} ne 'http';
108  
109 # Build headers
110 my @headers = (
111 ['content-type', 'text/event-stream'],
112 ['cache-control', 'no-cache'],
113 ['connection', 'keep-alive'],
114 @$extra_headers,
115 );
116  
117 await $send->({
118 type => 'http.response.start',
119 status => 200,
120 headers => \@headers,
121 });
122  
123 # Initialize channel
124 $channels{$channel} //= {
125 clients => {},
126 history => [],
127 history_size => $history_size,
128 };
129  
130 my $client_id = $next_id++;
131 my $client_data = {
132 send => $send,
133 scope => $scope,
134 closed => 0,
135 };
136 $channels{$channel}{clients}{$client_id} = $client_data;
137  
138 # Send retry hint
139 if (defined $retry) {
140 await $send->({
141 type => 'http.response.body',
142 body => "retry: $retry\n\n",
143 more => 1,
144 });
145 }
146  
147 # Send history if requested
148 my $last_event_id = _get_last_event_id($scope);
149 if ($history_size && defined $last_event_id) {
150 my $found = 0;
151 for my $event (@{$channels{$channel}{history}}) {
152 if ($found) {
153 await $send->({
154 type => 'http.response.body',
155 body => _format_event($event),
156 more => 1,
157 });
158 } elsif ($event->{id} && $event->{id} eq $last_event_id) {
159 $found = 1;
160 }
161 }
162 }
163  
164 $on_connect->($scope, $channel) if $on_connect;
165  
166 # Wait for disconnect
167 while (!$client_data->{closed}) {
168 my $event = await $receive->();
169 if ($event->{type} eq 'http.disconnect') {
170 last;
171 }
172 }
173  
174 # Cleanup
175 delete $channels{$channel}{clients}{$client_id};
176 delete $channels{$channel} if !keys %{$channels{$channel}{clients}};
177  
178 $on_close->($scope, $channel) if $on_close;
179  
180 # End response
181 unless ($client_data->{closed}) {
182 await $send->({
183 type => 'http.response.body',
184 body => '',
185 more => 0,
186 });
187 }
188 };
189 }
190  
191 sub _format_event {
192 my ($event) = @_;
193  
194 my $data = '';
195  
196 if ($event->{event}) {
197 $data .= "event: $event->{event}\n";
198 }
199 if ($event->{id}) {
200 $data .= "id: $event->{id}\n";
201 }
202  
203 my $content = $event->{data} // '';
204 for my $line (split /\n/, $content) {
205 $data .= "data: $line\n";
206 }
207  
208 return "$data\n";
209 }
210  
211 sub _get_last_event_id {
212 my ($scope) = @_;
213  
214 for my $h (@{$scope->{headers} // []}) {
215 if (lc($h->[0]) eq 'last-event-id') {
216 return $h->[1];
217 }
218 }
219 return undef;
220 }
221  
222 1;
223  
224 __END__