1use std::{path::PathBuf, sync::Arc, time::Duration};
2
3use serde_with::serde_as;
4use snafu::{ResultExt, Snafu};
5pub use vector_lib::event::lua;
6use vector_lib::{
7 codecs::MetricTagValues,
8 configurable::configurable_component,
9 transform::runtime_transform::{RuntimeTransform, Timer},
10};
11
12use crate::{
13 config::{self, CONFIG_PATHS, ComponentKey, DataType, Input, OutputId, TransformOutput},
14 event::{Event, lua::event::LuaEvent},
15 internal_events::{LuaBuildError, LuaGcTriggered},
16 schema,
17 schema::Definition,
18 transforms::Transform,
19};
20
21#[derive(Debug, Snafu)]
22pub enum BuildError {
23 #[snafu(display("Invalid \"search_dirs\": {}", source))]
24 InvalidSearchDirs { source: mlua::Error },
25 #[snafu(display("Cannot evaluate Lua code in \"source\": {}", source))]
26 InvalidSource { source: mlua::Error },
27
28 #[snafu(display("Cannot evaluate Lua code defining \"hooks.init\": {}", source))]
29 InvalidHooksInit { source: mlua::Error },
30 #[snafu(display("Cannot evaluate Lua code defining \"hooks.process\": {}", source))]
31 InvalidHooksProcess { source: mlua::Error },
32 #[snafu(display("Cannot evaluate Lua code defining \"hooks.shutdown\": {}", source))]
33 InvalidHooksShutdown { source: mlua::Error },
34 #[snafu(display("Cannot evaluate Lua code defining timer handler: {}", source))]
35 InvalidTimerHandler { source: mlua::Error },
36
37 #[snafu(display("Runtime error in \"hooks.init\" function: {}", source))]
38 RuntimeErrorHooksInit { source: mlua::Error },
39 #[snafu(display("Runtime error in \"hooks.process\" function: {}", source))]
40 RuntimeErrorHooksProcess { source: mlua::Error },
41 #[snafu(display("Runtime error in \"hooks.shutdown\" function: {}", source))]
42 RuntimeErrorHooksShutdown { source: mlua::Error },
43 #[snafu(display("Runtime error in timer handler: {}", source))]
44 RuntimeErrorTimerHandler { source: mlua::Error },
45
46 #[snafu(display("Cannot call GC in Lua runtime: {}", source))]
47 RuntimeErrorGc { source: mlua::Error },
48}
49
50#[configurable_component]
52#[derive(Clone, Debug)]
53#[serde(deny_unknown_fields)]
54pub struct LuaConfig {
55 #[configurable(metadata(
61 docs::examples = "function init()\n\tcount = 0\nend\n\nfunction process()\n\tcount = count + 1\nend\n\nfunction timer_handler(emit)\n\temit(make_counter(counter))\n\tcounter = 0\nend\n\nfunction shutdown(emit)\n\temit(make_counter(counter))\nend\n\nfunction make_counter(value)\n\treturn metric = {\n\t\tname = \"event_counter\",\n\t\tkind = \"incremental\",\n\t\ttimestamp = os.date(\"!*t\"),\n\t\tcounter = {\n\t\t\tvalue = value\n\t\t}\n \t}\nend",
62 docs::examples = "-- external file with hooks and timers defined\nrequire('custom_module')",
63 ))]
64 source: Option<String>,
65
66 #[serde(default = "default_config_paths")]
70 #[configurable(metadata(docs::examples = "/etc/vector/lua"))]
71 #[configurable(metadata(docs::human_name = "Search Directories"))]
72 search_dirs: Vec<PathBuf>,
73
74 #[configurable(derived)]
75 hooks: HooksConfig,
76
77 #[serde(default)]
79 timers: Vec<TimerConfig>,
80
81 #[serde(default)]
88 metric_tag_values: MetricTagValues,
89}
90
91fn default_config_paths() -> Vec<PathBuf> {
92 match CONFIG_PATHS.lock().ok() {
93 Some(config_paths) => config_paths
94 .clone()
95 .into_iter()
96 .map(|config_path| match config_path {
97 config::ConfigPath::File(mut path, _format) => {
98 path.pop();
99 path
100 }
101 config::ConfigPath::Dir(path) => path,
102 })
103 .collect(),
104 None => vec![],
105 }
106}
107
108#[configurable_component]
112#[derive(Clone, Debug)]
113#[serde(deny_unknown_fields)]
114struct HooksConfig {
115 #[configurable(metadata(
122 docs::examples = "function (emit)\n\t-- Custom Lua code here\nend",
123 docs::examples = "init",
124 ))]
125 init: Option<String>,
126
127 #[configurable(metadata(
135 docs::examples = "function (event, emit)\n\tevent.log.field = \"value\" -- set value of a field\n\tevent.log.another_field = nil -- remove field\n\tevent.log.first, event.log.second = nil, event.log.first -- rename field\n\t-- Very important! Emit the processed event.\n\temit(event)\nend",
136 docs::examples = "process",
137 ))]
138 process: String,
139
140 #[configurable(metadata(
147 docs::examples = "function (emit)\n\t-- Custom Lua code here\nend",
148 docs::examples = "shutdown",
149 ))]
150 shutdown: Option<String>,
151}
152
153#[serde_as]
155#[configurable_component]
156#[derive(Clone, Debug)]
157struct TimerConfig {
158 #[serde_as(as = "serde_with::DurationSeconds<u64>")]
160 #[configurable(metadata(docs::human_name = "Interval"))]
161 interval_seconds: Duration,
162
163 #[configurable(metadata(docs::examples = "timer_handler"))]
171 handler: String,
172}
173
174impl LuaConfig {
175 pub fn build(&self, key: ComponentKey) -> crate::Result<Transform> {
176 Lua::new(self, key).map(Transform::event_task)
177 }
178
179 pub fn input(&self) -> Input {
180 Input::new(DataType::Metric | DataType::Log)
181 }
182
183 pub fn outputs(
184 &self,
185 input_definitions: &[(OutputId, schema::Definition)],
186 ) -> Vec<TransformOutput> {
187 let namespaces = input_definitions
189 .iter()
190 .flat_map(|(_output, definition)| definition.log_namespaces().clone())
191 .collect();
192
193 let definition = input_definitions
194 .iter()
195 .map(|(output, _definition)| {
196 (
197 output.clone(),
198 Definition::default_for_namespace(&namespaces),
199 )
200 })
201 .collect();
202
203 vec![TransformOutput::new(
204 DataType::Metric | DataType::Log,
205 definition,
206 )]
207 }
208}
209
210const GC_INTERVAL: usize = 16;
217
218pub struct Lua {
219 lua: mlua::Lua,
220 invocations_after_gc: usize,
221 hook_init: Option<mlua::RegistryKey>,
222 hook_process: mlua::RegistryKey,
223 hook_shutdown: Option<mlua::RegistryKey>,
224 timers: Vec<(Timer, mlua::RegistryKey)>,
225 multi_value_tags: bool,
226 source_id: Arc<ComponentKey>,
227}
228
229fn make_registry_value(lua: &mlua::Lua, source: &str) -> mlua::Result<mlua::RegistryKey> {
231 lua.load(source)
232 .eval::<mlua::Function>()
233 .and_then(|f| lua.create_registry_value(f))
234}
235
236impl Lua {
237 pub fn new(config: &LuaConfig, key: ComponentKey) -> crate::Result<Self> {
238 let lua = unsafe {
241 mlua::Lua::unsafe_new_with(mlua::StdLib::ALL_SAFE, mlua::LuaOptions::default())
242 };
243
244 let additional_paths = config
245 .search_dirs
246 .iter()
247 .map(|d| format!("{}/?.lua", d.to_string_lossy()))
248 .collect::<Vec<_>>()
249 .join(";");
250
251 let mut timers = Vec::new();
252
253 if !additional_paths.is_empty() {
254 let package = lua.globals().get::<mlua::Table>("package")?;
255 let current_paths = package
256 .get::<String>("path")
257 .unwrap_or_else(|_| ";".to_string());
258 let paths = format!("{additional_paths};{current_paths}");
259 package.set("path", paths)?;
260 }
261
262 if let Some(source) = &config.source {
263 lua.load(source).eval::<()>().context(InvalidSourceSnafu)?;
264 }
265
266 let hook_init_code = config.hooks.init.as_ref();
267 let hook_init = hook_init_code
268 .map(|code| make_registry_value(&lua, code))
269 .transpose()
270 .context(InvalidHooksInitSnafu)?;
271
272 let hook_process =
273 make_registry_value(&lua, &config.hooks.process).context(InvalidHooksProcessSnafu)?;
274
275 let hook_shutdown_code = config.hooks.shutdown.as_ref();
276 let hook_shutdown = hook_shutdown_code
277 .map(|code| make_registry_value(&lua, code))
278 .transpose()
279 .context(InvalidHooksShutdownSnafu)?;
280
281 for (id, timer) in config.timers.iter().enumerate() {
282 let handler_key = lua
283 .load(&timer.handler)
284 .eval::<mlua::Function>()
285 .and_then(|f| lua.create_registry_value(f))
286 .context(InvalidTimerHandlerSnafu)?;
287
288 let timer = Timer {
289 id: id as u32,
290 interval: timer.interval_seconds,
291 };
292 timers.push((timer, handler_key));
293 }
294
295 let multi_value_tags = config.metric_tag_values == MetricTagValues::Full;
296
297 Ok(Self {
298 lua,
299 invocations_after_gc: 0,
300 timers,
301 hook_init,
302 hook_process,
303 hook_shutdown,
304 multi_value_tags,
305 source_id: Arc::new(key),
306 })
307 }
308
309 #[cfg(test)]
310 fn process(&mut self, event: Event, output: &mut Vec<Event>) -> Result<(), mlua::Error> {
311 let source_id = event.source_id().cloned();
312 let lua = &self.lua;
313 let result = lua.scope(|scope| {
314 let emit = scope.create_function_mut(|_, mut event: Event| {
315 if let Some(source_id) = &source_id {
316 event.set_source_id(Arc::clone(source_id));
317 }
318 output.push(event);
319 Ok(())
320 })?;
321
322 lua.registry_value::<mlua::Function>(&self.hook_process)?
323 .call((
324 LuaEvent {
325 event,
326 metric_multi_value_tags: self.multi_value_tags,
327 },
328 emit,
329 ))
330 });
331
332 self.attempt_gc();
333 result
334 }
335
336 #[cfg(test)]
337 fn process_single(&mut self, event: Event) -> Result<Option<Event>, mlua::Error> {
338 let mut out = Vec::new();
339 self.process(event, &mut out)?;
340 assert!(out.len() <= 1);
341 Ok(out.into_iter().next())
342 }
343
344 fn attempt_gc(&mut self) {
345 self.invocations_after_gc += 1;
346 if self.invocations_after_gc % GC_INTERVAL == 0 {
347 emit!(LuaGcTriggered {
348 used_memory: self.lua.used_memory()
349 });
350 _ = self
351 .lua
352 .gc_collect()
353 .context(RuntimeErrorGcSnafu)
354 .map_err(|error| error!(%error, rate_limit = 30));
355 self.invocations_after_gc = 0;
356 }
357 }
358}
359
360fn wrap_emit_fn<'scope, 'env, F: 'scope + FnMut(Event)>(
362 scope: &'scope mlua::Scope<'scope, 'env>,
363 mut emit_fn: F,
364 source_id: Arc<ComponentKey>,
365) -> mlua::Result<mlua::Function> {
366 scope.create_function_mut(move |_, mut event: Event| -> mlua::Result<()> {
367 event.set_source_id(Arc::clone(&source_id));
368 emit_fn(event);
369 Ok(())
370 })
371}
372
373impl RuntimeTransform for Lua {
374 fn hook_process<F>(&mut self, event: Event, emit_fn: F)
375 where
376 F: FnMut(Event),
377 {
378 let lua = &self.lua;
379 let source_id = Arc::clone(event.source_id().unwrap_or(&self.source_id));
380 _ = lua
381 .scope(|scope| -> mlua::Result<()> {
382 lua.registry_value::<mlua::Function>(&self.hook_process)?
383 .call((
384 LuaEvent {
385 event,
386 metric_multi_value_tags: self.multi_value_tags,
387 },
388 wrap_emit_fn(scope, emit_fn, source_id)?,
389 ))
390 })
391 .context(RuntimeErrorHooksProcessSnafu)
392 .map_err(|e| emit!(LuaBuildError { error: e }));
393
394 self.attempt_gc();
395 }
396
397 fn hook_init<F>(&mut self, emit_fn: F)
398 where
399 F: FnMut(Event),
400 {
401 let lua = &self.lua;
402 _ = lua
403 .scope(|scope| -> mlua::Result<()> {
404 match &self.hook_init {
405 Some(key) => lua
406 .registry_value::<mlua::Function>(key)?
407 .call(wrap_emit_fn(scope, emit_fn, Arc::clone(&self.source_id))?),
408 None => Ok(()),
409 }
410 })
411 .context(RuntimeErrorHooksInitSnafu)
412 .map_err(|error| error!(%error, rate_limit = 30));
413
414 self.attempt_gc();
415 }
416
417 fn hook_shutdown<F>(&mut self, emit_fn: F)
418 where
419 F: FnMut(Event),
420 {
421 let lua = &self.lua;
422 _ = lua
423 .scope(|scope| -> mlua::Result<()> {
424 match &self.hook_shutdown {
425 Some(key) => lua
426 .registry_value::<mlua::Function>(key)?
427 .call(wrap_emit_fn(scope, emit_fn, Arc::clone(&self.source_id))?),
428 None => Ok(()),
429 }
430 })
431 .context(RuntimeErrorHooksShutdownSnafu)
432 .map_err(|error| error!(%error, rate_limit = 30));
433
434 self.attempt_gc();
435 }
436
437 fn timer_handler<F>(&mut self, timer: Timer, emit_fn: F)
438 where
439 F: FnMut(Event),
440 {
441 let lua = &self.lua;
442 _ = lua
443 .scope(|scope| -> mlua::Result<()> {
444 let handler_key = &self.timers[timer.id as usize].1;
445 lua.registry_value::<mlua::Function>(handler_key)?
446 .call(wrap_emit_fn(scope, emit_fn, Arc::clone(&self.source_id))?)
447 })
448 .context(RuntimeErrorTimerHandlerSnafu)
449 .map_err(|error| error!(%error, rate_limit = 30));
450
451 self.attempt_gc();
452 }
453
454 fn timers(&self) -> Vec<Timer> {
455 self.timers.iter().map(|(timer, _)| *timer).collect()
456 }
457}
458
459#[cfg(test)]
460mod tests {
461 use std::{future::Future, sync::Arc};
462
463 use similar_asserts::assert_eq;
464 use tokio::sync::{
465 Mutex,
466 mpsc::{self, Receiver, Sender},
467 };
468 use tokio_stream::wrappers::ReceiverStream;
469
470 use super::*;
471 use crate::{
472 event::{
473 Event, LogEvent, Value,
474 metric::{Metric, MetricKind, MetricValue},
475 },
476 test_util,
477 test_util::{components::assert_transform_compliance, random_string},
478 transforms::test::create_topology,
479 };
480
481 fn format_error(error: &mlua::Error) -> String {
482 match error {
483 mlua::Error::CallbackError { traceback, cause } => {
484 format_error(cause) + "\n" + traceback
485 }
486 err => err.to_string(),
487 }
488 }
489
490 fn from_config(config: &str) -> crate::Result<Box<Lua>> {
491 Lua::new(&toml::from_str(config).unwrap(), "transform".into()).map(Box::new)
492 }
493
494 async fn run_transform<T: Future>(
495 config: &str,
496 func: impl FnOnce(Sender<Event>, Arc<Mutex<Receiver<Event>>>) -> T,
497 ) -> T::Output {
498 test_util::trace_init();
499 assert_transform_compliance(async move {
500 let config = super::super::LuaConfig::V2(toml::from_str(config).unwrap());
501 let (tx, rx) = mpsc::channel(1);
502 let (topology, out) = create_topology(ReceiverStream::new(rx), config).await;
503
504 let out = Arc::new(tokio::sync::Mutex::new(out));
505
506 let result = func(tx, Arc::clone(&out)).await;
507
508 topology.stop().await;
509 assert_eq!(out.lock().await.recv().await, None);
510
511 result
512 })
513 .await
514 }
515
516 async fn next_event(out: &Arc<Mutex<Receiver<Event>>>, source: &str) -> Event {
517 let event = out
518 .lock()
519 .await
520 .recv()
521 .await
522 .expect("Event was not received");
523 assert_eq!(
524 event.source_id(),
525 Some(&Arc::new(ComponentKey::from(source)))
526 );
527 event
528 }
529
530 #[tokio::test]
531 async fn lua_runs_init_hook() {
532 let line1 = random_string(9);
533 run_transform(
534 &format!(
535 r#"
536 version = "2"
537 hooks.init = """function (emit)
538 event = {{log={{message="{line1}"}}}}
539 emit(event)
540 end
541 """
542 hooks.process = """function (event, emit)
543 emit(event)
544 end
545 """
546 "#
547 ),
548 |tx, out| async move {
549 let line2 = random_string(9);
550 tx.send(Event::Log(LogEvent::from(line2.as_str())))
551 .await
552 .unwrap();
553 drop(tx);
554 assert_eq!(
555 next_event(&out, "transform").await.as_log()["message"],
556 line1.into()
557 );
558 assert_eq!(
559 next_event(&out, "in").await.as_log()["message"],
560 line2.into(),
561 );
562 },
563 )
564 .await;
565 }
566
567 #[tokio::test]
568 async fn lua_add_field() {
569 run_transform(
570 r#"
571 version = "2"
572 hooks.process = """function (event, emit)
573 event["log"]["hello"] = "goodbye"
574 emit(event)
575 end
576 """
577 "#,
578 |tx, out| async move {
579 let event = Event::Log(LogEvent::from("program me"));
580 tx.send(event).await.unwrap();
581
582 assert_eq!(
583 next_event(&out, "in").await.as_log()["hello"],
584 "goodbye".into()
585 );
586 },
587 )
588 .await;
589 }
590
591 #[tokio::test]
592 async fn lua_read_field() {
593 run_transform(
594 r#"
595 version = "2"
596 hooks.process = """function (event, emit)
597 _, _, name = string.find(event.log.message, "Hello, my name is (%a+).")
598 event.log.name = name
599 emit(event)
600 end
601 """
602 "#,
603 |tx, out| async move {
604 let event = Event::Log(LogEvent::from("Hello, my name is Bob."));
605 tx.send(event).await.unwrap();
606
607 assert_eq!(next_event(&out, "in").await.as_log()["name"], "Bob".into());
608 },
609 )
610 .await;
611 }
612
613 #[tokio::test]
614 async fn lua_remove_field() {
615 run_transform(
616 r#"
617 version = "2"
618 hooks.process = """function (event, emit)
619 event.log.name = nil
620 emit(event)
621 end
622 """
623 "#,
624 |tx, out| async move {
625 let mut event = LogEvent::default();
626 event.insert("name", "Bob");
627
628 tx.send(event.into()).await.unwrap();
629
630 assert_eq!(next_event(&out, "in").await.as_log().get("name"), None);
631 },
632 )
633 .await;
634 }
635
636 #[tokio::test]
637 async fn lua_drop_event() {
638 run_transform(
639 r#"
640 version = "2"
641 hooks.process = """function (event, emit)
642 -- emit nothing
643 end
644 """
645 "#,
646 |tx, _out| async move {
647 let event = LogEvent::default().into();
648 tx.send(event).await.unwrap();
649
650 },
652 )
653 .await;
654 }
655
656 #[tokio::test]
657 async fn lua_duplicate_event() {
658 run_transform(
659 r#"
660 version = "2"
661 hooks.process = """function (event, emit)
662 emit(event)
663 emit(event)
664 end
665 """
666 "#,
667 |tx, out| async move {
668 let mut event = LogEvent::default();
669 event.insert("host", "127.0.0.1");
670 tx.send(event.into()).await.unwrap();
671
672 assert!(out.lock().await.recv().await.is_some());
673 assert!(out.lock().await.recv().await.is_some());
674 },
675 )
676 .await;
677 }
678
679 #[tokio::test]
680 async fn lua_read_empty_field() {
681 run_transform(
682 r#"
683 version = "2"
684 hooks.process = """function (event, emit)
685 if event["log"]["non-existant"] == nil then
686 event["log"]["result"] = "empty"
687 else
688 event["log"]["result"] = "found"
689 end
690 emit(event)
691 end
692 """
693 "#,
694 |tx, out| async move {
695 let event = LogEvent::default();
696 tx.send(event.into()).await.unwrap();
697
698 assert_eq!(
699 next_event(&out, "in").await.as_log()["result"],
700 "empty".into()
701 );
702 },
703 )
704 .await;
705 }
706
707 #[tokio::test]
708 async fn lua_integer_value() {
709 run_transform(
710 r#"
711 version = "2"
712 hooks.process = """function (event, emit)
713 event["log"]["number"] = 3
714 emit(event)
715 end
716 """
717 "#,
718 |tx, out| async move {
719 let event = LogEvent::default();
720 tx.send(event.into()).await.unwrap();
721
722 assert_eq!(
723 next_event(&out, "in").await.as_log()["number"],
724 Value::Integer(3)
725 );
726 },
727 )
728 .await;
729 }
730
731 #[tokio::test]
732 async fn lua_numeric_value() {
733 run_transform(
734 r#"
735 version = "2"
736 hooks.process = """function (event, emit)
737 event["log"]["number"] = 3.14159
738 emit(event)
739 end
740 """
741 "#,
742 |tx, out| async move {
743 let event = LogEvent::default();
744 tx.send(event.into()).await.unwrap();
745
746 assert_eq!(
747 next_event(&out, "in").await.as_log()["number"],
748 Value::from(3.14159)
749 );
750 },
751 )
752 .await;
753 }
754
755 #[tokio::test]
756 async fn lua_boolean_value() {
757 run_transform(
758 r#"
759 version = "2"
760 hooks.process = """function (event, emit)
761 event["log"]["bool"] = true
762 emit(event)
763 end
764 """
765 "#,
766 |tx, out| async move {
767 let event = LogEvent::default();
768 tx.send(event.into()).await.unwrap();
769
770 assert_eq!(
771 next_event(&out, "in").await.as_log()["bool"],
772 Value::Boolean(true)
773 );
774 },
775 )
776 .await;
777 }
778
779 #[tokio::test]
780 async fn lua_non_coercible_value() {
781 run_transform(
782 r#"
783 version = "2"
784 hooks.process = """function (event, emit)
785 event["log"]["junk"] = nil
786 emit(event)
787 end
788 """
789 "#,
790 |tx, out| async move {
791 let event = LogEvent::default();
792 tx.send(event.into()).await.unwrap();
793
794 assert_eq!(next_event(&out, "in").await.as_log().get("junk"), None);
795 },
796 )
797 .await;
798 }
799
800 #[tokio::test]
801 async fn lua_non_string_key_write() -> crate::Result<()> {
802 let mut transform = from_config(
803 r#"
804 hooks.process = """function (event, emit)
805 event["log"][false] = "hello"
806 emit(event)
807 end
808 """
809 "#,
810 )
811 .unwrap();
812
813 let err = transform
814 .process_single(LogEvent::default().into())
815 .unwrap_err();
816 let err = format_error(&err);
817 assert!(
818 err.contains("error converting Lua boolean to String"),
819 "{}",
820 err
821 );
822 Ok(())
823 }
824
825 #[tokio::test]
826 async fn lua_non_string_key_read() {
827 run_transform(
828 r#"
829 version = "2"
830 hooks.process = """function (event, emit)
831 event.log.result = event.log[false]
832 emit(event)
833 end
834 """
835 "#,
836 |tx, out| async move {
837 let event = LogEvent::default();
838 tx.send(event.into()).await.unwrap();
839
840 assert_eq!(next_event(&out, "in").await.as_log().get("result"), None);
841 },
842 )
843 .await;
844 }
845
846 #[tokio::test]
847 async fn lua_script_error() -> crate::Result<()> {
848 let mut transform = from_config(
849 r#"
850 hooks.process = """function (event, emit)
851 error("this is an error")
852 end
853 """
854 "#,
855 )
856 .unwrap();
857
858 let err = transform
859 .process_single(LogEvent::default().into())
860 .unwrap_err();
861 let err = format_error(&err);
862 assert!(err.contains("this is an error"), "{}", err);
863 Ok(())
864 }
865
866 #[tokio::test]
867 async fn lua_syntax_error() -> crate::Result<()> {
868 let err = from_config(
869 r#"
870 hooks.process = """function (event, emit)
871 1234 = sadf <>&*!#@
872 end
873 """
874 "#,
875 )
876 .map(|_| ())
877 .unwrap_err()
878 .to_string();
879
880 assert!(err.contains("syntax error:"), "{}", err);
881 Ok(())
882 }
883
884 #[tokio::test]
885 async fn lua_load_file() {
886 use std::{fs::File, io::Write};
887
888 let dir = tempfile::tempdir().unwrap();
889 let mut file = File::create(dir.path().join("script2.lua")).unwrap();
890 write!(
891 &mut file,
892 r#"
893 local M = {{}}
894
895 local function modify(event2)
896 event2["log"]["new field"] = "new value"
897 end
898 M.modify = modify
899
900 return M
901 "#
902 )
903 .unwrap();
904
905 run_transform(
906 &format!(
907 r#"
908 version = "2"
909 hooks.process = """function (event, emit)
910 local script2 = require("script2")
911 script2.modify(event)
912 emit(event)
913 end
914 """
915 search_dirs = [{:?}]
916 "#,
917 dir.path().as_os_str() ),
919 |tx, out| async move {
920 let event = LogEvent::default();
921 tx.send(event.into()).await.unwrap();
922
923 assert_eq!(
924 next_event(&out, "in").await.as_log()["\"new field\""],
925 "new value".into()
926 );
927 },
928 )
929 .await;
930 }
931
932 #[tokio::test]
933 async fn lua_pairs() {
934 run_transform(
935 r#"
936 version = "2"
937 hooks.process = """function (event, emit)
938 for k,v in pairs(event.log) do
939 event.log[k] = k .. v
940 end
941 emit(event)
942 end
943 """
944 "#,
945 |tx, out| async move {
946 let mut event = LogEvent::default();
947 event.insert("name", "Bob");
948 event.insert("friend", "Alice");
949 tx.send(event.into()).await.unwrap();
950
951 let output = next_event(&out, "in").await;
952
953 assert_eq!(output.as_log()["name"], "nameBob".into());
954 assert_eq!(output.as_log()["friend"], "friendAlice".into());
955 },
956 )
957 .await;
958 }
959
960 #[tokio::test]
961 async fn lua_metric() {
962 run_transform(
963 r#"
964 version = "2"
965 hooks.process = """function (event, emit)
966 event.metric.counter.value = event.metric.counter.value + 1
967 emit(event)
968 end
969 """
970 "#,
971 |tx, out| async move {
972 let metric = Metric::new(
973 "example counter",
974 MetricKind::Absolute,
975 MetricValue::Counter { value: 1.0 },
976 );
977
978 let mut expected = metric
979 .clone()
980 .with_value(MetricValue::Counter { value: 2.0 });
981 let metadata = expected.metadata_mut();
982 metadata.set_upstream_id(Arc::new(OutputId::from("transform")));
983 metadata.set_source_id(Arc::new(ComponentKey::from("in")));
984
985 tx.send(metric.into()).await.unwrap();
986
987 assert_eq!(next_event(&out, "in").await.as_metric(), &expected);
988 },
989 )
990 .await;
991 }
992
993 #[tokio::test]
994 async fn lua_multiple_events() {
995 run_transform(
996 r#"
997 version = "2"
998 hooks.process = """function (event, emit)
999 event["log"]["hello"] = "goodbye"
1000 emit(event)
1001 end
1002 """
1003 "#,
1004 |tx, out| async move {
1005 let n: usize = 10;
1006 let events = (0..n).map(|i| Event::Log(LogEvent::from(format!("program me {i}"))));
1007 for event in events {
1008 tx.send(event).await.unwrap();
1009 assert!(out.lock().await.recv().await.is_some());
1010 }
1011 },
1012 )
1013 .await;
1014 }
1015}