Skip to main content

greentic_runner_host/runner/
media_node.rs

1//! Flow-execution media node (LOCKED ENCODING v1: `component == "media.create"`).
2//!
3//! A plain flow can create a file (`txt`, `md`, `csv`, `pdf`) and store it
4//! through the same artifact `put` port an extension's `host.artifact.put`
5//! uses, so the file reaches the user as the same `artifact://` id a worker's
6//! file does.
7//!
8//! ```text
9//! nodes:
10//!   make_pdf:
11//!     media.create:
12//!       format: pdf              # txt | md | csv | pdf (required)
13//!       name: "Claim Summary"    # file stem, sanitised by the renderer
14//!       text: "{{vars.summary}}" # txt / md / pdf; blank is an error value
15//!       rows: [[...], ...]       # csv only: array of arrays
16//!       output: file             # optional state key
17//!     routing: end
18//! ```
19//!
20//! The result is the C5 value (`docs/media-contract-v1.md`):
21//! `{ok:true, artifact:{id,mime_type,name}, artifacts:[..], warnings:[..]}` or
22//! `{ok:false, error:{code,message}}`. A failure is a VALUE; the engine marks
23//! the node failed only when it has an `on_error` edge (see
24//! `engine::media_node_output`). Without an `output:` key the result IS the
25//! node output, which is what greentic-start's outbound collector reads (a
26//! top-level `artifact`).
27//!
28//! Rendering is ported from `component-media-ext`, see [`super::media_render`].
29
30use std::sync::Arc;
31
32use greentic_ext_runtime::host_ports::{
33    ArtifactPort, ArtifactPortError, ArtifactPutRequest, HostCallContext,
34};
35use serde_json::Value;
36
37use super::media_render::{
38    Artifact, Failure, MAX_ARTIFACT_BYTES, codes, failure, parse_create_document, render, success,
39};
40
41/// Extension id reported to the port (host log only).
42const SOURCE_ID: &str = "greentic.media";
43
44/// Map a port refusal onto a C5 failure. The port's `Unavailable` text is a
45/// fixed, credential-free reason; a door status is recognised in it.
46fn put_failure(error: &ArtifactPortError) -> Failure {
47    match error {
48        ArtifactPortError::Unsupported => Failure::new(
49            codes::ARTIFACT_UNAVAILABLE,
50            "this runtime has no artifact storage",
51        ),
52        ArtifactPortError::InvalidMediaType => Failure::new(
53            codes::ARTIFACT_REJECTED,
54            "artifact storage refused the file type",
55        ),
56        ArtifactPortError::QuotaExceeded => Failure::new(
57            codes::ARTIFACT_REJECTED,
58            "artifact storage refused the file: the storage quota is exhausted",
59        ),
60        ArtifactPortError::Unavailable(reason) => match door_status(reason) {
61            Some(401 | 403) => Failure::new(
62                codes::UNAUTHORIZED,
63                "artifact storage did not accept this worker's credential",
64            ),
65            Some(413) => Failure::new(
66                codes::TOO_LARGE,
67                "artifact storage refused the file as too large",
68            ),
69            Some(_) => Failure::new(
70                codes::ARTIFACT_REJECTED,
71                "artifact storage refused the file",
72            ),
73            None => Failure::new(
74                codes::ARTIFACT_UNAVAILABLE,
75                "artifact storage is unavailable",
76            ),
77        },
78        _ => Failure::new(
79            codes::ARTIFACT_UNAVAILABLE,
80            "artifact storage is unavailable",
81        ),
82    }
83}
84
85/// The status in the port's `door answered <n>` reason, if that is what it is.
86fn door_status(reason: &str) -> Option<u16> {
87    reason.strip_prefix("door answered ")?.trim().parse().ok()
88}
89
90/// Create the file described by the rendered node `payload` and store it for
91/// `tenant`. Always returns a C5 value; never panics.
92pub async fn create(payload: &Value, tenant: &str, port: Option<&Arc<dyn ArtifactPort>>) -> Value {
93    let request = match parse_create_document(payload) {
94        Ok(request) => request,
95        Err(f) => return failure(&f),
96    };
97    let rendered = match render(&request) {
98        Ok(rendered) => rendered,
99        Err(f) => return failure(&f),
100    };
101    if rendered.bytes.len() > MAX_ARTIFACT_BYTES {
102        return failure(&Failure::new(
103            codes::TOO_LARGE,
104            "the document is larger than the 10 MB limit",
105        ));
106    }
107    let Some(port) = port else {
108        return failure(&Failure::new(
109            codes::ARTIFACT_UNAVAILABLE,
110            "this runtime has no artifact storage",
111        ));
112    };
113    let name = format!("{}.{}", request.stem, rendered.ext);
114    let put = ArtifactPutRequest {
115        bytes: rendered.bytes,
116        mime_type: rendered.mime.to_string(),
117        name: name.clone(),
118    };
119    let ctx = HostCallContext {
120        tenant: Some(tenant.to_string()).filter(|t| !t.trim().is_empty()),
121        user_email: None,
122    };
123    let port = Arc::clone(port);
124    // `ArtifactPort::put` is synchronous and blocks on the door; run it on the
125    // blocking pool so it never parks an async worker.
126    let stored = tokio::task::spawn_blocking(move || port.put(SOURCE_ID, &ctx, put)).await;
127    match stored {
128        Ok(Ok(id)) => success(
129            &[Artifact {
130                id,
131                mime_type: rendered.mime.to_string(),
132                name,
133            }],
134            &rendered.warnings,
135        ),
136        Ok(Err(error)) => {
137            tracing::warn!(code = "media_create_put_failed", %error, "media.create put failed");
138            failure(&put_failure(&error))
139        }
140        Err(_) => failure(&Failure::new(
141            codes::ARTIFACT_UNAVAILABLE,
142            "artifact storage is unavailable",
143        )),
144    }
145}
146
147/// Reserved key of a turn's final reply payload that lists the files the
148/// RUNNER created for the end user during that turn (`media.create`), as
149/// `[{id, mime_type, name}]`.
150///
151/// This is a runner-to-host contract: greentic-start delivers every listed
152/// file whose id this deployment's artifact port stored, in addition to a
153/// top-level `artifact`. Only [`attach_created`] writes it, and it removes any
154/// copy a flow's own data put there, so a node (or an HTTP echo) cannot
155/// forge the list. A failure result never lists a file.
156pub const CREATED_ARTIFACTS_KEY: &str = "created_artifacts";
157
158/// More files than this in one turn are not tracked (the host delivers at
159/// most 5 per reply anyway).
160pub const MAX_CREATED_PER_TURN: usize = 20;
161
162/// The files a successful `media.create` result created; empty for a failure.
163pub fn created_files(result: &Value) -> Vec<Value> {
164    if is_failure(result) || result.get("ok").and_then(Value::as_bool) != Some(true) {
165        return Vec::new();
166    }
167    let listed = result
168        .get("artifacts")
169        .and_then(Value::as_array)
170        .filter(|items| !items.is_empty())
171        .cloned()
172        .or_else(|| result.get("artifact").map(|one| vec![one.clone()]))
173        .unwrap_or_default();
174    listed
175        .into_iter()
176        .filter(|file| file.get("id").and_then(Value::as_str).is_some())
177        .collect()
178}
179
180fn strip_reserved(value: &mut Value) {
181    if let Value::Object(map) = value {
182        map.remove(CREATED_ARTIFACTS_KEY);
183    }
184}
185
186/// Fold the turn's created files into its final reply `reply`.
187///
188/// Always removes a pre-existing [`CREATED_ARTIFACTS_KEY`] first (a flow must
189/// not be able to name files). With files: an object gets the key; an array
190/// (several emitted payloads) gets it on its LAST element, so the link goes
191/// with the final reply; a plain string becomes `{text, key}`; `null` becomes
192/// `{key}` (a file-only turn).
193pub fn attach_created(mut reply: Value, created: Vec<Value>) -> Value {
194    match &mut reply {
195        Value::Array(items) => items.iter_mut().for_each(strip_reserved),
196        other => strip_reserved(other),
197    }
198    if created.is_empty() {
199        return reply;
200    }
201    let list = Value::Array(created);
202    let key = CREATED_ARTIFACTS_KEY.to_string();
203    match reply {
204        Value::Object(mut map) => {
205            map.insert(key, list);
206            Value::Object(map)
207        }
208        Value::Null => serde_json::json!({ key: list }),
209        Value::String(text) => serde_json::json!({ "text": text, key: list }),
210        Value::Array(mut items) => {
211            match items.last_mut() {
212                Some(Value::Object(map)) => {
213                    map.insert(key, list);
214                }
215                Some(Value::String(text)) => {
216                    let text = std::mem::take(text);
217                    if let Some(last) = items.last_mut() {
218                        *last = serde_json::json!({ "text": text, key: list });
219                    }
220                }
221                _ => items.push(serde_json::json!({ key: list })),
222            }
223            Value::Array(items)
224        }
225        other => Value::Array(vec![other, serde_json::json!({ key: list })]),
226    }
227}
228
229/// Whether a node result is a C5 failure value.
230pub fn is_failure(result: &Value) -> bool {
231    result.get("ok").and_then(Value::as_bool) == Some(false)
232}
233
234/// The failure's `error.message`, for the node's `errors[0]`.
235pub fn failure_message(result: &Value) -> String {
236    result
237        .pointer("/error/message")
238        .and_then(Value::as_str)
239        .unwrap_or("media.create failed")
240        .to_string()
241}
242
243/// The failure's `error.code`.
244pub fn failure_code(result: &Value) -> String {
245    result
246        .pointer("/error/code")
247        .and_then(Value::as_str)
248        .unwrap_or("media_create_failed")
249        .to_string()
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255    use serde_json::json;
256    use std::sync::Mutex;
257
258    type Seen = (String, String, usize, Option<String>);
259
260    #[derive(Default)]
261    struct Stub {
262        seen: Mutex<Vec<Seen>>,
263        answer: Mutex<Option<ArtifactPortError>>,
264    }
265
266    impl ArtifactPort for Stub {
267        fn put(
268            &self,
269            _extension_id: &str,
270            ctx: &HostCallContext,
271            request: ArtifactPutRequest,
272        ) -> Result<String, ArtifactPortError> {
273            if let Ok(mut seen) = self.seen.lock() {
274                seen.push((
275                    request.name.clone(),
276                    request.mime_type.clone(),
277                    request.bytes.len(),
278                    ctx.tenant.clone(),
279                ));
280            }
281            match self.answer.lock().ok().and_then(|mut a| a.take()) {
282                Some(error) => Err(error),
283                None => Ok(format!("artifact://{}", "a".repeat(64))),
284            }
285        }
286    }
287
288    fn port(stub: &Arc<Stub>) -> Arc<dyn ArtifactPort> {
289        Arc::clone(stub) as Arc<dyn ArtifactPort>
290    }
291
292    #[tokio::test]
293    async fn each_format_is_stored_with_its_mime_and_name() {
294        let cases = [
295            (
296                json!({"format":"txt","name":"n","text":"hi"}),
297                "n.txt",
298                "text/plain",
299            ),
300            (
301                json!({"format":"md","name":"n","text":"# hi"}),
302                "n.md",
303                "text/markdown",
304            ),
305            (
306                json!({"format":"csv","name":"n","rows":[["a","b"]]}),
307                "n.csv",
308                "text/csv",
309            ),
310            (
311                json!({"format":"pdf","name":"n","text":"hi"}),
312                "n.pdf",
313                "application/pdf",
314            ),
315        ];
316        for (payload, name, mime) in cases {
317            let stub = Arc::new(Stub::default());
318            let value = create(&payload, "acme", Some(&port(&stub))).await;
319            assert_eq!(value["ok"], true, "{value}");
320            assert_eq!(value["artifact"]["name"], name);
321            assert_eq!(value["artifact"]["mime_type"], mime);
322            assert_eq!(value["artifacts"].as_array().map(Vec::len), Some(1));
323            let seen = stub.seen.lock().map(|s| s.clone()).unwrap_or_default();
324            assert_eq!(seen[0].3.as_deref(), Some("acme"));
325        }
326    }
327
328    #[tokio::test]
329    async fn bad_input_never_reaches_the_port() {
330        let stub = Arc::new(Stub::default());
331        let blank = create(
332            &json!({"format":"pdf","text":"  "}),
333            "acme",
334            Some(&port(&stub)),
335        )
336        .await;
337        assert_eq!(blank["error"]["code"], "invalid_input");
338        let fmt = create(
339            &json!({"format":"docx","text":"x"}),
340            "acme",
341            Some(&port(&stub)),
342        )
343        .await;
344        assert_eq!(fmt["error"]["code"], "unsupported_format");
345        assert!(stub.seen.lock().map(|s| s.is_empty()).unwrap_or(false));
346    }
347
348    #[tokio::test]
349    async fn no_port_is_an_unavailable_value() {
350        let value = create(&json!({"format":"txt","text":"x"}), "acme", None).await;
351        assert_eq!(value["ok"], false);
352        assert_eq!(value["error"]["code"], "artifact_unavailable");
353    }
354
355    #[tokio::test]
356    async fn port_refusals_map_onto_codes() {
357        let cases = [
358            (ArtifactPortError::Unsupported, "artifact_unavailable"),
359            (ArtifactPortError::InvalidMediaType, "artifact_rejected"),
360            (ArtifactPortError::QuotaExceeded, "artifact_rejected"),
361            (
362                ArtifactPortError::Unavailable("door answered 401".into()),
363                "unauthorized",
364            ),
365            (
366                ArtifactPortError::Unavailable("door answered 403".into()),
367                "unauthorized",
368            ),
369            (
370                ArtifactPortError::Unavailable("door answered 413".into()),
371                "too_large",
372            ),
373            (
374                ArtifactPortError::Unavailable("door answered 500".into()),
375                "artifact_rejected",
376            ),
377            (
378                ArtifactPortError::Unavailable("artifact door unreachable".into()),
379                "artifact_unavailable",
380            ),
381        ];
382        for (error, code) in cases {
383            let stub = Arc::new(Stub::default());
384            if let Ok(mut answer) = stub.answer.lock() {
385                *answer = Some(error);
386            }
387            let value = create(
388                &json!({"format":"txt","text":"x"}),
389                "acme",
390                Some(&port(&stub)),
391            )
392            .await;
393            assert_eq!(value["error"]["code"], code, "{value}");
394        }
395    }
396
397    #[tokio::test]
398    async fn a_pdf_with_unencodable_text_warns() {
399        let stub = Arc::new(Stub::default());
400        let value = create(
401            &json!({"format":"pdf","text":"日本"}),
402            "acme",
403            Some(&port(&stub)),
404        )
405        .await;
406        assert_eq!(value["warnings"][0]["code"], "characters_replaced");
407    }
408}
409
410#[cfg(test)]
411mod created_tests {
412    use super::*;
413    use serde_json::json;
414
415    fn file(n: u8) -> Value {
416        json!({"id": format!("artifact://{}", n.to_string().repeat(64)), "name": "n.txt"})
417    }
418
419    #[test]
420    fn only_a_success_lists_files() {
421        let ok = success(
422            &[Artifact {
423                id: "artifact://x".into(),
424                mime_type: "text/plain".into(),
425                name: "n.txt".into(),
426            }],
427            &[],
428        );
429        assert_eq!(created_files(&ok).len(), 1);
430        let bad = failure(&Failure::new(codes::INVALID_INPUT, "no"));
431        assert!(created_files(&bad).is_empty());
432        assert!(created_files(&json!({"artifact": {"id": "a"}})).is_empty());
433    }
434
435    #[test]
436    fn an_object_reply_gets_the_key_and_a_forged_one_is_replaced() {
437        let reply = json!({"text": "hi", "created_artifacts": [{"id": "forged"}]});
438        let out = attach_created(reply, vec![file(1)]);
439        assert_eq!(out["created_artifacts"], json!([file(1)]));
440        let none = attach_created(json!({"created_artifacts": [1]}), vec![]);
441        assert!(none.get("created_artifacts").is_none());
442    }
443
444    #[test]
445    fn shapes_other_than_an_object_are_wrapped_or_extended() {
446        let s = attach_created(json!("hello"), vec![file(1)]);
447        assert_eq!(s["text"], "hello");
448        let n = attach_created(Value::Null, vec![file(1)]);
449        assert_eq!(n["created_artifacts"][0], file(1));
450        let a = attach_created(json!([{"text": "a"}, "b"]), vec![file(1)]);
451        assert!(a[0].get("created_artifacts").is_none());
452        assert_eq!(a[1]["text"], "b");
453        assert_eq!(a[1]["created_artifacts"][0], file(1));
454        let e = attach_created(json!([]), vec![file(1)]);
455        assert_eq!(e[0]["created_artifacts"][0], file(1));
456        let unchanged = attach_created(json!("x"), vec![]);
457        assert_eq!(unchanged, json!("x"));
458    }
459}