fireweed-dsl-postgres 0.34.0

PostgreSQL executor for Fireweed's data-plane DSL (API-008): DDL from schemas and plain SQL for each statement.
Documentation
//! Runs the shared DSL conformance suite (API-008 §Conformance) against
//! PostgreSQL, and the checks only PostgreSQL has: the indexes a schema
//! creates, and an insert that waits on a concurrent insert of the same key.
//! Needs `FIREWEED_PG_TEST_URL`; without it every test skips. Each test uses
//! its own space.

use fireweed_dsl::{Applied, Program, Response, Result, Schema, Status, from_yaml};
use fireweed_dsl_conformance::{Conn, Executor, SCHEMA, Swept, space, suite};
use fireweed_dsl_postgres::{apply_schema, execute, execute_batch, get_schema, sweep};
use tokio_postgres::{Client, NoTls};

struct Pg {
    url: String,
}

impl Pg {
    fn from_env() -> Option<Pg> {
        Some(Pg {
            url: std::env::var("FIREWEED_PG_TEST_URL").ok()?,
        })
    }
}

/// A connection with its own single-threaded runtime: every call runs inside
/// `block_on`, which also drives the connection task.
struct PgConn {
    rt: tokio::runtime::Runtime,
    c: Client,
}

impl Executor for Pg {
    type Conn = PgConn;
    fn connect(&self) -> PgConn {
        let rt = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()
            .unwrap();
        let c = rt.block_on(async {
            let (c, conn) = tokio_postgres::connect(&self.url, NoTls)
                .await
                .expect("connect");
            tokio::spawn(conn);
            c
        });
        PgConn { rt, c }
    }
}

impl PgConn {
    fn schema_name(&mut self, t: &str, sp: &str) -> String {
        let c = &self.c;
        self.rt.block_on(async {
            c.query_one(
                "SELECT 'fws_' || id FROM fireweed.spaces WHERE tenant = $1 AND space = $2",
                &[&t, &sp],
            )
            .await
            .unwrap()
            .get(0)
        })
    }

    fn stat(&mut self, t: &str, sp: &str, sql: &str) -> i64 {
        let schema = self.schema_name(t, sp);
        let c = &self.c;
        self.rt.block_on(async {
            c.batch_execute("SELECT pg_stat_force_next_flush(); SELECT pg_stat_clear_snapshot();")
                .await
                .unwrap();
            c.query_one(sql, &[&schema]).await.unwrap().get(0)
        })
    }
}

impl Conn for PgConn {
    fn apply_schema(
        &mut self,
        t: &str,
        sp: &str,
        s: &Schema,
        expected: Option<i64>,
    ) -> Result<Applied> {
        self.rt
            .block_on(apply_schema(&mut self.c, t, sp, s, expected))
    }
    fn get_schema(&mut self, t: &str, sp: &str) -> Result<Option<Schema>> {
        self.rt.block_on(get_schema(&self.c, t, sp))
    }
    fn execute(&mut self, t: &str, sp: &str, p: &Program) -> Result<Response> {
        self.rt.block_on(execute(&mut self.c, t, sp, p))
    }
    fn execute_batch(
        &mut self,
        t: &str,
        sp: &str,
        ps: &[Program],
    ) -> Result<Vec<Result<Response>>> {
        self.rt.block_on(execute_batch(&mut self.c, t, sp, ps))
    }
    fn sweep(&mut self, t: &str, sp: &str, batch: u32) -> Result<Swept> {
        let s = self.rt.block_on(sweep(&mut self.c, t, sp, batch))?;
        Ok(Swept {
            expired_leases: s.expired_leases,
            deleted: s.deleted,
        })
    }
    fn now(&mut self) -> String {
        let c = &self.c;
        self.rt.block_on(async {
            match c.query_one("SELECT fireweed.now()::text", &[]).await {
                Ok(r) => r.get(0),
                // No catalog yet: the server's clock.
                Err(_) => c.query_one("SELECT now()::text", &[]).await.unwrap().get(0),
            }
        })
    }
    fn set_now(&mut self, at: Option<&str>) {
        let sql = match at {
            Some(at) => format!("SET fireweed.now = '{at}'"),
            None => "RESET fireweed.now".into(),
        };
        self.rt.block_on(self.c.batch_execute(&sql)).unwrap();
    }
    fn stored_response(&mut self, t: &str, sp: &str, rid: &str) -> Option<String> {
        let schema = self.schema_name(t, sp);
        let c = &self.c;
        self.rt.block_on(async {
            c.query_opt(
                &format!(
                    "SELECT response::text FROM \"{schema}\".fw_requests WHERE request_id = $1"
                ),
                &[&rid],
            )
            .await
            .unwrap()
            .and_then(|r| r.get(0))
        })
    }
    fn table_scans(&mut self, t: &str, sp: &str) -> i64 {
        self.stat(
            t,
            sp,
            "SELECT seq_scan FROM pg_stat_user_tables WHERE schemaname = $1 AND relname = 'q_work'",
        )
    }
    fn index_reads(&mut self, t: &str, sp: &str) -> Option<i64> {
        Some(self.stat(
            t,
            sp,
            "SELECT coalesce(sum(idx_tup_read), 0)::bigint FROM pg_stat_user_indexes WHERE schemaname = $1 AND relname = 'q_work'",
        ))
    }
    fn analyze(&mut self, t: &str, sp: &str) {
        let schema = self.schema_name(t, sp);
        self.rt
            .block_on(
                self.c
                    .batch_execute(&format!("VACUUM ANALYZE \"{schema}\".q_work")),
            )
            .unwrap();
    }
}

