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    pub fn from_value(value: Value) -> Result<Self, FormatError> {
46        let mut fields = normalize(value)?;
47        let step: Step = serde_json::from_value(Value::Object(fields.clone()))
48            .map_err(|e| FormatError(e.to_string()))?;
49        // Host sleeps must be representable durations; reject them before callers can panic.
50        let duration = match &step {
51            Step::Pause { secs } => Some(*secs),
52            Step::ExpectExit { within } => *within,
53            _ => None,
54        };
55        if let Some(secs) = duration
56            && std::time::Duration::try_from_secs_f64(secs).is_err()
57        {
58            return Err(FormatError(format!(
59                "{}: duration must be finite, non-negative and representable",
60                step.op()
61            )));
62        }
63        for key in ["skip_on", "only_on"] {
64            if let Some(value) = fields.get(key)
65                && !value
66                    .as_array()
67                    .is_some_and(|a| a.iter().all(Value::is_string))
68            {
69                return Err(FormatError(format!("{key} must be a sequence of strings")));
70            }
71        }
72        if fields.get("animation").is_some_and(|v| !v.is_boolean()) {
73            return Err(FormatError("animation must be a boolean".into()));
74        }
75        for key in protocol_fields(&step).keys() {
76            fields.remove(key);
77        }
78        // This protocol field is omitted by serde when false, but is never an annotation.
79        if matches!(step, Step::NavBack { .. }) {
80            fields.remove("native");
81        }
82        Ok(Self {
83            step,
84            annotations: fields,
85        })
86    }
87
88    /// Flatten the operation and annotations for host-side processing. Protocol fields win
89    /// if a caller manually adds a conflicting annotation.
90    pub fn to_value(&self) -> Value {
91        let mut fields = self.annotations.clone();
92        // Preserve the omission of a default `native: false`, even with conflicting metadata.
93        if matches!(self.step, Step::NavBack { .. }) {
94            fields.remove("native");
95        }
96        fields.extend(protocol_fields(&self.step));
97        Value::Object(fields)
98    }
99}
100
101impl From<Step> for ScriptStep {
102    fn from(step: Step) -> Self {
103        Self {
104            step,
105            annotations: Map::new(),
106        }
107    }
108}
109
110/// A script document, including host policy and author-supplied document metadata.
111#[derive(Clone, Debug, Default, PartialEq)]
112pub struct Script {
113    pub steps: Vec<ScriptStep>,
114    pub on_failure: FailurePolicy,
115    pub metadata: Map<String, Value>,
116}
117
118impl Script {
119    /// Parse and validate the entire flow before executing any of it. YAML comments and a
120    /// UTF-8 BOM are accepted; every flow entry must have exactly one operation key.
121    pub fn from_yaml(yaml: &str) -> Result<Self, FormatError> {
122        // YAML's own Value rejects duplicate keys before conversion to a JSON map would
123        // overwrite them. Reject non-finite numbers before JSON conversion, which would
124        // silently turn them into null, including in optional durations.
125        let yaml: serde_norway::Value = serde_norway::from_str(yaml.trim_start_matches('\u{feff}'))
126            .map_err(|e| FormatError(e.to_string()))?;
127        if !finite_numbers(&yaml) {
128            return Err(FormatError("script contains a non-finite number".into()));
129        }
130        let doc = serde_json::to_value(yaml).map_err(|e| FormatError(e.to_string()))?;
131        let Value::Object(mut metadata) = doc else {
132            return Err(FormatError("script must be a mapping".into()));
133        };
134        let on_failure = match metadata.remove("on_failure") {
135            None => FailurePolicy::Continue,
136            Some(value) => serde_json::from_value(value)
137                .map_err(|_| FormatError("on_failure must be stop or continue".into()))?,
138        };
139        let Some(Value::Array(flow)) = metadata.remove("flow") else {
140            return Err(FormatError("script has no `flow:` sequence".into()));
141        };
142        let mut steps = Vec::with_capacity(flow.len());
143        for (index, entry) in flow.into_iter().enumerate() {
144            // Flattened entries are accepted by JSON driving, but a YAML flow has one
145            // operation key; allowing both would make `op: tap` an ambiguous disk entry.
146            if !entry.as_object().is_some_and(|m| m.len() == 1) {
147                return Err(FormatError(format!(
148                    "flow step {}: entries must be single-key mappings",
149                    index + 1
150                )));
151            }
152            let fields = normalize_entry(entry)
153                .map_err(|e| FormatError(format!("flow step {}: {e}", index + 1)))?;
154            let step = ScriptStep::from_value(Value::Object(fields))
155                .map_err(|e| FormatError(format!("flow step {}: {e}", index + 1)))?;
156            steps.push(step);
157        }
158        if steps
159            .iter()
160            .take(steps.len().saturating_sub(1))
161            .any(|s| matches!(s.step, Step::ExpectExit { .. }))
162        {
163            return Err(FormatError("expect_exit must be the last step".into()));
164        }
165        Ok(Self {
166            steps,
167            on_failure,
168            metadata,
169        })
170    }
171
172    /// Serialize as the canonical single-key YAML form. Optional null parameters are omitted;
173    /// author metadata and annotations are retained. The default failure policy is implicit.
174    pub fn to_yaml(&self) -> String {
175        let mut doc = self.metadata.clone();
176        doc.remove("on_failure");
177        if self.on_failure == FailurePolicy::Stop {
178            doc.insert("on_failure".into(), Value::String("stop".into()));
179        }
180        let flow = self
181            .steps
182            .iter()
183            .map(|step| {
184                let Value::Object(mut fields) = step.to_value() else {
185                    unreachable!("script step is an object")
186                };
187                fields.remove("op");
188                fields.retain(|key, value| !value.is_null() || step.annotations.contains_key(key));
189                let params = if fields.is_empty() {
190                    Value::Null
191                } else {
192                    Value::Object(fields)
193                };
194                let mut entry = Map::new();
195                entry.insert(step.step.op().into(), params);
196                Value::Object(entry)
197            })
198            .collect();
199        doc.insert("flow".into(), Value::Array(flow));
200        // The document contains only JSON scalars, sequences and string-keyed maps.
201        serde_norway::to_string(&doc).expect("JSON dayscript document serializes as YAML")
202    }
203}
204
205/// Serialize operations without host annotations, as the recorder does.
206pub fn steps_to_yaml(steps: &[Step]) -> String {
207    Script {
208        steps: steps.iter().cloned().map(ScriptStep::from).collect(),
209        ..Script::default()
210    }
211    .to_yaml()
212}
213
214/// Read operations for in-process playback. Host annotations and failure policy are validated
215/// but execution remains the caller's responsibility.
216pub fn steps_from_yaml(yaml: &str) -> Result<Vec<Step>, String> {
217    Script::from_yaml(yaml)
218        .map(|script| script.steps.into_iter().map(|s| s.step).collect())
219        .map_err(|e| e.to_string())
220}
221
222fn protocol_fields(step: &Step) -> Map<String, Value> {
223    match serde_json::to_value(step).expect("dayscript step serializes as JSON") {
224        Value::Object(fields) => fields,
225        _ => unreachable!("internally tagged step is an object"),
226    }
227}
228
229fn finite_numbers(value: &serde_norway::Value) -> bool {
230    use serde_norway::Value as Yaml;
231    match value {
232        Yaml::Number(n) => n.is_finite(),
233        Yaml::Sequence(values) => values.iter().all(finite_numbers),
234        Yaml::Mapping(fields) => fields
235            .iter()
236            .all(|(key, value)| finite_numbers(key) && finite_numbers(value)),
237        Yaml::Tagged(value) => finite_numbers(&value.value),
238        Yaml::Null | Yaml::Bool(_) | Yaml::String(_) => true,
239    }
240}
241
242fn normalize(value: Value) -> Result<Map<String, Value>, FormatError> {
243    if let Some(fields) = value.as_object()
244        && fields.contains_key("op")
245    {
246        return Ok(fields.clone());
247    }
248    normalize_entry(value)
249}
250
251fn normalize_entry(value: Value) -> Result<Map<String, Value>, FormatError> {
252    let Value::Object(entry) = value else {
253        return Err(FormatError("step must be a mapping".into()));
254    };
255    if entry.len() != 1 {
256        return Err(FormatError("step must be a single-key mapping".into()));
257    }
258    let (op, params) = entry.into_iter().next().expect("exactly one key");
259    let mut fields = match params {
260        Value::Object(fields) => fields,
261        Value::String(s) if op == "screenshot" => Map::from_iter([("name".into(), s.into())]),
262        Value::Number(n) if op == "pause" => Map::from_iter([("secs".into(), n.into())]),
263        Value::String(s) if op == "resize" && s == "auto" => {
264            Map::from_iter([("restore".into(), true.into())])
265        }
266        Value::Null => Map::new(),
267        other => {
268            return Err(FormatError(format!(
269                "step {op}: unsupported params {other}"
270            )));
271        }
272    };
273    if fields.contains_key("op") {
274        return Err(FormatError(format!(
275            "step {op}: params cannot override `op`"
276        )));
277    }
278    fields.insert("op".into(), op.into());
279    Ok(fields)
280}