xtra 0.6.0

A tiny actor framework
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
use std::cmp::Ordering as CmpOrdering;
use std::ops::ControlFlow;
use std::task::Poll;
use std::time::Duration;

use futures_util::task::noop_waker_ref;
use futures_util::FutureExt;
use smol_timeout::TimeoutExt;
use tokio::task::JoinSet;
use xtra::prelude::*;
use xtra::Error;

#[derive(Clone, Debug, Eq, PartialEq)]
struct Accumulator(usize);

impl Actor for Accumulator {
    type Stop = usize;

    async fn stopped(self) -> usize {
        self.0
    }
}

struct Inc;

struct Report;

impl Handler<Inc> for Accumulator {
    type Return = ();

    async fn handle(&mut self, _: Inc, _ctx: &mut Context<Self>) {
        self.0 += 1;
    }
}

impl Handler<Report> for Accumulator {
    type Return = Self;

    async fn handle(&mut self, _: Report, _ctx: &mut Context<Self>) -> Self {
        self.clone()
    }
}

impl Handler<StopAll> for Accumulator {
    type Return = ();

    async fn handle(&mut self, _: StopAll, ctx: &mut Context<Self>) -> Self::Return {
        ctx.stop_all();
    }
}

impl Handler<StopSelf> for Accumulator {
    type Return = ();

    async fn handle(&mut self, _: StopSelf, ctx: &mut Context<Self>) {
        ctx.stop_self();
    }
}

#[tokio::test]
async fn accumulate_to_ten() {
    let (addr, mailbox) = Mailbox::unbounded();
    tokio::spawn(xtra::run(mailbox, Accumulator(0)));

    let mut join_set = JoinSet::new();

    for _ in 0..10 {
        join_set.spawn(addr.send(Inc).detach().await.unwrap());
    }

    while join_set.join_next().await.is_some() {}

    assert_eq!(addr.send(Report).await.unwrap().0, 10);
}

#[derive(xtra::Actor)]
struct StopTester;

struct StopAll;

struct StopSelf;

impl Handler<StopSelf> for StopTester {
    type Return = ();

    async fn handle(&mut self, _: StopSelf, ctx: &mut Context<Self>) {
        ctx.stop_self();
    }
}

impl Handler<StopAll> for StopTester {
    type Return = ();

    async fn handle(&mut self, _: StopAll, ctx: &mut Context<Self>) {
        ctx.stop_all();
    }
}

#[tokio::test]
async fn actor_stops_on_last_drop_of_address() {
    let (addr, mailbox) = Mailbox::unbounded();
    let handle = tokio::spawn(xtra::run(mailbox, StopTester));
    let weak = addr.downgrade();
    let join = weak.join();

    drop(addr);
    handle.await.unwrap();

    assert!(!weak.is_connected());
    assert!(join.now_or_never().is_some());
}

#[tokio::test]
async fn actor_stops_on_stop_self_message() {
    let (addr, mailbox) = Mailbox::unbounded();
    let handle = tokio::spawn(xtra::run(mailbox, StopTester));
    let weak = addr.downgrade();
    let join = weak.join();

    let _ = addr.send(StopSelf).detach().await;
    handle.await.unwrap();

    assert!(!weak.is_connected());
    assert!(!addr.is_connected());
    assert!(join.now_or_never().is_some());
}

#[tokio::test]
async fn actor_stops_on_stop_all_message() {
    let (addr, mailbox) = Mailbox::unbounded();
    let handle = tokio::spawn(xtra::run(mailbox, StopTester));
    let weak = addr.downgrade();
    let join = weak.join();

    let _ = addr.send(StopAll).detach().await;
    handle.await.unwrap();

    assert!(!weak.is_connected());
    assert!(!addr.is_connected());
    assert!(join.now_or_never().is_some());
}

#[tokio::test]
async fn actor_stops_on_last_drop_of_address_even_if_not_yet_running() {
    let (addr, mailbox) = Mailbox::unbounded();
    let weak = addr.downgrade();
    let join = weak.join();

    drop(addr);
    tokio::spawn(xtra::run(mailbox, StopTester)).await.unwrap();

    assert!(!weak.is_connected());
    assert!(join.now_or_never().is_some());
}

