flow-abi 0.1.0-rc.5

The host boundary's value encoding: the binary encoding and the JSON form, the canonical form and its hash, JSON Schemas, Tool signatures, and the answers a Tool call passes.
Documentation
//! The answers the dispatch seam passes, in the value encoding: what became
//! of a call ([`Outcome`]), what a host did with an answer offered to it
//! ([`Ack`]), and why it has no type to encode an answer at ([`Untyped`]),
//! each with the one binary form every carrier of it writes and reads
//! (`abi.md`, *The Tool process protocol*).

use crate::json::Json;
use crate::wire;
use crate::wire::Rest;

wire! {
    /// What a host did with a `reply`: the three results every route that
    /// offers an answer returns (`history.md`, *Open calls*).
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub enum Ack {
        /// The answer is recorded.
        Ok,
        /// The call was not open; `same` says whether the answer it already
        /// has equals this one.
        AlreadyAnswered {
            /// Whether the recorded answer equals the one offered.
            same: bool,
        },
        /// The answer does not decode at the call's types, and why.
        TypeError(String),
    }
}

wire! {
    /// Why a host has no result type to give for a call a `type` asks about
    /// (`abi.md`, *Replies from outside a call*).
    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
    pub enum NoType {
        /// The host holds no run with that id.
        UnknownRun,
        /// The run never made that call.
        NoSuchCall,
        /// The run's program cannot be formed again.
        Unformed,
        /// The run's record cannot be read.
        Unreadable,
    }
}

wire! {
    /// A host's answer to `type` when it has no result type to give: why,
    /// for a program to branch on, and what it says, for a person.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub struct Untyped {
        /// Why.
        pub reason: NoType,
        /// What the host says, for a person.
        pub said: String,
    }
}

impl std::fmt::Display for Untyped {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.said)
    }
}

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

wire! {
    /// A reply's answer: a number and what follows it (`errors.md`, *Tool
    /// problems*, says what each claims).
    ///
    /// On the wire the value is in the value encoding, `V = Rest`, read at
    /// the call's result type once the reply's key has named the call; an
    /// implementation in the host's own process answers with the value
    /// itself, and an adapter that speaks JSON, or a reply supplied in JSON,
    /// with its JSON form.
    #[derive(Clone, PartialEq, Eq, Debug)]
    pub enum Outcome<V = Rest> {
        /// A value of the Tool's result type.
        Ok(V),
        /// The work did not begin, and why.
        NotStarted(String),
        /// The work began and stopped before a value, and why.
        Interrupted(String),
        /// The network to the Tool failed; `sent` says whether the request
        /// went out.
        NetworkError {
            /// Whether the request went out.
            sent: bool,
            /// Why.
            reason: String,
        },
    }
    /// Which outcome one is.
    pub enum OutcomeKind;
}

impl<V> Outcome<V> {
    /// The same outcome with its `Ok` value made by `f`.
    pub fn map<W>(self, f: impl FnOnce(V) -> W) -> Outcome<W> {
        match self {
            Outcome::Ok(value) => Outcome::Ok(f(value)),
            Outcome::NotStarted(reason) => Outcome::NotStarted(reason),
            Outcome::Interrupted(reason) => Outcome::Interrupted(reason),
            Outcome::NetworkError { sent, reason } => Outcome::NetworkError { sent, reason },
        }
    }
}

impl Outcome<Json> {
    /// The outcome in its JSON form, a value of `Result<R, ToolProblem>`
    /// (`abi.md`, *The JSON form*), as [`Outcome::from_json`] reads it.
    pub fn json(&self) -> Json {
        let one = |key: &str, value: Json| Json::Object(vec![(key.to_owned(), value)]);
        let problem = match self {
            Outcome::Ok(value) => return one("Ok", value.clone()),
            Outcome::NotStarted(reason) => one("NotStarted", Json::String(reason.clone())),
            Outcome::Interrupted(reason) => one("Interrupted", Json::String(reason.clone())),
            Outcome::NetworkError { sent, reason } => one(
                "NetworkError",
                Json::Object(vec![
                    ("sent".to_owned(), Json::Bool(*sent)),
                    ("reason".to_owned(), Json::String(reason.clone())),
                ]),
            ),
        };
        one("Err", problem)
    }

    /// Reads an outcome in its JSON form: `{"Ok": value}`,
    /// `{"Err": {"NotStarted": reason}}`, `{"Err": {"Interrupted": reason}}`
    /// or `{"Err": {"NetworkError": {"sent", "reason"}}}`, as a reply supplied
    /// in JSON is written. The `Ok` value stays in its JSON form, to be
    /// decoded at the call's result type.
    ///
    /// # Errors
    ///
    /// Why it is none of those.
    pub fn from_json(json: &Json) -> Result<Self, String> {
        let Some((key, value)) = only(json) else {
            return Err("the reply is not an object with one member".to_owned());
        };
        match key {
            "Ok" => return Ok(Outcome::Ok(value.clone())),
            "Err" => {}
            key => return Err(format!("the reply's {key} is neither Ok nor Err")),
        }
        let Some((key, value)) = only(value) else {
            return Err(
                "the reply's Err is not a ToolProblem, an object with one member".to_owned(),
            );
        };
        let text = |value: &Json| match value {
            Json::String(text) => Ok(text.clone()),
            Json::Null | Json::Bool(_) | Json::Number(_) | Json::Array(_) | Json::Object(_) => {
                Err(format!("the reply's {key} carries no reason"))
            }
        };
        match key {
            "NotStarted" => Ok(Outcome::NotStarted(text(value)?)),
            "Interrupted" => Ok(Outcome::Interrupted(text(value)?)),
            "NetworkError" => {
                let (Json::Object(fields), Some(Json::Bool(sent)), Some(Json::String(reason))) =
                    (value, value.get("sent"), value.get("reason"))
                else {
                    return Err(malformed());
                };
                if fields.len() != 2 {
                    return Err(malformed());
                }
                Ok(Outcome::NetworkError {
                    sent: *sent,
                    reason: reason.clone(),
                })
            }
            key => Err(format!("the reply's {key} is no ToolProblem")),
        }
    }
}

/// The one member of `json`, when it is an object with exactly one.
fn only(json: &Json) -> Option<(&str, &Json)> {
    let Json::Object(members) = json else {
        return None;
    };
    let [(key, value)] = members.as_slice() else {
        return None;
    };
    Some((key.as_str(), value))
}

/// Why a `NetworkError` written in JSON is not one.
fn malformed() -> String {
    "the reply's NetworkError is not {\"sent\", \"reason\"}".to_owned()
}