vrl 0.32.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
use crate::path::OwnedValuePath;
use std::collections::BTreeMap;

use super::Collection;
use crate::value::Kind;

/// The type-state of "unknown" values in a collection.
///
/// That is, given a collection, it can have a set of "known" value types (e.g. we know the object
/// collection has a field `.foo` with a type `integer`), but also a singular "unknown" value type
/// (e.g. the array collection has an integer value at index 0, and is 3 values in size. We don't
/// know the exact values for indices 1 and 2, but we do know that it has to be the type defined by
/// `Unknown`).
///
/// "unknown" values can either be "undefined" or the "unknown" type.
/// For example, an array with an infinite unknown of "integer" doesn't imply that _every_
/// index contains an array. Rather, it says every index contains an "integer" or is "undefined".
#[derive(Debug, Clone, Eq, PartialEq, PartialOrd)]
pub struct Unknown(pub(super) Inner);

#[derive(Debug, Clone, Eq, PartialEq, PartialOrd)]
pub(super) enum Inner {
    Exact(Box<Kind>),

    /// The `Infinite` unknown kind stores non-recursive types, with the invariant that the same
    /// states set on this type also apply to its nested collection types.
    ///
    /// That is, if we have an infinite type with the `bytes` and `array` state set, then the
    /// assumption is that the array of this type also has the bytes and array state, and its array
    /// has the bytes and array state, ad infinitum.
    Infinite(Infinite),
}

impl Unknown {
    /// Returns a standard representation of an "unknown" type.
    #[must_use]
    pub(crate) fn canonicalize(&self) -> Self {
        self.to_kind().or_undefined().into()
    }

    /// Get the `any` state for `Unknown`.
    #[must_use]
    pub(crate) fn any() -> Self {
        Self::infinite(Infinite::any())
    }

    /// Get the `exact` state for `Unknown`.
    #[must_use]
    pub(crate) fn exact(kind: impl Into<Kind>) -> Self {
        Self(Inner::Exact(Box::new(kind.into())))
    }

    /// Get the `exact` state for `Unknown`.
    #[must_use]
    pub(super) fn infinite(infinite: impl Into<Infinite>) -> Self {
        Self(Inner::Infinite(infinite.into()))
    }

    /// Get the `json` state for `Unknown`.
    ///
    /// See [`Unknown::exact`] for details on the [`Option`] return value.
    #[must_use]
    pub(crate) fn json() -> Self {
        Self::infinite(Infinite::json())
    }

    /// Check if the state of `Unknown` is "any".
    #[must_use]
    pub const fn is_any(&self) -> bool {
        matches!(self.0, Inner::Infinite(infinite) if infinite.is_any())
    }

    /// Check if the state of `Unknown` is "any".
    #[must_use]
    pub const fn is_json(&self) -> bool {
        matches!(self.0, Inner::Infinite(infinite) if infinite.is_json())
    }

    /// Check if the state of `Unknown` is "exact".
    #[must_use]
    pub const fn is_exact(&self) -> bool {
        matches!(self.0, Inner::Exact(_))
    }

    /// Get the `Kind` stored in this `Unknown`.
    /// This represents the kind of any type not "known".
    /// It will always include "undefined", since unknown
    /// values are not guaranteed to exist.
    #[must_use]
    pub fn to_kind(&self) -> Kind {
        self.to_existing_kind().or_undefined()
    }

    /// Get the `Kind` stored in this `Unknown`.
    ///
    /// This represents the kind of any _EXISTING_ type not "known".
    /// This function assumes the type you are accessing actually exists.
    /// If it's an optional field, `to_kind` should be used instead.
    ///
    /// This will never have "undefined" as part of the type
    #[must_use]
    pub fn to_existing_kind(&self) -> Kind {
        let mut result = match &self.0 {
            Inner::Infinite(infinite) => (*infinite).into(),
            Inner::Exact(kind) => kind.as_ref().clone(),
        };
        result.remove_undefined();
        result
    }

