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
//! A multi-producer, single-consumer queue for sending messages and signals between actors.
//!
//! An actor mailbox is a channel which stores pending messages and signals for an actor to process sequentially.
use std::{
collections::VecDeque,
fmt,
task::{Context, Poll},
time::Duration,
};
use dyn_clone::DynClone;
use futures::{FutureExt, future::BoxFuture};
use tokio::sync::mpsc::{self, error::TryRecvError};
use crate::{
Actor,
actor::{ActorId, ActorRef},
error::{ActorStopReason, SendError},
message::BoxMessage,
reply::BoxReplySender,
};
/// Creates a bounded mailbox for communicating between actors with backpressure.
///
/// _See tokio's [`mpsc::channel`] docs for more info._
///
/// [`mpsc::channel`]: tokio::sync::mpsc::channel
pub fn bounded<A: Actor>(buffer: usize) -> (MailboxSender<A>, MailboxReceiver<A>) {
let (tx, rx) = mpsc::channel(buffer);
#[cfg(feature = "hotpath")]
let (tx, rx) = hotpath::channel!((tx, rx), label = A::name());
(
MailboxSender {
inner: MailboxSenderInner::Bounded(tx),
#[cfg(feature = "metrics")]
messages_sent: metrics::counter!("piying_messages_sent", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
lifecycle_signals_sent: metrics::counter!("piying_lifecycle_sent", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
link_died_signals_sent: metrics::counter!("piying_link_died_sent", "actor_name" => A::name()),
},
MailboxReceiver {
inner: MailboxReceiverInner::Bounded(rx),
front: VecDeque::new(),
#[cfg(feature = "metrics")]
messages_received: metrics::counter!("piying_messages_received", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
lifecycle_signals_received: metrics::counter!("piying_lifecycle_received", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
link_died_signals_received: metrics::counter!("piying_link_died_received", "actor_name" => A::name()),
},
)
}
/// Creates an unbounded mailbox for communicating between actors without backpressure.
///
/// See tokio's [`mpsc::unbounded_channel`] docs for more info.
///
/// [`mpsc::unbounded_channel`]: tokio::sync::mpsc::unbounded_channel
pub fn unbounded<A: Actor>() -> (MailboxSender<A>, MailboxReceiver<A>) {
let (tx, rx) = mpsc::unbounded_channel();
#[cfg(feature = "hotpath")]
let (tx, rx) = hotpath::channel!((tx, rx), label = A::name());
(
MailboxSender {
inner: MailboxSenderInner::Unbounded(tx),
#[cfg(feature = "metrics")]
messages_sent: metrics::counter!("piying_messages_sent", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
lifecycle_signals_sent: metrics::counter!("piying_lifecycle_sent", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
link_died_signals_sent: metrics::counter!("piying_link_died_sent", "actor_name" => A::name()),
},
MailboxReceiver {
inner: MailboxReceiverInner::Unbounded(rx),
front: VecDeque::new(),
#[cfg(feature = "metrics")]
messages_received: metrics::counter!("piying_messages_received", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
lifecycle_signals_received: metrics::counter!("piying_lifecycle_received", "actor_name" => A::name()),
#[cfg(feature = "metrics")]
link_died_signals_received: metrics::counter!("piying_link_died_received", "actor_name" => A::name()),
},
)
}
/// Sends messages and signals to the associated `MailboxReceiver`.
///
/// Instances are created by the [`bounded`] and [`unbounded`] functions.
pub struct MailboxSender<A: Actor> {
inner: MailboxSenderInner<A>,
#[cfg(feature = "metrics")]
messages_sent: metrics::Counter,
#[cfg(feature = "metrics")]
lifecycle_signals_sent: metrics::Counter,
#[cfg(feature = "metrics")]
link_died_signals_sent: metrics::Counter,
}
enum MailboxSenderInner<A: Actor> {
/// Bounded mailbox sender.
Bounded(mpsc::Sender<Signal<A>>),
/// Unbounded mailbox sender.
Unbounded(mpsc::UnboundedSender<Signal<A>>),
}
#[cfg(feature = "metrics")]
enum SignalKind {
Message,
Lifecycle,
LinkDied,
}
#[cfg(feature = "metrics")]
impl SignalKind {
#[inline]
fn apply_metric<A: Actor>(self, tx: &MailboxSender<A>) {
match self {
SignalKind::Message => tx.messages_sent.increment(1),
SignalKind::Lifecycle => tx.lifecycle_signals_sent.increment(1),
SignalKind::LinkDied => tx.link_died_signals_sent.increment(1),
}
}
}
#[cfg(feature = "metrics")]
impl<A: Actor> From<&Signal<A>> for SignalKind {
#[inline]
fn from(signal: &Signal<A>) -> Self {
match signal {
Signal::Message { .. } => SignalKind::Message,
Signal::StartupFinished | Signal::Stop => SignalKind::Lifecycle,
Signal::LinkDied { .. } => SignalKind::LinkDied,
}
}
}
impl<A: Actor> MailboxSender<A> {
/// Sends a value, waiting until there is capacity.
///
/// See tokio's [`mpsc::Sender::send`] and [`mpsc::UnboundedSender::send`] docs for more info.
///
/// [`mpsc::Sender::send`]: tokio::sync::mpsc::Sender::send
/// [`mpsc::UnboundedSender::send`]: tokio::sync::mpsc::UnboundedSender::send
#[allow(clippy::result_large_err)]
pub async fn send(&self, signal: Signal<A>) -> Result<(), mpsc::error::SendError<Signal<A>>> {
#[cfg(feature = "metrics")]
let signal_kind = SignalKind::from(&signal);
let res = match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.send(signal).await,
MailboxSenderInner::Unbounded(tx) => tx.send(signal),
};
#[cfg(feature = "metrics")]
if res.is_ok() {
signal_kind.apply_metric(self);
}
res
}
/// Attempts to immediately send a message on this `Sender`.
/// Unbounded mailboxes will always have capacity.
///
/// See tokio's [`mpsc::Sender::try_send`] and [`mpsc::UnboundedSender::send`] docs for more info.
///
/// [`mpsc::Sender::try_send`]: tokio::sync::mpsc::Sender::try_send
/// [`mpsc::UnboundedSender::send`]: tokio::sync::mpsc::UnboundedSender::send
#[allow(clippy::result_large_err)]
pub fn try_send(&self, signal: Signal<A>) -> Result<(), mpsc::error::TrySendError<Signal<A>>> {
#[cfg(feature = "metrics")]
let signal_kind = SignalKind::from(&signal);
let res = match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.try_send(signal),
MailboxSenderInner::Unbounded(tx) => tx
.send(signal)
.map_err(|err| mpsc::error::TrySendError::Closed(err.0)),
};
#[cfg(feature = "metrics")]
if res.is_ok() {
signal_kind.apply_metric(self);
}
res
}
/// Sends a value, waiting until there is capacity, but only for a limited time.
/// Unbounded mailboxes will never need to wait for capacity.
///
/// See tokio's [`mpsc::Sender::try_send`] and [`mpsc::UnboundedSender::send`] docs for more info.
///
/// [`mpsc::Sender::try_send`]: tokio::sync::mpsc::Sender::try_send
/// [`mpsc::UnboundedSender::send`]: tokio::sync::mpsc::UnboundedSender::send
#[allow(clippy::result_large_err)]
pub async fn send_timeout(
&self,
signal: Signal<A>,
timeout: Duration,
) -> Result<(), mpsc::error::SendTimeoutError<Signal<A>>> {
#[cfg(feature = "metrics")]
let signal_kind = SignalKind::from(&signal);
let res = match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.send_timeout(signal, timeout).await,
MailboxSenderInner::Unbounded(tx) => tx
.send(signal)
.map_err(|err| mpsc::error::SendTimeoutError::Closed(err.0)),
};
#[cfg(feature = "metrics")]
if res.is_ok() {
signal_kind.apply_metric(self);
}
res
}
/// Blocking send to call outside of asynchronous contexts.
/// Unbounded mailboxes will never block due to unbounded capacity.
///
/// See tokio's [`mpsc::Sender::blocking_send`] and [`mpsc::UnboundedSender::send`] docs for more info.
///
/// [`mpsc::Sender::blocking_send`]: tokio::sync::mpsc::Sender::blocking_send
/// [`mpsc::UnboundedSender::send`]: tokio::sync::mpsc::UnboundedSender::send
#[allow(clippy::result_large_err)]
pub fn blocking_send(
&self,
signal: Signal<A>,
) -> Result<(), mpsc::error::SendError<Signal<A>>> {
#[cfg(feature = "metrics")]
let signal_kind = SignalKind::from(&signal);
let res = match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.blocking_send(signal),
MailboxSenderInner::Unbounded(tx) => tx.send(signal),
};
#[cfg(feature = "metrics")]
if res.is_ok() {
signal_kind.apply_metric(self);
}
res
}
/// Completes when the receiver has dropped.
///
/// See tokio's [`mpsc::Sender::closed`] and [`mpsc::UnboundedSender::closed`] docs for more info.
///
/// [`mpsc::Sender::closed`]: tokio::sync::mpsc::Sender::closed
/// [`mpsc::UnboundedSender::closed`]: tokio::sync::mpsc::UnboundedSender::closed
pub async fn closed(&self) {
match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.closed().await,
MailboxSenderInner::Unbounded(tx) => tx.closed().await,
}
}
/// Checks if the channel has been closed. This happens when the
/// [`MailboxReceiver`] is dropped, or when the [`MailboxReceiver::close`] method is
/// called.
///
/// See tokio's [`mpsc::Sender::is_closed`] and [`mpsc::UnboundedSender::is_closed`] docs for more info.
///
/// [`mpsc::Sender::is_closed`]: tokio::sync::mpsc::Sender::is_closed
/// [`mpsc::UnboundedSender::is_closed`]: tokio::sync::mpsc::UnboundedSender::is_closed
pub fn is_closed(&self) -> bool {
match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.is_closed(),
MailboxSenderInner::Unbounded(tx) => tx.is_closed(),
}
}
/// Returns `true` if senders belong to the same channel.
///
/// See tokio's [`mpsc::Sender::same_channel`] and [`mpsc::UnboundedSender::same_channel`] docs for more info.
///
/// [`mpsc::Sender::same_channel`]: tokio::sync::mpsc::Sender::same_channel
/// [`mpsc::UnboundedSender::same_channel`]: tokio::sync::mpsc::UnboundedSender::same_channel
pub fn same_channel(&self, other: &MailboxSender<A>) -> bool {
match (&self.inner, &other.inner) {
(MailboxSenderInner::Bounded(a), MailboxSenderInner::Bounded(b)) => a.same_channel(b),
(MailboxSenderInner::Bounded(_), MailboxSenderInner::Unbounded(_)) => false,
(MailboxSenderInner::Unbounded(_), MailboxSenderInner::Bounded(_)) => false,
(MailboxSenderInner::Unbounded(a), MailboxSenderInner::Unbounded(b)) => {
a.same_channel(b)
}
}
}
/// Returns the current capacity of the channel, if bounded.
/// Unbounded channels return `None`.
///
/// See tokio's [`mpsc::Sender::capacity`] docs for more info.
///
/// [`mpsc::Sender::capacity`]: tokio::sync::mpsc::Sender::capacity
pub fn capacity(&self) -> Option<usize> {
match &self.inner {
MailboxSenderInner::Bounded(tx) => Some(tx.capacity()),
MailboxSenderInner::Unbounded(_) => None,
}
}
/// Converts the `MailboxSender` to a [`WeakMailboxSender`] that does not count
/// towards RAII semantics, i.e. if all `Sender` instances of the
/// channel were dropped and only `WeakMailboxSender` instances remain,
/// the channel is closed.
///
/// See tokio's [`mpsc::Sender::downgrade`] and [`mpsc::UnboundedSender::downgrade`] docs for more info.
///
/// [`mpsc::Sender::downgrade`]: tokio::sync::mpsc::Sender::downgrade
/// [`mpsc::UnboundedSender::downgrade`]: tokio::sync::mpsc::UnboundedSender::downgrade
pub fn downgrade(&self) -> WeakMailboxSender<A> {
match &self.inner {
MailboxSenderInner::Bounded(tx) => WeakMailboxSender {
inner: WeakMailboxSenderInner::Bounded(tx.downgrade()),
#[cfg(feature = "metrics")]
messages_sent: self.messages_sent.clone(),
#[cfg(feature = "metrics")]
lifecycle_signals_sent: self.lifecycle_signals_sent.clone(),
#[cfg(feature = "metrics")]
link_died_signals_sent: self.link_died_signals_sent.clone(),
},
MailboxSenderInner::Unbounded(tx) => WeakMailboxSender {
inner: WeakMailboxSenderInner::Unbounded(tx.downgrade()),
#[cfg(feature = "metrics")]
messages_sent: self.messages_sent.clone(),
#[cfg(feature = "metrics")]
lifecycle_signals_sent: self.lifecycle_signals_sent.clone(),
#[cfg(feature = "metrics")]
link_died_signals_sent: self.link_died_signals_sent.clone(),
},
}
}
/// Returns the number of [`MailboxSender`] handles.
///
/// See tokio's [`mpsc::Sender::strong_count`] and [`mpsc::UnboundedSender::strong_count`] docs for more info.
///
/// [`mpsc::Sender::strong_count`]: tokio::sync::mpsc::Sender::strong_count
/// [`mpsc::UnboundedSender::strong_count`]: tokio::sync::mpsc::UnboundedSender::strong_count
pub fn strong_count(&self) -> usize {
match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.strong_count(),
MailboxSenderInner::Unbounded(tx) => tx.strong_count(),
}
}
/// Returns the number of [`WeakMailboxSender`] handles.
///
/// See tokio's [`mpsc::Sender::weak_count`] and [`mpsc::UnboundedSender::weak_count`] docs for more info.
///
/// [`mpsc::Sender::weak_count`]: tokio::sync::mpsc::Sender::weak_count
/// [`mpsc::UnboundedSender::weak_count`]: tokio::sync::mpsc::UnboundedSender::weak_count
pub fn weak_count(&self) -> usize {
match &self.inner {
MailboxSenderInner::Bounded(tx) => tx.weak_count(),
MailboxSenderInner::Unbounded(tx) => tx.weak_count(),
}
}
}
impl<A: Actor> Clone for MailboxSender<A> {
fn clone(&self) -> Self {
match &self.inner {
MailboxSenderInner::Bounded(tx) => MailboxSender {
inner: MailboxSenderInner::Bounded(tx.clone()),
#[cfg(feature = "metrics")]
messages_sent: self.messages_sent.clone(),
#[cfg(feature = "metrics")]
lifecycle_signals_sent: self.lifecycle_signals_sent.clone(),
#[cfg(feature = "metrics")]
link_died_signals_sent: self.link_died_signals_sent.clone(),
},
MailboxSenderInner::Unbounded(tx) => MailboxSender {
inner: MailboxSenderInner::Unbounded(tx.clone()),
#[cfg(feature = "metrics")]
messages_sent: self.messages_sent.clone(),
#[cfg(feature = "metrics")]
lifecycle_signals_sent: self.lifecycle_signals_sent.clone(),
#[cfg(feature = "metrics")]
link_died_signals_sent: self.link_died_signals_sent.clone(),
},
}
}
}
impl<A: Actor> fmt::Debug for MailboxSender<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.inner {
MailboxSenderInner::Bounded(tx) => f.debug_tuple("Bounded").field(tx).finish(),
MailboxSenderInner::Unbounded(tx) => f.debug_tuple("Unbounded").field(tx).finish(),
}
}
}
include!("mailbox/weak_sender.rs");
include!("mailbox/receiver.rs");
include!("mailbox/signal.rs");