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
//! This crate provides a lock-free Pub/Sub event-bus inspired by the LMAX Disruptor.
//!
//! Users can configure how publishers handle slow subscribers through `WaitStrategy`
//! policies.
//!
//! Both sync and async APIs are available.
//!
//! # Examples
//!
//! Please use the provided [example programs](https://github.com/sachanganesh/eventador-rs/tree/main/examples)
//! for a more thorough approach on how to use this crate.
//!
//! Basic sync usage:
//!
//! ```
//! use eventador::Eventador;
//! let eventbus = Eventador::new(4).unwrap();
//! let subscriber = eventbus.subscribe::<usize>();
//!
//! let i: usize = 1234;
//! eventbus.publish(i);
//!
//! let mut publisher = eventbus.publisher();
//! publisher.send(i + 1111);
//!
//! let mut msg = subscriber.recv();
//! assert_eq!(i, *msg);
//!
//! msg = subscriber.recv();
//! assert_eq!(i + 1111, *msg);
//! ```
//!
//! Basic async usage:
//!
//! ```ignore
//! use eventador::{Eventador, SinkExt, StreamExt};
//! let eventbus = Eventador::new(4).unwrap();
//!
//! let mut subscriber = eventador.async_subscriber::<usize>();
//! let mut publisher = eventador.async_publisher::<usize>(4);
//!
//! let i: usize = 1234;
//! publisher.send(i).await?;
//!
//! let msg = subscriber.next().await?;
//! assert_eq!(i, *msg);
//! ```
//!
//! ## Why?
//!
//! Event-buses ease the development burden of concurrent programs by enabling concurrent
//! application subroutines to interact and affect other subroutines through events.
//!
//! Eventador embraces the Rust model of *Choose Your Guarantees &trade;* by offering different
//! policies for publishing when subscribers are lagging. These are represented as
//! [WaitStrategies](https://docs.rs/eventador/latest/eventador/enum.WaitStrategy), with the
//! default being to wait for all subscribers to read an event before it is overwritten.
//!
//! ## Design Considerations
//!
//! A general overview of the architecture of the library can be found
//! [here](https://github.com/sachanganesh/eventador-rs/blob/main/ARCHITECTURE.md).
//!
//! ### Ring Buffer
//!
//! Like Eventador, most event-bus implementations use some form of ring buffer for the underlying
//! data structure to store published events. As such, an Eventador instance cannot indefinitely
//! grow to accommodate events, unlike a `Vec`. Publishers require configurable policies to decide
//! how and when to overwrite old data in the ring.
//!
//! ### LMAX Disruptor
//!
//! The LMAX Disruptor serves as a basis for a lot of event-bus implementations, though the
//! contemporary architecture of the Disruptor looks very different from the one presented in the
//! outdated LMAX white-paper. Eventador draws from the principles of the current Disruptor
//! architecture, but the similarities stop there.
//!
//! A sequencer atomically assigns an event to an index in the ring buffer on publishing of an
//! event.
//!
//! Subscribers internally have their own sequencer to determine their last read event in the ring
//! buffer. On receiving a subscribed message, the sequencer is atomically updated to reflect that
//! it can now receive the next event.
//!
//! ### Lock-free
//!
//! Eventador has the potential to be a high-contention (aka bottlenecking) structure to a given
//! concurrent program, so the implementation needs to handle contention as effectively as possible.
//! Atomic CAS operations are generally faster than locking, and is the preferred approach to handle
//! contention.
//!
//! ### TypeId
//! This crate relies on the use of `TypeId` to determine what type an event is, and what types of
//! events a subscriber is subscribed to.
//!
//! Unfortunately, due to the limitations of Rust reflection tools, an Enum will have a different
//! TypeId than an Enum variant. This means that a subscriber must subscribe to the Enum type and
//! ignore any variants it's not interested in that it still receives. Likewise, the publisher must
//! publish events as the Enum type and not the variant in order to maintain that consistency.
//!

#![feature(doc_cfg)]

mod alertable;
mod event;
mod publisher;
mod ring_buffer;
mod sequence;
mod subscriber;
mod wait_strategy;

#[cfg(feature = "async")]
#[doc(cfg(feature = "async"))]
mod futures;

#[cfg(feature = "async")]
#[doc(cfg(feature = "async"))]
pub use crate::futures::{AsyncPublisher, AsyncSubscriber, PublishError};

#[cfg(feature = "async")]
#[doc(cfg(feature = "async"))]
pub use ::futures::{SinkExt, StreamExt};

pub use event::EventRead;
pub use publisher::Publisher;
pub use subscriber::Subscriber;
pub use wait_strategy::WaitStrategy;

