rsactor 0.14.1

A Simple and Efficient In-Process Actor Model Implementation for Rust.
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// filepath: /Volumes/Workspace/rust/rsactor/tests/generic_tests.rs
// filepath: /Volumes/Workspace/rust/rsactor/tests/generic_tests.rs

use anyhow::Result;
use rsactor::{spawn, Actor, ActorRef, ActorResult, Message};
use std::fmt::Debug;

// ---- Generic Actor Definition ----
// T must have all bounds required by any message handler and the Actor trait itself.
#[derive(Debug)]
struct GenericActor<T: Send + Debug + Clone + 'static> {
    data: Option<T>,
}

// ---- Actor Trait Implementation ----
impl<T: Send + Debug + Clone + 'static> Actor for GenericActor<T> {
    type Args = Option<T>; // Initial value for data
    type Error = anyhow::Error;

    async fn on_start(args: Self::Args, _actor_ref: &ActorRef<Self>) -> Result<Self, Self::Error> {
        Ok(GenericActor { data: args })
    }
}

// ---- Test Data Struct Definition (moved before impl_message_handler) ----
#[derive(Debug, Clone, PartialEq)]
struct MyTestData {
    id: i32,
    name: String,
}

impl MyTestData {
    fn new(id: i32, name: &str) -> Self {
        Self {
            id,
            name: name.to_string(),
        }
    }
}

// ---- Message Definitions ----
#[derive(Debug)]
pub struct SetValue<T: Send + Debug + 'static>(pub T);

#[derive(Debug, Clone, Copy)]
pub struct GetValue;

#[derive(Debug, Clone, Copy)]
pub struct ClearValue;

// ---- Message Trait Implementations ----

// Handle SetValue<T>
impl<T: Send + Debug + Clone + 'static> Message<SetValue<T>> for GenericActor<T> {
    type Reply = ();

    async fn handle(&mut self, msg: SetValue<T>, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data = Some(msg.0);
    }
}

// Handle GetValue
impl<T: Send + Debug + Clone + 'static> Message<GetValue> for GenericActor<T> {
    type Reply = Option<T>;

    async fn handle(&mut self, _msg: GetValue, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data.clone()
    }
}

// Handle ClearValue
impl<T: Send + Debug + Clone + 'static> Message<ClearValue> for GenericActor<T> {
    type Reply = ();

    async fn handle(&mut self, _msg: ClearValue, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data = None;
    }
}

