camel-language-js 0.20.0

JavaScript language plugin for camel-language
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Expression, MutatingExpression, and Predicate implementations for JS.

use std::{sync::Arc, time::Duration};

use async_trait::async_trait;
use camel_language_api::{Body, Exchange, Value};
use camel_language_api::{Expression, LanguageError, MutatingExpression, Predicate};

use crate::{
    engine::{JsEngine, JsEvalResult, JsExchange},
    error::JsLanguageError,
};

/// Convert a [`JsLanguageError`] into a [`LanguageError`].
fn js_err_to_lang_err(source: &str, e: JsLanguageError) -> LanguageError {
    match e {
        JsLanguageError::Parse { message } => LanguageError::ParseError {
            expr: source.to_string(),
            reason: message,
        },
        other => LanguageError::eval_error(source, other),
    }
}

/// Validate `script` and convert any error to a `LanguageError::ParseError`.
pub(crate) fn validate_to_parse_error(
    engine: &Arc<dyn JsEngine>,
    script: &str,
) -> Result<(), LanguageError> {
    engine
        .validate(script)
        .map_err(|e| LanguageError::ParseError {
            expr: script.to_string(),
            reason: e.to_string(),
        })
}

/// Build a [`JsExchange`] snapshot from an [`Exchange`] reference.
fn snapshot_exchange(exchange: &Exchange) -> Result<JsExchange, LanguageError> {
    let body = match &exchange.input.body {
        Body::Json(v) => v.clone(),
        Body::Text(s) | Body::Xml(s) => Value::String(s.clone()),
        Body::Empty | Body::Bytes(_) => Value::Null,
        Body::Stream(_) => {
            return Err(LanguageError::EvalError(
                "Body::Stream cannot be used in JS — add 'stream_cache' or 'convert_body_to' before this step".to_string(),
            ));
        }
    };

    Ok(JsExchange::from_headers_body_properties(
        exchange.input.headers.clone(),
        body,
        exchange.properties.clone(),
    ))
}

/// Apply [`JsEvalResult`] mutations back onto a mutable [`Exchange`].
fn apply_result_to_exchange(result: &JsEvalResult, exchange: &mut Exchange) {
    exchange.input.headers = result.headers.clone();
    exchange.properties = result.properties.clone();

    let original_was_representable = matches!(
        &exchange.input.body,
        Body::Json(_) | Body::Text(_) | Body::Xml(_)
    );
    if result.body != Value::Null || original_was_representable {
        exchange.input.body = value_to_body(&result.body);
    }
}

/// Convert a `Value` to a `Body`.
fn value_to_body(v: &Value) -> Body {
    match v {
        Value::String(s) => Body::from(s.as_str()),
        other => Body::from(other.clone()),
    }
}

/// A non-mutating JS expression.
///
/// Evaluates the script and returns its result. No mutations are applied to the exchange.
pub struct JsExpression {
    script: String,
    engine: Arc<dyn JsEngine>,
    execution_timeout_ms: u64,
}

impl JsExpression {
    pub fn new(script: String, engine: Arc<dyn JsEngine>, execution_timeout_ms: u64) -> Self {
        Self {
            script,
            engine,
            execution_timeout_ms,
        }
    }
}

#[async_trait]
impl Expression for JsExpression {
    async fn evaluate(&self, exchange: &Exchange) -> Result<Value, LanguageError> {
        let js_exchange = snapshot_exchange(exchange)?;
        let result = eval_async(
            Arc::clone(&self.engine),
            self.script.clone(),
            js_exchange,
            self.execution_timeout_ms,
        )
        .await
        .map_err(|e| js_err_to_lang_err(&self.script, e))?;
        Ok(result.return_value)
    }
}

/// A mutating JS expression.
///
/// Evaluates the script and propagates any mutations to `headers`, `properties`,
/// and `body` back to the exchange. On failure, changes are rolled back atomically.
pub struct JsMutatingExpression {
    script: String,
    engine: Arc<dyn JsEngine>,
    execution_timeout_ms: u64,
}

impl JsMutatingExpression {
    pub fn new(script: String, engine: Arc<dyn JsEngine>, execution_timeout_ms: u64) -> Self {
        Self {
            script,
            engine,
            execution_timeout_ms,
        }
    }
}

