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
mod engine;
mod parallel;
mod replay;
mod scaffold;
mod trace;
use std::{
collections::HashMap,
path::Path,
str::FromStr,
sync::{Arc, Mutex},
};
use trace::{tracer, Trace};
use crate::{
error::Error,
model::{Bpmn, EventType},
reader::{read_bpmn_file, read_bpmn_str},
Eventhandler, Symbol,
};
pub(crate) type ExecuteResult<'a> = Result<Vec<&'a str>, Error>;
/// Process result from a process run.
#[derive(Debug)]
pub struct ProcessResult<T> {
/// Result produced by the task flow.
pub result: T,
/// Trace from the process run
pub trace: Vec<(&'static str, String)>,
}
/// Process that contains information from the BPMN file
#[derive(Debug)]
pub struct Process {
data: HashMap<String, HashMap<String, Bpmn>>,
definitions_id: String,
activity_ids: HashMap<String, HashMap<Symbol, String>>,
catch_events_ids: HashMap<String, HashMap<Symbol, String>>,
}
impl Process {
/// Create new process and initialize it from the BPMN file path.
/// ```
/// use snurr::Process;
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let bpmn = Process::new("examples/example.bpmn")?;
/// Ok(())
/// }
/// ```
pub fn new(path: impl AsRef<Path>) -> Result<Self, Error> {
Self::assemble_data(read_bpmn_file(path)?)
}
fn assemble_data(
(definitions_id, mut data): (String, HashMap<String, HashMap<String, Bpmn>>),
) -> Result<Self, Error> {
// Collect all referencing output names
let mut gateway_ids: HashMap<String, HashMap<String, String>> = HashMap::new();
// Collect all boundary symbols attached to an activity id
let mut activity_ids: HashMap<String, HashMap<Symbol, String>> = HashMap::new();
// Collect all IntermediateCatchEvents
let mut catch_events_ids: HashMap<String, HashMap<Symbol, String>> = HashMap::new();
data.values().for_each(|process: &HashMap<String, Bpmn>| {
process.values().for_each(|bpmn| {
if let Bpmn::SequenceFlow {
id,
name: Some(name),
source_ref,
..
} = bpmn
{
if let Some(Bpmn::Gateway { .. }) = process.get(source_ref) {
let entry = gateway_ids.entry(source_ref.into()).or_default();
entry.insert(name.into(), id.into());
}
}
if let Bpmn::Event {
event: EventType::Boundary,
symbol: Some(symbol),
id,
attached_to_ref: Some(attached_to_ref),
..
} = bpmn
{
let entry = activity_ids.entry(attached_to_ref.into()).or_default();
entry.insert(symbol.clone(), id.into());
}
if let Bpmn::Event {
event: EventType::IntermediateCatch,
symbol: Some(symbol),
id,
name: Some(name),
..
} = bpmn
{
let entry = catch_events_ids.entry(name.into()).or_default();
entry.insert(symbol.clone(), id.into());
}
});
});
// Update gateway outputs with name
data.values_mut().for_each(|process| {
process.values_mut().for_each(|bpmn| {
if let Bpmn::Gateway { id, outputs, .. } = bpmn {
if let Some(map) = gateway_ids.get(id) {
for (name, id) in map.iter() {
outputs.register_name(id, name);
}
}
}
});
});
Ok(Self {
data,
definitions_id,
activity_ids,
catch_events_ids,
})
}
/// Run the process and return the `ProcessResult` or an `Error`.
/// ```
/// use snurr::{Process, Eventhandler};
///
/// #[derive(Debug, Default)]
/// struct Counter {
/// count: u32,
/// }
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let bpmn = Process::new("examples/example.bpmn")?;
/// let handler: Eventhandler<Counter> = Eventhandler::default();
/// // Register Task and Gateways to handler here...
/// let pr = bpmn.run(&handler, Counter::default())?;
/// Ok(())
/// }
/// ```
pub fn run<T>(&self, handler: &Eventhandler<T>, data: T) -> Result<ProcessResult<T>, Error>
where
T: Send + std::fmt::Debug,
{
let data = Arc::new(Mutex::new(data));
let trace: Trace<(&str, String)> = tracer();
// Run every process specified in the diagram
for (_, bpmn) in self
.data
.get(&self.definitions_id)
.ok_or(Error::MissingDefinitionsId)?
.iter()
{
if let Bpmn::Process {
id,
start_id: Some(start_id),
..
} = bpmn
{
self.execute(
vec![start_id],
self.data
.get_key_value(id)
.ok_or_else(|| Error::MissingProcessData(id.into()))?,
handler,
Arc::clone(&data),
trace.sender(),
)?;
}
}
Ok(ProcessResult {
result: Arc::into_inner(data)
.ok_or(Error::NoProcessResult)?
.into_inner()
.map_err(|_| Error::NoProcessResult)?,
trace: trace.finish(),
})
}
}
impl FromStr for Process {
type Err = Error;
/// Create new process and initialize it from a BPMN `&str`.
/// ```
/// use snurr::Process;
///
/// static BPMN_DATA: &str = include_str!("../examples/example.bpmn");
///
/// fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let bpmn: Process = BPMN_DATA.parse()?;
/// Ok(())
/// }
/// ```
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::assemble_data(read_bpmn_str(s)?)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn create_and_run() -> Result<(), Box<dyn std::error::Error>> {
let bpmn = Process::new("examples/example.bpmn")?;
let handler: Eventhandler<_> = Eventhandler::default();
bpmn.run(&handler, {})?;
Ok(())
}
}