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
//! Demonstrates how we can throttle an actor. We use the stream_throttle crate to deliver
//! messages at a rate of 1 per second.
//
use
{
thespis :: { * } ,
thespis_impl :: { Addr } ,
async_executors :: { AsyncStd, } ,
std :: { error::Error, time::Duration } ,
futures :: { channel::mpsc, SinkExt } ,
stream_throttle :: { ThrottleRate, ThrottlePool, ThrottledStream } ,
};
#[ derive( Debug, Actor ) ]
//
struct MyActor
{
count: usize,
}
struct Count;
struct Show;
impl Message for Count { type Return = (); }
impl Message for Show { type Return = usize; }
impl Handler< Count > for MyActor
{
#[async_fn] fn handle( &mut self, _msg: Count )
{
self.count += 1;
println!( "Received a message." );
}
}
impl Handler< Show > for MyActor
{
#[async_fn] fn handle( &mut self, _msg: Show ) -> usize
{
self.count
}
}
#[async_std::main]
//
async fn main() -> Result< (), Box<dyn Error> >
{
let (tx, rx) = mpsc::channel( 10 );
let rate = ThrottleRate::new( 1, Duration::from_secs(1) );
let pool = ThrottlePool::new( rate );
let rx = rx.throttle( pool );
let (mut addr, mb_handle) = Addr::builder( "Throttled" )
.channel( tx, rx )
.spawn_handle( MyActor{ count: 0 }, &AsyncStd )?
;
for _ in 0..10
{
addr.send( Count ).await?;
}
assert_eq!( 10, addr.call(Show).await? );
// Allow the program to end.
//
// One gotcha here. Normally the mailbox will stay alive even after dropping all strong
// addresses as long as there are messages in the channel. However, when the channel returns
// `Pending` it thinks it's empty. Where as here it is just throttled.
//
// This is not an issue here because we use the call with `Show` above to synchronize. That message
// needs to be handled before we can arrive here, which means all prior messages have been handled as
// well.
//
// If it wasn't for this last call, the program would end after the actor processed just 1 message.
//
drop( addr );
mb_handle.await;
Ok(())
}