#[tokio::test]
async fn actor_stops_on_stop_message_even_if_sent_before_started() {
    let (addr, mailbox) = Mailbox::unbounded();
    let weak = addr.downgrade();
    let join = weak.join();

    let _ = addr.send(StopSelf).detach().await;
    tokio::spawn(xtra::run(mailbox, StopTester)).await.unwrap();

    assert!(!weak.is_connected());
    assert!(!addr.is_connected());
    assert!(join.now_or_never().is_some());
}

#[tokio::test]
async fn handle_left_messages() {
    let (addr, mailbox) = Mailbox::unbounded();

    for _ in 0..10 {
        let _ = addr.send(Inc).detach().await;
    }

    drop(addr);

    assert_eq!(xtra::run(mailbox, Accumulator(0)).await, 10);
}

#[tokio::test]
async fn actor_can_be_restarted() {
    let (addr, mailbox) = Mailbox::unbounded();

    tokio::spawn(async move {
        for _ in 0..5 {
            let _ = addr.send(Inc).await;
        }

        let _ = addr.send(StopSelf).await;
    });

    assert_eq!(xtra::run(mailbox, Accumulator(0)).await, 5);

    let (addr, ctx) = Mailbox::unbounded();
    let fut1 = xtra::run(ctx.clone(), Accumulator(0));
    let fut2 = xtra::run(ctx, Accumulator(0));

    tokio::spawn({
        let addr = addr.clone();
        async move {
            for _ in 0..5 {
                let _ = addr.send(Inc).await;
            }

            let _ = addr.send(StopAll).await;
        }
    });

    assert_eq!(fut1.await, 5);
    assert!(addr.is_connected());

    // These should not be handled, as fut2 should get the stop_all in this mailbox and stop the
    // actor
    for _ in 0..5 {
        let _ = addr.send(Inc).detach().await;
    }

    assert_eq!(fut2.await, 0);
    assert!(!addr.is_connected());
}

#[tokio::test]
async fn single_actor_on_address_with_stop_self_returns_disconnected_on_stop() {
    let (address, mailbox) = Mailbox::unbounded();
    let fut = xtra::run(mailbox, ActorStopSelf);
    let _ = address.send(StopSelf).detach().await;
    assert!(fut.now_or_never().is_some());
    assert!(address.join().now_or_never().is_some());
    assert!(!address.is_connected());
}

#[tokio::test]
async fn two_actors_on_address_with_stop_self() {
    let (address, ctx) = Mailbox::unbounded();
    tokio::spawn(xtra::run(ctx.clone(), ActorStopSelf));
    tokio::spawn(xtra::run(ctx, ActorStopSelf));
    address.send(StopSelf).await.unwrap();
    tokio::time::sleep(Duration::from_secs(1)).await;

    assert!(address.is_connected());
    address.send(StopSelf).await.unwrap();

    tokio::time::sleep(Duration::from_secs(1)).await;
    assert!(!address.is_connected());
}

#[tokio::test]
async fn two_actors_on_address_with_stop_self_context_alive() {
    let (address, ctx) = Mailbox::unbounded();
    tokio::spawn(xtra::run(ctx.clone(), ActorStopSelf));
    tokio::spawn(xtra::run(ctx.clone(), ActorStopSelf)); // Context not dropped here
    address.send(StopSelf).await.unwrap();
    tokio::time::sleep(Duration::from_secs(1)).await;

    assert!(address.is_connected());
    address.send(StopSelf).await.unwrap();

    tokio::time::sleep(Duration::from_secs(1)).await;
    assert!(address.is_connected());
}

#[derive(xtra::Actor)]
struct ActorStopSelf;

impl Handler<StopSelf> for ActorStopSelf {
    type Return = ();

    async fn handle(&mut self, _: StopSelf, ctx: &mut Context<Self>) {
        ctx.stop_self();
    }
}

#[derive(xtra::Actor)]
struct LongRunningHandler;

impl Handler<Duration> for LongRunningHandler {
    type Return = ();

    async fn handle(&mut self, duration: Duration, _: &mut Context<Self>) -> Self::Return {
        tokio::time::sleep(duration).await
    }
}

