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
//!
//! A envelope wraps messages and signs them to help user identify message senders
//! and instruct Bastion how to send messages back to them

use crate::broadcast::Sender;
use crate::message::{BastionMessage, Message, Msg};
use crate::path::BastionPath;
use crate::system::SYSTEM;
use std::sync::Arc;

#[derive(Debug)]
pub(crate) struct Envelope {
    pub(crate) msg: BastionMessage,
    pub(crate) sign: RefAddr,
}

#[derive(Debug)]
/// A struct containing a message and its sender signature
///
/// # Example
///
/// ```rust
/// # use bastion::prelude::*;
/// #
/// # fn main() {
///     # Bastion::init();
///     #
/// Bastion::children(|children| {
///     children.with_exec(|ctx: BastionContext| {
///         async move {
///             let msg: SignedMessage = ctx.recv().await?;
///
///             Ok(())
///         }
///     })
/// }).expect("Couldn't create the children group.");
///     #
///     # Bastion::start();
///     # Bastion::stop();
///     # Bastion::block_until_stopped();
/// # }
/// ```
pub struct SignedMessage {
    pub(crate) msg: Msg,
    pub(crate) sign: RefAddr,
}

impl SignedMessage {
    pub(crate) fn new(msg: Msg, sign: RefAddr) -> Self {
        SignedMessage { msg, sign }
    }

    #[doc(hidden)]
    pub fn extract(self) -> (Msg, RefAddr) {
        (self.msg, self.sign)
    }

    /// Returns a message signature to identify the message sender
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # fn main() {
    ///     # Bastion::init();
    ///     #
    /// Bastion::children(|children| {
    ///     children.with_exec(|ctx: BastionContext| {
    ///         async move {
    ///             let msg: SignedMessage = ctx.recv().await?;
    ///             println!("received message from {:?}", msg.signature().path());
    ///             Ok(())
    ///         }
    ///     })
    /// }).expect("Couldn't create the children group.");
    ///     #
    ///     # Bastion::start();
    ///     # Bastion::stop();
    ///     # Bastion::block_until_stopped();
    /// # }
    /// ```
    pub fn signature(&self) -> &RefAddr {
        &self.sign
    }
}

#[derive(Debug, Clone)]
/// Message signature used to identify message sender and send messages to it.
///
/// # Example
///
/// ```rust
/// # use bastion::prelude::*;
/// #
/// # fn main() {
///     # Bastion::init();
///     #
/// Bastion::children(|children| {
///     children.with_exec(|ctx: BastionContext| {
///         async move {
///             // Wait for a message to be received...
///             let msg: SignedMessage = ctx.recv().await?;
///             
///             ctx.tell(msg.signature(), "reply").expect("Unable to reply");
///             Ok(())
///         }
///     })
/// }).expect("Couldn't create the children group.");
///     #
///     # Bastion::start();
///     # Bastion::stop();
///     # Bastion::block_until_stopped();
/// # }
/// ```
pub struct RefAddr {
    path: Arc<BastionPath>,
    sender: Sender,
}

impl RefAddr {
    pub(crate) fn new(path: Arc<BastionPath>, sender: Sender) -> Self {
        RefAddr { path, sender }
    }

    pub(crate) fn dead_letters() -> Self {
        Self::new(
            SYSTEM.dead_letters().path().clone(),
            SYSTEM.dead_letters().sender().clone(),
        )
    }

    /// Checks whether the sender is identified.
    /// Usually anonymous sender means messages sent by
    /// [broadcast][crate::Bastion::broadcast()] and it's other methods implied to
    /// be called outside of the Bastion context.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # fn main() {
    ///     # Bastion::init();
    ///     #
    ///     # let children_ref = Bastion::children(|children| children).unwrap();
    /// let msg = "A message containing data.";
    /// children_ref.broadcast(msg).expect("Couldn't send the message.");
    ///
    ///     # Bastion::children(|children| {
    ///         # children.with_exec(|ctx: BastionContext| {
    ///             # async move {
    /// msg! { ctx.recv().await?,
    ///     ref msg: &'static str => {
    ///         assert!(signature!().is_sender_identified());
    ///     };
    ///     // We are only sending a `&'static str` in this
    ///     // example, so we know that this won't happen...
    ///     _: _ => ();
    /// }
    ///                 #
    ///                 # Ok(())
    ///             # }
    ///         # })
    ///     # }).unwrap();
    ///     #
    ///     # Bastion::start();
    ///     # Bastion::stop();
    ///     # Bastion::block_until_stopped();
    /// # }
    /// ```
    pub fn is_sender_identified(&self) -> bool {
        self.path.is_dead_letters()
    }

    /// Returns `BastionPath` of a sender
    ///
    /// # Example
    ///
    /// ```rust
    /// # use bastion::prelude::*;
    /// #
    /// # fn main() {
    ///     # Bastion::init();
    ///     #
    ///     # let children_ref = Bastion::children(|children| children).unwrap();
    /// let msg = "A message containing data.";
    /// children_ref.broadcast(msg).expect("Couldn't send the message.");
    ///
    ///     # Bastion::children(|children| {
    ///         # children.with_exec(|ctx: BastionContext| {
    ///             # async move {
    /// msg! { ctx.recv().await?,
    ///     ref msg: &'static str => {
    ///         let path = signature!().path();
    ///         assert!(path.is_dead_letters());
    ///     };
    ///     // We are only sending a `&'static str` in this
    ///     // example, so we know that this won't happen...
    ///     _: _ => ();
    /// }
    ///                 #
    ///                 # Ok(())
    ///             # }
    ///         # })
    ///     # }).unwrap();
    ///     #
    ///     # Bastion::start();
    ///     # Bastion::stop();
    ///     # Bastion::block_until_stopped();
    /// # }
    /// ```
    pub fn path(&self) -> &Arc<BastionPath> {
        &self.path
    }

    pub(crate) fn sender(&self) -> &Sender {
        &self.sender
    }
}

impl Envelope {
    pub(crate) fn new(msg: BastionMessage, path: Arc<BastionPath>, sender: Sender) -> Self {
        Envelope {
            msg,
            sign: RefAddr::new(path, sender),
        }
    }

    pub(crate) fn new_with_sign(msg: BastionMessage, sign: RefAddr) -> Self {
        Envelope { msg, sign }
    }

    pub(crate) fn from_dead_letters(msg: BastionMessage) -> Self {
        Envelope {
            msg,
            sign: RefAddr::dead_letters(),
        }
    }

    pub(crate) fn try_clone(&self) -> Option<Self> {
        self.msg.try_clone().map(|msg| Envelope {
            msg,
            sign: self.sign.clone(),
        })
    }

    pub(crate) fn into_msg<M: Message>(self) -> Option<M> {
        self.msg.into_msg()
    }
}