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
use serde::de::Deserialize;
use serde::ser::Serialize;

use super::bridge::OneshotBridge;
use super::traits::Oneshot;
use super::worker::OneshotWorker;
use crate::actor::WorkerSpawner;
use crate::codec::{Bincode, Codec};

/// A spawner to create oneshot workers.
#[derive(Debug, Default)]
pub struct OneshotSpawner<N, CODEC = Bincode>
where
    N: Oneshot + 'static,
    CODEC: Codec,
{
    inner: WorkerSpawner<OneshotWorker<N>, CODEC>,
}

impl<N, CODEC> OneshotSpawner<N, CODEC>
where
    N: Oneshot + 'static,
    CODEC: Codec,
{
    /// Creates a [OneshotSpawner].
    pub const fn new() -> Self {
        Self {
            inner: WorkerSpawner::<OneshotWorker<N>, CODEC>::new(),
        }
    }

    /// Sets a new message encoding.
    pub const fn encoding<C>(&self) -> OneshotSpawner<N, C>
    where
        C: Codec,
    {
        OneshotSpawner {
            inner: WorkerSpawner::<OneshotWorker<N>, C>::new(),
        }
    }

    /// Spawns an Oneshot Worker.
    pub fn spawn(mut self, path: &str) -> OneshotBridge<N>
    where
        N::Input: Serialize + for<'de> Deserialize<'de>,
        N::Output: Serialize + for<'de> Deserialize<'de>,
    {
        let rx = OneshotBridge::register_callback(&mut self.inner);

        let inner = self.inner.spawn(path);

        OneshotBridge::new(inner, rx)
    }

    /// Spawns an Oneshot Worker with a loader shim script.
    pub fn spawn_with_loader(mut self, loader_path: &str) -> OneshotBridge<N>
    where
        N::Input: Serialize + for<'de> Deserialize<'de>,
        N::Output: Serialize + for<'de> Deserialize<'de>,
    {
        let rx = OneshotBridge::register_callback(&mut self.inner);

        let inner = self.inner.spawn_with_loader(loader_path);

        OneshotBridge::new(inner, rx)
    }
}