vrl 0.37.0

Vector Remap 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
use std::{error::Error, fmt, ops::ControlFlow};

use crate::path::OwnedTargetPath;
use crate::value::Value;

use super::ExpressionError;
use super::TimeZone;
use super::{Context, Program, Target, state};

#[allow(clippy::module_name_repetitions)]
pub type RuntimeResult = Result<Value, Terminate>;

/// Allows an embedder to cooperatively interrupt VRL execution.
///
/// VRL invokes [`ExecutionControl::checkpoint`] between expressions. A
/// controller returns [`ControlFlow::Break`] to stop execution or
/// [`ControlFlow::Continue`] to allow it to proceed. The controller owns the
/// interruption policy, such as a deadline, operation budget, or shared
/// cancellation token.
pub trait ExecutionControl {
    fn checkpoint(&mut self) -> ControlFlow<()>;
}

impl<F> ExecutionControl for F
where
    F: FnMut() -> ControlFlow<()>,
{
    fn checkpoint(&mut self) -> ControlFlow<()> {
        self()
    }
}

#[derive(Debug, Default)]
pub struct Runtime {
    state: state::RuntimeState,
}

/// The error raised if the runtime is terminated.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Terminate {
    /// Execution was interrupted by an embedder-provided execution control.
    Interrupted,

    /// A manual `abort` call.
    ///
    /// This is an intentional termination that does not result in an
    /// `Ok(Value)` result, but should neither be interpreted as an unexpected
    /// outcome.
    Abort(ExpressionError),

    /// An unexpected program termination.
    Error(ExpressionError),
}

impl Terminate {
    #[must_use]
    pub fn get_expression_error(self) -> ExpressionError {
        match self {
            Terminate::Interrupted => ExpressionError::Interrupted,
            Terminate::Error(error) | Terminate::Abort(error) => error,
        }
    }
}

impl fmt::Display for Terminate {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Terminate::Interrupted => f.write_str("execution interrupted"),
            Terminate::Error(error) | Terminate::Abort(error) => error.fmt(f),
        }
    }
}

impl Error for Terminate {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        None
    }
}

impl Runtime {
    #[must_use]
    pub fn new(state: state::RuntimeState) -> Self {
        Self { state }
    }

    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.state.is_empty()
    }

    pub fn clear(&mut self) {
        self.state.clear();
    }

    /// Resolves the provided [`Program`] to completion using the given [`Target`].
    ///
    /// This function ensures that the target contains a valid root object before proceeding.
    /// If the target is invalid or missing, an error is returned. The resolution process
    /// is performed using a [`Context`] that maintains execution state and timezone information.
    ///
    /// # Arguments
    ///
    /// * `target` - A mutable reference to an object implementing the [`Target`] trait. This
    ///   serves as the execution environment for resolving the program.
    /// * `program` - A reference to the [`Program`] that needs to be resolved.
    /// * `timezone` - A reference to the [`TimeZone`] used for resolving time-dependent expressions.
    ///
    /// # Returns
    ///
    /// Returns a [`RuntimeResult`], which is either:
    /// - `Ok(value)`: The program resolved successfully, producing a value.
    /// - `Err(Terminate::Error)`: A fatal error occurred during resolution.
    /// - `Err(Terminate::Abort)`: The resolution was aborted due to a non-fatal expression error.
    ///
    /// # Errors
    ///
    /// The function may return an error in the following cases:
    /// - If the target does not contain a valid root object, an error is returned.
    /// - If the resolution process encounters an [`ExpressionError::Error`].
    /// - If the program execution results in an [`ExpressionError::Abort`], [`ExpressionError::Fallible`], or [`ExpressionError::Missing`], the function aborts with `Terminate::Abort`.
    pub fn resolve(
        &mut self,
        target: &mut dyn Target,
        program: &Program,
        timezone: &TimeZone,
    ) -> RuntimeResult {
        self.resolve_inner(target, program, *timezone, None)
    }

    /// Resolves the provided [`Program`] with an embedder-provided execution
    /// control.
    ///
    /// The control is scoped to this invocation and is not stored in the
    /// [`Runtime`] or its [`state::RuntimeState`]. Returning
    /// [`ControlFlow::Break`] from [`ExecutionControl::checkpoint`] terminates
    /// the invocation with [`Terminate::Interrupted`].
    ///
    /// This is cooperative interruption: VRL checks between expressions and
    /// wherever a function explicitly calls [`Context::checkpoint`]. It does
    /// not preempt a single blocking or long-running function call.
    ///
    /// # Errors
    ///
    /// Returns [`Terminate::Interrupted`] when the control requests
    /// interruption. Other termination conditions are the same as
    /// [`Runtime::resolve`].
    pub fn resolve_with_control(
        &mut self,
        target: &mut dyn Target,
        program: &Program,
        timezone: &TimeZone,
        control: &mut dyn ExecutionControl,
    ) -> RuntimeResult {
        self.resolve_inner(target, program, *timezone, Some(control))
    }

    fn resolve_inner(
        &mut self,
        target: &mut dyn Target,
        program: &Program,
        timezone: TimeZone,
        control: Option<&mut dyn ExecutionControl>,
    ) -> RuntimeResult {
        // Validate that the path is a value.
        match target.target_get(&OwnedTargetPath::event_root()) {
            Ok(Some(_)) => {}
            Ok(None) => {
                return Err(Terminate::Error(
                    "expected target object, got nothing".to_owned().into(),
                ));
            }
            Err(err) => {
                return Err(Terminate::Error(
                    format!("error querying target object: {err}").into(),
                ));
            }
        }

        let mut ctx = match control {
            Some(control) => Context::new_with_control(target, &mut self.state, &timezone, control),
            None => Context::new(target, &mut self.state, &timezone),
        };

        match program.resolve(&mut ctx) {
            Err(ExpressionError::Interrupted) => Err(Terminate::Interrupted),
            Ok(value) | Err(ExpressionError::Return { value, .. }) => Ok(value),
            Err(
                err @ (ExpressionError::Abort { .. }
                | ExpressionError::Fallible { .. }
                | ExpressionError::Missing { .. }),
            ) => Err(Terminate::Abort(err)),
            Err(err @ (ExpressionError::Error { .. } | ExpressionError::Break { .. })) => {
                Err(Terminate::Error(err))
            }
        }
    }
}

