camel-language-api 0.25.1

Language trait API for rust-camel (Expression, Predicate)
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
//! Tunable resource limits for in-process scripting engines (Rhai, Boa JS).
//!
//! These types live in `camel-language-api` (the lowest shared language contract
//! crate) to avoid a circular dependency: `camel-language-rhai` / `camel-language-js`
//! already depend on `camel-language-api`, so the limit types must be defined here
//! rather than in `camel-config` (which those crates cannot depend on).
//!
//! All fields are `Option`; `None` means "use the rust-camel runtime default" —
//! never the upstream engine's unlimited default (per ADR-0011). The resolve
//! functions in each language crate document the concrete defaults.

use serde::{Deserialize, Serialize};

// ---------------------------------------------------------------------------
// Rhai limits
// ---------------------------------------------------------------------------

/// Tunable resource limits for a single Rhai `Engine` instance.
///
/// Surfaced in `Camel.toml` as:
///
/// ```toml
/// [languages.rhai.limits]
/// max-operations = 500000
/// max-string-size = 10485760
/// max-array-size = 100000
/// max-map-size = 100000
/// max-expression-depth = 10
/// max-function-expression-depth = 5
/// execution-timeout-ms = 5000
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RhaiLimitsConfig {
    /// Maximum number of operations before Rhai terminates the script
    /// (rhai: `max_operations`). Counter resets each call.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_operations: Option<u64>,

    /// Maximum string size in bytes (rhai: `max_string_size`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_string_size: Option<usize>,

    /// Maximum array size in elements (rhai: `max_array_size`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_array_size: Option<usize>,

    /// Maximum map size in key-value pairs (rhai: `max_map_size`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_map_size: Option<usize>,

    /// Maximum nesting depth for expressions (rhai: `max_expression_depth`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_expression_depth: Option<u32>,

    /// Maximum nesting depth for function call expressions
    /// (rhai: `max_function_expression_depth`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_function_expression_depth: Option<u32>,

    /// Maximum execution wall-clock time in milliseconds.
    /// Rhai has no built-in timeout; the consuming code enforces this via
    /// `Engine::on_progress` or a tokio timeout wrapper.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_timeout_ms: Option<u64>,
}

// ---------------------------------------------------------------------------
// JS (Boa) limits
// ---------------------------------------------------------------------------

/// Tunable resource limits for a single Boa JS `Context` instance.
///
/// Surfaced in `Camel.toml` as:
///
/// ```toml
/// [languages.js.limits]
/// execution-timeout-ms = 5000
/// max-loop-iterations = 1000000
/// max-recursion-depth = 64
/// max-stack-size = 1048576
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct JsLimitsConfig {
    /// Maximum execution wall-clock time in milliseconds.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_timeout_ms: Option<u64>,

    /// Maximum number of loop iterations before Boa terminates execution.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_loop_iterations: Option<u64>,

    /// Maximum recursion depth for function calls.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_recursion_depth: Option<usize>,

    /// Maximum Boa VM stack size, in stack slots (not bytes).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_stack_size: Option<usize>,
}

// ---------------------------------------------------------------------------
// MiniJinja limits
// ---------------------------------------------------------------------------

/// Tunable resource limits for a single MiniJinja `Environment` instance.
///
/// Surfaced in `Camel.toml` as:
///
/// ```toml
/// [languages.minijinja.limits]
/// max-template-source-size = 1048576
/// max-context-size = 4194304
/// max-output-size = 4194304
/// fuel = 100000
/// max-recursion-depth = 64
/// execution-timeout-ms = 5000
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MinijinjaLimitsConfig {
    /// Maximum size of the compiled template source in bytes.
    /// (minijinja: `Environment::set_max_template_source_size`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_template_source_size: Option<usize>,

    /// Maximum serialised context size in bytes.
    /// (minijinja: `Environment::set_max_context_size`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_context_size: Option<usize>,

    /// Maximum rendered output size in bytes.
    /// (minijinja: `Environment::set_max_output_size`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_output_size: Option<usize>,

    /// Fuel limit for the MiniJinja VM (coarse instruction budget).
    /// (minijinja: `Environment::set_fuel`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub fuel: Option<u64>,

    /// Maximum recursion depth for template includes/blocks.
    /// (minijinja: `Environment::set_max_recursion_depth`)
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_recursion_depth: Option<u32>,

    /// Maximum execution wall-clock time in milliseconds.
    /// The consuming code enforces this via a tokio timeout wrapper.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_timeout_ms: Option<u64>,
}

