Skip to main content

graphrt_code/
lib.rs

1//! # graphrt-code
2//!
3//! The `code` node: runs user-supplied code over workflow variables.
4//!
5//! - **JavaScript** runs in an embedded QuickJS engine (feature `js`, on by
6//!   default). The engine has no file system, network, timers or module
7//!   loader; memory, stack and execution time are capped.
8//! - **Other languages** (e.g. `python3`) run in a host-provided
9//!   [`RemoteSandbox`] service. The optional `remote` feature provides
10//!   `HttpSandbox`, a client for an HTTP sandbox service. The optional `python`
11//!   feature provides `SubprocessPython`, which runs a local `python3` with
12//!   resource limits — **not a security sandbox**, for trusted code only.
13//!
14//! User code defines `main(args)`, which receives an object with the configured
15//! input variables and returns an object (or a promise of one):
16//!
17//! ```js
18//! function main({ a, b }) {
19//!   return { sum: a + b };
20//! }
21//! ```
22//!
23//! Inputs are passed with secrets **revealed**: code nodes frequently need API
24//! keys from `env.*`. Treat the sandbox as a trusted sink and do not echo
25//! secrets into outputs.
26
27use std::fmt;
28use std::sync::Arc;
29
30use futures::future::BoxFuture;
31use indexmap::IndexMap;
32use serde::Deserialize;
33
34use graphrt_core::dsl::NodeDoc;
35use graphrt_core::node::{ConfigError, Node, NodeContext, NodeError, NodeOutput, NodeResult, Registry, parse_config};
36use graphrt_core::{Selector, Value, ValueType};
37
38#[cfg(feature = "js")]
39mod js;
40#[cfg(feature = "python")]
41mod python;
42#[cfg(feature = "remote")]
43mod remote;
44
45#[cfg(feature = "python")]
46pub use python::SubprocessPython;
47#[cfg(feature = "remote")]
48pub use remote::HttpSandbox;
49
50/// Node kind handled by this crate.
51pub const KIND: &str = "code";
52
53/// Resource limits for one code execution.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
55#[serde(default)]
56pub struct CodeLimits {
57    /// Wall-clock execution budget in milliseconds.
58    pub time_ms: u64,
59    /// Heap limit in bytes.
60    pub memory_bytes: usize,
61    /// Native stack limit in bytes.
62    pub stack_bytes: usize,
63    /// Maximum size of the JSON-encoded result.
64    pub max_output_bytes: usize,
65    /// Maximum nesting depth of the result.
66    pub max_depth: usize,
67}
68
69impl CodeLimits {
70    /// Field-wise minimum of `self` and `max`: workflow-provided limits may only lower
71    /// the operator's limits, never raise them.
72    pub fn clamp_to(self, max: &CodeLimits) -> CodeLimits {
73        CodeLimits {
74            time_ms: self.time_ms.min(max.time_ms),
75            memory_bytes: self.memory_bytes.min(max.memory_bytes),
76            stack_bytes: self.stack_bytes.min(max.stack_bytes),
77            max_output_bytes: self.max_output_bytes.min(max.max_output_bytes),
78            max_depth: self.max_depth.min(max.max_depth),
79        }
80    }
81}
82
83impl Default for CodeLimits {
84    fn default() -> Self {
85        Self {
86            time_ms: 10_000,
87            memory_bytes: 64 * 1024 * 1024,
88            stack_bytes: 1024 * 1024,
89            max_output_bytes: 4 * 1024 * 1024,
90            max_depth: 32,
91        }
92    }
93}
94
95/// A sandbox that executes code out of process (for languages without an embedded engine).
96///
97/// Register it as `Arc<dyn RemoteSandbox>` in [`graphrt_core::Services`].
98pub trait RemoteSandbox: Send + Sync + fmt::Debug {
99    /// Execute `code` in `language` with `inputs` (a JSON object). Must return the JSON
100    /// object produced by the code's `main` function.
101    fn execute<'a>(
102        &'a self,
103        language: &'a str,
104        code: &'a str,
105        inputs: serde_json::Value,
106        limits: CodeLimits,
107    ) -> BoxFuture<'a, Result<serde_json::Value, NodeError>>;
108
109    /// Like [`RemoteSandbox::execute`], also returning diagnostics (captured output,
110    /// limits that could not be applied). The default reports none.
111    fn execute_detailed<'a>(
112        &'a self,
113        language: &'a str,
114        code: &'a str,
115        inputs: serde_json::Value,
116        limits: CodeLimits,
117    ) -> BoxFuture<'a, Result<SandboxRun, NodeError>> {
118        Box::pin(async move {
119            let result = self.execute(language, code, inputs, limits).await?;
120            Ok(SandboxRun { result, stdout: None, notes: Vec::new() })
121        })
122    }
123}
124
125/// Result of [`RemoteSandbox::execute_detailed`].
126#[derive(Clone, Debug, Default, PartialEq)]
127pub struct SandboxRun {
128    /// The object returned by `main`.
129    pub result: serde_json::Value,
130    /// What the code printed (capped), if captured.
131    pub stdout: Option<String>,
132    /// Operator-facing notes, e.g. resource limits the platform could not apply.
133    pub notes: Vec<String>,
134}
135
136/// Where code runs.
137#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum SandboxChoice {
140    /// Embedded engine when available for the language, otherwise the remote sandbox.
141    #[default]
142    Auto,
143    /// Always use the registered [`RemoteSandbox`].
144    Remote,
145}
146
147#[derive(Clone, Debug, Deserialize)]
148struct InputVar {
149    variable: String,
150    value_selector: Selector,
151}
152
153#[derive(Clone, Debug, Deserialize)]
154struct OutputDecl {
155    #[serde(rename = "type")]
156    ty: ValueType,
157}
158
159#[derive(Clone, Debug, Deserialize)]
160struct CodeConfig {
161    #[serde(default = "default_language")]
162    code_language: String,
163    code: String,
164    #[serde(default)]
165    variables: Vec<InputVar>,
166    #[serde(default)]
167    outputs: IndexMap<String, OutputDecl>,
168    #[serde(default)]
169    limits: Option<CodeLimits>,
170    #[serde(default)]
171    sandbox: SandboxChoice,
172}
173
174fn default_language() -> String {
175    "javascript".to_owned()
176}
177
178/// Normalized language name.
179fn normalize_language(lang: &str) -> String {
180    match lang.trim().to_ascii_lowercase().as_str() {
181        "js" | "javascript" | "nodejs" | "node" => "javascript".to_owned(),
182        "py" | "python" | "python3" => "python3".to_owned(),
183        other => other.to_owned(),
184    }
185}
186
187/// The `code` node.
188#[derive(Debug)]
189pub struct CodeNode {
190    language: String,
191    code: Arc<str>,
192    variables: Vec<InputVar>,
193    outputs: IndexMap<String, OutputDecl>,
194    limits: Option<CodeLimits>,
195    sandbox: SandboxChoice,
196}
197
198impl CodeNode {
199    /// Build from a node document.
200    pub fn from_doc(doc: &NodeDoc) -> Result<Self, ConfigError> {
201        let cfg: CodeConfig = parse_config(doc)?;
202        if cfg.code.trim().is_empty() {
203            return Err(ConfigError::new(doc, "`code` must not be empty"));
204        }
205        let language = normalize_language(&cfg.code_language);
206        if language == "jinja2" {
207            return Err(ConfigError::new(doc, "jinja2 is not a code language; use a template-transform node"));
208        }
209        Ok(Self {
210            language,
211            code: Arc::from(cfg.code),
212            variables: cfg.variables,
213            outputs: cfg.outputs,
214            limits: cfg.limits,
215            sandbox: cfg.sandbox,
216        })
217    }
218
219    /// Effective limits: the host's [`CodeLimits`] service (or the defaults) is the
220    /// ceiling; limits in the node config can only lower it. The time limit is further
221    /// capped by the attempt deadline so a node timeout also interrupts the interpreter
222    /// (which blocks synchronously).
223    fn effective_limits(&self, ctx: &NodeContext) -> CodeLimits {
224        let host = ctx.service::<CodeLimits>().copied().unwrap_or_default();
225        let mut limits = match self.limits {
226            Some(requested) => requested.clamp_to(&host),
227            None => host,
228        };
229        if let Some(remaining) = ctx.remaining() {
230            let remaining_ms = u64::try_from(remaining.as_millis()).unwrap_or(u64::MAX).max(1);
231            limits.time_ms = limits.time_ms.min(remaining_ms);
232        }
233        limits
234    }
235
236    /// Build the `main(args)` object. Selectors that do not resolve are passed as
237    /// `null` and returned in the second element (reported as `missing_inputs` metadata).
238    fn build_inputs(&self, ctx: &NodeContext) -> (serde_json::Value, Vec<String>) {
239        let mut args = serde_json::Map::new();
240        let mut missing = Vec::new();
241        for var in &self.variables {
242            let value = match ctx.get(&var.value_selector) {
243                Some(v) => v,
244                None => {
245                    missing.push(var.value_selector.to_string());
246                    Value::Null
247                }
248            };
249            args.insert(var.variable.clone(), value.to_json_exposed());
250        }
251        (serde_json::Value::Object(args), missing)
252    }
253
254    async fn execute(&self, ctx: &NodeContext, inputs: serde_json::Value) -> Result<SandboxRun, NodeError> {
255        let limits = self.effective_limits(ctx);
256        let use_remote = self.sandbox == SandboxChoice::Remote || !embedded_supports(&self.language);
257        if use_remote {
258            let sandbox = ctx.service::<Arc<dyn RemoteSandbox>>().ok_or_else(|| {
259                NodeError::fatal(
260                    "missing_service",
261                    format!(
262                        "{} code requires a remote sandbox; register an `Arc<dyn RemoteSandbox>` service",
263                        self.language
264                    ),
265                )
266            })?;
267            return sandbox.execute_detailed(&self.language, &self.code, inputs, limits).await;
268        }
269        let result = run_embedded(self.code.clone(), inputs, limits).await?;
270        Ok(SandboxRun { result, stdout: None, notes: Vec::new() })
271    }
272
273    fn convert_outputs(&self, result: serde_json::Value, limits: &CodeLimits) -> Result<NodeOutput, NodeError> {
274        let serde_json::Value::Object(map) = result else {
275            return Err(NodeError::fatal("invalid_output", "main() must return an object"));
276        };
277        let depth = json_depth(&serde_json::Value::Object(map.clone()));
278        if depth > limits.max_depth {
279            return Err(NodeError::fatal(
280                "invalid_output",
281                format!("result nesting depth {depth} exceeds the limit of {}", limits.max_depth),
282            ));
283        }
284        let mut output = NodeOutput::new();
285        if self.outputs.is_empty() {
286            for (key, value) in map {
287                output.outputs.insert(key, Value::from_json(value));
288            }
289            return Ok(output);
290        }
291        for (name, decl) in &self.outputs {
292            let raw = map
293                .get(name)
294                .cloned()
295                .ok_or_else(|| NodeError::fatal("invalid_output", format!("missing output `{name}`")))?;
296            let value = decl
297                .ty
298                .coerce(Value::from_json(raw))
299                .map_err(|e| NodeError::fatal("invalid_output", format!("output `{name}`: {e}")))?;
300            output.outputs.insert(name.clone(), value);
301        }
302        let ignored: Vec<&String> = map.keys().filter(|k| !self.outputs.contains_key(*k)).collect();
303        if !ignored.is_empty() {
304            let names = ignored.iter().map(|k| Value::from(k.as_str()));
305            output.metadata.insert("ignored_outputs".to_owned(), Value::array(names));
306        }
307        Ok(output)
308    }
309}
310
311impl Node for CodeNode {
312    fn run(&self, ctx: NodeContext) -> BoxFuture<'_, NodeResult> {
313        Box::pin(async move {
314            let limits = self.effective_limits(&ctx);
315            let (inputs, missing) = self.build_inputs(&ctx);
316            let run = self.execute(&ctx, inputs).await?;
317            let mut output = self.convert_outputs(run.result, &limits)?;
318            if let Some(stdout) = run.stdout.filter(|s| !s.is_empty()) {
319                output = output.meta("stdout", stdout);
320            }
321            if !run.notes.is_empty() {
322                output = output.meta("sandbox_notes", Value::array(run.notes.into_iter().map(Value::from)));
323            }
324            if !missing.is_empty() {
325                output = output.meta("missing_inputs", Value::array(missing.into_iter().map(Value::from)));
326            }
327            Ok(output.meta("language", self.language.as_str()).into())
328        })
329    }
330
331    fn inputs(&self) -> Vec<Selector> {
332        self.variables.iter().map(|v| v.value_selector.clone()).collect()
333    }
334}
335
336fn embedded_supports(language: &str) -> bool {
337    cfg!(feature = "js") && language == "javascript"
338}
339
340#[cfg(feature = "js")]
341async fn run_embedded(
342    code: Arc<str>,
343    inputs: serde_json::Value,
344    limits: CodeLimits,
345) -> Result<serde_json::Value, NodeError> {
346    let input_text = serde_json::to_string(&inputs)
347        .map_err(|e| NodeError::fatal("invalid_input", format!("cannot encode inputs: {e}")))?;
348    let job = move || js::run(&code, &input_text, &limits);
349
350    // QuickJS is synchronous. Inside a tokio runtime, run it on the blocking pool so the
351    // executor thread stays free; elsewhere run inline (bounded by the time limit).
352    #[cfg(feature = "tokio")]
353    {
354        if let Ok(handle) = tokio::runtime::Handle::try_current() {
355            return handle
356                .spawn_blocking(job)
357                .await
358                .map_err(|e| NodeError::new("sandbox", format!("code execution task failed: {e}")))?;
359        }
360    }
361    job()
362}
363
364#[cfg(not(feature = "js"))]
365async fn run_embedded(
366    _code: Arc<str>,
367    _inputs: serde_json::Value,
368    _limits: CodeLimits,
369) -> Result<serde_json::Value, NodeError> {
370    Err(NodeError::fatal("unsupported", "embedded JavaScript is disabled (feature `js`)"))
371}
372
373fn json_depth(value: &serde_json::Value) -> usize {
374    match value {
375        serde_json::Value::Array(items) => 1 + items.iter().map(json_depth).max().unwrap_or(0),
376        serde_json::Value::Object(map) => 1 + map.values().map(json_depth).max().unwrap_or(0),
377        _ => 0,
378    }
379}
380
381/// Register the `code` node kind.
382pub fn register(registry: &mut Registry) {
383    registry.register_described(descriptor(), |doc| Ok(Arc::new(CodeNode::from_doc(doc)?) as Arc<dyn Node>));
384}
385
386/// Catalog descriptor of the `code` node.
387pub fn descriptor() -> graphrt_core::catalog::NodeDescriptor {
388    use graphrt_core::catalog::schema::{nested, object, value_type, variable_bindings};
389    use graphrt_core::catalog::{NodeCategory, NodeDescriptor};
390    use serde_json::json;
391
392    let limit = |what: &str| json!({ "type": "integer", "minimum": 0, "description": what });
393    NodeDescriptor::new(KIND, "Code", NodeCategory::Integration)
394        .describe(
395            "Runs `main(args)` over bound variables. JavaScript runs in an embedded QuickJS engine with \
396             no I/O and memory/time limits; other languages (python3) need a sandbox service. Declared \
397             outputs are type-checked; without declarations every returned key becomes an output.",
398        )
399        .icon("code")
400        .source("graphrt-code")
401        .schema(object(
402            json!({
403                "code_language": {
404                    "type": "string",
405                    "enum": ["javascript", "js", "nodejs", "node", "python3", "python", "py"],
406                    "default": "javascript"
407                },
408                "code": { "type": "string", "minLength": 1 },
409                "variables": variable_bindings(),
410                "outputs": { "type": "object", "additionalProperties": nested(json!({ "type": value_type() }), &["type"]) },
411                "limits": nested(json!({
412                    "time_ms": limit("Wall-clock budget (ms)"),
413                    "memory_bytes": limit("Heap limit"),
414                    "stack_bytes": limit("Stack limit"),
415                    "max_output_bytes": limit("Result size limit"),
416                    "max_depth": limit("Result nesting limit")
417                }), &[]),
418                "sandbox": { "type": "string", "enum": ["auto", "remote"], "default": "auto" }
419            }),
420            &["code"],
421        ))
422        .dynamic_outputs()
423}
424
425#[cfg(test)]
426mod tests {
427    use super::*;
428    use graphrt_core::node::NodeOutcome;
429    use graphrt_core::{Services, VariablePool};
430
431    fn node(config: serde_json::Value) -> Result<CodeNode, ConfigError> {
432        CodeNode::from_doc(&NodeDoc::new("c", KIND, config))
433    }
434
435    fn pool() -> VariablePool {
436        let mut p = VariablePool::new();
437        p.insert("start", "a", Value::Int(2));
438        p.insert("start", "b", Value::Int(3));
439        p.insert("start", "list", Value::from_json(serde_json::json!([1, 2, 3])));
440        p.insert("env", "KEY", Value::Secret(Arc::from("sk-live")));
441        p
442    }
443
444    async fn run(config: serde_json::Value) -> Result<NodeOutput, NodeError> {
445        let n = node(config).map_err(|e| NodeError::fatal("config", e.to_string()))?;
446        match n.run(NodeContext::for_test("c", pool())).await? {
447            NodeOutcome::Completed(o) => Ok(o),
448            NodeOutcome::Paused(_) => Err(NodeError::fatal("test", "unexpected pause")),
449        }
450    }
451
452    fn vars() -> serde_json::Value {
453        serde_json::json!([
454            {"variable": "a", "value_selector": ["start", "a"]},
455            {"variable": "b", "value_selector": ["start", "b"]},
456            {"variable": "list", "value_selector": ["start", "list"]},
457            {"variable": "key", "value_selector": ["env", "KEY"]},
458        ])
459    }
460
461    #[tokio::test]
462    async fn arithmetic() {
463        let out = run(serde_json::json!({
464            "code": "function main({a, b}) { return { sum: a + b, ratio: b / a }; }",
465            "variables": vars(),
466            "outputs": {"sum": {"type": "number"}, "ratio": {"type": "float"}},
467        }))
468        .await
469        .unwrap();
470        assert_eq!(out.outputs.get("sum"), Some(&Value::Int(5)));
471        assert_eq!(out.outputs.get("ratio"), Some(&Value::Float(1.5)));
472    }
473
474    #[tokio::test]
475    async fn object_and_array_returns_untyped() {
476        let out = run(serde_json::json!({
477            "code": "function main(args) { return { doubled: args.list.map(x => x * 2), obj: { k: 'v' } }; }",
478            "variables": vars(),
479        }))
480        .await
481        .unwrap();
482        assert_eq!(out.outputs.get("doubled"), Some(&Value::from_json(serde_json::json!([2, 4, 6]))));
483        assert_eq!(out.outputs.get("obj"), Some(&Value::from_json(serde_json::json!({"k": "v"}))));
484    }
485
486    #[tokio::test]
487    async fn async_main_is_supported() {
488        let out = run(serde_json::json!({
489            "code": "async function main({a}) { const v = await Promise.resolve(a * 10); return { v }; }",
490            "variables": vars(),
491        }))
492        .await
493        .unwrap();
494        assert_eq!(out.outputs.get("v"), Some(&Value::Int(20)));
495    }
496
497    #[tokio::test]
498    async fn secrets_are_available_to_code() {
499        let out = run(serde_json::json!({
500            "code": "function main({key}) { return { len: key.length }; }",
501            "variables": vars(),
502        }))
503        .await
504        .unwrap();
505        assert_eq!(out.outputs.get("len"), Some(&Value::Int(7)));
506    }
507
508    #[tokio::test]
509    async fn type_validation_failure() {
510        let err = run(serde_json::json!({
511            "code": "function main() { return { n: 'not a number' }; }",
512            "outputs": {"n": {"type": "number"}},
513        }))
514        .await
515        .unwrap_err();
516        assert_eq!(err.kind, "invalid_output");
517        assert!(!err.retryable);
518    }
519
520    #[tokio::test]
521    async fn missing_declared_output() {
522        let err = run(serde_json::json!({
523            "code": "function main() { return { other: 1 }; }",
524            "outputs": {"n": {"type": "number"}},
525        }))
526        .await
527        .unwrap_err();
528        assert!(err.message.contains("missing output `n`"), "{err}");
529    }
530
531    #[tokio::test]
532    async fn non_object_result() {
533        let err = run(serde_json::json!({ "code": "function main() { return 42; }" })).await.unwrap_err();
534        assert!(err.message.contains("must return an object"), "{err}");
535    }
536
537    #[tokio::test]
538    async fn thrown_error_message_is_reported() {
539        let err =
540            run(serde_json::json!({ "code": "function main() { throw new Error('boom here'); }" })).await.unwrap_err();
541        assert_eq!(err.kind, "code_error");
542        assert!(err.message.contains("boom here"), "{err}");
543    }
544
545    #[tokio::test]
546    async fn syntax_error_is_reported() {
547        let err = run(serde_json::json!({ "code": "function main( { return {}; }" })).await.unwrap_err();
548        assert_eq!(err.kind, "code_error");
549    }
550
551    #[tokio::test]
552    async fn missing_main() {
553        let err = run(serde_json::json!({ "code": "function notMain() { return {}; }" })).await.unwrap_err();
554        assert!(err.message.contains("main"), "{err}");
555    }
556
557    #[tokio::test]
558    async fn infinite_loop_is_interrupted() {
559        let started = std::time::Instant::now();
560        let err = run(serde_json::json!({
561            "code": "function main() { while (true) {} }",
562            "limits": {"time_ms": 200},
563        }))
564        .await
565        .unwrap_err();
566        assert_eq!(err.kind, "timeout");
567        assert!(started.elapsed() < std::time::Duration::from_secs(5));
568    }
569
570    #[tokio::test]
571    async fn attempt_deadline_caps_the_time_limit() {
572        // The configured limit is generous, but the engine-provided deadline is not.
573        let n = node(serde_json::json!({"code": "function main() { while (true) {} }", "limits": {"time_ms": 60000}}))
574            .unwrap();
575        let ctx = NodeContext::for_test("c", pool());
576        let deadline = ctx.clock.now_ms() + 200;
577        let started = std::time::Instant::now();
578        let err = n.run(ctx.with_deadline(Some(deadline))).await.unwrap_err();
579        assert_eq!(err.kind, "timeout");
580        assert!(started.elapsed() < std::time::Duration::from_secs(5), "{:?}", started.elapsed());
581    }
582
583    #[tokio::test]
584    async fn top_level_infinite_loop_is_interrupted() {
585        let err = run(serde_json::json!({
586            "code": "while (true) {} function main() { return {}; }",
587            "limits": {"time_ms": 200},
588        }))
589        .await
590        .unwrap_err();
591        assert_eq!(err.kind, "timeout");
592    }
593
594    #[tokio::test]
595    async fn memory_bomb_is_limited() {
596        let err = run(serde_json::json!({
597            "code": "function main() { const a = []; while (true) { a.push('x'.repeat(1 << 20)); } }",
598            "limits": {"memory_bytes": 16777216, "time_ms": 5000},
599        }))
600        .await
601        .unwrap_err();
602        assert!(err.kind == "out_of_memory" || err.kind == "code_error", "{err}");
603        assert!(!err.retryable);
604    }
605
606    #[tokio::test]
607    async fn timeouts_are_not_retryable() {
608        let err = run(serde_json::json!({
609            "code": "function main() { while (true) {} }",
610            "limits": {"time_ms": 100},
611        }))
612        .await
613        .unwrap_err();
614        assert_eq!(err.kind, "timeout");
615        assert!(!err.retryable);
616    }
617
618    #[tokio::test]
619    async fn config_limits_cannot_exceed_host_limits() {
620        let n = node(serde_json::json!({
621            "code": "function main() { while (true) {} }",
622            "limits": {"time_ms": 3_600_000u64, "memory_bytes": 1_000_000_000_000u64},
623        }))
624        .unwrap();
625        let host = CodeLimits { time_ms: 150, ..CodeLimits::default() };
626        let services = Arc::new(Services::new().with(host));
627        let ctx = NodeContext::for_test("c", pool()).with_services(services.clone());
628        assert_eq!(n.effective_limits(&ctx).time_ms, 150);
629        assert_eq!(n.effective_limits(&ctx).memory_bytes, CodeLimits::default().memory_bytes);
630        let started = std::time::Instant::now();
631        let err = n.run(ctx).await.unwrap_err();
632        assert_eq!(err.kind, "timeout");
633        assert!(started.elapsed() < std::time::Duration::from_secs(5));
634
635        // Without a host service, the defaults are the ceiling.
636        let ctx = NodeContext::for_test("c", pool());
637        assert_eq!(n.effective_limits(&ctx).time_ms, CodeLimits::default().time_ms);
638    }
639
640    #[tokio::test]
641    async fn non_finite_numbers_are_rejected() {
642        let err = run(serde_json::json!({ "code": "function main() { return { x: 1 / 0 }; }" })).await.unwrap_err();
643        assert_eq!(err.kind, "code_error");
644        assert!(err.message.contains("non-finite"), "{err}");
645    }
646
647    #[tokio::test]
648    async fn user_errors_mentioning_memory_are_code_errors() {
649        let err =
650            run(serde_json::json!({ "code": "function main() { throw new Error('out of memory reading file'); }" }))
651                .await
652                .unwrap_err();
653        assert_eq!(err.kind, "code_error", "{err}");
654    }
655
656    #[tokio::test]
657    async fn thrown_non_error_values_are_described() {
658        let err = run(serde_json::json!({ "code": "function main() { throw 42; }" })).await.unwrap_err();
659        assert_eq!(err.kind, "code_error");
660        assert!(err.message.contains("42"), "{err}");
661    }
662
663    #[tokio::test]
664    async fn missing_inputs_are_reported() {
665        let out = run(serde_json::json!({
666            "code": "function main({ x }) { return { isNull: x === null }; }",
667            "variables": [{"variable": "x", "value_selector": ["start", "nope"]}],
668        }))
669        .await
670        .unwrap();
671        assert_eq!(out.outputs.get("isNull"), Some(&Value::Bool(true)));
672        assert_eq!(out.metadata.get("missing_inputs"), Some(&Value::array([Value::from("start.nope")])));
673    }
674
675    #[tokio::test]
676    async fn output_size_is_limited() {
677        let err = run(serde_json::json!({
678            "code": "function main() { return { s: 'x'.repeat(100000) }; }",
679            "limits": {"max_output_bytes": 1000},
680        }))
681        .await
682        .unwrap_err();
683        assert_eq!(err.kind, "invalid_output");
684    }
685
686    #[tokio::test]
687    async fn no_host_capabilities() {
688        let out = run(serde_json::json!({
689            "code": "function main() { return { t: typeof setTimeout, f: typeof fetch, r: typeof require, s: typeof std, o: typeof os }; }",
690        }))
691        .await
692        .unwrap();
693        for key in ["t", "f", "r", "s", "o"] {
694            assert_eq!(out.outputs.get(key), Some(&Value::from("undefined")), "{key}");
695        }
696    }
697
698    #[test]
699    fn runs_without_tokio_runtime_context() {
700        let n = node(serde_json::json!({ "code": "function main() { return { ok: true }; }" })).unwrap();
701        let out = futures::executor::block_on(n.run(NodeContext::for_test("c", pool()))).unwrap();
702        assert!(matches!(out, NodeOutcome::Completed(o) if o.outputs.get("ok") == Some(&Value::Bool(true))));
703    }
704
705    #[tokio::test]
706    async fn python_without_remote_sandbox() {
707        let err = run(serde_json::json!({
708            "code_language": "python3",
709            "code": "def main():\n    return {}",
710        }))
711        .await
712        .unwrap_err();
713        assert_eq!(err.kind, "missing_service");
714        assert!(err.message.contains("remote sandbox"));
715    }
716
717    #[derive(Debug)]
718    struct EchoSandbox;
719
720    impl RemoteSandbox for EchoSandbox {
721        fn execute<'a>(
722            &'a self,
723            language: &'a str,
724            _code: &'a str,
725            inputs: serde_json::Value,
726            _limits: CodeLimits,
727        ) -> BoxFuture<'a, Result<serde_json::Value, NodeError>> {
728            Box::pin(async move { Ok(serde_json::json!({ "language": language, "inputs": inputs })) })
729        }
730    }
731
732    #[tokio::test]
733    async fn python_with_remote_sandbox() {
734        let n = node(serde_json::json!({
735            "code_language": "python3",
736            "code": "def main(a):\n    return {}",
737            "variables": [{"variable": "a", "value_selector": ["start", "a"]}],
738        }))
739        .unwrap();
740        let services = Services::new().with::<Arc<dyn RemoteSandbox>>(Arc::new(EchoSandbox));
741        let ctx = NodeContext::for_test("c", pool()).with_services(Arc::new(services));
742        let out = n.run(ctx).await.unwrap();
743        let NodeOutcome::Completed(out) = out else { panic!("paused") };
744        assert_eq!(out.outputs.get("language"), Some(&Value::from("python3")));
745        assert_eq!(out.outputs.get("inputs"), Some(&Value::from_json(serde_json::json!({"a": 2}))));
746    }
747
748    #[test]
749    fn config_validation() {
750        assert!(node(serde_json::json!({ "code": "  " })).is_err());
751        assert!(node(serde_json::json!({ "code_language": "jinja2", "code": "x" })).is_err());
752        assert!(node(serde_json::json!({ "code_language": "js", "code": "x" })).is_ok());
753    }
754
755    #[test]
756    fn registers_kind() {
757        let mut r = Registry::new();
758        register(&mut r);
759        assert!(r.contains(KIND));
760    }
761}