bombay-behavior 0.2.0

Composable, statically typed actor behavior algebra
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::time::Duration;

use behavior::{
    Acted, Actions, At, AtEvent, AtGeneration, AtId, Base, Behavior, Births, ChildStopped, Crash,
    Create, Delivery, Exit, MailAddr, Move, Never, NoBirths, PeerStopped, Proxy, ProxyCommand,
    Recipient, RestartPolicy, Route, Spec, StashRoute, State, Step, Strategy, Supervising,
    SupervisionEvent, TimeReached, User, UserEvent, WatchEvent, Watching, run,
    stop_on_abnormal_death, workers,
};
use communication::{Config, channel};
use proptest::prelude::*;
use tokio::runtime::Builder;
use tokio::time::Instant;

struct Quiet;

fn requires_no_births<B: Behavior<Birth = NoBirths>>(_behavior: &B) {}

fn requires_births<B, C>(_behavior: &B)
where
    B: Behavior<Birth = Births<C>>,
{
}

impl State for Quiet {
    type Addr = MailAddr;
    type Msg = u64;

    fn handle(
        &mut self,
        _from: MailAddr,
        _message: u64,
    ) -> Acted<MailAddr, Never, Vec<Delivery<MailAddr, Never>>, NoBirths, Never> {
        Ok(Actions::cont())
    }
}

#[test]
fn actions_are_exactly_the_agha_triple() {
    let mut actions: Actions<MailAddr, Never, Vec<Delivery<MailAddr, u64>>, NoBirths> =
        Actions::cont();
    actions
        .sends
        .push(Delivery::new(Recipient::global(MailAddr(9)), 42));

    assert_eq!(actions.sends[0].to.route(), Route::Global(MailAddr(9)));
    assert_eq!(actions.sends[0].message, 42);
    assert!(actions.creates.is_empty());
    assert!(matches!(actions.become_, Step::Continue));
}

#[tokio::test]
async fn at_is_a_typed_clock_actor_protocol() {
    let now = Instant::now();
    let mut behavior = Spec::new(Quiet).at(Some(now), |_| Ok(Step::Continue));

    let initial = behavior.init().await.unwrap();
    assert!(initial.sends.inner.is_empty());
    assert_eq!(initial.sends.own.len(), 1);
    assert_eq!(initial.sends.own[0].at, now);

    let fired = behavior
        .step(AtEvent::Reached(TimeReached {
            id: AtId(0),
            generation: AtGeneration(0),
            at: now,
        }))
        .await
        .unwrap();
    assert!(fired.sends.own.is_empty());
}

#[tokio::test]
async fn driver_interprets_initial_effect_before_receiving() {
    let due = Instant::now() + Duration::from_secs(1);
    let behavior = Spec::new(Quiet).at(Some(due), |_| Ok(Step::Continue));
    let (control, user, mailbox) = channel::<Never, u64>(Config::new(1));
    drop(user);
    drop(control);

    let transcript = run(behavior, mailbox, MailAddr(0)).await.unwrap();
    assert_eq!(transcript.sends.own.len(), 1);
    assert_eq!(transcript.sends.own[0].at, due);
    assert_eq!(transcript.exit, Exit::Collected);
}

#[tokio::test]
async fn nested_at_composition_routes_stale_and_matching_events() {
    let early = Instant::now() + Duration::from_secs(1);
    let late = early + Duration::from_secs(1);
    let inner = At::new(Base::new(Quiet), AtId(0), Some(early), |_| {
        Ok(Step::Continue)
    });
    let mut outer = At::new(inner, AtId(1), Some(late), |_| Ok(Step::Continue));

    let initial = outer.init().await.unwrap();
    assert_eq!(initial.sends.inner.own[0].id, AtId(0));
    assert_eq!(initial.sends.own[0].id, AtId(1));
    assert_eq!(initial.sends.inner.own[0].at, early);
    assert_eq!(initial.sends.own[0].at, late);

    let early_event = AtEvent::Reached(TimeReached {
        id: AtId(0),
        generation: AtGeneration(0),
        at: early,
    });
    let actions = outer.step(early_event).await.unwrap();
    assert!(actions.sends.inner.own.is_empty());
}