// ---------------------------------------------------------------------------
// Wrapper structs for Camel.toml sections
// ---------------------------------------------------------------------------

/// Rhai engine configuration block in `Camel.toml`.
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct RhaiEngineConfig {
    /// Resource limits for the Rhai engine.
    #[serde(default)]
    pub limits: RhaiLimitsConfig,
}

/// JS (Boa) engine configuration block in `Camel.toml`.
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct JsEngineConfig {
    /// Resource limits for the Boa JS engine.
    #[serde(default)]
    pub limits: JsLimitsConfig,
}

/// MiniJinja engine configuration block in `Camel.toml`.
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct MinijinjaEngineConfig {
    /// Resource limits for the MiniJinja engine.
    #[serde(default)]
    pub limits: MinijinjaLimitsConfig,
}

/// Top-level `[languages]` section in `Camel.toml`.
///
/// ```toml
/// [languages.rhai.limits]
/// max-operations = 500000
///
/// [languages.js.limits]
/// execution-timeout-ms = 5000
/// ```
#[derive(Debug, Clone, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case", deny_unknown_fields)]
pub struct LanguagesConfig {
    /// Rhai engine configuration.
    #[serde(default)]
    pub rhai: RhaiEngineConfig,

    /// JS (Boa) engine configuration.
    #[serde(default)]
    pub js: JsEngineConfig,

    /// MiniJinja engine configuration.
    #[serde(default)]
    pub minijinja: MinijinjaEngineConfig,
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    // -- RhaiLimitsConfig tests -------------------------------------------

    #[test]
    fn rhai_defaults_to_all_none() {
        let cfg = RhaiLimitsConfig::default();
        assert_eq!(cfg.max_operations, None);
        assert_eq!(cfg.max_string_size, None);
        assert_eq!(cfg.max_array_size, None);
        assert_eq!(cfg.max_map_size, None);
        assert_eq!(cfg.max_expression_depth, None);
        assert_eq!(cfg.max_function_expression_depth, None);
        assert_eq!(cfg.execution_timeout_ms, None);
    }

    #[test]
    fn rhai_deserialises_full_block() {
        let toml = toml::toml! {
            max-operations = 500000i64
            max-string-size = 10485760i64
            max-array-size = 100000i64
            max-map-size = 100000i64
            max-expression-depth = 10
            max-function-expression-depth = 5
            execution-timeout-ms = 5000i64
        };
        let cfg: RhaiLimitsConfig = toml.try_into().expect("deserialize");
        assert_eq!(cfg.max_operations, Some(500_000));
        assert_eq!(cfg.max_string_size, Some(10_485_760));
        assert_eq!(cfg.max_array_size, Some(100_000));
        assert_eq!(cfg.max_map_size, Some(100_000));
        assert_eq!(cfg.max_expression_depth, Some(10));
        assert_eq!(cfg.max_function_expression_depth, Some(5));
        assert_eq!(cfg.execution_timeout_ms, Some(5000));
    }

    #[test]
    fn rhai_deserialises_partial_block() {
        let toml = toml::toml! {
            max-operations = 100000i64
            execution-timeout-ms = 3000i64
        };
        let cfg: RhaiLimitsConfig = toml.try_into().expect("deserialize");
        assert_eq!(cfg.max_operations, Some(100_000));
        assert_eq!(cfg.execution_timeout_ms, Some(3000));
        // All other fields should be None
        assert_eq!(cfg.max_string_size, None);
        assert_eq!(cfg.max_expression_depth, None);
    }

    #[test]
    fn rhai_rejects_unknown_field() {
        let toml = toml::toml! {
            max-operations = 100000i64
            fuel = 1000i64
        };
        let result: Result<RhaiLimitsConfig, _> = toml.try_into();
        assert!(result.is_err(), "deny_unknown_fields must reject `fuel`");
    }