#[tokio::test]
async fn receiving_async_on_address_returns_immediately_after_dispatch() {
    let address = xtra::spawn_tokio(LongRunningHandler, Mailbox::unbounded());

    let send_future = address.send(Duration::from_secs(3)).detach();
    let handler_future = send_future
        .now_or_never()
        .expect("Dispatch should be immediate on first poll")
        .expect("Actor is not disconnected");

    handler_future.await.unwrap();
}

#[tokio::test]
async fn receiving_async_on_message_channel_returns_immediately_after_dispatch() {
    let address = xtra::spawn_tokio(LongRunningHandler, Mailbox::unbounded());
    let channel = MessageChannel::new(address);

    let send_future = channel.send(Duration::from_secs(3)).detach();
    let handler_future = send_future
        .now_or_never()
        .expect("Dispatch should be immediate on first poll")
        .expect("Actor is not disconnected");

    handler_future.await.unwrap();
}

#[derive(Eq, PartialEq, Clone, Debug)]
enum Message {
    Broadcast { priority: u32 },
    Priority { priority: u32 },
}

impl PartialOrd<Self> for Message {
    fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
        Some(self.cmp(other))
    }
}

impl Ord for Message {
    fn cmp(&self, other: &Self) -> CmpOrdering {
        match self {
            Message::Broadcast { priority } => match other {
                Message::Broadcast { priority: other } => priority.cmp(other),
                Message::Priority { priority: other } => priority.cmp(other),
            },
            Message::Priority { priority } => match other {
                Message::Broadcast { priority: other } => priority.cmp(other),
                Message::Priority { priority: other } => priority.cmp(other),
            },
        }
    }
}

// An elephant never forgets :)
struct Elephant {
    name: &'static str,
    msgs: Vec<Message>,
}

impl Default for Elephant {
    fn default() -> Self {
        Elephant {
            name: "Indlovu",
            msgs: vec![],
        }
    }
}

impl Actor for Elephant {
    type Stop = Vec<Message>;

    async fn stopped(self) -> Self::Stop {
        self.msgs
    }
}

impl Handler<Message> for Elephant {
    type Return = ();

    async fn handle(&mut self, message: Message, _ctx: &mut Context<Self>) {
        eprintln!("{} is handling {:?}", self.name, message);
        self.msgs.push(message);
    }
}

#[tokio::test]
async fn handle_order() {
    let mut expected = vec![];

    let fut = {
        let (ele, mailbox) = Mailbox::unbounded();
        let fut = xtra::run(mailbox, Elephant::default());

        let mut send = |msg: Message| {
            expected.push(msg.clone());

            async {
                match msg {
                    Message::Broadcast { priority } => {
                        let _ = ele.broadcast(msg).priority(priority).await;
                    }
                    Message::Priority { priority } => {
                        let _ = ele.send(msg).priority(priority).detach().await;
                    }
                }
            }
        };

        send(Message::Priority { priority: 0 }).await;
        send(Message::Priority { priority: 1 }).await;
        send(Message::Priority { priority: 2 }).await;
        send(Message::Broadcast { priority: 4 }).await;
        send(Message::Broadcast { priority: 5 }).await;
        send(Message::Broadcast { priority: 3 }).await;
        send(Message::Priority { priority: 4 }).await;
        send(Message::Broadcast { priority: 5 }).await;

        fut
    };

    expected.sort();
    expected.reverse();

    assert_eq!(fut.await, expected);
}

