sids 1.0.3

An actor-model concurrency framework providing abstraction over async and blocking actors.
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
443
444
445
446
447
448
449
450
451
452
453
454
455
use super::messages::Message;
use log::info;
use tokio::sync::{broadcast, mpsc};

/// The main actor trait that all actors must implement.
#[trait_variant::make(Send)]
pub trait Actor<MType, Response> {
    async fn receive(&mut self, message: Message<MType, Response>)
    where
        Self: Sized + 'static;
}

/// Helper function for running an actor.
pub(super) async fn run_an_actor<MType, Response, T: Actor<MType, Response> + 'static>(
    mut actor: ActorImpl<T, MType, Response>,
) {
    if let Some(mut shutdown_rx) = actor.shutdown_rx.take() {
        // Actor has shutdown signal
        loop {
            tokio::select! {
                Some(message) = actor.receiver.recv() => {
                    if message.stop {
                        info!(actor=actor.name.clone().unwrap_or("Unnamed Actor".to_string()).as_str(); "Actor {} received stop message", actor.name.clone().unwrap_or("Unnamed Actor".to_string()));
                        break;
                    }
                    actor.receive(message).await;
                }
                _ = shutdown_rx.recv() => {
                    info!(actor=actor.name.clone().unwrap_or("Unnamed Actor".to_string()).as_str(); "Actor {} received shutdown signal", actor.name.clone().unwrap_or("Unnamed Actor".to_string()));
                    break;
                }
            }
        }
    } else {
        // No shutdown signal, use original loop
        while let Some(message) = actor.receiver.recv().await {
            if message.stop {
                info!(actor=actor.name.clone().unwrap_or("Unnamed Actor".to_string()).as_str(); "Actor {} received stop message", actor.name.clone().unwrap_or("Unnamed Actor".to_string()));
                break;
            }
            actor.receive(message).await;
        }
    }
}

/// Helper function for running a blocking actor.
pub(super) async fn run_a_blocking_actor<MType, Response, T: Actor<MType, Response> + 'static>(
    mut actor: BlockingActorImpl<T, MType, Response>,
) {
    if let Some(shutdown_rx) = actor.shutdown_rx.take() {
        // Actor has shutdown signal
        loop {
            // For blocking actors, we need to check for messages in the blocking receiver
            // Since we can't use tokio::select! with std::sync::mpsc directly, we'll check both conditions
            match actor
                .receiver
                .recv_timeout(std::time::Duration::from_millis(100))
            {
                Ok(message) => {
                    if message.stop {
                        break;
                    }
                    actor.receive(message).await;
                }
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                    break;
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                    // Check if shutdown signal was sent
                    if shutdown_rx.is_closed() {
                        info!(actor=actor.name.clone().unwrap_or("Unnamed Blocking Actor".to_string()).as_str(); "Blocking actor {} received shutdown signal", actor.name.clone().unwrap_or("Unnamed Blocking Actor".to_string()));
                        break;
                    }
                }
            }
        }
    } else {
        // No shutdown signal, use original loop
        while let Ok(message) = actor.receiver.recv() {
            if message.stop {
                info!(actor=actor.name.clone().unwrap_or("Unnamed Blocking Actor".to_string()).as_str(); "Blocking actor {} received stop message", actor.name.clone().unwrap_or("Unnamed Blocking Actor".to_string()));
                break;
            }
            actor.receive(message).await;
        }
    }
}

/// Implements an actor with an Actor type T, and a ResponseMessage type Response.
///
/// A default ResponseMessage is available in actors::messages::ResponseMessage with basic functionality.
pub struct ActorImpl<T, MType, Response> {
    name: Option<String>,
    actor: T,
    receiver: mpsc::Receiver<Message<MType, Response>>,
    shutdown_rx: Option<broadcast::Receiver<()>>,
}

impl<MType, Response, T: Actor<MType, Response> + 'static> ActorImpl<T, MType, Response> {
    pub async fn receive(&mut self, message: Message<MType, Response>) {
        info!(actor=self.name.clone().unwrap_or("Unnamed Actor".to_string()).as_str(); "Actor {} received message", self.name.clone().unwrap_or("Unnamed Actor".to_string()));
        T::receive(&mut self.actor, message).await;
    }
    pub fn new(
        name: Option<String>,
        actor: T,
        receiver: mpsc::Receiver<Message<MType, Response>>,
        shutdown_rx: Option<broadcast::Receiver<()>>,
    ) -> Self {
        ActorImpl {
            name,
            actor,
            receiver,
            shutdown_rx,
        }
    }
}

/// Implementation of a blocking actor, which runs in a separate thread and uses std::sync::mpsc for communication.
///
/// A classic example of a blocking actor is one that will get data from http or other source.
pub struct BlockingActorImpl<T, MType, Response> {
    name: Option<String>,
    actor: T,
    receiver: std::sync::mpsc::Receiver<Message<MType, Response>>,
    shutdown_rx: Option<broadcast::Receiver<()>>,
}