#[cfg(all(test, feature = "stdlib"))]
mod execution_control_tests {
    use std::collections::BTreeMap;
    use std::ops::ControlFlow;

    use indoc::indoc;

    use super::{Context, ExecutionControl, Runtime, Terminate, TimeZone};
    use crate::compiler::state::RuntimeState;
    use crate::compiler::{Program, TargetValue};
    use crate::parser::ast::Ident;
    use crate::value::{Secrets, Value};

    struct BreakAt {
        checkpoint: usize,
        break_at: usize,
    }

    impl BreakAt {
        fn new(break_at: usize) -> Self {
            Self {
                checkpoint: 0,
                break_at,
            }
        }
    }

    impl ExecutionControl for BreakAt {
        fn checkpoint(&mut self) -> ControlFlow<()> {
            self.checkpoint += 1;

            if self.checkpoint >= self.break_at {
                ControlFlow::Break(())
            } else {
                ControlFlow::Continue(())
            }
        }
    }

    fn compile(source: &str) -> Program {
        crate::compiler::compile(source, &crate::stdlib::all())
            .expect("program should compile")
            .program
    }

    fn target() -> Value {
        BTreeMap::from([
            ("items".into(), Value::Array(vec![Value::from(1); 100])),
            ("value".into(), Value::from("1")),
        ])
        .into()
    }

    #[test]
    fn resolve_without_control_preserves_existing_api() {
        let program = compile("1 + 2");
        let mut target = target();
        let mut runtime = Runtime::new(RuntimeState::default());

        assert_eq!(
            runtime.resolve(&mut target, &program, &TimeZone::default()),
            Ok(Value::from(3)),
        );
    }

    #[test]
    fn for_each_loop_returns_interrupted() {
        let source = r"
            count = 0
            for_each(array!(.items)) -> |_index, _value| {
                count = count + 1
            }
            count
        ";

        let program = compile(source);

        let mut target: Value =
            BTreeMap::from([("items".into(), Value::Array(vec![Value::from(1); 5_000]))]).into();

        let mut runtime = Runtime::new(RuntimeState::default());
        let mut control = || ControlFlow::Break(());

        assert_eq!(
            runtime
                .resolve_with_control(&mut target, &program, &TimeZone::default(), &mut control,),
            Err(Terminate::Interrupted),
        );
    }

    #[test]
    fn interruption_is_not_caught_by_error_coalescing() {
        let program = compile("to_int(.value) ?? 2");
        let mut target = target();
        let mut runtime = Runtime::new(RuntimeState::default());
        let mut control = BreakAt::new(2);

        assert_eq!(
            runtime
                .resolve_with_control(&mut target, &program, &TimeZone::default(), &mut control,),
            Err(Terminate::Interrupted),
        );
    }

