mm1-sup 0.7.23

An Erlang-style actor runtime for Rust.
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
use std::collections::HashMap;
use std::time::Duration;

use eyre::Context;
use mm1_address::address::Address;
use mm1_common::errors::chain::StdErrorDisplayChainExt;
use mm1_common::errors::error_of::ErrorOf;
use mm1_common::log::{debug, warn};
use mm1_common::types::AnyError;
use mm1_core::context::{Fork, Linking, Messaging, Start, Stop, Tell, Watching};
use mm1_core::envelope::dispatch;
use mm1_core::tracing::WithTraceIdExt;
use mm1_proto::message;
use mm1_proto_ask::{Request, RequestHeader};
use mm1_proto_sup::common as sup_common;
use mm1_proto_sup::uniform::{self as unisup};
use mm1_proto_system::{
    StartErrorKind, StopErrorKind, {self as system},
};
use slotmap::SlotMap;

use crate::common::child_spec::{ChildSpec, InitType};
use crate::common::factory::ActorFactory;
use crate::uniform::child_type::UniformChildType;
use crate::uniform::{UniformSup, UniformSupContext};

pub async fn uniform_sup<R, Ctx, F, C>(
    ctx: &mut Ctx,
    sup_spec: UniformSup<F, C>,
) -> Result<(), AnyError>
where
    R: Send + 'static,
    Ctx: UniformSupContext<R>,
    F: ActorFactory<Runnable = R>,
    F::Args: Send,
    C: UniformChildType<F::Args>,
{
    let UniformSup { child_spec } = sup_spec;

    ctx.set_trap_exit(true).await;
    ctx.init_done(ctx.address()).await;

    let mut children: Children<C::Data> = Children {
        primary:    Default::default(),
        by_address: Default::default(),
    };

    loop {
        let envelope = ctx.recv().await.wrap_err("ctx.recv")?;
        let trace_id = envelope.header().trace_id();

        dispatch!(match envelope {
            Request::<_> {
                header: reply_to,
                payload: unisup::StartRequest::<F::Args> { args },
            } =>
                handle_start_request(ctx, &child_spec, &mut children, reply_to, args)
                    .with_trace_id(trace_id)
                    .await
                    .wrap_err("handle_start_request")?,

            ChildStarted { key, address } =>
                handle_child_started(ctx, &mut children, key, address)
                    .with_trace_id(trace_id)
                    .await
                    .wrap_err("handle_child_started")?,

            Request::<_> {
                header: reply_to,
                payload: unisup::StopRequest { child },
            } =>
                handle_stop_request(ctx, &child_spec, &mut children, reply_to, child)
                    .with_trace_id(trace_id)
                    .await
                    .wrap_err("handle_stop_request")?,

            system::Exited { peer, normal_exit } =>
                handle_sys_exited(ctx, &child_spec, &mut children, peer, normal_exit)
                    .with_trace_id(trace_id)
                    .await
                    .wrap_err("handle_sys_exited")?,

            unexpected @ _ => {
                trace_id.scope_sync(|| warn!(msg = ?unexpected, "unexpected message"));
            },
        });
    }
}

slotmap::new_key_type! {
    struct ChildKey;
}

#[derive(Debug)]
struct Children<D> {
    primary:    SlotMap<ChildKey, ChildEntry<D>>,
    by_address: HashMap<Address, ChildKey>,
}

#[derive(derive_more::Debug)]
struct ChildEntry<D> {
    status: ChildStatus,

    #[debug(skip)]
    data: D,
}

#[derive(Debug)]
enum ChildStatus {
    Starting,
    Started(Address),
    Stopping(Address),
}

async fn handle_start_request<Ctx, F, C>(
    ctx: &mut Ctx,
    child_spec: &ChildSpec<F, C>,
    children: &mut Children<C::Data>,
    reply_to: RequestHeader,
    args: F::Args,
) -> Result<(), AnyError>
where
    F: ActorFactory,
    Ctx: UniformSupContext<F::Runnable>,
    C: UniformChildType<F::Args>,
    F::Runnable: Send + 'static,
{
    let sup_address = ctx.address();
    let ChildSpec {
        launcher,
        child_type,
        init_type,
        stop_timeout: _,
        announce_parent,
    } = child_spec;
    let init_type = *init_type;
    let announce_parent = *announce_parent;

    let mut data = child_type.new_data(args);
    let runnable = child_type
        .make_runnable(launcher, &mut data)
        .wrap_err("child_type.make_runnable")?;
    let entry = ChildEntry {
        status: ChildStatus::Starting,
        data,
    };
    let key = children.primary.insert(entry);

    ctx.fork()
        .await
        .wrap_err("ctx.fork")?
        .run(async move |mut ctx| {
            let result = do_start_child(
                &mut ctx,
                sup_address,
                key,
                init_type,
                announce_parent,
                runnable,
            )
            .await;
            ctx.reply(reply_to, result).await.ok();
        })
        .await;

    debug!(key = ?key, "child status Created -> Starting");

    Ok(())
}

