BoardStreams/Hub.pm

filter: Statementstmt 24.3% 119 / 489 Branchbran 0.0% 0 / 216 Conditioncond 0.0% 0 / 74 MC/DCmcdc 0.0% 0 / 43 Subroutinesub 18.8% 17 / 90 Podpod 0.0% 0 / 13 totaltotal 14.7% 136 / 925 CC 166 SCAR 43.9
CC
166
Cov
15%
_controlled
272.0
__ANON__
272.0
__ANON__
272.0
CRAP 80.5
↑ Summary BoardStreams/Diff.pm »
1 2 ▶use v5.44;
Subroutine BEGIN: called CC=1 SCAR=0.0
2 2 ▶use experimental 'class';
Subroutine BEGIN: called CC=1 SCAR=0.0
3  
4 # The server side of BoardStreams: registers channel handlers, talks to
5 # browsers over WebSockets, and keeps channel state and events in
6 # PostgreSQL so that they survive disconnections and restarts.
7 2 class BoardStreams::Hub {
8 2 our $VERSION = "v0.0.60";
9  
10 2 ▶ use Future::AsyncAwait future_class => "Mojo::Promise";
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶ use Mojo::IOLoop;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 2 ▶ use Mojo::JSON qw(encode_json from_json to_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
13 2 ▶ use Mojo::Log;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 2 ▶ use Mojo::Promise;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 2 ▶ use Scalar::Util qw(blessed weaken);
Subroutine BEGIN: called CC=1 SCAR=0.0
16  
17 2 ▶ use BoardStreams ();
Subroutine BEGIN: called CC=1 SCAR=0.0
18 2 ▶ use BoardStreams::Context;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 2 ▶ use BoardStreams::Diff qw(diff);
Subroutine BEGIN: called CC=1 SCAR=0.0
20 2 ▶ use BoardStreams::Rejection;
Subroutine BEGIN: called CC=1 SCAR=0.0
21 2 ▶ use BoardStreams::Update;
Subroutine BEGIN: called CC=1 SCAR=0.0
22  
23 2 ▶ use constant NOTIFY_NAME => 'boardstreams';
Subroutine BEGIN: called CC=1 SCAR=0.0
24 2 ▶ use constant PUMP_BATCH => 500;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 2 ▶ use constant CONTROL_NAME => 'boardstreams_control';
Subroutine BEGIN: called CC=1 SCAR=0.0
26 2 ▶ use constant CONTROL_MAX => 7000; # PostgreSQL allows notifications of just under 8000 bytes
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 2 field $pg :param :reader;
29 2 field $log :param = Mojo::Log->new;
30 2 field $retention :param = 3600; # seconds that events and request ids are kept
31 2 field $retry_delay :param = 1; # seconds between retries when PostgreSQL is unreachable
32 2 field $heartbeat_interval :param = 25; # seconds between heartbeats to each browser
33 2 field $identify :param = undef; # sub ($c) returning who a connection belongs to
34 2 field $listener_check_interval :param = 5; # seconds between checks that notifications still arrive
35  
36 2 field @specs; # registered channels, each { pattern, regex, ... }
37 2 field %conns; # connection id => { c => controller, channels => { name => 1 }, user => ... }
38 2 field %members; # channel => { connection id => last sequence number sent }
39 2 field %pumping; # channel => 1 while delivering, 2 if asked again meanwhile
40 2 field %joining; # channel => { join number => \$stale } for joins reading the channel's row
41 2 field $next_join = 0;
42 2 field $next_conn = 0;
43 2 field $migrated = 0;
44 2 field $started = 0;
45 2 field $wired = 0;
46 2 field $hearing = 0; # true while this process receives PostgreSQL notifications
47 2 field $token; # tells this process's own echoes from those of others
48 2 field $echo_sent = 0;
49 2 field $echo_awaited; # number of the echo that has not come back yet
50 2 field $scope; # the PostgreSQL schema the tables are in
51 2 field $outdated = 0; # schema version that a newer process announced, if above this code's
52 2 field $stopping = 0; # true once this process has begun to stop gracefully
53 2 field $on_finish; # this hub's subscriber to the event loop's finish event
54  
55 2 my $SCHEMA = <<~'SQL';
56 -- 1 up
57 create table bs_channel (
58 name text primary key,
59 seq bigint not null default 0,
60 state jsonb not null
61 );
62 create table bs_event (
63 channel text not null,
64 seq bigint not null,
65 diff jsonb,
66 events jsonb not null,
67 created_at timestamptz not null default now(),
68 primary key (channel, seq)
69 );
70 create index bs_event_created_at on bs_event (created_at);
71 create table bs_request (
72 id text primary key,
73 channel text not null,
74 seq bigint not null default 0,
75 response jsonb,
76 created_at timestamptz not null default now()
77 );
78 create index bs_request_created_at on bs_request (created_at);
79 -- 1 down
80 drop table bs_request;
81 drop table bs_event;
82 drop table bs_channel;
83 -- 2 up
84 delete from bs_event e where not exists (select 1 from bs_channel c where c.name = e.channel);
85 delete from bs_request r where not exists (select 1 from bs_channel c where c.name = r.channel);
86 alter table bs_event add constraint bs_event_channel_fkey
87 foreign key (channel) references bs_channel (name) on delete cascade;
88 alter table bs_request add constraint bs_request_channel_fkey
89 foreign key (channel) references bs_channel (name) on delete cascade;
90 create index bs_request_channel on bs_request (channel);
91 -- A deleted channel that is created again must not reuse sequence
92 -- numbers, or a browser returning with an old number would be sent
93 -- updates of the new channel as if they continued the old one. So
94 -- every new channel starts above the highest number that any
95 -- deleted channel ever reached, which this one row keeps.
96 create table bs_floor (
97 only_row boolean primary key default true check (only_row),
98 seq bigint not null default 0
99 );
100 insert into bs_floor default values;
101 create function bs_channel_deleted() returns trigger language plpgsql
102 set search_path from current as $body$
103 begin
104 update bs_floor set seq = greatest(seq, old.seq + 1);
105 return old;
106 end
107 $body$;
108 create trigger bs_channel_deleted after delete on bs_channel
109 for each row execute function bs_channel_deleted();
110 -- 2 down
111 drop trigger bs_channel_deleted on bs_channel;
112 drop function bs_channel_deleted();
113 drop table bs_floor;
114 drop index bs_request_channel;
115 alter table bs_request drop constraint bs_request_channel_fkey;
116 alter table bs_event drop constraint bs_event_channel_fkey;
117 SQL
118  
119 # The newest schema version this code knows.
120 2 my ($SCHEMA_VERSION) = sort { $b <=> $a } $SCHEMA =~ /^-- (\d+) up$/mg;
121  
122 # Registers handlers for a channel name, or for a family of names when
123 # the pattern contains "*". A "*" stands for any run of characters other
124 # than ":", possibly none: "chat:*" covers "chat:lobby" and "chat:" but
125 # not "chat:eu:lobby", which needs "chat:*:*". A "**" stands for any
126 # run of characters at all, so "chat:**" covers all three. Everything
127 # else in a pattern is literal. If several patterns cover a name, the
128 # most specific wins: an exact name, then the pattern with the most
129 # literal characters, then the one with the fewest "**", then the one
130 # registered first.
131 # join => sub ($ctx) { ... } true to accept; $ctx->reject($reason) to refuse
132 # actions => { name => sub ($ctx, $payload) { ... } }
133 # requests => { name => sub ($ctx, $payload) { ...; return $response_payload } }
134 # initial_state => { ... }
135 # Handlers may be async subs.
136 0 ▶ method channel ($pattern, %spec) {
Subroutine channel: not called CC=3 SCAR=24.8
Pod undocumented
137 0 my @parts = split /(\*\*|\*)/, $pattern, -1;
138 0 ▶ my $regex = join '', map { $_ eq '**' ? '.*' : $_ eq '*' ? '[^:]*' : quotemeta } @parts;
Branch: 2 branches
BranchTrueFalseTotal
$_ eq '**' ? : 0 0 0
$_ eq '*' ? : 0 0 0
139 push @specs, {
140 %spec,
141 pattern => $pattern,
142 regex => qr/\A$regex\z/s,
143 0 literal => length(join '', grep { !/\A\*\*?\z/ } @parts),
144 0 deep => scalar(grep { $_ eq '**' } @parts),
145 };
146 0 return $self;
147 2 }
148  
149 # Creates the tables unless they exist. Called at startup by the plugin
150 # (unless it is told to be lazy) and in any case before the first use
151 # of the tables in each process, so it never has to be called by hand.
152 0 ▶ method migrate {
Subroutine migrate: not called CC=2 SCAR=17.9
Pod undocumented
153 0 ▶ return 1 if $migrated;
Branch: 1 branch
BranchTrueFalseTotal
if $migrated 0 0 0
154 0 $pg->migrations->name('boardstreams')->from_string($SCHEMA)->migrate;
155 0 $migrated = 1;
156 # Processes still running older code would go on using the tables
157 # the old way; tell them at once (and again with every echo).
158 0 eval {
159 0 $pg->db->query('select pg_notify(?, ?)', CONTROL_NAME,
160 to_json({ op => 'schema', schema => $SCHEMA_VERSION, scope => $self->_scope }));
161 };
162 0 return 1;
163 2 }
164  
165 # Notifications are heard by every session of the database, including
166 # other applications that keep their own BoardStreams tables in another
167 # schema of it. Control messages carry the schema they are about.
168 0 ▶ method _scope {
Subroutine _scope: not called CC=2 SCAR=17.9
169 0 ▶ return $scope //= $pg->db->query('select current_schema()')->array->[0];
Condition0%0/3
$scope //= $pg->db->query("select current_schema()")->array->[0]
l!l&&r!l&&!r
000
MC/DC0%0/2
$scope //= $pg->db->query("select current_schema()")->array->[0]
$scope $pg->db->query("select current_schema()")->array->[0]
Truth table0%0/3
A //= B
A= $scopeB= $pg->db->query("select current_schema()")->array->[0]
ABresult
1X1
011
000
170 2 }
171  
172 # A database handle, for work that needs the tables.
173 0 ▶ method _db {
Subroutine _db: not called CC=2 SCAR=17.9
174 0 ▶ die "BoardStreams: the database is at schema version $outdated, which this code is too old for\n" if $outdated;
Branch: 1 branch
BranchTrueFalseTotal
if $outdated 0 0 0
175 0 $self->migrate;
176 0 return $pg->db;
177 2 }
178  
179 # Changes a channel's state and/or emits events on it, as one atomic
180 # step with one sequence number. The callback receives a
181 # BoardStreams::Update. Returns a promise of the channel's sequence
182 # number afterwards.
183 0 ▶ method update ($channel, $cb, %opt) {
Subroutine update: not called CC=1 SCAR=6.9
Pod undocumented
184 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=6 SCAR=37.4
185 0 my $db = $self->_db;
186 0 my $tx = $db->begin;
187 0 my $row = await $self->_row($db, $channel, ' for update');
188 0 my $seq = $row->{seq} + 0;
189  
190 0 my $update = BoardStreams::Update->new(state => from_json($row->{state}));
191 0 await Mojo::Promise->resolve($cb->($update));
192 0 my $diff = diff(from_json($row->{state}), $update->state);
193 0 my @events = $update->events;
194  
195 0 ▶ if ($diff or @events) {
Branch: 1 branch
BranchTrueFalseTotal
if ($diff or @events) 0 0 0
Condition0%0/3
$diff or @events
l!l&&r!l&&!r
000
MC/DC0%0/2
$diff or @events
$diff @events
Truth table0%0/3
A or B
A= $diffB= @events
ABresult
1X1
011
000
196 0 $seq++;
197 0 await $db->query_p('update bs_channel set seq = ?, state = ? where name = ?',
198 $seq, { json => $update->state }, $channel);
199 0 ▶ await $db->query_p('insert into bs_event (channel, seq, diff, events) values (?, ?, ?, ?)',
Branch: 1 branch
BranchTrueFalseTotal
$diff ? : 0 0 0
200 $channel, $seq, ($diff ? { json => $diff } : undef), { json => \@events });
201 0 await $db->query_p('select pg_notify(?, ?)', NOTIFY_NAME, "$seq $channel");
202 }
203 0 ▶ if (defined(my $id = $opt{request_id})) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $id = $opt{"request_id"})) 0 0 0
204 0 my $inserted = (await $db->query_p(
205 'insert into bs_request (id, channel, seq) values (?, ?, ?) on conflict (id) do nothing',
206 $id, $channel, $seq))->rows;
207 0 ▶ die BoardStreams::Hub::Duplicate->new unless $inserted > 0;
Branch: 1 branch
BranchTrueFalseTotal
unless $inserted > 0 0 0 0
208 }
209 0 $tx->commit;
210  
211 0 $self->_pump($channel);
212 0 return $seq;
213 0 })->();
214 2 }
215  
216 0 ▶ method emit ($channel, $name, $payload = undef) {
Subroutine emit: not called CC=2 SCAR=17.9
Pod undocumented
217 0 ▶ return $self->update($channel, sub ($u) { $u->emit($name, $payload) });
Subroutine __ANON__: not called CC=1 SCAR=6.9
218 2 }
219  
220 # Promise of { seq => ..., state => ... } for a channel.
221 0 ▶ method snapshot ($channel) {
Subroutine snapshot: not called CC=1 SCAR=6.9
Pod undocumented
222 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
223 0 my $row = await $self->_row($self->_db, $channel, '');
224 0 return { seq => $row->{seq} + 0, state => from_json($row->{state}) };
225 0 })->();
226 2 }
227  
228 # The row of a channel, created first if the channel does not exist.
229 # It can be deleted again before it is read, hence the retries.
230 0 ▶ method _row ($db, $channel, $lock) {
Subroutine _row: not called CC=1 SCAR=6.9
231 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
232 0 for my $attempt (1 .. 5) {
233 0 my $row = (await $db->query_p(
234 "select seq, state::text as state from bs_channel where name = ?$lock", $channel))->hash;
235 0 ▶ return $row if $row;
Branch: 1 branch
BranchTrueFalseTotal
if $row 0 0 0
236 0 await $db->query_p(
237 'insert into bs_channel (name, seq, state) select ?, seq, ?::jsonb from bs_floor
238 on conflict (name) do nothing',
239 $channel, { json => $self->_initial_state($channel) });
240 }
241 0 die "BoardStreams: channel $channel keeps disappearing\n";
242 0 })->();
243 2 }
244  
245 # Deletes a channel: its state, its history and its recorded requests.
246 # Every member, on all server processes, is removed and told so with
247 # the reason, as with kick_all. If the channel is used again it starts
248 # afresh from its initial state. Returns a promise of whether there
249 # was anything to delete.
250 0 ▶ method delete_channel ($channel, $reason = 'deleted', $data = undef) {
Subroutine delete_channel: not called CC=3 SCAR=24.8
Pod undocumented
251 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
252 0 my $message = { op => 'deleted', channel => $channel, reason => $reason, data => $data, scope => $self->_scope };
253 0 ▶ die "BoardStreams: the reason and data of a deletion must be small\n"
Branch: 1 branch
BranchTrueFalseTotal
if length encode_json($message) > 7000 0 0 0
254 if length(encode_json($message)) > CONTROL_MAX;
255 0 my $db = $self->_db;
256 0 my $tx = $db->begin;
257 0 my $deleted = (await $db->query_p('delete from bs_channel where name = ?', $channel))->rows;
258 # Sent by the same transaction, so that no process hears of the
259 # deletion before it can see it.
260 0 await $db->query_p('select pg_notify(?, ?)', CONTROL_NAME, to_json($message));
261 0 $tx->commit;
262 0 ▶ return $deleted > 0 ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
$deleted > 0 ? : 0 0 0
263 0 })->();
264 2 }
265  
266 # Deletes events and request ids older than the retention period.
267 0 ▶ method purge {
Subroutine purge: not called CC=2 SCAR=17.9
Pod undocumented
268 # Nothing this process could have written yet; do not create the
269 # tables just to find them empty.
270 0 ▶ return Mojo::Promise->resolve unless $migrated;
Branch: 1 branch
BranchTrueFalseTotal
unless $migrated 0 0 0
271 return Mojo::Promise->all(
272 0 map { $pg->db->query_p("delete from $_ where created_at < now() - ? * interval '1 second'", $retention) }
273 qw(bs_event bs_request));
274 2 }
275  
276 # Removes a user from a channel, on whichever server processes their
277 # browsers are connected to. The browser is told that its membership
278 # ended, with the reason, and gets nothing further from the channel.
279 # Nothing stops it from asking to join again: that is for the join
280 # handler to refuse. Returns a promise.
281 0 ▶ method kick ($user, $channel, $reason = 'kicked', $data = undef) {
Subroutine kick: not called CC=3 SCAR=24.8
Pod undocumented
282 0 return $self->_control({ op => 'kick', user => "$user", channel => $channel, reason => $reason, data => $data });
283 2 }
284  
285 # Removes everyone from a channel, on all server processes: every
286 # member's browser is told that its membership ended, with the reason,
287 # exactly as with kick. The channel's state and history stay as they
288 # are, and browsers may ask to join again. Returns a promise.
289 0 ▶ method kick_all ($channel, $reason = 'kicked', $data = undef) {
Subroutine kick_all: not called CC=3 SCAR=24.8
Pod undocumented
290 0 return $self->_control({ op => 'kick_all', channel => $channel, reason => $reason, data => $data });
291 2 }
292  
293 # Closes every WebSocket connection of a user, on whichever server
294 # processes they are. The browser is told the reason first, and the
295 # client does not reconnect. Returns a promise.
296 0 ▶ method disconnect ($user, $reason = 'disconnected', $data = undef) {
Subroutine disconnect: not called CC=3 SCAR=24.8
Pod undocumented
297 0 return $self->_control({ op => 'disconnect', user => "$user", reason => $reason, data => $data });
298 2 }
299  
300 # The same two, for one connection of this process (used by
301 # BoardStreams::Context).
302 0 ▶ method kick_connection ($id, $channel, $reason = 'kicked', $data = undef) {
Subroutine kick_connection: not called CC=5 SCAR=34.0
Pod undocumented
303 0 ▶ my $conn = $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = $conns{$id} or return 0 0 0
304 0 ▶ return unless delete $conn->{channels}{$channel};
Branch: 1 branch
BranchTrueFalseTotal
unless delete $conn->{"channels"}{$channel} 0 0 0
305 0 $self->_send($id, { type => 'rejected', channel => $channel, reason => $reason, data => $data });
306 0 $self->_leave($id, $channel);
307 0 return 1;
308 2 }
309  
310 0 ▶ method disconnect_connection ($id, $reason = 'disconnected', $data = undef) {
Subroutine disconnect_connection: not called CC=5 SCAR=34.0
Pod undocumented
311 0 ▶ my $conn = $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = $conns{$id} or return 0 0 0
312 0 $self->_send($id, { type => 'disconnect', reason => $reason, data => $data });
313 # Forget the connection now, so that nothing more is sent on it.
314 0 delete $conns{$id};
315 0 $self->_leave($id, $_) for keys $conn->{channels}->%*;
316 0 $conn->{tx}->finish(4000);
317 0 return 1;
318 2 }
319  
320 # Tells every server process, this one included, to act on a user.
321 0 ▶ method _control ($message) {
Subroutine _control: not called CC=1 SCAR=6.9
322 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
323 0 $message->{scope} = $self->_scope;
324 0 ▶ die "BoardStreams: the reason and data of a kick or disconnect must be small\n"
Branch: 1 branch
BranchTrueFalseTotal
if length encode_json($message) > 7000 0 0 0
325 if length(encode_json($message)) > CONTROL_MAX;
326 0 await $pg->db->query_p('select pg_notify(?, ?)', CONTROL_NAME, to_json($message));
327 0 return;
328 0 })->();
329 2 }
330  
331 0 ▶ method _controlled ($message) {
Subroutine _controlled: not called CC=16 SCAR=56.1
332 0 ▶ return unless ref $message eq 'HASH' and defined $message->{op};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $message eq "HASH" and defined $message->{"op"} 0 0 0
Condition0%0/3
ref $message eq "HASH" and defined $message->{"op"}
!ll&&!rl&&r
000
MC/DC0%0/2
ref $message eq "HASH" and defined $message->{"op"}
ref $message eq "HASH" defined $message->{"op"}
Truth table0%0/3
A and B
A= ref $message eq "HASH"B= defined $message->{"op"}
ABresult
0X0
100
111
333 0 ▶ if ($message->{op} eq 'kick_all' or $message->{op} eq 'deleted') {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{"op"} eq "kick_all" or $message->{"op"} eq "deleted") 0 0 0
Condition0%0/3
$message->{"op"} eq "kick_all" or $message->{"op"} eq "deleted"
l!l&&r!l&&!r
000
MC/DC0%0/2
$message->{"op"} eq "kick_all" or $message->{"op"} eq "deleted"
$message->{"op"} eq "kick_all" $message->{"op"} eq "deleted"
Truth table0%0/3
A or B
A= $message->{"op"} eq "kick_all"B= $message->{"op"} eq "deleted"
ABresult
1X1
011
000
334 0 ▶ my $channel = $message->{channel} // return;
Condition0%0/2
$message->{"channel"} // (return)
l!l
00
MC/DC0%0/1
$message->{"channel"} // (return)
$message->{"channel"}
Truth table0%0/2
A
A= $message->{"channel"}
Aresult
11
00
335 0 ▶ if ($message->{op} eq 'deleted') {
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{"op"} eq "deleted") 0 0 0
336 0 ▶ $$_ = 1 for values %{ $joining{$channel} // {} };
Condition0%0/2
$joining{$channel} // {}
l!l
00
MC/DC0%0/1
$joining{$channel} // {}
$joining{$channel}
Truth table0%0/2
A
A= $joining{$channel}
Aresult
11
00
337 }
338 $self->kick_connection($_, $channel, $message->{reason}, $message->{data})
339 0 ▶ for keys %{ $members{$channel} // {} };
Condition0%0/2
$members{$channel} // {}
l!l
00
MC/DC0%0/1
$members{$channel} // {}
$members{$channel}
Truth table0%0/2
A
A= $members{$channel}
Aresult
11
00
340 0 return;
341 }
342 0 ▶ return unless defined $message->{user};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $message->{"user"} 0 0 0
343 0 ▶ my @ids = grep { defined $conns{$_}{user} and $conns{$_}{user} eq $message->{user} } keys %conns;
Condition0%0/3
defined $conns{$_}{'user'} && $conns{$_}{'user'} eq $message->{'user'}
!ll&&!rl&&r
000
MC/DC0%0/2
defined $conns{$_}{'user'} && $conns{$_}{'user'} eq $message->{'user'}
defined $conns{$_}{'user'} $conns{$_}{'user'} eq $message->{'user'}
Truth table0%0/3
A && B
A= defined $conns{$_}{'user'}B= $conns{$_}{'user'} eq $message->{'user'}
ABresult
0X0
100
111
344 0 for my $id (@ids) {
345 0 ▶ if ($message->{op} eq 'kick') {
Branch: 2 branches
BranchTrueFalseTotal
if ($message->{'op'} eq 'kick') { } 0 0 0
elsif ($message->{'op'} eq 'disconnect') { } 0 0 0
346 0 $self->kick_connection($id, $message->{channel}, $message->{reason}, $message->{data});
347 }
348 elsif ($message->{op} eq 'disconnect') {
349 0 $self->disconnect_connection($id, $message->{reason}, $message->{data});
350 }
351 }
352 2 }
353  
354 # Takes over a WebSocket connection. Call from a websocket route.
355 0 ▶ method serve ($c) {
Subroutine serve: not called CC=7 SCAR=40.3
Pod undocumented
356 0 $self->_start;
357 # A process that cannot hear PostgreSQL would miss updates, kicks
358 # and disconnects, so it serves nobody. The browser keeps trying.
359 0 ▶ return $c->finish(1013) if $outdated or !$hearing;
Branch: 1 branch
BranchTrueFalseTotal
if $outdated or not $hearing 0 0 0
Condition0%0/3
$outdated or not $hearing
l!l&&r!l&&!r
000
MC/DC0%0/2
$outdated or not $hearing
$outdated not $hearing
Truth table0%0/3
A or not(B)
A= $outdatedB= not $hearing
ABresult
1X1
011
000
360 # Nor does a process that is on its way out; the browser will find
361 # another, or the one that replaces this.
362 0 ▶ return $c->finish(1001) if $stopping;
Branch: 1 branch
BranchTrueFalseTotal
if $stopping 0 0 0
363 0 $self->_watch_for_stop;
364 # From here on the connection is used through its transaction. The
365 # controller's own send and on each answer the handshake as well,
366 # which is one answer too many per call when this route was reached
367 # asynchronously (behind an "under" that continues later): the
368 # server then closes the connection it has just opened.
369 0 my $tx = $c->tx;
370 0 my $id = ++$next_conn;
371 0 ▶ my $user = $identify ? $identify->($c) : undef;
Branch: 1 branch
BranchTrueFalseTotal
$identify ? : 0 0 0
372 0 ▶ $conns{$id} = { c => $c, tx => $tx, channels => {}, user => (defined $user ? "$user" : undef) };
Branch: 1 branch
BranchTrueFalseTotal
defined $user ? : 0 0 0
373 0 $c->inactivity_timeout($heartbeat_interval * 2 + 10);
374 # Two signs of life per interval: a WebSocket ping, whose automatic
375 # pong tells this side that the browser is there, and a heartbeat
376 # message, which is the only one of the two that the browser's
377 # JavaScript can see.
378 0 ▶ my $beat = sub (@extra) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
379 0 $tx->send([1, 0, 0, 0, 9, '']);
380 0 $tx->send({ json => { type => 'heartbeat', interval => $heartbeat_interval, @extra } });
381 0 };
382 # The first heartbeat also announces the protocol version; a client
383 # that speaks another refuses to go on.
384 0 $beat->(protocol => BoardStreams::PROTOCOL_VERSION);
385 0 ▶ my $ping = Mojo::IOLoop->recurring($heartbeat_interval => sub { $beat->() });
Subroutine __ANON__: not called CC=1 SCAR=6.9
386  
387 0 ▶ $tx->on(json => sub ($tx, $msg) {
Subroutine __ANON__: not called CC=9 SCAR=45.0
388 0 ▶ return unless ref $msg eq 'HASH' and defined $msg->{type} and defined $msg->{channel};
Branch: 1 branch
BranchTrueFalseTotal
unless ref $msg eq "HASH" and defined $msg->{"type"} and defined $msg->{"channel"} 0 0 0
Condition0%0/6
ref $msg eq "HASH" and defined $msg->{"type"} and defined $msg->{"channel"}
!ll&&!rl&&r
000
ref $msg eq "HASH" and defined $msg->{"type"}
!ll&&!rl&&r
000
MC/DC0%0/3
ref $msg eq "HASH" and defined $msg->{"type"} and defined $msg->{"channel"}
ref $msg eq "HASH" defined $msg->{"type"} defined $msg->{"channel"}
Truth table0%0/4
A and B and C
A= ref $msg eq "HASH"B= defined $msg->{"type"}C= defined $msg->{"channel"}
ABCresult
0XX0
10X0
1100
1111
389 0 my $type = $msg->{type};
390 my $p = $type eq 'join' ? $self->_join($id, $msg)
391 : $type eq 'leave' ? $self->_leave($id, $msg->{channel})
392 0 ▶ : $type eq 'action' ? $self->_call($id, $msg, 'actions')
Branch: 4 branches
BranchTrueFalseTotal
$type eq 'join' ? : 0 0 0
$type eq 'leave' ? : 0 0 0
$type eq 'action' ? : 0 0 0
$type eq 'request' ? : 0 0 0
393 : $type eq 'request' ? $self->_call($id, $msg, 'requests')
394 : undef;
395 0 ▶ $p->catch(sub ($err) { $log->error("BoardStreams: $type failed: $err") }) if blessed $p;
Subroutine __ANON__: not called CC=1 SCAR=6.9
Branch: 1 branch
BranchTrueFalseTotal
if builtin::blessed($p) 0 0 0
396 0 });
397 0 ▶ $tx->on(finish => sub {
Subroutine __ANON__: not called CC=3 SCAR=24.8
398 0 Mojo::IOLoop->remove($ping);
399 0 ▶ my $conn = delete $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = delete $conns{$id} or return 0 0 0
400 0 $self->_leave($id, $_) for keys $conn->{channels}->%*;
401 0 });
402 # The handshake is answered here, exactly once, with whatever
403 # headers earlier steps of the route have put on the response.
404 0 ▶ $c->rendered(101) unless $tx->established;
Branch: 1 branch
BranchTrueFalseTotal
unless $tx->established 0 0 0
405 0 return $self;
406 2 }
407  
408 0 ▶ method _spec ($channel) {
Subroutine _spec: not called CC=3 SCAR=24.8
409 0 my ($exact) = grep { $_->{pattern} eq $channel } @specs;
410 0 ▶ return $exact if $exact;
Branch: 1 branch
BranchTrueFalseTotal
if $exact 0 0 0
411 # Perl's sort is stable, so the earliest registered wins a full tie.
412 0 ▶ my ($best) = sort { $b->{literal} <=> $a->{literal} or $a->{deep} <=> $b->{deep} }
Condition0%0/3
$BoardStreams::Hub::b->{'literal'} <=> $BoardStreams::Hub::a->{'literal'} || $BoardStreams::Hub::a->{'deep'} <=> $BoardStreams::Hub::b->{'deep'}
l!l&&r!l&&!r
000
MC/DC0%0/2
$BoardStreams::Hub::b->{'literal'} <=> $BoardStreams::Hub::a->{'literal'} || $BoardStreams::Hub::a->{'deep'} <=> $BoardStreams::Hub::b->{'deep'}
$BoardStreams::Hub::b->{'literal'} <=> $BoardStreams::Hub::a->{'literal'} $BoardStreams::Hub::a->{'deep'} <=> $BoardStreams::Hub::b->{'deep'}
Truth table0%0/3
A || B
A= $BoardStreams::Hub::b->{'literal'} <=> $BoardStreams::Hub::a->{'literal'}B= $BoardStreams::Hub::a->{'deep'} <=> $BoardStreams::Hub::b->{'deep'}
ABresult
1X1
011
000
413 0 grep { $channel =~ $_->{regex} } @specs;
414 0 return $best;
415 2 }
416  
417 0 ▶ method _initial_state ($channel) {
Subroutine _initial_state: not called CC=3 SCAR=24.8
418 0 my $spec = $self->_spec($channel);
419 0 ▶ return $spec && $spec->{initial_state} ? $spec->{initial_state} : {};
Branch: 1 branch
BranchTrueFalseTotal
$spec && $spec->{'initial_state'} ? : 0 0 0
Condition0%0/3
$spec and $spec->{"initial_state"}
!ll&&!rl&&r
000
MC/DC0%0/2
$spec and $spec->{"initial_state"}
$spec $spec->{"initial_state"}
Truth table0%0/3
A and B
A= $specB= $spec->{"initial_state"}
ABresult
0X0
100
111
420 2 }
421  
422 0 ▶ method _send ($id, $msg) {
Subroutine _send: not called CC=2 SCAR=17.9
423 0 ▶ my $conn = $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = $conns{$id} or return 0 0 0
424 0 $conn->{tx}->send({ json => $msg });
425 2 }
426  
427 # Starts the per-process machinery; must run inside the worker's event loop.
428 0 ▶ method _start {
Subroutine _start: not called CC=3 SCAR=24.8
429 0 ▶ return if $started++;
Branch: 1 branch
BranchTrueFalseTotal
if $started++ 0 0 0
430 0 $token = join '-', $$, int rand 1e9;
431 0 $self->_listen;
432 0 ▶ Mojo::IOLoop->recurring($listener_check_interval => sub { $self->_check_listener });
Subroutine __ANON__: not called CC=1 SCAR=6.9
433 0 ▶ Mojo::IOLoop->recurring(($retention / 10 > 60 ? $retention / 10 : 60) => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
434 0 ▶ $self->purge->catch(sub ($err) { $log->warn("BoardStreams: purge failed: $err") });
Subroutine __ANON__: not called CC=1 SCAR=6.9
435 0 ▶ });
Branch: 1 branch
BranchTrueFalseTotal
$retention / 10 > 60 ? : 0 0 0
436 2 }
437  
438 0 ▶ method _listen {
Subroutine _listen: not called CC=3 SCAR=24.8
439 0 my $pubsub = $pg->pubsub;
440 0 ▶ unless ($wired++) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($wired++) 0 0 0
441 0 $pubsub->reconnect_interval($retry_delay);
442 0 ▶ $pubsub->on(disconnect => sub { $self->_deaf('lost its PostgreSQL connection') });
Subroutine __ANON__: not called CC=1 SCAR=6.9
443 0 ▶ $pubsub->on(reconnect => sub { $self->_hears });
Subroutine __ANON__: not called CC=1 SCAR=6.9
444 }
445 0 my $ok = eval {
446 0 $pubsub->db; # connects, or dies before any listener is added
447 0 my $mine = $self->_scope;
448 0 ▶ $pubsub->json(CONTROL_NAME)->listen(CONTROL_NAME, sub ($pubsub, $message) {
Subroutine __ANON__: not called CC=12 SCAR=50.5
449 0 ▶ return unless ref $message eq 'HASH' and ($message->{scope} // '') eq $mine;
Branch: 1 branch
BranchTrueFalseTotal
unless ref $message eq "HASH" and ($message->{"scope"} // "") eq $mine 0 0 0
Condition0%0/5
ref $message eq "HASH" and ($message->{"scope"} // "") eq $mine
!ll&&!rl&&r
000
$message->{"scope"} // ""
l!l
00
MC/DC0%0/2
ref $message eq "HASH" and ($message->{"scope"} // "") eq $mine
ref $message eq "HASH" $message->{"scope"}
Truth table0%0/3
A and B
A= ref $message eq "HASH"B= $message->{"scope"}
ABresult
0X0
100
111
450 0 ▶ my $op = $message->{op} // '';
Condition0%0/2
$message->{"op"} // ""
l!l
00
MC/DC0%0/1
$message->{"op"} // ""
$message->{"op"}
Truth table0%0/2
A
A= $message->{"op"}
Aresult
11
00
451 0 ▶ $self->_retire($message->{schema}) if ($message->{schema} // 0) > $SCHEMA_VERSION;
Branch: 1 branch
BranchTrueFalseTotal
if ($message->{"schema"} // 0) > $SCHEMA_VERSION 0 0 0
Condition0%0/2
$message->{"schema"} // 0
l!l
00
MC/DC0%0/1
$message->{"schema"} // 0
$message->{"schema"}
Truth table0%0/2
A
A= $message->{"schema"}
Aresult
11
00
452 0 ▶ return if $op eq 'schema';
Branch: 1 branch
BranchTrueFalseTotal
if $op eq "schema" 0 0 0
453 0 ▶ return $self->_controlled($message) unless $op eq 'echo';
Branch: 1 branch
BranchTrueFalseTotal
unless $op eq "echo" 0 0 0
454 undef $echo_awaited
455 0 ▶ if defined $echo_awaited and $message->{token} eq $token and $message->{n} == $echo_awaited;
Branch: 1 branch
BranchTrueFalseTotal
if defined $echo_awaited and $message->{"token"} eq $token and $message->{"n"} == $echo_awaited 0 0 0
Condition0%0/6
defined $echo_awaited and $message->{"token"} eq $token and $message->{"n"} == $echo_awaited
!ll&&!rl&&r
000
defined $echo_awaited and $message->{"token"} eq $token
!ll&&!rl&&r
000
MC/DC0%0/3
defined $echo_awaited and $message->{"token"} eq $token and $message->{"n"} == $echo_awaited
defined $echo_awaited $message->{"token"} eq $token $message->{"n"} == $echo_awaited
Truth table0%0/4
A and B and C
A= defined $echo_awaitedB= $message->{"token"} eq $tokenC= $message->{"n"} == $echo_awaited
ABCresult
0XX0
10X0
1100
1111
456 0 });
457 0 ▶ $pubsub->listen(NOTIFY_NAME, sub ($pubsub, $payload) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
458 0 my ($seq, $channel) = split / /, $payload, 2;
459 0 ▶ my $of = $members{$channel} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $of = $members{$channel} or return 0 0 0
460 0 ▶ $self->_pump($channel) if grep { $_ < $seq } values %$of;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$_ < $seq;} values %$of 0 0 0
461 0 });
462 0 1;
463 };
464 0 ▶ return if $ok;
Branch: 1 branch
BranchTrueFalseTotal
if $ok 0 0 0
465 0 $log->warn("BoardStreams: cannot reach PostgreSQL yet: $@");
466 0 ▶ Mojo::IOLoop->timer($retry_delay => sub { $self->_listen });
Subroutine __ANON__: not called CC=1 SCAR=6.9
467 2 }
468  
469 0 ▶ method _hears {
Subroutine _hears: not called CC=2 SCAR=17.9
470 0 ▶ $log->info('BoardStreams: hearing PostgreSQL, accepting browsers') unless $hearing;
Branch: 1 branch
BranchTrueFalseTotal
unless $hearing 0 0 0
471 0 $hearing = 1;
472 0 undef $echo_awaited;
473 2 }
474  
475 # While this process cannot hear PostgreSQL it would miss updates,
476 # kicks and disconnects. Instead of catching up later, it lets go of
477 # every browser now: they reconnect, to this process once it hears
478 # again or to another one, and every join handler runs afresh.
479 0 ▶ method _deaf ($why) {
Subroutine _deaf: not called CC=2 SCAR=17.9
480 0 ▶ return unless $hearing;
Branch: 1 branch
BranchTrueFalseTotal
unless $hearing 0 0 0
481 0 $hearing = 0;
482 0 undef $echo_awaited;
483 0 $log->warn(sprintf 'BoardStreams: %s; closing %d connection(s) until it is back', $why, scalar keys %conns);
484 0 $self->_drop_all;
485 2 }
486  
487 0 ▶ method _drop_all ($code = 1013) {
Subroutine _drop_all: not called CC=4 SCAR=30.0
488 0 for my $id (keys %conns) {
489 0 my $conn = delete $conns{$id};
490 0 $self->_leave($id, $_) for keys $conn->{channels}->%*;
491 0 $conn->{tx}->finish($code);
492 }
493 2 }
494  
495 # A graceful stop (the QUIT signal, a hypnotoad hot deployment, a
496 # worker that has served its share of connections) waits for the
497 # connections of this process to end, and WebSockets never end by
498 # themselves. The event loop announces such a stop with its finish
499 # event, so this hub listens for it. It has to do so in the process
500 # that holds the connections, which need not be the one that built the
501 # hub, and again if the loop was reset meanwhile; so this is called
502 # for every new connection and subscribes when it finds itself absent.
503 0 ▶ method _watch_for_stop {
Subroutine _watch_for_stop: not called CC=3 SCAR=24.8
504 0 my $loop = Mojo::IOLoop->singleton;
505 0 ▶ $on_finish //= do {
Condition0%0/3
$on_finish //= do { builtin::weaken(my $hub = $self); sub { $hub->_stop if $hub; } }
l!l&&r!l&&!r
000
MC/DC0%0/2
$on_finish //= do { builtin::weaken(my $hub = $self); sub { $hub->_stop if $hub; } }
$on_finish do { builtin::weaken(my $hub = $self); sub { $hub->_stop if $hub; } }
Truth table0%0/3
A //= B
A= $on_finishB= do { builtin::weaken(my $hub = $self); sub { $hub->_stop if $hub; } }
ABresult
1X1
011
000
506 0 weaken(my $hub = $self);
507 0 ▶ sub { $hub->_stop if $hub };
Subroutine __ANON__: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
if $hub 0 0 0
508 };
509 0 ▶ $loop->on(finish => $on_finish) unless grep { $_ == $on_finish } $loop->subscribers('finish')->@*;
Branch: 1 branch
BranchTrueFalseTotal
unless grep {$_ == $on_finish;} @{$loop->subscribers("finish")} 0 0 0
510 2 }
511  
512 # Lets go of every browser, so that the process can exit. They are
513 # not told to stay away: to them this is a lost connection like any
514 # other, and they reconnect, to whichever process answers.
515 0 ▶ method _stop {
Subroutine _stop: not called CC=2 SCAR=17.9
516 0 ▶ return if $stopping++;
Branch: 1 branch
BranchTrueFalseTotal
if $stopping++ 0 0 0
517 0 my @transactions = map { $_->{tx} } values %conns;
518 0 $log->info(sprintf 'BoardStreams: stopping gracefully; closing %d connection(s)', scalar @transactions);
519 0 $self->_drop_all(1001);
520 # A browser that does not answer the close must not hold the
521 # process up either.
522 0 ▶ Mojo::IOLoop->timer(1 => sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
523 0 Mojo::IOLoop->remove($_->connection) for grep { !$_->is_finished } @transactions;
524 0 });
525 2 }
526  
527 # A process running newer code has changed the tables. This code would
528 # go on using them the old way, so it stops: it lets go of every
529 # browser, refuses new ones and refuses to touch the tables, until the
530 # process is restarted with the new code.
531 0 ▶ method _retire ($newer) {
Subroutine _retire: not called CC=2 SCAR=17.9
532 0 ▶ return if $outdated;
Branch: 1 branch
BranchTrueFalseTotal
if $outdated 0 0 0
533 0 $outdated = $newer;
534 0 $log->error(sprintf 'BoardStreams: the database has moved to schema version %d, but this process runs code for version %d. '
535 . 'It has closed its %d connection(s) and serves nobody until restarted with the new code',
536 $newer, $SCHEMA_VERSION, scalar keys %conns);
537 0 $self->_drop_all;
538 2 }
539  
540 # A connection can die without the socket noticing, so this process
541 # keeps sending itself a notification and makes sure it arrives.
542 0 ▶ method _check_listener {
Subroutine _check_listener: not called CC=4 SCAR=30.0
543 0 ▶ return unless $hearing;
Branch: 1 branch
BranchTrueFalseTotal
unless $hearing 0 0 0
544 0 ▶ if (defined $echo_awaited) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $echo_awaited) 0 0 0
545 0 $self->_deaf('stopped receiving PostgreSQL notifications');
546 # Have the listener start over on a fresh connection.
547 0 eval { $pg->pubsub->db->disconnect };
548 0 return;
549 }
550 0 my $n = $echo_awaited = ++$echo_sent;
551 0 eval {
552 0 my %echo = (op => 'echo', token => $token, n => $n, scope => $self->_scope);
553 0 ▶ $echo{schema} = $SCHEMA_VERSION if $migrated;
Branch: 1 branch
BranchTrueFalseTotal
if $migrated 0 0 0
554 0 ▶ $pg->db->query_p('select pg_notify(?, ?)', CONTROL_NAME, to_json(\%echo))->catch(sub { });
Subroutine __ANON__: not called CC=1 SCAR=6.9
555 };
556 2 }
557  
558 0 ▶ method _join ($id, $msg) {
Subroutine _join: not called CC=1 SCAR=6.9
559 0 my $channel = $msg->{channel};
560 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=9 SCAR=45.0
561 0 my $spec = $self->_spec($channel);
562 0 ▶ my $reject = sub ($reason, $data = undef) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
563 0 $self->_send($id, { type => 'rejected', channel => $channel, reason => $reason, data => $data });
564 0 };
565 0 ▶ return $reject->('unknown_channel') unless $spec and $spec->{join};
Branch: 1 branch
BranchTrueFalseTotal
unless $spec and $spec->{"join"} 0 0 0
Condition0%0/3
$spec and $spec->{"join"}
!ll&&!rl&&r
000
MC/DC0%0/2
$spec and $spec->{"join"}
$spec $spec->{"join"}
Truth table0%0/3
A and B
A= $specB= $spec->{"join"}
ABresult
0X0
100
111
566 0 ▶ my $conn = $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = $conns{$id} or return 0 0 0
567  
568 my $ctx = BoardStreams::Context->new(
569 0 hub => $self, c => $conn->{c}, channel => $channel, connection => $id, user => $conn->{user});
570 0 my $accepted = eval { await Mojo::Promise->resolve($spec->{join}->($ctx)) };
571 0 ▶ if (my $err = $@) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $err = $@) 0 0 0
572 0 ▶ return $reject->($err->reason, $err->data) if _is_rejection($err);
Branch: 1 branch
BranchTrueFalseTotal
if _is_rejection($err) 0 0 0
573 0 $log->error("BoardStreams: join handler for $channel died: $err");
574 0 return $reject->('internal_error');
575 }
576 0 ▶ return $reject->('forbidden') unless $accepted;
Branch: 1 branch
BranchTrueFalseTotal
unless $accepted 0 0 0
577  
578 0 $conn->{channels}{$channel} = 1;
579 0 ▶ unless (eval { await $self->_enter($id, $channel, $msg->{since}); 1 }) {
Branch: 1 branch
BranchTrueFalseTotal
unless (eval { do { <custom op await>; 1 } }) 0 0 0
580 # Most likely PostgreSQL is unreachable: drop the connection
581 # so that the browser retries, instead of leaving it joined
582 # to nothing.
583 0 $log->warn("BoardStreams: cannot join $channel: $@");
584 0 ▶ $conn->{tx}->finish(1013) if $conns{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $conns{$id} 0 0 0
585 }
586 0 })->();
587 2 }
588  
589 # Sends a browser what it needs to be up to date on a channel (the
590 # updates it missed, or failing that the whole state) and makes it a
591 # member from that point on.
592 0 ▶ method _enter ($id, $channel, $since, $gap = 0) {
Subroutine _enter: not called CC=2 SCAR=17.9
593 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=16 SCAR=56.1
594 0 my ($snapshot, $seq, $updates);
595 0 while (1) {
596 # If the channel is deleted while this join reads it, what
597 # it read belongs to a channel that no longer exists. The
598 # deletion notice finds this mark and sets it.
599 0 my $stale = 0;
600 0 my $number = ++$next_join;
601 0 $joining{$channel}{$number} = \$stale;
602 0 my $ok = eval {
603 0 $snapshot = await $self->snapshot($channel);
604 0 $seq = $snapshot->{seq};
605 0 undef $updates;
606 0 ▶ if (defined $since and $since =~ /\A[0-9]+\z/ and !$gap) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $since and $since =~ /\A[0-9]+\z/u and not $gap) 0 0 0
Condition0%0/6
defined $since and $since =~ /\A[0-9]+\z/u and not $gap
!ll&&!rl&&r
000
defined $since and $since =~ /\A[0-9]+\z/u
!ll&&!rl&&r
000
MC/DC0%0/3
defined $since and $since =~ /\A[0-9]+\z/u and not $gap
defined $since $since =~ /\A[0-9]+\z/u not $gap
Truth table0%0/4
A and B and not(C)
A= defined $sinceB= $since =~ /\A[0-9]+\z/uC= not $gap
ABCresult
0XX0
10X0
1100
1111
607 0 ▶ if ($since == $seq) { $updates = [] }
Branch: 2 branches
BranchTrueFalseTotal
if ($since == $seq) { } 0 0 0
elsif ($since < $seq) { } 0 0 0
608 elsif ($since < $seq) {
609 0 my $rows = await $self->_updates($channel, $since, $seq);
610 0 ▶ $updates = $rows if @$rows == $seq - $since;
Branch: 1 branch
BranchTrueFalseTotal
if @$rows == $seq - $since 0 0 0
611 }
612 0 ▶ $gap = 1 unless $updates;
Branch: 1 branch
BranchTrueFalseTotal
unless $updates 0 0 0
613 }
614 0 1;
615 };
616 0 my $err = $@;
617 0 delete $joining{$channel}{$number};
618 0 ▶ delete $joining{$channel} unless $joining{$channel}->%*;
Branch: 1 branch
BranchTrueFalseTotal
unless %{$joining{$channel}} 0 0 0
619 0 ▶ die $err unless $ok;
Branch: 1 branch
BranchTrueFalseTotal
unless $ok 0 0 0
620 0 ▶ last unless $stale;
Branch: 1 branch
BranchTrueFalseTotal
unless $stale 0 0 0
621 # Read again; whatever the browser had before is history.
622 0 ▶ $gap = 1 if defined $since;
Branch: 1 branch
BranchTrueFalseTotal
if defined $since 0 0 0
623 }
624  
625 0 my %msg = (type => 'joined', channel => $channel, seq => $seq);
626 0 ▶ if ($updates) { $msg{updates} = $updates }
Branch: 1 branch
BranchTrueFalseTotal
if ($updates) { } 0 0 0
627 0 ▶ else { $msg{state} = $snapshot->{state}; $msg{gap} = \1 if $gap }
Branch: 1 branch
BranchTrueFalseTotal
if $gap 0 0 0
628  
629 0 ▶ my $conn = $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = $conns{$id} or return 0 0 0
630 0 ▶ return unless $conn->{channels}{$channel}; # left meanwhile
Branch: 1 branch
BranchTrueFalseTotal
unless $conn->{"channels"}{$channel} 0 0 0
631 0 $members{$channel}{$id} = $seq;
632 0 $self->_send($id, \%msg);
633 0 $self->_pump($channel);
634 0 })->();
635 2 }
636  
637 0 ▶ method _updates ($channel, $after, $upto = undef) {
Subroutine _updates: not called CC=3 SCAR=24.8
638 return $self->_db->query_p(
639 'select seq, diff::text as diff, events::text as events from bs_event
640 where channel = ? and seq > ? and seq <= ? order by seq limit ?',
641 $channel, $after, $upto // $after + PUMP_BATCH, PUMP_BATCH
642 0 ▶ )->then(sub ($results) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
643 0 ▶ return $results->hashes->map(sub {
Subroutine __ANON__: not called CC=2 SCAR=17.9
644 return {
645 seq => $_->{seq} + 0,
646 events => from_json($_->{events}),
647 0 ▶ (defined $_->{diff} ? (diff => from_json($_->{diff})) : ()),
Branch: 1 branch
BranchTrueFalseTotal
defined $_->{'diff'} ? : 0 0 0
648 };
649 0 })->to_array;
650 0 ▶ });
Condition0%0/2
$upto // $after + 500
l!l
00
MC/DC0%0/1
$upto // $after + 500
$upto
Truth table0%0/2
A
A= $upto
Aresult
11
00
651 2 }
652  
653 0 ▶ method _leave ($id, $channel) {
Subroutine _leave: not called CC=4 SCAR=30.0
654 0 ▶ delete $conns{$id}{channels}{$channel} if $conns{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $conns{$id} 0 0 0
655 0 ▶ my $of = $members{$channel} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $of = $members{$channel} or return 0 0 0
656 0 delete $of->{$id};
657 0 ▶ delete $members{$channel} unless %$of;
Branch: 1 branch
BranchTrueFalseTotal
unless %$of 0 0 0
658 0 return;
659 2 }
660  
661 # Delivers committed updates of a channel to its members on this
662 # process, strictly in sequence order. Runs once per channel at a time.
663 0 ▶ method _pump ($channel) {
Subroutine _pump: not called CC=3 SCAR=24.8
664 0 ▶ return unless $members{$channel};
Branch: 1 branch
BranchTrueFalseTotal
unless $members{$channel} 0 0 0
665 0 ▶ return $pumping{$channel} = 2 if $pumping{$channel};
Branch: 1 branch
BranchTrueFalseTotal
if $pumping{$channel} 0 0 0
666 0 $pumping{$channel} = 1;
667  
668 0 ▶ (async sub {
Subroutine __ANON__: not called CC=12 SCAR=50.5
669 0 ▶ while (my $of = $members{$channel}) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $of = $members{$channel}) 0 0 0
670 0 $pumping{$channel} = 1;
671 0 my ($from) = sort { $a <=> $b } values %$of;
672 0 my $rows = await $self->_updates($channel, $from);
673 0 ▶ $of = $members{$channel} or last;
Branch: 1 branch
BranchTrueFalseTotal
$of = $members{$channel} or last 0 0 0
674  
675 0 for my $id (keys %$of) {
676 0 for my $row (@$rows) {
677 0 ▶ next if $row->{seq} <= $of->{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $row->{"seq"} <= $of->{$id} 0 0 0
678 0 ▶ last if $row->{seq} != $of->{$id} + 1;
Branch: 1 branch
BranchTrueFalseTotal
if $row->{"seq"} != $of->{$id} + 1 0 0 0
679 0 $self->_send($id, { type => 'update', channel => $channel, %$row });
680 0 $of->{$id} = $row->{seq};
681 }
682 }
683  
684 # A member whose next update no longer exists (purged) is
685 # given the whole state again, flagged as a gap.
686 0 ▶ if (@$rows) {
Branch: 1 branch
BranchTrueFalseTotal
if (@$rows) 0 0 0
687 0 my $last = $rows->[-1]{seq};
688 0 for my $id (grep { $of->{$_} < $last } keys %$of) {
689 0 delete $of->{$id};
690 0 ▶ $self->_enter($id, $channel, undef, 1)->catch(sub ($err) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
691 0 $log->warn("BoardStreams: cannot resync $channel: $err");
692 0 ▶ $conns{$id}{tx}->finish(1013) if $conns{$id};
Branch: 1 branch
BranchTrueFalseTotal
if $conns{$id} 0 0 0
693 0 });
694 }
695 0 ▶ delete $members{$channel} unless %$of;
Branch: 1 branch
BranchTrueFalseTotal
unless %$of 0 0 0
696 }
697 0 ▶ last if @$rows < PUMP_BATCH and $pumping{$channel} == 1;
Branch: 1 branch
BranchTrueFalseTotal
if @$rows < 500 and $pumping{$channel} == 1 0 0 0
Condition0%0/3
@$rows < 500 and $pumping{$channel} == 1
!ll&&!rl&&r
000
MC/DC0%0/2
@$rows < 500 and $pumping{$channel} == 1
@$rows < 500 $pumping{$channel} == 1
Truth table0%0/3
A and B
A= @$rows < 500B= $pumping{$channel} == 1
ABresult
0X0
100
111
698 }
699 0 delete $pumping{$channel};
700 0 ▶ })->()->catch(sub ($err) {
Subroutine __ANON__: not called CC=1 SCAR=6.9
701 0 $log->warn("BoardStreams: cannot read updates of $channel, retrying: $err");
702 0 ▶ Mojo::IOLoop->timer($retry_delay => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
703 0 delete $pumping{$channel};
704 0 $self->_pump($channel);
705 0 });
706 0 });
707 0 return;
708 2 }
709  
710 # Runs an action or request handler, at most once per unique id.
711 0 ▶ method _call ($id, $msg, $kind) {
Subroutine _call: not called CC=1 SCAR=6.9
712 0 my ($channel, $name, $msg_id) = @$msg{qw(channel name id)};
713 0 my $is_request = $kind eq 'requests';
714 0 ▶ return (async sub {
Subroutine __ANON__: not called CC=16 SCAR=56.1
715 0 ▶ my $reply = sub ($res, $seq) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
716 0 ▶ return $self->_send($id, { type => 'ack', id => $msg_id }) unless $is_request;
Branch: 1 branch
BranchTrueFalseTotal
unless $is_request 0 0 0
717 0 $self->_send($id, { type => 'response', id => $msg_id, seq => $seq, %$res });
718 0 };
719 0 ▶ my $failure = sub ($reason, $data = undef) {
Subroutine __ANON__: not called CC=2 SCAR=17.9
720 0 return { ok => \0, error => { reason => $reason, data => $data } };
721 0 };
722  
723 0 ▶ return $reply->($failure->('not_joined'), 0) unless $conns{$id} and $conns{$id}{channels}{$channel};
Branch: 1 branch
BranchTrueFalseTotal
unless $conns{$id} and $conns{$id}{"channels"}{$channel} 0 0 0
Condition0%0/3
$conns{$id} and $conns{$id}{"channels"}{$channel}
!ll&&!rl&&r
000
MC/DC0%0/2
$conns{$id} and $conns{$id}{"channels"}{$channel}
$conns{$id} $conns{$id}{"channels"}{$channel}
Truth table0%0/3
A and B
A= $conns{$id}B= $conns{$id}{"channels"}{$channel}
ABresult
0X0
100
111
724 0 my $spec = $self->_spec($channel);
725 0 ▶ my $handler = defined $name ? $spec->{$kind}{$name} : undef;
Branch: 1 branch
BranchTrueFalseTotal
defined $name ? : 0 0 0
726 0 ▶ return $reply->($failure->("unknown_" . ($is_request ? 'request' : 'action')), 0) unless $handler;
Branch: 2 branches
BranchTrueFalseTotal
unless $handler 0 0 0
$is_request ? : 0 0 0
727  
728 0 ▶ if (defined $msg_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $msg_id) 0 0 0
729 0 my $stored = await $self->_stored($msg_id);
730 0 ▶ return $reply->(@$stored) if $stored;
Branch: 1 branch
BranchTrueFalseTotal
if $stored 0 0 0
731 }
732  
733 0 ▶ my $conn = $conns{$id} or return;
Branch: 1 branch
BranchTrueFalseTotal
my $conn = $conns{$id} or return 0 0 0
734 my $ctx = BoardStreams::Context->new(
735 hub => $self, c => $conn->{c}, channel => $channel, request_id => $msg_id,
736 0 connection => $id, user => $conn->{user});
737 0 my $res;
738 0 ▶ if (eval { $res = { ok => \1, payload => await Mojo::Promise->resolve($handler->($ctx, $msg->{payload})) }; 1 }) { }
Branch: 3 branches
BranchTrueFalseTotal
if (eval { do { $res = {'ok', \1, 'payload', <custom op await>}; 1 } }) { } 0 0 0
elsif (builtin::blessed($@) and $@->isa('BoardStreams::Hub::Duplicate')) { } 0 0 0
elsif (_is_rejection($@)) { } 0 0 0
739 ▶ elsif (blessed $@ and $@->isa('BoardStreams::Hub::Duplicate')) {
Condition0%0/3
builtin::blessed($@) and $@->isa("BoardStreams::Hub::Duplicate")
!ll&&!rl&&r
000
MC/DC0%0/2
builtin::blessed($@) and $@->isa("BoardStreams::Hub::Duplicate")
builtin::blessed($@) $@->isa("BoardStreams::Hub::Duplicate")
Truth table0%0/3
A and B
A= builtin::blessed($@)B= $@->isa("BoardStreams::Hub::Duplicate")
ABresult
0X0
100
111
740 # Another copy of this message got there first.
741 0 my $stored = await $self->_stored($msg_id);
742 0 ▶ return $reply->(@$stored) if $stored;
Branch: 1 branch
BranchTrueFalseTotal
if $stored 0 0 0
743 0 $res = $failure->('internal_error');
744 }
745 0 elsif (_is_rejection($@)) { $res = $failure->($@->reason, $@->data) }
746 else {
747 0 $log->error("BoardStreams: $kind handler '$name' on $channel died: $@");
748 0 $res = $failure->('internal_error');
749 }
750  
751 0 my $seq = $ctx->seq;
752 0 ▶ if (defined $msg_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $msg_id) 0 0 0
753 0 ▶ eval {
Branch: 1 branch
BranchTrueFalseTotal
eval { do { my $row = <custom op await>->hash; $seq = $row->{"seq"} + 0; 1 } } or $log->warn("BoardStreams: cannot record outcome of ${msg_id}: $@") 0 0 0
754 0 my $row = (await $self->_db->query_p(
755 'insert into bs_request (id, channel, seq, response) values (?, ?, ?, ?)
756 on conflict (id) do update set response = excluded.response returning seq',
757 $msg_id, $channel, $seq, { json => $res }))->hash;
758 0 $seq = $row->{seq} + 0;
759 0 1;
760 } or $log->warn("BoardStreams: cannot record outcome of $msg_id: $@");
761 }
762 0 $reply->($res, $seq);
763 0 })->();
764 2 }
765  
766 # The recorded outcome of an already handled message, as [$response, $seq].
767 # If the first copy changed the channel but its outcome was never
768 # recorded (the process died in between), the best that can be said is
769 # that it succeeded.
770 0 ▶ method _stored ($msg_id) {
Subroutine _stored: not called CC=1 SCAR=6.9
771 return $self->_db->query_p('select seq, response::text as response from bs_request where id = ?', $msg_id)
772 0 ▶ ->then(sub ($results) {
Subroutine __ANON__: not called CC=3 SCAR=24.8
773 0 ▶ my $row = $results->hash or return undef;
Branch: 1 branch
BranchTrueFalseTotal
my $row = $results->hash or return undef 0 0 0
774 0 ▶ my $res = defined $row->{response} ? from_json($row->{response}) : { ok => \1, payload => undef };
Branch: 1 branch
BranchTrueFalseTotal
defined $row->{'response'} ? : 0 0 0
775 0 return [$res, $row->{seq} + 0];
776 0 });
777 2 }
778  
779 0 ▶ sub _is_rejection ($err) { blessed $err and $err->isa('BoardStreams::Rejection') }
Subroutine _is_rejection: not called CC=2 SCAR=17.9
Branch: 1 branch
BranchTrueFalseTotal
builtin::blessed($err) and $err->isa("BoardStreams::Rejection") 0 0 0
780 }
781  
782 2 class BoardStreams::Hub::Duplicate { }
783  
784 2 1;
↑ Summary BoardStreams/Diff.pm »