wse 3.1.0

WebSocket engine for reactive user interfaces: topics with message recovery, presence, clustering without a broker, JWT, end-to-end encryption and signed messages.
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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use chrono::{DateTime, Utc};
use pyo3::prelude::*;
use pyo3::sync::PyOnceLock;
use pyo3::types::{
    PyBool, PyBytes, PyDict, PyFloat, PyInt, PyList, PyNone, PyString, PyTuple, PyType,
};
use uuid::Uuid;

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

#[inline]
fn is_clean_primitive(obj: &Bound<'_, PyAny>) -> bool {
    obj.is_instance_of::<PyString>()
        || obj.is_instance_of::<PyBool>()
        || obj.is_instance_of::<PyInt>()
        || obj.is_instance_of::<PyFloat>()
        || obj.is_instance_of::<PyNone>()
}

/// Containers nested deeper than this are rejected with `ValueError`; deeper
/// recursion could overflow the thread's stack, which aborts the process.
const MAX_DEPTH: usize = 128;

static DECIMAL_TYPE: PyOnceLock<Py<PyType>> = PyOnceLock::new();

fn is_decimal(obj: &Bound<'_, PyAny>) -> PyResult<bool> {
    let decimal = DECIMAL_TYPE.import(obj.py(), "decimal", "Decimal")?;
    obj.is_instance(decimal)
}

/// True when `obj` is made only of JSON-ready values - str, bool, int, float,
/// None, and lists/dicts of them at any depth - so it can be passed through
/// without a copy. Past `MAX_DEPTH` it answers false and lets the converter
/// report the depth (or the reference cycle) as an error.
fn is_json_ready(obj: &Bound<'_, PyAny>, depth: usize) -> bool {
    if is_clean_primitive(obj) {
        return true;
    }
    if depth >= MAX_DEPTH {
        return false;
    }
    if let Ok(list) = obj.cast::<PyList>() {
        return list.iter().all(|item| is_json_ready(&item, depth + 1));
    }
    if let Ok(dict) = obj.cast::<PyDict>() {
        return dict.iter().all(|(_, v)| is_json_ready(&v, depth + 1));
    }
    false
}

/// Record that the converter enters the container `obj`; see
/// `compression::enter_container` for the depth and cycle rules.
fn enter_container(obj: &Bound<'_, PyAny>, path: &mut Vec<usize>) -> PyResult<()> {
    let id = obj.as_ptr() as usize;
    if path.contains(&id) {
        return Err(pyo3::exceptions::PyValueError::new_err(
            "cannot convert a value that contains a reference cycle",
        ));
    }
    if path.len() >= MAX_DEPTH {
        return Err(pyo3::exceptions::PyValueError::new_err(format!(
            "cannot convert a value nested deeper than {MAX_DEPTH} levels"
        )));
    }
    path.push(id);
    Ok(())
}

/// Convert `obj` to JSON-safe Python values (UUID, datetime/date, Decimal,
/// Enum, bytes and objects with `__dict__` become str/primitives), at any
/// depth. Containers that are already JSON-ready are returned as they are.
fn convert_value(py: Python<'_>, obj: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
    convert_at(py, obj, &mut Vec::new())
}

