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
use crate::{relay::RelayMessage, Context};
use ockam_core::{Address, Message};
use std::fmt::{self, Debug, Display, Formatter};
use tokio::sync::mpsc::{Receiver, Sender};

/// A mailbox for encoded messages
///
/// Message type information can't be exposed at this stage because
/// they need to either be typed in the [`Relay`](crate::Relay) or in
/// the worker's [`Context`](crate::Context).
#[derive(Debug)]
pub struct Mailbox {
    rx: Receiver<RelayMessage>,
    tx: Sender<RelayMessage>,
}

impl Mailbox {
    pub fn new(rx: Receiver<RelayMessage>, tx: Sender<RelayMessage>) -> Self {
        Self { rx, tx }
    }

    pub fn sender(&self) -> Sender<RelayMessage> {
        self.tx.clone()
    }

    /// Get the next message from the mailbox
    pub async fn next(&mut self) -> Option<RelayMessage> {
        self.rx.recv().await
    }

    /// If a message wasn't expected, requeue it
    pub async fn requeue(&self, msg: RelayMessage) {
        self.tx.send(msg).await.unwrap();
    }
}

/// A message wraper type that allows users to cancel message receival
///
/// A worker can block in place to wait for a message.  If the next
/// message is not the desired type, it can be cancelled which
/// re-queues it into the mailbox.
pub struct Cancel<'ctx, M: Message> {
    inner: M,
    addr: Address,
    ctx: &'ctx Context,
}

impl<'ctx, M: Message> Cancel<'ctx, M> {
    pub(crate) fn new(inner: M, addr: Address, ctx: &'ctx Context) -> Self {
        Self { inner, addr, ctx }
    }

    /// Cancel this message
    pub async fn cancel(self) {
        let ctx = self.ctx;
        let enc = self.inner.encode().unwrap();
        ctx.mailbox.requeue(RelayMessage::new(self.addr, enc)).await;
    }
}

impl<'ctx, M: Message> std::ops::Deref for Cancel<'ctx, M> {
    type Target = M;

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

impl<'ctx, M: Message + PartialEq> PartialEq<M> for Cancel<'ctx, M> {
    fn eq(&self, o: &M) -> bool {
        &self.inner == o
    }
}

impl<'ctx, M: Message + Debug> Debug for Cancel<'ctx, M> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl<'ctx, M: Message + Display> Display for Cancel<'ctx, M> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        self.inner.fmt(f)
    }
}