laser-wire 0.8.1

LaserData SDK over Apache Iggy: typed streaming, operational and lakehouse query, materialization destinations, key-value state, copy-on-write forks, and an optional agent runtime with the Agent Data Exchange Protocol (AGDX).
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
use crate::error::InvalidError;
use crate::limits::MAX_FILTER_STRING_BYTES;
use regex::{Regex, RegexBuilder};
use serde::{Deserialize, Serialize};

/// Compiled text predicates (regex and glob) one filter may hold. With the
/// program bound below, one compiled filter stays under 2 MiB of regex
/// programs, and the per-shard cache of compiled filters stays bounded with
/// it. Search time is linear in the value for each pattern, so a record costs
/// at most this many passes over its text fields.
pub const MAX_REGEX_PREDICATES: usize = 4;
/// Compiled program bound for one regex or glob, NFA and lazy DFA each. This
/// bounds memory. Time stays linear in the searched text because the engine
/// never backtracks.
const REGEX_SIZE_LIMIT: usize = 256 << 10;
const REGEX_NEST_LIMIT: u32 = 64;
const GLOB_ANY_RUN: char = '*';
const GLOB_ANY_ONE: char = '?';
const GLOB_ESCAPE: char = '\\';

/// A text match against one payload field or one header. The value must be
/// text: a missing value is unknown, and a value of another type is a type
/// mismatch, which follows the filter's mismatch policy.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TextPredicate {
    /// A payload field path, or a header key for [`FilterExpr::HeaderText`](crate::filter::FilterExpr::HeaderText).
    pub field: String,
    pub kind: TextMatch,
    pub pattern: String,
    /// Regex uses the engine's Unicode folding. Other kinds lowercase both sides.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub case_insensitive: bool,
}

/// How a [`TextPredicate`] matches, from cheapest to most expensive.
#[derive(
    Clone,
    Copy,
    Debug,
    PartialEq,
    Eq,
    Serialize,
    Deserialize,
    strum::Display,
    strum::EnumString,
    strum::VariantArray,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum TextMatch {
    /// The whole value equals the pattern.
    Equals,
    /// The value starts with the pattern.
    Prefix,
    /// The value ends with the pattern.
    Suffix,
    /// The pattern occurs anywhere in the value.
    Contains,
    /// The whole value matches a glob: `*` is any run of characters, `?` is
    /// one character, and `\` escapes the next character.
    Glob,
    /// The value contains a match of a regular expression, run by the
    /// server's Rust engine in time linear in the value. Lookaround,
    /// backreferences, and inline flags are refused. `\d`, `\w`, `\s`, and
    /// `\b` are Unicode-aware, and case-insensitive matching uses the
    /// engine's simple case folding, where the other kinds lowercase both
    /// sides. The server's verdict is the contract, and the Rust, Python, and
    /// TypeScript local evaluators follow the same rules.
    Regex,
}

/// A validated [`TextPredicate`] ready to run per record.
#[derive(Clone, Debug)]
pub struct TextMatcher {
    kind: TextMatch,
    /// The pattern as written, for explanations.
    source: String,
    case_insensitive: bool,
    program: Program,
}

/// What one evaluation runs: a plain comparison against the pattern, lowercased
/// when case-insensitive, or a compiled regex for the `glob` and `regex` kinds.
#[derive(Clone, Debug)]
enum Program {
    Plain(String),
    Compiled(Regex),
}

impl TextPredicate {
    /// Compiling is the validation, so a predicate is checked exactly once.
    pub fn validate(&self) -> Result<(), InvalidError> {
        TextMatcher::compile(self).map(|_| ())
    }
}

impl TextMatcher {
    pub fn compile(predicate: &TextPredicate) -> Result<Self, InvalidError> {
        if predicate.pattern.len() > MAX_FILTER_STRING_BYTES {
            return Err(InvalidError::new(format!(
                "a text pattern exceeds {MAX_FILTER_STRING_BYTES}B"
            )));
        }
        let program = match predicate.kind {
            TextMatch::Regex => Program::Compiled(compile_regex(
                &predicate.pattern,
                predicate.case_insensitive,
            )?),
            TextMatch::Glob => Program::Compiled(compile_glob(
                &predicate.pattern,
                predicate.case_insensitive,
            )?),
            _ if predicate.case_insensitive => Program::Plain(predicate.pattern.to_lowercase()),
            _ => Program::Plain(predicate.pattern.clone()),
        };
        Ok(Self {
            kind: predicate.kind,
            source: predicate.pattern.clone(),
            case_insensitive: predicate.case_insensitive,
            program,
        })
    }

    pub fn matches(&self, value: &str) -> bool {
        let pattern = match &self.program {
            Program::Compiled(regex) => {
                return if self.kind == TextMatch::Glob && self.case_insensitive {
                    regex.is_match(&value.to_lowercase())
                } else {
                    regex.is_match(value)
                };
            }
            Program::Plain(pattern) => pattern.as_str(),
        };
        let folded;
        let value = if self.case_insensitive {
            folded = value.to_lowercase();
            folded.as_str()
        } else {
            value
        };
        match self.kind {
            TextMatch::Equals => value == pattern,
            TextMatch::Prefix => value.starts_with(pattern),
            TextMatch::Suffix => value.ends_with(pattern),
            TextMatch::Contains => value.contains(pattern),
            TextMatch::Glob | TextMatch::Regex => false,
        }
    }

