1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
use crate::snapshot::SnapshotOptions;
use crate::{
ActPackage, ActPlugin, Config, Engine, config::ConfigLog, package::ActPackageRegister,
store::KvStore,
};
use std::{path::Path, sync::Arc};
pub struct EngineBuilder {
config: Config,
plugins: Vec<Arc<dyn ActPlugin>>,
packages: Vec<ActPackageRegister>,
snapshots: Vec<(String, SnapshotOptions)>,
store: Option<Arc<dyn KvStore>>,
}
impl Default for EngineBuilder {
fn default() -> Self {
Self::new()
}
}
impl EngineBuilder {
pub fn new() -> Self {
let mut config = Config::default();
#[cfg(not(test))]
let file = Path::new("config/acts.toml");
#[cfg(test)]
let file = Path::new("test/acts.toml");
if file.exists() {
config = Config::create(file);
}
Self {
config,
plugins: Vec::new(),
packages: Vec::new(),
snapshots: Vec::new(),
store: None,
}
}
pub fn set_config(mut self, config: &Config) -> Self {
self.config = config.clone();
self
}
pub fn set_config_source(mut self, source: &Path) -> Self {
self.config = Config::create(source);
self
}
pub fn log(mut self, dir: &str, level: &str) -> Self {
self.config.data.log = Some(ConfigLog {
dir: dir.to_string(),
level: level.to_string(),
});
self
}
pub fn cache_size(mut self, size: i64) -> Self {
self.config.data.cache_cap = Some(size);
self
}
pub fn tick_interval_secs(mut self, secs: i64) -> Self {
self.config.data.tick_interval_secs = Some(secs);
self
}
pub fn max_message_retry_times(mut self, retry_times: i32) -> Self {
self.config.data.max_message_retry_times = Some(retry_times);
self
}
/// bound the times a tree node can be executed in one process (protects
/// against unbounded task creation caused by a node self-loop or a cyclic
/// `next`); 0 disables the check
pub fn max_node_run_times(mut self, times: i64) -> Self {
self.config.data.max_node_run_times = Some(times);
self
}
/// register plugin
///
/// ## Example
///
/// ```no_run
/// use acts::{ActPlugin, Message, Engine, Workflow, Result};
///
/// #[derive(Clone)]
/// struct TestPlugin;
/// impl TestPlugin {
/// fn new() -> Self {
/// Self
/// }
/// }
/// #[async_trait::async_trait]
/// impl ActPlugin for TestPlugin {
/// fn on_init(&self, engine: &Engine) -> Result<()> {
/// println!("TestPlugin");
/// engine.channel().on_start(|_| async {});
/// engine.channel().on_complete(|_| async {});
/// engine.channel().on_message(|_| async {});
/// Ok(())
/// }
/// }
///
/// #[tokio::main]
/// async fn main() {
/// let engine = Engine::builder().add_plugin(&TestPlugin::new()).build().start().await.unwrap();
/// }
/// ```
pub fn add_plugin<T>(mut self, plugin: &T) -> Self
where
T: ActPlugin + Clone + 'static,
{
self.plugins.push(Arc::new(plugin.clone()));
self
}
/// register package
//// ## Example
/// ```no_run
/// use acts::{ActPackage, ActPackageDefinition, ActPackageCatalog, Context, Engine, Result, Vars};
/// use serde::{Deserialize, Serialize};
/// use serde_json::json;
///
/// #[derive(Debug, Clone, Deserialize, Serialize)]
/// struct MyPackage;
///
/// #[async_trait::async_trait]
/// impl ActPackage for MyPackage {
/// fn definition() -> ActPackageDefinition {
/// ActPackageDefinition {
/// id: "my_package",
/// name: "my package",
/// desc: "",
/// icon: "",
/// doc: "",
/// version: "0.1.0",
/// schema: json!({}),
/// options: Some(json!({})),
/// run_as: acts::ActRunAs::Func,
/// resources: vec![],
/// catalog: ActPackageCatalog::App,
/// }
/// }
///
/// fn new(_config: &acts::Config) -> Result<Self> {
/// Ok(Self)
/// }
///
/// async fn execute(&self, ctx: &Context, params: &serde_json::Value) -> Result<Option<Vars>> {
/// // do something with ctx
/// Ok(None)
/// }
/// }
/// #[tokio::main]
/// async fn main() {
/// let engine = Engine::builder().add_package::<MyPackage>().build().start().await.unwrap();
/// }
/// ```
pub fn add_package<T>(mut self) -> Self
where
T: ActPackage + Clone + 'static,
{
let package_register = ActPackageRegister::new::<T>();
self.packages.push(package_register);
self
}
/// Pre-register a snapshot-backed sealed-data target before `start()`.
///
/// Data is fed later through [`Engine::snapshot`](crate::Engine::snapshot)
/// (message-channel adapters or the embedding application) and is sealed
/// into tasks at their prepare from the local cache — no network I/O on
/// the scheduling path.
pub fn add_snapshot(mut self, name: &str, options: SnapshotOptions) -> Self {
self.snapshots.push((name.to_string(), options));
self
}
/// set the store
///
/// The store backend is created externally and set here. When unset, an
/// in-memory store is used. Only one store can be set — calling this
/// again panics.
///
/// ## Example
///
/// ```no_run
/// use acts::{Engine, MemoryStore};
/// use std::sync::Arc;
///
/// #[tokio::main]
/// async fn main() {
/// let engine = Engine::builder()
/// .set_store(Arc::new(MemoryStore::new()))
/// .build()
/// .start()
/// .await
/// .unwrap();
/// }
/// ```
///
/// The persistent backends live in the `acts-store` crate — enable its
/// matching feature and import the backend from there, e.g. with feature
/// `sqlite`: `use acts_store::SqliteStore;
/// set_store(Arc::new(SqliteStore::open(path).await?))`. Any type
/// implementing [`KvStore`](crate::KvStore) is accepted.
pub fn set_store(mut self, store: Arc<dyn KvStore>) -> Self {
assert!(
self.store.is_none(),
"store already set: only one backend is allowed"
);
self.store = Some(store);
self
}
pub fn build(self) -> Engine {
Engine::new()
.with_config(&self.config)
.set_plugins(self.plugins.clone())
.set_packages(self.packages.clone())
.set_snapshots(self.snapshots.clone())
.set_store(self.store)
}
}