wasm4pm 26.6.13

High-performance process mining algorithms in WebAssembly for JavaScript/TypeScript
Documentation
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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
//! WASM bindings for streaming discovery algorithms.
//!
//! This module provides JavaScript-accessible functions for all streaming
//! algorithms. Each algorithm has:
//!
//! - `streaming_<algorithm>_begin()` - Create new session
//! - `streaming_<algorithm>_add_event()` - Add one event
//! - `streaming_<algorithm>_add_batch()` - Add batch of events
//! - `streaming_<algorithm>_close_trace()` - Close a trace
//! - `streaming_<algorithm>_snapshot()` - Get current model
//! - `streaming_<algorithm>_finalize()` - Finalize and return model
//! - `streaming_<algorithm>_stats()` - Get statistics

use crate::state::{get_or_init_state, StoredObject};
use crate::streaming::{
    StreamingAlgorithm, StreamingDfgBuilder, StreamingHeuristicBuilder, StreamingSkeletonBuilder,
};
use crate::utilities::to_js_str;
use serde_json::json;
use wasm_bindgen::prelude::*;

// ============================================================================
// DFG Streaming (already existed, moved here)
// ============================================================================

/// Begin a new streaming DFG session.
#[wasm_bindgen]
pub fn streaming_dfg_begin() -> Result<JsValue, JsValue> {
    let handle = get_or_init_state()
        .store_object(StoredObject::StreamingDfgBuilder(StreamingDfgBuilder::new()))?;
    Ok(crate::error::js_val(&handle))
}

/// Append one event to an in-progress DFG trace.
#[wasm_bindgen]
pub fn streaming_dfg_add_event(
    handle: &str,
    case_id: &str,
    activity: &str,
) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            b.add_event(case_id, activity);
            to_js_str(&json!({
                "ok": true,
                "event_count": b.event_count,
                "open_traces": b.open_traces.len(),
                "activities": b.interner.len(),
            }))
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })
}

/// Add a batch of events in one call (chunked ingestion).
#[wasm_bindgen]
pub fn streaming_dfg_add_batch(handle: &str, events_json: &str) -> Result<JsValue, JsValue> {
    let batch: Vec<serde_json::Value> = serde_json::from_str(events_json)
        .map_err(|e| crate::error::js_val(&format!("Invalid events JSON: {}", e)))?;

    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            let mut added = 0usize;
            for item in &batch {
                let case_id = item["case_id"].as_str().ok_or_else(|| {
                    crate::error::js_val("Each event must have a 'case_id' string field")
                })?;
                let activity = item["activity"].as_str().ok_or_else(|| {
                    crate::error::js_val("Each event must have an 'activity' string field")
                })?;
                b.add_event(case_id, activity);
                added += 1;
            }
            to_js_str(&json!({
                "ok": true,
                "added": added,
                "event_count": b.event_count,
                "open_traces": b.open_traces.len(),
                "activities": b.interner.len(),
            }))
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })
}

/// Close a DFG trace and fold into model.
#[wasm_bindgen]
pub fn streaming_dfg_close_trace(handle: &str, case_id: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            let closed = b.close_trace(case_id);
            to_js_str(&json!({
                "ok": closed,
                "trace_count": b.trace_count,
                "open_traces": b.open_traces.len(),
            }))
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })
}

/// Flush all currently-open DFG traces.
#[wasm_bindgen]
pub fn streaming_dfg_flush_open(handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            let case_ids: Vec<String> = b.open_traces.keys().cloned().collect();
            let flushed = case_ids.len();
            for id in case_ids {
                b.close_trace(&id);
            }
            to_js_str(&json!({
                "ok": true,
                "flushed": flushed,
                "trace_count": b.trace_count,
            }))
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })
}

/// Take a non-destructive DFG snapshot.
///
/// Returns a JSON string (not a JS object) — callers must `JSON.parse()` the result.
/// This uses `serde_json::to_string` + `JsValue::from_str` to avoid the known
/// `serde_wasm_bindgen::to_value` bug that silently returns `{}` on wasm32 for
/// `serde_json::Value` payloads.
#[wasm_bindgen]
pub fn streaming_dfg_snapshot(handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            let dfg = b.snapshot();
            to_js_str(&dfg)
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })
}

