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
//! A message channel is a channel through which you can send only one kind of message, but to
//! any actor that can handle it. It is like [`Address`], but associated with
//! the message type rather than the actor type.

use std::fmt;

use crate::address::{ActorJoinHandle, Address};
use crate::chan::RefCounter;
use crate::refcount::{Either, Strong, Weak};
use crate::send_future::{ActorErasedSending, ResolveToHandlerReturn, SendFuture};
use crate::Handler;

/// A message channel is a channel through which you can send only one kind of message, but to
/// any actor that can handle it. It is like [`Address`], but associated with the message type rather
/// than the actor type.
///
/// # Example
///
/// ```rust
/// # use xtra::prelude::*;
/// struct WhatsYourName;
///
/// struct Alice;
/// struct Bob;
///
/// impl Actor for Alice {
///     type Stop = ();
///     async fn stopped(self) {
///         println!("Oh no");
///     }
/// }
/// #  impl Actor for Bob {type Stop = (); async fn stopped(self) -> Self::Stop {} }
///
/// impl Handler<WhatsYourName> for Alice {
///     type Return = &'static str;
///
///     async fn handle(&mut self, _: WhatsYourName, _ctx: &mut Context<Self>) -> Self::Return {
///         "Alice"
///     }
/// }
///
/// impl Handler<WhatsYourName> for Bob {
///     type Return = &'static str;
///
///     async fn handle(&mut self, _: WhatsYourName, _ctx: &mut Context<Self>) -> Self::Return {
///         "Bob"
///     }
/// }
///
/// fn main() {
/// # #[cfg(feature = "smol")]
/// smol::block_on(async {
///         let alice = xtra::spawn_smol(Alice, Mailbox::unbounded());
///         let bob = xtra::spawn_smol(Bob, Mailbox::unbounded());
///
///         let channels = [
///             MessageChannel::new(alice),
///             MessageChannel::new(bob)
///         ];
///         let name = ["Alice", "Bob"];
///
///         for (channel, name) in channels.iter().zip(&name) {
///             assert_eq!(*name, channel.send(WhatsYourName).await.unwrap());
///         }
///     })
/// }
/// ```
pub struct MessageChannel<M, R, Rc = Strong> {
    inner: Box<dyn MessageChannelTrait<M, Rc, Return = R> + Send + Sync + 'static>,
}

impl<M, Rc, R> MessageChannel<M, R, Rc>
where
    M: Send + 'static,
    R: Send + 'static,
{
    /// Construct a new [`MessageChannel`] from the given [`Address`].
    ///
    /// The actor behind the [`Address`] must implement the [`Handler`] trait for the message type.
    pub fn new<A>(address: Address<A, Rc>) -> Self
    where
        A: Handler<M, Return = R>,
        Rc: RefCounter + Into<Either>,
    {
        Self {
            inner: Box::new(address),
        }
    }

    /// Returns whether the actor referred to by this message channel is running and accepting messages.
    pub fn is_connected(&self) -> bool {
        self.inner.is_connected()
    }

    /// Returns the number of messages in the actor's mailbox.
    ///
    /// Note that this does **not** differentiate between types of messages; it will return the
    /// count of all messages in the actor's mailbox, not only the messages sent by this
    /// [`MessageChannel`].
    pub fn len(&self) -> usize {
        self.inner.len()
    }

    /// The total capacity of the actor's mailbox.
    ///
    /// Note that this does **not** differentiate between types of messages; it will return the
    /// total capacity of actor's mailbox, not only the messages sent by this [`MessageChannel`].
    pub fn capacity(&self) -> Option<usize> {
        self.inner.capacity()
    }

    /// Returns whether the actor's mailbox is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Send a message to the actor.
    ///
    /// This function returns a [`Future`](SendFuture) that resolves to the [`Return`](crate::Handler::Return) value of the handler.
    /// The [`SendFuture`] will resolve to [`Err(Disconnected)`] in case the actor is stopped and not accepting messages.
    pub fn send(&self, message: M) -> SendFuture<ActorErasedSending, ResolveToHandlerReturn<R>> {
        self.inner.send(message)
    }

    /// Waits until this [`MessageChannel`] becomes disconnected.
    pub fn join(&self) -> ActorJoinHandle {
        self.inner.join()
    }

    /// Determines whether this and the other [`MessageChannel`] address the same actor mailbox.
    pub fn same_actor<Rc2>(&self, other: &MessageChannel<M, R, Rc2>) -> bool
    where
        Rc2: Send + 'static,
    {
        self.inner.to_inner_ptr() == other.inner.to_inner_ptr()
    }
}

#[cfg(feature = "sink")]
impl<M, Rc> MessageChannel<M, (), Rc>
where
    M: Send + 'static,
{
    /// Construct a [`Sink`] from this [`MessageChannel`].
    ///
    /// Sending an item into a [`Sink`]s does not return a value. Consequently, this function is
    /// only available on [`MessageChannel`]s with a return value of `()`.
    ///
    /// To create such a [`MessageChannel`] use an [`Address`] that points to an actor where the
    /// [`Handler`] of a given message has [`Return`](Handler::Return) set to `()`.
    ///
    /// The provided [`Sink`] will process one message at a time completely and thus enforces
    /// back-pressure according to the bounds of the actor's mailbox.
    ///
    /// [`Sink`]: futures_sink::Sink
    pub fn into_sink(self) -> impl futures_sink::Sink<M, Error = crate::Error> {
        futures_util::sink::unfold((), move |(), message| self.send(message))
    }
}

impl<A, M, R, Rc> From<Address<A, Rc>> for MessageChannel<M, R, Rc>
where
    A: Handler<M, Return = R>,
    R: Send + 'static,
    M: Send + 'static,
    Rc: RefCounter + Into<Either>,
{
    fn from(address: Address<A, Rc>) -> Self {
        MessageChannel::new(address)
    }
}

