Skip to main content

fireweed_dsl_postgres/
lib.rs

1//! PostgreSQL executor for Fireweed's data-plane DSL (API-008).
2//!
3//! [`PgExecutor`] implements [`fireweed_dsl::Executor`] over a pool of
4//! connections, so a consumer can hold it as a `dyn Executor`.
5//! `apply_schema` creates a space's tables and indexes from its schema,
6//! `execute` runs a program as one transaction of plain SQL statements over
7//! those tables, and `sweep` writes back time-driven state and deletes what
8//! retention has expired.
9//!
10//! The same operations are free functions over one connection, for a caller
11//! that keeps its own. They keep nothing in the process between calls: each
12//! call reads the space's schema from the database, checks the program
13//! against it, and runs it. Queries are sent unprepared with text parameters
14//! (`query_typed`), so each costs one round trip.
15
16#![forbid(unsafe_code)]
17
18mod ddl;
19mod executor;
20mod lower;
21mod run;
22
23use fireweed_dsl::check;
24use fireweed_dsl::{Applied, Durability, Error, Program, Response, Result, Schema, Swept};
25use tokio_postgres::types::{ToSql, Type};
26use tokio_postgres::{Client, Row, Transaction};
27
28use ddl::CATALOG;
29pub use executor::PgExecutor;
30use lower::Q;
31
32/// How many times a program retries a deadlock or serialization failure.
33const RETRIES: usize = 5;
34
35pub(crate) fn db(e: tokio_postgres::Error) -> Error {
36    match e.as_db_error() {
37        // Data exceptions: a value didn't convert (a bad timestamp, an
38        // overflow, a body path that isn't a number).
39        Some(d) if d.code().code().starts_with("22") => Error::Invalid(d.message().to_owned()),
40        Some(d) => Error::Unavailable(format!("{}: {}", d.code().code(), d.message())),
41        None => Error::Unavailable(e.to_string()),
42    }
43}
44
45fn retryable(e: &tokio_postgres::Error) -> bool {
46    e.code()
47        .is_some_and(|c| matches!(c.code(), "40001" | "40P01"))
48}
49
50/// Runs `q` unprepared, every parameter typed `text`.
51pub(crate) async fn rows(
52    tx: &Transaction<'_>,
53    q: &Q,
54) -> std::result::Result<Vec<Row>, tokio_postgres::Error> {
55    let params: Vec<(&(dyn ToSql + Sync), Type)> = q
56        .params
57        .iter()
58        .map(|p| (p as &(dyn ToSql + Sync), Type::TEXT))
59        .collect();
60    tx.query_typed(&q.sql, &params).await
61}
62
63/// A space as stored in the catalog.
64pub(crate) struct Space {
65    pub id: i64,
66    pub schema_name: String,
67    pub schema: Schema,
68}
69
70async fn load(c: &Client, tenant: &str, space: &str) -> Result<Option<(i64, Schema)>> {
71    let row = c
72        .query_typed_opt(
73            "SELECT id, schema_doc::text FROM fireweed.spaces WHERE tenant = $1 AND space = $2",
74            &[(&tenant, Type::TEXT), (&space, Type::TEXT)],
75        )
76        .await;
77    let row = match row {
78        Ok(r) => r,
79        // The catalog doesn't exist yet: no space does.
80        Err(e)
81            if e.code()
82                .is_some_and(|c| c.code() == "42P01" || c.code() == "3F000") =>
83        {
84            return Ok(None);
85        }
86        Err(e) => return Err(db(e)),
87    };
88    match row {
89        None => Ok(None),
90        Some(r) => {
91            let doc: String = r.get(1);
92            let schema = serde_json::from_str(&doc)
93                .map_err(|e| Error::Unavailable(format!("stored schema: {e}")))?;
94            Ok(Some((r.get(0), schema)))
95        }
96    }
97}
98
99/// The stored schema of a space, if it exists.
100pub async fn get_schema(c: &Client, tenant: &str, space: &str) -> Result<Option<Schema>> {
101    Ok(load(c, tenant, space).await?.map(|(_, s)| s))
102}
103
104/// Creates a space, or changes its schema (API-008 §Changing a schema).
105/// `expected` is the version the caller expects to replace: `None` for a
106/// new space.
107pub async fn apply_schema(
108    c: &mut Client,
109    tenant: &str,
110    space: &str,
111    schema: &Schema,
112    expected: Option<i64>,
113) -> Result<Applied> {
114    check::schema(schema)?;
115    let tx = c.transaction().await.map_err(db)?;
116    // One catalog change at a time, across every process.
117    tx.batch_execute("SELECT pg_advisory_xact_lock(7342651001)")
118        .await
119        .map_err(db)?;
120    tx.batch_execute(CATALOG).await.map_err(db)?;
121    // ALTER TABLE waits for an exclusive lock, and claims would queue behind
122    // that wait: bound it.
123    tx.batch_execute("SET LOCAL lock_timeout = '5s'")
124        .await
125        .map_err(db)?;
126    let doc = serde_json::to_string(schema).expect("schemas serialize");
127    let version = schema.version.to_string();
128    let row = tx
129        .query_typed_opt(
130            "SELECT id, schema_doc::text FROM fireweed.spaces WHERE tenant = $1 AND space = $2 FOR UPDATE",
131            &[(&tenant, Type::TEXT), (&space, Type::TEXT)],
132        )
133        .await
134        .map_err(db)?;
135    let applied = match row {
136        None => {
137            if expected.is_some() {
138                return Err(Error::SchemaConflict { current: None });
139            }
140            let id: i64 = tx
141                .query_typed_one(
142                    "INSERT INTO fireweed.spaces (tenant, space, version, schema_doc) VALUES ($1, $2, $3::bigint, $4::jsonb) RETURNING id",
143                    &[(&tenant, Type::TEXT), (&space, Type::TEXT), (&version, Type::TEXT), (&doc, Type::TEXT)],
144                )
145                .await
146                .map_err(db)?
147                .get(0);
148            tx.batch_execute(&ddl::create(&ddl::schema_name(id), schema))
149                .await
150                .map_err(db)?;
151            Applied {
152                version: schema.version,
153                changed: true,
154            }
155        }
156        Some(r) => {
157            let id: i64 = r.get(0);
158            let old: Schema = serde_json::from_str(r.get::<_, &str>(1))
159                .map_err(|e| Error::Unavailable(format!("stored schema: {e}")))?;
160            if &old == schema {
161                return Ok(Applied {
162                    version: old.version,
163                    changed: false,
164                });
165            }
166            if expected != Some(old.version) {
167                return Err(Error::SchemaConflict {
168                    current: Some(old.version),
169                });
170            }
171            check::change(&old, schema)?;
172            tx.batch_execute(&ddl::change(&ddl::schema_name(id), &old, schema))
173                .await
174                .map_err(db)?;
175            let id = id.to_string();
176            tx.execute_typed(
177                "UPDATE fireweed.spaces SET version = $2::bigint, schema_doc = $3::jsonb WHERE id = $1::bigint",
178                &[(&id, Type::TEXT), (&version, Type::TEXT), (&doc, Type::TEXT)],
179            )
180            .await
181            .map_err(db)?;
182            Applied {
183                version: schema.version,
184                changed: true,
185            }
186        }
187    };
188    tx.commit().await.map_err(db)?;
189    Ok(applied)
190}
191
192/// Runs a program as one transaction (API-008 §Transactions).
193pub async fn execute(c: &mut Client, tenant: &str, space: &str, p: &Program) -> Result<Response> {
194    let fingerprint = check::fingerprint(p)?;
195    let durability = durability(p);
196    for _ in 0..RETRIES {
197        let tx = c.transaction().await.map_err(db)?;
198        match program(
199            &tx,
200            tenant,
201            space,
202            p,
203            &fingerprint,
204            &setup(durability),
205            durability,
206        )
207        .await
208        {
209            Ok(r) => match tx.commit().await {
210                Ok(()) => return Ok(r),
211                Err(e) if retryable(&e) => continue,
212                Err(e) => return Err(db(e)),
213            },
214            Err(Attempt::Retry) => continue,
215            Err(Attempt::Failed(e)) => return Err(e),
216        }
217    }
218    Err(Error::Contention)
219}
220
221/// Runs independent programs in one space as one transaction with one
222/// commit (API-008 §Batches). Each program runs under its own savepoint, so
223/// one that fails or rejects leaves the others alone; each gets its own
224/// result, in order. A program that hits a deadlock is run again.
225pub async fn execute_batch(
226    c: &mut Client,
227    tenant: &str,
228    space: &str,
229    programs: &[Program],
230) -> Result<Vec<Result<Response>>> {
231    if programs.len() > check::MAX_BATCH {
232        return Err(Error::Invalid(format!(
233            "a batch has at most {} programs",
234            check::MAX_BATCH
235        )));
236    }
237    let mut out: Vec<Option<Result<Response>>> = programs
238        .iter()
239        .map(|p| check::fingerprint(p).err().map(Err))
240        .collect();
241    for _ in 0..RETRIES {
242        let pending: Vec<usize> = (0..programs.len()).filter(|&i| out[i].is_none()).collect();
243        if pending.is_empty() {
244            break;
245        }
246        // One commit for all, so it waits for the WAL flush unless every
247        // program is fire-and-forget.
248        let durability = if pending
249            .iter()
250            .all(|&i| durability(&programs[i]) == Durability::FireAndForget)
251        {
252            Durability::FireAndForget
253        } else {
254            Durability::Durable
255        };
256        let tx = c.transaction().await.map_err(db)?;
257        let mut setup = setup(durability);
258        let mut done = vec![];
259        for &i in &pending {
260            let p = &programs[i];
261            let fp = check::fingerprint(p)?;
262            let r = program(&tx, tenant, space, p, &fp, &setup, durability).await;
263            setup.clear();
264            let undo = if r.is_ok() {
265                "RELEASE SAVEPOINT open"
266            } else {
267                "ROLLBACK TO SAVEPOINT open; RELEASE SAVEPOINT open"
268            };
269            tx.batch_execute(undo).await.map_err(db)?;
270            match r {
271                Ok(resp) => done.push((i, Ok(resp))),
272                Err(Attempt::Failed(e)) => done.push((i, Err(e))),
273                Err(Attempt::Retry) => {}
274            }
275        }
276        match tx.commit().await {
277            Ok(()) => done.into_iter().for_each(|(i, r)| out[i] = Some(r)),
278            Err(e) if retryable(&e) => {}
279            Err(e) => return Err(db(e)),
280        }
281    }
282    Ok(out
283        .into_iter()
284        .map(|r| r.unwrap_or(Err(Error::Contention)))
285        .collect())
286}
287
288fn durability(p: &Program) -> Durability {
289    match p.durability {
290        Some(Durability::FireAndForget) => Durability::FireAndForget,
291        _ => Durability::Durable,
292    }
293}
294
295/// A transaction's settings. The timeouts come first, so even a wait on a
296/// duplicate request's record is bounded. The checker admits only
297/// statements with an index path (API-008 §Index rule), so the planner is
298/// told to take it rather than read a whole table it judges small.
299fn setup(durability: Durability) -> String {
300    let mut s = String::from(
301        "SET LOCAL TimeZone = 'UTC'; SET LOCAL statement_timeout = '5s'; \
302         SET LOCAL enable_seqscan = off;",
303    );
304    if durability == Durability::FireAndForget {
305        s.push_str(" SET LOCAL synchronous_commit = off;");
306    }
307    s
308}
309
310pub(crate) enum Attempt {
311    Retry,
312    Failed(Error),
313}
314
315impl From<tokio_postgres::Error> for Attempt {
316    fn from(e: tokio_postgres::Error) -> Self {
317        if retryable(&e) {
318            Attempt::Retry
319        } else {
320            Attempt::Failed(db(e))
321        }
322    }
323}
324
325impl From<Error> for Attempt {
326    fn from(e: Error) -> Self {
327        Attempt::Failed(e)
328    }
329}
330
331/// Runs one program inside `tx`, under savepoint `open`, which the caller
332/// releases or rolls back to. The caller commits. Round trips: one
333/// pipelined flight of `setup`, the savepoint, `fireweed.open_space` (the
334/// space's schema and its request record) and a second savepoint; one per
335/// statement; the response.
336async fn program(
337    tx: &Transaction<'_>,
338    tenant: &str,
339    space: &str,
340    p: &Program,
341    fingerprint: &str,
342    setup: &str,
343    durability: Durability,
344) -> std::result::Result<Response, Attempt> {
345    let rid = p.request_id.clone();
346    let issued = p.issued_at.clone();
347    let fp = fingerprint.to_owned();
348    let open = "SELECT space_id, schema_doc, fingerprint, response, fresh, expired \
349                FROM fireweed.open_space($1, $2, $3, $4, $5::timestamptz)";
350    let open_params: [(&(dyn ToSql + Sync), Type); 5] = [
351        (&tenant, Type::TEXT),
352        (&space, Type::TEXT),
353        (&rid, Type::TEXT),
354        (&fp, Type::TEXT),
355        (&issued, Type::TEXT),
356    ];
357    let first = format!("{setup} SAVEPOINT open;");
358    let (_, row, _) = match futures::try_join!(
359        tx.batch_execute(&first),
360        tx.query_typed_one(open, &open_params),
361        tx.batch_execute("SAVEPOINT program"),
362    ) {
363        Ok(x) => x,
364        // No catalog yet: no space exists.
365        Err(e)
366            if e.code()
367                .is_some_and(|c| matches!(c.code(), "42883" | "3F000" | "42P01")) =>
368        {
369            return Err(Attempt::Failed(Error::SpaceNotFound));
370        }
371        Err(e) => return Err(e.into()),
372    };
373    let Some(id) = row.get::<_, Option<i64>>(0) else {
374        return Err(Attempt::Failed(Error::SpaceNotFound));
375    };
376    if row.get::<_, bool>(5) {
377        return Err(Attempt::Failed(Error::RequestExpired));
378    }
379    let schema: Schema = serde_json::from_str(row.get::<_, &str>(1))
380        .map_err(|e| Attempt::Failed(Error::Unavailable(format!("stored schema: {e}"))))?;
381    let sp = Space {
382        id,
383        schema_name: ddl::schema_name(id),
384        schema,
385    };
386    let r = check::resolve(&sp.schema, p)?;
387    if !row.get::<_, bool>(4) {
388        if row.get::<_, Option<&str>>(2) != Some(fingerprint) {
389            return Err(Attempt::Failed(Error::RequestIdConflict));
390        }
391        let mut resp: Response =
392            serde_json::from_str(row.get::<_, Option<&str>>(3).unwrap_or("null")).map_err(|e| {
393                Attempt::Failed(Error::Unavailable(format!("stored response: {e}")))
394            })?;
395        run::rehydrate_claims(tx, &sp, &r, &mut resp).await?;
396        resp.replayed = true;
397        return Ok(resp);
398    }
399    let mut results = fireweed_dsl::exec::Results::default();
400    for st in &r.statements {
401        if !results.push(run::statement(tx, &sp, st).await?) {
402            break;
403        }
404    }
405    let is_rejected = results.is_rejected();
406    let resp = results.response(p.request_id.clone(), durability);
407    // A rejection undoes the statements but keeps the request record.
408    if is_rejected {
409        tx.batch_execute("ROLLBACK TO SAVEPOINT program").await?;
410    }
411    let Some(rid) = &p.request_id else {
412        return Ok(resp);
413    };
414    // Claims are recorded as ids and tokens; a replay re-reads the items.
415    let recorded = fireweed_dsl::exec::compact_claims(&r, &resp);
416    let mut q = Q::default();
417    let (id, doc) = (
418        q.bind(Some(rid.clone())),
419        q.bind(Some(
420            serde_json::to_string(&recorded).expect("responses serialize"),
421        )),
422    );
423    q.sql = format!(
424        "UPDATE \"{}\".fw_requests SET response = {doc}::jsonb WHERE request_id = {id}",
425        sp.schema_name
426    );
427    rows(tx, &q).await?;
428    Ok(resp)
429}
430
431/// Writes back time-driven state and deletes what retention has expired,
432/// at most `batch` rows per object (API-008 §Time). Rows other
433/// transactions hold are skipped.
434pub async fn sweep(c: &mut Client, tenant: &str, space: &str, batch: u32) -> Result<Swept> {
435    let (id, schema) = load(c, tenant, space).await?.ok_or(Error::SpaceNotFound)?;
436    let sp = Space {
437        id,
438        schema_name: ddl::schema_name(id),
439        schema,
440    };
441    let tx = c.transaction().await.map_err(db)?;
442    let out = run::sweep(&tx, &sp, batch as i64).await.map_err(db)?;
443    tx.commit().await.map_err(db)?;
444    Ok(out)
445}