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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
//! # WebAssembly / JavaScript support
//!
use crate::bpmn;
use crate::bpmn::schema::BaseElementType;
use crate::model::Model;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use tokio::sync::oneshot;
use wasm_bindgen::prelude::*;
use wasm_rs_shared_channel::spsc;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_name = "self")]
static scope: web_sys::DedicatedWorkerGlobalScope;
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
id: u32,
variant: Variant,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Variant {
Info,
CreateModel { xml: String },
ListProcesses { model_id: u32 },
StartProcess { model_id: u32, process_id: u32 },
SubscribeProcessLog { model_id: u32, process_id: u32 },
}
#[wasm_bindgen]
pub struct Channel {
sender: Option<spsc::Sender<Request>>,
receiver: Option<spsc::Receiver<Request>>,
}
#[wasm_bindgen]
impl Channel {
#[wasm_bindgen(constructor)]
#[allow(clippy::new_without_default)]
pub fn new() -> Channel {
let (sender, receiver) = spsc::channel::<Request>(1024 * 1024).split();
Channel {
sender: Some(sender),
receiver: Some(receiver),
}
}
pub fn from(val: JsValue) -> Self {
let (sender, receiver) = spsc::SharedChannel::from(val).split();
Channel {
sender: Some(sender),
receiver: Some(receiver),
}
}
pub fn replica(&self) -> JsValue {
self.receiver.as_ref().unwrap().0.clone().into()
}
pub fn run(&mut self) -> Result<(), JsValue> {
console_error_panic_hook::set_once();
let receiver = self.receiver.take().unwrap();
let (sender, mut rcvr) = oneshot::channel();
let fut = async move {
let mut model_id_counter = 0u32;
let mut models = HashMap::new();
let mut previous_tasks = executor::queued_tasks();
loop {
crate::sys::task::yield_now().await;
let tasks = executor::queued_tasks();
// stasis detection
// current thesis is that if there's nothing queued or it's the same tokens
// as in the previous iteration of the loop, it means we need new input to
// resolve any of the futures
let timeout = if executor::queued_tasks_count() == 0 || tasks == previous_tasks {
Some(std::time::Duration::from_secs(1))
} else {
None
};
previous_tasks = tasks;
match receiver.recv(timeout) {
Err(_) => {
let _ = sender.send(receiver);
break;
}
Ok(None) => {}
Ok(Some(Request {
id,
variant: Variant::Info,
})) => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"status".into(), &"running".into());
let _ =
scope.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
Ok(Some(Request {
id,
variant: Variant::CreateModel { xml },
})) => match bpmn::parse(&xml) {
Ok(doc) => {
let model_id = model_id_counter;
model_id_counter += 1;
models.insert(model_id, Model::new(doc).spawn().await);
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"model_id".into(), &model_id.into());
let _ = scope
.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
Err(err) => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(
&"error".into(),
&format!("error parsing xml: {}", err).into(),
);
let _ = scope
.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
},
Ok(Some(Request {
id,
variant: Variant::ListProcesses { model_id },
})) => match models.get(&model_id) {
None => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"error".into(), &"model not found".into());
let _ = scope
.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
Some(model) => {
let processes = model.processes().await.unwrap();
let map = js_sys::Map::new();
for (index, process) in processes.iter().enumerate() {
let id = match process.element().id() {
None => JsValue::from(index as u32),
Some(id) => JsValue::from(id),
};
map.set(&JsValue::from(index as u32), &id);
}
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(
&"processes".into(),
&js_sys::Object::from_entries(&map).unwrap(),
);
let _ = scope
.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
},
Ok(Some(Request {
id,
variant:
Variant::StartProcess {
model_id,
process_id,
},
})) => match models.get(&model_id) {
None => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"error".into(), &"model not found".into());
let _ = scope
.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
Some(model) => {
let processes = model.processes().await.unwrap();
match processes
.iter()
.enumerate()
.find(|(index, _)| *index as u32 == process_id)
{
None => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"error".into(), &"process not found".into());
let _ = scope.post_message(
&js_sys::Object::from_entries(&response).unwrap(),
);
}
Some((_, process)) => {
let result = process.start().await;
match result {
Ok(()) => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"started".into(), &JsValue::TRUE);
let _ = scope.post_message(
&js_sys::Object::from_entries(&response).unwrap(),
);
}
Err(err) => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"started".into(), &JsValue::FALSE);
response
.set(&"error".into(), &format!("{}", err).into());
let _ = scope.post_message(
&js_sys::Object::from_entries(&response).unwrap(),
);
}
}
}
}
}
},
Ok(Some(Request {
id,
variant:
Variant::SubscribeProcessLog {
model_id,
process_id,
},
})) => match models.get(&model_id) {
None => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"error".into(), &"model not found".into());
let _ = scope
.post_message(&js_sys::Object::from_entries(&response).unwrap());
}
Some(model) => {
let processes = model.processes().await.unwrap();
match processes
.iter()
.enumerate()
.find(|(index, _)| *index as u32 == process_id)
{
None => {
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"error".into(), &"process not found".into());
let _ = scope.post_message(
&js_sys::Object::from_entries(&response).unwrap(),
);
}
Some((_, process)) => {
let mut log_receiver = process.log_receiver();
let worker_scope = scope.clone();
executor::spawn(async move {
loop {
if let Ok(message) = log_receiver.recv().await {
let notification = js_sys::Map::new();
notification.set(&"id".into(), &id.into());
notification.set(
&"data".into(),
&JsValue::from_serde(&message).unwrap(),
);
let _ = worker_scope.post_message(
&js_sys::Object::from_entries(¬ification)
.unwrap(),
);
} else {
break;
}
}
});
let response = js_sys::Map::new();
response.set(&"id".into(), &id.into());
response.set(&"subscribed".into(), &JsValue::TRUE);
let _ = scope.post_message(
&js_sys::Object::from_entries(&response).unwrap(),
);
}
}
}
},
}
}
};
use wasm_rs_async_executor::single_threaded as executor;
executor::run(Some(executor::spawn(fut).task()));
self.receiver.replace(rcvr.try_recv().unwrap());
Ok(())
}
pub fn sender(&mut self) -> Result<Sender, JsValue> {
match self.sender.take() {
Some(sender) => Ok(Sender(sender)),
None => Err("sender is already taken".to_string().into()),
}
}
}
#[wasm_bindgen]
pub struct Sender(spsc::Sender<Request>);
#[wasm_bindgen]
impl Sender {
pub fn info(&self, id: u32) -> Result<(), JsValue> {
self.0.send(&Request {
id,
variant: Variant::Info,
})
}
#[wasm_bindgen(js_name = "createModel")]
pub fn create_model(&self, xml: String, id: u32) -> Result<(), JsValue> {
self.0.send(&Request {
id,
variant: Variant::CreateModel { xml },
})
}
#[wasm_bindgen(js_name = "processes")]
pub fn list_processes(&self, model_id: u32, id: u32) -> Result<(), JsValue> {
self.0.send(&Request {
id,
variant: Variant::ListProcesses { model_id },
})
}
#[wasm_bindgen(js_name = "startProcess")]
pub fn start_process(&self, model_id: u32, process_id: u32, id: u32) -> Result<(), JsValue> {
self.0.send(&Request {
id,
variant: Variant::StartProcess {
model_id,
process_id,
},
})
}
#[wasm_bindgen(js_name = "subscribeToProcessLog")]
pub fn subscribe_process_log(
&self,
model_id: u32,
process_id: u32,
id: u32,
) -> Result<(), JsValue> {
self.0.send(&Request {
id,
variant: Variant::SubscribeProcessLog {
model_id,
process_id,
},
})
}
}