acts_next/export/
extender.rs

1use core::fmt;
2use std::sync::{Arc, Mutex};
3
4use crate::{scheduler::Runtime, ActModule, ActPlugin};
5
6#[derive(Clone)]
7pub struct Extender {
8    runtime: Arc<Runtime>,
9    plugins: Arc<Mutex<Vec<Box<dyn ActPlugin>>>>,
10}
11
12impl fmt::Debug for Extender {
13    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
14        f.debug_struct("Extender").finish()
15    }
16}
17
18impl Extender {
19    pub(crate) fn new(runtime: &Arc<Runtime>) -> Self {
20        Self {
21            runtime: runtime.clone(),
22            plugins: Arc::new(Mutex::new(Vec::new())),
23        }
24    }
25
26    /// register module
27    ///
28    /// ## Example
29    /// ```no_run
30    /// use acts::Engine;
31    /// mod test_module {
32    ///   use acts::{ActModule, Result};
33    ///   #[derive(Clone)]
34    ///   pub struct TestModule;
35    ///   impl ActModule for TestModule {
36    ///     fn init<'a>(&self, _ctx: &rquickjs::Ctx<'a>) -> Result<()> {
37    ///         Ok(())
38    ///     }
39    ///   }
40    /// }
41    /// let engine = Engine::new();
42    /// let module = test_module::TestModule;
43    /// engine.extender().register_module(&module);
44    /// ```
45    pub fn register_module<T: ActModule + Clone + 'static>(&self, module: &T) {
46        self.runtime.env().register_module(module)
47    }
48
49    /// register plugin
50    ///
51    /// ## Example
52    ///
53    /// ```no_run
54    /// use acts::{ActPlugin, Message, Engine, Workflow};
55    ///
56    /// #[derive(Clone)]
57    /// struct TestPlugin;
58    /// impl TestPlugin {
59    ///     fn new() -> Self {
60    ///         Self
61    ///     }
62    /// }
63    /// impl ActPlugin for TestPlugin {
64    ///     fn on_init(&self, engine: &Engine) {
65    ///         println!("TestPlugin");
66    ///         engine.channel().on_start(|e| {});
67    ///         engine.channel().on_complete(|e| {});
68    ///         engine.channel().on_message(|e| {});
69    ///     }
70    /// }
71    /// let engine = Engine::new();
72    /// engine.extender().register_plugin(&TestPlugin::new());
73    /// ```
74    pub fn register_plugin<T: ActPlugin + 'static + Clone>(&self, plugin: &T) {
75        let mut plugins = self.plugins.lock().unwrap();
76        plugins.push(Box::new(plugin.clone()));
77    }
78
79    pub fn plugins(&self) -> Arc<Mutex<Vec<Box<dyn ActPlugin>>>> {
80        self.plugins.clone()
81    }
82}