swiftide_agents/
util.rs

1//! Internal utility functions and macros for anything agent
2
3/// Simple macro to consistently call hooks and clean up the code
4#[macro_export]
5macro_rules! invoke_hooks {
6    (OnStream, $self_expr:expr $(, $arg:expr)* ) => {{
7        // For streaming we log less and only on the trace level
8        for hook in $self_expr.hooks_by_type(HookTypes::OnStream) {
9            // Downcast to the correct closure variant
10            if let Hook::OnStream(hook_fn) = hook {
11                // Create a tracing span for instrumentation
12                let span = tracing::trace_span!(
13                    "hook",
14                    "otel.name" = format!("hook.{:?}", HookTypes::OnStream)
15                );
16
17                // Call the hook, instrument, and log on failure
18                if let Err(err) = hook_fn($self_expr $(, $arg)*)
19                    .instrument(span.or_current())
20                    .await
21                {
22                    tracing::error!(
23                        "Error in {hooktype} hook: {err}",
24                        hooktype = HookTypes::OnStream,
25                    );
26                }
27            }
28        }
29    }};
30    ($hook_type:ident, $self_expr:expr $(, $arg:expr)* ) => {{
31        // Iterate through every hook matching `HookTypes::$hook_type`
32        for hook in $self_expr.hooks_by_type(HookTypes::$hook_type) {
33            // Downcast to the correct closure variant
34            if let Hook::$hook_type(hook_fn) = hook {
35                // Create a tracing span for instrumentation
36                let span = tracing::info_span!(
37                    "hook",
38                    "otel.name" = format!("hook.{:?}", HookTypes::$hook_type)
39                );
40                tracing::debug!("Calling {} hook", HookTypes::$hook_type);
41
42                // Call the hook, instrument, and log on failure
43                if let Err(err) = hook_fn($self_expr $(, $arg)*)
44                    .instrument(span.or_current())
45                    .await
46                {
47                    tracing::error!(
48                        "Error in {hooktype} hook: {err}",
49                        hooktype = HookTypes::$hook_type,
50                    );
51                }
52            }
53        }
54    }};
55}