speare 0.4.3

actor-like thin abstraction over tokio::task and flume channels
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
use crate::{
    pubsub::{PubSub, Subscriber, TopicEntry},
    Backoff, Limit,
};
use flume::Receiver;
use std::{
    any::{Any, TypeId},
    cmp,
    collections::{hash_map::Entry, HashMap},
    future::Future,
    ops::Deref,
    sync::{Arc, RwLock},
    time::Duration,
};
use tokio::{
    task::{self, AbortHandle},
    time,
};

/// Creates a root context for the Speare::mini runtime.
///
/// The root context starts with no args, no child tasks, and [`OnErr::Stop`]
/// as its default error policy.
pub fn root() -> Ctx<()> {
    Ctx {
        args: Arc::new(()),
        pubsub: Default::default(),
        on_err: OnErr::Stop,
        children: Default::default(),
    }
}

#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub struct TaskId(u64);

/// Execution context for a mini task tree.
///
/// A `Ctx` carries:
/// - the task's typed args
/// - the shared pub/sub bus
/// - the task's child-task registry
/// - the error policy used when child tasks fail
///
/// Child tasks spawned from a context inherit its pub/sub bus and receive their
/// own child registry.
pub struct Ctx<Args = ()> {
    args: Arc<Args>,
    pubsub: Arc<RwLock<PubSub>>,
    on_err: OnErr,
    children: Arc<RwLock<HashMap<TaskId, AbortHandle>>>,
}

impl<Args> Clone for Ctx<Args> {
    fn clone(&self) -> Self {
        Self {
            args: self.args.clone(),
            pubsub: self.pubsub.clone(),
            on_err: self.on_err,
            children: self.children.clone(),
        }
    }
}

impl<Args> Drop for Ctx<Args> {
    fn drop(&mut self) {
        let _ = self.abort_children();
    }
}

impl<Args> Deref for Ctx<Args> {
    type Target = Args;

    fn deref(&self) -> &Self::Target {
        &self.args
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub enum SpeareErr {
    TypeMismatch { topic: String },
    LockPoisonErr,
}

impl std::fmt::Display for SpeareErr {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SpeareErr::TypeMismatch { topic } => {
                write!(f, "pub/sub topic type mismatch for topic: {topic}")
            }

            SpeareErr::LockPoisonErr => write!(f, "internal RwLock poisoned"),
        }
    }
}

impl std::error::Error for SpeareErr {}

type Result<T, E = SpeareErr> = std::result::Result<T, E>;

