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
use tokio::sync::mpsc;
use tokio::sync::oneshot;

pub trait Message: std::fmt::Debug + Send  {}

pub trait Name: std::fmt::Debug + std::fmt::Display + Send + Sync + Clone {}

impl Name for &'static str {}

pub struct Sender<M: Message, N: Name> {
    pub name: N,
    sender: mpsc::Sender<M>,
}

impl<M: Message, N: Name> Clone for Sender<M, N> {
    fn clone(&self) -> Self {
        Self {
            name: self.name.clone(),
            sender: self.sender.clone(),
        }
    }
}

impl<M: Message, N: Name> std::fmt::Debug for Sender<M, N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sender")
            .field("name", &self.name)
            .field(
                "sender",
                if self.sender.is_closed() {
                    &"closed"
                } else {
                    &"open"
                },
            )
            .finish()
    }
}

impl<M: Message, N: Name> Sender<M, N> {
    pub async fn closed(&self) {
        self.sender.closed().await;
    }
}

impl<M: Message, N: Name> Sender<M, N> {
    /// Send message to the receiver expecting a response.
    /// Message is constructed by calling message_fn
    pub async fn call<R: std::fmt::Debug>(
        &self,
        message_fn: impl FnOnce(oneshot::Sender<R>) -> M,
    ) -> R {
        let (tx, rx) = oneshot::channel();
        let message = message_fn(tx);

        #[cfg(feature = "log")]
        log::debug!("call `{:?}` on `{}`", message, self.name);

        self.sender.send(message).await.unwrap();
        let response = rx.await.unwrap();

        #[cfg(feature = "log")]
        log::debug!("response `{:?}` from `{}`", response, self.name);

        response
    }

    /// Send message to the receiver.
    /// Message is constructed by calling message_fn
    pub async fn notify(&self, message_fn: impl FnOnce() -> M) {
        let message = message_fn();

        #[cfg(feature = "log")]
        log::debug!("notify `{:?}` on `{}`", message, self.name);

        self.sender.send(message).await.unwrap();
    }
}

pub struct Receiver<M: Message, N: Name> {
    pub name: N,
    receiver: mpsc::Receiver<M>,
}

impl<M: Message, N: Name> std::fmt::Debug for Receiver<M, N> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Name").field("name", &self.name).finish()
    }
}

impl<M: Message, N: Name> std::ops::Deref for Receiver<M, N> {
    type Target = mpsc::Receiver<M>;

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

impl<M: Message, N: Name> std::ops::DerefMut for Receiver<M, N> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.receiver
    }
}

/// Creates a bounded mpsc channel for communicating between actors with backpressure.
///
/// The channel will buffer up to the provided number of messages.  Once the
/// buffer is full, attempts to send new messages will wait until a message is
/// received from the channel. The provided buffer capacity must be at least 1.
///
/// All data sent on `Sender` will become available on `Receiver` in the same
/// order as it was sent.
///
/// The `Sender` can be cloned to `send` to the same channel from multiple code
/// locations. Only one `Receiver` is supported.
///
/// If the `Receiver` is disconnected while trying to `send`, the `send` method
/// will return a `SendError`. Similarly, if `Sender` is disconnected while
/// trying to `recv`, the `recv` method will return `None`.
///
/// # Panics
///
/// Panics if the buffer capacity is 0.
pub fn channel<M: Message, N: Name>(buffer: usize, name: N) -> (Sender<M, N>, Receiver<M, N>) {
    let (sender, receiver) = mpsc::channel(buffer);

    (
        Sender {
            name: name.clone(),
            sender,
        },
        Receiver {
            name: name.clone(),
            receiver,
        },
    )
}

use async_trait::async_trait;

#[async_trait]
pub trait Handle<M: Message, N: Name> {
    fn sender(&self) -> &Sender<M, N>;

    fn name(&self) -> N {
        self.sender().name.clone()
    }

    async fn wait_for_stop(&self) {
        let sender = self.sender().clone();
        sender.closed().await
    }
}

use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;

pub struct MasterHandle<M: Message, N: Name, H: Handle<M, N>> {
    // TODO: Consider making use of HashSet<H> instead of Vec<H> to optimize `get` function
    slaves: Vec<H>,
    message_phantom: PhantomData<M>,
    name_phantom: PhantomData<N>,
}