    pub fn kind(&self) -> TextMatch {
        self.kind
    }

    /// The pattern as written, with its case mode, for explanations.
    pub fn label(&self) -> String {
        if self.case_insensitive {
            format!("{:?} ignoring case", self.source)
        } else {
            format!("{:?}", self.source)
        }
    }
}

// A glob compiles to an anchored regex, so it runs in linear time like every
// other kind. Case-insensitive globs lowercase their literals, and `matches`
// lowercases the value, the same rule the plain kinds follow.
fn compile_glob(pattern: &str, case_insensitive: bool) -> Result<Regex, InvalidError> {
    let tokens = glob_tokens(pattern).ok_or_else(|| {
        InvalidError::new("a glob pattern cannot end with an unescaped backslash")
    })?;
    let mut expression = String::from("\\A(?:");
    for token in tokens {
        match token {
            GlobToken::AnyRun => expression.push_str(".*"),
            GlobToken::AnyOne => expression.push('.'),
            GlobToken::Literal(character) => {
                let literal = character.to_string();
                let literal = if case_insensitive {
                    literal.to_lowercase()
                } else {
                    literal
                };
                expression.push_str(&regex::escape(&literal));
            }
        }
    }
    expression.push_str(")\\z");
    RegexBuilder::new(&expression)
        .dot_matches_new_line(true)
        .size_limit(REGEX_SIZE_LIMIT)
        .dfa_size_limit(REGEX_SIZE_LIMIT)
        .nest_limit(REGEX_NEST_LIMIT)
        .build()
        .map_err(|error| InvalidError::new(format!("invalid glob: {error}")))
}

// Inline flags, lookaround, and backreferences have no shared meaning across
// the SDK regex engines, so they are refused before the engine sees them.
fn compile_regex(pattern: &str, case_insensitive: bool) -> Result<Regex, InvalidError> {
    if let Some(construct) = unportable_regex_construct(pattern) {
        return Err(InvalidError::new(format!(
            "regex {construct} is not supported, write the pattern without it"
        )));
    }
    RegexBuilder::new(pattern)
        .case_insensitive(case_insensitive)
        .size_limit(REGEX_SIZE_LIMIT)
        .dfa_size_limit(REGEX_SIZE_LIMIT)
        .nest_limit(REGEX_NEST_LIMIT)
        .build()
        .map_err(|error| InvalidError::new(format!("invalid regex: {error}")))
}

fn unportable_regex_construct(pattern: &str) -> Option<&'static str> {
    let mut characters = pattern.chars().peekable();
    let mut in_class = false;
    while let Some(character) = characters.next() {
        match character {
            '\\' => match characters.next() {
                Some('1'..='9') => return Some("backreferences"),
                Some('k') => return Some("named backreferences"),
                _ => {}
            },
            '[' => in_class = true,
            ']' => in_class = false,
            '(' if !in_class && characters.peek() == Some(&'?') => {
                characters.next();
                if characters.peek() != Some(&':') {
                    return Some("groups starting with (? other than (?:");
                }
            }
            _ => {}
        }
    }
    None
}

/// One glob element, after escapes are resolved.
#[derive(Clone, Copy, PartialEq, Eq)]
enum GlobToken {
    AnyRun,
    AnyOne,
    Literal(char),
}

fn glob_tokens(pattern: &str) -> Option<Vec<GlobToken>> {
    let mut tokens = Vec::with_capacity(pattern.len());
    let mut characters = pattern.chars();
    while let Some(character) = characters.next() {
        tokens.push(match character {
            GLOB_ANY_RUN => GlobToken::AnyRun,
            GLOB_ANY_ONE => GlobToken::AnyOne,
            GLOB_ESCAPE => GlobToken::Literal(characters.next()?),
            literal => GlobToken::Literal(literal),
        });
    }
    Some(tokens)
}