impl<Args> Ctx<Args>
where
    Args: Send + 'static,
{
    /// Subscribes to a topic and returns a typed receiver.
    ///
    /// If the topic does not exist yet, it is created with `T` as its message
    /// type.
    ///
    /// Returns [`SpeareErr::TypeMismatch`] if the topic already exists with a
    /// different message type.
    pub fn subscribe<T>(&self, topic: &str) -> Result<Receiver<T>>
    where
        T: Clone + Send + 'static,
    {
        let mut bus = self.pubsub.write().map_err(|_| SpeareErr::LockPoisonErr)?;

        let type_id = TypeId::of::<T>();

        if let Some(entry) = bus.topics.get(topic) {
            if entry.type_id != type_id {
                return Err(SpeareErr::TypeMismatch {
                    topic: topic.to_string(),
                });
            }
        }

        let sub_id = bus.next_sub_id;
        bus.next_sub_id += 1;

        let entry = bus
            .topics
            .entry(topic.to_string())
            .or_insert_with(|| TopicEntry {
                type_id,
                subscribers: Vec::new(),
            });

        let (msg_tx, msg_rx) = flume::unbounded();
        let send_fn = Box::new(move |any: &dyn Any| -> bool {
            if let Some(val) = any.downcast_ref::<T>() {
                msg_tx.send(val.clone()).is_ok()
            } else {
                false
            }
        });

        entry.subscribers.push(Subscriber {
            id: sub_id,
            send_fn,
        });

        Ok(msg_rx)
    }

    /// Publishes a message to all subscribers of a topic.
    ///
    /// The message is cloned once per live subscriber.
    ///
    /// Publishing to a topic with no subscribers is a no-op.
    ///
    /// Returns [`SpeareErr::TypeMismatch`] if the topic exists with a different
    /// message type.
    pub fn publish<T>(&self, topic: &str, msg: T) -> Result<()>
    where
        T: Clone + Send + 'static,
    {
        let mut bus = self.pubsub.write().map_err(|_| SpeareErr::LockPoisonErr)?;

        let Some(entry) = bus.topics.get_mut(topic) else {
            return Ok(());
        };

        if entry.type_id != TypeId::of::<T>() {
            return Err(SpeareErr::TypeMismatch {
                topic: topic.to_string(),
            });
        }

        let msg_any = &msg as &dyn Any;
        entry.subscribers.retain(|sub| (sub.send_fn)(msg_any));

        Ok(())
    }

    /// Spawns a child task with no extra args.
    ///
    /// The task receives an owned [`Ctx<()>`], which lets callers use async
    /// closures without boxing:
    ///
    /// ```ignore
    /// root.task(async |ctx| {
    ///     ctx.publish("events", "started")?;
    ///     Ok::<(), MyErr>(())
    /// })?;
    /// ```
    ///
    /// The child inherits this context's pub/sub bus and uses the default
    /// restart policy unless configured otherwise through [`SpawnBuilder`].
    pub fn task<ChildErr, TaskFn, Fut>(&self, taskfn: TaskFn) -> Result<()>
    where
        ChildErr: Send + 'static,
        TaskFn: Send + 'static + Fn(Ctx<()>) -> Fut,
        Fut: Future<Output = Result<(), ChildErr>> + Send,
    {
        SpawnBuilder::new(self, ())
            .inner_spawn(taskfn, false)
            .map(|_| ())
    }

    /// Returns a builder for spawning a child task with explicit args and
    /// supervision settings.
    pub fn task_with<'a>(&'a self) -> SpawnBuilder<'a, Args> {
        SpawnBuilder::new(self, ())
    }

    pub fn oneshot<ChildErr, TaskFn, Fut>(&self, taskfn: TaskFn) -> Result<()>
    where
        ChildErr: Send + 'static,
        TaskFn: Send + 'static + FnOnce(Ctx<()>) -> Fut,
        Fut: Future<Output = Result<(), ChildErr>> + Send,
    {
        let mut children = self
            .children
            .write()
            .map_err(|_| SpeareErr::LockPoisonErr)?;

        let child_ctx = Ctx {
            args: Arc::new(()),
            pubsub: self.pubsub.clone(),
            on_err: OnErr::Stop,
            children: Default::default(),
        };

        let handle = task::spawn(async move { taskfn(child_ctx).await });

        let next_id = children
            .keys()
            .fold(0, |highest_id, curr_id| cmp::max(highest_id, curr_id.0))
            + 1;

        let next_id = TaskId(next_id);

        children.insert(next_id, handle.abort_handle());

        Ok(())
    }
}

impl<Args> Ctx<Args> {
    pub fn abort_child(&self, id: TaskId) -> Result<bool> {
        let mut children = self
            .children
            .write()
            .map_err(|_| SpeareErr::LockPoisonErr)?;

        let aborted = match children.entry(id) {
            Entry::Vacant(_) => false,
            Entry::Occupied(child) => {
                child.get().abort();
                child.remove();
                true
            }
        };

        Ok(aborted)
    }

    pub fn abort_children(&self) -> Result<()> {
        let mut children = self
            .children
            .write()
            .map_err(|_| SpeareErr::LockPoisonErr)?;

        for child in children.values() {
            child.abort();
        }

        children.clear();

        Ok(())
    }
}

/// Builder for configuring and spawning a child task.
///
/// Use this when the child needs typed args or a non-default [`OnErr`] policy.
pub struct SpawnBuilder<'a, ParentArgs, ChildArgs = ()> {
    parent_ctx: &'a Ctx<ParentArgs>,
    child_args: ChildArgs,
    on_err: OnErr,
}

