Skip to main content

day_script_protocol/
format.rs

1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! Canonical `flow:` documents. Transport, project expansion and execution stay with callers.
5
6use std::fmt;
7
8use serde::{Deserialize, Serialize};
9use serde_json::{Map, Value};
10
11use crate::Step;
12
13/// Whether the host runner continues a flow after a failed step.
14#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
15#[serde(rename_all = "snake_case")]
16pub enum FailurePolicy {
17    #[default]
18    Continue,
19    Stop,
20}
21
22/// An invalid document or step, with a one-based flow position when applicable.
23#[derive(Clone, Debug, PartialEq, Eq)]
24pub struct FormatError(String);
25
26impl fmt::Display for FormatError {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        f.write_str(&self.0)
29    }
30}
31
32impl std::error::Error for FormatError {}
33
34/// A typed operation and its non-protocol fields (platform gates, gallery metadata, etc.).
35/// Annotations survive document round trips but are not part of [`crate::Request`].
36#[derive(Clone, Debug, PartialEq)]
37pub struct ScriptStep {
38    pub step: Step,
39    pub annotations: Map<String, Value>,
40}
41
42impl ScriptStep {
43    /// Accept an on-disk single-key entry or the flattened JSON wire spelling.
44    /// Unknown parameter fields are retained as annotations for forward compatibility.
45    ///
46    /// # Errors
47    ///
48    /// Returns a [`FormatError`] when the value is not a step mapping, names an unknown operation
49    /// or a parameter of the wrong type, carries a duration that is not finite, non-negative and
50    /// representable, or has a malformed `skip_on`, `only_on` or `animation` annotation.
51    pub fn from_value(value: Value) -> Result<Self, FormatError> {
52        let mut fields = normalize(value)?;
53        let step: Step = serde_json::from_value(Value::Object(fields.clone()))
54            .map_err(|e| FormatError(e.to_string()))?;
55        // Host sleeps must be representable durations; reject them before callers can panic.
56        let duration = match &step {
57            Step::Pause { secs } => Some(*secs),
58            Step::ExpectExit { within } => *within,
59            _ => None,
60        };
61        if let Some(secs) = duration
62            && std::time::Duration::try_from_secs_f64(secs).is_err()
63        {
64            return Err(FormatError(format!(
65                "{}: duration must be finite, non-negative and representable",
66                step.op()
67            )));
68        }
69        for key in ["skip_on", "only_on"] {
70            if let Some(value) = fields.get(key)
71                && !value
72                    .as_array()
73                    .is_some_and(|a| a.iter().all(Value::is_string))
74            {
75                return Err(FormatError(format!("{key} must be a sequence of strings")));
76            }
77        }
78        if fields.get("animation").is_some_and(|v| !v.is_boolean()) {
79            return Err(FormatError("animation must be a boolean".into()));
80        }
81        for key in protocol_fields(&step).keys() {
82            fields.remove(key);
83        }
84        // This protocol field is omitted by serde when false, but is never an annotation.
85        if matches!(step, Step::NavBack { .. }) {
86            fields.remove("native");
87        }
88        Ok(Self {
89            step,
90            annotations: fields,
91        })
92    }
93
94    /// Flatten the operation and annotations for host-side processing. Protocol fields win
95    /// if a caller manually adds a conflicting annotation.
96    #[must_use]
97    pub fn to_value(&self) -> Value {
98        let mut fields = self.annotations.clone();
99        // Preserve the omission of a default `native: false`, even with conflicting metadata.
100        if matches!(self.step, Step::NavBack { .. }) {
101            fields.remove("native");
102        }
103        fields.extend(protocol_fields(&self.step));
104        Value::Object(fields)
105    }
106}
107
108impl From<Step> for ScriptStep {
109    fn from(step: Step) -> Self {
110        Self {
111            step,
112            annotations: Map::new(),
113        }
114    }
115}
116
117/// A script document, including host policy and author-supplied document metadata.
118#[derive(Clone, Debug, Default, PartialEq)]
119pub struct Script {
120    pub steps: Vec<ScriptStep>,
121    pub on_failure: FailurePolicy,
122    pub metadata: Map<String, Value>,
123}
124
125impl Script {
126    /// Parse and validate the entire flow before executing any of it. YAML comments and a
127    /// UTF-8 BOM are accepted; every flow entry must have exactly one operation key.
128    ///
129    /// # Errors
130    ///
131    /// Returns a [`FormatError`] when the text is not valid YAML, contains a non-finite number, is
132    /// not a mapping with a `flow:` sequence, has an invalid `on_failure`, contains an invalid
133    /// step, or places `expect_exit` anywhere but last.
134    pub fn from_yaml(yaml: &str) -> Result<Self, FormatError> {
135        // YAML's own Value rejects duplicate keys before conversion to a JSON map would
136        // overwrite them. Reject non-finite numbers before JSON conversion, which would
137        // silently turn them into null, including in optional durations.
138        let yaml: serde_norway::Value = serde_norway::from_str(yaml.trim_start_matches('\u{feff}'))
139            .map_err(|e| FormatError(e.to_string()))?;
140        if !finite_numbers(&yaml) {
141            return Err(FormatError("script contains a non-finite number".into()));
142        }
143        let doc = serde_json::to_value(yaml).map_err(|e| FormatError(e.to_string()))?;
144        let Value::Object(mut metadata) = doc else {
145            return Err(FormatError("script must be a mapping".into()));
146        };
147        let on_failure = match metadata.remove("on_failure") {
148            None => FailurePolicy::Continue,
149            Some(value) => serde_json::from_value(value)
150                .map_err(|_| FormatError("on_failure must be stop or continue".into()))?,
151        };
152        let Some(Value::Array(flow)) = metadata.remove("flow") else {
153            return Err(FormatError("script has no `flow:` sequence".into()));
154        };
155        let mut steps = Vec::with_capacity(flow.len());
156        for (index, entry) in flow.into_iter().enumerate() {
157            // Flattened entries are accepted by JSON driving, but a YAML flow has one
158            // operation key; allowing both would make `op: tap` an ambiguous disk entry.
159            if entry.as_object().is_none_or(|m| m.len() != 1) {
160                return Err(FormatError(format!(
161                    "flow step {}: entries must be single-key mappings",
162                    index + 1
163                )));
164            }
165            let fields = normalize_entry(entry)
166                .map_err(|e| FormatError(format!("flow step {}: {e}", index + 1)))?;
167            let step = ScriptStep::from_value(Value::Object(fields))
168                .map_err(|e| FormatError(format!("flow step {}: {e}", index + 1)))?;
169            steps.push(step);
170        }
171        if steps
172            .iter()
173            .take(steps.len().saturating_sub(1))
174            .any(|s| matches!(s.step, Step::ExpectExit { .. }))
175        {
176            return Err(FormatError("expect_exit must be the last step".into()));
177        }
178        Ok(Self {
179            steps,
180            on_failure,
181            metadata,
182        })
183    }
184
185    /// Serialize as the canonical single-key YAML form. Optional null parameters are omitted;
186    /// author metadata and annotations are retained. The default failure policy is implicit.
187    ///
188    /// # Panics
189    ///
190    /// Panics if a step does not serialize as a JSON object or the document does not serialize as
191    /// YAML, neither of which a valid [`Script`] can cause.
192    #[must_use]
193    pub fn to_yaml(&self) -> String {
194        let mut doc = self.metadata.clone();
195        doc.remove("on_failure");
196        if self.on_failure == FailurePolicy::Stop {
197            doc.insert("on_failure".into(), Value::String("stop".into()));
198        }
199        let flow = self
200            .steps
201            .iter()
202            .map(|step| {
203                let Value::Object(mut fields) = step.to_value() else {
204                    unreachable!("script step is an object")
205                };
206                fields.remove("op");
207                fields.retain(|key, value| !value.is_null() || step.annotations.contains_key(key));
208                let params = if fields.is_empty() {
209                    Value::Null
210                } else {
211                    Value::Object(fields)
212                };
213                let mut entry = Map::new();
214                entry.insert(step.step.op().into(), params);
215                Value::Object(entry)
216            })
217            .collect();
218        doc.insert("flow".into(), Value::Array(flow));
219        // The document contains only JSON scalars, sequences and string-keyed maps.
220        serde_norway::to_string(&doc).expect("JSON dayscript document serializes as YAML")
221    }
222}
223
224/// Serialize operations without host annotations, as the recorder does.
225pub fn steps_to_yaml(steps: &[Step]) -> String {
226    Script {
227        steps: steps.iter().cloned().map(ScriptStep::from).collect(),
228        ..Script::default()
229    }
230    .to_yaml()
231}
232
233/// Read operations for in-process playback. Host annotations and failure policy are validated
234/// but execution remains the caller's responsibility.
235///
236/// # Errors
237///
238/// Returns the message of the [`FormatError`] that [`Script::from_yaml`] reports.
239pub fn steps_from_yaml(yaml: &str) -> Result<Vec<Step>, String> {
240    Script::from_yaml(yaml)
241        .map(|script| script.steps.into_iter().map(|s| s.step).collect())
242        .map_err(|e| e.to_string())
243}
244
245fn protocol_fields(step: &Step) -> Map<String, Value> {
246    match serde_json::to_value(step).expect("dayscript step serializes as JSON") {
247        Value::Object(fields) => fields,
248        _ => unreachable!("internally tagged step is an object"),
249    }
250}
251
252fn finite_numbers(value: &serde_norway::Value) -> bool {
253    use serde_norway::Value as Yaml;
254    match value {
255        Yaml::Number(n) => n.is_finite(),
256        Yaml::Sequence(values) => values.iter().all(finite_numbers),
257        Yaml::Mapping(fields) => fields
258            .iter()
259            .all(|(key, value)| finite_numbers(key) && finite_numbers(value)),
260        Yaml::Tagged(value) => finite_numbers(&value.value),
261        Yaml::Null | Yaml::Bool(_) | Yaml::String(_) => true,
262    }
263}
264
265fn normalize(value: Value) -> Result<Map<String, Value>, FormatError> {
266    if let Some(fields) = value.as_object()
267        && fields.contains_key("op")
268    {
269        return Ok(fields.clone());
270    }
271    normalize_entry(value)
272}
273
274fn normalize_entry(value: Value) -> Result<Map<String, Value>, FormatError> {
275    let Value::Object(entry) = value else {
276        return Err(FormatError("step must be a mapping".into()));
277    };
278    if entry.len() != 1 {
279        return Err(FormatError("step must be a single-key mapping".into()));
280    }
281    let (op, params) = entry.into_iter().next().expect("exactly one key");
282    let mut fields = match params {
283        Value::Object(fields) => fields,
284        Value::String(s) if op == "screenshot" => Map::from_iter([("name".into(), s.into())]),
285        Value::Number(n) if op == "pause" => Map::from_iter([("secs".into(), n.into())]),
286        Value::String(s) if op == "resize" && s == "auto" => {
287            Map::from_iter([("restore".into(), true.into())])
288        }
289        Value::Null => Map::new(),
290        other => {
291            return Err(FormatError(format!(
292                "step {op}: unsupported params {other}"
293            )));
294        }
295    };
296    if fields.contains_key("op") {
297        return Err(FormatError(format!(
298            "step {op}: params cannot override `op`"
299        )));
300    }
301    fields.insert("op".into(), op.into());
302    Ok(fields)
303}