serenade_messenger/
transport.rs1use std::any::Any;
4use std::collections::VecDeque;
5use std::future::Future;
6use std::pin::Pin;
7use std::sync::{Arc, Mutex};
8
9use crate::{Message, MessengerError};
10
11#[derive(Clone)]
13pub struct Envelope {
14 message_name: &'static str,
15 body: Arc<dyn Any + Send + Sync>,
16}
17
18impl Envelope {
19 #[must_use]
21 pub fn new<M: Message>(message: M) -> Self {
22 Self {
23 message_name: M::NAME,
24 body: Arc::new(message),
25 }
26 }
27
28 #[must_use]
30 pub const fn message_name(&self) -> &'static str {
31 self.message_name
32 }
33
34 #[must_use]
36 pub fn downcast_ref<T: 'static>(&self) -> Option<&T> {
37 self.body.downcast_ref::<T>()
38 }
39}
40
41impl std::fmt::Debug for Envelope {
42 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43 formatter
44 .debug_struct("Envelope")
45 .field("message_name", &self.message_name)
46 .finish_non_exhaustive()
47 }
48}
49
50pub trait Transport: Send + Sync {
54 fn send(
56 &self,
57 envelope: Envelope,
58 ) -> Pin<Box<dyn Future<Output = Result<(), MessengerError>> + Send + '_>>;
59}
60
61#[derive(Clone, Default)]
63pub struct InMemoryTransport {
64 queue: Arc<Mutex<VecDeque<Envelope>>>,
65}
66
67impl InMemoryTransport {
68 #[must_use]
70 pub fn new() -> Self {
71 Self::default()
72 }
73
74 #[must_use]
80 pub fn len(&self) -> usize {
81 self.queue.lock().expect("in-memory transport lock").len()
82 }
83
84 #[must_use]
90 pub fn is_empty(&self) -> bool {
91 self.len() == 0
92 }
93
94 #[must_use]
100 pub fn pop(&self) -> Option<Envelope> {
101 self.queue
102 .lock()
103 .expect("in-memory transport lock")
104 .pop_front()
105 }
106}
107
108impl Transport for InMemoryTransport {
109 fn send(
115 &self,
116 envelope: Envelope,
117 ) -> Pin<Box<dyn Future<Output = Result<(), MessengerError>> + Send + '_>> {
118 let queue = Arc::clone(&self.queue);
119 Box::pin(async move {
120 queue
121 .lock()
122 .expect("in-memory transport lock")
123 .push_back(envelope);
124 Ok(())
125 })
126 }
127}
128
129#[cfg(test)]
130mod tests {
131 use std::sync::Arc;
132
133 use super::{Envelope, InMemoryTransport, Transport};
134 use crate::{Command, Message, MessengerError};
135
136 #[derive(Debug)]
137 struct DemoCommand {
138 id: u32,
139 }
140
141 impl Message for DemoCommand {
142 const NAME: &'static str = "demo.command";
143 }
144
145 impl Command for DemoCommand {}
146
147 struct FailingTransport;
148
149 impl Transport for FailingTransport {
150 fn send(
151 &self,
152 _envelope: Envelope,
153 ) -> std::pin::Pin<
154 Box<dyn std::future::Future<Output = Result<(), MessengerError>> + Send + '_>,
155 > {
156 Box::pin(async {
157 Err(MessengerError::Transport {
158 message: "backend down".to_owned(),
159 })
160 })
161 }
162 }
163
164 #[tokio::test]
165 async fn in_memory_transport_queues_fifo() {
166 let transport = InMemoryTransport::new();
167 assert!(transport.is_empty());
168 transport
169 .send(Envelope::new(DemoCommand { id: 1 }))
170 .await
171 .expect("send 1");
172 transport
173 .send(Envelope::new(DemoCommand { id: 2 }))
174 .await
175 .expect("send 2");
176 assert_eq!(transport.len(), 2);
177 let first = transport.pop().expect("first");
178 assert_eq!(first.message_name(), "demo.command");
179 assert_eq!(first.downcast_ref::<DemoCommand>().expect("type").id, 1);
180 assert!(first.downcast_ref::<u32>().is_none());
181 let second = transport.pop().expect("second");
182 assert_eq!(second.downcast_ref::<DemoCommand>().expect("type").id, 2);
183 assert!(transport.pop().is_none());
184 assert!(transport.is_empty());
185 }
186
187 #[tokio::test]
188 async fn dyn_transport_send_works() {
189 let memory = InMemoryTransport::new();
190 let transport: Arc<dyn Transport> = Arc::new(memory.clone());
191 transport
192 .send(Envelope::new(DemoCommand { id: 9 }))
193 .await
194 .expect("send");
195 assert_eq!(memory.len(), 1);
196 assert_eq!(
197 memory
198 .pop()
199 .expect("queued")
200 .downcast_ref::<DemoCommand>()
201 .expect("type")
202 .id,
203 9
204 );
205 }
206
207 #[tokio::test]
208 async fn failing_transport_returns_transport_error() {
209 let transport = FailingTransport;
210 let err = transport
211 .send(Envelope::new(DemoCommand { id: 1 }))
212 .await
213 .expect_err("fail");
214 assert_eq!(
215 err,
216 MessengerError::Transport {
217 message: "backend down".to_owned(),
218 }
219 );
220 }
221
222 #[test]
223 fn envelope_debug_includes_message_name() {
224 let envelope = Envelope::new(DemoCommand { id: 3 });
225 let debug = format!("{envelope:?}");
226 assert!(debug.contains("demo.command"));
227 }
228}