fn convert_at(
    py: Python<'_>,
    obj: &Bound<'_, PyAny>,
    path: &mut Vec<usize>,
) -> PyResult<Py<PyAny>> {
    if is_clean_primitive(obj) {
        return Ok(obj.clone().unbind());
    }

    if let Ok(dict) = obj.cast::<PyDict>() {
        if is_json_ready(obj, path.len()) {
            return Ok(dict.clone().into_any().unbind());
        }
        enter_container(obj, path)?;
        let new_dict = PyDict::new(py);
        for (k, v) in dict.iter() {
            let converted = convert_at(py, &v, path)?;
            new_dict.set_item(k, converted)?;
        }
        path.pop();
        return Ok(new_dict.into_any().unbind());
    }

    if let Ok(pybytes) = obj.cast::<PyBytes>() {
        let raw: &[u8] = pybytes.as_bytes();
        if let Ok(s) = std::str::from_utf8(raw) {
            return Ok(PyString::new(py, s).into_any().unbind());
        }
        let s: String = raw.iter().map(|&b| b as char).collect();
        return Ok(PyString::new(py, &s).into_any().unbind());
    }

    // UUID (has `hex` attr that is a 32-char string)
    if obj.hasattr("hex")?
        && let Ok(hex_val) = obj.getattr("hex")
        && let Ok(hex_str) = hex_val.extract::<String>()
        && hex_str.len() == 32
    {
        let s = obj.str()?;
        return Ok(s.into_any().unbind());
    }

    // datetime/date (has isoformat + year)
    if obj.hasattr("isoformat")? && obj.hasattr("year")? {
        let iso = obj.call_method0("isoformat")?;
        return Ok(iso.unbind());
    }

    // Decimal -> its exact decimal string (a float would lose precision)
    if is_decimal(obj)? {
        return Ok(obj.str()?.into_any().unbind());
    }

    // Enum (has value + name)
    if obj.hasattr("value")? && obj.hasattr("name")? {
        enter_container(obj, path)?;
        let converted = convert_at(py, &obj.getattr("value")?, path)?;
        path.pop();
        return Ok(converted);
    }

    if let Ok(list) = obj.cast::<PyList>() {
        if is_json_ready(obj, path.len()) {
            return Ok(list.clone().into_any().unbind());
        }
        enter_container(obj, path)?;
        let new_list = PyList::empty(py);
        for item in list.iter() {
            let converted = convert_at(py, &item, path)?;
            new_list.append(converted)?;
        }
        path.pop();
        return Ok(new_list.into_any().unbind());
    }

    if let Ok(tuple) = obj.cast::<PyTuple>() {
        enter_container(obj, path)?;
        let new_list = PyList::empty(py);
        for item in tuple.iter() {
            let converted = convert_at(py, &item, path)?;
            new_list.append(converted)?;
        }
        path.pop();
        return Ok(new_list.into_any().unbind());
    }

    if obj.hasattr("__dict__")? {
        let dunder_dict = obj.getattr("__dict__")?;
        if let Ok(dict) = dunder_dict.cast::<PyDict>() {
            enter_container(obj, path)?;
            let converted = convert_at(py, dict.as_any(), path)?;
            path.pop();
            return Ok(converted);
        }
    }

    Ok(obj.clone().unbind())
}

fn ensure_str(py: Python<'_>, obj: &Bound<'_, PyAny>) -> PyResult<Py<PyAny>> {
    if let Ok(pybytes) = obj.cast::<PyBytes>() {
        let raw = pybytes.as_bytes();
        if let Ok(s) = std::str::from_utf8(raw) {
            return Ok(PyString::new(py, s).into_any().unbind());
        }
        let s: String = raw.iter().map(|&b| b as char).collect();
        return Ok(PyString::new(py, &s).into_any().unbind());
    }

    if obj.hasattr("hex")?
        && let Ok(hex_val) = obj.getattr("hex")
        && let Ok(hex_str) = hex_val.extract::<String>()
        && hex_str.len() == 32
    {
        let s = obj.str()?;
        return Ok(s.into_any().unbind());
    }

    if obj.hasattr("isoformat")? && obj.hasattr("year")? {
        let iso = obj.call_method0("isoformat")?;
        return Ok(iso.unbind());
    }

    if obj.hasattr("value")? && obj.hasattr("name")? {
        let val = obj.getattr("value")?;
        return Ok(val.unbind());
    }

    Ok(obj.clone().unbind())
}

#[inline]
fn dict_get_str(dict: &Bound<'_, PyDict>, key: &str) -> PyResult<Option<String>> {
    match dict.get_item(key)? {
        Some(val) if !val.is_none() => Ok(Some(val.str()?.to_string())),
        _ => Ok(None),
    }
}

#[inline]
fn dict_get<'py>(dict: &Bound<'py, PyDict>, key: &str) -> PyResult<Option<Bound<'py, PyAny>>> {
    match dict.get_item(key)? {
        Some(val) if !val.is_none() => Ok(Some(val)),
        _ => Ok(None),
    }
}

// ---------------------------------------------------------------------------
// Latency calculation
// ---------------------------------------------------------------------------

