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
//! A runtime to supervise set of standalone actors.

mod signal;
mod spawn_actor;
//mod spawn_fn_task;
mod spawn_task;
mod thread;

// TODO: Continue here
pub use spawn_actor::Standalone;
pub use spawn_task::StandaloneTask;

use crate::actor::{Actor, Address, AddressPair, Context};
use crate::handlers::{InterruptedBy, StartedBy};
use anyhow::Error;
use async_trait::async_trait;
use derive_more::{Deref, DerefMut, From, Into};

/// The link to control the spawned `System`.
#[derive(Debug, From, Into, Deref, DerefMut, Clone)]
pub struct SystemLink {
    address: Address<System>,
}

impl SystemLink {
    /// Interrupt the `System`.
    pub fn interrupt(&mut self) -> Result<(), Error> {
        self.address.interrupt_by()
    }
}

/// Virtual actor that represents the system/environment.
pub struct System {
    supervisors_counter: usize,
}

#[doc(hidden)]
/// Group of actors of the `System`.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Group {
    /// Watched signals.
    Signals,
    /// Spawned actors (supervisors).
    Supervisors(usize),
    /// Spawned tasks.
    Tasks,
}

impl Actor for System {
    type GroupBy = Group;

    fn log_target(&self) -> &str {
        "System"
    }
}

#[async_trait]
impl StartedBy<Self> for System {
    async fn handle(&mut self, _ctx: &mut Context<Self>) -> Result<(), Error> {
        Ok(())
    }
}

#[async_trait]
impl InterruptedBy<Self> for System {
    async fn handle(&mut self, ctx: &mut Context<Self>) -> Result<(), Error> {
        ctx.shutdown();
        Ok(())
    }
}

impl System {
    /// Creates a `System` instance.
    pub fn new() -> Self {
        Self {
            supervisors_counter: 0,
        }
    }

    /// Start the `System` in the current `tokio` runtime.
    pub fn start(self) -> SystemLink {
        let pair = AddressPair::new();
        let address = pair.address().clone();
        crate::actor::spawn(self, Option::<Address<Self>>::None, pair);
        address.link()
    }

    /// Start the `System` in the separate thread.
    pub fn start_isolated(self) -> Result<SystemLink, Error> {
        let address = thread::spawn(self)?;
        Ok(address.link())
    }
}