use crate::ring_buffer::RingBuffer;
use crate::sequence::Sequence;
use std::sync::Arc;

/// A lock-free and thread-safe event-bus implementation.
///
/// # Example
///
/// Basic usage:
///
/// ```ignore
/// let eventbus = Eventador::new(4)?;
/// let subscriber = eventbus.subscribe::<usize>();
///
/// let mut i: usize = 1234;
/// eventbus.publish(i);
///
/// let mut msg = subscriber.recv();
/// assert_eq!(i, *msg);
/// ```
///
#[derive(Clone)]
pub struct Eventador {
    ring: Arc<RingBuffer>,
}

impl Eventador {
    /// Creates a new Eventador event-bus.
    ///
    /// **The capacity is required to be a power of 2.**
    ///
    /// This uses the default wait-strategy of [`WaitStrategy::AllSubscribers`], which will ensure
    /// a publisher can't overwrite an event in the ring until all subscribers have read it.
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4)?;
    /// ```
    ///
    pub fn new(capacity: u64) -> anyhow::Result<Self> {
        Ok(Self {
            ring: Arc::new(RingBuffer::new(capacity, WaitStrategy::AllSubscribers)?),
        })
    }

    /// Creates a new Eventador event-bus with a specific [`WaitStrategy`] for publishers.
    ///
    /// **The capacity is required to be a power of 2.**
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4, WaitStrategy::AllSubscribers)?;
    /// ```
    ///
    pub fn with_strategy(capacity: u64, wait_strategy: WaitStrategy) -> anyhow::Result<Self> {
        Ok(Self {
            ring: Arc::new(RingBuffer::new(capacity, wait_strategy)?),
        })
    }

    /// Synchronously publish an event to the event-bus.
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4)?;
    ///
    /// let i: usize = 1234;
    /// eventbus.publish(i);
    /// ```
    ///
    pub fn publish<T: 'static + Send + Sync>(&self, message: T) {
        let sequence = self.ring.next();

        if let Some(event_store) = self.ring.get_envelope(sequence).clone() {
            event_store.overwrite::<T>(sequence, message);
        }
    }

    /// Creates a [`Publisher`] that synchronously publishes messages on the event-bus.
    ///
    /// Although the [`Eventador::publish`] function has the exact same behavior, this handle offers
    /// an API that mirrors the `AsyncPublisher`.
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4)?;
    /// let mut publisher = eventbus.publisher();
    ///
    /// let i: usize = 1234;
    /// publisher.send(i);
    /// ```
    ///
    pub fn publisher(&self) -> Publisher {
        Publisher::new(self.ring.clone())
    }

    /// Creates a [`Subscriber`] that subscribes to an event type receives them synchronously.
    ///
    /// The [`Subscriber`] will not receive subscribed events that were published to the event-bus
    /// before time of subscription. It will only receive events that are published after
    /// time of subscription.
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4)?;
    ///
    /// // subscribe first, before publishing!
    /// let subscriber = eventbus.subscribe::<usize>();
    ///
    /// let mut i: usize = 1234;
    /// eventbus.publish(i);
    ///
    /// let mut msg = subscriber.recv();
    /// assert_eq!(i, *msg);
    /// ```
    ///
    pub fn subscribe<T: 'static + Send>(&self) -> Subscriber<T> {
        let sequence = Arc::new(Sequence::with_value(self.ring.sequencer().get() + 1));

        self.ring
            .sequencer()
            .register_gating_sequence(sequence.clone());

        Subscriber::new(self.ring.clone(), sequence)
    }

    /// Creates an [`AsyncPublisher`] that can publish to the event-bus asynchronously.
    ///
    /// The buffer size indicates the number of events that can be buffered until a flush is made
    /// to the event bus. Until events are flushed to the event bus, they are not yet published.
    ///
    /// Because events are buffered, an AsyncPublisher can only publish events of the same
    /// type. A new AsyncPublisher must be instantiated for events of another type.
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4)?;
    /// let mut publisher: AsyncPublisher<usize> = eventbus.async_publisher(10);
    ///
    /// let mut i: usize = 1234;
    /// publisher.send(i).await?;
    /// ```
    ///
    #[cfg(feature = "async")]
    #[doc(cfg(feature = "async"))]
    pub fn async_publisher<T: 'static + Send + Sync + Unpin>(
        &self,
        buffer_size: usize,
    ) -> AsyncPublisher<T> {
        AsyncPublisher::new(self.ring.clone(), buffer_size)
    }

    /// Creates an [`AsyncSubscriber`] that subscribes to an event type and receive them
    /// asynchronously.
    ///
    /// # Example
    ///
    /// Basic usage:
    ///
    /// ```ignore
    /// let eventbus = Eventador::new(4)?;
    ///
    /// let subscriber = eventbus.async_subscriber::<usize>();
    /// let mut publisher: AsyncPublisher<usize> = eventbus.async_publisher();
    ///
    /// let mut i: usize = 1234;
    /// publisher.send(i).await?;
    ///
    /// let mut msg = subscriber.next().await.unwrap();
    /// assert_eq!(i, *msg);
    /// ```
    ///
    #[cfg(feature = "async")]
    #[doc(cfg(feature = "async"))]
    pub fn async_subscriber<T: Send + Unpin>(&self) -> AsyncSubscriber<T> {
        let sequence = Arc::new(Sequence::with_value(self.ring.sequencer().get() + 1));
        self.ring
            .sequencer()
            .register_gating_sequence(sequence.clone());

        AsyncSubscriber::new(self.ring.clone(), sequence)
    }
}