/// Parse an ISO 8601 timestamp string and compute milliseconds from then to now.
/// Returns None if parsing fails or the timestamp is not available.
fn compute_latency_ms(timestamp_str: &str) -> Option<i64> {
    // Handle 'Z' suffix -> '+00:00'
    let normalized = if let Some(stripped) = timestamp_str.strip_suffix('Z') {
        format!("{}+00:00", stripped)
    } else {
        timestamp_str.to_string()
    };

    // Try parsing with chrono
    if let Ok(dt) = DateTime::parse_from_rfc3339(&normalized) {
        let now = Utc::now();
        let delta = now.signed_duration_since(dt.with_timezone(&Utc));
        return Some(delta.num_milliseconds());
    }

    // Fallback: try parsing without timezone (assume UTC)
    if let Ok(dt) = chrono::NaiveDateTime::parse_from_str(timestamp_str, "%Y-%m-%dT%H:%M:%S%.f") {
        let utc_dt = dt.and_utc();
        let now = Utc::now();
        let delta = now.signed_duration_since(utc_dt);
        return Some(delta.num_milliseconds());
    }

    None
}

// ---------------------------------------------------------------------------
// Generic payload extraction
// ---------------------------------------------------------------------------

/// Generic payload extraction: convert all values to JSON-safe types.
/// If event has a `payload` key, use it; otherwise use the event itself.
/// Strips internal keys like `_metadata`.
fn extract_payload<'py>(
    py: Python<'py>,
    event: &Bound<'py, PyDict>,
) -> PyResult<Bound<'py, PyDict>> {
    // Check if there is a 'payload' key
    let source = match dict_get(event, "payload")? {
        Some(val) => {
            if let Ok(d) = val.cast::<PyDict>() {
                d.clone()
            } else {
                event.clone()
            }
        }
        None => event.clone(),
    };

    // Remove _metadata if present
    let result = PyDict::new(py);
    for (k, v) in source.iter() {
        let key_str = k.str()?.to_string();
        if key_str == "_metadata" {
            continue;
        }
        let converted = convert_value(py, &v)?;
        result.set_item(k, converted)?;
    }

    // Ensure event_type is set if type is provided
    let has_event_type = result.contains("event_type")?;
    if !has_event_type && let Some(type_val) = dict_get(&result, "type")? {
        result.set_item("event_type", type_val)?;
    }

    Ok(result)
}

// ---------------------------------------------------------------------------
// Main entry point: transform raw event dict -> wire envelope
// ---------------------------------------------------------------------------