    /// Check if `self` is a superset of `other`.
    ///
    /// Meaning, if `self` is `Any`, then it's always a superset of `other`, otherwise its
    /// accumulative types need to be a superset of `other`.
    pub(crate) fn is_superset(&self, other: &Self) -> Result<(), OwnedValuePath> {
        match (&self.0, &other.0) {
            (Inner::Infinite(infinite), _) if infinite.is_any() => Ok(()),
            (Inner::Infinite(infinite), Inner::Exact(rhs)) => {
                Kind::from(*infinite).is_superset(rhs)
            }
            (Inner::Exact(lhs), Inner::Exact(rhs)) => lhs
                .clone()
                .without_undefined()
                .is_superset(&rhs.clone().without_undefined()),
            (Inner::Exact(lhs), Inner::Infinite(..)) => {
                if lhs.is_any() {
                    Ok(())
                } else {
                    Err(OwnedValuePath::root())
                }
            }
            (Inner::Infinite(lhs), Inner::Infinite(rhs)) => {
                if lhs.is_superset(rhs) {
                    Ok(())
                } else {
                    Err(OwnedValuePath::root())
                }
            }
        }
    }

    /// Merge `other` into `self`, using the provided `Strategy`.
    ///
    /// If any of the two `Unknown`s is marked as "infinite", it will overwrite the finite variant.
    pub(crate) fn merge(&mut self, other: Self, overwrite: bool) {
        match (&mut self.0, other.0) {
            (Inner::Exact(lhs), Inner::Exact(rhs)) => lhs.merge_keep(*rhs, overwrite),
            (Inner::Infinite(lhs), Inner::Infinite(rhs)) => lhs.merge(rhs),
            (_, rhs @ Inner::Infinite(_)) => self.0 = rhs,
            (Inner::Infinite(_), _) => {}
        }
    }
}

impl From<Kind> for Unknown {
    fn from(kind: Kind) -> Self {
        (&kind).into()
    }
}

impl From<&Kind> for Unknown {
    fn from(kind: &Kind) -> Self {
        if kind.is_any() {
            return Self::any();
        }

        if kind.is_json() {
            return Self::json();
        }

        Self::exact(kind.clone())
    }
}

#[derive(Debug, Clone, Copy, Eq, PartialEq, PartialOrd)]
pub(super) struct Infinite {
    bytes: Option<()>,
    integer: Option<()>,
    float: Option<()>,
    boolean: Option<()>,
    timestamp: Option<()>,
    regex: Option<()>,
    null: Option<()>,
    array: Option<()>,
    object: Option<()>,
}

impl Infinite {
    const fn any() -> Self {
        Self {
            bytes: Some(()),
            integer: Some(()),
            float: Some(()),
            boolean: Some(()),
            timestamp: Some(()),
            regex: Some(()),
            null: Some(()),
            array: Some(()),
            object: Some(()),
        }
    }

    const fn json() -> Self {
        Self {
            bytes: Some(()),
            integer: Some(()),
            float: Some(()),
            boolean: Some(()),
            timestamp: None,
            regex: None,
            null: Some(()),
            array: Some(()),
            object: Some(()),
        }
    }

    #[must_use]
    pub const fn is_any(&self) -> bool {
        self.bytes.is_some()
            && self.integer.is_some()
            && self.float.is_some()
            && self.boolean.is_some()
            && self.timestamp.is_some()
            && self.regex.is_some()
            && self.null.is_some()
            && self.array.is_some()
            && self.object.is_some()
    }

    /// Returns `true` if the JSON type states are valid.
    #[must_use]
    pub const fn is_json(&self) -> bool {
        self.bytes.is_some()
            && self.integer.is_some()
            && self.float.is_some()
            && self.boolean.is_some()
            && self.timestamp.is_none()
            && self.regex.is_none()
            && self.null.is_some()
            && self.array.is_some()
            && self.object.is_some()
    }