suite!(Pg::from_env());

#[test]
fn schema_creates_tables_and_indexes() {
    let Some(pg) = Pg::from_env() else { return };
    let mut c = pg.connect();
    let sp = space("ddl-pg");
    let s: Schema = from_yaml(SCHEMA).unwrap();
    c.apply_schema("t", &sp, &s, None).unwrap();
    let schema_name = c.schema_name("t", &sp);
    let idx: Vec<String> = c.rt.block_on(async {
        c.c.query(
            "SELECT indexdef FROM pg_indexes WHERE schemaname = $1 ORDER BY indexdef",
            &[&schema_name],
        )
        .await
        .unwrap()
        .iter()
        .map(|r| r.get(0))
        .collect()
    });
    let has = |s: &str| idx.iter().any(|d| d.contains(s));
    assert!(
        has("q_work USING btree (due_at, priority, id) WHERE (state = ANY"),
        "{idx:#?}"
    );
    assert!(has("q_work USING gin (f_awaits)"), "{idx:#?}");
    assert!(
        has("UNIQUE INDEX") && has("t_slots USING btree (f_contact, f_hour)"),
        "{idx:#?}"
    );
}

/// An insert that waits on a concurrent insert of the same key reports the
/// winner's id, not null.
#[tokio::test]
async fn insert_racing_the_same_key_reports_its_id() {
    let Ok(url) = std::env::var("FIREWEED_PG_TEST_URL") else {
        return;
    };
    let connect = || async {
        let (c, conn) = tokio_postgres::connect(&url, NoTls).await.unwrap();
        tokio::spawn(conn);
        c
    };
    let mut c = connect().await;
    let sp = space("race-key");
    let s: Schema = from_yaml(SCHEMA).unwrap();
    apply_schema(&mut c, "t", &sp, &s, None).await.unwrap();
    let schema: String = c
        .query_one(
            "SELECT 'fws_' || id FROM fireweed.spaces WHERE tenant = 't' AND space = $1",
            &[&sp],
        )
        .await
        .unwrap()
        .get(0);
    let at: String = c.query_one("SELECT now()::text", &[]).await.unwrap().get(0);
    let doc = format!(
        "request_id: i1\nissued_at: \"{at}\"\nstatements:\n  - insert: {{into: work, rows: [{{key: k1}}]}}\n"
    );
    let p: Program = from_yaml(&doc).unwrap();
    let mut other = connect().await;
    let tx = other.transaction().await.unwrap();
    tx.batch_execute(&format!(
        "INSERT INTO \"{schema}\".q_work (key, state, priority, due_at, attempts, version, created_at, updated_at)
         VALUES ('k1', 'pending', 0, now(), 0, 1, now(), now())"
    ))
    .await
    .unwrap();
    let (sp2, p2) = (sp.clone(), p.clone());
    let mut c2 = connect().await;
    let waiting = tokio::spawn(async move { execute(&mut c2, "t", &sp2, &p2).await.unwrap() });
    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
    tx.commit().await.unwrap();
    let r = waiting.await.unwrap();
    let e = &r.results[0][0];
    assert_eq!(e["status"], "exists");
    assert!(e["id"].is_i64(), "{e}");
    // The record replays the same id.
    let again = execute(&mut c, "t", &sp, &p).await.unwrap();
    assert!(again.replayed && again.status == Status::Committed);
    assert_eq!(again.results[0][0]["id"], e["id"]);
}