#[async_trait]
impl MutatingExpression for JsMutatingExpression {
    async fn evaluate(&self, exchange: &mut Exchange) -> Result<Value, LanguageError> {
        let js_exchange = snapshot_exchange(exchange)?;
        let original_headers = exchange.input.headers.clone();
        let original_properties = exchange.properties.clone();
        let original_body = exchange.input.body.clone();

        match eval_async(
            Arc::clone(&self.engine),
            self.script.clone(),
            js_exchange,
            self.execution_timeout_ms,
        )
        .await
        {
            Ok(result) => {
                apply_result_to_exchange(&result, exchange);
                Ok(result.return_value)
            }
            Err(e) => {
                exchange.input.headers = original_headers;
                exchange.properties = original_properties;
                exchange.input.body = original_body;
                Err(js_err_to_lang_err(&self.script, e))
            }
        }
    }
}

/// A JS predicate.
///
/// Evaluates the script and interprets the return value as a boolean.
pub struct JsPredicate {
    script: String,
    engine: Arc<dyn JsEngine>,
    execution_timeout_ms: u64,
}

impl JsPredicate {
    pub fn new(script: String, engine: Arc<dyn JsEngine>, execution_timeout_ms: u64) -> Self {
        Self {
            script,
            engine,
            execution_timeout_ms,
        }
    }
}

#[async_trait]
impl Predicate for JsPredicate {
    async fn matches(&self, exchange: &Exchange) -> Result<bool, LanguageError> {
        let js_exchange = snapshot_exchange(exchange)?;
        let result = eval_async(
            Arc::clone(&self.engine),
            self.script.clone(),
            js_exchange,
            self.execution_timeout_ms,
        )
        .await
        .map_err(|e| js_err_to_lang_err(&self.script, e))?;
        Ok(is_truthy(&result.return_value))
    }
}

/// Evaluate a JS expression asynchronously with a timeout.
///
/// Uses `tokio::task::spawn_blocking` to run the synchronous JS engine on a
/// blocking thread, and `tokio::time::timeout` to enforce the execution deadline.
async fn eval_async(
    engine: Arc<dyn JsEngine>,
    script: String,
    exchange: JsExchange,
    execution_timeout_ms: u64,
) -> Result<JsEvalResult, JsLanguageError> {
    let timeout = Duration::from_millis(execution_timeout_ms);
    tokio::time::timeout(timeout, async {
        let join = tokio::task::spawn_blocking(move || engine.eval(&script, exchange));
        join.await.map_err(|e| JsLanguageError::Execution {
            message: format!("JS execution task join error: {e}"),
        })?
    })
    .await
    .map_err(|_| JsLanguageError::Execution {
        message: "JS execution timeout".to_string(),
    })?
}

/// Interpret a [`Value`] as a JS-style truthy boolean.
fn is_truthy(v: &Value) -> bool {
    match v {
        Value::Null => false,
        Value::Bool(b) => *b,
        Value::Number(n) => n.as_f64().map(|f| f != 0.0).unwrap_or(false),
        Value::String(s) => !s.is_empty(),
        Value::Array(_) | Value::Object(_) => true,
    }
}

#[cfg(test)]
mod tests {
    use std::{sync::Arc, time::Instant};

    use camel_language_api::Message;
    use serde_json::json;

    use super::*;
    use crate::engines::boa::BoaEngine;
    use crate::error::JsLanguageError;

    fn make_exchange() -> Exchange {
        let mut msg = Message::default();
        msg.headers.insert("foo".to_string(), json!("bar"));
        msg.body = Body::Text("hello".to_string());
        let mut ex = Exchange::new(msg);
        ex.properties.insert("key".to_string(), json!("val"));
        ex
    }

    fn engine() -> Arc<dyn JsEngine> {
        Arc::new(BoaEngine::new())
    }

    #[derive(Debug)]
    struct SlowEngine;

    impl JsEngine for SlowEngine {
        fn eval(
            &self,
            _source: &str,
            exchange: JsExchange,
        ) -> Result<JsEvalResult, JsLanguageError> {
            std::thread::sleep(Duration::from_millis(500));
            Ok(JsEvalResult {
                return_value: json!("done"),
                headers: exchange.headers,
                body: exchange.body,
                properties: exchange.properties,
            })
        }

        fn validate(&self, _source: &str) -> Result<(), JsLanguageError> {
            Ok(())
        }
    }