/// Transform a raw event dictionary into a WSE wire envelope.
///
/// Input: arbitrary Python dict with event data, optional `_metadata`, `event_type`/`type`.
/// Output: `{t, id, ts, seq, p, v}` wire-format dict ready for JSON serialization.
///
/// This is the generic version: payload is extracted and converted without
/// domain-specific transforms. All Python types (UUID, datetime, Enum, bytes)
/// are converted to JSON-safe primitives.
#[pyfunction]
pub fn rust_transform_event<'py>(
    py: Python<'py>,
    event: &Bound<'py, PyDict>,
    sequence: i64,
    event_type_map: &Bound<'py, PyDict>,
) -> PyResult<Bound<'py, PyDict>> {
    // 0. Already transformed?
    let has_v = event.contains("v")?;
    let has_t = event.contains("t")?;
    let has_p = event.contains("p")?;
    let has_id = event.contains("id")?;
    let has_ts = event.contains("ts")?;

    if has_v && has_t && has_p && has_id && has_ts {
        if event.contains("seq")? {
            return Ok(event.clone());
        }
        // Never mutate the caller's dict: stamp the sequence on a copy.
        let stamped = event.copy()?;
        stamped.set_item("seq", sequence)?;
        return Ok(stamped);
    }

    // 1. Resolve event_type
    let raw_event_type: String = {
        let val = dict_get(event, "event_type")?.or(dict_get(event, "type")?);
        match val {
            Some(v) => {
                let converted: Py<PyAny> = ensure_str(py, &v)?;
                converted.bind(py).str()?.to_string()
            }
            None => "unknown".to_string(),
        }
    };

    let ws_event_type: String = match event_type_map.get_item(&raw_event_type)? {
        Some(mapped) => mapped.str()?.to_string(),
        None => raw_event_type.to_lowercase(),
    };

    // 2. Extract metadata
    let metadata: Option<Bound<'py, PyDict>> = match dict_get(event, "_metadata")? {
        Some(val) => val.cast::<PyDict>().ok().cloned(),
        None => None,
    };

    // 3. Compute latency
    let event_timestamp_str: Option<String> = {
        let from_meta = metadata
            .as_ref()
            .and_then(|m| dict_get_str(m, "timestamp").ok().flatten());
        let from_event = dict_get_str(event, "timestamp").ok().flatten();
        from_meta.or(from_event)
    };

    let event_latency_ms: Option<i64> = event_timestamp_str.as_deref().and_then(compute_latency_ms);

    // 4. Resolve event ID
    let event_id: String = {
        let from_meta = metadata
            .as_ref()
            .and_then(|m| dict_get(m, "event_id").ok().flatten());
        let from_event = dict_get(event, "event_id")?.filter(|v| !v.is_none());
        match from_meta.or(from_event) {
            Some(val) => {
                let converted: Py<PyAny> = ensure_str(py, &val)?;
                converted.bind(py).str()?.to_string()
            }
            None => Uuid::now_v7().to_string(),
        }
    };

    // 5. Resolve timestamp
    let timestamp: String = {
        let from_meta = metadata
            .as_ref()
            .and_then(|m| dict_get(m, "timestamp").ok().flatten());
        let from_event = dict_get(event, "timestamp")?.filter(|v| !v.is_none());
        match from_meta.or(from_event) {
            Some(val) => {
                let converted: Py<PyAny> = ensure_str(py, &val)?;
                converted.bind(py).str()?.to_string()
            }
            None => Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Micros, true),
        }
    };

    // 6. Generic payload extraction (convert all values to JSON-safe types)
    let payload = extract_payload(py, event)?;
    let payload_converted = convert_value(py, payload.as_any())?;

    // 7. Build wire envelope: c first, t second, v last
    let envelope = PyDict::new(py);

    // c first (category)
    if let Some(msg_cat) = dict_get(event, "c")? {
        envelope.set_item("c", msg_cat)?;
    } else if ws_event_type.contains("_snapshot") || ws_event_type.contains("snapshot_") {
        envelope.set_item("c", "S")?;
    } else {
        const WSE_TYPES: &[&str] = &[
            "server_ready",
            "snapshot_complete",
            "client_hello_ack",
            "connection_state_change",
            "error",
            "pong",
        ];
        if WSE_TYPES.contains(&ws_event_type.as_str()) {
            envelope.set_item("c", "WSE")?;
        } else {
            envelope.set_item("c", "U")?;
        }
    }

    // t second
    envelope.set_item("t", PyString::new(py, &ws_event_type))?;
    envelope.set_item("id", PyString::new(py, &event_id))?;
    envelope.set_item("ts", PyString::new(py, &timestamp))?;
    envelope.set_item("seq", sequence)?;
    envelope.set_item("p", payload_converted)?;
    envelope.set_item("v", 1)?;

    // Preserve original event type
    if raw_event_type != ws_event_type {
        envelope.set_item("original_event_type", PyString::new(py, &raw_event_type))?;
    }

    // 10. Latency
    if let Some(ms) = event_latency_ms {
        envelope.set_item("latency_ms", ms)?;
    }

    // 11. Optional fields
    let cid_from_meta = metadata
        .as_ref()
        .and_then(|m| dict_get_str(m, "correlation_id").ok().flatten());
    let cid_from_event = dict_get_str(event, "correlation_id")?.filter(|s| !s.is_empty());
    if let Some(cid) = cid_from_meta.or(cid_from_event) {
        envelope.set_item("cid", PyString::new(py, &cid))?;
    }

    let pri_from_meta = metadata
        .as_ref()
        .and_then(|m| dict_get(m, "priority").ok().flatten());
    let pri_from_event = dict_get(event, "pri")?.filter(|v| !v.is_none());
    if let Some(pri) = pri_from_meta.or(pri_from_event) {
        envelope.set_item("pri", pri)?;
    }

    {
        let ver_from_event = dict_get(event, "version")?;
        let ver_from_meta = metadata
            .as_ref()
            .and_then(|m| dict_get(m, "version").ok().flatten());
        match ver_from_event.or(ver_from_meta) {
            Some(v) => {
                if let Ok(n) = v.extract::<i64>() {
                    envelope.set_item("event_version", n)?;
                } else {
                    envelope.set_item("event_version", 1)?;
                }
            }
            None => {
                envelope.set_item("event_version", 1)?;
            }
        }
    }

    {
        let trace_from_meta = metadata
            .as_ref()
            .and_then(|m| dict_get_str(m, "trace_id").ok().flatten());
        let trace_from_event = dict_get_str(event, "trace_id")?.filter(|s| !s.is_empty());
        if let Some(trace_id) = trace_from_meta.or(trace_from_event) {
            envelope.set_item("trace_id", PyString::new(py, &trace_id))?;
        }
    }

    Ok(envelope)
}