#[tokio::test]
async fn spec_hides_composed_protocols_without_losing_their_effects() {
    let due = Instant::now() + Duration::from_secs(1);
    let peer = MailAddr(8);
    let mut behavior = Spec::new(Quiet)
        .at(Some(due), |_| Ok(Step::Continue))
        .watch(peer, stop_on_abnormal_death)
        .stash(|_| StashRoute::Deliver);

    let initial = behavior.init().await.unwrap();
    assert_eq!(initial.sends.inner.own[0].at, due);
    assert_eq!(initial.sends.own[0].message.peer, peer);

    let time = WatchEvent::Inner(AtEvent::Reached(TimeReached {
        id: AtId(0),
        generation: AtGeneration(0),
        at: due,
    }));
    let actions = behavior.step(time).await.unwrap();
    assert!(matches!(actions.become_, Step::Continue));
}

#[tokio::test]
async fn watching_registers_and_reacts_through_messages() {
    let peer = MailAddr(7);
    let mut behavior = Watching::new(Base::new(Quiet), peer, stop_on_abnormal_death);
    let initial = behavior.init().await.unwrap();
    assert_eq!(initial.sends.own[0].message.peer, peer);

    let stopped = WatchEvent::PeerStopped(PeerStopped {
        peer,
        outcome: Err(Crash::Failed),
    });
    let actions = behavior.step(stopped).await.unwrap();
    assert!(matches!(actions.become_, Step::Stop(Exit::LinkDied(p)) if p == peer));
}

#[tokio::test]
async fn stashing_is_local_state_and_replay() {
    struct Seen(Vec<u64>);
    impl State for Seen {
        type Addr = MailAddr;
        type Msg = u64;
        fn handle(
            &mut self,
            _from: MailAddr,
            message: u64,
        ) -> Acted<MailAddr, Never, Vec<Delivery<MailAddr, Never>>, NoBirths, Never> {
            self.0.push(message);
            Ok(Actions::cont())
        }
    }
    let mut behavior = Spec::new(Seen(Vec::new())).stash(|message| match message {
        0 => StashRoute::Release,
        1 => StashRoute::Stash,
        _ => StashRoute::Deliver,
    });
    behavior.step(User::user(MailAddr(1), 1)).await.unwrap();
    behavior.step(User::user(MailAddr(1), 0)).await.unwrap();
    assert_eq!(behavior.behavior().inner().state().0, vec![0]);
    assert_eq!(behavior.behavior().held(), 1);
}

#[tokio::test]
async fn fsm_is_receive_plus_become_policy() {
    #[derive(Clone, Copy, PartialEq)]
    enum Phase {
        Loading,
        Ready,
    }
    enum Message {
        Work(u64),
        Ready,
    }
    let mut machine = Spec::machine(
        Vec::new(),
        Phase::Loading,
        |phase, seen: &mut Vec<u64>, message| {
            Ok::<Move<Phase>, Never>(match (phase, message) {
                (Phase::Loading, Message::Work(_)) => Move::Defer,
                (_, Message::Work(value)) => {
                    seen.push(*value);
                    Move::Stay
                }
                (_, Message::Ready) => Move::Goto(Phase::Ready),
            })
        },
    );
    machine
        .step(User::user(MailAddr(0), Message::Work(3)))
        .await
        .unwrap();
    machine
        .step(User::user(MailAddr(0), Message::Ready))
        .await
        .unwrap();
    assert_eq!(machine.behavior().state(), &[3]);
}

type Child = Base<Quiet>;

struct Parent;

impl State<Never, Births<Child>, Never> for Parent {
    type Addr = MailAddr;
    type Msg = u64;

    fn handle(
        &mut self,
        _from: MailAddr,
        _message: u64,
    ) -> Acted<MailAddr, Never, Vec<Delivery<MailAddr, Never>>, Births<Child>, Never> {
        Ok(Actions::cont())
    }
}

fn child(_index: usize) -> Child {
    Base::new(Quiet)
}

#[test]
fn birth_modes_are_disjoint_and_wrappers_forward_them() {
    requires_no_births(&Spec::new(Quiet));

    let creator = Spec::new(Parent)
        .at(None, |_| Ok(Step::Continue))
        .watch(MailAddr(4), stop_on_abnormal_death)
        .stash(|_| StashRoute::Deliver);
    requires_births::<_, Child>(&creator);

    let supervisor = Spec::new(Parent).children((1, child));
    requires_births::<_, Proxy<Child>>(&supervisor);
    requires_births::<_, Child>(&Proxy::new(child(0)));
}