    #[tokio::test]
    async fn test_expression_timeout_returns_error_before_eval_completes() {
        let expr = JsExpression::new("sleep500()".to_string(), Arc::new(SlowEngine), 100);
        let ex = make_exchange();

        let start = Instant::now();
        let result = expr.evaluate(&ex).await;
        let elapsed = start.elapsed();

        assert!(result.is_err(), "expected timeout error");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("JS execution timeout"),
            "unexpected error message: {err}"
        );
        assert!(
            elapsed < Duration::from_millis(500),
            "timeout should happen before 500ms, elapsed: {elapsed:?}"
        );
    }

    #[tokio::test]
    async fn test_expression_arithmetic() {
        let expr = JsExpression::new("1 + 2".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert_eq!(result.as_i64().unwrap(), 3);
    }

    #[tokio::test]
    async fn test_expression_reads_header() {
        let expr = JsExpression::new("camel.headers.get('foo')".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert_eq!(result.as_str().unwrap(), "bar");
    }

    #[tokio::test]
    async fn test_expression_reads_body() {
        let expr = JsExpression::new("camel.body".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert_eq!(result.as_str().unwrap(), "hello");
    }

    #[tokio::test]
    async fn test_expression_does_not_mutate() {
        let expr = JsExpression::new(
            "camel.headers.set('x', 'y'); camel.body = 'changed'".to_string(),
            engine(),
            5_000,
        );
        let ex = make_exchange();
        let _ = expr.evaluate(&ex).await.unwrap();
        assert!(!ex.input.headers.contains_key("x"));
        assert_eq!(ex.input.body.as_text(), Some("hello"));
    }

    #[tokio::test]
    async fn test_mutating_expression_propagates_header() {
        let expr = JsMutatingExpression::new(
            "camel.headers.set('newkey', 'newval'); 'done'".to_string(),
            engine(),
            5_000,
        );
        let mut ex = make_exchange();
        let result = expr.evaluate(&mut ex).await.unwrap();
        assert_eq!(result.as_str().unwrap(), "done");
        assert_eq!(
            ex.input.headers.get("newkey").unwrap().as_str().unwrap(),
            "newval"
        );
    }

    #[tokio::test]
    async fn test_mutating_expression_propagates_property() {
        let expr = JsMutatingExpression::new(
            "camel.set_property('newkey', 'newval'); 'done'".to_string(),
            engine(),
            5_000,
        );
        let mut ex = make_exchange();
        let result = expr.evaluate(&mut ex).await.unwrap();
        assert_eq!(result.as_str().unwrap(), "done");
        assert_eq!(
            ex.properties.get("newkey").unwrap().as_str().unwrap(),
            "newval"
        );
    }

    #[tokio::test]
    async fn test_expression_reads_property_function() {
        let expr = JsExpression::new("camel.property('key')".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert_eq!(result.as_str().unwrap(), "val");
    }

    #[tokio::test]
    async fn test_mutating_expression_propagates_body() {
        let expr = JsMutatingExpression::new(
            "camel.body = 'modified'; camel.body".to_string(),
            engine(),
            5_000,
        );
        let mut ex = make_exchange();
        let _ = expr.evaluate(&mut ex).await.unwrap();
        assert_eq!(ex.input.body.as_text(), Some("modified"));
    }

    #[tokio::test]
    async fn test_mutating_expression_preserves_bytes_body() {
        let expr = JsMutatingExpression::new(
            "camel.headers.set('x', '1'); 'done'".to_string(),
            engine(),
            5_000,
        );
        let mut ex = Exchange::new(Message::default());
        ex.input.body = Body::from(b"binary data".to_vec());

        let _ = expr.evaluate(&mut ex).await.unwrap();

        assert!(
            matches!(ex.input.body, Body::Bytes(_)),
            "Bytes body should be preserved"
        );
    }

    #[tokio::test]
    async fn test_mutating_expression_preserves_empty_body() {
        let expr = JsMutatingExpression::new(
            "camel.headers.set('x', '1'); 'done'".to_string(),
            engine(),
            5_000,
        );
        let mut ex = Exchange::new(Message::default());
        ex.input.body = Body::Empty;

        let _ = expr.evaluate(&mut ex).await.unwrap();

        assert!(
            matches!(ex.input.body, Body::Empty),
            "Empty body should be preserved when JS does not set camel.body"
        );
    }

    #[tokio::test]
    async fn test_mutating_expression_rejects_stream_body() {
        let expr = JsMutatingExpression::new(
            "camel.headers.set('x', '1'); 'done'".to_string(),
            engine(),
            5_000,
        );
        let mut ex = Exchange::new(Message::default());
        ex.input.body = Body::Stream(camel_api::StreamBody {
            stream: std::sync::Arc::new(tokio::sync::Mutex::new(None)),
            metadata: camel_api::StreamMetadata::default(),
        });

        let result = expr.evaluate(&mut ex).await;
        assert!(result.is_err(), "JS should reject Body::Stream with error");
    }

    #[tokio::test]
    async fn test_mutating_expression_can_override_bytes_body() {
        let expr = JsMutatingExpression::new(
            "camel.body = 'replaced'; 'done'".to_string(),
            engine(),
            5_000,
        );
        let mut ex = Exchange::new(Message::default());
        ex.input.body = Body::from(b"binary".to_vec());

        let _ = expr.evaluate(&mut ex).await.unwrap();

        assert!(
            !matches!(ex.input.body, Body::Bytes(_)),
            "Body should be updated when JS explicitly sets camel.body"
        );
        assert_eq!(ex.input.body.as_text(), Some("replaced"));
    }

    #[tokio::test]
    async fn test_mutating_expression_atomic_rollback_on_error() {
        let expr = JsMutatingExpression::new(
            "camel.headers.set('x', 'y'); throw new Error('fail')".to_string(),
            engine(),
            5_000,
        );
        let mut ex = make_exchange();
        let result = expr.evaluate(&mut ex).await;
        assert!(result.is_err());
        assert!(!ex.input.headers.contains_key("x"));
        assert_eq!(ex.input.body.as_text(), Some("hello"));
    }

    #[tokio::test]
    async fn test_predicate_true() {
        let pred = JsPredicate::new("true".to_string(), engine(), 5_000);
        let ex = make_exchange();
        assert!(pred.matches(&ex).await.unwrap());
    }

    #[tokio::test]
    async fn test_predicate_false() {
        let pred = JsPredicate::new("false".to_string(), engine(), 5_000);
        let ex = make_exchange();
        assert!(!pred.matches(&ex).await.unwrap());
    }

    #[tokio::test]
    async fn test_predicate_header_condition() {
        let pred = JsPredicate::new(
            "camel.headers.get('foo') === 'bar'".to_string(),
            engine(),
            5_000,
        );
        let ex = make_exchange();
        assert!(pred.matches(&ex).await.unwrap());
    }

    #[tokio::test]
    async fn test_predicate_truthy_string() {
        let pred = JsPredicate::new("'non-empty'".to_string(), engine(), 5_000);
        let ex = make_exchange();
        assert!(pred.matches(&ex).await.unwrap());
    }

    #[tokio::test]
    async fn test_predicate_falsy_null() {
        let pred = JsPredicate::new("null".to_string(), engine(), 5_000);
        let ex = make_exchange();
        assert!(!pred.matches(&ex).await.unwrap());
    }

    #[tokio::test]
    async fn test_is_truthy_values() {
        assert!(is_truthy(&json!(true)));
        assert!(is_truthy(&json!(1)));
        assert!(is_truthy(&json!("x")));
        assert!(is_truthy(&json!({})));
        assert!(!is_truthy(&json!(false)));
        assert!(!is_truthy(&json!(0)));
        assert!(!is_truthy(&json!("")));
        assert!(!is_truthy(&Value::Null));
    }

    // --- JS-003: Edge case tests ---

    #[tokio::test]
    async fn test_expression_empty_script_returns_undefined() {
        // An empty script should evaluate to undefined (maps to Null)
        let expr = JsExpression::new("".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert!(
            result.is_null(),
            "empty script should return null/undefined"
        );
    }

    #[tokio::test]
    async fn test_expression_syntax_error_returns_err() {
        let expr = JsExpression::new("let x = {{{".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await;
        assert!(result.is_err(), "syntax error should return Err");
    }

    #[tokio::test]
    async fn test_expression_non_string_return_value() {
        // A script returning a number (not string) should work correctly
        let expr = JsExpression::new("42".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert_eq!(result.as_i64().unwrap(), 42);
    }

    #[tokio::test]
    async fn test_expression_object_return_value() {
        // A script returning an object should produce a JSON object
        let expr = JsExpression::new("({a: 1, b: 'two'})".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert!(result.is_object(), "object result should be a JSON object");
        let obj = result.as_object().unwrap();
        assert_eq!(obj.get("a").unwrap().as_i64().unwrap(), 1);
        assert_eq!(obj.get("b").unwrap().as_str().unwrap(), "two");
    }

    #[tokio::test]
    async fn test_expression_array_return_value() {
        let expr = JsExpression::new("[1, 2, 3]".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert!(result.is_array());
        let arr = result.as_array().unwrap();
        assert_eq!(arr.len(), 3);
    }

    #[tokio::test]
    async fn test_expression_boolean_return_value() {
        let expr = JsExpression::new("true".to_string(), engine(), 5_000);
        let ex = make_exchange();
        let result = expr.evaluate(&ex).await.unwrap();
        assert!(result.is_boolean());
        assert!(result.as_bool().unwrap());
    }
}