// ---- Test Cases ----
#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_generic_actor_string() {
        let initial_value: Option<String> = Some("initial_string".to_string());
        let (actor_ref, join_handle) = spawn::<GenericActor<String>>(initial_value.clone());

        // Get initial value
        let value: Option<String> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, initial_value);

        // Set a new value
        let new_value = "new_string".to_string();
        actor_ref.tell(SetValue(new_value.clone())).await.unwrap();

        // Get new value
        let value: Option<String> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, Some(new_value));

        // Clear value
        actor_ref.tell(ClearValue).await.unwrap();
        let value: Option<String> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, None);

        // Stop actor and wait
        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
        if let ActorResult::Completed { actor, killed: _ } = result {
            assert_eq!(actor.data, None); // Check final state after stop
        } else {
            panic!("Actor did not complete as expected");
        }
    }

    #[tokio::test]
    async fn test_generic_actor_i32() {
        let initial_value: Option<i32> = Some(42);
        let (actor_ref, join_handle) = spawn::<GenericActor<i32>>(initial_value);

        // Get initial value
        let value: Option<i32> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, initial_value);

        // Set a new value
        let new_value = 100;
        actor_ref.tell(SetValue(new_value)).await.unwrap();

        // Get new value
        let value: Option<i32> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, Some(new_value));

        // Clear value
        actor_ref.tell(ClearValue).await.unwrap();
        let value: Option<i32> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, None);

        // Stop actor and wait
        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
        if let ActorResult::Completed { actor, killed: _ } = result {
            assert_eq!(actor.data, None); // Check final state after stop
        } else {
            panic!("Actor did not complete as expected");
        }
    }

    #[tokio::test]
    async fn test_generic_actor_struct() {
        let initial_data = MyTestData::new(1, "initial_data");
        // Ensure MyTestData satisfies Send + Debug + Clone + 'static for GenericActor<MyTestData>
        let (actor_ref, join_handle) =
            spawn::<GenericActor<MyTestData>>(Some(initial_data.clone()));

        let value: Option<MyTestData> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, Some(initial_data.clone()));

        let new_data = MyTestData::new(2, "new_data");
        actor_ref.tell(SetValue(new_data.clone())).await.unwrap();

        let value: Option<MyTestData> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, Some(new_data.clone()));

        actor_ref.tell(ClearValue).await.unwrap();
        let value: Option<MyTestData> = actor_ref.ask(GetValue).await.unwrap();
        assert_eq!(value, None);

        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
        if let ActorResult::Completed { actor, killed: _ } = result {
            assert_eq!(actor.data, None); // Check final state after stop
        } else {
            panic!("Actor did not complete as expected");
        }
    }

    #[tokio::test]
    async fn test_bi_generic_actor() {
        // Test BiGenericActor with String and i32
        let (actor_ref, join_handle) = spawn::<BiGenericActor<String, i32>>((None, None));

        // Set key-value pair
        actor_ref
            .tell(SetKeyValue("hello".to_string(), 42))
            .await
            .unwrap();

        // Get key
        let key: Option<String> = actor_ref.ask(GetKey).await.unwrap();
        assert_eq!(key, Some("hello".to_string()));

        // Get value
        let value: Option<i32> = actor_ref.ask(GetValueFromBi).await.unwrap();
        assert_eq!(value, Some(42));

        // Clear both
        actor_ref.tell(ClearBoth).await.unwrap();
        let key: Option<String> = actor_ref.ask(GetKey).await.unwrap();
        let value: Option<i32> = actor_ref.ask(GetValueFromBi).await.unwrap();
        assert_eq!(key, None);
        assert_eq!(value, None);

        // Stop actor
        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
    }

    #[tokio::test]
    async fn test_tri_generic_actor() {
        // Test TriGenericActor with Vec<u8>, bool, and String
        let (actor_ref, join_handle) =
            spawn::<TriGenericActor<Vec<u8>, bool, String>>((true, "initial".to_string()));

        // Test GetAll to get initial state
        let (t_data, u_data, w_data): (Vec<u8>, bool, String) =
            actor_ref.ask(GetAll).await.unwrap();
        assert_eq!(t_data, Vec::<u8>::default()); // T::default()
        assert!(u_data);
        assert_eq!(w_data, "initial".to_string());

        // Set T data
        actor_ref.tell(SetT(vec![1, 2, 3])).await.unwrap();

        // Set U data
        actor_ref.tell(SetU(false)).await.unwrap();

        // Set W data
        actor_ref.tell(SetW("updated".to_string())).await.unwrap();

        // Get all updated data
        let (t_data, u_data, w_data): (Vec<u8>, bool, String) =
            actor_ref.ask(GetAll).await.unwrap();
        assert_eq!(t_data, vec![1, 2, 3]);
        assert!(!u_data);
        assert_eq!(w_data, "updated".to_string());

        // Test CompareU
        let is_equal: bool = actor_ref.ask(CompareU(false)).await.unwrap();
        assert!(is_equal);

        let is_equal: bool = actor_ref.ask(CompareU(true)).await.unwrap();
        assert!(!is_equal);

        // Test GetWAsString
        let w_as_string: String = actor_ref.ask(GetWAsString).await.unwrap();
        assert_eq!(w_as_string, "updated".to_string());

        // Stop actor
        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
    }

    #[tokio::test]
    async fn test_serializable_actor_json() {
        // Test SerializableActor with JsonData
        let (actor_ref, join_handle) = spawn::<SerializableActor<JsonData>>(());

        // Set JsonData
        let json_data = JsonData {
            value: "test".to_string(),
        };
        actor_ref
            .tell(SetSerializable(json_data.clone()))
            .await
            .unwrap();

        // Get original data
        let original: Option<JsonData> = actor_ref.ask(GetOriginal).await.unwrap();
        assert_eq!(original.unwrap().value, "test".to_string());

        // Get serialized data
        let serialized: Option<String> = actor_ref.ask(GetSerialized).await.unwrap();
        assert_eq!(serialized.unwrap(), "{\"value\":\"test\"}".to_string());

        // Stop actor
        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
    }

    #[tokio::test]
    async fn test_serializable_actor_xml() {
        // Test SerializableActor with XmlData
        let (actor_ref, join_handle) = spawn::<SerializableActor<XmlData>>(());

        // Set XmlData
        let xml_data = XmlData {
            content: "example".to_string(),
        };
        actor_ref
            .tell(SetSerializable(xml_data.clone()))
            .await
            .unwrap();

        // Get original data
        let original: Option<XmlData> = actor_ref.ask(GetOriginal).await.unwrap();
        assert_eq!(original.unwrap().content, "example".to_string());

        // Get serialized data
        let serialized: Option<String> = actor_ref.ask(GetSerialized).await.unwrap();
        assert_eq!(serialized.unwrap(), "<data>example</data>".to_string());

        // Stop actor
        actor_ref.stop().await.unwrap();
        let result = join_handle.await.unwrap();
        assert!(result.is_completed());
    }
}