// The classic two-pointer match: on a mismatch after a `*`, the star absorbs
// one more character and matching resumes, which can repeat prefix comparisons on adversarial inputs.
#[cfg(test)]
fn glob_matches(pattern: &str, value: &str) -> bool {
    let Some(tokens) = glob_tokens(pattern) else {
        return false;
    };
    let text: Vec<char> = value.chars().collect();
    let (mut token, mut position) = (0, 0);
    let mut resume: Option<(usize, usize)> = None;
    while position < text.len() {
        match tokens.get(token) {
            Some(GlobToken::AnyRun) => {
                resume = Some((token, position));
                token += 1;
            }
            Some(GlobToken::AnyOne) => {
                token += 1;
                position += 1;
            }
            Some(GlobToken::Literal(literal)) if *literal == text[position] => {
                token += 1;
                position += 1;
            }
            _ => match resume {
                Some((star, absorbed)) => {
                    token = star + 1;
                    position = absorbed + 1;
                    resume = Some((star, absorbed + 1));
                }
                None => return false,
            },
        }
    }
    tokens[token..]
        .iter()
        .all(|token| *token == GlobToken::AnyRun)
}

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

    fn matcher(kind: TextMatch, pattern: &str, case_insensitive: bool) -> TextMatcher {
        TextMatcher::compile(&TextPredicate {
            field: "type".to_owned(),
            kind,
            pattern: pattern.to_owned(),
            case_insensitive,
        })
        .expect("the pattern compiles")
    }

    #[test]
    fn given_each_kind_when_matching_event_types_then_should_follow_its_rule() {
        let value = "metrics.cpu.v1.reported";
        assert!(matcher(TextMatch::Equals, value, false).matches(value));
        assert!(matcher(TextMatch::Prefix, "metrics.", false).matches(value));
        assert!(matcher(TextMatch::Suffix, ".reported", false).matches(value));
        assert!(matcher(TextMatch::Contains, ".v1.", false).matches(value));
        assert!(matcher(TextMatch::Glob, "metrics.*.v?.reported", false).matches(value));
        assert!(matcher(TextMatch::Regex, r"^metrics\.[a-z]+\.v[0-9]+\.", false).matches(value));
        assert!(!matcher(TextMatch::Suffix, ".deleted", false).matches(value));
        assert!(!matcher(TextMatch::Glob, "metrics.*", false).matches("storage.metrics.x"));
    }

    #[test]
    fn given_case_insensitive_matching_when_the_case_differs_then_should_still_match() {
        assert!(matcher(TextMatch::Equals, "Safe", true).matches("SAFE"));
        assert!(matcher(TextMatch::Contains, "CPU", true).matches("metrics.cpu.v1"));
        assert!(matcher(TextMatch::Glob, "METRICS.*", true).matches("metrics.x"));
        assert!(matcher(TextMatch::Regex, "^metrics", true).matches("METRICS.x"));
        assert!(!matcher(TextMatch::Equals, "Safe", false).matches("SAFE"));
    }

    #[test]
    fn given_globs_with_escapes_and_stars_when_matching_then_should_match_the_whole_value() {
        assert!(matcher(TextMatch::Glob, r"a\*b", false).matches("a*b"));
        assert!(!matcher(TextMatch::Glob, r"a\*b", false).matches("axb"));
        assert!(matcher(TextMatch::Glob, "*", false).matches(""));
        assert!(matcher(TextMatch::Glob, "a*b*c", false).matches("aXXbYYbZc"));
        assert!(!matcher(TextMatch::Glob, "a*b*c", false).matches("aXXbYY"));
        assert!(matcher(TextMatch::Glob, "?", false).matches("ł"));
    }

    #[test]
    fn given_glob_patterns_when_compiled_then_should_match_the_independent_original_oracle() {
        for pattern in [
            "", "*", "**", "?", "*?", "a*b*c", "*aaab", "a**b", r"a\*b", r"a\?b", r"a\\b", "*ł?",
            "*\n*", "[a]", "(?x)",
        ] {
            let compiled = matcher(TextMatch::Glob, pattern, false);
            for value in [
                "",
                "a",
                "ab",
                "ac",
                "aaab",
                "aaaaac",
                "a*b",
                "a?b",
                r"a\b",
                "aXXbYYbZc",
                "ł🙂",
                "aaał🙂",
                "a\nb",
                "[a]",
                "(?x)",
            ] {
                assert_eq!(
                    compiled.matches(value),
                    glob_matches(pattern, value),
                    "{pattern:?} {value:?}"
                );
            }
        }
        assert!(matcher(TextMatch::Glob, "İ?", true).matches("İx"));
        assert_eq!(matcher(TextMatch::Glob, "a*", false).label(), "\"a*\"");
    }

    #[test]
    fn given_a_long_repeated_prefix_when_matching_a_glob_then_should_reject_a_missing_suffix() {
        let pattern = format!("*{}b", "a".repeat(256));
        let value = "a".repeat(65_536);
        assert!(!matcher(TextMatch::Glob, &pattern, false).matches(&value));
    }

    #[test]
    fn given_unportable_or_broken_patterns_when_validated_then_should_refuse_them() {
        for (kind, pattern) in [
            (TextMatch::Regex, r"(a)\1"),
            (TextMatch::Regex, "(?=a)"),
            (TextMatch::Regex, "(?i)a"),
            (TextMatch::Regex, "(?P<name>a)"),
            (TextMatch::Regex, "("),
            (TextMatch::Glob, "a\\"),
        ] {
            let predicate = TextPredicate {
                field: "type".to_owned(),
                kind,
                pattern: pattern.to_owned(),
                case_insensitive: false,
            };
            assert!(predicate.validate().is_err(), "{pattern}");
        }
        assert!(matcher(TextMatch::Regex, "(?:a|b)[(?]", false).matches("b?"));
    }
}