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
use crate::*;
use async_trait::async_trait;
use std::collections::BTreeMap;
use std::marker::PhantomData;

// XXX: Use WeakMessageChannel and WeakAddress for broker

#[derive(Eq, PartialEq, PartialOrd, Ord, Copy, Clone, Hash)]
struct SubscriptionId(usize);

struct Subscribe<T>
where
    T: Message<Result = ()> + Clone,
{
    channel: Box<dyn MessageChannel<T>>,
}

struct Unsubscribe<T>
where
    T: Message<Result = ()> + Clone,
{
    id: SubscriptionId,
    _marker: PhantomData<T>,
}

struct Publish<T: Message<Result = ()> + Clone>(T);

pub struct Subscription<T>
where
    T: Message<Result = ()> + Clone,
{
    id: SubscriptionId,
    broker_addr: Address<Broker<T>>,
}

impl<T> Subscription<T>
where
    T: Message<Result = ()> + Clone,
{
    pub async fn unsubscribe(self) -> Result<(), ()> {
        let Self { id, broker_addr } = self;
        broker_addr
            .send(Unsubscribe {
                id,
                _marker: PhantomData,
            })
            .await
            .unwrap()
    }
}

impl<T> Message for Subscribe<T>
where
    T: Message<Result = ()> + Clone,
{
    type Result = Result<Subscription<T>, ()>;
}

impl<T> Message for Unsubscribe<T>
where
    T: Message<Result = ()> + Clone,
{
    type Result = Result<(), ()>;
}

impl<T> Message for Publish<T>
where
    T: Message<Result = ()> + Clone,
{
    type Result = ();
}

pub struct Broker<T>
where
    T: Message<Result = ()> + Clone,
{
    next_id: usize,
    subscriptions: BTreeMap<SubscriptionId, Box<dyn MessageChannel<T>>>,
}

impl<T> Broker<T>
where
    T: Message<Result = ()> + Clone,
{
    pub fn new() -> Self {
        Self {
            next_id: 0,
            subscriptions: BTreeMap::new(),
        }
    }

    pub async fn subscribe<A: Actor + Handler<T>>(
        subscriber: Address<A>,
    ) -> Result<Subscription<T>, ()> {
        let broker = Self::from_registry().await;
        subscriber.subscribe(broker).await
    }

    pub async fn publish(message: T) -> Result<(), xtra::Disconnected> {
        let broker = Self::from_registry().await;
        broker.publish(message).await
    }
}