fn supervisor(
    strategy: Strategy,
    policy: RestartPolicy,
    budget: u32,
) -> Supervising<Base<Parent, Never, Births<Child>, Never>, Child> {
    Supervising::new(
        Base::new(Parent),
        |index| u64::try_from(index).unwrap(),
        3,
        child,
        strategy,
        policy,
        budget,
        Duration::MAX,
    )
}

#[tokio::test]
async fn supervisor_creates_proxies_and_replacement_is_a_send() {
    let mut supervisor = Spec::new(Parent)
        .children((2, child))
        .restart(Strategy::OneForOne)
        .when(RestartPolicy::Transient)
        .within(2, Duration::MAX);
    let initial = supervisor.init().await.unwrap();
    assert_eq!(initial.creates.len(), 2);
    assert_eq!(initial.sends.own.inner.len(), 2);
    assert!(
        initial
            .sends
            .own
            .inner
            .iter()
            .all(|send| send.to.route() == Route::Service)
    );

    let event = SupervisionEvent::ChildStopped(ChildStopped {
        nonce: 0,
        outcome: Err(Crash::Failed),
        at: Instant::now(),
    });
    let actions = supervisor.step(event).await.unwrap();
    assert!(actions.creates.is_empty());
    assert_eq!(actions.sends.own.own.len(), 1);
    assert_eq!(actions.sends.own.own[0].to.route(), Route::Child(0));
}

#[tokio::test]
async fn proxy_replacement_creates_a_fresh_incarnation() {
    let mut proxy = Proxy::new(child(0));
    let first = proxy.init().await.unwrap();
    assert_eq!(first.creates[0].nonce, 0);
    let second = proxy
        .step(User::user(MailAddr(0), ProxyCommand::Replace(child(0))))
        .await
        .unwrap();
    assert_eq!(second.creates[0].nonce, 1);

    let forwarded = proxy
        .step(User::user(MailAddr(0), ProxyCommand::Forward(7)))
        .await
        .unwrap();
    assert_eq!(forwarded.sends[0].to.route(), Route::Child(1));
    assert_eq!(forwarded.sends[0].message, 7);
}

struct BirthingParent(bool);

impl State<Never, Births<Child>, Never> for BirthingParent {
    type Addr = MailAddr;
    type Msg = u64;

    fn handle(
        &mut self,
        _from: MailAddr,
        nonce: u64,
    ) -> Acted<MailAddr, Never, Vec<Delivery<MailAddr, Never>>, Births<Child>, Never> {
        if self.0 {
            return Ok(Actions::cont());
        }
        self.0 = true;
        Ok(Actions {
            sends: Vec::new(),
            creates: vec![Create {
                nonce,
                child: child(0),
            }],
            become_: Step::Continue,
        })
    }
}

#[tokio::test]
async fn supervisor_preserves_and_observes_dynamic_births_once() {
    let mut supervisor = Spec::new(BirthingParent(false))
        .children((0, child))
        .within(1, Duration::MAX);
    let initial = supervisor.init().await.unwrap();
    assert!(initial.creates.is_empty());

    let born = supervisor
        .step(UserEvent::user(MailAddr(0), 9))
        .await
        .unwrap();
    assert_eq!(born.creates.len(), 1);
    assert_eq!(born.creates[0].nonce, 9);
    assert_eq!(born.sends.own.inner.len(), 1);
    assert_eq!(born.sends.own.inner[0].message.nonce, 9);
    assert_eq!(supervisor.behavior().child_count(), 1);

    let stopped = SupervisionEvent::ChildStopped(ChildStopped {
        nonce: 9,
        outcome: Err(Crash::Failed),
        at: Instant::now(),
    });
    let replacement = supervisor.step(stopped).await.unwrap();
    assert_eq!(replacement.sends.own.own.len(), 1);
    assert_eq!(replacement.sends.own.own[0].to.route(), Route::Child(9));
}

#[tokio::test]
async fn supervision_strategy_policy_and_budget_are_pure_send_decisions() {
    let at = Instant::now();
    let stopped = |nonce| {
        SupervisionEvent::ChildStopped(ChildStopped {
            nonce,
            outcome: Err(Crash::Failed),
            at,
        })
    };

    let mut one = supervisor(Strategy::OneForOne, RestartPolicy::Transient, 3);
    assert_eq!(one.step(stopped(1)).await.unwrap().sends.own.own.len(), 1);

    let mut all = supervisor(Strategy::OneForAll, RestartPolicy::Transient, 3);
    assert_eq!(all.step(stopped(1)).await.unwrap().sends.own.own.len(), 3);

    let mut rest = supervisor(Strategy::RestForOne, RestartPolicy::Transient, 3);
    assert_eq!(rest.step(stopped(1)).await.unwrap().sends.own.own.len(), 2);

    let mut temporary = supervisor(Strategy::OneForOne, RestartPolicy::Temporary, 3);
    assert!(
        temporary
            .step(stopped(1))
            .await
            .unwrap()
            .sends
            .own
            .own
            .is_empty()
    );
    assert!(!temporary.is_alive(1));

    let mut denied = supervisor(Strategy::OneForOne, RestartPolicy::Permanent, 0);
    assert!(
        denied
            .step(stopped(1))
            .await
            .unwrap()
            .sends
            .own
            .own
            .is_empty()
    );
}