async fn handle_child_started<Ctx, D>(
    ctx: &mut Ctx,
    children: &mut Children<D>,
    key: ChildKey,
    address: Address,
) -> Result<(), AnyError>
where
    Ctx: Linking,
{
    let Children {
        primary,
        by_address,
    } = children;
    let ChildEntry { status, data: _ } = &mut primary[key];
    if !matches!(*status, ChildStatus::Starting) {
        return Err(eyre::format_err!(
            "unexpected child-status when received child-started: {:?}",
            status
        ))
    }
    ctx.link(address).await;
    let should_be_none = by_address.insert(address, key);
    assert!(should_be_none.is_none());
    *status = ChildStatus::Started(address);

    debug!(
        key = ?key, address = %address,
        "child status Starting -> Started"
    );

    Ok(())
}

async fn handle_stop_request<Ctx, F, C>(
    ctx: &mut Ctx,
    child_spec: &ChildSpec<F, C>,
    children: &mut Children<C::Data>,
    reply_to: RequestHeader,
    address: Address,
) -> Result<(), AnyError>
where
    F: ActorFactory,
    Ctx: UniformSupContext<F::Runnable>,
    C: UniformChildType<F::Args>,
    F::Runnable: Send + 'static,
{
    let sup_address = ctx.address();
    let ChildSpec { stop_timeout, .. } = child_spec;
    let stop_timeout = *stop_timeout;

    let Children {
        primary,
        by_address,
    } = children;
    if let Some(key) = by_address.get(&address).copied() {
        let ChildEntry { status, data: _ } = &mut primary[key];
        match *status {
            ChildStatus::Starting => {
                unreachable!("how could we recover child of this state by address?")
            },
            ChildStatus::Started(a) => {
                assert_eq!(a, address);
            },
            ChildStatus::Stopping(a) => {
                assert_eq!(a, address);
                ctx.reply(
                    reply_to,
                    unisup::StopResponse::Err(ErrorOf::new(
                        StopErrorKind::NotFound,
                        format!("already stopping: {}", address),
                    )),
                )
                .await
                .ok();
                return Ok(())
            },
        };
        *status = ChildStatus::Stopping(address);

        ctx.fork()
            .await
            .wrap_err("ctx.fork")?
            .run(async move |mut ctx| {
                let reply_with = do_stop_child(&mut ctx, sup_address, stop_timeout, address).await;
                ctx.reply(reply_to, reply_with).await.ok();
            })
            .await;
    } else {
        ctx.reply(
            reply_to,
            unisup::StopResponse::Err(ErrorOf::new(
                StopErrorKind::NotFound,
                format!("unknown address: {}", address),
            )),
        )
        .await
        .ok();
    }

    Ok(())
}