    #[test]
    fn rhai_serde_round_trip_preserves_set_fields() {
        let original = RhaiLimitsConfig {
            max_operations: Some(200_000),
            max_string_size: Some(5_242_880),
            execution_timeout_ms: Some(10_000),
            ..Default::default()
        };
        let serialized = toml::to_string(&original).expect("serialize");
        let back: RhaiLimitsConfig = toml::from_str(&serialized).expect("deserialize");
        assert_eq!(original, back);
    }

    #[test]
    fn rhai_skip_serializing_none_fields() {
        let cfg = RhaiLimitsConfig {
            max_operations: Some(100_000),
            max_string_size: None,
            execution_timeout_ms: Some(5000),
            ..Default::default()
        };
        let s = toml::to_string(&cfg).expect("serialize");
        assert!(s.contains("max-operations"));
        assert!(s.contains("execution-timeout-ms"));
        assert!(!s.contains("max-string-size"));
        assert!(!s.contains("max-expression-depth"));
    }

    // -- JsLimitsConfig tests ---------------------------------------------

    #[test]
    fn js_defaults_to_all_none() {
        let cfg = JsLimitsConfig::default();
        assert_eq!(cfg.execution_timeout_ms, None);
        assert_eq!(cfg.max_loop_iterations, None);
        assert_eq!(cfg.max_recursion_depth, None);
        assert_eq!(cfg.max_stack_size, None);
    }

    #[test]
    fn js_deserialises_full_block() {
        let toml = toml::toml! {
            execution-timeout-ms = 5000i64
            max-loop-iterations = 1000000i64
            max-recursion-depth = 64i64
            max-stack-size = 1048576i64
        };
        let cfg: JsLimitsConfig = toml.try_into().expect("deserialize");
        assert_eq!(cfg.execution_timeout_ms, Some(5000));
        assert_eq!(cfg.max_loop_iterations, Some(1_000_000));
        assert_eq!(cfg.max_recursion_depth, Some(64));
        assert_eq!(cfg.max_stack_size, Some(1_048_576));
    }

    #[test]
    fn js_deserialises_partial_block() {
        let toml = toml::toml! {
            execution-timeout-ms = 3000i64
            max-recursion-depth = 32i64
        };
        let cfg: JsLimitsConfig = toml.try_into().expect("deserialize");
        assert_eq!(cfg.execution_timeout_ms, Some(3000));
        assert_eq!(cfg.max_recursion_depth, Some(32));
        assert_eq!(cfg.max_loop_iterations, None);
        assert_eq!(cfg.max_stack_size, None);
    }

    #[test]
    fn js_rejects_unknown_field() {
        let toml = toml::toml! {
            execution-timeout-ms = 5000i64
            fuel = 1000i64
        };
        let result: Result<JsLimitsConfig, _> = toml.try_into();
        assert!(result.is_err(), "deny_unknown_fields must reject `fuel`");
    }

    #[test]
    fn js_serde_round_trip_preserves_set_fields() {
        let original = JsLimitsConfig {
            execution_timeout_ms: Some(10_000),
            max_loop_iterations: Some(500_000),
            ..Default::default()
        };
        let serialized = toml::to_string(&original).expect("serialize");
        let back: JsLimitsConfig = toml::from_str(&serialized).expect("deserialize");
        assert_eq!(original, back);
    }

    #[test]
    fn js_skip_serializing_none_fields() {
        let cfg = JsLimitsConfig {
            execution_timeout_ms: Some(5000),
            max_loop_iterations: Some(1_000_000),
            ..Default::default()
        };
        let s = toml::to_string(&cfg).expect("serialize");
        assert!(s.contains("execution-timeout-ms"));
        assert!(s.contains("max-loop-iterations"));
        assert!(!s.contains("max-recursion-depth"));
        assert!(!s.contains("max-stack-size"));
    }

    // -- Wrapper struct tests ---------------------------------------------

