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
//! [`eventually`] type implementations for PostgreSQL.
//!
//! ## Event Store
//!
//! This crate includes an [`EventStore`] implementation using PostgreSQL
//! as backend data source.
//!
//! Example usage:
//!
//! ```no_run
//! # use std::sync::Arc;
//! # use tokio::sync::RwLock;
//! # use eventually_postgres::EventStoreBuilder;
//! #
//! # async fn dox() -> Result<(), Box<dyn std::error::Error>> {
//! // Open a connection with Postgres.
//! let (client, connection) =
//!     tokio_postgres::connect("postgres://user@pass:localhost:5432/db", tokio_postgres::NoTls)
//!         .await
//!         .map_err(|err| {
//!             eprintln!("failed to connect to Postgres: {}", err);
//!             err
//!         })?;
//!
//! // The connection, responsible for the actual IO, must be handled by a different
//! // execution context.
//! tokio::spawn(async move {
//!     if let Err(e) = connection.await {
//!         eprintln!("connection error: {}", e);
//!     }
//! });
//!
//! // A domain event example -- it is deliberately simple.
//! #[derive(Debug, Clone)]
//! struct SomeEvent;
//!
//! // Use an EventStoreBuilder to build multiple EventStore instances.
//! let builder = EventStoreBuilder::from(Arc::new(RwLock::new(client)));
//!
//! // Events should be versioned to be used with the Postgres Event Store.
//! use eventually::versioned::Versioned;
//!
//! // Event store for the events.
//! let store = {
//!     let store = builder.event_stream::<String, Versioned<SomeEvent>>("orders");
//!     store.create_stream().await?;
//!     store
//! };
//!
//! # Ok(())
//! # }
//! ```
//!
//! [`eventually`]: https://docs.rs/eventually
//! [`EventStore`]: struct.EventStore.html

use std::sync::Arc;

use eventually::store::EventStream;
use eventually::versioned::Versioned;
use eventually::{Aggregate, AggregateId};

use futures::future::BoxFuture;
use futures::stream::{StreamExt, TryStreamExt};

use serde::{Deserialize, Serialize};

use tokio::sync::RwLock;

use tokio_postgres::types::ToSql;
use tokio_postgres::{Client, Error};

/// Builder type for [`EventStore`] instances.
///
/// [`EventStore`]: struct.EventStore.html
pub struct EventStoreBuilder(Arc<RwLock<Client>>);

impl From<Arc<RwLock<Client>>> for EventStoreBuilder {
    #[inline]
    fn from(client: Arc<RwLock<Client>>) -> Self {
        EventStoreBuilder(client.clone())
    }
}

impl EventStoreBuilder {
    /// Creates a new [`EventStore`] instance using the specified stream name
    /// as the Postgres backend table.
    ///
    /// [`EventStore`]: struct.EventStore.html
    #[inline]
    pub fn event_stream<Id, Event>(&self, name: &'static str) -> EventStore<Id, Event> {
        EventStore {
            client: self.0.clone(),
            table_name: name,
            id: std::marker::PhantomData,
            payload: std::marker::PhantomData,
            append_query: format!(
                "INSERT INTO {} (aggregate_id, event, version, \"offset\")
                VALUES ($1, $2, $3, $4)",
                name
            ),
            stream_query: format!(
                "SELECT * FROM {}
                WHERE aggregate_id = $1 AND version >= $2
                ORDER BY committed_at",
                name
            ),
            remove_query: format!("DELETE FROM {} WHERE aggregate_id = $1", name),
        }
    }

    /// Creates a new [`EventStore`] for an [`Aggregate`] type,
    /// backed by a Postgres table using the specified stream name.
    ///
    /// ## Usage
    ///
    /// ```text
    /// // Open a connection with Postgres.
    /// let (client, connection) =
    ///     tokio_postgres::connect("postgres://user@pass:localhost:5432/db", tokio_postgres::NoTls)
    ///         .await
    ///         .map_err(|err| {
    ///             eprintln!("failed to connect to Postgres: {}", err);
    ///             err
    ///         })?;
    ///
    /// // The connection, responsible for the actual IO, must be handled by a different
    /// // execution context.
    /// tokio::spawn(async move {
    ///     if let Err(e) = connection.await {
    ///         eprintln!("connection error: {}", e);
    ///     }
    /// });
    ///
    /// // Use an EventStoreBuilder to build multiple EventStore instances.
    /// let builder = EventStoreBuilder::from(Arc::new(RwLock::new(client)));
    ///
    /// // Aggregates should be versioned to be used with the Postgres Event Store.
    /// use eventually_util::versioned::AggregateExt;
    /// let aggregate = SomeAggregate.versioned();
    ///
    /// // Event store for the events.
    /// let store = {
    ///     let store = builder.aggregate_stream(&aggregate, "orders");
    ///     store.create_stream().await?;
    ///     store
    /// };
    /// ```
    ///
    /// [`EventStore`]: struct.EventStore.html
    /// [`Aggregate`]: ../../eventually_core/aggregate/trait.Aggregate.html
    #[inline]
    pub fn aggregate_stream<T>(
        &self,
        _: &T,
        name: &'static str,
    ) -> EventStore<AggregateId<T>, T::Event>
    where
        T: Aggregate,
    {
        self.event_stream::<AggregateId<T>, T::Event>(name)
    }
}

