xtra 0.6.0

A tiny actor framework
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
use std::future::Future;
use std::mem;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};

use futures_core::FusedFuture;
use futures_util::FutureExt;

use crate::chan::{MailboxFull, MessageToAll, MessageToOne, RefCounter, WaitingSender};
use crate::envelope::{BroadcastEnvelopeConcrete, ReturningEnvelope};
use crate::{chan, Error, Handler};

/// A [`Future`] that represents the state of sending a message to an actor.
///
/// By default, a [`SendFuture`] will resolve to the return value of the handler (see [`Handler::Return`](crate::Handler::Return)).
/// This behaviour can be changed by calling [`detach`](SendFuture::detach).
///
/// A detached [`SendFuture`] will resolve once the message is successfully queued into the actor's mailbox and resolve to the [`Receiver`].
/// The [`Receiver`] itself is a future that will resolve to the return value of the [`Handler`](crate::Handler).
///
/// In other words, detaching a [`SendFuture`] allows the current task to continue while the corresponding [`Handler`] of the actor processes the message.
///
/// In case an actor's mailbox is bounded, [`SendFuture`] will yield `Pending` until the message is queued successfully.
/// This allows an actor to exercise backpressure on its users.
#[must_use = "Futures do nothing unless polled"]
pub struct SendFuture<F, S> {
    sending: F,
    state: S,
}

/// State-type for [`SendFuture`] to declare that it should resolve to the return value of the [`Handler`](crate::Handler).
pub struct ResolveToHandlerReturn<R>(Receiver<R>);

/// State-type for [`SendFuture`] to declare that it should resolve to a [`Receiver`] once the message is queued into the actor's mailbox.
///
/// The [`Receiver`] can be used to await the completion of the handler separately.
pub struct ResolveToReceiver<R>(Option<Receiver<R>>);

/// State-type for [`SendFuture`] to declare that it is a broadcast.
pub struct Broadcast(());

impl<F, R> SendFuture<F, ResolveToHandlerReturn<R>>
where
    F: Future,
{
    /// Detaches this future from receiving the response of the handler.
    ///
    /// Awaiting a detached [`SendFuture`] will queue the message in the actor's mailbox and return you _another_ [`Future`] for receiving the response.
    pub fn detach(self) -> SendFuture<F, ResolveToReceiver<R>> {
        SendFuture {
            sending: self.sending,
            state: self.state.resolve_to_receiver(),
        }
    }
}

impl<F, S> SendFuture<F, S>
where
    F: private::SetPriority,
{
    /// Set the priority of a given message. See [`Address`](crate::Address) documentation for more info.
    ///
    /// Panics if this future has already been polled.
    pub fn priority(mut self, new_priority: u32) -> Self {
        self.sending.set_priority(new_priority);

        self
    }
}

/// "Sending" state of [`SendFuture`] for cases where the actor type is named and we sent a single message.
#[must_use = "Futures do nothing unless polled"]
pub struct ActorNamedSending<A, Rc: RefCounter>(Sending<A, MessageToOne<A>, Rc>);

/// "Sending" state of [`SendFuture`] for cases where the actor type is named and we broadcast a message.
#[must_use = "Futures do nothing unless polled"]
pub struct ActorNamedBroadcasting<A, Rc: RefCounter>(Sending<A, MessageToAll<A>, Rc>);

/// "Sending" state of [`SendFuture`] for cases where the actor type is erased.
#[must_use = "Futures do nothing unless polled"]
pub struct ActorErasedSending(Box<dyn private::ErasedSending>);

impl<A, R, Rc> SendFuture<ActorNamedSending<A, Rc>, ResolveToHandlerReturn<R>>
where
    R: Send + 'static,
    Rc: RefCounter,
{
    /// Construct a [`SendFuture`] that contains the actor's name in its type.
    ///
    /// Compared to [`SendFuture::sending_erased`], this function avoids one allocation.
    pub(crate) fn sending_named<M>(message: M, sender: chan::Ptr<A, Rc>) -> Self
    where
        A: Handler<M, Return = R>,
        M: Send + 'static,
    {
        let (envelope, receiver) = ReturningEnvelope::<A, M, R>::new(message, 0);

        Self {
            sending: ActorNamedSending(Sending::New {
                msg: Box::new(envelope) as MessageToOne<A>,
                sender,
            }),
            state: ResolveToHandlerReturn::new(receiver),
        }
    }
}

