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
use tokio::task::JoinHandle;
use crate::select::ActorSelect;

pub trait ActorContext: Default + Sized + Unpin + 'static {
// pub trait ActorContext: Sized {

}

pub struct Addr<A: Actor> {
    tx: A,
}

pub struct Context<A>
    where
        A: Actor<Context = Context<A>>,
{
    // parts: ContextParts<A>,
    // mb: Option<Mailbox<A>>,
    ll: Option<A>,
}

impl<A> Context<A> where A: Actor<Context=Context<A>>, {
    pub fn new() -> Self {
        Context {ll: None}
    }
}

impl<A> ActorContext for Context<A> where
    A: Actor<Context=Context<A>>, {}

impl<A> Default for Context<A> where
    A: Actor<Context=Context<A>>, {
    fn default() -> Self {
        Self {
            ll: None,
        }
    }
}

#[allow(unused_variables)]
pub trait Actor: Sized + Unpin + 'static {
    /// Actor execution context type
    type Context: ActorContext + Send;

    // fn started(&mut self, ctx: &mut Self::Context) {}
    // fn stopping(&mut self, ctx: &mut Self::Context) -> Running {
    //     Running::Stop
    // }
    // fn stopped(&mut self, ctx: &mut Self::Context) {}

    fn default_context() -> Self::Context{
        let ctx: Self::Context = Default::default();
        ctx
    }


    // async fn select(&mut self, ctx: &mut Self::Context) -> Box<dyn select::ActorSelect<Self>>;
}

pub mod select {
    use crate::{Actor, Handler, Message, SelectResult};

    #[async_trait::async_trait]
    pub trait ActorSelect<Z: Actor> {
        async fn select(&mut self, ctx: &mut Z::Context, actor: &mut Z) -> SelectResult;
    }

    pub type MpscReceiver<T> = tokio::sync::mpsc::Receiver<T>;

    #[async_trait::async_trait]
    impl <Z, A> ActorSelect<Z> for MpscReceiver<A>
        where Z: Handler<A> + Send,
              A: Message + Send,
    {
        async fn select(&mut self, ctx: &mut Z::Context, actor: &mut Z) -> SelectResult {
            tokio::select! {
                Some(msg) = self.recv() => {
                    actor.handle(msg, ctx).await?;
                }
            }
            Ok(())
        }
    }

    #[async_trait::async_trait]
    impl <Z, A, B> ActorSelect<Z> for (MpscReceiver<A>, MpscReceiver<B>)
        where Z: Handler<A> + Handler<B> + Send,
              A: Message + Send, B: Message + Send,
    {
        async fn select(&mut self, ctx: &mut Z::Context, actor: &mut Z) -> SelectResult {
            tokio::select! {
                Some(msg) = self.0.recv() => {
                    actor.handle(msg, ctx).await?;
                }
                Some(msg) = self.1.recv() => {
                    actor.handle(msg, ctx).await?;
                }
            }
            Ok(())
        }
    }

    #[async_trait::async_trait]
    impl <Z, A, B, C> ActorSelect<Z> for (MpscReceiver<A>, MpscReceiver<B>, MpscReceiver<C>)
        where Z: Handler<A> + Handler<B> + Handler<C> + Send,
              A: Message + Send, B: Message + Send, C: Message + Send,
    {
        async fn select(&mut self, ctx: &mut Z::Context, actor: &mut Z) -> SelectResult {
            tokio::select! {
                Some(msg) = self.0.recv() => {
                    actor.handle(msg, ctx).await?;
                }
                Some(msg) = self.1.recv() => {
                    actor.handle(msg, ctx).await?;
                }
                Some(msg) = self.2.recv() => {
                    actor.handle(msg, ctx).await?;
                }
            }
            Ok(())
        }
    }
}

pub trait Message { }

#[async_trait::async_trait]
pub trait Handler<M>
    where
        Self: Actor,
        M: Message,
{
    /// This method is called for every message received by this actor.
    async fn handle(&mut self, msg: M, ctx: &mut <Self as Actor>::Context) -> HandleResult;
}

pub type HandleResult = Result<(), Box<dyn std::error::Error>>;
pub type SelectResult = Result<(), Box<dyn std::error::Error>>;

pub struct System {
    name: String,
}

impl System {
    pub fn global() -> Self {
        System { name: "Global".to_string() }
    }
}

impl System {
    pub async fn run<A, S>(&self, mut actor: A, mut select: S) -> JoinHandle<()>
        where
            A: Actor + Send,
            S: ActorSelect<A> + Send + 'static
    {
        let system_name = self.name.clone();
        let process_name = std::any::type_name::<A>().to_owned();

        let handle = tokio::spawn(async move {
            tracing::debug!("The system: {:?} spawned process: {:?}", system_name, process_name);

            let mut ctx = A::default_context();

            loop {
                tracing::debug!("iteration of the process: {process_name:?}");
                let result = select.select(&mut ctx, &mut actor).await;
                tracing::debug!("{process_name:?} result: {result:?}");
            }
        });
        handle
    }

    pub async fn run_fn<A, F, S>(&self, f: F, mut select: S) -> JoinHandle<()>
        where
            A: Actor + Send,
            F: FnOnce(&mut A::Context) -> A,
            S: ActorSelect<A> + Send + 'static
    {
        let mut ctx = A::default_context();
        let mut actor = f(&mut ctx);

        let process_name = std::any::type_name::<A>().to_owned();
        let handle = tokio::spawn(async move {
            tracing::debug!("Spawn process: {process_name:?}");

            loop {
                tracing::debug!("iteration of the process: {process_name:?}");
                let result = select.select(&mut ctx, &mut actor).await;
                tracing::debug!("{process_name:?} result: {result:?}");
            }
        });
        handle
    }
}