tickets_over_http/runner.rs
1//! The read side: a process whose only job is to keep one view current.
2//!
3//! It shares nothing with `tickets-api` but a file. It never accepts a
4//! connection, never takes a decision and never appends an event; it reads the
5//! log, folds it, and commits the rows and the checkpoint together. Stopping
6//! it stops the view from advancing and stops nothing else — which is the
7//! property the whole example exists to show, and the one a single-process
8//! program cannot demonstrate no matter how it is arranged.
9//!
10//! Run it directly with `cargo run -p tickets-over-http -- project <database>`.
11//! It runs until it is stopped.
12
13#![allow(clippy::print_stdout, reason = "the progress log is the interface")]
14
15use core::time::Duration;
16use std::path::PathBuf;
17
18use anyhow::Result;
19use happenstance::{Chunk, Json, run_projection};
20use happenstance_sqlite::event_store::SqliteEventStore;
21use happenstance_sqlite::projection_store::SqliteProjectionStore;
22use tickets_over_http::{CHUNK, SeatHolders, ensure_schema};
23
24/// How long to wait after a pass that had nothing to do.
25///
26/// Polling, and it is worth being honest about why: `EventStore` has no
27/// subscription in its port, so a runner learns that the log grew by looking.
28/// Short enough that a demonstration does not spend its time asleep, long
29/// enough that an idle runner is not a spin loop competing with the API for
30/// the same file's write lock.
31const IDLE: Duration = Duration::from_millis(20);
32
33/// Keeps the view current until it is stopped.
34pub(crate) async fn run(path: PathBuf) -> Result<()> {
35 ensure_schema(&path)?;
36
37 // Built inside the runtime for the reason the API gives: ADR-0022 §9
38 // captures the tokio handle at construction.
39 let events = SqliteEventStore::open(&path)?;
40 let models = SqliteProjectionStore::open(&path)?;
41 let mut view = SeatHolders::new();
42 let chunk = Chunk::of(CHUNK.try_into()?);
43
44 println!("runner started against {}", path.display());
45
46 loop {
47 match run_projection(&events, &models, &mut view, &Json, chunk).await {
48 Ok(progress) => {
49 if progress.applied > 0 {
50 println!(
51 "applied {} event(s), through {:?}",
52 progress.applied, progress.through
53 );
54 }
55 }
56 // A failure here is reported and retried rather than fatal. The
57 // most likely one by far is `SQLITE_BUSY` surviving the busy
58 // timeout while the API holds the write lock, and a runner that
59 // exited on it would turn a moment of contention into an operator
60 // page. A *decode* failure would be permanent and would spin —
61 // which is why `rebuilding-read-models` exists to show what a
62 // policy for that looks like, and why this one says out loud that
63 // it does not have one.
64 Err(err) => eprintln!("projection pass failed: {err}"),
65 }
66
67 tokio::time::sleep(IDLE).await;
68 }
69}