Skip to main content

tickets_over_http/
lib.rs

1//! The domain two processes share, and the protocol they speak.
2//!
3//! One of two examples in the workspace with a library target (the other is
4//! `two-devices-one-seat`), and here the reason is the subject: an API process
5//! and a projection runner have to agree about a domain, and the only way to be
6//! certain they do is for there to be one copy of it. A `src/main.rs` has
7//! nothing importable in it, which is why the other examples' tests restate
8//! their domains with `include_str!` assertions instead of using them.
9//!
10//! See `src/bin/tickets-demo.rs` for what the two processes are made to do.
11
12pub mod http;
13
14use std::path::Path;
15
16use happenstance::bytes::Bytes;
17use happenstance::{
18    Checkpoint, Codec, CodecError, CommandError, CommandOutcome, DecisionModel, Delivered,
19    DomainEvent, EventType, InvalidTag, Projection, ProjectionId, ProjectionStore, Retry,
20    SequencePosition, Tag, Tags, commit,
21};
22use happenstance_sqlite::connection::open_configured;
23use happenstance_sqlite::event_store::{SqliteEventStore, SqliteEventStoreError};
24use happenstance_sqlite::projection_store::{
25    SqliteBatch, SqliteProjectionStore, SqliteProjectionStoreError,
26};
27use rusqlite::Connection;
28use rusqlite::types::Value;
29use serde::{Deserialize, Serialize};
30
31/// The one show this application sells seats for.
32pub const SHOW: &str = "gala";
33
34/// How many seats that show has.
35///
36/// Small on purpose. The demonstration is that more clients ask for seats than
37/// exist, concurrently, and that the count comes out right anyway.
38pub const CAPACITY: u32 = 5;
39
40/// How many times a reservation may be attempted before it gives up.
41///
42/// Larger than the other examples' three, and for a reason those examples do
43/// not have: every reservation contends on the show's own total, so a burst of
44/// concurrent requests really does spend attempts. Running out is
45/// [`Reservation::Contended`] and a `503`, never a hang.
46pub const ATTEMPTS: u32 = 8;
47
48/// How many events one projection chunk commits at a time.
49pub const CHUNK: usize = 16;
50
51/// The read model's name, not its checkpoint key: the runner commits under
52/// `checkpoint_id(&SeatHolders::new())`. A `const` built by `from_static` is
53/// checked at `cargo check`, so an invalid name is a build error, not a crash.
54pub const PROJECTION: ProjectionId = ProjectionId::from_static("seat_holder");
55
56/// The read-model table this application owns.
57///
58/// It is the application's table, not the adapter's: `SqliteProjectionStore`
59/// migrates `projection_checkpoint` and `projection_meta` and stops there.
60pub const READ_MODEL_DDL: &str = "
61CREATE TABLE IF NOT EXISTS seat_holder (
62    seat   TEXT PRIMARY KEY,
63    patron TEXT NOT NULL
64) STRICT;
65";
66
67/// Creates the read-model table if it is not already there.
68///
69/// Called by all three binaries rather than by whichever one happens to start
70/// first. Two processes racing to create the same table is exactly what
71/// `IF NOT EXISTS` is for, and deciding that one of them "owns" startup would
72/// be a rule the other one has to be trusted to obey.
73///
74/// # Errors
75///
76/// Returns the driver's error if the file cannot be opened or the statement
77/// cannot be run.
78pub fn ensure_schema(path: &Path) -> rusqlite::Result<()> {
79    open_configured(path)?.execute_batch(READ_MODEL_DDL)
80}
81
82// ---------------------------------------------------------------------------
83// Identity, validated once at the edge
84// ---------------------------------------------------------------------------
85
86/// A show, validated once into the tag its events carry.
87#[derive(Debug, Clone, Serialize, Deserialize)]
88#[serde(try_from = "String", into = "String")]
89pub struct ShowId {
90    /// The identifier as the application wrote it.
91    id: String,
92    /// The same value, validated into a tag.
93    tag: Tag,
94}
95
96/// A seat, validated once into the tag its events carry.
97#[derive(Debug, Clone, Serialize, Deserialize)]
98#[serde(try_from = "String", into = "String")]
99pub struct SeatId {
100    /// The identifier as the application wrote it.
101    id: String,
102    /// The same value, validated into a tag.
103    tag: Tag,
104}
105
106/// A patron, validated once into the tag its events carry.
107#[derive(Debug, Clone, Serialize, Deserialize)]
108#[serde(try_from = "String", into = "String")]
109pub struct PatronId {
110    /// The identifier as the application wrote it.
111    id: String,
112    /// The same value, validated into a tag.
113    tag: Tag,
114}
115
116/// Writes the three identical newtype bodies.
117///
118/// A macro rather than three copies, and it is internal — it is not exported,
119/// takes no callback and has one arm, so it is a spelling convenience and not
120/// an extension point. The three types are genuinely the same shape, and the
121/// resolution behind that shape is the one the other examples reach:
122/// `DomainEvent::tags` is infallible while `Tag::key_value` can refuse, so a
123/// domain type whose tags come from runtime values holds the validated form
124/// instead of rebuilding it on every call.
125macro_rules! identity {
126    ($type:ident, $key:literal) => {
127        impl $type {
128            /// Validates `id` into the tag every event for it is written with.
129            ///
130            /// # Errors
131            ///
132            /// Returns [`InvalidTag`] when `id` cannot be part of a tag —
133            /// empty, too long, or carrying a control character.
134            pub fn new(id: &str) -> Result<Self, InvalidTag> {
135                Ok(Self {
136                    id: id.to_owned(),
137                    tag: Tag::key_value($key, id)?,
138                })
139            }
140
141            /// The identifier as the application wrote it.
142            #[must_use]
143            pub fn as_str(&self) -> &str {
144                &self.id
145            }
146        }
147
148        impl TryFrom<String> for $type {
149            type Error = InvalidTag;
150
151            fn try_from(id: String) -> Result<Self, InvalidTag> {
152                Self::new(&id)
153            }
154        }
155
156        impl From<$type> for String {
157            fn from(value: $type) -> Self {
158                value.id
159            }
160        }
161    };
162}
163
164identity!(ShowId, "show");
165identity!(SeatId, "seat");
166identity!(PatronId, "patron");
167
168// ---------------------------------------------------------------------------
169// The domain: one enum, named once
170// ---------------------------------------------------------------------------
171
172/// Everything that can happen while a show is sold.
173///
174/// One enum, so a query and a fold cannot name different sets. There is no
175/// `_ =>` arm anywhere in this crate.
176#[derive(Debug, Serialize, Deserialize)]
177pub enum Ticketing {
178    /// A show went on sale, with a fixed number of seats.
179    ShowOpened {
180        /// The show now selling.
181        show: ShowId,
182        /// How many seats it has.
183        capacity: u32,
184    },
185    /// A patron took a seat.
186    SeatReserved {
187        /// The show the seat belongs to.
188        show: ShowId,
189        /// The seat now held.
190        seat: SeatId,
191        /// Who holds it.
192        patron: PatronId,
193    },
194    /// A patron gave a seat back.
195    SeatReleased {
196        /// The show the seat belongs to.
197        show: ShowId,
198        /// The seat now free.
199        seat: SeatId,
200        /// Who was holding it.
201        patron: PatronId,
202    },
203}
204
205const SHOW_OPENED: EventType = EventType::from_static("ShowOpened");
206const SEAT_RESERVED: EventType = EventType::from_static("SeatReserved");
207const SEAT_RELEASED: EventType = EventType::from_static("SeatReleased");
208
209impl DomainEvent for Ticketing {
210    const EVENT_TYPES: &'static [EventType] = &[SHOW_OPENED, SEAT_RESERVED, SEAT_RELEASED];
211
212    fn event_type(&self) -> EventType {
213        match self {
214            Self::ShowOpened { .. } => SHOW_OPENED,
215            Self::SeatReserved { .. } => SEAT_RESERVED,
216            Self::SeatReleased { .. } => SEAT_RELEASED,
217        }
218    }
219
220    fn tags(&self) -> Tags {
221        match self {
222            Self::ShowOpened { show, .. } => [show.tag.clone()].into_iter().collect(),
223            Self::SeatReserved { show, seat, patron }
224            | Self::SeatReleased { show, seat, patron } => {
225                [show.tag.clone(), seat.tag.clone(), patron.tag.clone()]
226                    .into_iter()
227                    .collect()
228            }
229        }
230    }
231
232    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
233        codec.encode(self)
234    }
235
236    fn decode<C: Codec>(
237        codec: &C,
238        _event_type: &EventType,
239        data: &Bytes,
240    ) -> Result<Self, CodecError> {
241        codec.decode(data)
242    }
243}
244
245/// Why a reservation refused.
246///
247/// Every variant carries the value the response body prints — `a-1 is held by
248/// p-2` and never `conflict` — so a client can act on a `409` without a second
249/// request.
250#[derive(Debug, thiserror::Error)]
251pub enum Refusal {
252    /// Seats cannot be sold for a show nobody opened.
253    #[error("show {show} is not open")]
254    NotOpen {
255        /// The show nobody opened.
256        show: String,
257    },
258    /// A seat is held by at most one patron.
259    #[error("{seat} is held by {patron}")]
260    SeatTaken {
261        /// The seat somebody else has.
262        seat: String,
263        /// Who has it.
264        patron: String,
265    },
266    /// The show has sold every seat it has.
267    #[error("{show} is full ({taken}/{capacity})")]
268    Full {
269        /// The show with nothing left.
270        show: String,
271        /// How many seats are held.
272        taken: u32,
273        /// How many there are.
274        capacity: u32,
275    },
276}
277
278// ---------------------------------------------------------------------------
279// The decision models: one per consistency concern
280// ---------------------------------------------------------------------------
281
282/// Who holds one seat, if anybody.
283#[derive(Debug, Clone)]
284pub struct Seat {
285    /// The tags every event inside this boundary carries.
286    scope: Tags,
287    /// Who holds it now, or `None` if nobody does.
288    taken_by: Option<String>,
289}
290
291impl Seat {
292    /// Validates the scope once, here, where the caller already writes a `?`.
293    ///
294    /// # Errors
295    ///
296    /// Returns [`InvalidTag`] when the seat cannot be part of a tag.
297    pub fn new(seat: &SeatId) -> Result<Self, InvalidTag> {
298        Ok(Self {
299            scope: Tags::from_pairs([("seat", seat.as_str())])?,
300            taken_by: None,
301        })
302    }
303}
304
305impl DecisionModel for Seat {
306    type Event = Ticketing;
307
308    fn scope(&self) -> &Tags {
309        &self.scope
310    }
311
312    fn apply(&mut self, event: Self::Event) {
313        match event {
314            Ticketing::SeatReserved { patron, .. } => self.taken_by = Some(patron.id),
315            Ticketing::SeatReleased { .. } => self.taken_by = None,
316            // An opening carries no `seat` tag, so this model's query never
317            // nominates one. The arm exists because the fold is exhaustive
318            // over the enum, and that exhaustiveness is the whole guarantee.
319            Ticketing::ShowOpened { .. } => {}
320        }
321    }
322}
323
324/// One show's capacity, and how much of it is spoken for.
325///
326/// **This is the contended boundary.** Every reservation for this show reads
327/// it and conditions on it, so two requests for two *different* seats still
328/// collide — which is what makes the retry loop in `commit` do visible work in
329/// this example and in none of the others.
330#[derive(Debug, Clone)]
331pub struct Show {
332    /// The tags every event inside this boundary carries.
333    scope: Tags,
334    /// How many seats there are, once the show has been opened.
335    capacity: Option<u32>,
336    /// How many are held.
337    taken: u32,
338}
339
340impl Show {
341    /// Validates the scope once, here, where the caller already writes a `?`.
342    ///
343    /// # Errors
344    ///
345    /// Returns [`InvalidTag`] when the show cannot be part of a tag.
346    pub fn new(show: &ShowId) -> Result<Self, InvalidTag> {
347        Ok(Self {
348            scope: Tags::from_pairs([("show", show.as_str())])?,
349            capacity: None,
350            taken: 0,
351        })
352    }
353}
354
355impl DecisionModel for Show {
356    type Event = Ticketing;
357
358    fn scope(&self) -> &Tags {
359        &self.scope
360    }
361
362    fn apply(&mut self, event: Self::Event) {
363        match event {
364            // Decoded, never scraped from the payload's bytes: a show with no
365            // capacity is a decode failure naming its position, and never a
366            // show with a capacity of zero.
367            Ticketing::ShowOpened { capacity, .. } => self.capacity = Some(capacity),
368            Ticketing::SeatReserved { .. } => self.taken = self.taken.saturating_add(1),
369            Ticketing::SeatReleased { .. } => self.taken = self.taken.saturating_sub(1),
370        }
371    }
372}
373
374// ---------------------------------------------------------------------------
375// The two commands
376// ---------------------------------------------------------------------------
377
378/// Opens the show, once.
379///
380/// # Errors
381///
382/// Returns the command loop's error, including the refusal when the show has
383/// already been opened.
384pub async fn open_show(
385    events: &SqliteEventStore,
386    capacity: u32,
387) -> Result<(), CommandError<SqliteEventStoreError, Refusal>> {
388    let show = ShowId::new(SHOW).map_err(|_| unreachable_show())?;
389    let boundary = Show::new(&show).map_err(|_| unreachable_show())?;
390
391    commit(events, boundary, retry_bound(), |state: &Show| {
392        if state.capacity.is_some() {
393            return Err(Refusal::NotOpen {
394                show: SHOW.to_owned(),
395            });
396        }
397        Ok(vec![Ticketing::ShowOpened {
398            show: show.clone(),
399            capacity,
400        }])
401    })
402    .await
403    .map(|_| ())
404}
405
406/// What answering a reservation came to.
407///
408/// A value rather than a `Result`, because all four arms are ordinary answers
409/// a client has to be told apart: a conflict is not a bug, a spent retry bound
410/// is not a conflict, and neither is a broken database. The API turns each one
411/// into its own status code and nothing else in the process has to decide.
412#[derive(Debug, Clone)]
413pub enum Reservation {
414    /// The seat was taken. `201`.
415    Taken {
416        /// Where the event landed. A client sends this back on a read to say
417        /// which version of the world it expects to see.
418        position: u64,
419        /// How many attempts the command loop spent, the successful one
420        /// included. Greater than 1 means this request lost a race and
421        /// re-decided.
422        attempts: u32,
423    },
424    /// A rule refused it. `409`.
425    Refused {
426        /// The refusal, rendered with its values.
427        why: String,
428    },
429    /// The retry bound was spent without the condition ever holding. `503`.
430    Contended {
431        /// How many attempts were made.
432        attempts: u32,
433    },
434    /// Anything else. `500`.
435    Failed {
436        /// What went wrong.
437        why: String,
438    },
439}
440
441impl Reservation {
442    /// The status code and reason phrase this outcome is answered with.
443    #[must_use]
444    pub fn status(&self) -> (u16, &'static str) {
445        match self {
446            Self::Taken { .. } => (201, "Created"),
447            Self::Refused { .. } => (409, "Conflict"),
448            Self::Contended { .. } => (503, "Service Unavailable"),
449            Self::Failed { .. } => (500, "Internal Server Error"),
450        }
451    }
452
453    /// The response body this outcome is answered with.
454    #[must_use]
455    pub fn body(&self) -> String {
456        match self {
457            Self::Taken { position, attempts } => {
458                format!("reserved at position {position} in {attempts} attempt(s)\n")
459            }
460            Self::Refused { why } => format!("refused: {why}\n"),
461            Self::Contended { attempts } => {
462                format!("still contended after {attempts} attempt(s); try again\n")
463            }
464            Self::Failed { why } => format!("failed: {why}\n"),
465        }
466    }
467}
468
469/// Reserves one seat for one patron.
470///
471/// The boundary is a tuple of two models with two different scopes — the seat
472/// and the show — so one append condition carries "nobody else took this seat"
473/// and "the show has not sold out" at the same time. Neither invariant fits
474/// inside the other's entity, and under the concurrency this example creates
475/// they are contradicted by different requests.
476pub async fn reserve(events: &SqliteEventStore, seat: &str, patron: &str) -> Reservation {
477    let (Ok(show), Ok(seat), Ok(patron)) =
478        (ShowId::new(SHOW), SeatId::new(seat), PatronId::new(patron))
479    else {
480        return Reservation::Failed {
481            why: "a seat and a patron must be non-empty and free of control characters".to_owned(),
482        };
483    };
484
485    let (Ok(one), Ok(all)) = (Seat::new(&seat), Show::new(&show)) else {
486        return Reservation::Failed {
487            why: "the boundary's scope could not be validated".to_owned(),
488        };
489    };
490    let boundary = (one, all);
491
492    let outcome = commit(
493        events,
494        boundary,
495        retry_bound(),
496        |(one, all): &(Seat, Show)| {
497            let Some(capacity) = all.capacity else {
498                return Err(Refusal::NotOpen {
499                    show: show.as_str().to_owned(),
500                });
501            };
502            if let Some(holder) = one.taken_by.clone() {
503                return Err(Refusal::SeatTaken {
504                    seat: seat.as_str().to_owned(),
505                    patron: holder,
506                });
507            }
508            if all.taken >= capacity {
509                return Err(Refusal::Full {
510                    show: show.as_str().to_owned(),
511                    taken: all.taken,
512                    capacity,
513                });
514            }
515            Ok(vec![Ticketing::SeatReserved {
516                show: show.clone(),
517                seat: seat.clone(),
518                patron: patron.clone(),
519            }])
520        },
521    )
522    .await;
523
524    match outcome {
525        Ok(CommandOutcome::Committed(committed)) => Reservation::Taken {
526            position: committed.position.get(),
527            attempts: committed.attempts,
528        },
529
530        // The handler above returns exactly one event or refuses, so this arm
531        // is unreachable *for this handler* — and it is spelled out rather than
532        // folded in with a `_`, because the compiler is the only thing that
533        // will notice the day somebody adds an early `return Ok(vec![])` to it.
534        // A 200 carrying a fabricated position would be worse than a 500.
535        Ok(CommandOutcome::Nothing) => Reservation::Failed {
536            why: "the handler decided no events, which this endpoint has no                   seat to report"
537                .to_owned(),
538        },
539
540        Err(CommandError::Refused(refusal)) => Reservation::Refused {
541            why: refusal.to_string(),
542        },
543        Err(CommandError::Exhausted { attempts, .. }) => Reservation::Contended { attempts },
544        Err(other) => Reservation::Failed {
545            why: other.to_string(),
546        },
547    }
548}
549
550/// The retry bound, built from [`ATTEMPTS`].
551///
552/// A `const` conversion would be tidier and is not available: `NonZeroU32`'s
553/// checked constructor is `const` but `Retry::attempts` takes the result, so
554/// the fallible step has to happen somewhere. It happens here, once, against a
555/// constant this crate owns — and falls back to one attempt rather than
556/// panicking, because a zero in that constant should degrade to "try once"
557/// and not take a web server down.
558fn retry_bound() -> Retry {
559    ATTEMPTS
560        .try_into()
561        .map_or_else(|_| Retry::once(), Retry::attempts)
562}
563
564/// The refusal used when the show's own identifier will not validate.
565///
566/// Unreachable: [`SHOW`] is a `&'static str` of seven ASCII letters. It is
567/// spelled as a refusal rather than an `unwrap` because this crate is linked
568/// into a server, and a panic path that no request can reach is still a panic
569/// path in the binary.
570fn unreachable_show() -> CommandError<SqliteEventStoreError, Refusal> {
571    CommandError::Refused(Refusal::NotOpen {
572        show: SHOW.to_owned(),
573    })
574}
575
576// ---------------------------------------------------------------------------
577// The read model, and the two processes' view of it
578// ---------------------------------------------------------------------------
579
580/// Who holds which seat, kept as a table rather than folded on every read.
581#[derive(Debug)]
582pub struct SeatHolders {
583    /// Which read model this is, within the projection store.
584    id: ProjectionId,
585    /// Every event, so the tags constrain nothing.
586    scope: Tags,
587}
588
589impl Default for SeatHolders {
590    fn default() -> Self {
591        Self::new()
592    }
593}
594
595impl SeatHolders {
596    /// The view over every seat.
597    #[must_use]
598    pub fn new() -> Self {
599        Self {
600            id: PROJECTION,
601            scope: Tags::empty(),
602        }
603    }
604}
605
606impl Projection for SeatHolders {
607    type Event = Ticketing;
608    type Store = SqliteProjectionStore;
609    type Error = SqliteProjectionStoreError;
610
611    fn id(&self) -> &ProjectionId {
612        &self.id
613    }
614
615    fn scope(&self) -> &Tags {
616        &self.scope
617    }
618
619    async fn apply(
620        &mut self,
621        event: Delivered<Ticketing>,
622        batch: &mut SqliteBatch,
623    ) -> Result<(), SqliteProjectionStoreError> {
624        match event.into_event() {
625            Ticketing::SeatReserved { seat, patron, .. } => batch.push(
626                "INSERT INTO seat_holder (seat, patron) VALUES (?1, ?2) \
627                 ON CONFLICT(seat) DO UPDATE SET patron = excluded.patron",
628                [Value::Text(seat.into()), Value::Text(patron.into())],
629            ),
630            Ticketing::SeatReleased { seat, .. } => batch.push(
631                "DELETE FROM seat_holder WHERE seat = ?1",
632                [Value::Text(seat.into())],
633            ),
634            // Nominated and ignored. The derived query is the event set crossed
635            // with the scope, and this view's scope is empty, so an opening
636            // arrives here whether it is wanted or not — the checkpoint still
637            // advances past it, which is what "the position considered" means.
638            Ticketing::ShowOpened { .. } => {}
639        }
640
641        Ok(())
642    }
643}
644
645/// Every held seat, as the application's own query sees it.
646///
647/// # Errors
648///
649/// Returns the driver's error if the statement cannot be prepared or run.
650pub fn seat_rows(app: &Connection) -> rusqlite::Result<Vec<(String, String)>> {
651    let mut statement = app.prepare("SELECT seat, patron FROM seat_holder ORDER BY seat")?;
652    let rows = statement.query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?;
653    rows.collect()
654}
655
656/// How far the read model has been brought, as a bare position.
657///
658/// `None` covers both "never run" and "rebuilding", which is right for the one
659/// question the API asks of it: *are the rows I am about to serve at least as
660/// new as the write this client just made?* A rebuilding view's rows are not
661/// authoritative, so the honest answer for it is the same as for a view that
662/// has never run.
663///
664/// `key` is the id the runner commits under,
665/// `checkpoint_id(&SeatHolders::new())`, derived once by the caller. Not
666/// [`PROJECTION`]: that is the view's name, and its row reads `NeverRun`
667/// whatever the runner did.
668///
669/// # Errors
670///
671/// Returns the projection store's error if the checkpoint cannot be read.
672pub async fn checkpoint_through(
673    models: &SqliteProjectionStore,
674    key: &ProjectionId,
675) -> Result<Option<u64>, SqliteProjectionStoreError> {
676    Ok(match models.checkpoint(key).await? {
677        Checkpoint::Live { through } => Some(through.get()),
678        // `NeverRun`, `Rebuilding`, and — `Checkpoint` being
679        // `#[non_exhaustive]` — anything added upstream. Every one of them
680        // answers this function's only question with "no": a rebuilding view's
681        // rows are explicitly not authoritative, and a state this build has
682        // never heard of must not be silently read as "caught up".
683        _ => None,
684    })
685}
686
687/// The position a client asked to read at, if it named one.
688///
689/// # Errors
690///
691/// Returns the raw value when it is not a position: zero does not exist —
692/// `SequencePosition` wraps a `NonZeroU64` — and neither does anything that is
693/// not a number.
694pub fn requested_position(raw: &str) -> Result<SequencePosition, &str> {
695    raw.parse().ok().and_then(SequencePosition::new).ok_or(raw)
696}