Skip to main content

fireweed_dsl_postgres/
lib.rs

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