/// Finalize the stream and return DFG handle.
#[wasm_bindgen]
pub fn streaming_dfg_finalize(handle: &str) -> Result<JsValue, JsValue> {
    let dfg = get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            let case_ids: Vec<String> = b.open_traces.keys().cloned().collect();
            for id in case_ids {
                b.close_trace(&id);
            }
            Ok(b.snapshot())
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })?;

    let n_nodes = dfg.nodes.len();
    let n_edges = dfg.edges.len();
    let dfg_handle = get_or_init_state()
        .store_object(StoredObject::DFG(dfg))
        .map_err(|_| crate::error::js_val("Failed to store DFG"))?;

    get_or_init_state().delete_object(handle)?;

    to_js_str(&json!({
        "dfg_handle": dfg_handle,
        "nodes": n_nodes,
        "edges": n_edges,
    }))
}

/// Report memory/progress statistics.
///
/// Returns a JSON string — callers must `JSON.parse()` the result.
#[wasm_bindgen]
pub fn streaming_dfg_stats(handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(handle, |obj| match obj {
        Some(StoredObject::StreamingDfgBuilder(b)) => {
            let stats = b.stats();
            to_js_str(&stats)
        }
        Some(_) => Err(crate::error::js_val("Handle is not a StreamingDfgBuilder")),
        None => Err(crate::error::js_val("StreamingDfgBuilder handle not found")),
    })
}

// ============================================================================
// Skeleton Streaming
// ============================================================================

/// Begin a new streaming Skeleton session.
#[wasm_bindgen]
pub fn streaming_skeleton_begin(min_frequency: usize) -> Result<JsValue, JsValue> {
    let builder = StreamingSkeletonBuilder::with_min_frequency(min_frequency);
    let handle =
        get_or_init_state().store_object(StoredObject::StreamingSkeletonBuilder(builder))?;
    Ok(crate::error::js_val(&handle))
}

/// Append one event to an in-progress Skeleton trace.
#[wasm_bindgen]
pub fn streaming_skeleton_add_event(
    handle: &str,
    case_id: &str,
    activity: &str,
) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingSkeletonBuilder(b)) => {
            b.add_event(case_id, activity);
            let stats = b.stats();
            to_js_str(&json!({
                "ok": true,
                "event_count": stats.event_count,
                "open_traces": stats.open_traces,
            }))
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingSkeletonBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingSkeletonBuilder handle not found",
        )),
    })
}

/// Close a Skeleton trace.
#[wasm_bindgen]
pub fn streaming_skeleton_close_trace(handle: &str, case_id: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingSkeletonBuilder(b)) => {
            let closed = b.close_trace(case_id);
            to_js_str(&json!({
                "ok": closed,
                "trace_count": b.trace_count,
            }))
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingSkeletonBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingSkeletonBuilder handle not found",
        )),
    })
}

/// Take a non-destructive Skeleton snapshot.
///
/// Returns a JSON string — callers must `JSON.parse()` the result.
#[wasm_bindgen]
pub fn streaming_skeleton_snapshot(handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(handle, |obj| match obj {
        Some(StoredObject::StreamingSkeletonBuilder(b)) => {
            let dfg = b.snapshot();
            to_js_str(&dfg)
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingSkeletonBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingSkeletonBuilder handle not found",
        )),
    })
}

/// Finalize Skeleton stream.
#[wasm_bindgen]
pub fn streaming_skeleton_finalize(handle: &str) -> Result<JsValue, JsValue> {
    let dfg = get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingSkeletonBuilder(b)) => {
            let case_ids: Vec<String> = b.open_trace_ids();
            for id in case_ids {
                b.close_trace(&id);
            }
            Ok(b.snapshot())
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingSkeletonBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingSkeletonBuilder handle not found",
        )),
    })?;

    let n_nodes = dfg.nodes.len();
    let n_edges = dfg.edges.len();
    let dfg_handle = get_or_init_state()
        .store_object(StoredObject::DFG(dfg))
        .map_err(|_| crate::error::js_val("Failed to store DFG"))?;

    get_or_init_state().delete_object(handle)?;

    to_js_str(&json!({
        "dfg_handle": dfg_handle,
        "nodes": n_nodes,
        "edges": n_edges,
    }))
}