impl From<RingBuffer> for Eventador {
    fn from(ring: RingBuffer) -> Self {
        Self {
            ring: Arc::new(ring),
        }
    }
}

impl From<Arc<RingBuffer>> for Eventador {
    fn from(ring: Arc<RingBuffer>) -> Self {
        Self { ring }
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "async")]
    use crate::futures::publisher::{AsyncPublisher, PublishError};

    #[cfg(feature = "async")]
    use futures::{
        future::{AbortHandle, Abortable},
        SinkExt, StreamExt,
    };

    #[cfg(feature = "async")]
    use async_channel::unbounded;

    #[cfg(feature = "async")]
    use ntest::timeout;

    use crate::Eventador;

    #[test]
    fn publish_and_subscribe() {
        let res = Eventador::new(2);
        assert!(res.is_ok());

        let eventador: Eventador = res.unwrap();

        let subscriber = eventador.subscribe::<usize>();
        assert_eq!(1, subscriber.sequence());

        let mut i: usize = 1234;
        eventador.publish(i);

        let mut msg = subscriber.recv();
        assert_eq!(i, *msg);

        i += 1111;
        let eventador2 = eventador.clone();

        std::thread::spawn(move || {
            std::thread::sleep(std::time::Duration::from_secs(1));
            eventador2.publish(i);
        });

        msg = subscriber.recv();
        assert_eq!(i, *msg);
    }

    #[async_std::test]
    #[timeout(5000)]
    #[cfg(feature = "async")]
    async fn async_publish() {
        println!("Starting test!");
        let res = Eventador::new(4);
        assert!(res.is_ok());

        let eventador: Eventador = res.unwrap();

        let mut subscriber = eventador.async_subscriber::<usize>();
        let mut publisher: AsyncPublisher<usize> = eventador.async_publisher(4);

        let (sender, mut receiver) = unbounded::<Result<usize, PublishError>>();

        let mut i: usize = 1234;
        let mut sent = sender.send(Ok(i)).await;
        assert!(sent.is_ok());

        let (handle, reg) = AbortHandle::new_pair();
        async_std::task::spawn(Abortable::new(
            async move {
                publisher.send_all(&mut receiver).await.unwrap();
            },
            reg,
        ));

        let mut msg = subscriber.next().await.unwrap();
        assert_eq!(i, *msg);
        println!("Passed part 1!");

        i += 1111;
        let eventador2 = eventador.clone();

        async_std::task::spawn(async move {
            async_std::task::sleep(std::time::Duration::from_secs(1)).await;
            eventador2.publish(i);
        });

        msg = subscriber.next().await.unwrap();
        assert_eq!(i, *msg);
        println!("Passed part 2!");

        i += 1111;
        sent = sender.send(Ok(i)).await;
        assert!(sent.is_ok());

        msg = subscriber.next().await.unwrap();
        assert_eq!(i, *msg);
        println!("Passed part 3! Done.");

        handle.abort();
    }

    #[derive(Debug, Eq, PartialEq)]
    enum TestEnum {
        SampleA,
    }

    #[test]
    fn enum_specific_subscription() {
        let res = Eventador::new(4);
        assert!(res.is_ok());
        println!("Passed part 1!");

        let eventador: Eventador = res.unwrap();

        let subscriber = eventador.subscribe::<TestEnum>();
        assert_eq!(1, subscriber.sequence());
        println!("Passed part 2!");

        eventador.publish(TestEnum::SampleA);

        let msg = subscriber.recv();
        assert_eq!(TestEnum::SampleA, *msg);
        println!("Passed part 3! Done.");
    }
}