    #[test]
    fn rhai_engine_config_defaults() {
        let cfg = RhaiEngineConfig::default();
        assert_eq!(cfg.limits, RhaiLimitsConfig::default());
    }

    #[test]
    fn js_engine_config_defaults() {
        let cfg = JsEngineConfig::default();
        assert_eq!(cfg.limits, JsLimitsConfig::default());
    }

    #[test]
    fn languages_config_defaults() {
        let cfg = LanguagesConfig::default();
        assert_eq!(cfg.rhai.limits, RhaiLimitsConfig::default());
        assert_eq!(cfg.js.limits, JsLimitsConfig::default());
        assert_eq!(cfg.minijinja.limits, MinijinjaLimitsConfig::default());
    }

    #[test]
    fn languages_deserialises_both_engines() {
        let toml_str = r#"
            [rhai.limits]
            max-operations = 500000
            execution-timeout-ms = 5000

            [js.limits]
            execution-timeout-ms = 3000
            max-loop-iterations = 1000000
        "#;
        let cfg: LanguagesConfig = toml::from_str(toml_str).expect("deserialize");
        assert_eq!(cfg.rhai.limits.max_operations, Some(500_000));
        assert_eq!(cfg.rhai.limits.execution_timeout_ms, Some(5000));
        assert_eq!(cfg.js.limits.execution_timeout_ms, Some(3000));
        assert_eq!(cfg.js.limits.max_loop_iterations, Some(1_000_000));
    }

    #[test]
    fn languages_serde_round_trip() {
        let original = LanguagesConfig {
            rhai: RhaiEngineConfig {
                limits: RhaiLimitsConfig {
                    max_operations: Some(100_000),
                    ..Default::default()
                },
            },
            js: JsEngineConfig::default(),
            minijinja: MinijinjaEngineConfig::default(),
        };
        let serialized = toml::to_string(&original).expect("serialize");
        let back: LanguagesConfig = toml::from_str(&serialized).expect("deserialize");
        assert_eq!(original, back);
    }

    // -- MinijinjaLimitsConfig tests ---------------------------------------

    #[test]
    fn minijinja_defaults_to_all_none() {
        let cfg = MinijinjaLimitsConfig::default();
        assert_eq!(cfg.max_template_source_size, None);
        assert_eq!(cfg.max_context_size, None);
        assert_eq!(cfg.max_output_size, None);
        assert_eq!(cfg.fuel, None);
        assert_eq!(cfg.max_recursion_depth, None);
        assert_eq!(cfg.execution_timeout_ms, None);
    }

    #[test]
    fn minijinja_deserialises_full_block() {
        let toml = toml::toml! {
            max-template-source-size = 1048576i64
            max-context-size = 4194304i64
            max-output-size = 4194304i64
            fuel = 100000i64
            max-recursion-depth = 64
            execution-timeout-ms = 5000i64
        };
        let cfg: MinijinjaLimitsConfig = toml.try_into().expect("deserialize");
        assert_eq!(cfg.max_template_source_size, Some(1_048_576));
        assert_eq!(cfg.max_context_size, Some(4_194_304));
        assert_eq!(cfg.max_output_size, Some(4_194_304));
        assert_eq!(cfg.fuel, Some(100_000));
        assert_eq!(cfg.max_recursion_depth, Some(64));
        assert_eq!(cfg.execution_timeout_ms, Some(5_000));
    }

    #[test]
    fn minijinja_rejects_unknown_field() {
        let toml = toml::toml! {
            fuel = 1000i64
            bogus = 1i64
        };
        let result: Result<MinijinjaLimitsConfig, _> = toml.try_into();
        assert!(result.is_err(), "deny_unknown_fields must reject `bogus`");
    }

    #[test]
    fn minijinja_skip_serializing_none_fields() {
        let cfg = MinijinjaLimitsConfig {
            fuel: Some(100_000),
            max_recursion_depth: Some(64),
            ..Default::default()
        };
        let s = toml::to_string(&cfg).expect("serialize");
        assert!(s.contains("fuel") && s.contains("max-recursion-depth"));
        assert!(!s.contains("max-template-source-size") && !s.contains("max-context-size"));
    }
}