impl<T> Default for Broker<T>
where
    T: Message<Result = ()> + Clone,
{
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
impl<T> Actor for Broker<T> where T: Message<Result = ()> + Clone {}

#[async_trait]
impl<T> Handler<Subscribe<T>> for Broker<T>
where
    T: Message<Result = ()> + Clone,
{
    async fn handle(
        &mut self,
        message: Subscribe<T>,
        ctx: &mut Context<Self>,
    ) -> <Subscribe<T> as Message>::Result {
        let broker_addr = ctx.address().map_err(|_| ())?;

        let id = SubscriptionId(self.next_id);
        self.next_id += 1;

        self.subscriptions.insert(id, message.channel);

        Ok(Subscription { id, broker_addr })
    }
}

#[async_trait]
impl<T> Handler<Unsubscribe<T>> for Broker<T>
where
    T: Message<Result = ()> + Clone,
{
    async fn handle(
        &mut self,
        message: Unsubscribe<T>,
        _ctx: &mut Context<Self>,
    ) -> <Unsubscribe<T> as Message>::Result {
        match self.subscriptions.remove(&message.id) {
            Some(_) => Ok(()),
            None => Err(()),
        }
    }
}

#[async_trait]
impl<T> Handler<Publish<T>> for Broker<T>
where
    T: Message<Result = ()> + Clone,
{
    async fn handle(&mut self, Publish(message): Publish<T>, _ctx: &mut Context<Self>) {
        let mut disconnected: Vec<SubscriptionId> = Vec::new();

        for (&id, subscriber) in &self.subscriptions {
            match subscriber.do_send(message.clone()) {
                Ok(()) => {}
                Err(xtra::Disconnected) => {
                    disconnected.push(id);
                }
            }
        }

        for id in disconnected {
            self.subscriptions.remove(&id);
        }
    }
}

#[async_trait]
pub trait SubscribeExt<M>
where
    M: Message<Result = ()> + Clone,
{
    async fn subscribe(&self, broker: Address<Broker<M>>) -> Result<Subscription<M>, ()>;
}

#[async_trait]
impl<T, M> SubscribeExt<M> for Address<T>
where
    T: Handler<M>,
    M: Message<Result = ()> + Clone,
{
    async fn subscribe(&self, broker: Address<Broker<M>>) -> Result<Subscription<M>, ()> {
        broker
            .send(Subscribe {
                channel: Box::new(self.clone()),
            })
            .await
            .map_err(|_| ())?
    }
}

#[async_trait]
pub trait PublishExt<M>
where
    M: Message<Result = ()> + Clone,
{
    async fn publish(&self, message: M) -> Result<(), xtra::Disconnected>;
}

#[async_trait]
impl<M> PublishExt<M> for Address<Broker<M>>
where
    M: Message<Result = ()> + Clone,
{
    async fn publish(&self, message: M) -> Result<(), xtra::Disconnected> {
        self.send(Publish(message)).await
    }
}

#[cfg(test)]
#[async_std::test]
async fn test_broker() {
    use xtra::spawn::AsyncStd;

    #[derive(Clone)]
    struct Msg {
        msg: String,
    }

    impl Message for Msg {
        type Result = ();
    }

    struct RetrieveMessages;

    impl Message for RetrieveMessages {
        type Result = Vec<String>;
    }

    struct Collector {
        messages: Vec<String>,
    }

    impl Collector {
        fn new() -> Self {
            Self { messages: vec![] }
        }
    }

    impl Actor for Collector {}

    struct SubscriberA {
        collector: Address<Collector>,
    }

    impl Actor for SubscriberA {}

    struct SubscriberB {
        collector: Address<Collector>,
    }

    impl Actor for SubscriberB {}

    #[async_trait]
    impl Handler<Msg> for Collector {
        async fn handle(&mut self, Msg { msg }: Msg, _ctx: &mut Context<Self>) {
            self.messages.push(msg);
        }
    }

    #[async_trait]
    impl Handler<RetrieveMessages> for Collector {
        async fn handle(
            &mut self,
            _: RetrieveMessages,
            _ctx: &mut Context<Self>,
        ) -> <RetrieveMessages as Message>::Result {
            let mut messages = vec![];

            std::mem::swap(&mut self.messages, &mut messages);

            messages
        }
    }

    #[async_trait]
    impl Handler<Msg> for SubscriberA {
        async fn handle(&mut self, msg: Msg, _ctx: &mut Context<Self>) {
            self.collector
                .do_send(Msg {
                    msg: format!("{} from SubscriberA", msg.msg),
                })
                .unwrap();
        }
    }

    #[async_trait]
    impl Handler<Msg> for SubscriberB {
        async fn handle(&mut self, msg: Msg, _ctx: &mut Context<Self>) {
            self.collector
                .do_send(Msg {
                    msg: format!("{} from SubscriberB", msg.msg),
                })
                .unwrap();
        }
    }

    let broker = Broker::<Msg>::new().create(None).spawn(&mut AsyncStd);
    let collector = Collector::new().create(None).spawn(&mut AsyncStd);

    let subscriber_a = SubscriberA {
        collector: collector.clone(),
    }
    .create(None)
    .spawn(&mut AsyncStd);
    let subscriber_b = SubscriberB {
        collector: collector.clone(),
    }
    .create(None)
    .spawn(&mut AsyncStd);

    // Initially empty
    assert!(collector.send(RetrieveMessages).await.unwrap().len() == 0);

    let subscription_a = subscriber_a.subscribe(broker.clone()).await.unwrap();
    let subscription_b = subscriber_b.subscribe(broker.clone()).await.unwrap();

    // ---------------------------------------------

    broker
        .publish(Msg {
            msg: "1".to_string(),
        })
        .await
        .unwrap();

    // Give enough time for the messages to be published to all receivers
    async_std::task::sleep(std::time::Duration::from_millis(100)).await;

    let msgs = collector.send(RetrieveMessages).await.unwrap();
    if msgs[0].as_str() == "1 from SubscriberA" {
        assert_eq!(
            msgs,
            vec![
                "1 from SubscriberA".to_string(),
                "1 from SubscriberB".to_string(),
            ]
        );
    } else {
        assert_eq!(
            msgs,
            vec![
                "1 from SubscriberB".to_string(),
                "1 from SubscriberA".to_string(),
            ]
        );
    }

    // ---------------------------------------------

    subscription_b.unsubscribe().await.unwrap();

    broker
        .publish(Msg {
            msg: "2".to_string(),
        })
        .await
        .unwrap();

    // Give enough time for the messages to be published to all receivers
    async_std::task::sleep(std::time::Duration::from_millis(100)).await;

    assert_eq!(
        collector.send(RetrieveMessages).await.unwrap(),
        vec!["2 from SubscriberA".to_string(),]
    );

    // ---------------------------------------------

    subscription_a.unsubscribe().await.unwrap();

    broker
        .publish(Msg {
            msg: "3".to_string(),
        })
        .await
        .unwrap();

    // Give enough time for the messages to be published to all receivers
    async_std::task::sleep(std::time::Duration::from_millis(100)).await;

    assert_eq!(
        collector.send(RetrieveMessages).await.unwrap(),
        Vec::<String>::new(),
    );
}

#[cfg(test)]
#[async_std::test]
async fn test_broker_using_registry() {
    #[derive(Clone)]
    struct Msg {
        msg: String,
    }

    impl Message for Msg {
        type Result = ();
    }

    #[derive(Default)]
    struct MyActor;

    impl Actor for MyActor {}

    #[async_trait]
    impl Handler<Msg> for MyActor {
        async fn handle(&mut self, _: Msg, _ctx: &mut Context<Self>) {}
    }

    let myactor = MyActor::from_registry().await;

    let subscription = Broker::<Msg>::subscribe(myactor).await.unwrap();

    Broker::<Msg>::publish(Msg { msg: "123".into() })
        .await
        .unwrap();

    subscription.unsubscribe().await.unwrap();
}