impl<M, R, Rc> fmt::Debug for MessageChannel<M, R, Rc>
where
    R: Send + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let actor_type = self.inner.actor_type();
        let message_type = &std::any::type_name::<M>();
        let return_type = &std::any::type_name::<R>();
        let rc_type = &std::any::type_name::<Rc>()
            .replace("xtra::chan::ptr::", "")
            .replace("Tx", "");

        f.debug_struct(&format!(
            "MessageChannel<{}, {}, {}, {}>",
            actor_type, message_type, return_type, rc_type
        ))
        .field("addresses", &self.inner.sender_count())
        .field("mailboxes", &self.inner.receiver_count())
        .finish()
    }
}

/// Determines whether this and the other message channel address the same actor mailbox **and**
/// they have reference count type equality. This means that this will only return true if
/// [`MessageChannel::same_actor`] returns true **and** if they both have weak or strong reference
/// counts. [`Either`] will compare as whichever reference count type it wraps.
impl<M, R, Rc> PartialEq for MessageChannel<M, R, Rc>
where
    M: Send + 'static,
    R: Send + 'static,
    Rc: Send + 'static,
{
    fn eq(&self, other: &Self) -> bool {
        self.same_actor(other) && (self.inner.is_strong() == other.inner.is_strong())
    }
}

impl<M, R, Rc> Clone for MessageChannel<M, R, Rc>
where
    R: Send + 'static,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone_channel(),
        }
    }
}

impl<M, R> MessageChannel<M, R, Strong>
where
    M: Send + 'static,
    R: Send + 'static,
{
    /// Downgrade this [`MessageChannel`] to a [`Weak`] reference count.
    pub fn downgrade(&self) -> MessageChannel<M, R, Weak> {
        MessageChannel {
            inner: self.inner.to_weak(),
        }
    }
}

impl<M, R> MessageChannel<M, R, Either>
where
    M: Send + 'static,
    R: Send + 'static,
{
    /// Downgrade this [`MessageChannel`] to a [`Weak`] reference count.
    pub fn downgrade(&self) -> MessageChannel<M, R, Weak> {
        MessageChannel {
            inner: self.inner.to_weak(),
        }
    }
}

/// Functions which apply to any kind of [`MessageChannel`], be they strong or weak.
impl<M, R, Rc> MessageChannel<M, R, Rc>
where
    M: Send + 'static,
    R: Send + 'static,
{
    /// Convert this [`MessageChannel`] to allow [`Either`] reference counts.
    pub fn as_either(&self) -> MessageChannel<M, R, Either> {
        MessageChannel {
            inner: self.inner.to_either(),
        }
    }
}

trait MessageChannelTrait<M, Rc> {
    type Return: Send + 'static;

    fn is_connected(&self) -> bool;

    fn len(&self) -> usize;

    fn capacity(&self) -> Option<usize>;

    fn send(
        &self,
        message: M,
    ) -> SendFuture<ActorErasedSending, ResolveToHandlerReturn<Self::Return>>;

    fn clone_channel(
        &self,
    ) -> Box<dyn MessageChannelTrait<M, Rc, Return = Self::Return> + Send + Sync + 'static>;

    fn join(&self) -> ActorJoinHandle;

    fn to_inner_ptr(&self) -> *const ();

    fn is_strong(&self) -> bool;

    fn to_weak(
        &self,
    ) -> Box<dyn MessageChannelTrait<M, Weak, Return = Self::Return> + Send + Sync + 'static>;

    fn sender_count(&self) -> usize;

    fn receiver_count(&self) -> usize;

    fn actor_type(&self) -> &str;

    fn to_either(
        &self,
    ) -> Box<dyn MessageChannelTrait<M, Either, Return = Self::Return> + Send + Sync + 'static>;
}

impl<A, R, M, Rc: RefCounter> MessageChannelTrait<M, Rc> for Address<A, Rc>
where
    A: Handler<M, Return = R>,
    M: Send + 'static,
    R: Send + 'static,
    Rc: Into<Either>,
{
    type Return = R;

    fn is_connected(&self) -> bool {
        self.is_connected()
    }

    fn len(&self) -> usize {
        self.len()
    }

    fn capacity(&self) -> Option<usize> {
        self.capacity()
    }

    fn send(&self, message: M) -> SendFuture<ActorErasedSending, ResolveToHandlerReturn<R>> {
        SendFuture::sending_erased(message, self.0.clone())
    }

    fn clone_channel(
        &self,
    ) -> Box<dyn MessageChannelTrait<M, Rc, Return = Self::Return> + Send + Sync + 'static> {
        Box::new(self.clone())
    }

    fn join(&self) -> ActorJoinHandle {
        self.join()
    }

    fn to_inner_ptr(&self) -> *const () {
        self.0.inner_ptr()
    }

    fn is_strong(&self) -> bool {
        self.0.is_strong()
    }

    fn to_weak(
        &self,
    ) -> Box<dyn MessageChannelTrait<M, Weak, Return = Self::Return> + Send + Sync + 'static> {
        Box::new(Address(self.0.to_tx_weak()))
    }

    fn sender_count(&self) -> usize {
        self.0.sender_count()
    }

    fn receiver_count(&self) -> usize {
        self.0.receiver_count()
    }

    fn actor_type(&self) -> &str {
        std::any::type_name::<A>()
    }

    fn to_either(
        &self,
    ) -> Box<dyn MessageChannelTrait<M, Either, Return = Self::Return> + Send + Sync + 'static>
    where
        Rc: RefCounter + Into<Either>,
    {
        Box::new(Address(self.0.to_tx_either()))
    }
}