fireweed-dsl 0.37.0

Fireweed's data-plane DSL (API-008): schema and program documents, and the checker that resolves a program against a schema.
Documentation
//! What API-008 defines once for every executor: a statement's outcome,
//! `expect` handling, the response, and how a request record keeps and
//! restores claim results. Executors lower statements to their own SQL and
//! use these to give the same results.

use std::collections::BTreeMap;

use serde_json::{Value, json};

use crate::check::{QueueObj, RStatement, Resolved};
use crate::{Durability, Expect, FieldType, OnUnmet, RejectReason, Rejection, Response, Status};

/// The system columns a claimed item reports (API-008 §claim), besides its
/// lease token and its declared fields.
pub const CLAIMED_COLUMNS: &[(&str, FieldType)] = &[
    ("id", FieldType::Int),
    ("key", FieldType::Text),
    ("attempts", FieldType::Int),
    ("priority", FieldType::Int),
    ("version", FieldType::Int),
    ("body", FieldType::Json),
];

/// What one statement did.
#[derive(Clone, Debug, PartialEq)]
pub enum StatementOutcome {
    /// The statement's result (API-008 gives its shape per statement).
    Done(Value),
    /// The statement rejected the program.
    Rejected(RejectReason),
}

/// The outcome of an unmet `expect`, if it is unmet: a rejection, or with
/// `on_unmet: report` a result saying so (API-008 §update). A guarded
/// write has already skipped its changes when the count missed.
pub fn unmet(expect: &Option<Expect>, matched: i64) -> Option<StatementOutcome> {
    let e = expect.as_ref().filter(|e| !e.holds(matched as u64))?;
    Some(match e.on_unmet {
        OnUnmet::Reject => StatementOutcome::Rejected(RejectReason::ExpectUnmet),
        OnUnmet::Report => StatementOutcome::Done(json!({"matched": matched, "met": false})),
    })
}

/// Adds `met: true` to a result when the statement had an `expect`.
pub fn with_met(mut out: Value, expect: &Option<Expect>) -> Value {
    if expect.is_some() {
        out["met"] = json!(true);
    }
    out
}

/// A program's statements, run in order until one rejects.
#[derive(Debug, Default)]
pub struct Results {
    results: Vec<Value>,
    rejected: Option<Rejection>,
}

impl Results {
    /// Records the next statement's outcome. False once the program has
    /// rejected: run no more statements.
    pub fn push(&mut self, outcome: StatementOutcome) -> bool {
        match outcome {
            StatementOutcome::Done(v) => self.results.push(v),
            StatementOutcome::Rejected(reason) => {
                self.rejected = Some(Rejection {
                    statement: self.results.len(),
                    reason,
                });
            }
        }
        self.rejected.is_none()
    }

    /// True if a statement rejected: the executor rolls the statements back
    /// and keeps the request record (API-008 §Transactions).
    pub fn is_rejected(&self) -> bool {
        self.rejected.is_some()
    }

    /// The program's response. A rejected program reports no results.
    pub fn response(self, request_id: Option<String>, durability: Durability) -> Response {
        let rejected = self.rejected.is_some();
        Response {
            request_id,
            status: if rejected {
                Status::Rejected
            } else {
                Status::Committed
            },
            rejected: self.rejected,
            results: if rejected { vec![] } else { self.results },
            durability,
            replayed: false,
        }
    }
}

/// The response to record: claim results keep only ids and tokens, so a
/// record never copies item bodies (ADR-027 §5).
pub fn compact_claims(r: &Resolved, resp: &Response) -> Response {
    let mut out = resp.clone();
    for (st, res) in r.statements.iter().zip(out.results.iter_mut()) {
        if matches!(st, RStatement::Claim(_))
            && let Value::Array(items) = res
        {
            for it in items.iter_mut() {
                *it = json!({"id": it["id"], "token": it["token"]});
            }
        }
    }
    out
}

/// The claims in a recorded response that a replay re-reads: for each claim
/// statement with items, its index, its queue and the item ids.
pub fn recorded_claims<'r>(
    r: &'r Resolved,
    resp: &Response,
) -> Vec<(usize, &'r QueueObj, Vec<i64>)> {
    r.statements
        .iter()
        .zip(&resp.results)
        .enumerate()
        .filter_map(|(i, (st, res))| match (st, res) {
            (RStatement::Claim(c), Value::Array(items)) if !items.is_empty() => Some((
                i,
                &c.queue,
                items.iter().filter_map(|it| it["id"].as_i64()).collect(),
            )),
            _ => None,
        })
        .collect()
}

/// Puts re-read items into a replayed claim's result: each item's current
/// fields, with the token the claim granted. `current` is keyed by id.
pub fn rehydrate_claim(result: &mut Value, mut current: BTreeMap<i64, Value>) {
    let Value::Array(items) = result else { return };
    for it in items.iter_mut() {
        if let Some(mut v) = it["id"].as_i64().and_then(|id| current.remove(&id)) {
            v["token"] = it["token"].clone();
            *it = v;
        }
    }
}