Skip to main content

tilo_actions/
offload.rs

1//! Where an admitted offloadable invocation runs.
2//!
3//! An action whose contract declares [`Offload`] is a pure transform of
4//! content: its inputs are the content its invocation names, its outputs are
5//! content, and they depend on the inputs alone. The action API admits such
6//! an invocation exactly as any other — who may invoke never changes — and
7//! then asks the device's [`ActionOffload`] whether another of the person's
8//! devices should run it. When one did, the API answers the invocation with
9//! that output ([`Offloaded::Ran`]); otherwise, for any reason at all, the
10//! app's own handler runs it here ([`Offloaded::RunHere`]), so a failed or
11//! unreachable worker only ever costs time, never a different answer.
12//!
13//! The inputs a job may read are only the content the invocation's own
14//! content parameters name ([`content_inputs`]), as the invoker's workspace
15//! reaches it; never a path, an environment or an argument vector.
16
17use std::future::Future;
18use std::pin::Pin;
19use std::time::Duration;
20
21use crate::{
22    ARGUMENTS_JSON_PREFIX, ActionAddress, ActionOutput, ActionParam, Offload, named_reference,
23    remote::InvokeRequest,
24};
25
26/// One admitted invocation of an offloadable action.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct OffloadRequest {
29    /// The workspace it was invoked in.
30    pub workspace: String,
31    pub app_id: String,
32    /// The invoked action.
33    pub address: ActionAddress,
34    /// The contract's declaration: what the work needs of a device.
35    pub offload: Offload,
36    /// Its inputs: the content hashes its arguments name, in order.
37    pub inputs: Vec<String>,
38}
39
40/// What became of an offload request.
41#[derive(Clone, Debug, PartialEq)]
42pub enum Offloaded {
43    /// Another device ran it; this is what a local run returns.
44    Ran {
45        output: ActionOutput,
46        /// The device that ran it, as the offloader names devices.
47        device: String,
48        /// Wall time from the request to the output.
49        elapsed: Duration,
50    },
51    /// Run it here, through the app's handler, and why.
52    RunHere {
53        /// Why it was not offloaded: no better-placed device, or what
54        /// failed remotely.
55        reason: String,
56    },
57}
58
59/// A boxed, sendable future, as [`ActionOffload`] answers.
60pub type OffloadFuture<'a> = Pin<Box<dyn Future<Output = Offloaded> + Send + 'a>>;
61
62/// The device's route for offloadable invocations.
63pub trait ActionOffload: Send + Sync {
64    /// Run `request` on the best-placed other device, or say why it should
65    /// run here.
66    fn offload(&self, request: OffloadRequest) -> OffloadFuture<'_>;
67
68    /// [`Self::offload`] for the invocation `request` was admitted from, as
69    /// this device's API would send it to another device: a route that runs
70    /// it elsewhere sends the invocation the person made, so the device that
71    /// runs it answers that one and a retry there is not a second run. A
72    /// route with no device to send it to keeps its own way of running it.
73    fn offload_invocation(
74        &self,
75        request: OffloadRequest,
76        invocation: InvokeRequest,
77    ) -> OffloadFuture<'_> {
78        let _ = invocation;
79        self.offload(request)
80    }
81}
82
83/// The content an invocation's `arguments` name through the content
84/// parameters among `params` ([`ActionParam::is_content`],
85/// [`ActionParam::is_content_list`]), in declaration order: a `tilo.content:`
86/// address, or the reference alone. Each is named by its address, which is
87/// what the caller's workspace keeps and hands another device, whether or not
88/// the record that names it keeps the content sealed
89/// ([`content_address`](tilo_content::content_address)).
90pub fn content_inputs(
91    params: &[ActionParam],
92    arguments: &serde_json::Map<String, serde_json::Value>,
93) -> Result<Vec<String>, String> {
94    let address = |name: &str, value: &serde_json::Value| -> Result<String, String> {
95        let text = value
96            .as_str()
97            .ok_or_else(|| format!("`{name}` is not a content address"))?;
98        named_reference(text)
99            .and_then(tilo_content::content_address)
100            .ok_or_else(|| format!("`{name}` is not a content address"))
101    };
102    let mut inputs = Vec::new();
103    for param in params {
104        let Some(value) = arguments
105            .get(param.name.as_ref())
106            .filter(|value| !value.is_null())
107        else {
108            continue;
109        };
110        if param.is_content() {
111            inputs.push(address(&param.name, value)?);
112        } else if param.is_content_list() {
113            let items = value
114                .as_array()
115                .ok_or_else(|| format!("`{}` is not a list of content", param.name))?;
116            for item in items {
117                inputs.push(address(&param.name, item)?);
118            }
119        }
120    }
121    Ok(inputs)
122}
123
124/// [`content_inputs`] of an invocation's wire `argument`: its named
125/// arguments ([`ARGUMENTS_JSON_PREFIX`]), or none.
126pub fn argument_inputs(
127    params: &[ActionParam],
128    argument: Option<&str>,
129) -> Result<Vec<String>, String> {
130    let Some(argument) = argument else {
131        return Ok(Vec::new());
132    };
133    let json = argument
134        .strip_prefix(ARGUMENTS_JSON_PREFIX)
135        .ok_or("the invocation's arguments are not named")?;
136    let arguments: serde_json::Map<String, serde_json::Value> =
137        serde_json::from_str(json).map_err(|error| format!("unreadable arguments: {error}"))?;
138    content_inputs(params, &arguments)
139}
140
141#[cfg(test)]
142mod tests {
143    use super::*;
144    use crate::ParamType;
145
146    #[test]
147    fn the_inputs_are_the_content_the_content_parameters_name_in_order() {
148        let a = "a".repeat(64);
149        let b = "b".repeat(64);
150        let params = vec![
151            ActionParam::required("images", ParamType::Array, "Images").as_content_list(),
152            ActionParam::optional("label", ParamType::Text, "A label"),
153            ActionParam::optional("cover", ParamType::Text, "Cover").as_content(),
154        ];
155        let arguments = serde_json::json!({
156            "images": [a, format!("tilo.content:{b}")],
157            "label": "not content",
158            "cover": a,
159        });
160        let arguments = arguments.as_object().unwrap();
161        assert_eq!(
162            content_inputs(&params, arguments),
163            Ok(vec![a.clone(), b, a])
164        );
165        assert!(params[0].is_content_list() && !params[0].is_content());
166        assert!(params[2].is_content() && !params[2].is_content_list());
167
168        let wire = format!(
169            "{ARGUMENTS_JSON_PREFIX}{}",
170            serde_json::to_string(arguments).unwrap()
171        );
172        assert_eq!(
173            argument_inputs(&params, Some(&wire)),
174            content_inputs(&params, arguments)
175        );
176        assert_eq!(argument_inputs(&params, None), Ok(Vec::new()));
177        assert!(argument_inputs(&params, Some("free text")).is_err());
178
179        // Content the record keeps sealed is handed over by the address the
180        // workspace keeps it under, as bare content already was.
181        let sealed = tilo_content::ContentStore::memory()
182            .sealing()
183            .put(b"a photograph")
184            .unwrap();
185        assert!(tilo_content::is_sealed(&sealed), "{sealed}");
186        let address = tilo_content::content_address(&sealed).unwrap();
187        let arguments = serde_json::json!({
188            "images": [sealed],
189            "cover": format!("tilo.content:{sealed}"),
190        });
191        assert_eq!(
192            content_inputs(&params, arguments.as_object().unwrap()),
193            Ok(vec![address.clone(), address])
194        );
195
196        // A path is never content.
197        let arguments = serde_json::json!({ "images": ["/home/someone/secret.png"] });
198        assert!(content_inputs(&params, arguments.as_object().unwrap()).is_err());
199    }
200}