#[tokio::test]
async fn waiting_sender_order() {
    let (addr, ctx) = Mailbox::bounded(1);
    let mut fut_ctx = std::task::Context::from_waker(noop_waker_ref());
    let mut ele = Elephant::default();

    // With priority

    let _ = addr
        .send(Message::Priority { priority: 1 })
        .priority(1)
        .detach()
        .await;
    let mut lesser = addr
        .send(Message::Priority { priority: 1 })
        .priority(1)
        .detach();
    let mut greater = addr
        .send(Message::Priority { priority: 2 })
        .priority(2)
        .detach();

    assert!(lesser.poll_unpin(&mut fut_ctx).is_pending());
    assert!(greater.poll_unpin(&mut fut_ctx).is_pending());

    let act = &mut ele;
    xtra::yield_once(&ctx, act).await;

    assert!(lesser.poll_unpin(&mut fut_ctx).is_pending());
    assert!(greater.poll_unpin(&mut fut_ctx).is_ready());

    // With broadcast

    let _ = addr
        .broadcast(Message::Broadcast { priority: 3 })
        .priority(3)
        .await;
    let mut lesser = addr
        .broadcast(Message::Broadcast { priority: 4 })
        .priority(4)
        .boxed();
    let mut greater = addr
        .broadcast(Message::Broadcast { priority: 5 })
        .priority(5)
        .boxed();

    assert!(lesser.poll_unpin(&mut fut_ctx).is_pending());
    assert!(greater.poll_unpin(&mut fut_ctx).is_pending());

    let act = &mut ele;
    xtra::yield_once(&ctx, act).await;

    assert!(lesser.poll_unpin(&mut fut_ctx).is_pending());
    assert!(greater.poll_unpin(&mut fut_ctx).is_ready());
}

#[tokio::test]
async fn set_priority_msg_channel() {
    let fut = {
        let (addr, mailbox) = Mailbox::unbounded();
        let fut = xtra::run(mailbox, Elephant::default());

        let channel = MessageChannel::new(addr);

        let _ = channel
            .send(Message::Priority { priority: 0 })
            .detach()
            .await;
        let _ = channel
            .send(Message::Priority { priority: 1 })
            .priority(1)
            .detach()
            .await;
        let _ = channel
            .send(Message::Priority { priority: 2 })
            .detach()
            .priority(2)
            .await;

        fut
    };

    assert_eq!(
        fut.await,
        vec![
            Message::Priority { priority: 2 },
            Message::Priority { priority: 1 },
            Message::Priority { priority: 0 },
        ]
    );
}

#[tokio::test]
async fn broadcast_tail_advances_bound_1() {
    let (addr, ctx) = Mailbox::bounded(1);
    let mut fut_ctx = std::task::Context::from_waker(noop_waker_ref());
    let mut ngwevu = Elephant {
        name: "Ngwevu",
        msgs: vec![],
    };

    let mut indlovu = Box::pin(xtra::run(ctx.clone(), Elephant::default()));

    addr.broadcast(Message::Broadcast { priority: 0 })
        .priority(0)
        .await
        .unwrap();

    assert!(
        addr.broadcast(Message::Broadcast { priority: 0 })
            .priority(0)
            .now_or_never()
            .is_none(),
        "New broadcast message should not be accepted when tail = len",
    );

    let mut send = addr
        .broadcast(Message::Broadcast { priority: 0 })
        .priority(0);

    assert!(
        send.poll_unpin(&mut fut_ctx).is_pending(),
        "New broadcast message should not be accepted when tail = len"
    );
    assert!(indlovu.poll_unpin(&mut fut_ctx).is_pending());
    let act = &mut ngwevu;
    xtra::yield_once(&ctx, act).await;

    assert!(
        addr.broadcast(Message::Broadcast { priority: 0 })
            .priority(0)
            .now_or_never()
            .is_none(),
        "New broadcast message should not be accepted when tail = len and one is already waiting",
    );

    assert!(
        send.poll_unpin(&mut fut_ctx).is_ready(),
        "New broadcast message should be accepted now"
    );

    assert!(indlovu.poll_unpin(&mut fut_ctx).is_pending());
    let act = &mut ngwevu;
    xtra::yield_once(&ctx, act).await;

    assert_eq!(
        addr.broadcast(Message::Broadcast { priority: 0 })
            .priority(0)
            .await,
        Ok(()),
        "New broadcast message should be accepted when queue is empty",
    );

    let mut lesser = addr
        .broadcast(Message::Broadcast { priority: 1 })
        .priority(1)
        .boxed();
    let mut greater = addr
        .broadcast(Message::Broadcast { priority: 2 })
        .priority(2)
        .boxed();

    assert!(
        lesser.poll_unpin(&mut fut_ctx).is_pending(),
        "Queue is full - should wait"
    );
    assert!(
        greater.poll_unpin(&mut fut_ctx).is_pending(),
        "Queue is full - should wait"
    );

    // Will handle the broadcast of priority 0 from earlier
    let act = &mut ngwevu;
    xtra::yield_once(&ctx, act).await;
    assert!(indlovu.poll_unpin(&mut fut_ctx).is_pending());

    assert!(
        lesser.poll_unpin(&mut fut_ctx).is_pending(),
        "Low prio - should wait"
    );
    assert!(
        greater.poll_unpin(&mut fut_ctx).is_ready(),
        "High prio - shouldn't wait"
    );

    // Should handle greater
    let act = &mut ngwevu;
    xtra::yield_once(&ctx, act).await;
    assert!(indlovu.poll_unpin(&mut fut_ctx).is_pending());

    assert!(
        lesser.poll_unpin(&mut fut_ctx).is_ready(),
        "Low prio should be sent in now"
    );

    assert!(
        addr.broadcast(Message::Broadcast { priority: 10 })
            .now_or_never()
            .is_none(),
        "Channel should not accept when full",
    )
}

