Skip to main content

greentic_runner_host/runner/media_render/
mod.rs

1//! Pure rendering for the `media.create` flow node: `txt`, `md`, `csv` and
2//! `pdf` documents.
3//!
4//! Ported from `component-media-ext` (`document.rs`, `pdf.rs`, `input.rs`,
5//! `names.rs`, `limits.rs`, `output.rs`) so a plain flow can create a file
6//! without the `greentic.media` extension installed. Behaviour and limits are
7//! kept identical on purpose; the duplication is recorded debt (design
8//! `2026-10-13-media-create-flow-node-design.md`, decision 2).
9//!
10//! Nothing here touches the host: parsing, rendering and the C5 result values
11//! (`docs/media-contract-v1.md`) are all pure.
12
13mod document;
14mod names;
15mod output;
16mod pdf;
17
18pub use document::{Rendered, render};
19pub use names::sanitize_stem;
20pub use output::{Artifact, Failure, codes, failure, success};
21
22use serde::Deserialize;
23use serde_json::Value;
24
25/// Largest artifact stored (matches the platform limit).
26pub const MAX_ARTIFACT_BYTES: usize = 10 * 1024 * 1024;
27/// Largest `text`, in Unicode scalar values.
28pub const MAX_DOC_CHARS: usize = 2_000_000;
29/// Largest PDF rendered. Checked while wrapping, before the pages are built.
30pub const MAX_PDF_PAGES: usize = 2000;
31
32/// Document formats the node can create.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum Format {
35    Txt,
36    Md,
37    Csv,
38    Pdf,
39}
40
41/// A validated `media.create` request.
42#[derive(Debug, Clone, PartialEq)]
43pub struct DocRequest {
44    pub format: Format,
45    pub stem: String,
46    pub text: String,
47    pub rows: Vec<Vec<Value>>,
48    pub escape_formulas: bool,
49}
50
51#[derive(Deserialize, Default)]
52#[serde(default)]
53struct RawDoc {
54    format: String,
55    name: Option<String>,
56    text: Option<String>,
57    rows: Option<Vec<Vec<Value>>>,
58    escape_formulas: Option<bool>,
59}
60
61/// Parse and validate the rendered node payload. `Err` is an `invalid_input`
62/// (or `unsupported_format`) message.
63pub fn parse_create_document(args: &Value) -> Result<DocRequest, Failure> {
64    let raw: RawDoc = serde_json::from_value(args.clone())
65        .map_err(|e| Failure::new(codes::INVALID_INPUT, format!("invalid arguments: {e}")))?;
66    let format = match raw.format.trim().to_ascii_lowercase().as_str() {
67        "txt" => Format::Txt,
68        "md" => Format::Md,
69        "csv" => Format::Csv,
70        "pdf" => Format::Pdf,
71        other => {
72            return Err(Failure::new(
73                codes::UNSUPPORTED_FORMAT,
74                format!("`format` must be one of txt, md, csv, pdf (got `{other}`)"),
75            ));
76        }
77    };
78    let invalid = |m: String| Failure::new(codes::INVALID_INPUT, m);
79    let stem = sanitize_stem(raw.name.as_deref(), "document");
80    let escape_formulas = raw.escape_formulas.unwrap_or(true);
81    if format == Format::Csv {
82        let rows = raw.rows.unwrap_or_default();
83        if rows.is_empty() {
84            return Err(invalid(
85                "`rows` is required for csv and must not be empty".into(),
86            ));
87        }
88        for (r, row) in rows.iter().enumerate() {
89            for (c, cell) in row.iter().enumerate() {
90                if matches!(cell, Value::Array(_) | Value::Object(_)) {
91                    return Err(invalid(format!(
92                        "cell [{r}][{c}] must be a string, number, boolean or null"
93                    )));
94                }
95            }
96        }
97        return Ok(DocRequest {
98            format,
99            stem,
100            text: String::new(),
101            rows,
102            escape_formulas,
103        });
104    }
105    let text = raw.text.unwrap_or_default();
106    if text.trim().is_empty() {
107        return Err(invalid("`text` is required and must not be blank".into()));
108    }
109    if text.chars().count() > MAX_DOC_CHARS {
110        return Err(invalid(format!(
111            "`text` is longer than {MAX_DOC_CHARS} characters"
112        )));
113    }
114    Ok(DocRequest {
115        format,
116        stem,
117        text,
118        rows: Vec::new(),
119        escape_formulas,
120    })
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use serde_json::json;
127
128    #[test]
129    fn text_formats_need_text() {
130        for f in ["txt", "md", "pdf", "PDF"] {
131            assert!(parse_create_document(&json!({"format": f, "text": "hello"})).is_ok());
132            let err = parse_create_document(&json!({"format": f, "text": "  "})).unwrap_err();
133            assert_eq!(err.code, "invalid_input");
134        }
135    }
136
137    #[test]
138    fn csv_needs_scalar_rows() {
139        let ok = parse_create_document(&json!({"format":"csv","rows":[["a","b"],[1,true]]}));
140        assert_eq!(ok.unwrap().rows.len(), 2);
141        assert!(parse_create_document(&json!({"format":"csv","rows":[]})).is_err());
142        assert!(parse_create_document(&json!({"format":"csv"})).is_err());
143        let nested = parse_create_document(&json!({"format":"csv","rows":[["a",{"x":1}]]}));
144        assert!(nested.unwrap_err().message.contains("[0][1]"));
145    }
146
147    #[test]
148    fn unknown_format_is_unsupported_and_names_are_sanitised() {
149        let err = parse_create_document(&json!({"format":"docx","text":"x"})).unwrap_err();
150        assert_eq!(err.code, "unsupported_format");
151        let d = parse_create_document(&json!({"format":"txt","text":"x","name":"../a b"}));
152        assert_eq!(d.unwrap().stem, "a-b");
153        let d = parse_create_document(&json!({"format":"txt","text":"x"}));
154        assert_eq!(d.unwrap().stem, "document");
155    }
156
157    #[test]
158    fn text_over_the_limit_is_rejected() {
159        let big = "a".repeat(MAX_DOC_CHARS + 1);
160        assert!(parse_create_document(&json!({"format":"txt","text":big})).is_err());
161        let fits = "a".repeat(MAX_DOC_CHARS);
162        assert!(parse_create_document(&json!({"format":"txt","text":fits})).is_ok());
163    }
164}