// ============================================================================
// Heuristic Streaming
// ============================================================================

/// Begin a new streaming Heuristic Miner session.
#[wasm_bindgen]
pub fn streaming_heuristic_begin(threshold: f64) -> Result<JsValue, JsValue> {
    let builder = StreamingHeuristicBuilder::with_dependency_threshold(threshold);
    let handle =
        get_or_init_state().store_object(StoredObject::StreamingHeuristicBuilder(builder))?;
    Ok(crate::error::js_val(&handle))
}

/// Append one event to an in-progress Heuristic trace.
#[wasm_bindgen]
pub fn streaming_heuristic_add_event(
    handle: &str,
    case_id: &str,
    activity: &str,
) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingHeuristicBuilder(b)) => {
            b.add_event(case_id, activity);
            let stats = b.stats();
            to_js_str(&json!({
                "ok": true,
                "event_count": stats.event_count,
                "open_traces": stats.open_traces,
            }))
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingHeuristicBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingHeuristicBuilder handle not found",
        )),
    })
}

/// Close a Heuristic trace.
#[wasm_bindgen]
pub fn streaming_heuristic_close_trace(handle: &str, case_id: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingHeuristicBuilder(b)) => {
            let closed = b.close_trace(case_id);
            to_js_str(&json!({
                "ok": closed,
                "trace_count": b.trace_count,
            }))
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingHeuristicBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingHeuristicBuilder handle not found",
        )),
    })
}

/// Take a non-destructive Heuristic snapshot.
///
/// Returns a JSON string — callers must `JSON.parse()` the result.
#[wasm_bindgen]
pub fn streaming_heuristic_snapshot(handle: &str) -> Result<JsValue, JsValue> {
    get_or_init_state().with_object(handle, |obj| match obj {
        Some(StoredObject::StreamingHeuristicBuilder(b)) => {
            let dfg = b.snapshot();
            to_js_str(&dfg)
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingHeuristicBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingHeuristicBuilder handle not found",
        )),
    })
}

/// Finalize Heuristic stream.
#[wasm_bindgen]
pub fn streaming_heuristic_finalize(handle: &str) -> Result<JsValue, JsValue> {
    let dfg = get_or_init_state().with_object_mut(handle, |obj| match obj {
        Some(StoredObject::StreamingHeuristicBuilder(b)) => {
            let case_ids: Vec<String> = b.open_trace_ids();
            for id in case_ids {
                b.close_trace(&id);
            }
            Ok(b.snapshot())
        }
        Some(_) => Err(crate::error::js_val(
            "Handle is not a StreamingHeuristicBuilder",
        )),
        None => Err(crate::error::js_val(
            "StreamingHeuristicBuilder handle not found",
        )),
    })?;

    let n_nodes = dfg.nodes.len();
    let n_edges = dfg.edges.len();
    let dfg_handle = get_or_init_state()
        .store_object(StoredObject::DFG(dfg))
        .map_err(|_| crate::error::js_val("Failed to store DFG"))?;

    get_or_init_state().delete_object(handle)?;

    to_js_str(&json!({
        "dfg_handle": dfg_handle,
        "nodes": n_nodes,
        "edges": n_edges,
    }))
}

/// Streaming module info.
#[wasm_bindgen]
pub fn streaming_info() -> String {
    serde_json::json!({
        "status": "streaming_api_available",
        "description": "Streaming discovery algorithms for infinite event streams",
        "algorithms": [
            {"name": "dfg", "status": "implemented"},
            {"name": "skeleton", "status": "implemented"},
            {"name": "heuristic", "status": "implemented"},
            {"name": "alpha_plus_plus", "status": "implemented"},
            {"name": "declare", "status": "implemented"},
            {"name": "inductive_miner", "status": "implemented"},
            {"name": "hill_climbing", "status": "implemented"},
            {"name": "noise_filtered_dfg", "status": "implemented"},
            {"name": "astar", "status": "implemented"},
        ]
    })
    .to_string()
}