#[tokio::test]
async fn broadcast_tail_advances_bound_2() {
    let (addr, ctx) = Mailbox::bounded(2);
    let mut ngwevu = Elephant {
        name: "Ngwevu",
        msgs: vec![],
    };

    tokio::spawn(xtra::run(ctx.clone(), Elephant::default()));

    let _ = addr
        .broadcast(Message::Broadcast { priority: 0 })
        .priority(0)
        .await;
    let _ = addr
        .broadcast(Message::Broadcast { priority: 0 })
        .priority(0)
        .await;

    let act = &mut ngwevu;
    xtra::yield_once(&ctx, act).await;

    assert_eq!(
        addr.broadcast(Message::Broadcast { priority: 0 })
            .priority(0)
            .timeout(Duration::from_secs(2))
            .await,
        Some(Ok(())),
        "New broadcast message should be accepted when queue has space",
    );
}

#[tokio::test]
async fn broadcast_tail_does_not_advance_unless_both_handle() {
    let (addr, ctx) = Mailbox::bounded(2);
    let mut ngwevu = Elephant {
        name: "Ngwevu",
        msgs: vec![],
    };

    let _fut = xtra::run(ctx.clone(), Elephant::default());

    let _ = addr
        .broadcast(Message::Broadcast { priority: 0 })
        .priority(0)
        .await;
    let _ = addr
        .broadcast(Message::Broadcast { priority: 0 })
        .priority(0)
        .await;

    let act = &mut ngwevu;
    xtra::yield_once(&ctx, act).await;

    assert_eq!(
        addr.broadcast(Message::Broadcast { priority: 0 }).priority(0).timeout(Duration::from_secs(2)).await,
        None,
        "New broadcast message should NOT be accepted since the other actor has not yet handled the message",
    );
}

#[derive(xtra::Actor)]
struct Greeter;