impl<MType, Response, T: Actor<MType, Response> + 'static> BlockingActorImpl<T, MType, Response> {
    pub async fn receive(&mut self, message: Message<MType, Response>) {
        info!(actor=self.name.clone().unwrap_or("Unnamed Blocking Actor".to_string()).as_str(); "Blocking actor {} received message", self.name.clone().unwrap_or("Unnamed Blocking Actor".to_string()));
        T::receive(&mut self.actor, message).await;
    }

    pub fn new(
        name: Option<String>,
        actor: T,
        receiver: std::sync::mpsc::Receiver<Message<MType, Response>>,
        shutdown_rx: Option<broadcast::Receiver<()>>,
    ) -> BlockingActorImpl<T, MType, Response> {
        BlockingActorImpl {
            name,
            actor,
            receiver,
            shutdown_rx,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::actors::messages::ResponseMessage;
    use std::sync::{Arc, Mutex};
    use tokio::sync::mpsc;

    struct TestPayload {
        _value: String,
    }

    struct CounterPayload {
        increment: i32,
    }
    struct EchoActor;

    impl Actor<TestPayload, ResponseMessage> for EchoActor {
        async fn receive(&mut self, message: Message<TestPayload, ResponseMessage>) {
            if let Some(_payload) = message.payload {
                if let Some(responder) = message.responder {
                    responder.handle(ResponseMessage::Success).await;
                }
            }
        }
    }

    /// An actor that counts the messages it receives.
    struct CounterActor {
        count: Arc<Mutex<i32>>,
    }

    impl Actor<CounterPayload, ResponseMessage> for CounterActor {
        async fn receive(&mut self, message: Message<CounterPayload, ResponseMessage>) {
            if let Some(payload) = message.payload {
                let mut count = self.count.lock().unwrap();
                *count += payload.increment;
            }
        }
    }

    /// An actor that responds to blocking messages by sending a success response.
    struct BlockingEchoActor;

    impl Actor<TestPayload, ResponseMessage> for BlockingEchoActor {
        async fn receive(&mut self, message: Message<TestPayload, ResponseMessage>) {
            if let Some(blocking) = message.blocking {
                let _ = blocking.send(ResponseMessage::Success);
            }
        }
    }

    #[tokio::test]
    async fn test_actor_impl_creation() {
        let (_tx, rx) = mpsc::channel::<Message<TestPayload, ResponseMessage>>(1);
        let actor = EchoActor;
        let actor_impl = ActorImpl::new(Some("TestActor".to_string()), actor, rx, None);

        assert!(actor_impl.name.is_some());
        assert_eq!(actor_impl.name.unwrap(), "TestActor");
    }

    #[tokio::test]
    async fn test_actor_impl_creation_without_name() {
        let (_tx, rx) = mpsc::channel::<Message<TestPayload, ResponseMessage>>(1);
        let actor = EchoActor;
        let actor_impl = ActorImpl::new(None, actor, rx, None);

        assert!(actor_impl.name.is_none());
    }

    #[tokio::test]
    async fn test_actor_impl_receive() {
        let (_tx, rx) = mpsc::channel::<Message<TestPayload, ResponseMessage>>(1);
        let actor = EchoActor;
        let mut actor_impl = ActorImpl::new(Some("EchoActor".to_string()), actor, rx, None);

        let (responder_tx, responder_rx) = tokio::sync::oneshot::channel();
        let handler = super::super::response_handler::from_oneshot(responder_tx);
        let payload = TestPayload {
            _value: "test".to_string(),
        };
        let message = Message {
            payload: Some(payload),
            stop: false,
            responder: Some(handler),
            blocking: None,
        };

        actor_impl.receive(message).await;

        let response = responder_rx.await.expect("Failed to receive response");
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_counter_actor() {
        let count = Arc::new(Mutex::new(0));
        let count_clone = count.clone();

        let (_tx, rx) = mpsc::channel::<Message<CounterPayload, ResponseMessage>>(10);
        let actor = CounterActor { count: count_clone };
        let mut actor_impl = ActorImpl::new(Some("CounterActor".to_string()), actor, rx, None);

        // Send multiple messages
        for i in 1..=5 {
            let payload = CounterPayload { increment: i };
            let message = Message {
                payload: Some(payload),
                stop: false,
                responder: None,
                blocking: None,
            };
            actor_impl.receive(message).await;
        }

        let final_count = *count.lock().unwrap();
        assert_eq!(final_count, 15); // 1+2+3+4+5 = 15
    }

    #[tokio::test]
    async fn test_run_an_actor_with_stop() {
        let (tx, rx) = mpsc::channel::<Message<CounterPayload, ResponseMessage>>(10);
        let count = Arc::new(Mutex::new(0));
        let count_clone = count.clone();

        let actor = CounterActor { count: count_clone };
        let actor_impl = ActorImpl::new(Some("CounterActor".to_string()), actor, rx, None);

        // Spawn the actor in a background task
        let actor_task = tokio::spawn(async move {
            run_an_actor(actor_impl).await;
        });

        // Send a regular message
        let payload = CounterPayload { increment: 5 };
        let message = Message {
            payload: Some(payload),
            stop: false,
            responder: None,
            blocking: None,
        };
        tx.send(message).await.unwrap();

        // Give time for message to be processed
        tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;

        // Verify the message was processed
        assert_eq!(*count.lock().unwrap(), 5);

        // Send a stop message
        let stop_message = Message {
            payload: None,
            stop: true,
            responder: None,
            blocking: None,
        };
        tx.send(stop_message).await.unwrap();

        // Wait for actor to finish
        let result =
            tokio::time::timeout(tokio::time::Duration::from_millis(100), actor_task).await;

        // The actor should have stopped cleanly
        assert!(result.is_ok(), "Actor should have stopped");
    }

    #[test]
    fn test_blocking_actor_impl_creation() {
        let (_tx, rx) = std::sync::mpsc::channel::<Message<TestPayload, ResponseMessage>>();
        let actor = BlockingEchoActor;
        let actor_impl = BlockingActorImpl::new(Some("BlockingTest".to_string()), actor, rx, None);

        assert!(actor_impl.name.is_some());
        assert_eq!(actor_impl.name.unwrap(), "BlockingTest");
    }

    #[test]
    fn test_blocking_actor_impl_creation_without_name() {
        let (_tx, rx) = std::sync::mpsc::channel::<Message<TestPayload, ResponseMessage>>();
        let actor = BlockingEchoActor;
        let actor_impl = BlockingActorImpl::new(None, actor, rx, None);

        assert!(actor_impl.name.is_none());
    }

    #[tokio::test]
    async fn test_blocking_actor_receive() {
        let (_tx, rx) = std::sync::mpsc::channel::<Message<TestPayload, ResponseMessage>>();
        let actor = BlockingEchoActor;
        let mut actor_impl =
            BlockingActorImpl::new(Some("BlockingEcho".to_string()), actor, rx, None);

        let (blocking_tx, blocking_rx) = std::sync::mpsc::sync_channel(1);
        let payload = TestPayload {
            _value: "test".to_string(),
        };
        let message = Message {
            payload: Some(payload),
            stop: false,
            responder: None,
            blocking: Some(blocking_tx),
        };

        actor_impl.receive(message).await;

        let response = blocking_rx.recv().expect("Failed to receive response");
        assert_eq!(response, ResponseMessage::Success);
    }

    #[tokio::test]
    async fn test_run_an_actor_multiple_messages() {
        let (tx, rx) = mpsc::channel::<Message<CounterPayload, ResponseMessage>>(10);
        let count = Arc::new(Mutex::new(0));
        let count_clone = count.clone();

        let actor = CounterActor { count: count_clone };
        let actor_impl = ActorImpl::new(Some("CounterActor".to_string()), actor, rx, None);

        // Spawn the actor
        let actor_task = tokio::spawn(async move {
            run_an_actor(actor_impl).await;
        });

        // Send multiple messages
        for i in 1..=10 {
            let payload = CounterPayload { increment: i };
            let message = Message {
                payload: Some(payload),
                stop: false,
                responder: None,
                blocking: None,
            };
            tx.send(message).await.unwrap();
        }

        // Give time for messages to be processed
        tokio::time::sleep(tokio::time::Duration::from_millis(50)).await;

        // Send stop message
        let stop_message = Message {
            payload: None,
            stop: true,
            responder: None,
            blocking: None,
        };
        tx.send(stop_message).await.unwrap();

        actor_task.await.unwrap();

        let final_count = *count.lock().unwrap();
        assert_eq!(final_count, 55); // Sum of 1 to 10
    }

    #[tokio::test]
    async fn test_actor_stops_on_stop_message() {
        let (tx, rx) = mpsc::channel::<Message<TestPayload, ResponseMessage>>(10);
        let actor = EchoActor;
        let actor_impl = ActorImpl::new(Some("EchoActor".to_string()), actor, rx, None);

        let actor_task = tokio::spawn(async move {
            run_an_actor(actor_impl).await;
        });

        // Send stop message immediately
        let stop_message = Message {
            payload: None,
            stop: true,
            responder: None,
            blocking: None,
        };
        tx.send(stop_message).await.unwrap();

        // Actor should complete quickly
        let result =
            tokio::time::timeout(tokio::time::Duration::from_millis(100), actor_task).await;

        assert!(result.is_ok(), "Actor should have stopped");
    }

    #[test]
    fn test_blocking_actor_stops_on_stop_message() {
        let (tx, rx) = std::sync::mpsc::channel::<Message<TestPayload, ResponseMessage>>();
        let actor = BlockingEchoActor;
        let actor_impl = BlockingActorImpl::new(Some("BlockingEcho".to_string()), actor, rx, None);

        // Spawn blocking actor in a thread
        let handle = std::thread::spawn(move || {
            let runtime = tokio::runtime::Runtime::new().unwrap();
            runtime.block_on(async {
                run_a_blocking_actor(actor_impl).await;
            });
        });

        // Send stop message
        let stop_message = Message {
            payload: None,
            stop: true,
            responder: None,
            blocking: None,
        };
        tx.send(stop_message).unwrap();

        // Wait for thread to complete
        handle.join().unwrap();
    }
}