moduforge_rules_engine/handler/function/
mod.rs

1use std::rc::Rc;
2use std::time::Duration;
3
4use ::serde::{Deserialize, Serialize};
5use anyhow::anyhow;
6use rquickjs::{async_with, CatchResultExt, Object};
7use serde_json::json;
8
9use crate::handler::function::error::FunctionResult;
10use crate::handler::function::function::{Function, HandlerResponse};
11use crate::handler::function::module::console::Log;
12use crate::handler::function::serde::JsValue;
13use crate::handler::node::{
14    NodeRequest, NodeResponse, NodeResult, PartialTraceError,
15};
16use crate::model::{DecisionNodeKind, FunctionNodeContent};
17
18pub mod error;
19pub mod function;
20pub mod listener;
21pub mod module;
22pub mod serde;
23
24#[derive(Serialize, Deserialize)]
25pub struct FunctionResponse {
26    performance: String,
27    data: Option<HandlerResponse>,
28}
29
30pub struct FunctionHandler {
31    function: Rc<Function>,
32    trace: bool,
33    iteration: u8,
34    max_depth: u8,
35}
36
37static MAX_DURATION: Duration = Duration::from_millis(5_000);
38
39impl FunctionHandler {
40    pub fn new(
41        function: Rc<Function>,
42        trace: bool,
43        iteration: u8,
44        max_depth: u8,
45    ) -> Self {
46        Self { function, trace, iteration, max_depth }
47    }
48
49    pub async fn handle(
50        &self,
51        request: NodeRequest,
52    ) -> NodeResult {
53        let content = match &request.node.kind {
54            DecisionNodeKind::FunctionNode { content } => match content {
55                FunctionNodeContent::Version2(content) => Ok(content),
56                _ => Err(anyhow!("Unexpected node type")),
57            },
58            _ => Err(anyhow!("Unexpected node type")),
59        }?;
60        let start = std::time::Instant::now();
61
62        let module_name = self
63            .function
64            .suggest_module_name(request.node.id.as_str(), &content.source);
65        let interrupt_handler =
66            Box::new(move || start.elapsed() > MAX_DURATION);
67        self.function
68            .runtime()
69            .set_interrupt_handler(Some(interrupt_handler))
70            .await;
71
72        self.attach_globals().await.map_err(|e| anyhow!(e.to_string()))?;
73
74        self.function
75            .register_module(&module_name, content.source.as_str())
76            .await
77            .map_err(|e| anyhow!(e.to_string()))?;
78        let response_result = self
79            .function
80            .call_handler(&module_name, JsValue(request.input.clone()))
81            .await;
82
83        match response_result {
84            Ok(response) => {
85                self.function.runtime().set_interrupt_handler(None).await;
86
87                Ok(NodeResponse {
88                    output: response.data,
89                    trace_data: self
90                        .trace
91                        .then(|| json!({ "log": response.logs })),
92                })
93            },
94            Err(e) => {
95                let mut log = self.function.extract_logs().await;
96                log.push(Log {
97                    lines: vec![json!(e.to_string()).to_string()],
98                    ms_since_run: start.elapsed().as_millis() as usize,
99                });
100
101                Err(anyhow!(PartialTraceError {
102                    message: e.to_string(),
103                    trace: Some(json!({ "log": log })),
104                }))
105            },
106        }
107    }
108
109    async fn attach_globals(&self) -> FunctionResult {
110        async_with!(self.function.context() => |ctx| {
111            let config = Object::new(ctx.clone()).catch(&ctx)?;
112
113            config.prop("iteration", self.iteration).catch(&ctx)?;
114            config.prop("maxDepth", self.max_depth).catch(&ctx)?;
115            config.prop("trace", self.trace).catch(&ctx)?;
116
117            ctx.globals().set("config", config).catch(&ctx)?;
118
119            Ok(())
120        })
121        .await
122    }
123}