Skip to main content

vector_core/event/lua/
log.rs

1use mlua::prelude::*;
2
3use super::super::{EventMetadata, LogEvent, Value};
4
5impl IntoLua for LogEvent {
6    #![allow(clippy::wrong_self_convention)] // this trait is defined by mlua
7    fn into_lua(self, lua: &Lua) -> LuaResult<LuaValue> {
8        let (value, _metadata) = self.into_parts();
9        value.into_lua(lua)
10    }
11}
12
13impl FromLua for LogEvent {
14    fn from_lua(lua_value: LuaValue, lua: &Lua) -> LuaResult<Self> {
15        let value = Value::from_lua(lua_value, lua)?;
16        Ok(LogEvent::from_parts(value, EventMetadata::default()))
17    }
18}
19
20#[cfg(test)]
21mod test {
22    use super::*;
23    use vrl::event_path;
24
25    #[test]
26    fn into_lua() {
27        let mut log = LogEvent::default();
28        log.insert(event_path!("a"), 1);
29        log.insert(event_path!("nested", "field"), "2");
30        log.insert(event_path!("nested", "array", 0isize), "example value");
31        log.insert(event_path!("nested", "array", 2isize), "another value");
32
33        let assertions = vec![
34            "type(log) == 'table'",
35            "log.a == 1",
36            "type(log.nested) == 'table'",
37            "log.nested.field == '2'",
38            "#log.nested.array == 3",
39            "log.nested.array[1] == 'example value'",
40            "log.nested.array[2] == ''",
41            "log.nested.array[3] == 'another value'",
42        ];
43
44        let lua = Lua::new();
45        lua.globals().set("log", log.clone()).unwrap();
46        for assertion in assertions {
47            let result: bool = lua
48                .load(assertion)
49                .eval()
50                .unwrap_or_else(|_| panic!("Failed to verify assertion {assertion:?}"));
51            assert!(result, "{}", assertion);
52        }
53    }
54
55    #[test]
56    fn from_lua() {
57        let lua_event = r"
58        {
59            a = 1,
60            nested = {
61                field = '2',
62                array = {'example value', '', 'another value'}
63            }
64        }
65        ";
66
67        let event: LogEvent = Lua::new().load(lua_event).eval().unwrap();
68
69        assert_eq!(event["a"], Value::Integer(1));
70        assert_eq!(event["nested.field"], Value::Bytes("2".into()));
71        assert_eq!(
72            event["nested.array[0]"],
73            Value::Bytes("example value".into())
74        );
75        assert_eq!(event["nested.array[1]"], Value::Bytes("".into()));
76        assert_eq!(
77            event["nested.array[2]"],
78            Value::Bytes("another value".into())
79        );
80    }
81}