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
//! # PostgreSQL Disintegrate Backend Library
mod error;
mod event_store;
#[cfg(feature = "listener")]
mod listener;
mod snapshotter;

pub use crate::event_store::PgEventStore;
#[cfg(feature = "listener")]
pub use crate::listener::{PgEventListener, PgEventListenerConfig};
pub use crate::snapshotter::PgSnapshotter;
use disintegrate::{DecisionMaker, EventSourcedDecisionStateStore, NoSnapshot, WithSnapshot};
use disintegrate_serde::Serde;
pub use error::Error;

/// An alias for [`DecisionMaker`], specialized for Postgres.
pub type PgDecisionMaker<E, S, SN> =
    DecisionMaker<EventSourcedDecisionStateStore<PgEventStore<E, S>, SN>>;

/// An alias for [`WithSnapshot`], specialized for Postgres.
pub type WithPgSnapshot = WithSnapshot<PgSnapshotter>;

/// Creates a decision maker specialized for Postgres with snapshotting.
/// The `every` parameter determines the frequency of snapshot creation, indicating the number of events
/// between consecutive snapshots.
///
/// # Arguments
///
/// - `event_store`: An instance of `PgEventStore`.
/// - `every`: The frequency of snapshot creation, specified as the number of events between consecutive snapshots.
///
/// # Returns
///
/// A `PgDecisionMaker` with snapshotting configured using the provided snapshot frequency.
pub async fn decision_maker_with_snapshot<E: Clone, S: Serde<E> + Clone + Sync + Send>(
    event_store: PgEventStore<E, S>,
    every: u64,
) -> Result<PgDecisionMaker<E, S, WithPgSnapshot>, Error> {
    let pool = event_store.pool.clone();
    let snapshot = WithSnapshot::new(PgSnapshotter::new(pool, every).await?);
    Ok(DecisionMaker::new(EventSourcedDecisionStateStore::new(
        event_store,
        snapshot,
    )))
}

/// Creates a decision maker specialized for Postgres without snapshotting.
///
/// # Arguments
///
/// - `event_store`: An instance of `PgEventStore`.
///
/// # Returns
///
/// A `PgDecisionMaker` without snapshotting.
pub fn decision_maker<E: Clone, S: Serde<E> + Clone + Sync + Send>(
    event_store: PgEventStore<E, S>,
) -> PgDecisionMaker<E, S, NoSnapshot> {
    DecisionMaker::new(EventSourcedDecisionStateStore::new(event_store, NoSnapshot))
}