summaryrefslogtreecommitdiffstats
path: root/crates/core/tedge_api/src/address.rs
blob: 93a514506c71f27d535dd516b362d41f9f1aeae9 (plain)
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
use std::{marker::PhantomData, time::Duration};

use tokio::sync::mpsc::error::{SendTimeoutError, TrySendError};

use crate::{
    message::MessageType,
    plugin::{AcceptsReplies, Message},
};

#[doc(hidden)]
pub type AnyMessageBox = Box<dyn Message>;

#[doc(hidden)]
#[derive(Debug)]
pub struct InternalMessage {
    pub(crate) data: AnyMessageBox,
    pub(crate) reply_sender: tokio::sync::oneshot::Sender<AnyMessageBox>,
}

/// THIS IS NOT PART OF THE PUBLIC API, AND MAY CHANGE AT ANY TIME
#[doc(hidden)]
pub type MessageSender = tokio::sync::mpsc::Sender<InternalMessage>;

/// THIS IS NOT PART OF THE PUBLIC API, AND MAY CHANGE AT ANY TIME
#[doc(hidden)]
pub type MessageReceiver = tokio::sync::mpsc::Receiver<InternalMessage>;

/// An address of a plugin that can receive messages a certain type of messages
///
/// An instance of this type represents an address that can be used to send messages of a
/// well-defined type to a specific plugin.
/// The `Address` instance can be used to send messages of several types, but each type has to be
/// in `RB: ReceiverBundle`.
pub struct Address<RB: ReceiverBundle> {
    _pd: PhantomData<fn(RB)>,
    sender: MessageSender,
}

impl<RB: ReceiverBundle> std::fmt::Debug for Address<RB> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct(&format!("Address<{}>", std::any::type_name::<RB>()))
            .finish_non_exhaustive()
    }
}

impl<RB: ReceiverBundle> Clone for Address<RB> {
    fn clone(&self) -> Self {
        Self {
            _pd: PhantomData,
            sender: self.sender.clone(),
        }
    }
}

impl<RB: ReceiverBundle> Address<RB> {
    /// THIS IS NOT PART OF THE PUBLIC API, AND MAY CHANGE AT ANY TIME
    #[doc(hidden)]
    pub fn new(sender: MessageSender) -> Self {
        Self {
            _pd: PhantomData,
            sender,
        }
    }

    /// Send a message `M` to the address represented by the instance of this struct and wait for
    /// them to accept it
    ///
    /// This function can be used to send a message of type `M` to the plugin that is addressed by
    /// the instance of this type.
    ///
    /// # Return
    ///
    /// The function either returns `Ok(())` if sending the message succeeded,
    /// or the message in the error variant of the `Result`: `Err(M)`.
    ///
    /// The error is returned if the receiving side (the plugin that is addressed) does not receive
    /// messages anymore.
    ///
    /// # Details
    ///
    /// This function may block indefinitely if the receiving end does not start correctly. If this
    /// could become an issue use something akin to timeout (like
    /// [`timeout`](tokio::time::timeout)).
    /// For details on sending and receiving, see `tokio::sync::mpsc::Sender`.
    pub async fn send_and_wait<M: Message>(&self, msg: M) -> Result<ReplyReceiverFor<M>, M>
    where
        RB: Contains<M>,
    {
        let (sender, receiver) = tokio::sync::oneshot::channel();

        self.sender
            .send(InternalMessage {
                data: Box::new(msg),
                reply_sender: sender,
            })
            .await
            .map_err(|msg| *msg.0.data.downcast::<M>().unwrap())?;

        Ok(ReplyReceiverFor {
            _pd: PhantomData,
            reply_recv: receiver,
        })
    }

    /// Try sending a message `M` to the plugin behind this address without potentially waiting
    ///
    /// This function should be used when waiting for the plugin to receive the message is not
    /// required.
    ///
    /// # Return
    ///
    /// The function either returns `Ok(())` if sending the message succeeded,
    /// or the message in the error variant of the `Result`: `Err(M)`.
    ///
    /// The error is returned if the receiving side (the plugin that is addressed) cannot currently
    /// receive messages (either because it is closed or the queue is full).
    pub fn try_send<M: Message>(&self, msg: M) -> Result<ReplyReceiverFor<M>, M> {
        let (sender, receiver) = tokio::sync::oneshot::channel();

        self.sender
            .try_send(InternalMessage {
                data: Box::new(msg),
                reply_sender: sender,
            })
            .map_err(|msg| match msg {
                TrySendError::Full(data) | TrySendError::Closed(data) => {
                    *data.data.downcast::<M>().unwrap()
                }
            })?;

        Ok(ReplyReceiverFor {
            _pd: PhantomData,
            reply_recv: receiver,
        })
    }