impl<R> SendFuture<ActorErasedSending, ResolveToHandlerReturn<R>> {
    pub(crate) fn sending_erased<A, M, Rc>(message: M, sender: chan::Ptr<A, Rc>) -> Self
    where
        Rc: RefCounter,
        A: Handler<M, Return = R>,
        M: Send + 'static,
        R: Send + 'static,
    {
        let (envelope, receiver) = ReturningEnvelope::<A, M, R>::new(message, 0);

        Self {
            sending: ActorErasedSending(Box::new(Sending::New {
                msg: Box::new(envelope) as MessageToOne<A>,
                sender,
            })),
            state: ResolveToHandlerReturn::new(receiver),
        }
    }
}

impl<A, Rc> SendFuture<ActorNamedBroadcasting<A, Rc>, Broadcast>
where
    Rc: RefCounter,
{
    pub(crate) fn broadcast_named<M>(msg: M, sender: chan::Ptr<A, Rc>) -> Self
    where
        A: Handler<M, Return = ()>,
        M: Clone + Send + Sync + 'static,
    {
        let envelope = BroadcastEnvelopeConcrete::new(msg, 0);

        Self {
            sending: ActorNamedBroadcasting(Sending::New {
                msg: Arc::new(envelope) as MessageToAll<A>,
                sender,
            }),
            state: Broadcast(()),
        }
    }
}

#[allow(dead_code)] // This will useful later.
impl SendFuture<ActorErasedSending, Broadcast> {
    pub(crate) fn broadcast_erased<A, M, Rc>(msg: M, sender: chan::Ptr<A, Rc>) -> Self
    where
        Rc: RefCounter,
        A: Handler<M, Return = ()>,
        M: Clone + Send + Sync + 'static,
    {
        let envelope = BroadcastEnvelopeConcrete::new(msg, 0);

        Self {
            sending: ActorErasedSending(Box::new(Sending::New {
                msg: Arc::new(envelope) as MessageToAll<A>,
                sender,
            })),
            state: Broadcast(()),
        }
    }
}

/// The core state machine around sending a message to an actor's mailbox.
#[must_use = "Futures do nothing unless polled"]
enum Sending<A, M, Rc: RefCounter> {
    New { msg: M, sender: chan::Ptr<A, Rc> },
    WaitingToSend(WaitingSender<M>),
    Done,
}

impl<A, Rc> Future for Sending<A, MessageToOne<A>, Rc>
where
    Rc: RefCounter,
{
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();

        loop {
            match mem::replace(this, Sending::Done) {
                Sending::New { msg, sender } => match sender.try_send_to_one(msg)? {
                    Ok(()) => return Poll::Ready(Ok(())),
                    Err(MailboxFull(waiting)) => {
                        *this = Sending::WaitingToSend(waiting);
                    }
                },
                Sending::WaitingToSend(mut waiting) => {
                    return match waiting.poll_unpin(cx)? {
                        Poll::Ready(()) => Poll::Ready(Ok(())),
                        Poll::Pending => {
                            *this = Sending::WaitingToSend(waiting);
                            Poll::Pending
                        }
                    };
                }
                Sending::Done => panic!("Polled after completion"),
            }
        }
    }
}

impl<A, Rc> Future for Sending<A, MessageToAll<A>, Rc>
where
    Rc: RefCounter,
{
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let this = self.get_mut();

        loop {
            match mem::replace(this, Sending::Done) {
                Sending::New { msg, sender } => match sender.try_send_to_all(msg)? {
                    Ok(()) => return Poll::Ready(Ok(())),
                    Err(MailboxFull(waiting)) => {
                        *this = Sending::WaitingToSend(waiting);
                    }
                },
                Sending::WaitingToSend(mut waiting) => {
                    return match waiting.poll_unpin(cx)? {
                        Poll::Ready(()) => Poll::Ready(Ok(())),
                        Poll::Pending => {
                            *this = Sending::WaitingToSend(waiting);
                            Poll::Pending
                        }
                    };
                }
                Sending::Done => panic!("Polled after completion"),
            }
        }
    }
}

impl<A, M, Rc> FusedFuture for Sending<A, M, Rc>
where
    Self: Future,
    Rc: RefCounter,
{
    fn is_terminated(&self) -> bool {
        matches!(self, Sending::Done)
    }
}

impl<A, Rc: RefCounter> Future for ActorNamedSending<A, Rc> {
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.poll_unpin(cx)
    }
}

impl<A, Rc> FusedFuture for ActorNamedSending<A, Rc>
where
    Self: Future,
    Rc: RefCounter,
{
    fn is_terminated(&self) -> bool {
        self.0.is_terminated()
    }
}

impl<A, Rc: RefCounter> Future for ActorNamedBroadcasting<A, Rc> {
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.poll_unpin(cx)
    }
}