impl<'a, ParentArgs, ChildArgs> SpawnBuilder<'a, ParentArgs, ChildArgs>
where
    ParentArgs: Send + 'static,
    ChildArgs: Send + 'static + Sync,
{
    pub fn new(parent_ctx: &'a Ctx<ParentArgs>, child_args: ChildArgs) -> Self {
        Self {
            parent_ctx,
            child_args,
            on_err: OnErr::Restart {
                max: Limit::None,
                backoff: Backoff::None,
            },
        }
    }

    pub fn args<NewChildArgs>(
        self,
        child_args: NewChildArgs,
    ) -> SpawnBuilder<'a, ParentArgs, NewChildArgs> {
        SpawnBuilder {
            parent_ctx: self.parent_ctx,
            child_args,
            on_err: self.on_err,
        }
    }

    pub fn on_err(mut self, on_err: OnErr) -> Self {
        self.on_err = on_err;
        self
    }

    /// Spawns the child task.
    ///
    /// The task receives an owned child [`Ctx`]. If the task returns `Err`, the
    /// builder's [`OnErr`] policy decides whether it stops or restarts.
    pub fn spawn<ChildErr, TaskFn, Fut>(self, taskfn: TaskFn) -> Result<()>
    where
        ChildErr: Send + 'static,
        TaskFn: Send + 'static + Fn(Ctx<ChildArgs>) -> Fut,
        Fut: Future<Output = Result<(), ChildErr>> + Send,
    {
        self.inner_spawn(taskfn, false).map(|_| ())
    }

    /// Spawns the child task and returns a receiver for reported task failures.
    ///
    /// Each time the task returns `Err`, the `(TaskId, error)` pair is sent on
    /// the returned channel before the [`OnErr`] policy is applied.
    pub fn spawnwatch<ChildErr, TaskFn, Fut>(
        self,
        taskfn: TaskFn,
    ) -> Result<Receiver<(TaskId, ChildErr)>>
    where
        ChildErr: Send + 'static,
        TaskFn: Send + 'static + Fn(Ctx<ChildArgs>) -> Fut,
        Fut: Future<Output = Result<(), ChildErr>> + Send,
    {
        self.inner_spawn(taskfn, true)
            .map(|receiver| receiver.unwrap())
    }

    fn inner_spawn<ChildErr, TaskFn, Fut>(
        self,
        taskfn: TaskFn,
        watch: bool,
    ) -> Result<Option<Receiver<(TaskId, ChildErr)>>>
    where
        ChildArgs: Send + Sync,
        ChildErr: Send + 'static,
        TaskFn: Send + 'static + Fn(Ctx<ChildArgs>) -> Fut,
        Fut: Future<Output = Result<(), ChildErr>> + Send,
    {
        let mut children = self
            .parent_ctx
            .children
            .write()
            .map_err(|_| SpeareErr::LockPoisonErr)?;

        let next_id = children
            .keys()
            .fold(0, |highest_id, curr_id| cmp::max(highest_id, curr_id.0))
            + 1;

        let next_id = TaskId(next_id);

        let (err_tx, err_rx) = if watch {
            let (tx, rx) = flume::unbounded();
            (Some(tx), Some(rx))
        } else {
            (None, None)
        };

        let child_ctx = Ctx {
            args: Arc::new(self.child_args),
            pubsub: self.parent_ctx.pubsub.clone(),
            on_err: self.on_err,
            children: Default::default(),
        };

        let mut restart_count = 0_u64;

        let parent_children = self.parent_ctx.children.clone();
        let handle = task::spawn(async move {
            let child_ctx = child_ctx;
            let mut err_tx = err_tx;
            let task_id = next_id;

            while let Err(e) = taskfn(child_ctx.clone()).await {
                if let Some(tx) = &err_tx {
                    if tx.send((task_id, e)).is_err() {
                        err_tx = None;
                    }
                }

                match child_ctx.on_err {
                    OnErr::Stop => break,
                    OnErr::Restart { max, backoff } => {
                        if max == restart_count {
                            break;
                        }

                        let wait = match backoff {
                            Backoff::None => Duration::ZERO,
                            Backoff::Static(duration) => duration,
                            Backoff::Incremental { min, max, step } => {
                                let wait = step.mul_f64((restart_count + 1) as f64);
                                let wait = cmp::min(max, wait);
                                cmp::max(min, wait)
                            }
                        };

                        time::sleep(wait).await;
                    }
                };

                restart_count += 1;
            }

            if let Ok(mut children) = parent_children.write() {
                children.remove(&task_id);
            }
        });

        children.insert(next_id, handle.abort_handle());

        Ok(err_rx)
    }
}

/// Behavior to apply when a child task returns `Err`.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum OnErr {
    /// Stop the task after the first error.
    Stop,
    /// Restart the task after an error, subject to the configured limits and
    /// backoff policy.
    Restart { max: Limit, backoff: Backoff },
}