async fn handle_sys_exited<Ctx, F, C>(
    ctx: &mut Ctx,
    child_spec: &ChildSpec<F, C>,
    children: &mut Children<C::Data>,
    peer: Address,
    normal_exit: bool,
) -> Result<(), AnyError>
where
    Ctx: UniformSupContext<F::Runnable>,
    F: ActorFactory,
    F::Args: Send,
    F::Runnable: Send + 'static,
    C: UniformChildType<F::Args>,
{
    let sup_address = ctx.address();
    let ChildSpec {
        launcher,
        child_type,
        init_type,
        stop_timeout: _,
        announce_parent,
    } = child_spec;

    let init_type = *init_type;
    let announce_parent = *announce_parent;

    let Children {
        primary,
        by_address,
    } = children;

    let Some(key) = by_address.remove(&peer) else {
        reap_started_children(ctx, child_spec, children)
            .await
            .wrap_err("reap children")?;
        ctx.quit_err(UnknownPeerExited(peer)).await;
        unreachable!()
    };

    let ChildEntry { status, data } = &mut primary[key];
    match *status {
        ChildStatus::Starting => {
            unreachable!("how could we recover child of this state by address?")
        },
        ChildStatus::Stopping(a) => {
            assert_eq!(a, peer);
            primary.remove(key);

            debug!(
                key = ?key, peer = %peer,
                "child status Stopping -> Stopped"
            );

            Ok(())
        },
        ChildStatus::Started(a) => {
            if child_type.should_restart(data, normal_exit)? {
                assert_eq!(a, peer);

                let runnable = child_type
                    .make_runnable(launcher, data)
                    .wrap_err("child_type.make_runnable")?;

                *status = ChildStatus::Starting;

                debug!(
                    key = ?key, peer = %peer,
                    "child status Started -> Starting"
                );

                ctx.fork()
                    .await
                    .wrap_err("ctx.fork")?
                    .run(async move |mut ctx| {
                        let _reply_with = do_start_child(
                            &mut ctx,
                            sup_address,
                            key,
                            init_type,
                            announce_parent,
                            runnable,
                        )
                        .await;
                    })
                    .await;

                Ok(())
            } else {
                primary.remove(key);

                debug!(
                    key = ?key, peer = %peer,
                    "child status Started -> Stopped (should not restart)"
                );
                Ok(())
            }
        },
    }
}

async fn do_start_child<Runnable, Ctx>(
    ctx: &mut Ctx,
    sup_address: Address,
    child_key: ChildKey,
    init_type: InitType,
    announce_parent: bool,
    runnable: Runnable,
) -> unisup::StartResponse
where
    Ctx: Messaging + Start<Runnable>,
{
    debug!(init_type = ?init_type, "starting child");

    let result = match init_type {
        InitType::NoAck => {
            ctx.spawn(runnable, true)
                .await
                .map_err(|e| e.map_kind(StartErrorKind::Spawn))
        },
        InitType::WithAck { start_timeout } => ctx.start(runnable, true, start_timeout).await,
    };
    match result {
        Err(reason) => {
            warn!(reason = %reason.as_display_chain(), "error");
            Err(reason)
        },
        Ok(child) => {
            debug!(address = %child, "child");
            if announce_parent {
                debug!(address = %child, "child announcing parent");
                ctx.tell(
                    child,
                    sup_common::SetParent {
                        parent: sup_address,
                    },
                )
                .await
                .ok();
            }
            let _ = ctx
                .tell(
                    sup_address,
                    ChildStarted {
                        key:     child_key,
                        address: child,
                    },
                )
                .await;
            Ok(child)
        },
    }
}

async fn do_stop_child<Ctx>(
    ctx: &mut Ctx,
    _sup_address: Address,
    stop_timeout: Duration,
    child_address: Address,
) -> unisup::StopResponse
where
    Ctx: Fork + Stop + Watching + Messaging,
{
    debug!(
        child_address = %child_address, stop_timeout = ?stop_timeout,
        "stopping child"
    );

    ctx.shutdown(child_address, stop_timeout)
        .await
        .map_err(|e| e.map_kind(|_| StopErrorKind::InternalError))
}

async fn reap_started_children<Ctx, F, C, D>(
    ctx: &mut Ctx,
    child_spec: &ChildSpec<F, C>,
    children: &mut Children<D>,
) -> Result<(), AnyError>
where
    Ctx: UniformSupContext<F::Runnable>,
    F: ActorFactory,
{
    let sup_address = ctx.address();
    let ChildSpec { stop_timeout, .. } = child_spec;
    let Children {
        primary,
        by_address,
    } = children;

    for (child_key, ChildEntry { status, data: _ }) in primary.drain() {
        let ChildStatus::Started(child_address) = status else {
            continue;
        };

        let should_be_child_key = by_address.remove(&child_address);
        assert_eq!(should_be_child_key, Some(child_key));

        do_stop_child(ctx, sup_address, *stop_timeout, child_address)
            .await
            .wrap_err("do_stop_child")?;
    }

    Ok(())
}

#[derive(Debug)]
#[message(base_path = ::mm1_proto)]
struct ChildStarted {
    key:     ChildKey,
    address: Address,
}

#[derive(Debug, thiserror::Error)]
#[error("unknown peer failure: {}", _0)]
struct UnknownPeerExited(Address);