config/
lib.rs

1use crate::epoch::{get_current_epoch, ConfigEpoch};
2pub use crate::field_names::struct_field_names;
3use crate::pool::{pool_get, pool_put};
4pub use crate::pool::{set_gc_on_put, set_max_age, set_max_spare, set_max_use};
5use anyhow::Context;
6use kumo_prometheus::declare_metric;
7use kumo_prometheus::prometheus::HistogramTimer;
8use mlua::{
9    FromLua, FromLuaMulti, IntoLua, IntoLuaMulti, Lua, LuaSerdeExt, MetaMethod, RegistryKey, Table,
10    UserData, UserDataMethods, Value,
11};
12use parking_lot::FairMutex as Mutex;
13pub use pastey as paste;
14use serde::Serialize;
15use std::borrow::Cow;
16use std::collections::HashSet;
17use std::path::PathBuf;
18use std::sync::atomic::{AtomicBool, Ordering};
19use std::sync::{LazyLock, Once};
20use std::time::Instant;
21
22pub mod epoch;
23mod field_names;
24mod pool;
25
26static POLICY_FILE: LazyLock<Mutex<Option<PathBuf>>> = LazyLock::new(|| Mutex::new(None));
27static FUNCS: LazyLock<Mutex<Vec<RegisterFunc>>> = LazyLock::new(|| Mutex::new(vec![]));
28
29declare_metric! {
30/// how many times the policy lua script has been loaded into a new context
31static LUA_LOAD_COUNT: IntCounter("lua_load_count");
32}
33
34declare_metric! {
35/// the number of lua contexts currently alive
36static LUA_COUNT: IntGauge("lua_count");
37}
38
39static CALLBACK_ALLOWS_MULTIPLE: LazyLock<Mutex<HashSet<String>>> =
40    LazyLock::new(|| Mutex::new(HashSet::new()));
41
42pub static VALIDATE_ONLY: AtomicBool = AtomicBool::new(false);
43pub static VALIDATION_FAILED: AtomicBool = AtomicBool::new(false);
44
45declare_metric! {
46/// how long a given lua event callback took
47static LATENCY_HIST: HistogramVec(
48        "lua_event_latency",
49        &["event"]);
50}
51
52declare_metric! {
53/// Incremented each time we start to call a lua event callback. Use lua_event_latency_count to track completed events
54static EVENT_STARTED_COUNT: CounterVec(
55        "lua_event_started",
56        &["event"]
57    );
58}
59
60pub type RegisterFunc = fn(&Lua) -> anyhow::Result<()>;
61
62fn latency_timer(label: &str) -> HistogramTimer {
63    EVENT_STARTED_COUNT
64        .get_metric_with_label_values(&[label])
65        .expect("to get counter")
66        .inc();
67    LATENCY_HIST
68        .get_metric_with_label_values(&[label])
69        .expect("to get histo")
70        .start_timer()
71}
72
73#[derive(Debug)]
74struct LuaConfigInner {
75    lua: Lua,
76    created: Instant,
77    use_count: usize,
78    epoch: ConfigEpoch,
79}
80
81impl Drop for LuaConfigInner {
82    fn drop(&mut self) {
83        LUA_COUNT.dec();
84    }
85}
86
87#[derive(Debug)]
88pub struct LuaConfig {
89    inner: Option<LuaConfigInner>,
90}
91
92pub async fn set_policy_path(path: PathBuf) -> anyhow::Result<()> {
93    POLICY_FILE.lock().replace(path);
94    let config = load_config().await?;
95    config.put();
96    Ok(())
97}
98
99fn get_policy_path() -> Option<PathBuf> {
100    POLICY_FILE.lock().clone()
101}
102
103fn get_funcs() -> Vec<RegisterFunc> {
104    FUNCS.lock().clone()
105}
106pub fn is_validating() -> bool {
107    VALIDATE_ONLY.load(Ordering::Relaxed)
108}
109
110tokio::task_local! {
111    static POLICY_LOADING: ();
112}
113
114/// Returns true when the current task is inside the evaluation of the
115/// top-level policy chunk performed by `load_config`.
116pub fn is_policy_loading() -> bool {
117    POLICY_LOADING.try_with(|_| ()).is_ok()
118}
119
120pub fn validation_failed() -> bool {
121    VALIDATION_FAILED.load(Ordering::Relaxed)
122}
123
124pub fn set_validation_failed() {
125    VALIDATION_FAILED.store(true, Ordering::Relaxed)
126}
127
128pub async fn load_config() -> anyhow::Result<LuaConfig> {
129    if let Some(pool) = pool_get() {
130        return Ok(pool);
131    }
132
133    LUA_LOAD_COUNT.inc();
134    let lua = Lua::new();
135    let created = Instant::now();
136    let epoch = get_current_epoch();
137
138    {
139        let globals = lua.globals();
140
141        if is_validating() {
142            globals.set("_VALIDATING_CONFIG", true)?;
143        }
144
145        let package: Table = globals.get("package")?;
146        let package_path: String = package.get("path")?;
147        let mut path_array: Vec<String> = package_path.split(";").map(|s| s.to_owned()).collect();
148
149        fn prefix_path(array: &mut Vec<String>, path: &str) {
150            array.insert(0, format!("{}/?.lua", path));
151            array.insert(1, format!("{}/?/init.lua", path));
152        }
153
154        prefix_path(&mut path_array, "/opt/kumomta/etc/policy");
155        prefix_path(&mut path_array, "/opt/kumomta/share");
156
157        #[cfg(debug_assertions)]
158        prefix_path(&mut path_array, "assets");
159
160        package.set("path", path_array.join(";"))?;
161    }
162
163    register_declared_events();
164
165    for func in get_funcs() {
166        (func)(&lua)?;
167    }
168
169    if let Some(policy) = get_policy_path() {
170        let code = tokio::fs::read_to_string(&policy)
171            .await
172            .with_context(|| format!("reading policy file {policy:?}"))?;
173
174        let func = {
175            let chunk = lua.load(&code);
176            let chunk = chunk.set_name(policy.to_string_lossy());
177            chunk.into_function()?
178        };
179
180        let _timer = latency_timer("context-creation");
181        POLICY_LOADING.scope((), func.call_async::<()>(())).await?;
182    }
183    LUA_COUNT.inc();
184
185    Ok(LuaConfig {
186        inner: Some(LuaConfigInner {
187            lua,
188            created,
189            use_count: 1,
190            epoch,
191        }),
192    })
193}
194
195pub fn register(func: RegisterFunc) {
196    FUNCS.lock().push(func);
197}
198
199impl LuaConfig {
200    fn set_current_event(&mut self, name: &str) -> mlua::Result<()> {
201        self.inner
202            .as_mut()
203            .unwrap()
204            .lua
205            .globals()
206            .set("_KUMO_CURRENT_EVENT", name.to_string())
207    }
208
209    /// Returns the Lua context managed by this config, or an error if the
210    /// context is not currently held by this LuaConfig.
211    pub fn lua(&self) -> anyhow::Result<&Lua> {
212        Ok(&self
213            .inner
214            .as_ref()
215            .context("LuaConfig is missing the inner Lua context")?
216            .lua)
217    }
218
219    /// Convert an array of args into a MultiValue that can be passed
220    /// to a callback signature
221    pub fn convert_args_to_multi<A: Serialize>(
222        &self,
223        args: &[A],
224    ) -> anyhow::Result<mlua::MultiValue> {
225        let lua = self.inner.as_ref().unwrap();
226        let mut arg_vec = vec![];
227        for a in args.iter() {
228            arg_vec.push(lua.lua.to_value(a)?);
229        }
230        Ok(mlua::MultiValue::from_vec(arg_vec))
231    }
232
233    /// Intended to be used together with kumo.spawn_task
234    pub async fn convert_args_and_call_callback<A: Serialize>(
235        &mut self,
236        sig: &CallbackSignature<Value, ()>,
237        args: A,
238    ) -> anyhow::Result<()> {
239        let lua = self.inner.as_mut().unwrap();
240        let args = lua.lua.to_value(&args)?;
241
242        let name = sig.name();
243        let decorated_name = sig.decorated_name();
244
245        match lua
246            .lua
247            .named_registry_value::<mlua::Function>(&decorated_name)
248        {
249            Ok(func) => {
250                let _timer = latency_timer(name);
251                Ok(func.call_async(args).await?)
252            }
253            _ => anyhow::bail!("{name} has not been registered"),
254        }
255    }
256
257    /// Explicitly put the config object back into its containing pool.
258    /// Ideally we'd do this automatically when the object is dropped,
259    /// but lua's garbage collection makes this problematic:
260    /// if a future whose graph contains an async lua call within
261    /// this config object is cancelled (eg: simply stopped without
262    /// calling it again), and the config object is not explicitly garbage
263    /// collected, any futures and data owned by any dependencies of
264    /// the cancelled future remain alive until the next gc run,
265    /// which can cause things like async locks and semaphores to
266    /// have a lifetime extended by the maximum age of the lua context.
267    ///
268    /// The combat this, consumers of LuaConfig should explicitly
269    /// call `config.put()` after successfully using the config
270    /// object.
271    ///
272    /// Or framing it another way: consumers must not call `config.put()`
273    /// if a transitive dep might have been cancelled.
274    pub fn put(mut self) {
275        if let Some(inner) = self.inner.take() {
276            pool_put(inner);
277        }
278    }
279
280    pub async fn call_callback<'a, A: IntoLuaMulti + Clone, R: FromLuaMulti>(
281        &mut self,
282        sig: &'a CallbackSignature<A, R>,
283        args: A,
284    ) -> anyhow::Result<CallbackDisposition<'a, R>> {
285        let name = sig.name();
286        self.set_current_event(name)?;
287        let lua = self.inner.as_mut().unwrap();
288        sig.call(&lua.lua, args).await
289    }
290
291    pub async fn async_call_callback<A: IntoLuaMulti + Clone, R: FromLuaMulti + Default>(
292        &mut self,
293        sig: &CallbackSignature<A, R>,
294        args: A,
295    ) -> anyhow::Result<R> {
296        let name = sig.name();
297        self.set_current_event(name)?;
298        let lua = self.inner.as_mut().unwrap();
299        Ok(sig.call(&lua.lua, args).await?.or_default())
300    }
301
302    pub async fn async_call_callback_non_default<A: IntoLuaMulti + Clone, R: FromLuaMulti>(
303        &mut self,
304        sig: &CallbackSignature<A, R>,
305        args: A,
306    ) -> anyhow::Result<R> {
307        let name = sig.name();
308        self.set_current_event(name)?;
309        let lua = self.inner.as_mut().unwrap();
310        sig.call(&lua.lua, args).await?.require_value()
311    }
312
313    pub async fn async_call_callback_non_default_opt<A: IntoLuaMulti + Clone, R: FromLua>(
314        &mut self,
315        sig: &CallbackSignature<A, Option<R>>,
316        args: A,
317    ) -> anyhow::Result<Option<R>> {
318        let name = sig.name();
319        self.set_current_event(name)?;
320        let lua = self.inner.as_mut().unwrap();
321        let result = sig.call(&lua.lua, args).await?;
322        match result.result {
323            None => Ok(None),
324            Some(result) => Ok(result),
325        }
326    }
327
328    pub fn remove_registry_value(&mut self, value: RegistryKey) -> anyhow::Result<()> {
329        Ok(self
330            .inner
331            .as_mut()
332            .unwrap()
333            .lua
334            .remove_registry_value(value)?)
335    }
336
337    /// Call a constructor registered via `on`. Returns a registry key that can be
338    /// used to reference the returned value again later on this same Lua instance
339    pub async fn async_call_ctor<A: IntoLuaMulti + Clone>(
340        &mut self,
341        sig: &CallbackSignature<A, Value>,
342        args: A,
343    ) -> anyhow::Result<RegistryKey> {
344        let name = sig.name();
345        anyhow::ensure!(
346            !sig.allow_multiple(),
347            "ctor event signature for {name} is defined as allow_multiple, which is not supported"
348        );
349
350        let decorated_name = sig.decorated_name();
351        self.set_current_event(name)?;
352
353        let inner = self.inner.as_mut().unwrap();
354
355        let func = inner
356            .lua
357            .named_registry_value::<mlua::Function>(&decorated_name)?;
358
359        let _timer = latency_timer(name);
360        let value: Value = func.call_async(args.clone()).await?;
361        drop(func);
362
363        Ok(inner.lua.create_registry_value(value)?)
364    }
365
366    /// Operate on an object/value that was previously constructed via
367    /// async_call_ctor.
368    pub async fn with_registry_value<F, R, FUT>(
369        &mut self,
370        value: &RegistryKey,
371        func: F,
372    ) -> anyhow::Result<R>
373    where
374        R: FromLuaMulti,
375        F: FnOnce(Value) -> anyhow::Result<FUT>,
376        FUT: std::future::Future<Output = anyhow::Result<R>>,
377    {
378        let inner = self.inner.as_mut().unwrap();
379        let value = inner.lua.registry_value(value)?;
380        let future = (func)(value)?;
381        future.await
382    }
383}
384
385pub fn get_or_create_module(lua: &Lua, name: &str) -> anyhow::Result<mlua::Table> {
386    let globals = lua.globals();
387    let package: Table = globals.get("package")?;
388    let loaded: Table = package.get("loaded")?;
389
390    let module = loaded.get(name)?;
391    match module {
392        Value::Nil => {
393            let module = lua.create_table()?;
394            loaded.set(name, module.clone())?;
395            Ok(module)
396        }
397        Value::Table(table) => Ok(table),
398        wat => anyhow::bail!(
399            "cannot register module {} as package.loaded.{} is already set to a value of type {}",
400            name,
401            name,
402            wat.type_name()
403        ),
404    }
405}
406
407/// Given a name path like `foo` or `foo.bar.baz`, sets up the module
408/// registry hierarchy to instantiate that path.
409/// Returns the leaf node of that path to allow the caller to
410/// register/assign functions etc. into it
411pub fn get_or_create_sub_module(lua: &Lua, name_path: &str) -> anyhow::Result<mlua::Table> {
412    let mut parent = get_or_create_module(lua, "kumo")?;
413    let mut path_so_far = String::new();
414
415    for name in name_path.split('.') {
416        if !path_so_far.is_empty() {
417            path_so_far.push('.');
418        }
419        path_so_far.push_str(name);
420
421        let sub = parent.get(name)?;
422        match sub {
423            Value::Nil => {
424                let sub = lua.create_table()?;
425                parent.set(name, sub.clone())?;
426                parent = sub;
427            }
428            Value::Table(sub) => {
429                parent = sub;
430            }
431            wat => anyhow::bail!(
432                "cannot register module kumo.{path_so_far} as it is already set to a value of type {}",
433                wat.type_name()
434            ),
435        }
436    }
437
438    Ok(parent)
439}
440
441/// Helper for mapping back to lua errors
442pub fn any_err<E: std::fmt::Display>(err: E) -> mlua::Error {
443    mlua::Error::external(format!("{err:#}"))
444}
445
446/// Provides implementations of __pairs, __index and __len metamethods
447/// for a type that is Serialize and UserData.
448/// Neither implementation is considered to be ideal, as we must
449/// first serialize the value into a json Value which is then either
450/// iterated over, or indexed to produce the appropriate result for
451/// the metamethod.
452pub fn impl_pairs_and_index<T, M>(methods: &mut M)
453where
454    T: UserData + Serialize,
455    M: UserDataMethods<T>,
456{
457    methods.add_meta_method(MetaMethod::Pairs, move |lua, this, _: ()| {
458        let Ok(serde_json::Value::Object(map)) = serde_json::to_value(this).map_err(any_err) else {
459            return Err(mlua::Error::external("must serialize to Map"));
460        };
461
462        let mut value_iter = map.into_iter();
463
464        let iter_func = lua.create_function_mut(
465            move |lua, (_state, _control): (Value, Value)| match value_iter.next() {
466                Some((key, value)) => {
467                    let key = lua.to_value(&key)?;
468                    let value = lua.to_value(&value)?;
469                    Ok((key, value))
470                }
471                None => Ok((Value::Nil, Value::Nil)),
472            },
473        )?;
474
475        Ok((Value::Function(iter_func), Value::Nil, Value::Nil))
476    });
477
478    methods.add_meta_method(MetaMethod::Index, move |lua, this, field: Value| {
479        let value = lua.to_value(this)?;
480        match value {
481            Value::Table(t) => t.get(field),
482            _ => Ok(Value::Nil),
483        }
484    });
485
486    methods.add_meta_method(MetaMethod::Len, move |lua, this, _: ()| {
487        let value = lua.to_value(this)?;
488        match value {
489            Value::Table(v) => v.len(),
490            Value::String(v) => Ok(v.as_bytes().len() as i64),
491            _ => Ok(0),
492        }
493    });
494}
495
496/// This function will try to obtain a native lua representation
497/// of the provided value. It does this by attempting to iterate
498/// the pairs of any userdata it finds as either the value itself
499/// or the values of a table value by recursively applying
500/// materialize_to_lua_value to the value.
501/// This produces a lua value that can then be processed by the
502/// Deserialize impl on Value.
503pub fn materialize_to_lua_value(lua: &Lua, value: mlua::Value) -> mlua::Result<mlua::Value> {
504    match value {
505        mlua::Value::UserData(ud) => {
506            let mt = ud.metatable()?;
507            let Ok(pairs) = mt.get::<mlua::Function>("__pairs") else {
508                let value = ud.into_lua(lua)?;
509                return Err(mlua::Error::external(format!(
510                    "cannot materialize_to_lua_value {value:?} \
511                     because it has no __pairs metamethod"
512                )));
513            };
514            let tbl = lua.create_table()?;
515            let (iter_func, state, mut control): (mlua::Function, mlua::Value, mlua::Value) =
516                pairs.call(mlua::Value::UserData(ud.clone()))?;
517
518            loop {
519                let (k, v): (mlua::Value, mlua::Value) =
520                    iter_func.call((state.clone(), control))?;
521                if k.is_nil() {
522                    break;
523                }
524
525                tbl.set(k.clone(), materialize_to_lua_value(lua, v)?)?;
526                control = k;
527            }
528
529            Ok(mlua::Value::Table(tbl))
530        }
531        mlua::Value::Table(t) => {
532            let tbl = lua.create_table()?;
533            for pair in t.pairs::<mlua::Value, mlua::Value>() {
534                let (k, v) = pair?;
535                tbl.set(k.clone(), materialize_to_lua_value(lua, v)?)?;
536            }
537            Ok(mlua::Value::Table(tbl))
538        }
539        value => Ok(value),
540    }
541}
542
543/// Helper wrapper type for passing/returning serde encoded values from/to lua
544pub struct SerdeWrappedValue<T>(pub T);
545
546impl<T: serde::Serialize> serde::Serialize for SerdeWrappedValue<T> {
547    fn serialize<S>(
548        &self,
549        s: S,
550    ) -> Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>
551    where
552        S: serde::Serializer,
553    {
554        self.0.serialize(s)
555    }
556}
557
558impl<T: Clone> Clone for SerdeWrappedValue<T> {
559    fn clone(&self) -> Self {
560        SerdeWrappedValue(self.0.clone())
561    }
562}
563
564impl<T: Default> Default for SerdeWrappedValue<T> {
565    fn default() -> Self {
566        SerdeWrappedValue(Default::default())
567    }
568}
569
570impl<T: serde::Serialize> SerdeWrappedValue<T> {
571    pub fn to_lua_value(&self, lua: &Lua) -> mlua::Result<mlua::Value> {
572        lua.to_value_with(&self.0, serialize_options())
573    }
574}
575
576impl<T: serde::Serialize> IntoLua for SerdeWrappedValue<T> {
577    fn into_lua(self, lua: &Lua) -> mlua::Result<mlua::Value> {
578        lua.to_value_with(&self.0, serialize_options())
579    }
580}
581
582impl<T: serde::de::DeserializeOwned> FromLua for SerdeWrappedValue<T> {
583    fn from_lua(value: mlua::Value, lua: &Lua) -> mlua::Result<SerdeWrappedValue<T>> {
584        let inner: T = from_lua_value(lua, value)?;
585        Ok(SerdeWrappedValue(inner))
586    }
587}
588
589impl<T> std::ops::Deref for SerdeWrappedValue<T> {
590    type Target = T;
591    fn deref(&self) -> &T {
592        &self.0
593    }
594}
595
596impl<T> std::ops::DerefMut for SerdeWrappedValue<T> {
597    fn deref_mut(&mut self) -> &mut T {
598        &mut self.0
599    }
600}
601
602/// Convert from a lua value to a deserializable type,
603/// with a slightly more helpful error message in case of failure.
604/// NOTE: the ", while processing" portion of the error messages generated
605/// here is coupled with a regex in typing.lua!
606pub fn from_lua_value<R>(lua: &Lua, value: mlua::Value) -> mlua::Result<R>
607where
608    R: serde::de::DeserializeOwned,
609{
610    let value_cloned = value.clone();
611    match lua.from_value(value) {
612        Ok(r) => Ok(r),
613        Err(err) => match materialize_to_lua_value(lua, value_cloned.clone()) {
614            Ok(materialized) => match lua.from_value(materialized.clone()) {
615                Ok(r) => Ok(r),
616                Err(err) => {
617                    let mut serializer = serde_json::Serializer::new(Vec::new());
618                    let serialized = match materialized.serialize(&mut serializer) {
619                        Ok(_) => String::from_utf8_lossy(&serializer.into_inner()).to_string(),
620                        Err(err) => format!("<unable to encode as json: {err:#}>"),
621                    };
622                    Err(mlua::Error::external(format!(
623                        "{err:#}, while processing {serialized}"
624                    )))
625                }
626            },
627            Err(materialize_err) => Err(mlua::Error::external(format!(
628                "{err:#}, while processing a userdata. \
629                    Additionally, encountered {materialize_err:#} \
630                    when trying to iterate the pairs of that userdata"
631            ))),
632        },
633    }
634}
635
636/// CallbackSignature is a bit sugar to aid with statically typing event callback
637/// function invocation.
638///
639/// The idea is that you declare a signature instance that is typed
640/// with its argument tuple (A), and its return type tuple (R).
641///
642/// The signature instance can then be used to invoke the callback by name.
643///
644/// The register method allows pre-registering events so that `kumo.on`
645/// can reason about them better.  The main function enabled by this is
646/// `allow_multiple`; when that is set to true, `kumo.on` will allow
647/// recording multiple callback instances, calling them in sequence
648/// until one of them returns a value.
649pub struct CallbackSignature<A, R>
650where
651    A: IntoLuaMulti,
652    R: FromLuaMulti,
653{
654    marker: std::marker::PhantomData<(A, R)>,
655    allow_multiple: bool,
656    name: Cow<'static, str>,
657}
658
659#[linkme::distributed_slice]
660pub static CALLBACK_SIGNATURES: [fn()];
661
662/// Helper for declaring a named event handler callback signature.
663///
664/// Usage looks like:
665///
666/// ```rust,ignore
667/// declare_event! {
668/// pub static GET_Q_CONFIG_SIG: Multiple(
669///         "get_queue_config",
670///         domain: &'static str,
671///         tenant: Option<&'static str>,
672///         campaign: Option<&'static str>,
673///         routing_domain: Option<&'static str>,
674///     ) -> QueueConfig;
675/// }
676/// ```
677///
678/// A handler can be either `Single` or `Multiple`, indicating whether
679/// only a single registration or multiple registrations are permitted.
680/// The string literal is the name of the event, followed by a fn-style
681/// parameter list which names each parameter in sequence, followed by
682/// the return value.  The names are not currently used in any way,
683/// but enhance the readability of the code.
684///
685/// In addition to declaring the signature in a global, some glue
686/// is generated that will register the signature appropriately
687/// so that lua knows whether it is single or multiple and can
688/// act appropriately when `kumo.on` is called.
689#[macro_export]
690macro_rules! declare_event {
691    ($vis:vis static $sym:ident: Multiple($name:literal $(,)? $($param_name:ident: $args:ty),* $(,)? ) -> $ret:ty;) => {
692        $vis static $sym: ::std::sync::LazyLock<
693            $crate::CallbackSignature<($($args),*), $ret>> =
694                ::std::sync::LazyLock::new(|| $crate::CallbackSignature::new_with_multiple($name));
695
696        $crate::paste::paste! {
697            #[linkme::distributed_slice($crate::CALLBACK_SIGNATURES)]
698            static [<CALLBACK_SIG_REGISTER_ $sym>]: fn() = || {
699                $sym.register();
700            };
701        }
702    };
703    ($vis:vis static $sym:ident: Single($name:literal $(,)? $($param_name:ident: $args:ty),* $(,)? ) -> $ret:ty;) => {
704        $vis static $sym: ::std::sync::LazyLock<
705            $crate::CallbackSignature<($($args),*), $ret>> =
706                ::std::sync::LazyLock::new(|| $crate::CallbackSignature::new($name));
707
708        $crate::paste::paste! {
709            #[linkme::distributed_slice($crate::CALLBACK_SIGNATURES)]
710            static [<CALLBACK_SIG_REGISTER_ $sym>]: fn() = || {
711                $sym.register();
712            };
713        }
714    };
715}
716
717/// For each event handler CallbackSignature that was declared via
718/// `declare_event!`, call its `.register()` method to register
719/// it so that `kumo.on` can give appropriate messaging if misused,
720/// and so that runtime dispatch will work correctly.
721///
722/// This should be called once, prior to running any lua code.
723fn register_declared_events() {
724    static ONCE: Once = Once::new();
725    ONCE.call_once(|| {
726        for reg_func in CALLBACK_SIGNATURES {
727            reg_func();
728        }
729    });
730}
731
732impl<A, R> CallbackSignature<A, R>
733where
734    A: IntoLuaMulti,
735    R: FromLuaMulti,
736{
737    pub fn new<S: Into<Cow<'static, str>>>(name: S) -> Self {
738        let name = name.into();
739
740        Self {
741            marker: std::marker::PhantomData,
742            allow_multiple: false,
743            name,
744        }
745    }
746
747    /// Make sure that you call .register() on this from
748    /// eg: mod_kumo::register in order for it to be instantiated
749    /// and visible to the config loader
750    pub fn new_with_multiple<S: Into<Cow<'static, str>>>(name: S) -> Self {
751        let name = name.into();
752
753        Self {
754            marker: std::marker::PhantomData,
755            allow_multiple: true,
756            name,
757        }
758    }
759
760    pub fn register(&self) {
761        if self.allow_multiple {
762            CALLBACK_ALLOWS_MULTIPLE
763                .lock()
764                .insert(self.name.to_string());
765        }
766    }
767
768    pub fn raise_error_if_allow_multiple(&self) -> anyhow::Result<()> {
769        anyhow::ensure!(
770            !self.allow_multiple(),
771            "handler {} is set to allow multiple handlers \
772                    but is registered with a single instance. This indicates that \
773                    register() was not called on the signature when initializing \
774                    the lua context. Please report this issue to the KumoMTA team!",
775            self.name
776        );
777        Ok(())
778    }
779
780    /// Return true if this signature allows multiple instances to be registered
781    /// and called.
782    pub fn allow_multiple(&self) -> bool {
783        self.allow_multiple
784    }
785
786    pub fn name(&self) -> &str {
787        &self.name
788    }
789
790    pub fn decorated_name(&self) -> String {
791        decorate_callback_name(&self.name)
792    }
793}
794
795impl<A, R> CallbackSignature<A, R>
796where
797    A: IntoLuaMulti + Clone,
798    R: FromLuaMulti,
799{
800    /// Calls the callback, passing in the supplied arguments.
801    /// Returns the callback disposition which allows further
802    /// intrepretation of the result, such as deciding whether
803    /// to Default the value based on whether the callback
804    /// was defined or not
805    pub async fn call<'a>(
806        &'a self,
807        lua: &Lua,
808        args: A,
809    ) -> anyhow::Result<CallbackDisposition<'a, R>> {
810        let name = self.name();
811        let decorated_name = self.decorated_name();
812
813        match lua.named_registry_value::<mlua::Value>(&decorated_name)? {
814            Value::Table(tbl) => {
815                for func in tbl.sequence_values::<mlua::Function>().collect::<Vec<_>>() {
816                    let func = func?;
817                    let _timer = latency_timer(name);
818                    let result: mlua::MultiValue = func.call_async(args.clone()).await?;
819                    if result.is_empty() {
820                        // Continue with other handlers
821                        continue;
822                    }
823                    let result = R::from_lua_multi(result, lua)?;
824                    return Ok(CallbackDisposition {
825                        handler_was_defined: true,
826                        result: Some(result),
827                        event_name: name,
828                    });
829                }
830                Ok(CallbackDisposition {
831                    handler_was_defined: false,
832                    result: None,
833                    event_name: name,
834                })
835            }
836            Value::Function(func) => {
837                self.raise_error_if_allow_multiple()?;
838                let _timer = latency_timer(name);
839                Ok(CallbackDisposition {
840                    handler_was_defined: true,
841                    result: Some(func.call_async(args.clone()).await?),
842                    event_name: name,
843                })
844            }
845            _ => Ok(CallbackDisposition {
846                handler_was_defined: false,
847                result: None,
848                event_name: name,
849            }),
850        }
851    }
852}
853
854pub fn does_callback_allow_multiple(name: &str) -> bool {
855    CALLBACK_ALLOWS_MULTIPLE.lock().contains(name)
856}
857
858pub fn decorate_callback_name(name: &str) -> String {
859    format!("kumomta-on-{name}")
860}
861
862/// Allows reasoning about the result of a callback to decide
863/// how to interpret the result
864pub struct CallbackDisposition<'a, T> {
865    /// Indicates whether the handler was found. If false,
866    /// then result will also be None.
867    /// If true and result.is_none(), it indicates that
868    /// none of the handlers returned a value.
869    pub handler_was_defined: bool,
870    /// The result!
871    pub result: Option<T>,
872    /// Which event was called (or to be called)
873    pub event_name: &'a str,
874}
875
876impl<'a, T> CallbackDisposition<'a, T> {
877    /// Requires that a value be returned.  Translates the disposition
878    /// into appropriate error messaging if no value was returned.
879    pub fn require_value(mut self) -> anyhow::Result<T> {
880        if !self.handler_was_defined {
881            anyhow::bail!("Event {} has not been registered", self.event_name);
882        }
883        match self.result.take() {
884            Some(value) => Ok(value),
885            None => anyhow::bail!("Event {} did not return a value", self.event_name),
886        }
887    }
888}
889impl<'a, T: Default> CallbackDisposition<'a, T> {
890    /// Unwraps the value type, or the Default impl if no value was returned
891    pub fn or_default(self) -> T {
892        self.result.unwrap_or_default()
893    }
894}
895
896pub fn serialize_options() -> mlua::SerializeOptions {
897    mlua::SerializeOptions::new()
898        .serialize_none_to_null(false)
899        .serialize_unit_to_null(false)
900}