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
193
194
195
196
197
198
199
200
//! Where an admitted offloadable invocation runs.
//!
//! An action whose contract declares [`Offload`] is a pure transform of
//! content: its inputs are the content its invocation names, its outputs are
//! content, and they depend on the inputs alone. The action API admits such
//! an invocation exactly as any other — who may invoke never changes — and
//! then asks the device's [`ActionOffload`] whether another of the person's
//! devices should run it. When one did, the API answers the invocation with
//! that output ([`Offloaded::Ran`]); otherwise, for any reason at all, the
//! app's own handler runs it here ([`Offloaded::RunHere`]), so a failed or
//! unreachable worker only ever costs time, never a different answer.
//!
//! The inputs a job may read are only the content the invocation's own
//! content parameters name ([`content_inputs`]), as the invoker's workspace
//! reaches it; never a path, an environment or an argument vector.
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use crate::{
ARGUMENTS_JSON_PREFIX, ActionAddress, ActionOutput, ActionParam, Offload, named_reference,
remote::InvokeRequest,
};
/// One admitted invocation of an offloadable action.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct OffloadRequest {
/// The workspace it was invoked in.
pub workspace: String,
pub app_id: String,
/// The invoked action.
pub address: ActionAddress,
/// The contract's declaration: what the work needs of a device.
pub offload: Offload,
/// Its inputs: the content hashes its arguments name, in order.
pub inputs: Vec<String>,
}
/// What became of an offload request.
#[derive(Clone, Debug, PartialEq)]
pub enum Offloaded {
/// Another device ran it; this is what a local run returns.
Ran {
output: ActionOutput,
/// The device that ran it, as the offloader names devices.
device: String,
/// Wall time from the request to the output.
elapsed: Duration,
},
/// Run it here, through the app's handler, and why.
RunHere {
/// Why it was not offloaded: no better-placed device, or what
/// failed remotely.
reason: String,
},
}
/// A boxed, sendable future, as [`ActionOffload`] answers.
pub type OffloadFuture<'a> = Pin<Box<dyn Future<Output = Offloaded> + Send + 'a>>;
/// The device's route for offloadable invocations.
pub trait ActionOffload: Send + Sync {
/// Run `request` on the best-placed other device, or say why it should
/// run here.
fn offload(&self, request: OffloadRequest) -> OffloadFuture<'_>;
/// [`Self::offload`] for the invocation `request` was admitted from, as
/// this device's API would send it to another device: a route that runs
/// it elsewhere sends the invocation the person made, so the device that
/// runs it answers that one and a retry there is not a second run. A
/// route with no device to send it to keeps its own way of running it.
fn offload_invocation(
&self,
request: OffloadRequest,
invocation: InvokeRequest,
) -> OffloadFuture<'_> {
let _ = invocation;
self.offload(request)
}
}
/// The content an invocation's `arguments` name through the content
/// parameters among `params` ([`ActionParam::is_content`],
/// [`ActionParam::is_content_list`]), in declaration order: a `tilo.content:`
/// address, or the reference alone. Each is named by its address, which is
/// what the caller's workspace keeps and hands another device, whether or not
/// the record that names it keeps the content sealed
/// ([`content_address`](tilo_content::content_address)).
pub fn content_inputs(
params: &[ActionParam],
arguments: &serde_json::Map<String, serde_json::Value>,
) -> Result<Vec<String>, String> {
let address = |name: &str, value: &serde_json::Value| -> Result<String, String> {
let text = value
.as_str()
.ok_or_else(|| format!("`{name}` is not a content address"))?;
named_reference(text)
.and_then(tilo_content::content_address)
.ok_or_else(|| format!("`{name}` is not a content address"))
};
let mut inputs = Vec::new();
for param in params {
let Some(value) = arguments
.get(param.name.as_ref())
.filter(|value| !value.is_null())
else {
continue;
};
if param.is_content() {
inputs.push(address(¶m.name, value)?);
} else if param.is_content_list() {
let items = value
.as_array()
.ok_or_else(|| format!("`{}` is not a list of content", param.name))?;
for item in items {
inputs.push(address(¶m.name, item)?);
}
}
}
Ok(inputs)
}
/// [`content_inputs`] of an invocation's wire `argument`: its named
/// arguments ([`ARGUMENTS_JSON_PREFIX`]), or none.
pub fn argument_inputs(
params: &[ActionParam],
argument: Option<&str>,
) -> Result<Vec<String>, String> {
let Some(argument) = argument else {
return Ok(Vec::new());
};
let json = argument
.strip_prefix(ARGUMENTS_JSON_PREFIX)
.ok_or("the invocation's arguments are not named")?;
let arguments: serde_json::Map<String, serde_json::Value> =
serde_json::from_str(json).map_err(|error| format!("unreadable arguments: {error}"))?;
content_inputs(params, &arguments)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ParamType;
#[test]
fn the_inputs_are_the_content_the_content_parameters_name_in_order() {
let a = "a".repeat(64);
let b = "b".repeat(64);
let params = vec![
ActionParam::required("images", ParamType::Array, "Images").as_content_list(),
ActionParam::optional("label", ParamType::Text, "A label"),
ActionParam::optional("cover", ParamType::Text, "Cover").as_content(),
];
let arguments = serde_json::json!({
"images": [a, format!("tilo.content:{b}")],
"label": "not content",
"cover": a,
});
let arguments = arguments.as_object().unwrap();
assert_eq!(
content_inputs(¶ms, arguments),
Ok(vec![a.clone(), b, a])
);
assert!(params[0].is_content_list() && !params[0].is_content());
assert!(params[2].is_content() && !params[2].is_content_list());
let wire = format!(
"{ARGUMENTS_JSON_PREFIX}{}",
serde_json::to_string(arguments).unwrap()
);
assert_eq!(
argument_inputs(¶ms, Some(&wire)),
content_inputs(¶ms, arguments)
);
assert_eq!(argument_inputs(¶ms, None), Ok(Vec::new()));
assert!(argument_inputs(¶ms, Some("free text")).is_err());
// Content the record keeps sealed is handed over by the address the
// workspace keeps it under, as bare content already was.
let sealed = tilo_content::ContentStore::memory()
.sealing()
.put(b"a photograph")
.unwrap();
assert!(tilo_content::is_sealed(&sealed), "{sealed}");
let address = tilo_content::content_address(&sealed).unwrap();
let arguments = serde_json::json!({
"images": [sealed],
"cover": format!("tilo.content:{sealed}"),
});
assert_eq!(
content_inputs(¶ms, arguments.as_object().unwrap()),
Ok(vec![address.clone(), address])
);
// A path is never content.
let arguments = serde_json::json!({ "images": ["/home/someone/secret.png"] });
assert!(content_inputs(¶ms, arguments.as_object().unwrap()).is_err());
}
}