/// [`EventStore`] implementation using a PostgreSQL backend.
///
/// This implementation uses `tokio-postgres` crate to interface with Postgres.
///
/// Check out [`EventStoreBuilder`] for examples to how initialize new
/// instances of this type.
///
/// [`EventStore`]: ../../eventually_core/store/trait.EventStore.html
/// [`EventStoreBuilder`]: ../../eventually_core/store/trait.EventStoreBuilder.html
#[derive(Debug, Clone)]
pub struct EventStore<Id, Event> {
    client: Arc<RwLock<Client>>,
    table_name: &'static str,
    id: std::marker::PhantomData<Id>,
    payload: std::marker::PhantomData<Event>,

    append_query: String,
    stream_query: String,
    remove_query: String,
}

impl<Id, Event> EventStore<Id, Event>
where
    Id: ToString + Eq + Send + Sync,
{
    /// Creates a new table in the database for the provided Stream name
    /// during initialization.
    ///
    /// Check out [`EventStoreBuilder`] for more information.
    ///
    /// [`EventStoreBuilder`]: ../../eventually_core/store/trait.EventStoreBuilder.html
    pub async fn create_stream(&self) -> Result<(), Error> {
        let query = format!(
            "CREATE TABLE IF NOT EXISTS {table_name} (
                event_id SERIAL PRIMARY KEY,
                committed_at TIMESTAMP WITH TIME ZONE DEFAULT current_timestamp,
                aggregate_id VARCHAR NOT NULL,
                version OID NOT NULL,
                \"offset\" OID NOT NULL,
                event JSONB NOT NULL,
                CONSTRAINT {table_name}_versioned UNIQUE (aggregate_id, version, \"offset\")
            )",
            table_name = self.table_name
        );

        self.client
            .read()
            .await
            .execute(&*query, &[])
            .await
            .map(|_| ())
    }
}

impl<Id, Event> eventually::EventStore for EventStore<Id, Versioned<Event>>
where
    Id: ToString + Eq + Send + Sync,
    Event: Serialize + Send + Sync,
    for<'de> Event: Deserialize<'de>,
{
    type SourceId = Id;
    type Offset = usize;
    type Event = Versioned<Event>;
    type Error = Error;

    fn append(
        &mut self,
        id: Self::SourceId,
        events: Vec<Self::Event>,
    ) -> BoxFuture<Result<(), Self::Error>> {
        let serialized = events
            .into_iter()
            .enumerate()
            .map(|(i, event)| {
                let version = event.version();
                serde_json::to_value(event.take()).map(|value| (i, version, value))
            })
            .collect::<Result<Vec<_>, _>>()
            .unwrap();

        Box::pin(async move {
            let mut tx = self.client.write().await;
            let tx = tx.transaction().await?;

            for (i, version, event) in serialized {
                tx.execute(
                    &*self.append_query,
                    &[&id.to_string(), &event, &version, &(i as u32)],
                )
                .await?;
            }

            tx.commit().await
        })
    }

    fn stream(
        &self,
        id: Self::SourceId,
        from: Self::Offset,
    ) -> BoxFuture<Result<EventStream<Self>, Self::Error>> {
        Box::pin(async move {
            let params: Params = &[&id.to_string(), &(from as u32)];

            Ok(self
                .client
                .read()
                .await
                .query_raw(&*self.stream_query, slice_iter(params))
                .await?
                .map_ok(|row| {
                    let event = serde_json::from_value(row.get("event")).unwrap();
                    let version: u32 = row.get("version");

                    Versioned::new(event, version)
                })
                .boxed())
        })
    }

    fn remove(&mut self, id: Self::SourceId) -> BoxFuture<Result<(), Self::Error>> {
        Box::pin(async move {
            self.client
                .read()
                .await
                .execute(&*self.remove_query, &[&id.to_string()])
                .await
                .map(|_| ())
        })
    }
}

type Params<'a> = &'a [&'a (dyn ToSql + Sync)];

#[inline]
#[allow(trivial_casts)]
fn slice_iter<'a>(s: Params<'a>) -> impl ExactSizeIterator<Item = &'a dyn ToSql> + 'a {
    s.iter().map(|s| *s as _)
}