// ---- Multi-Generic Type Examples ----

// Example 1: Actor with two generic types
#[derive(Debug)]
struct BiGenericActor<K: Send + Debug + Clone + 'static, V: Send + Debug + Clone + 'static> {
    key: Option<K>,
    value: Option<V>,
}

impl<K: Send + Debug + Clone + 'static, V: Send + Debug + Clone + 'static> Actor
    for BiGenericActor<K, V>
{
    type Args = (Option<K>, Option<V>);
    type Error = anyhow::Error;

    async fn on_start(args: Self::Args, _actor_ref: &ActorRef<Self>) -> Result<Self, Self::Error> {
        Ok(BiGenericActor {
            key: args.0,
            value: args.1,
        })
    }
}

// Messages for BiGenericActor
#[derive(Debug)]
pub struct SetKeyValue<K: Send + Debug + 'static, V: Send + Debug + 'static>(pub K, pub V);

#[derive(Debug)]
pub struct GetKey;

#[derive(Debug)]
pub struct GetValueFromBi;

#[derive(Debug)]
pub struct ClearBoth;

// Message implementations for BiGenericActor
impl<K: Send + Debug + Clone + 'static, V: Send + Debug + Clone + 'static>
    Message<SetKeyValue<K, V>> for BiGenericActor<K, V>
{
    type Reply = ();

    async fn handle(&mut self, msg: SetKeyValue<K, V>, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.key = Some(msg.0);
        self.value = Some(msg.1);
    }
}

impl<K: Send + Debug + Clone + 'static, V: Send + Debug + Clone + 'static> Message<GetKey>
    for BiGenericActor<K, V>
{
    type Reply = Option<K>;

    async fn handle(&mut self, _msg: GetKey, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.key.clone()
    }
}

impl<K: Send + Debug + Clone + 'static, V: Send + Debug + Clone + 'static> Message<GetValueFromBi>
    for BiGenericActor<K, V>
{
    type Reply = Option<V>;

    async fn handle(&mut self, _msg: GetValueFromBi, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.value.clone()
    }
}

impl<K: Send + Debug + Clone + 'static, V: Send + Debug + Clone + 'static> Message<ClearBoth>
    for BiGenericActor<K, V>
{
    type Reply = ();

    async fn handle(&mut self, _msg: ClearBoth, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.key = None;
        self.value = None;
    }
}

// Example 2: Actor with three generic types and complex constraints
#[derive(Debug)]
struct TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    data_t: T,
    data_u: U,
    data_w: W,
}

impl<T, U, W> Actor for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Args = (U, W);
    type Error = anyhow::Error;

    async fn on_start(args: Self::Args, _actor_ref: &ActorRef<Self>) -> Result<Self, Self::Error> {
        Ok(TriGenericActor {
            data_t: T::default(),
            data_u: args.0,
            data_w: args.1,
        })
    }
}