impl<M: Message, N: Name, H: Handle<M, N>> MasterHandle<M, N, H> {
    pub fn new(slaves: Vec<H>) -> Self {
        Self {
            slaves,
            message_phantom: Default::default(),
            name_phantom: Default::default(),
        }
    }

    pub fn names(&self) -> Vec<N> {
        self.slaves.iter().map(Handle::name).collect()
    }
}

impl<M: Message, N: Name + PartialOrd, H: Handle<M, N>> MasterHandle<M, N, H> {
    pub fn get(&self, name: N) -> Option<&H> {
        self.slaves.iter().find(|h| h.name() == name)
    }
}

impl<'s, M: Message, N: Name, H: Handle<M, N>> MasterHandle<M, N, H> {
    pub async fn execute_on_all<'a, O>(
        &'s self,
        f: impl Fn(&'s H) -> Pin<Box<dyn Future<Output = O> + Send + 'a>> + 'a,
    ) -> Vec<O> {
        use futures::stream::FuturesOrdered;
        use futures::StreamExt;

        let mut futures = FuturesOrdered::new();
        for future in self.slaves.iter().map(f) {
            futures.push(future)
        }

        futures.collect().await
    }
}

#[cfg(test)]
mod tests {
    use futures::FutureExt;
    use tokio::sync::oneshot;

    #[derive(Debug, Clone, PartialEq, PartialOrd)]
    enum Name {
        MyActorA,
        MyActorB,
    }

    impl AsRef<str> for Name {
        fn as_ref(&self) -> &str {
            match self {
                Name::MyActorA => "my-actor-a",
                Name::MyActorB => "my-actor-b",
            }
        }
    }

    impl std::fmt::Display for Name {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            let s: &str = self.as_ref();
            f.write_str(s)
        }
    }

    impl crate::Name for Name {}

    #[derive(Debug)]
    enum Message {
        Increment,
        Get { respond_to: oneshot::Sender<usize> },
    }

    impl crate::Message for Message {}

    struct MyActor {
        receiver: crate::Receiver<Message, Name>,
        counter: usize,
    }

    impl MyActor {
        async fn run(&mut self) {
            while let Some(message) = self.receiver.recv().await {
                match message {
                    Message::Increment => self.counter += 1,
                    Message::Get { respond_to } => respond_to.send(self.counter).unwrap(),
                }
            }
        }
    }

    #[derive(Debug, Clone)]
    struct MyActorHandle {
        sender: crate::Sender<Message, Name>,
    }

    impl crate::Handle<Message, Name> for MyActorHandle {
        fn sender(&self) -> &crate::Sender<Message, Name> {
            &self.sender
        }
    }

    impl MyActorHandle {
        pub fn new(name: Name) -> Self {
            let (sender, receiver) = crate::channel(8, name);
            let mut actor = MyActor {
                receiver,
                counter: 0,
            };
            tokio::spawn(async move { actor.run().await });
            Self { sender }
        }

        pub async fn increment(&self) {
            self.sender.notify(|| Message::Increment).await
        }

        pub async fn get(&self) -> usize {
            self.sender
                .call(|respond_to| Message::Get { respond_to })
                .await
        }
    }


    #[tokio::test]
    async fn simple() {
        let handle = MyActorHandle::new(Name::MyActorA);
        for _ in 0..100 {
            handle.increment().await;
        }
        assert_eq!(handle.get().await, 100);
    }

    #[tokio::test]
    async fn test_master_and_slave() {
        let handle_a = MyActorHandle::new(Name::MyActorA);
        let handle_b = MyActorHandle::new(Name::MyActorB);
        let master = crate::MasterHandle::new(vec![handle_a.clone(), handle_b.clone()]);
        let get_values = || async {
            let results = master.execute_on_all(|handle| handle.get().boxed()).await;
            assert_eq!(results.len(), 2);
            (results[0], results[1])
        };
        for _ in 0..100 {
            master
                .execute_on_all(|handle| handle.increment().boxed())
                .await;
        }
        assert_eq!(get_values().await, (100, 100));
        {
            let actor_a = master.get(Name::MyActorA).unwrap();
            for _ in 0..10 {
                actor_a.increment().await;
            }
        }
        assert_eq!(get_values().await, (110, 100));

    }
}