Skip to main content

mojentic/realtime/
schemas.rs

1//! Boundary handling for OpenAI Realtime API server events.
2//!
3//! Tolerates provider drift: unknown event types and unknown fields pass
4//! through verbatim. Typeless payloads are tagged with `type: "unknown"`
5//! so the session driver can ignore them deterministically. Matches the
6//! Python / Elixir / TypeScript boundary behaviour.
7
8use serde_json::Value;
9
10/// Best-effort parse: returns the raw value as-is when it has a `type`
11/// field, otherwise tags it `unknown` so the session driver's match
12/// arm sees a stable shape.
13pub fn parse_server_event(raw: Value) -> Value {
14    if raw.get("type").and_then(|v| v.as_str()).is_some() {
15        raw
16    } else {
17        Value::Object(serde_json::Map::from_iter([(
18            "type".to_string(),
19            Value::String("unknown".to_string()),
20        )]))
21    }
22}
23
24#[cfg(test)]
25mod tests {
26    use super::*;
27    use serde_json::json;
28
29    #[test]
30    fn passes_through_known_events() {
31        let raw = json!({"type": "session.created", "session": {"id": "s1"}});
32        assert_eq!(parse_server_event(raw.clone()), raw);
33    }
34
35    #[test]
36    fn unknown_marker_for_typeless() {
37        let parsed = parse_server_event(json!({"no_type": true}));
38        assert_eq!(parsed, json!({"type": "unknown"}));
39    }
40
41    #[test]
42    fn passes_through_unknown_types() {
43        let raw = json!({"type": "session.something_new"});
44        assert_eq!(parse_server_event(raw.clone()), raw);
45    }
46}