Skip to main content

tickets_over_http/
api.rs

1//! The write side: an HTTP server that takes reservations and serves the view.
2//!
3//! It appends to the event log and it **never** maintains the read model — that
4//! is `tickets-runner`'s job, in another process. What this one does with the
5//! read model is the interesting half: it reads the *checkpoint* to decide
6//! whether the rows it is about to serve are new enough to answer the client
7//! that just wrote.
8//!
9//! Run it directly with `cargo run -p tickets-over-http -- serve <database>`;
10//! it prints the address it bound to on its first line of output, which is how
11//! the demo role finds it. Port 0, because a demonstration that fails when
12//! something else on the machine holds 8080 is a demonstration about port
13//! allocation.
14
15#![allow(clippy::print_stdout, reason = "the bound address is the interface")]
16
17use core::fmt::Write as _;
18use std::net::SocketAddr;
19use std::path::PathBuf;
20use std::sync::Arc;
21
22use anyhow::Result;
23use happenstance::{ProjectionId, checkpoint_id};
24use happenstance_sqlite::connection::open_configured;
25use happenstance_sqlite::event_store::SqliteEventStore;
26use happenstance_sqlite::projection_store::SqliteProjectionStore;
27use tickets_over_http::http::{Request, respond};
28use tickets_over_http::{
29    CAPACITY, Reservation, SeatHolders, checkpoint_through, ensure_schema, open_show,
30    requested_position, reserve, seat_rows,
31};
32use tokio::net::{TcpListener, TcpStream};
33
34/// What every connection handler needs.
35///
36/// The path is held as well as the two stores because the read-model table is
37/// the *application's*, and `rusqlite::Connection` is `Send` but not `Sync` —
38/// so a handler opens its own rather than sharing one behind a lock. That is a
39/// real cost of owning your read model and it is not hidden here; a server
40/// under load would keep a pool, which is a paragraph of connection management
41/// that would teach nothing about happenstance.
42#[derive(Debug)]
43struct State {
44    /// The log this process appends to.
45    events: SqliteEventStore,
46    /// The checkpoint store this process only ever reads.
47    models: SqliteProjectionStore,
48    /// The id the runner commits the view's checkpoint under, derived once.
49    checkpoint: ProjectionId,
50    /// The file, for opening a read-model connection per request.
51    path: PathBuf,
52}
53
54/// Serves until it is stopped.
55pub(crate) async fn run(path: PathBuf) -> Result<()> {
56    ensure_schema(&path)?;
57
58    // Both stores are built **inside** the runtime, and that is load-bearing
59    // rather than stylistic: ADR-0022 §9 captures the tokio handle at
60    // construction, so a store built before a runtime exists records `None` and
61    // every read fails with `SqliteEventStoreError::NoRuntime`.
62    let events = SqliteEventStore::open(&path)?;
63    let models = SqliteProjectionStore::open(&path)?;
64
65    // Opening the show is idempotent by refusal: a second process starting
66    // against the same file is told the show is already open, and that is the
67    // correct answer rather than an error to report.
68    drop(open_show(&events, CAPACITY).await);
69
70    let listener = TcpListener::bind(SocketAddr::from(([127, 0, 0, 1], 0))).await?;
71    // The first line of stdout, and a contract with the demo role. Rust's
72    // stdout is line-buffered, so this reaches the pipe before `accept` blocks.
73    println!("listening on {}", listener.local_addr()?);
74
75    // The runner process derives the same id from the same view: the name and
76    // a digest of its query (PS-25). Reading under the bare name would answer
77    // `202` for ever.
78    let checkpoint = checkpoint_id(&SeatHolders::new())?;
79    let state = Arc::new(State {
80        events,
81        models,
82        checkpoint,
83        path,
84    });
85
86    loop {
87        let (stream, _) = listener.accept().await?;
88        let state = Arc::clone(&state);
89        tokio::spawn(async move {
90            if let Err(err) = serve(&state, stream).await {
91                eprintln!("connection failed: {err}");
92            }
93        });
94    }
95}
96
97/// Reads one request and answers it.
98async fn serve(state: &State, mut stream: TcpStream) -> Result<()> {
99    let Some(request) = Request::read(&mut stream).await? else {
100        return Ok(());
101    };
102
103    match (request.method.as_str(), request.path.as_str()) {
104        ("POST", "/reserve") => take_a_seat(state, &request, &mut stream).await,
105        ("GET", "/seats") => show_the_seats(state, &request, &mut stream).await,
106        _ => Ok(respond(&mut stream, 404, "Not Found", &[], "no such route\n").await?),
107    }
108}
109
110/// `POST /reserve?seat=…&patron=…`
111///
112/// Every outcome of the command loop becomes its own status code, and the
113/// distinctions are the point. A `409` is a rule refusing, and retrying it
114/// unchanged will refuse again. A `503` is the retry bound spent under
115/// contention, and retrying it is exactly the right thing to do. Collapsing
116/// the two — which a handler that returned `500` for everything that was not
117/// `Ok` would do — leaves a client unable to tell "never" from "not yet".
118async fn take_a_seat(state: &State, request: &Request, stream: &mut TcpStream) -> Result<()> {
119    let (Some(seat), Some(patron)) = (request.param("seat"), request.param("patron")) else {
120        return Ok(respond(
121            stream,
122            400,
123            "Bad Request",
124            &[],
125            "seat and patron are required\n",
126        )
127        .await?);
128    };
129
130    let outcome = reserve(&state.events, seat, patron).await;
131    let (status, reason) = outcome.status();
132
133    // The position is what makes the read below able to wait for this write.
134    // A client that never sends it back gets whatever the view happens to hold.
135    let headers = match &outcome {
136        Reservation::Taken { position, attempts } => vec![
137            ("X-Happenstance-Position", position.to_string()),
138            ("X-Happenstance-Attempts", attempts.to_string()),
139        ],
140        Reservation::Contended { attempts } => {
141            vec![("X-Happenstance-Attempts", attempts.to_string())]
142        }
143        Reservation::Refused { .. } | Reservation::Failed { .. } => Vec::new(),
144    };
145
146    Ok(respond(stream, status, reason, &headers, &outcome.body()).await?)
147}
148
149/// `GET /seats` — optionally `?at=<position>`
150///
151/// Without `at`, this serves whatever the runner has got to, which is the
152/// ordinary case and is allowed to be stale. With `at`, the client is saying
153/// *"I wrote at this position and I want to see a view that includes it"*, and
154/// a view that has not reached it answers `202` with its own checkpoint rather
155/// than serving rows that would silently be missing the caller's own write.
156///
157/// The `202` matters more than it looks. Read-your-own-writes across an
158/// asynchronous read model is the failure every projection-backed API has, and
159/// the usual shape of it is a client that writes, immediately reads, sees
160/// nothing, and concludes the write was lost.
161async fn show_the_seats(state: &State, request: &Request, stream: &mut TcpStream) -> Result<()> {
162    let through = checkpoint_through(&state.models, &state.checkpoint).await?;
163    let checkpoint = through.map_or_else(|| "none".to_owned(), |position| position.to_string());
164
165    if let Some(raw) = request.param("at") {
166        let wanted = match requested_position(raw) {
167            Ok(position) => position,
168            Err(bad) => {
169                return Ok(respond(
170                    stream,
171                    400,
172                    "Bad Request",
173                    &[],
174                    &format!("`{bad}` is not a position\n"),
175                )
176                .await?);
177            }
178        };
179
180        if through.is_none_or(|reached| reached < wanted.get()) {
181            return Ok(respond(
182                stream,
183                202,
184                "Accepted",
185                &[("X-Happenstance-Checkpoint", checkpoint)],
186                "the read model has not reached that position yet\n",
187            )
188            .await?);
189        }
190    }
191
192    let app = open_configured(&state.path)?;
193    let mut body = String::new();
194    for (seat, patron) in seat_rows(&app)? {
195        // Writing into a `String` cannot fail; the `Result` is discarded rather
196        // than `unwrap`ped so this server carries no panic path a request could
197        // reach even in principle.
198        let _ = writeln!(body, "{seat} {patron}");
199    }
200
201    Ok(respond(
202        stream,
203        200,
204        "OK",
205        &[("X-Happenstance-Checkpoint", checkpoint)],
206        &body,
207    )
208    .await?)
209}