    /// Check if `self` is a superset of `other`.
    ///
    /// Meaning, if `self` is `Any`, then it's always a superset of `other`, otherwise its
    /// accumulative types need to be a superset of `other`.
    pub(super) const fn is_superset(&self, other: &Self) -> bool {
        if let (None, Some(())) = (self.bytes, other.bytes) {
            return false;
        }

        if let (None, Some(())) = (self.integer, other.integer) {
            return false;
        }

        if let (None, Some(())) = (self.float, other.float) {
            return false;
        }

        if let (None, Some(())) = (self.boolean, other.boolean) {
            return false;
        }

        if let (None, Some(())) = (self.timestamp, other.timestamp) {
            return false;
        }

        if let (None, Some(())) = (self.regex, other.regex) {
            return false;
        }

        if let (None, Some(())) = (self.null, other.null) {
            return false;
        }

        if let (None, Some(())) = (self.array, other.array) {
            return false;
        }

        if let (None, Some(())) = (self.object, other.object) {
            return false;
        }

        true
    }

    /// Merge `other` into `self`.
    pub(super) fn merge(&mut self, other: Self) {
        self.bytes = self.bytes.or(other.bytes);
        self.integer = self.integer.or(other.integer);
        self.float = self.float.or(other.float);
        self.boolean = self.boolean.or(other.boolean);
        self.timestamp = self.timestamp.or(other.timestamp);
        self.regex = self.regex.or(other.regex);
        self.null = self.null.or(other.null);
        self.array = self.array.or(other.array);
        self.object = self.object.or(other.object);
    }
}

impl From<Infinite> for Kind {
    fn from(infinite: Infinite) -> Self {
        let mut kind = Self::never();

        if infinite.bytes.is_some() {
            kind.add_bytes();
        }

        if infinite.integer.is_some() {
            kind.add_integer();
        }

        if infinite.float.is_some() {
            kind.add_float();
        }

        if infinite.boolean.is_some() {
            kind.add_boolean();
        }

        if infinite.timestamp.is_some() {
            kind.add_timestamp();
        }

        if infinite.regex.is_some() {
            kind.add_regex();
        }

        if infinite.null.is_some() {
            kind.add_null();
        }

        if infinite.array.is_some() {
            kind.add_array(Collection::from(infinite));
        }

        if infinite.object.is_some() {
            kind.add_object(Collection::from(infinite));
        }

        kind
    }
}

impl<T: Ord> From<Infinite> for Collection<T> {
    fn from(infinite: Infinite) -> Self {
        Self {
            known: BTreeMap::default(),
            unknown: Unknown::infinite(infinite),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::*;

    #[test]
    #[allow(clippy::too_many_lines)]
    fn test_is_superset() {
        struct TestCase {
            this: Unknown,
            other: Unknown,
            want: bool,
        }

        for (title, TestCase { this, other, want }) in HashMap::from([
            (
                "any comparison",
                TestCase {
                    this: Unknown::any(),
                    other: Unknown::any(),
                    want: true,
                },
            ),
            (
                "exact/any mismatch",
                TestCase {
                    this: Unknown::json(),
                    other: Unknown::any(),
                    want: false,
                },
            ),
            (
                "any/exact match",
                TestCase {
                    this: Unknown::any(),
                    other: Unknown::json(),
                    want: true,
                },
            ),
            (
                "exact matching comparison",
                TestCase {
                    this: Unknown::json(),
                    other: Unknown::json(),
                    want: true,
                },
            ),
            (
                "exact mismatch comparison",
                TestCase {
                    this: Unknown::exact(Kind::bytes()),
                    other: Unknown::exact(Kind::integer()),
                    want: false,
                },
            ),
        ]) {
            assert_eq!(this.is_superset(&other).is_ok(), want, "{title}");
        }
    }
}