#[tokio::test]
async fn stale_time_events_do_not_fire_or_reschedule() {
    let due = Instant::now() + Duration::from_secs(2);
    let mut behavior = At::new(Base::new(Quiet), AtId(0), Some(due), |_| {
        Ok(Step::Stop(Exit::Normal))
    });
    behavior.init().await.unwrap();
    let stale = AtEvent::Reached(TimeReached {
        id: AtId(0),
        generation: AtGeneration(0),
        at: due - Duration::from_secs(1),
    });
    let ignored = behavior.step(stale).await.unwrap();
    assert!(matches!(ignored.become_, Step::Continue));

    let fired = behavior
        .step(AtEvent::Reached(TimeReached {
            id: AtId(0),
            generation: AtGeneration(0),
            at: due,
        }))
        .await
        .unwrap();
    assert!(matches!(fired.become_, Step::Stop(Exit::Normal)));

    let duplicate = behavior
        .step(AtEvent::Reached(TimeReached {
            id: AtId(0),
            generation: AtGeneration(0),
            at: due,
        }))
        .await
        .unwrap();
    assert!(matches!(duplicate.become_, Step::Continue));
}

#[tokio::test]
async fn workers_macro_hides_a_heterogeneous_child_sum() {
    struct Other;
    impl State for Other {
        type Addr = MailAddr;
        type Msg = u64;
        fn handle(
            &mut self,
            _from: MailAddr,
            _message: u64,
        ) -> Acted<MailAddr, Never, Vec<Delivery<MailAddr, Never>>, NoBirths, Never> {
            Ok(Actions::cont())
        }
    }
    fn other(_index: usize) -> Base<Other> {
        Base::new(Other)
    }

    let (count, build) = workers![(2, Child, child), (1, Base<Other>, other)];
    assert_eq!(count, 3);
    let mut worker = build(2);
    worker.step(User::user(MailAddr(0), 7)).await.unwrap();
}

proptest! {
    #![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]

    #[test]
    fn nested_time_protocol_preserves_every_schedule(first in 0_u64..10_000, second in 0_u64..10_000) {
        let origin = Instant::now();
        let first = origin + Duration::from_nanos(first);
        let second = origin + Duration::from_nanos(second);
        let inner = At::new(Base::new(Quiet), AtId(0), Some(first), |_| Ok(Step::Continue));
        let mut outer = At::new(inner, AtId(1), Some(second), |_| Ok(Step::Continue));
        let runtime = Builder::new_current_thread().enable_all().build().unwrap();
        let actions = runtime.block_on(outer.init()).unwrap();
        prop_assert_eq!(actions.sends.inner.own[0].at, first);
        prop_assert_eq!(actions.sends.own[0].at, second);
    }

    #[test]
    fn supervision_strategy_matches_its_candidate_set(dead in 0_usize..3, strategy in 0_u8..3) {
        let strategy = match strategy {
            0 => Strategy::OneForOne,
            1 => Strategy::OneForAll,
            _ => Strategy::RestForOne,
        };
        let expected = match strategy {
            Strategy::OneForOne => 1,
            Strategy::OneForAll => 3,
            Strategy::RestForOne => 3 - dead,
        };
        let mut behavior = supervisor(strategy, RestartPolicy::Transient, 3);
        let event = SupervisionEvent::ChildStopped(ChildStopped {
            nonce: u64::try_from(dead).unwrap(),
            outcome: Err(Crash::Failed),
            at: Instant::now(),
        });
        let runtime = Builder::new_current_thread().enable_all().build().unwrap();
        let actions = runtime.block_on(behavior.step(event)).unwrap();
        prop_assert_eq!(actions.sends.own.own.len(), expected);
        prop_assert!(actions.creates.is_empty());
    }
}