    /// Send a message `M` to the address represented by the instance of this struct and wait for
    /// them to accept it or timeout
    ///
    /// This method is identical to [`Address::send_and_wait`] except a timeout can be specified after which
    /// trying to send is aborted.
    ///
    /// If you do not wish to wait for a timeout see [`Address::try_send`]
    pub async fn send_with_timeout<M: Message>(
        &self,
        msg: M,
        timeout: Duration,
    ) -> Result<ReplyReceiverFor<M>, M> {
        let (sender, receiver) = tokio::sync::oneshot::channel();

        self.sender
            .send_timeout(
                InternalMessage {
                    data: Box::new(msg),
                    reply_sender: sender,
                },
                timeout,
            )
            .await
            .map_err(|msg| match msg {
                SendTimeoutError::Timeout(data) | SendTimeoutError::Closed(data) => {
                    *data.data.downcast::<M>().unwrap()
                }
            })?;

        Ok(ReplyReceiverFor {
            _pd: PhantomData,
            reply_recv: receiver,
        })
    }
}

#[derive(Debug)]
/// Listener that allows one to wait for a reply as sent through [`Address::send_and_wait`]
pub struct ReplyReceiverFor<M> {
    _pd: PhantomData<fn(M)>,
    reply_recv: tokio::sync::oneshot::Receiver<AnyMessageBox>,
}

impl<M: Message> ReplyReceiverFor<M> {
    /// Wait for a reply until for the duration given in `timeout`
    ///
    /// ## Note
    ///
    /// Plugins could not reply for any number of reasons, hence waiting indefinitely on a reply
    /// can cause problems in long-running applications. As such, one needs to specify how long a
    /// reply should take before another action be taken.
    ///
    /// It is also important, that just because a given `M: Message` has a `M::Reply` type set,
    /// that the plugin that a message was sent to does _not_ have to reply with it. It can choose
    /// to not do so.
    pub async fn wait_for_reply<R>(self, timeout: Duration) -> Result<R, ReplyError>
    where
        R: Message,
        M: AcceptsReplies<Reply = R>,
    {
        let data = tokio::time::timeout(timeout, self.reply_recv)
            .await
            .map_err(|_| ReplyError::Timeout)?
            .map_err(|_| ReplyError::SendSideClosed)?;

        Ok(*data.downcast().expect("Invalid type received"))
    }
}

#[derive(Debug)]
/// Allows the [`Handle`](crate::plugin::Handle) implementation to reply with a given message as
/// specified by the currently handled message.
pub struct ReplySenderFor<M> {
    _pd: PhantomData<fn(M)>,
    reply_sender: tokio::sync::oneshot::Sender<AnyMessageBox>,
}

impl<M: Message> ReplySenderFor<M> {
    pub(crate) fn new(reply_sender: tokio::sync::oneshot::Sender<AnyMessageBox>) -> Self {
        Self {
            _pd: PhantomData,
            reply_sender,
        }
    }

    /// Reply to the originating plugin with the given message
    pub fn reply<R>(self, msg: R) -> Result<(), M>
    where
        R: Message,
        M: AcceptsReplies<Reply = R>,
    {
        self.reply_sender
            .send(Box::new(msg))
            .map_err(|msg| *msg.downcast::<M>().unwrap())
    }

    /// Check whether the ReplySender is closed
    ///
    /// This function returns when the internal communication channel is closed.
    /// This can be used (with e.g. [tokio::select]) to check whether the message sender stopped
    /// waiting for a reply.
    pub async fn closed(&mut self) {
        self.reply_sender.closed().await
    }
}

#[derive(Debug, thiserror::Error)]
/// An error occured while replying
pub enum ReplyError {
    /// The timeout elapsed before the other plugin responded
    #[error("There was no response before timeout")]
    Timeout,
    /// The other plugin dropped its sending side
    ///
    /// This means that there will never be an answer
    #[error("Could not send reply")]
    SendSideClosed,
}

#[doc(hidden)]
pub trait ReceiverBundle: Send + 'static {
    fn get_ids() -> Vec<MessageType>;
}

#[doc(hidden)]
pub trait Contains<M: Message> {}

/// Declare a set of messages to be a [`ReceiverBundle`] which is then used with an [`Address`] to
/// specify which kind of messages a given recipient plugin has to support.
///
/// The list of messages MUST be a subset of the messages the plugin behind `Address` supports.
///
/// ## Example
///
/// ```rust
/// # use tedge_api::{Message, make_receiver_bundle};
///
/// #[derive(Debug)]
/// struct IntMessage(u8);
///
/// impl Message for IntMessage { }
///
/// #[derive(Debug)]
/// struct StatusMessage(String);
///
/// impl Message for StatusMessage { }
///
/// make_receiver_bundle!(struct MessageReceiver(IntMessage, StatusMessage));
///
/// // or if you want to export it