// Messages for TriGenericActor
#[derive(Debug)]
pub struct SetT<T: Send + Debug + 'static>(pub T);

#[derive(Debug)]
pub struct SetU<U: Send + Debug + 'static>(pub U);

#[derive(Debug)]
pub struct SetW<W: Send + Debug + 'static>(pub W);

#[derive(Debug)]
pub struct GetAll;

#[derive(Debug)]
pub struct CompareU<U: Send + Debug + 'static>(pub U);

#[derive(Debug)]
pub struct GetWAsString;

// Message implementations for TriGenericActor
impl<T, U, W> Message<SetT<T>> for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Reply = ();

    async fn handle(&mut self, msg: SetT<T>, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data_t = msg.0;
    }
}

impl<T, U, W> Message<SetU<U>> for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Reply = ();

    async fn handle(&mut self, msg: SetU<U>, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data_u = msg.0;
    }
}

impl<T, U, W> Message<SetW<W>> for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Reply = ();

    async fn handle(&mut self, msg: SetW<W>, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data_w = msg.0;
    }
}

impl<T, U, W> Message<GetAll> for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Reply = (T, U, W);

    async fn handle(&mut self, _msg: GetAll, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        (
            self.data_t.clone(),
            self.data_u.clone(),
            self.data_w.clone(),
        )
    }
}

impl<T, U, W> Message<CompareU<U>> for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Reply = bool;

    async fn handle(&mut self, msg: CompareU<U>, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data_u == msg.0
    }
}

impl<T, U, W> Message<GetWAsString> for TriGenericActor<T, U, W>
where
    T: Send + Debug + Clone + Default + 'static,
    U: Send + Debug + Clone + PartialEq + 'static,
    W: Send + Debug + Clone + ToString + 'static,
{
    type Reply = String;

    async fn handle(&mut self, _msg: GetWAsString, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data_w.to_string()
    }
}

// Example 3: Generic actor with associated types constraints
pub trait Serializable: Send + Debug + Clone + 'static {
    type Output: Send + Debug + Clone + 'static;
    fn serialize(&self) -> Self::Output;
}

#[derive(Debug, Clone)]
pub struct JsonData {
    pub value: String,
}

impl Serializable for JsonData {
    type Output = String;

    fn serialize(&self) -> Self::Output {
        format!("{{\"value\":\"{}\"}}", self.value)
    }
}

#[derive(Debug, Clone)]
pub struct XmlData {
    pub content: String,
}

impl Serializable for XmlData {
    type Output = String;

    fn serialize(&self) -> Self::Output {
        format!("<data>{}</data>", self.content)
    }
}

#[derive(Debug)]
struct SerializableActor<T: Serializable> {
    data: Option<T>,
}

impl<T: Serializable> Actor for SerializableActor<T> {
    type Args = ();
    type Error = anyhow::Error;

    async fn on_start(_args: Self::Args, _actor_ref: &ActorRef<Self>) -> Result<Self, Self::Error> {
        Ok(SerializableActor { data: None })
    }
}

// Messages for SerializableActor
#[derive(Debug)]
pub struct SetSerializable<T: Serializable>(pub T);

#[derive(Debug)]
pub struct GetSerialized;

#[derive(Debug)]
pub struct GetOriginal;

// Message implementations for SerializableActor
impl<T: Serializable> Message<SetSerializable<T>> for SerializableActor<T> {
    type Reply = ();

    async fn handle(
        &mut self,
        msg: SetSerializable<T>,
        _actor_ref: &ActorRef<Self>,
    ) -> Self::Reply {
        self.data = Some(msg.0);
    }
}

impl<T: Serializable> Message<GetSerialized> for SerializableActor<T> {
    type Reply = Option<T::Output>;

    async fn handle(&mut self, _msg: GetSerialized, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data.as_ref().map(|d| d.serialize())
    }
}

impl<T: Serializable> Message<GetOriginal> for SerializableActor<T> {
    type Reply = Option<T>;

    async fn handle(&mut self, _msg: GetOriginal, _actor_ref: &ActorRef<Self>) -> Self::Reply {
        self.data.clone()
    }
}