acts-package-javascript 0.26.0

acts package that runs JavaScript code with an embedded QuickJS runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use crate::{CodePackage, env::Environment};
use acts::{Engine, Principal, Variant, Vars, Workflow};
use serde_json::json;
use serial_test::serial;

// ---- QuickJS environment ----

#[test]
fn js_env_eval_object() {
    let env = Environment::new();
    let result = env
        .eval::<serde_json::Value>(r#"({ "a": 1, "b": "abc" })"#)
        .unwrap();
    assert_eq!(result, json!({ "a": 1, "b": "abc" }));
}

#[test]
fn js_env_eval_array() {
    let env = Environment::new();
    let result = env.eval::<Vec<String>>(r#"["u1", "u2"]"#).unwrap();
    assert_eq!(result, ["u1", "u2"]);
}

#[test]
fn js_env_eval_arithmetic() {
    let env = Environment::new();
    assert_eq!(env.eval::<i64>(r#"2 + 3 * 4"#).unwrap(), 14);
}

#[test]
fn js_env_array_ops() {
    let env = Environment::new();
    assert_eq!(
        env.eval::<Vec<String>>(r#"["a"].union(["b"])"#).unwrap(),
        ["a", "b"]
    );
    assert_eq!(
        env.eval::<Vec<String>>(r#"["a", "b"].intersection(["b", "c"])"#)
            .unwrap(),
        ["b"]
    );
    assert_eq!(
        env.eval::<Vec<String>>(r#"["a", "b"].difference(["b"])"#)
            .unwrap(),
        ["a"]
    );
}

#[test]
fn js_env_throw_is_error() {
    let env = Environment::new();
    for expr in [r#"throw new Error("boom")"#, "throw 42", r#"throw "boom""#] {
        let result = env.eval::<serde_json::Value>(expr);
        assert!(result.is_err(), "{expr} must fail the expression");
    }
}

/// A modules lock another thread panicked under is reported, not unwrapped:
/// the environment stays a library, not a place a panic escapes from.
#[test]
fn js_env_reports_a_poisoned_modules_lock() {
    let env = Environment::new();
    let modules = env.modules.clone();
    let handle = std::thread::spawn(move || {
        let _guard = modules.write().unwrap();
        panic!("poison the modules lock");
    });
    assert!(handle.join().is_err(), "the helper thread panics");

    let err = env.eval::<serde_json::Value>("1").unwrap_err();
    assert!(err.to_string().contains("poisoned"), "{err}");
}

// ---- code package ----

async fn run_code(workflow: &Workflow) -> Vars {
    let engine = Engine::builder()
        .add_package::<CodePackage>()
        .start()
        .await
        .unwrap();

    let sig = engine.signal(Vars::new());
    let done = sig.clone();
    engine.channel().on_complete(move |e| {
        let done = done.clone();
        async move {
            done.update(|d| *d = e.outputs.clone());
            done.close();
        }
    });

    let executor = engine.executor(&Principal::unrestricted());
    executor.model().deploy(workflow, None).await.unwrap();
    executor
        .proc()
        .start(&workflow.id, Vars::new())
        .await
        .unwrap();

    sig.recv().await
}

#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn pack_code_outputs() {
    let workflow = Workflow::new().with_id("code_outputs").with_step(|step| {
        step.with_id("step1")
            .with_expose(Variant::create("my_output", json!(null)))
            .with_uses_code("acts.app.javascript", r#"return { "my_output": "abc" };"#)
    });

    let outputs = run_code(&workflow).await;
    assert_eq!(outputs.get::<String>("my_output").unwrap(), "abc");
}

#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn pack_code_computes_and_returns() {
    let workflow = Workflow::new().with_id("code_compute").with_step(|step| {
        step.with_id("step1").with_uses_code(
            "acts.app.javascript",
            r#"return { sum: 2 + 3, msg: "hi".toUpperCase() };"#,
        )
    });

    let outputs = run_code(&workflow).await;
    assert_eq!(outputs.get::<i32>("sum").unwrap(), 5);
    assert_eq!(outputs.get::<String>("msg").unwrap(), "HI");
}

/// Task data reaches the JavaScript through `${{ }}` expressions, which the
/// engine evaluates before the script runs.
#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn pack_code_reads_injected_value() {
    let workflow = Workflow::new()
        .with_id("w1")
        .with_var("value", 21)
        .with_step(|step| {
            step.with_id("step1").with_uses_code(
                "acts.app.javascript",
                r#"return { doubled: ${{ value }} * 2 };"#,
            )
        });

    let outputs = run_code(&workflow).await;
    assert_eq!(outputs.get::<i32>("doubled").unwrap(), 42);
}

// ---- the JSON <-> JS value boundary ----

use crate::value::ActJsValue;
use acts::ActPackage;
use rquickjs::{FromJs, IntoJs};

fn roundtrip(value: serde_json::Value) -> serde_json::Value {
    let runtime = rquickjs::Runtime::new().unwrap();
    let ctx = rquickjs::Context::full(&runtime).unwrap();
    ctx.with(|ctx| {
        let js = ActJsValue::new(value).into_js(&ctx).unwrap();
        serde_json::Value::from(ActJsValue::from_js(&ctx, js).unwrap())
    })
}

#[test]
fn js_value_roundtrips_every_json_kind() {
    for value in [
        json!(null),
        json!(true),
        json!(false),
        json!(0),
        json!(-3),
        json!(3.5),
        json!("abc"),
        json!([1, "a", null, [true]]),
        json!({ "a": { "b": [false, 1.5] } }),
        json!(i64::MAX),
        json!(i64::MIN),
        json!(u64::MAX),
        json!(1.0e300),
    ] {
        assert_eq!(roundtrip(value.clone()), value, "{value}");
    }
}

#[test]
fn js_value_accessors_and_conversions() {
    let value = ActJsValue::new(json!({ "a": 1 }));
    assert_eq!(value.inner(), &json!({ "a": 1 }));
    assert_eq!(value.to::<serde_json::Value>().unwrap(), json!({ "a": 1 }));
    assert!(value.to::<Vec<String>>().is_err());

    let from_vars: ActJsValue = Vars::from(json!({ "x": 2 })).into();
    assert_eq!(serde_json::Value::from(from_vars), json!({ "x": 2 }));

    let from_string: ActJsValue = String::from("hi").into();
    assert_eq!(serde_json::Value::from(from_string), json!("hi"));
}

// ---- the environment's error and conversion edges ----

#[test]
fn js_env_console_logs_without_failing() {
    let env = Environment::new();
    let result = env
        .eval::<serde_json::Value>(
            r#"console.log("a", 1, { b: 2 }); console.info("i"); console.warn("w"); console.error("e"); 7"#,
        )
        .unwrap();
    assert_eq!(result, json!(7));
}

#[test]
fn js_env_reads_undefined_as_null() {
    let env = Environment::new();
    assert_eq!(
        env.eval::<serde_json::Value>("undefined").unwrap(),
        json!(null)
    );
    assert_eq!(
        env.eval::<serde_json::Value>("const a = 1;").unwrap(),
        json!(null)
    );
}

/// Values JSON cannot carry are refused instead of being coerced.
#[test]
fn js_env_refuses_unrepresentable_values() {
    let env = Environment::new();
    for expr in [
        "NaN",
        "Infinity",
        "(() => 1)",
        "Symbol('x')",
        "Promise.resolve(1)",
    ] {
        assert!(
            env.eval::<serde_json::Value>(expr).is_err(),
            "{expr} must not convert"
        );
    }
}

#[test]
fn js_env_converts_bigints_or_refuses_overflow() {
    let env = Environment::new();
    assert_eq!(
        env.eval::<serde_json::Value>("9007199254740993n").unwrap(),
        json!(9_007_199_254_740_993_i64)
    );
    assert_eq!(
        env.eval::<serde_json::Value>("18446744073709551615n")
            .unwrap(),
        json!(u64::MAX)
    );
    assert_eq!(
        env.eval::<serde_json::Value>("-9223372036854775808n")
            .unwrap(),
        json!(i64::MIN)
    );
    for expr in ["2n ** 100n", "-(2n ** 100n)"] {
        assert!(
            env.eval::<serde_json::Value>(expr).is_err(),
            "{expr} is outside the i64/u64 range"
        );
    }
}

#[test]
fn js_env_reads_a_proxy_through_its_traps() {
    let env = Environment::new();
    let result = env
        .eval::<serde_json::Value>(r#"new Proxy({ a: 1 }, {})"#)
        .unwrap();
    assert_eq!(result, json!({ "a": 1 }));
}

#[test]
fn js_env_reports_a_deserialization_mismatch() {
    let env = Environment::new();
    let err = env.eval::<Vec<String>>(r#"({ a: 1 })"#).unwrap_err();
    assert!(err.to_string().contains("invalid type"), "{err}");
}

// ---- the code package's own edges ----

#[test]
fn code_definition_is_a_string_parameter() {
    let meta = CodePackage::definition();
    assert_eq!(meta.id, "acts.app.javascript");
    assert_eq!(meta.schema["type"], "string");
    CodePackage::new(&acts::Config::default()).expect("no configuration is required");
}

async fn run_code_error(workflow: &Workflow) -> Vars {
    let engine = Engine::builder()
        .add_package::<CodePackage>()
        .start()
        .await
        .unwrap();

    let sig = engine.signal(Vars::new());
    let failed = sig.clone();
    engine.channel().on_error(move |e| {
        let failed = failed.clone();
        async move {
            failed.update(|d| *d = e.outputs.clone());
            failed.close();
        }
    });

    let executor = engine.executor(&Principal::unrestricted());
    executor.model().deploy(workflow, None).await.unwrap();
    executor
        .proc()
        .start(&workflow.id, Vars::new())
        .await
        .unwrap();

    sig.recv().await
}

#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn pack_code_non_object_result_has_no_outputs() {
    let workflow = Workflow::new().with_id("code_scalar").with_step(|step| {
        step.with_id("step1")
            .with_uses_code("acts.app.javascript", "return 42;")
    });
    let outputs = run_code(&workflow).await;
    assert!(outputs.get::<i32>("x").is_none(), "{outputs}");
}

#[serial]
#[tokio::test(flavor = "multi_thread")]
async fn pack_code_refuses_a_non_string_parameter() {
    let workflow = Workflow::from_yml(
        r#"
name: js bad params
id: code_bad_params
ver: "0.1.0"
steps:
  - id: step1
    uses: acts.app.javascript
    params: 42
"#,
    )
    .unwrap();

    let outputs = run_code_error(&workflow).await;
    assert!(
        outputs.to_string().contains("requires a string parameter")
            || outputs.to_string().contains("validation error"),
        "{outputs}"
    );
}

#[test]
fn js_env_integral_floats_within_the_safe_range_are_json_integers() {
    let env = Environment::new();
    assert_eq!(
        env.eval::<serde_json::Value>("3e10").unwrap(),
        json!(30_000_000_000_i64)
    );
}

#[test]
fn js_value_sends_wide_integers_as_doubles_while_they_are_exact() {
    assert_eq!(
        roundtrip(json!(3_000_000_000_i64)),
        json!(3_000_000_000_i64)
    );
}

/// A proxy whose `get` trap throws is read like an object: the failing
/// property is simply not part of the value.
#[test]
fn js_env_reads_a_proxy_whose_get_trap_throws() {
    let env = Environment::new();
    let result = env
        .eval::<serde_json::Value>(r#"new Proxy({ a: 1 }, { get() { throw new Error("no") } })"#)
        .unwrap();
    assert_eq!(result, json!({}));
}

/// A caught exception is a JS value of its own: converting it re-throws it
/// instead of turning it into JSON.
#[test]
fn js_value_rethrows_a_caught_exception() {
    let runtime = rquickjs::Runtime::new().unwrap();
    let ctx = rquickjs::Context::full(&runtime).unwrap();
    ctx.with(|ctx| {
        let _ = ctx.eval::<rquickjs::Value, _>(r#"throw new Error("boom")"#);
        let caught = ctx.catch();
        assert!(
            ActJsValue::from_js(&ctx, caught).is_err(),
            "an exception has no JSON representation"
        );
    });
}

#[test]
fn environment_has_a_debug_representation_and_a_default() {
    let env = Environment::default();
    assert!(format!("{env:?}").contains("Environment"));
}

#[test]
fn js_env_stops_a_script_that_outlives_the_timeout() {
    let env = Environment::new();
    let start = std::time::Instant::now();
    let err = env
        .eval::<serde_json::Value>("while (true) {}")
        .unwrap_err();
    assert!(err.to_string().contains("timeout"), "{err}");
    assert!(
        start.elapsed() < std::time::Duration::from_secs(30),
        "the interrupt handler must end the loop"
    );
}