    #[test]
    fn interruption_is_not_caught_by_infallible_assignment() {
        let program = compile("value, error = to_int(.value)\nvalue");
        let mut target = target();
        let mut runtime = Runtime::new(RuntimeState::default());
        let mut control = BreakAt::new(2);

        assert_eq!(
            runtime
                .resolve_with_control(&mut target, &program, &TimeZone::default(), &mut control,),
            Err(Terminate::Interrupted),
        );
    }

    #[test]
    fn interruption_is_not_wrapped_by_boolean_or() {
        let program = compile("false || true");
        let mut target = target();
        let mut runtime = Runtime::new(RuntimeState::default());
        let mut control = BreakAt::new(3);

        assert_eq!(
            runtime
                .resolve_with_control(&mut target, &program, &TimeZone::default(), &mut control,),
            Err(Terminate::Interrupted),
        );
    }

    #[test]
    fn control_is_scoped_to_one_resolve_call() {
        let program = compile("1");
        let mut target = target();
        let mut runtime = Runtime::new(RuntimeState::default());
        let mut control = || ControlFlow::Break(());

        assert_eq!(
            runtime
                .resolve_with_control(&mut target, &program, &TimeZone::default(), &mut control,),
            Err(Terminate::Interrupted),
        );
        assert_eq!(
            runtime.resolve(&mut target, &program, &TimeZone::default()),
            Ok(Value::from(1)),
        );
    }

    #[test]
    fn interruption_restores_closure_variables() {
        let source = r#"
            item = "outer"
            for_each(array!(.items)) -> |_index, item| {
                item
            }
            item
        "#;
        let program = compile(source);
        let mut target = target();
        let mut runtime = Runtime::new(RuntimeState::default());
        let mut control = BreakAt::new(10);

        assert_eq!(
            runtime
                .resolve_with_control(&mut target, &program, &TimeZone::default(), &mut control,),
            Err(Terminate::Interrupted),
        );
        assert_eq!(
            runtime.state.variable(&Ident::new("item")),
            Some(&Value::from("outer")),
        );
    }

    #[test]
    fn break_is_not_caught_by_infallible_assignment() {
        let source = indoc! {r#"
            count = 0
            for_each([1, 2, 3]) -> |_i, val| {
                count = count + 1
                _, err = if val == 2 {
                    break
                } else {
                    parse_int("not_a_number")
                }
            }
            count
        "#};

        let fns = crate::stdlib::all();
        let program = crate::compiler::compile(source, &fns).unwrap().program;

        let mut target = TargetValue {
            value: Value::Null,
            metadata: Value::Null,
            secrets: Secrets::new(),
        };
        let mut state = RuntimeState::default();
        let tz = TimeZone::default();
        let mut ctx = Context::new(&mut target, &mut state, &tz);

        let result = program.resolve(&mut ctx);
        assert_eq!(result, Ok(Value::from(2)));
    }

    #[test]
    fn break_is_not_caught_by_error_coalescing() {
        let source = indoc! {r#"
            count = 0
            for_each([1, 2, 3]) -> |_i, val| {
                count = count + 1
                res = { if val == 2 { break } else { parse_int("not_a_number") } } ?? 999
            }
            count
        "#};

        let fns = crate::stdlib::all();
        let program = crate::compiler::compile(source, &fns).unwrap().program;

        let mut target = TargetValue {
            value: Value::Null,
            metadata: Value::Null,
            secrets: Secrets::new(),
        };
        let mut state = RuntimeState::default();
        let tz = TimeZone::default();
        let mut ctx = Context::new(&mut target, &mut state, &tz);

        let result = program.resolve(&mut ctx);
        assert_eq!(result, Ok(Value::from(2)));
    }

    #[test]
    fn break_is_not_wrapped_by_boolean_or() {
        let source = indoc! {r"
            count = 0
            for_each([1, 2, 3]) -> |_i, val| {
                count = count + 1
                if false || { if val == 2 { break } else { true } } {
                    res = val
                }
            }
            count
        "};

        let fns = crate::stdlib::all();
        let program = crate::compiler::compile(source, &fns).unwrap().program;

        let mut target = TargetValue {
            value: Value::Null,
            metadata: Value::Null,
            secrets: Secrets::new(),
        };
        let mut state = RuntimeState::default();
        let tz = TimeZone::default();
        let mut ctx = Context::new(&mut target, &mut state, &tz);

        let result = program.resolve(&mut ctx);
        assert_eq!(result, Ok(Value::from(2)));
    }
}