fireweed-dsl-postgres 0.37.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, BoxFuture, Program, Response, Result, Schema, Status, from_yaml};
use fireweed_dsl_conformance::{Conn, Harness, SCHEMA, runtime, space, suite};
use tokio::sync::Mutex;
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()?,
        })
    }
}

/// One connection as an executor, over the crate's functions, so a
/// connection setting such as `fireweed.now` holds for every call.
struct OneConn(Mutex<Client>);

impl fireweed_dsl::Executor for OneConn {
    fn apply_schema<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        schema: &'a Schema,
        expected: Option<i64>,
    ) -> BoxFuture<'a, Result<Applied>> {
        Box::pin(async move {
            let mut c = self.0.lock().await;
            fireweed_dsl_postgres::apply_schema(&mut c, tenant, space, schema, expected).await
        })
    }
    fn get_schema<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
    ) -> BoxFuture<'a, Result<Option<Schema>>> {
        Box::pin(async move {
            let c = self.0.lock().await;
            fireweed_dsl_postgres::get_schema(&c, tenant, space).await
        })
    }
    fn execute<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        program: &'a Program,
    ) -> BoxFuture<'a, Result<Response>> {
        Box::pin(async move {
            let mut c = self.0.lock().await;
            fireweed_dsl_postgres::execute(&mut c, tenant, space, program).await
        })
    }
    fn execute_batch<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        programs: &'a [Program],
    ) -> BoxFuture<'a, Result<Vec<Result<Response>>>> {
        Box::pin(async move {
            let mut c = self.0.lock().await;
            fireweed_dsl_postgres::execute_batch(&mut c, tenant, space, programs).await
        })
    }
    fn sweep<'a>(
        &'a self,
        tenant: &'a str,
        space: &'a str,
        batch: u32,
    ) -> BoxFuture<'a, Result<fireweed_dsl::Swept>> {
        Box::pin(async move {
            let mut c = self.0.lock().await;
            fireweed_dsl_postgres::sweep(&mut c, tenant, space, batch).await
        })
    }
}

/// 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,
    pg: OneConn,
}

impl Harness for Pg {
    type Conn = PgConn;
    fn connect(&self) -> PgConn {
        let rt = runtime();
        let c = rt.block_on(async {
            let (c, conn) = tokio_postgres::connect(&self.url, NoTls)
                .await
                .expect("connect");
            tokio::spawn(conn);
            c
        });
        PgConn {
            rt,
            pg: OneConn(Mutex::new(c)),
        }
    }
}

impl PgConn {
    /// The connection, for a probe's own query. Calls run one at a time.
    fn c(&self) -> tokio::sync::MutexGuard<'_, Client> {
        self.pg.0.try_lock().expect("no call in flight")
    }

    fn schema_name(&mut self, t: &str, sp: &str) -> String {
        self.rt.block_on(async {
            self.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);
        self.rt.block_on(async {
            let c = self.c();
            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 {
    type Executor = OneConn;
    fn executor(&self) -> (&tokio::runtime::Runtime, &OneConn) {
        (&self.rt, &self.pg)
    }
    fn now(&mut self) -> String {
        self.rt.block_on(async {
            let c = self.c();
            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);
        self.rt.block_on(async {
            self.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();
    fireweed_dsl_postgres::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 {
        fireweed_dsl_postgres::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 = fireweed_dsl_postgres::execute(&mut c, "t", &sp, &p)
        .await
        .unwrap();
    assert!(again.replayed && again.status == Status::Committed);
    assert_eq!(again.results[0][0]["id"], e["id"]);
}

/// A consumer's view: the shared programs through `Arc<dyn Executor>`.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn through_the_executor_trait() {
    let Some(pg) = Pg::from_env() else { return };
    let e = fireweed_dsl_postgres::PgExecutor::new(pg.url.parse().unwrap());
    fireweed_dsl_conformance::interface::through_executor(std::sync::Arc::new(e)).await;
}