impl<A, Rc> FusedFuture for ActorNamedBroadcasting<A, Rc>
where
    Self: Future,
    Rc: RefCounter,
{
    fn is_terminated(&self) -> bool {
        self.0.is_terminated()
    }
}

impl Future for ActorErasedSending {
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut().0.poll_unpin(cx)
    }
}

impl FusedFuture for ActorErasedSending {
    fn is_terminated(&self) -> bool {
        self.0.is_terminated()
    }
}

impl<R, F> Future for SendFuture<F, ResolveToReceiver<R>>
where
    F: Future<Output = Result<(), Error>> + FusedFuture + Unpin,
{
    type Output = Result<Receiver<R>, Error>;

    fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
        let this = self.get_mut();

        if !this.sending.is_terminated() {
            futures_util::ready!(this.sending.poll_unpin(ctx))?;
        }

        let receiver = this.state.0.take().expect("polled after completion");

        Poll::Ready(Ok(receiver))
    }
}

impl<R, F> Future for SendFuture<F, ResolveToHandlerReturn<R>>
where
    F: Future<Output = Result<(), Error>> + FusedFuture + Unpin,
{
    type Output = Result<R, Error>;

    fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
        let this = self.get_mut();

        if !this.sending.is_terminated() {
            futures_util::ready!(this.sending.poll_unpin(ctx))?;
        }

        this.state.0.poll_unpin(ctx)
    }
}
impl<F> Future for SendFuture<F, Broadcast>
where
    F: Future<Output = Result<(), Error>> + Unpin,
{
    type Output = Result<(), Error>;

    fn poll(self: Pin<&mut Self>, ctx: &mut Context) -> Poll<Self::Output> {
        self.get_mut().sending.poll_unpin(ctx)
    }
}

/// A [`Future`] that resolves to the [`Return`](crate::Handler::Return) value of a [`Handler`](crate::Handler).
///
/// In case the actor becomes disconnected during the execution of the handler, this future will resolve to [`Error::Interrupted`].
#[must_use = "Futures do nothing unless polled"]
pub struct Receiver<R>(catty::Receiver<R>);

impl<R> Future for Receiver<R> {
    type Output = Result<R, Error>;

    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.get_mut()
            .0
            .poll_unpin(cx)
            .map_err(|_| Error::Interrupted)
    }
}

impl<R> ResolveToHandlerReturn<R> {
    fn new(receiver: catty::Receiver<R>) -> Self {
        Self(Receiver(receiver))
    }

    fn resolve_to_receiver(self) -> ResolveToReceiver<R> {
        ResolveToReceiver(Some(self.0))
    }
}

mod private {
    use super::*;

    pub trait SetPriority {
        fn set_priority(&mut self, priority: u32);
    }

    impl<A, Rc> SetPriority for Sending<A, MessageToOne<A>, Rc>
    where
        Rc: RefCounter,
    {
        fn set_priority(&mut self, new_priority: u32) {
            match self {
                Sending::New { msg, .. } => msg.set_priority(new_priority),
                _ => panic!("Cannot set priority after first poll"),
            }
        }
    }

    impl<A, Rc> SetPriority for Sending<A, MessageToAll<A>, Rc>
    where
        Rc: RefCounter,
    {
        fn set_priority(&mut self, new_priority: u32) {
            match self {
                Sending::New { msg, .. } => Arc::get_mut(msg)
                    .expect("envelope is not cloned until here")
                    .set_priority(new_priority),
                _ => panic!("Cannot set priority after first poll"),
            }
        }
    }

    impl<A, Rc> SetPriority for ActorNamedSending<A, Rc>
    where
        Rc: RefCounter,
    {
        fn set_priority(&mut self, priority: u32) {
            self.0.set_priority(priority)
        }
    }

    impl<A, Rc> SetPriority for ActorNamedBroadcasting<A, Rc>
    where
        Rc: RefCounter,
    {
        fn set_priority(&mut self, priority: u32) {
            self.0.set_priority(priority)
        }
    }

    impl SetPriority for ActorErasedSending {
        fn set_priority(&mut self, priority: u32) {
            self.0.set_priority(priority)
        }
    }

    /// Helper trait because Rust does not allow to `+` non-auto traits in trait objects.
    pub trait ErasedSending:
        Future<Output = Result<(), Error>> + FusedFuture + SetPriority + Send + 'static + Unpin
    {
    }

    impl<F> ErasedSending for F where
        F: Future<Output = Result<(), Error>> + FusedFuture + SetPriority + Send + 'static + Unpin
    {
    }
}