Skip to main content

dora_message/
ws_protocol.rs

1//! WebSocket message protocol for the control plane.
2//!
3//! Three message types over JSON text frames:
4//!
5//! - **Request** (client -> server): `{"id": "uuid", "method": "...", "params": {...}}`
6//! - **Response** (server -> client): `{"id": "uuid", "result": {...}}` or `{"id": "uuid", "error": "..."}`
7//! - **Event** (either direction): `{"event": "...", "payload": {...}}`
8
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11use uuid::Uuid;
12
13/// A request from client to server, expecting a response with the same `id`.
14#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct WsRequest {
16    pub id: Uuid,
17    pub method: String,
18    pub params: Value,
19}
20
21/// A response from server to client, matching a request `id`.
22///
23/// # Serde invariant
24///
25/// `result: Some(Value::Null)` and `result: None` are **equivalent for a
26/// reader**. `None` serializes without a `result` field and `Some(Null)` as
27/// `"result":null`, but both deserialize to `None` (the standard serde rule
28/// that JSON `null` becomes `None` for `Option<T>`), so the distinction does
29/// not survive a round trip. This is intentional and matches JSON-RPC
30/// convention. Pinned by a unit test below
31/// (`ws_response_some_null_equals_none_on_wire`).
32///
33/// If you need to distinguish "no result" from "result is JSON null"
34/// across the wire, change the field type to `Option<Option<Value>>`
35/// and use `serde_with::rust::double_option`. This is a deliberately
36/// non-default choice; do not make it without coordination.
37#[derive(Debug, Clone, Serialize, Deserialize)]
38pub struct WsResponse {
39    pub id: Uuid,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub result: Option<Value>,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub error: Option<String>,
44}
45
46impl WsResponse {
47    pub fn ok(id: Uuid, result: Value) -> Self {
48        Self {
49            id,
50            result: Some(result),
51            error: None,
52        }
53    }
54
55    pub fn err(id: Uuid, error: String) -> Self {
56        Self {
57            id,
58            result: None,
59            error: Some(error),
60        }
61    }
62}
63
64/// A fire-and-forget event in either direction.
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct WsEvent {
67    pub event: String,
68    pub payload: Value,
69}
70
71/// Discriminated union for parsing any incoming WS text frame.
72///
73/// Uses `#[serde(untagged)]` which tries variants in order.
74/// Discriminating fields (order matters):
75/// 1. `Request` — matched first because it has a required `method` field
76/// 2. `Response` — has `id` + optional `result`/`error` (no `method`)
77/// 3. `Event` — has `event` field, no `id` or `method`
78///
79/// A message with both `method` and `result` would match `Request`.
80/// This is correct because responses never have a `method` field.
81#[derive(Debug, Clone, Serialize, Deserialize)]
82#[serde(untagged)]
83pub enum WsMessage {
84    Request(WsRequest),
85    Response(WsResponse),
86    Event(WsEvent),
87}
88
89#[cfg(test)]
90mod tests {
91    use super::*;
92    use serde_json::json;
93
94    #[test]
95    fn ws_request_roundtrip() {
96        let id = Uuid::new_v4();
97        let req = WsRequest {
98            id,
99            method: "control".into(),
100            params: json!({"foo": 42}),
101        };
102        let json = serde_json::to_string(&req).unwrap();
103        let decoded: WsRequest = serde_json::from_str(&json).unwrap();
104        assert_eq!(decoded.id, id);
105        assert_eq!(decoded.method, "control");
106        assert_eq!(decoded.params, json!({"foo": 42}));
107    }
108
109    #[test]
110    fn ws_response_ok_roundtrip() {
111        let id = Uuid::new_v4();
112        let resp = WsResponse::ok(id, json!({"status": "running"}));
113        let json = serde_json::to_string(&resp).unwrap();
114        let decoded: WsResponse = serde_json::from_str(&json).unwrap();
115        assert_eq!(decoded.id, id);
116        assert_eq!(decoded.result, Some(json!({"status": "running"})));
117        assert!(decoded.error.is_none());
118    }
119
120    #[test]
121    fn ws_response_err_roundtrip() {
122        let id = Uuid::new_v4();
123        let resp = WsResponse::err(id, "something failed".into());
124        let json = serde_json::to_string(&resp).unwrap();
125        let decoded: WsResponse = serde_json::from_str(&json).unwrap();
126        assert_eq!(decoded.id, id);
127        assert!(decoded.result.is_none());
128        assert_eq!(decoded.error.as_deref(), Some("something failed"));
129    }
130
131    #[test]
132    fn ws_event_roundtrip() {
133        let evt = WsEvent {
134            event: "log".into(),
135            payload: json!({"line": "hello"}),
136        };
137        let json = serde_json::to_string(&evt).unwrap();
138        let decoded: WsEvent = serde_json::from_str(&json).unwrap();
139        assert_eq!(decoded.event, "log");
140        assert_eq!(decoded.payload, json!({"line": "hello"}));
141    }
142
143    #[test]
144    fn ws_message_dispatches_to_response() {
145        let id = Uuid::new_v4();
146        let json = json!({"id": id, "result": {"ok": true}}).to_string();
147        let msg: WsMessage = serde_json::from_str(&json).unwrap();
148        assert!(matches!(msg, WsMessage::Response(_)));
149    }
150
151    #[test]
152    fn ws_message_dispatches_to_event() {
153        let json = json!({"event": "log", "payload": {}}).to_string();
154        let msg: WsMessage = serde_json::from_str(&json).unwrap();
155        assert!(matches!(msg, WsMessage::Event(_)));
156    }
157
158    #[test]
159    fn ws_response_ok_helper() {
160        let id = Uuid::new_v4();
161        let resp = WsResponse::ok(id, json!("done"));
162        assert_eq!(resp.result, Some(json!("done")));
163        assert!(resp.error.is_none());
164    }
165
166    #[test]
167    fn ws_response_err_helper() {
168        let id = Uuid::new_v4();
169        let resp = WsResponse::err(id, "bad".into());
170        assert!(resp.result.is_none());
171        assert_eq!(resp.error.as_deref(), Some("bad"));
172    }
173
174    #[test]
175    fn ws_request_nil_id_rejected() {
176        // Malformed JSON (missing required fields) -> serde error
177        let bad = r#"{"id": null}"#;
178        assert!(serde_json::from_str::<WsRequest>(bad).is_err());
179    }
180
181    #[test]
182    fn ws_message_unknown_shape() {
183        // JSON that matches neither Request, Response, nor Event
184        let bad = json!({"random": "stuff"}).to_string();
185        assert!(serde_json::from_str::<WsMessage>(&bad).is_err());
186    }
187
188    /// Pins the documented serde invariant on `WsResponse`:
189    /// `result: Some(Value::Null)` and `result: None` are equivalent on the
190    /// wire. A `Some(Null)` value serializes as `result: null` (because
191    /// `skip_serializing_if = "Option::is_none"` only checks the outer
192    /// Option), and serde's default Option<T> deserializer turns JSON
193    /// `null` back into `None`. The roundtrip is therefore lossy in one
194    /// direction by design.
195    ///
196    /// Discovered by property testing
197    /// (`prop_response_roundtrip` failure on commit fddbe7b). Documented
198    /// in `WsResponse`'s doc comment as intentional. Do NOT delete this
199    /// test without updating the docs and the proptest strategy.
200    #[test]
201    fn ws_response_some_null_equals_none_on_wire() {
202        let id = Uuid::new_v4();
203        let with_some_null = WsResponse {
204            id,
205            result: Some(serde_json::Value::Null),
206            error: None,
207        };
208        let with_none = WsResponse {
209            id,
210            result: None,
211            error: None,
212        };
213
214        // Both serialize the same way: result field is omitted entirely
215        // for None, and serialized as `null` for Some(Null). They are
216        // structurally different but indistinguishable as JSON values.
217        let json_some = serde_json::to_string(&with_some_null).unwrap();
218        let json_none = serde_json::to_string(&with_none).unwrap();
219        assert!(
220            json_some.contains("\"result\":null") || json_some == json_none,
221            "expected Some(Null) to serialize as result:null or be omitted; got {json_some}"
222        );
223
224        // Both deserialize to the same in-memory representation: None.
225        let from_some: WsResponse = serde_json::from_str(&json_some).unwrap();
226        let from_none: WsResponse = serde_json::from_str(&json_none).unwrap();
227        assert_eq!(from_some.result, None, "Some(Null) must round-trip to None");
228        assert_eq!(from_none.result, None);
229    }
230
231    // --- Property tests (proptest) ---
232    //
233    // These tests exercise the JSON serde roundtrip for each WsMessage
234    // variant over generated inputs. The key properties are:
235    //
236    //   1. serialize -> deserialize is a fixed point for each variant
237    //      (the value is preserved)
238    //   2. when wrapped in the untagged WsMessage enum, the original
239    //      variant is preserved across roundtrip (no variant escaping)
240    //
241    // These catch two classes of bugs that the hand-written tests miss:
242    //   - variant confusion in untagged enums (a Request deserializing
243    //     as a Response, or similar)
244    //   - field-ordering sensitivity in serde
245    //   - edge cases in string/number/array handling that nobody
246    //     thought to add to the hand-written suite
247
248    use proptest::prelude::*;
249
250    /// Strategy for arbitrary JSON values with bounded recursion depth.
251    fn arb_json_value() -> impl Strategy<Value = serde_json::Value> {
252        use serde_json::Value;
253        let leaf = prop_oneof![
254            Just(Value::Null),
255            any::<bool>().prop_map(Value::Bool),
256            any::<i64>().prop_map(|n| Value::Number(n.into())),
257            // f64 strategy: only generate values that are guaranteed to
258            // round-trip exactly through JSON. Arbitrary f64s near the edge
259            // of precision (e.g., 1e120) lose 1 ULP through the string
260            // representation; that's a property of JSON itself, not dora.
261            // We restrict to values within the i32 range cast to f64, which
262            // are always representable losslessly.
263            (any::<i32>()).prop_map(|n| serde_json::Number::from_f64(f64::from(n))
264                .map(Value::Number)
265                .unwrap_or(Value::Null)),
266            "[a-zA-Z0-9 _-]{0,32}".prop_map(Value::String),
267        ];
268        leaf.prop_recursive(
269            3,  // depth
270            16, // max total nodes
271            4,  // items per collection
272            |inner| {
273                prop_oneof![
274                    prop::collection::vec(inner.clone(), 0..4).prop_map(Value::Array),
275                    prop::collection::hash_map("[a-zA-Z][a-zA-Z0-9_]{0,8}", inner, 0..4)
276                        .prop_map(|m| Value::Object(m.into_iter().collect())),
277                ]
278            },
279        )
280    }
281
282    fn arb_method() -> impl Strategy<Value = String> {
283        "[a-z][a-z_]{0,16}".prop_map(|s| s.to_string())
284    }
285
286    fn arb_event() -> impl Strategy<Value = String> {
287        "[a-z][a-z_]{0,16}".prop_map(|s| s.to_string())
288    }
289
290    fn arb_ws_request() -> impl Strategy<Value = WsRequest> {
291        (any::<u128>(), arb_method(), arb_json_value()).prop_map(|(id, method, params)| WsRequest {
292            id: Uuid::from_u128(id),
293            method,
294            params,
295        })
296    }
297
298    fn arb_ws_response() -> impl Strategy<Value = WsResponse> {
299        // Filter `Some(Value::Null)` out of the `result` field: by the
300        // documented serde invariant on WsResponse, `Some(Null)` is
301        // equivalent to `None` on the wire and would not survive a
302        // structural roundtrip. The equivalence itself is pinned by the
303        // `ws_response_some_null_equals_none_on_wire` unit test, so this
304        // filter does not hide a bug — it scopes the property to inputs
305        // that are *expected* to roundtrip identically.
306        (
307            any::<u128>(),
308            prop::option::of(arb_json_value().prop_filter("not Value::Null", |v| !v.is_null())),
309            prop::option::of("[a-z0-9 ]{0,32}".prop_map(|s| s.to_string())),
310        )
311            .prop_map(|(id, result, error)| WsResponse {
312                id: Uuid::from_u128(id),
313                result,
314                error,
315            })
316    }
317
318    fn arb_ws_event() -> impl Strategy<Value = WsEvent> {
319        (arb_event(), arb_json_value()).prop_map(|(event, payload)| WsEvent { event, payload })
320    }
321
322    proptest! {
323        #![proptest_config(ProptestConfig::with_cases(2000))]
324
325        /// WsRequest roundtrips through JSON.
326        #[test]
327        fn prop_request_roundtrip(req in arb_ws_request()) {
328            let json = serde_json::to_string(&req).unwrap();
329            let decoded: WsRequest = serde_json::from_str(&json)
330                .expect("request must deserialize");
331            prop_assert_eq!(decoded.id, req.id);
332            prop_assert_eq!(decoded.method, req.method);
333            prop_assert_eq!(decoded.params, req.params);
334        }
335
336        /// WsResponse roundtrips through JSON.
337        #[test]
338        fn prop_response_roundtrip(resp in arb_ws_response()) {
339            let json = serde_json::to_string(&resp).unwrap();
340            let decoded: WsResponse = serde_json::from_str(&json)
341                .expect("response must deserialize");
342            prop_assert_eq!(decoded.id, resp.id);
343            prop_assert_eq!(decoded.result, resp.result);
344            prop_assert_eq!(decoded.error, resp.error);
345        }
346
347        /// WsEvent roundtrips through JSON.
348        #[test]
349        fn prop_event_roundtrip(evt in arb_ws_event()) {
350            let json = serde_json::to_string(&evt).unwrap();
351            let decoded: WsEvent = serde_json::from_str(&json)
352                .expect("event must deserialize");
353            prop_assert_eq!(decoded.event, evt.event);
354            prop_assert_eq!(decoded.payload, evt.payload);
355        }
356
357        /// A WsRequest wrapped in WsMessage must round-trip as WsMessage::Request.
358        /// This is the critical property for the untagged enum: variants must
359        /// not "escape" to other variants across a serde roundtrip.
360        #[test]
361        fn prop_message_request_does_not_escape(req in arb_ws_request()) {
362            let msg = WsMessage::Request(req.clone());
363            let json = serde_json::to_string(&msg).unwrap();
364            let decoded: WsMessage = serde_json::from_str(&json)
365                .expect("wsmessage must deserialize");
366            match decoded {
367                WsMessage::Request(r) => {
368                    prop_assert_eq!(r.id, req.id);
369                    prop_assert_eq!(r.method, req.method);
370                    prop_assert_eq!(r.params, req.params);
371                }
372                other => prop_assert!(
373                    false,
374                    "Request escaped to other variant: {:?}",
375                    other
376                ),
377            }
378        }
379
380        /// A WsResponse wrapped in WsMessage must round-trip as WsMessage::Response.
381        #[test]
382        fn prop_message_response_does_not_escape(resp in arb_ws_response()) {
383            let msg = WsMessage::Response(resp.clone());
384            let json = serde_json::to_string(&msg).unwrap();
385            let decoded: WsMessage = serde_json::from_str(&json)
386                .expect("wsmessage must deserialize");
387            match decoded {
388                WsMessage::Response(r) => {
389                    prop_assert_eq!(r.id, resp.id);
390                    prop_assert_eq!(r.result, resp.result);
391                    prop_assert_eq!(r.error, resp.error);
392                }
393                other => prop_assert!(
394                    false,
395                    "Response escaped to other variant: {:?}",
396                    other
397                ),
398            }
399        }
400
401        /// A WsEvent wrapped in WsMessage must round-trip as WsMessage::Event.
402        #[test]
403        fn prop_message_event_does_not_escape(evt in arb_ws_event()) {
404            let msg = WsMessage::Event(evt.clone());
405            let json = serde_json::to_string(&msg).unwrap();
406            let decoded: WsMessage = serde_json::from_str(&json)
407                .expect("wsmessage must deserialize");
408            match decoded {
409                WsMessage::Event(e) => {
410                    prop_assert_eq!(e.event, evt.event);
411                    prop_assert_eq!(e.payload, evt.payload);
412                }
413                other => prop_assert!(
414                    false,
415                    "Event escaped to other variant: {:?}",
416                    other
417                ),
418            }
419        }
420    }
421}