BoardStreams/Client/Stream.pm untested

filter: Statementstmt 0.0% 0 / 193 Branchbran 0.0% 0 / 46 Conditioncond 0.0% 0 / 23 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 7 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 283 CC 20 SCAR 54.7
CC
20
Cov
0%
new
342.0
send_join_or_leave
12.0
BEGIN
2.0
CRAP 238.5
1 package BoardStreams::Client::Stream;
2  
3 use Mojo::Base 'Mojo::EventEmitter', -signatures, -async_await;
4  
5 use BoardStreams::Client::StructDiff 'patch_state';
6 use BoardStreams::Util 'eqq';
7  
8 use RxPerl::Mojo ':all';
9 use Storable 'dclone';
10  
11 our $VERSION = "v0.0.36";
12  
13 has name => sub { die 'missing name' };
14 has manager => sub { die 'missing manager' };
15  
16 has 'initial_states_o';
17 has 'events_patches_o';
18 has 'events_with_ids_o';
19 has 'events_o';
20 has 'state' => undef;
21 has 'state_o';
22  
23 sub new ($class, $name, $manager) {
24 my $self = $class->SUPER::new(
25 name => $name,
26 manager => $manager,
27 );
28  
29 $self->{last_id} = undef;
30  
31 $self->{desired_join_state_o} = rx_behavior_subject->new(0); # user's stated wishes (defined)
32 $self->{join_state_o} = rx_behavior_subject->new(0); # joined || leaving
33 $self->{future_state_o} = rx_behavior_subject->new(0); # joining || joined
34  
35 # derived
36 $self->{stabilized_join_state_1} = rx_behavior_subject->new(0);
37 $self->{stabilized_join_state_2} = rx_behavior_subject->new(0);
38  
39 $self->{EPSs_o} = rx_subject->new; # stream of event patches and states
40 $self->initial_states_o(
41 $self->{EPSs_o}->pipe(
42 op_filter(sub { $_->{type} eq 'state' }),
43 op_map(sub { $_->{data} }),
44 op_share(),
45 )
46 );
47 $self->events_patches_o(
48 $self->{EPSs_o}->pipe(
49 op_filter(sub { $_->{type} eq 'eventPatch' }),
50 op_map(sub {
51 +{
52 id => $_->{id},
53 exists($_->{event}) ? (event => $_->{event}) : (),
54 exists($_->{patch}) ? (patch => $_->{patch}) : (),
55 };
56 }),
57 op_share(),
58 )
59 );
60 $self->events_with_ids_o(
61 $self->events_patches_o->pipe(
62 op_filter(sub { defined $_->{event} }),
63 op_map(sub {
64 +{ $_->%{qw/ id event /} };
65 }),
66 )
67 );
68 $self->events_o(
69 $self->events_with_ids_o->pipe(
70 op_map(sub { $_->{event} }),
71 )
72 );
73 $self->state_o(rx_replay_subject->new(1));
74  
75 # set stream's state on every state & eventPatch message
76 # useful because the type of state might change, and because
77 # of initial_states_o
78  
79 # TODO: all these need to be destroyed, because we will have circular references (memory leak)
80 $self->state_o->subscribe(sub ($s) { $self->state($s) });
81 $self->state_o->subscribe(sub ($state) { $self->emit('state', $state) });
82 $self->events_patches_o->subscribe(sub ($event_patch) { $self->emit('event_patch', $event_patch) });
83 $self->events_with_ids_o->subscribe(sub ($event_with_id) { $self->emit('event_with_id', $event_with_id) });
84 $self->events_o->subscribe(sub ($event) { $self->emit('event', $event) });
85 $self->initial_states_o->subscribe(sub ($i_state) { $self->emit('initial_state', $i_state) });
86  
87 # send join or leave request (returns state and past events)
88 my sub send_join_or_leave ($desired_join_state) {
89 $manager->do_request(
90 '!open',
91 $desired_join_state ? 'join' : 'leave',
92 $desired_join_state ? {
93 name => $name,
94 last_id => $self->{last_id},
95 } : $name,
96 );
97 }
98  
99 my $ep_repository = [];
100  
101 # these subscriptions will be unsubscribed from on channel destruction
102 $self->{subscriptions_to_destroy} = [
103  
104 # keep state and state_o up to date
105 rx_merge(
106 $self->initial_states_o->pipe(
107 op_map(sub { [$_, undef] }),
108 ),
109  
110 $self->events_patches_o->pipe(
111 op_filter(sub { exists $_->{patch} }),
112 op_map(sub { [undef, $_->{patch}] }),
113 ),
114 )->pipe(
115 op_scan(sub ($acc, $init_and_diff, @) {
116 my ($initial_state, $diff) = @$init_and_diff;
117  
118 if (defined $initial_state) { return $initial_state; }
119 return dclone([patch_state($acc, $diff)])->[0];
120 }, undef),
121 op_tap(sub ($x) { $self->state($x) }),
122 )->subscribe($self->state_o),
123  
124 # on disconnect, set not-joined (left)
125 $manager->connected_o->pipe(
126 op_filter(sub { ! $_ }),
127 )->subscribe(sub {
128 $self->{future_state_o}->next(0);
129 $self->{join_state_o}->next(0);
130 }),
131  
132 # fill ep_repository if we must with incoming event-patches
133 $manager->{incoming_o}->pipe(
134 op_filter(sub ($msg, @) {
135 eqq($msg->{stream}, $name) and eqq($msg->{type}, 'eventPatch');
136 }),
137 op_map(sub { dclone($_) }),
138 )->subscribe(sub ($ep) {
139 delete $ep->{stream};
140 if ($ep_repository) {
141 push @$ep_repository, $ep;
142 } elsif ($self->{join_state_o}) {
143 if ($ep->{id} > $self->{last_id}) {
144 $self->{EPSs_o}->next($ep);
145 $self->{last_id} = $ep->{id};
146 }
147 }
148 }),
149  
150 # set or remove ep_repository
151 $self->{join_state_o}->pipe(
152 op_combine_latest_with($self->{future_state_o}),
153 op_filter(sub {
154 my ($present) = @$_;
155 return ! $present;
156 }),
157 )->subscribe(sub ($pair) {
158 my (undef, $future) = @$pair;
159 if ($future) { $ep_repository //= [] }
160 else { $ep_repository = undef }
161 }),
162  
163 # set stabilized join states
164 $self->{join_state_o}->pipe(
165 op_combine_latest_with($self->{future_state_o}),
166 op_map(sub {
167 my ($present, $future) = @$_;
168 return $present == $future ? $present : undef;
169 }),
170 op_switch_map(sub ($x, @) {
171 if (! defined $x) {
172 return rx_of(undef);
173 } else {
174 return rx_of($x)->pipe(
175 op_delay(0.1),
176 );
177 }
178 }),
179 op_distinct_until_changed(),
180 )->subscribe($self->{stabilized_join_state_1}),
181  
182 $self->{join_state_o}->pipe(
183 op_combine_latest_with(
184 $self->{future_state_o},
185 $manager->connected_o,
186 $self->{desired_join_state_o},
187 ),
188 op_switch_map(sub ($quad, @) {
189 my ($present, $future, $connected, $desired) = @$quad;
190 return $desired ? rx_of(undef) : rx_of(0)->pipe(op_delay(0.1)) if ! $connected;
191 return $present == $future ? rx_of($present)->pipe(op_delay(0.1)) : rx_of(undef);
192 }),
193 op_distinct_until_changed(),
194 )->subscribe($self->{stabilized_join_state_2}),
195  
196 # send join or leave requests at the right times, and process results
197 $self->{desired_join_state_o}->pipe(
198 op_combine_latest_with($manager->connected_o),
199 op_concat_map(sub ($pair, @) {
200 my ($desired, $connected) = @$pair;
201  
202 $connected or return rx_EMPTY;
203 $desired == $self->{desired_join_state_o}->get_value or return rx_EMPTY;
204 $desired != $self->{future_state_o}->get_value or return rx_EMPTY;
205 $self->{future_state_o}->next($desired);
206  
207 return rx_from(
208 send_join_or_leave($desired)->then(
209 sub ($state_and_past_events) {
210 +{
211 ok => 1,
212 desired => $desired,
213 state_and_past_events => $state_and_past_events,
214 };
215 },
216 sub {
217 +{
218 ok => 0,
219 desired => $desired,
220 };
221 },
222 )
223 );
224 }),
225 )->subscribe(sub ($obj) {
226 my ($ok, $desired, $state_and_past_events) = $obj->@{qw/ ok desired state_and_past_events /};
227 if ($ok) {
228 if ($desired) {
229 # push to EPSs_o and set join_state
230 my ($events, $state_obj) = $state_and_past_events->@{qw/ events state /};
231 my ($state, $state_id) = $state_obj->@{qw/ data id /};
232  
233 $state_id >= ($self->{last_id} // 0) or die 'state.id < self.last_id';
234 foreach my $pair (@$events) {
235 my ($event, $event_id) = $pair->@{qw/ event id /};
236 $event_id > ($self->{last_id} // 0) or return;
237 $self->{EPSs_o}->next({
238 type => 'eventPatch',
239 id => $event_id,
240 event => $event,
241 });
242 }
243  
244 $self->{EPSs_o}->next({
245 type => 'state',
246 id => $state_id,
247 data => $state,
248 });
249  
250 $self->{last_id} = $state_id;
251  
252 foreach my $ep (@$ep_repository) {
253 if ($ep->{id} > $self->{last_id}) {
254 $self->{EPSs_o}->next($ep);
255 $self->{last_id} = $ep->{id};
256 }
257 }
258  
259 undef $ep_repository;
260 }
261 $self->{join_state_o}->next($desired);
262 } else {
263 $self->{future_state_o}->next($self->{join_state_o}->get_value);
264 }
265 }),
266 ];
267  
268 return $self;
269 }
270  
271 async sub destroy ($self) {
272 $self->{desired_join_state_o}->next(0);
273 await first_value_from(
274 $self->{stabilized_join_state_1}->pipe(
275 op_filter(sub { eqq($_, 0) }),
276 )
277 );
278 $_->unsubscribe foreach $self->{subscriptions_to_destroy}->@*;
279 $_->complete foreach (
280 $self->@{qw/
281 desired_join_state_o join_state_o future_state_o
282 stabilized_join_state_1 stabilized_join_state_2
283 EPSs_o
284 /},
285 $self->state_o,
286 );
287 }
288  
289 async sub join_or_leave ($self, $value) {
290 $self->{desired_join_state_o}->next($value);
291 my $eventual_state = await first_value_from(
292 $self->{'stabilized_join_state_' . ($value ? 2 : 1)}->pipe(
293 op_filter(sub { defined $_ }),
294 )
295 );
296 if ($eventual_state == $value) { return }
297 my $verb = $value ? 'join' : 'leave';
298 if ($self->{desired_join_state_o}->get_value != $value) {
299 die "$verb cancelled";
300 }
301 die "Couldn't $verb";
302 }
303  
304 sub join ($self) {
305 $self->join_or_leave(1);
306 }
307  
308 sub leave ($self) {
309 $self->join_or_leave(0);
310 }
311  
312 async sub do_action ($self, $action_name, $payload = undef, $opts = {}) {
313 my $wait_for_join = $opts->{wait_for_join};
314 my $stabilized_state = await first_value_from(
315 $self->{'stabilized_join_state_' . ($wait_for_join ? 2 : 1)}->pipe(
316 op_filter(sub { defined $_ }),
317 )
318 );
319 $stabilized_state or die "not joined stream, can't do action";
320  
321 $self->manager->do_action($self->name, $action_name, $payload);
322 }
323  
324 async sub do_request ($self, $request_name, $payload = undef, $opts = {}) {
325 my $wait_for_join = $opts->{wait_for_join};
326 my $stabilized_state = await first_value_from(
327 $self->{'stabilized_join_state_' . ($wait_for_join ? 2 : 1)}->pipe(
328 op_filter(sub { defined $_ }),
329 )
330 );
331 $stabilized_state or die "not joined stream, can't do request";
332  
333 return $self->manager->do_request($self->name, $request_name, $payload);
334 }
335  
336 1;