1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
//! 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()
}