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
//! Fireweed's data-plane DSL (API-008).
//!
//! A [`Schema`] declares a space's queues, tables and reads. A [`Program`]
//! is a list of [`Statement`]s run as one transaction. Both are read from
//! YAML or JSON. [`check::resolve`] checks a program against a schema and
//! returns the resolved statements an executor lowers to SQL. [`Executor`]
//! is the interface every backend implements, so a consumer can run against
//! PostgreSQL or Turso without depending on either; [`exec`] holds what
//! API-008 defines once for every executor.

#![forbid(unsafe_code)]

pub mod check;
mod doc;
pub mod exec;
mod executor;

pub use doc::*;
pub use executor::{BoxFuture, Executor, Swept};

/// Errors that change nothing and are not recorded (API-008 §Transactions).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
    /// The document doesn't parse, or the program doesn't check against the schema.
    Invalid(String),
    SpaceNotFound,
    /// `apply_schema` with an expected version that isn't the stored one.
    SchemaConflict {
        current: Option<i64>,
    },
    /// A request id reused with a different program.
    RequestIdConflict,
    /// The request was issued before the space's horizon: its record may be
    /// gone, so it is refused rather than run twice (ADR-027 D61).
    RequestExpired,
    /// A guarded program kept failing to serialize.
    Contention,
    /// This process doesn't hold the space: another owner does, or a later
    /// one fenced it. The caller rechecks placement (ADR-027 §10).
    NotOwner,
    /// The backend can't take writes now (its log is behind); the caller
    /// retries after `after_ms`.
    RetryLater {
        after_ms: u64,
    },
    /// A database error.
    Unavailable(String),
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::Invalid(m) => write!(f, "invalid: {m}"),
            Error::SpaceNotFound => write!(f, "space not found"),
            Error::SchemaConflict { current } => {
                write!(f, "schema conflict (current version {current:?})")
            }
            Error::RequestIdConflict => write!(f, "request id reused with a different program"),
            Error::RequestExpired => write!(f, "request expired"),
            Error::Contention => write!(f, "contention"),
            Error::NotOwner => write!(f, "not owner: this process does not hold the space"),
            Error::RetryLater { after_ms } => write!(f, "retry later: after {after_ms} ms"),
            Error::Unavailable(m) => write!(f, "unavailable: {m}"),
        }
    }
}

impl std::error::Error for Error {}

impl Error {
    /// This process doesn't hold the space: [`Error::NotOwner`]. Stop
    /// serving it and recheck placement.
    pub fn is_superseded(&self) -> bool {
        matches!(self, Error::NotOwner)
    }

    /// Another engine holds the space's files: [`Error::NotOwner`], the same
    /// as [`Error::is_superseded`].
    pub fn is_busy(&self) -> bool {
        matches!(self, Error::NotOwner)
    }

    /// The backend is behind: [`Error::RetryLater`].
    pub fn is_rate_limited(&self) -> bool {
        matches!(self, Error::RetryLater { .. })
    }

    /// Whether sending the same program again, with the same request id and
    /// `issued_at`, may succeed: contention, `retry_later` and
    /// `unavailable`. A replay never runs a committed program twice.
    pub fn is_retryable(&self) -> bool {
        matches!(
            self,
            Error::Contention | Error::RetryLater { .. } | Error::Unavailable(_)
        )
    }
}

pub type Result<T> = std::result::Result<T, Error>;

pub(crate) fn invalid<T>(msg: impl Into<String>) -> Result<T> {
    Err(Error::Invalid(msg.into()))
}

/// Reads a YAML or JSON document (JSON is YAML). The YAML is read into JSON
/// first, so a statement or predicate is a single-key map in both.
pub fn from_yaml<T: serde::de::DeserializeOwned>(text: &str) -> Result<T> {
    let v: serde_json::Value =
        serde_norway::from_str(text).map_err(|e| Error::Invalid(e.to_string()))?;
    serde_json::from_value(v).map_err(|e| Error::Invalid(e.to_string()))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn errors_classify_the_same_on_every_backend() {
        let limited = Error::RetryLater { after_ms: 50 };
        let db = Error::Unavailable("08006: connection failure".into());
        assert!(Error::NotOwner.is_superseded() && Error::NotOwner.is_busy());
        assert!(!Error::NotOwner.is_retryable());
        assert!(limited.is_rate_limited() && limited.is_retryable());
        assert!(db.is_retryable() && !db.is_superseded() && !db.is_rate_limited());
        assert!(Error::Contention.is_retryable());
        for e in [
            Error::Invalid("x".into()),
            Error::SpaceNotFound,
            Error::SchemaConflict { current: None },
            Error::RequestIdConflict,
            Error::RequestExpired,
        ] {
            assert!(!e.is_retryable(), "{e}");
        }
    }
}