Skip to main content

two_devices_one_seat/
timeline.rs

1//! The read model every place keeps: each sale, whether it holds a seat, and
2//! why not if it does not.
3//!
4//! # Why it converges
5//!
6//! The three logs hold the same events in different orders: a device holds
7//! its own sale before the other device's, central holds them in arrival
8//! order. So [`Timeline`] is written to give the same table under **any**
9//! order, and declares [`ConvergentProjection`] because that is true rather
10//! than because it is convenient (SY-20):
11//!
12//! * a sale inserts its row as `held` and never touches the status of a row
13//!   that is already there, so a refund that arrived first stays a refund;
14//! * a refund sets `refunded` whatever is there, inserting the row if the sale
15//!   has not arrived yet;
16//! * nothing is ever incremented. Seats held are counted when the view is
17//!   read, so arrival order cannot change the count.
18//!
19//! It reads only the event, never its position (local to each store) and
20//! never state of its own. The price is that it cannot say *when*: a
21//! convergent fold has no clock every replica agrees on, so the rows print in
22//! an order every replica shares (refunds last, then by sale id) rather than
23//! in time order.
24
25use happenstance::{ConvergentProjection, Delivered, Projection, ProjectionId, Tags};
26use happenstance_sqlite::projection_store::{
27    SqliteBatch, SqliteProjectionStore, SqliteProjectionStoreError,
28};
29use rusqlite::Connection;
30use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, Value, ValueRef};
31
32use crate::domain::{BoxOffice, Place, ShowId};
33
34/// The read model's two tables, created by the application: the projection
35/// store migrates its checkpoint and nothing else.
36///
37/// A sale's row is keyed by its show as well as its id, because a [`SaleId`]
38/// counts sales within one show: a second show's first tablet sale would be
39/// `tablet-1` too.
40///
41/// [`SaleId`]: crate::SaleId
42pub(crate) const DDL: &str = "
43CREATE TABLE IF NOT EXISTS show_seats (
44    show     TEXT PRIMARY KEY,
45    capacity INTEGER NOT NULL
46) STRICT;
47CREATE TABLE IF NOT EXISTS seat_ledger (
48    show    TEXT NOT NULL,
49    sale    TEXT NOT NULL,
50    buyer   TEXT,
51    sold_by TEXT,
52    status  TEXT NOT NULL CHECK (status IN ('held', 'refunded')),
53    reason  TEXT,
54    PRIMARY KEY (show, sale)
55) STRICT;
56";
57
58/// The projection's name, validated by the compiler.
59const SEAT_TIMELINE: ProjectionId = ProjectionId::from_static("seat_timeline");
60
61/// The read model's projection, over one show.
62#[derive(Debug)]
63pub struct Timeline {
64    id: ProjectionId,
65    scope: Tags,
66}
67
68impl Timeline {
69    /// The projection over `show`'s events.
70    #[must_use]
71    pub fn new(show: &ShowId) -> Self {
72        Self {
73            id: SEAT_TIMELINE,
74            scope: show.scope(),
75        }
76    }
77}
78
79impl Projection for Timeline {
80    type Event = BoxOffice;
81    type Store = SqliteProjectionStore;
82    type Error = SqliteProjectionStoreError;
83
84    fn id(&self) -> &ProjectionId {
85        &self.id
86    }
87
88    fn scope(&self) -> &Tags {
89        &self.scope
90    }
91
92    async fn apply(
93        &mut self,
94        event: Delivered<BoxOffice>,
95        batch: &mut SqliteBatch,
96    ) -> Result<(), SqliteProjectionStoreError> {
97        match event.into_event() {
98            BoxOffice::ShowScheduled { show, capacity } => batch.push(
99                "INSERT INTO show_seats (show, capacity) VALUES (?1, ?2) \
100                 ON CONFLICT (show) DO NOTHING",
101                [Value::Text(show.into()), Value::Integer(capacity.into())],
102            ),
103            BoxOffice::SeatSold {
104                show,
105                sale,
106                buyer,
107                sold_by,
108            } => batch.push(
109                "INSERT INTO seat_ledger (show, sale, buyer, sold_by, status) \
110                 VALUES (?1, ?2, ?3, ?4, 'held') \
111                 ON CONFLICT (show, sale) DO UPDATE \
112                 SET buyer = excluded.buyer, sold_by = excluded.sold_by",
113                [
114                    Value::Text(show.into()),
115                    Value::Text(sale.into_string()),
116                    Value::Text(buyer),
117                    Value::Text(sold_by.as_str().to_owned()),
118                ],
119            ),
120            BoxOffice::SaleRefunded { show, sale, reason } => batch.push(
121                "INSERT INTO seat_ledger (show, sale, status, reason) \
122                 VALUES (?1, ?2, 'refunded', ?3) \
123                 ON CONFLICT (show, sale) DO UPDATE \
124                 SET status = 'refunded', reason = excluded.reason",
125                [
126                    Value::Text(show.into()),
127                    Value::Text(sale.into_string()),
128                    Value::Text(reason.to_string()),
129                ],
130            ),
131        }
132        Ok(())
133    }
134}
135
136/// True of [`Timeline`] by construction, as the module says.
137impl ConvergentProjection for Timeline {}
138
139/// Whether a sale holds its seat.
140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141pub enum Status {
142    /// It does.
143    Held,
144    /// It was refunded.
145    Refunded,
146}
147
148impl FromSql for Status {
149    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
150        match value.as_str()? {
151            "held" => Ok(Self::Held),
152            "refunded" => Ok(Self::Refunded),
153            _ => Err(FromSqlError::InvalidType),
154        }
155    }
156}
157
158impl FromSql for Place {
159    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
160        value
161            .as_str()?
162            .parse()
163            .map_err(|error| FromSqlError::Other(Box::new(error)))
164    }
165}
166
167/// One sale, as the read model holds it.
168#[derive(Debug, Clone, PartialEq, Eq)]
169pub struct Row {
170    /// Which sale.
171    pub sale: String,
172    /// Who bought it; `None` only while a refund has arrived ahead of its sale.
173    pub buyer: Option<String>,
174    /// Where it was sold, likewise.
175    pub sold_by: Option<Place>,
176    /// Whether it holds its seat.
177    pub status: Status,
178    /// Why it was refunded, if it was.
179    pub reason: Option<String>,
180}
181
182/// The read model as one place holds it.
183#[derive(Debug, Clone, PartialEq, Eq)]
184pub struct TimelineView {
185    /// The show's capacity, once scheduled.
186    pub capacity: Option<u32>,
187    /// Every sale, refunds last, then by sale id.
188    pub rows: Vec<Row>,
189}
190
191impl TimelineView {
192    /// Reads `show`'s view through the application's own connection.
193    ///
194    /// Both tables are keyed by show, so both reads name it: a file that
195    /// holds a second show holds its rows in the same tables.
196    ///
197    /// # Errors
198    ///
199    /// The driver's error, if a table is missing or a row does not decode.
200    pub fn read(app: &Connection, show: &ShowId) -> rusqlite::Result<Self> {
201        let capacity = app
202            .prepare("SELECT capacity FROM show_seats WHERE show = ?1")?
203            .query_map([show.as_str()], |row| row.get::<_, u32>(0))?
204            .next()
205            .transpose()?;
206        let rows = app
207            .prepare(
208                "SELECT sale, buyer, sold_by, status, reason FROM seat_ledger \
209                 WHERE show = ?1 ORDER BY status = 'refunded', sale",
210            )?
211            .query_map([show.as_str()], |row| {
212                Ok(Row {
213                    sale: row.get(0)?,
214                    buyer: row.get(1)?,
215                    sold_by: row.get(2)?,
216                    status: row.get(3)?,
217                    reason: row.get(4)?,
218                })
219            })?
220            .collect::<rusqlite::Result<_>>()?;
221        Ok(Self { capacity, rows })
222    }
223
224    /// Seats held, counted now rather than kept as a running total. Every
225    /// count here saturates at `u32::MAX`, which no show reaches.
226    #[must_use]
227    pub fn held(&self) -> u32 {
228        self.count(Status::Held)
229    }
230
231    /// Sales refunded.
232    #[must_use]
233    pub fn refunds(&self) -> u32 {
234        self.count(Status::Refunded)
235    }
236
237    /// Every sale the view knows of, refunded or not.
238    #[must_use]
239    pub fn sales(&self) -> u32 {
240        u32::try_from(self.rows.len()).unwrap_or(u32::MAX)
241    }
242
243    fn count(&self, status: Status) -> u32 {
244        let n = self.rows.iter().filter(|row| row.status == status).count();
245        u32::try_from(n).unwrap_or(u32::MAX)
246    }
247}
248
249#[cfg(test)]
250mod tests;