struct Hello(&'static str);

impl Handler<Hello> for Greeter {
    type Return = String;

    async fn handle(&mut self, Hello(name): Hello, _: &mut Context<Self>) -> Self::Return {
        format!("Hello {}", name)
    }
}

#[derive(Clone)]
struct PrintHello(&'static str);

impl Handler<PrintHello> for Greeter {
    type Return = ();

    async fn handle(
        &mut self,
        PrintHello(name): PrintHello,
        _: &mut Context<Self>,
    ) -> Self::Return {
        println!("Hello {}", name)
    }
}

#[tokio::test]
async fn address_send_exercises_backpressure() {
    let (address, context) = Mailbox::bounded(1);

    // Regular send

    let _ = address
        .send(Hello("world"))
        .detach()
        .now_or_never()
        .expect("be able to queue 1 message because the mailbox is empty");
    let handler2 = address.send(Hello("world")).detach().now_or_never();
    assert!(
        handler2.is_none(),
        "Fail to queue 2nd message because mailbox is full"
    );

    let act = &mut Greeter;
    xtra::yield_once(&context, act).await; // process one message

    let _ = address
        .send(Hello("world"))
        .detach()
        .now_or_never()
        .expect("be able to queue another message because the mailbox is empty again");

    let act = &mut Greeter;
    xtra::yield_once(&context, act).await; // process one message

    // Priority send

    let (address, context) = Mailbox::bounded(1);

    let _ = address
        .send(Hello("world"))
        .priority(1)
        .detach()
        .now_or_never()
        .expect("be able to queue 1 priority message because the mailbox is empty");
    let handler2 = address
        .send(Hello("world"))
        .priority(1)
        .detach()
        .now_or_never();
    assert!(
        handler2.is_none(),
        "Fail to queue 2nd priority message because mailbox is full"
    );

    let act = &mut Greeter;
    xtra::yield_once(&context, act).await; // process one message

    let _ = address
        .send(PrintHello("world"))
        .priority(1)
        .detach()
        .now_or_never()
        .expect("be able to queue another priority message because the mailbox is empty again");

    // Broadcast

    let _ = address
        .broadcast(PrintHello("world"))
        .priority(2)
        .now_or_never()
        .expect("be able to queue 1 broadcast because the mailbox is empty");
    let handler2 = address
        .broadcast(PrintHello("world"))
        .priority(1)
        .now_or_never();
    assert!(
        handler2.is_none(),
        "Fail to queue 2nd broadcast because mailbox is full"
    );

    let act = &mut Greeter;
    xtra::yield_once(&context, act).await; // process one message

    let _ = address
        .broadcast(PrintHello("world"))
        .priority(2)
        .now_or_never()
        .expect("be able to queue another broadcast because the mailbox is empty again");
}

#[test]
fn address_debug() {
    let (addr1, _ctx) = Mailbox::<Greeter>::unbounded();

    let addr2 = addr1.clone();
    let weak_addr = addr2.downgrade();

    assert_eq!(
        format!("{:?}", addr1),
        "Address<basic::Greeter, Strong> { addresses: 2, mailboxes: 1 }"
    );

    assert_eq!(format!("{:?}", addr1), format!("{:?}", addr2));

    assert_eq!(
        format!("{:?}", weak_addr),
        "Address<basic::Greeter, Weak> { addresses: 2, mailboxes: 1 }"
    );
}

#[test]
fn message_channel_debug() {
    let (addr1, _ctx) = Mailbox::<Greeter>::unbounded();

    let mc = MessageChannel::<Hello, String>::new(addr1);
    let weak_mc = mc.downgrade();

    assert_eq!(
        format!("{:?}", mc),
        "MessageChannel<basic::Greeter, basic::Hello, alloc::string::String, Strong> { addresses: 1, mailboxes: 1 }"
    );

    assert_eq!(
        format!("{:?}", weak_mc),
        "MessageChannel<basic::Greeter, basic::Hello, alloc::string::String, Weak> { addresses: 1, mailboxes: 1 }"
    );
}

#[test]
fn scoped_task() {
    // Completes when address is connected
    let (addr, ctx) = Mailbox::unbounded();
    let scoped = xtra::scoped(&addr, futures_util::future::ready(()));
    assert!(scoped.now_or_never().is_some());

    // Does not complete when address starts off from a disconnected weak
    let weak = addr.downgrade();
    drop(addr);
    assert!(xtra::run(ctx, Greeter).now_or_never().is_some());
    let scoped = xtra::scoped(&weak, futures_util::future::ready(()));
    assert_eq!(scoped.now_or_never(), Some(None));

    // Does not complete when address starts off from a disconnected strong
    let (addr, ctx) = Mailbox::unbounded();
    let _ = addr.send(StopSelf).detach().now_or_never().unwrap();
    assert!(xtra::run(ctx, ActorStopSelf).now_or_never().is_some());
    let scoped = xtra::scoped(&addr, futures_util::future::ready(()));
    assert_eq!(scoped.now_or_never(), Some(None));

    // Does not complete when address disconnects after ScopedTask creation but before first poll
    let (addr, ctx) = Mailbox::<Greeter>::unbounded();
    drop(ctx);
    let scoped = xtra::scoped(&addr, futures_util::future::ready(()));
    assert_eq!(scoped.now_or_never(), Some(None));

    // Does not complete when address disconnects after ScopedTask creation but before first poll
    let (addr, act_ctx) = Mailbox::<Greeter>::unbounded();
    let mut scoped = xtra::scoped(&addr, futures_util::future::pending::<()>()).boxed();
    let mut fut_ctx = std::task::Context::from_waker(noop_waker_ref());
    assert!(scoped.poll_unpin(&mut fut_ctx).is_pending());
    drop(act_ctx);
    assert_eq!(scoped.poll_unpin(&mut fut_ctx), Poll::Ready(None));
}

#[test]
fn test_addr_cmp_hash_eq() {
    let addr1 = Mailbox::<Greeter>::unbounded().0;
    let addr2 = Mailbox::<Greeter>::unbounded().0;

    assert_ne!(addr1, addr2);
    assert_ne!(addr1, addr1.downgrade());
    assert_eq!(addr1, addr1.clone());
    assert!(addr1.same_actor(&addr1));
    assert!(addr1.same_actor(&addr1.downgrade()));
    assert!(!addr1.same_actor(&addr2));
    assert!(addr1 > addr1.downgrade());

    let chan1 = MessageChannel::<Hello, String>::new(addr1);
    let chan2 = MessageChannel::<Hello, String>::new(addr2);
    assert!(chan1.eq(&chan1));
    assert!(!chan1.eq(&chan2));
    assert!(chan1.same_actor(&chan1));
    assert!(chan1.same_actor(&chan1.downgrade()));
    assert!(!chan1.same_actor(&chan2));
}

struct Pending;

impl Handler<Pending> for Greeter {
    type Return = ();

    async fn handle(&mut self, _: Pending, _ctx: &mut Context<Self>) {
        futures_util::future::pending().await
    }
}

#[tokio::test]
async fn timeout_returns_interrupted() {
    let (address, mailbox) = Mailbox::unbounded();
    let mut actor = Greeter;

    tokio::spawn(async move {
        if let Err(()) = actor.started(&mailbox).await {
            return;
        }

        loop {
            let ctrl = xtra::yield_once(&mailbox, &mut actor)
                .timeout(Duration::from_secs(1))
                .await;

            if let Some(ControlFlow::Break(_)) = ctrl {
                break;
            }
        }
    });

    address
        .send(Hello("world"))
        .detach()
        .now_or_never()
        .expect("Boundless message should be sent instantly")
        .expect("Actor is not disconnected")
        .timeout(Duration::from_secs(3))
        .await
        .expect("Message should not time out")
        .expect("Counter should not be dropped");

    assert_eq!(
        address.send(Pending).await,
        Err(Error::Interrupted),
        "Timeout should return Interrupted"
    );

    address
        .send(Hello("world"))
        .detach()
        .now_or_never()
        .expect("Boundless message should be sent instantly")
        .expect("Actor is not disconnected")
        .timeout(Duration::from_secs(3))
        .await
        .expect("Message should not time out")
        .expect("Counter should not be dropped");

    let weak = address.downgrade();
    let join = address.join();
    drop(address);

    join.await;
    assert_eq!(
        weak.send(Hello("world")).now_or_never(),
        Some(Err(Error::Disconnected)),
        "Interrupt should not be returned after actor stops"
    );
}

#[test]
fn no_sender_returns_disconnected() {
    let (addr, ctx) = Mailbox::<Greeter>::unbounded();
    drop(addr);
    assert!(!ctx.address().is_connected());
}

#[tokio::test]
async fn receive_future_can_dispatch_in_one_poll() {
    let (addr, mailbox) = Mailbox::<Greeter>::unbounded();

    let _ = addr.send(Hello("world")).detach().await;
    let receive_future = mailbox.next();

    assert!(receive_future.now_or_never().is_some())
}

#[tokio::test]
async fn receive_future_can_dispatch_in_one_poll_after_it_has_been_polled() {
    let (addr, mailbox) = Mailbox::<Greeter>::unbounded();
    let mut receive_future = mailbox.next();

    let poll = receive_future.poll_unpin(&mut std::task::Context::from_waker(
        futures_util::task::noop_waker_ref(),
    ));
    assert!(poll.is_pending());

    let _ = addr.send(Hello("world")).detach().await;

    assert!(receive_future.now_or_never().is_some())
}