|
| 1 | +use std::error::Error as StdError; |
| 2 | +use std::fmt::Debug; |
| 3 | +use std::sync::atomic::{AtomicU32, Ordering}; |
| 4 | +use std::sync::Arc; |
| 5 | + |
| 6 | +use eventually_core::projection::Projection; |
| 7 | +use eventually_core::store::{EventStore, Select}; |
| 8 | +use eventually_core::subscription::EventSubscriber; |
| 9 | + |
| 10 | +use futures::stream::{Stream, StreamExt, TryStreamExt}; |
| 11 | + |
| 12 | +use tokio::sync::watch::{channel, Receiver, Sender}; |
| 13 | + |
| 14 | +/// Reusable builder for multiple [`Projector`] instances. |
| 15 | +/// |
| 16 | +/// [`Projector`]: struct.Projector.html |
| 17 | +pub struct ProjectorBuilder<Store, Subscriber> { |
| 18 | + store: Arc<Store>, |
| 19 | + subscriber: Arc<Subscriber>, |
| 20 | +} |
| 21 | + |
| 22 | +impl<Store, Subscriber> ProjectorBuilder<Store, Subscriber> { |
| 23 | + /// Creates a new builder instance using the provided [`EventStore`] |
| 24 | + /// and [`EventSubscriber`]. |
| 25 | + /// |
| 26 | + /// [`EventStore`]: ../../../eventually-core/store/trait.EventStore.html |
| 27 | + /// [`EventSubscriber`]: ../../../eventually-core/subscription/trait.EventSubscriber.html |
| 28 | + pub fn new(store: Arc<Store>, subscriber: Arc<Subscriber>) -> Self { |
| 29 | + Self { store, subscriber } |
| 30 | + } |
| 31 | + |
| 32 | + /// Builds a new [`Projector`] for the [`Projection`] |
| 33 | + /// specified in the function type. |
| 34 | + /// |
| 35 | + /// [`Projector`]: struct.Projector.html |
| 36 | + /// [`Projection`]: ../../../eventually-core/projection/trait.Projection.html |
| 37 | + pub fn build<P>(&self) -> Projector<P, Store, Subscriber> |
| 38 | + where |
| 39 | + // NOTE: these bounds are required for Projector::run. |
| 40 | + P: Projection + Debug + Clone, |
| 41 | + Store: EventStore<SourceId = P::SourceId, Event = P::Event>, |
| 42 | + Subscriber: EventSubscriber<SourceId = P::SourceId, Event = P::Event>, |
| 43 | + <Store as EventStore>::Error: StdError + Send + Sync + 'static, |
| 44 | + <Subscriber as EventSubscriber>::Error: StdError + Send + Sync + 'static, |
| 45 | + { |
| 46 | + Projector::new(self.store.clone(), self.subscriber.clone()) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// A `Projector` manages the state of a single [`Projection`] |
| 51 | +/// by opening a long-running stream of all events coming from the [`EventStore`]. |
| 52 | +/// |
| 53 | +/// New instances of a `Projector` are obtainable through a [`ProjectorBuilder`] |
| 54 | +/// instance. |
| 55 | +/// |
| 56 | +/// The `Projector` will start updating the [`Projection`] state when [`run`] |
| 57 | +/// is called. |
| 58 | +/// |
| 59 | +/// At each update, the `Projector` will broadcast the latest version of the |
| 60 | +/// [`Projection`] on a `Stream` obtainable through [`watch`]. |
| 61 | +/// |
| 62 | +/// [`Projection`]: ../../../eventually-core/projection/trait.Projection.html |
| 63 | +/// [`EventStore`]: ../../../eventually-core/store/trait.EventStore.html |
| 64 | +/// [`ProjectorBuilder`]: struct.ProjectorBuilder.html |
| 65 | +/// [`run`]: struct.Projector.html#method.run |
| 66 | +/// [`watch`]: struct.Projector.html#method.watch |
| 67 | +pub struct Projector<P, Store, Subscriber> |
| 68 | +where |
| 69 | + P: Projection, |
| 70 | +{ |
| 71 | + tx: Sender<P>, |
| 72 | + rx: Receiver<P>, // Keep the receiver to be able to clone it in watch(). |
| 73 | + store: Arc<Store>, |
| 74 | + subscriber: Arc<Subscriber>, |
| 75 | + state: P, |
| 76 | + last_sequence_number: AtomicU32, |
| 77 | + projection: std::marker::PhantomData<P>, |
| 78 | +} |
| 79 | + |
| 80 | +impl<P, Store, Subscriber> Projector<P, Store, Subscriber> |
| 81 | +where |
| 82 | + P: Projection + Debug + Clone, |
| 83 | + Store: EventStore<SourceId = P::SourceId, Event = P::Event>, |
| 84 | + Subscriber: EventSubscriber<SourceId = P::SourceId, Event = P::Event>, |
| 85 | + // NOTE: these bounds are needed for anyhow::Error conversion. |
| 86 | + <Store as EventStore>::Error: StdError + Send + Sync + 'static, |
| 87 | + <Subscriber as EventSubscriber>::Error: StdError + Send + Sync + 'static, |
| 88 | +{ |
| 89 | + fn new(store: Arc<Store>, subscriber: Arc<Subscriber>) -> Self { |
| 90 | + let state: P = Default::default(); |
| 91 | + let (tx, rx) = channel(state.clone()); |
| 92 | + |
| 93 | + Self { |
| 94 | + tx, |
| 95 | + rx, |
| 96 | + store, |
| 97 | + subscriber, |
| 98 | + state, |
| 99 | + last_sequence_number: Default::default(), |
| 100 | + projection: std::marker::PhantomData, |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + /// Provides a `Stream` that receives the latest copy of the `Projection` state. |
| 105 | + pub fn watch(&self) -> impl Stream<Item = P> { |
| 106 | + self.rx.clone() |
| 107 | + } |
| 108 | + |
| 109 | + /// Starts the update of the `Projection` by processing all the events |
| 110 | + /// coming from the [`EventStore`]. |
| 111 | + /// |
| 112 | + /// [`EventStore`]: ../../../eventually-core/store/trait.EventStore.html |
| 113 | + pub async fn run(&mut self) -> anyhow::Result<()> { |
| 114 | + // Create the Subscription first, so that once the future has been resolved |
| 115 | + // we'll start receiving events right away. |
| 116 | + // |
| 117 | + // This is to avoid losing events when waiting for the one-off stream |
| 118 | + // to resolve its future. |
| 119 | + // |
| 120 | + // The impact is that we _might_ get duplicated events from the one-off stream |
| 121 | + // and the subscription stream. Luckily, we can discard those by |
| 122 | + // keeping an internal state of the last processed sequence number, |
| 123 | + // and discard all those events that are found. |
| 124 | + let subscription = self.subscriber.subscribe_all().await?; |
| 125 | + let one_off_stream = self.store.stream_all(Select::All).await?; |
| 126 | + |
| 127 | + let mut stream = one_off_stream |
| 128 | + .map_err(anyhow::Error::from) |
| 129 | + .chain(subscription.map_err(anyhow::Error::from)); |
| 130 | + |
| 131 | + while let Some(event) = stream.next().await { |
| 132 | + let event = event?; |
| 133 | + let expected_sequence_number = self.last_sequence_number.load(Ordering::SeqCst); |
| 134 | + let event_sequence_number = event.sequence_number(); |
| 135 | + |
| 136 | + if event_sequence_number < expected_sequence_number { |
| 137 | + continue; // Duplicated event detected, let's skip it. |
| 138 | + } |
| 139 | + |
| 140 | + self.state = P::project(self.state.clone(), event); |
| 141 | + |
| 142 | + self.last_sequence_number.compare_and_swap( |
| 143 | + expected_sequence_number, |
| 144 | + event_sequence_number, |
| 145 | + Ordering::SeqCst, |
| 146 | + ); |
| 147 | + |
| 148 | + // Notify watchers of the latest projection state. |
| 149 | + self.tx.broadcast(self.state.clone()).expect( |
| 150 | + "since this struct holds the original receiver, failures should not happen", |
| 151 | + ); |
| 152 | + } |
| 153 | + |
| 154 | + Ok(()) |
| 155 | + } |
| 156 | +} |
0 commit comments