Skip to main content

flow_abi/
answer.rs

1//! The answers the dispatch seam passes, in the value encoding: what became
2//! of a call ([`Outcome`]), what a host did with an answer offered to it
3//! ([`Ack`]), and why it has no type to encode an answer at ([`Untyped`]),
4//! each with the one binary form every carrier of it writes and reads
5//! (`abi.md`, *The Tool process protocol*).
6
7use crate::json::Json;
8use crate::wire;
9use crate::wire::Rest;
10
11wire! {
12    /// What a host did with a `reply`: the three results every route that
13    /// offers an answer returns (`history.md`, *Open calls*).
14    #[derive(Clone, PartialEq, Eq, Debug)]
15    pub enum Ack {
16        /// The answer is recorded.
17        Ok,
18        /// The call was not open; `same` says whether the answer it already
19        /// has equals this one.
20        AlreadyAnswered {
21            /// Whether the recorded answer equals the one offered.
22            same: bool,
23        },
24        /// The answer does not decode at the call's types, and why.
25        TypeError(String),
26    }
27}
28
29wire! {
30    /// Why a host has no result type to give for a call a `type` asks about
31    /// (`abi.md`, *Replies from outside a call*).
32    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
33    pub enum NoType {
34        /// The host holds no run with that id.
35        UnknownRun,
36        /// The run never made that call.
37        NoSuchCall,
38        /// The run's program cannot be formed again.
39        Unformed,
40        /// The run's record cannot be read.
41        Unreadable,
42    }
43}
44
45wire! {
46    /// A host's answer to `type` when it has no result type to give: why,
47    /// for a program to branch on, and what it says, for a person.
48    #[derive(Clone, PartialEq, Eq, Debug)]
49    pub struct Untyped {
50        /// Why.
51        pub reason: NoType,
52        /// What the host says, for a person.
53        pub said: String,
54    }
55}
56
57impl std::fmt::Display for Untyped {
58    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
59        f.write_str(&self.said)
60    }
61}
62
63impl std::error::Error for Untyped {}
64
65wire! {
66    /// A reply's answer: a number and what follows it (`errors.md`, *Tool
67    /// problems*, says what each claims).
68    ///
69    /// On the wire the value is in the value encoding, `V = Rest`, read at
70    /// the call's result type once the reply's key has named the call; an
71    /// implementation in the host's own process answers with the value
72    /// itself, and an adapter that speaks JSON, or a reply supplied in JSON,
73    /// with its JSON form.
74    #[derive(Clone, PartialEq, Eq, Debug)]
75    pub enum Outcome<V = Rest> {
76        /// A value of the Tool's result type.
77        Ok(V),
78        /// The work did not begin, and why.
79        NotStarted(String),
80        /// The work began and stopped before a value, and why.
81        Interrupted(String),
82        /// The network to the Tool failed; `sent` says whether the request
83        /// went out.
84        NetworkError {
85            /// Whether the request went out.
86            sent: bool,
87            /// Why.
88            reason: String,
89        },
90    }
91    /// Which outcome one is.
92    pub enum OutcomeKind;
93}
94
95impl<V> Outcome<V> {
96    /// The same outcome with its `Ok` value made by `f`.
97    pub fn map<W>(self, f: impl FnOnce(V) -> W) -> Outcome<W> {
98        match self {
99            Outcome::Ok(value) => Outcome::Ok(f(value)),
100            Outcome::NotStarted(reason) => Outcome::NotStarted(reason),
101            Outcome::Interrupted(reason) => Outcome::Interrupted(reason),
102            Outcome::NetworkError { sent, reason } => Outcome::NetworkError { sent, reason },
103        }
104    }
105}
106
107impl Outcome<Json> {
108    /// The outcome in its JSON form, a value of `Result<R, ToolProblem>`
109    /// (`abi.md`, *The JSON form*), as [`Outcome::from_json`] reads it.
110    pub fn json(&self) -> Json {
111        let one = |key: &str, value: Json| Json::Object(vec![(key.to_owned(), value)]);
112        let problem = match self {
113            Outcome::Ok(value) => return one("Ok", value.clone()),
114            Outcome::NotStarted(reason) => one("NotStarted", Json::String(reason.clone())),
115            Outcome::Interrupted(reason) => one("Interrupted", Json::String(reason.clone())),
116            Outcome::NetworkError { sent, reason } => one(
117                "NetworkError",
118                Json::Object(vec![
119                    ("sent".to_owned(), Json::Bool(*sent)),
120                    ("reason".to_owned(), Json::String(reason.clone())),
121                ]),
122            ),
123        };
124        one("Err", problem)
125    }
126
127    /// Reads an outcome in its JSON form: `{"Ok": value}`,
128    /// `{"Err": {"NotStarted": reason}}`, `{"Err": {"Interrupted": reason}}`
129    /// or `{"Err": {"NetworkError": {"sent", "reason"}}}`, as a reply supplied
130    /// in JSON is written. The `Ok` value stays in its JSON form, to be
131    /// decoded at the call's result type.
132    ///
133    /// # Errors
134    ///
135    /// Why it is none of those.
136    pub fn from_json(json: &Json) -> Result<Self, String> {
137        let Some((key, value)) = only(json) else {
138            return Err("the reply is not an object with one member".to_owned());
139        };
140        match key {
141            "Ok" => return Ok(Outcome::Ok(value.clone())),
142            "Err" => {}
143            key => return Err(format!("the reply's {key} is neither Ok nor Err")),
144        }
145        let Some((key, value)) = only(value) else {
146            return Err(
147                "the reply's Err is not a ToolProblem, an object with one member".to_owned(),
148            );
149        };
150        let text = |value: &Json| match value {
151            Json::String(text) => Ok(text.clone()),
152            Json::Null | Json::Bool(_) | Json::Number(_) | Json::Array(_) | Json::Object(_) => {
153                Err(format!("the reply's {key} carries no reason"))
154            }
155        };
156        match key {
157            "NotStarted" => Ok(Outcome::NotStarted(text(value)?)),
158            "Interrupted" => Ok(Outcome::Interrupted(text(value)?)),
159            "NetworkError" => {
160                let (Json::Object(fields), Some(Json::Bool(sent)), Some(Json::String(reason))) =
161                    (value, value.get("sent"), value.get("reason"))
162                else {
163                    return Err(malformed());
164                };
165                if fields.len() != 2 {
166                    return Err(malformed());
167                }
168                Ok(Outcome::NetworkError {
169                    sent: *sent,
170                    reason: reason.clone(),
171                })
172            }
173            key => Err(format!("the reply's {key} is no ToolProblem")),
174        }
175    }
176}
177
178/// The one member of `json`, when it is an object with exactly one.
179fn only(json: &Json) -> Option<(&str, &Json)> {
180    let Json::Object(members) = json else {
181        return None;
182    };
183    let [(key, value)] = members.as_slice() else {
184        return None;
185    };
186    Some((key.as_str(), value))
187}
188
189/// Why a `NetworkError` written in JSON is not one.
190fn malformed() -> String {
191    "the reply's NetworkError is not {\"sent\", \"reason\"}".to_owned()
192}