Skip to main content

aion_server/api/
ws_subscription.rs

1//! WebSocket subscription request reading and JSON decoding.
2//!
3//! The first client frame on `/events/stream` is a JSON `SubscriptionRequest`.
4//! This module owns the tolerant decode of that frame: the canonical proto
5//! serde shape is accepted first, then the documented hand-written shapes
6//! (`per_workflow` / `filtered` / `firehose`, optionally wrapped in
7//! `{"subscription": ...}`).
8
9use aion_proto::{
10    ClusterSubscription, FilteredSubscription, FirehoseSubscription, PerWorkflowSubscription,
11    ProtoActivityId, ProtoWorkflowId, SubscriptionRequest, TranscriptSubscription, WireError,
12    subscription_request,
13};
14use axum::extract::ws::{Message, WebSocket};
15use serde_json::{Map, Value};
16
17use crate::error::ServerError;
18
19/// Read the first subscription frame from an accepted WebSocket.
20///
21/// Ping/pong frames are ignored while waiting. A malformed frame or a socket
22/// error is a decode failure the caller reports as one terminal error frame.
23///
24/// A clean close *before* any subscribe frame arrives — either an explicit
25/// `Close` frame or the stream ending (`recv` returns `None`) — is NOT an error:
26/// it is the normal lifecycle of a client that disconnects before subscribing
27/// (e.g. a React `StrictMode` double-mount whose first socket is torn down before
28/// it can send, or a page navigated away during the handshake). It is returned
29/// as `Ok(None)` so the caller ends the connection gracefully without logging a
30/// spurious warning or trying to write an error frame to an already-closing
31/// socket.
32///
33/// # Errors
34///
35/// Returns [`ServerError::Wire`] (`invalid_input`) only when the request frame
36/// is present but cannot be read or decoded.
37pub async fn read_subscription_request(
38    socket: &mut WebSocket,
39) -> Result<Option<SubscriptionRequest>, ServerError> {
40    loop {
41        // Stream ended before any subscribe frame: a benign pre-subscribe close.
42        let Some(message) = socket.recv().await else {
43            return Ok(None);
44        };
45        let message = message.map_err(|source| {
46            WireError::invalid_input(format!(
47                "failed to read websocket subscription request: {source}"
48            ))
49        })?;
50
51        match message {
52            Message::Text(text) => return decode_subscription_request(text.as_bytes()).map(Some),
53            Message::Binary(bytes) => return decode_subscription_request(&bytes).map(Some),
54            Message::Ping(_) | Message::Pong(_) => {}
55            // Explicit clean close before subscribing: benign, not an error.
56            Message::Close(_) => return Ok(None),
57        }
58    }
59}
60
61/// Decode a subscription request from raw frame bytes.
62///
63/// # Errors
64///
65/// Returns [`ServerError::Wire`] (`invalid_input`) when the bytes are not a
66/// recognizable subscription JSON object.
67pub fn decode_subscription_request(bytes: &[u8]) -> Result<SubscriptionRequest, ServerError> {
68    let value = serde_json::from_slice::<Value>(bytes).map_err(|source| {
69        WireError::invalid_input(format!("invalid websocket subscription JSON: {source}"))
70    })?;
71    decode_subscription_value(&value)
72}
73
74fn decode_subscription_value(value: &Value) -> Result<SubscriptionRequest, ServerError> {
75    if let Ok(request) = serde_json::from_value::<SubscriptionRequest>(value.clone()) {
76        if request.subscription.is_some() {
77            return Ok(request);
78        }
79    }
80
81    let subscription = value.get("subscription").unwrap_or(value);
82    let Some(subscription) = subscription.as_object() else {
83        return Err(
84            WireError::invalid_input("websocket subscription must be a JSON object").into(),
85        );
86    };
87
88    if let Some(value) = subscription.get("per_workflow") {
89        return Ok(SubscriptionRequest {
90            subscription: Some(subscription_request::Subscription::PerWorkflow(
91                decode_per_workflow_subscription(value)?,
92            )),
93        });
94    }
95    if let Some(value) = subscription.get("filtered") {
96        return Ok(SubscriptionRequest {
97            subscription: Some(subscription_request::Subscription::Filtered(
98                decode_filtered_subscription(value)?,
99            )),
100        });
101    }
102    if let Some(value) = subscription.get("firehose") {
103        return Ok(SubscriptionRequest {
104            subscription: Some(subscription_request::Subscription::Firehose(
105                decode_firehose_subscription(value)?,
106            )),
107        });
108    }
109    if let Some(value) = subscription.get("cluster") {
110        return Ok(SubscriptionRequest {
111            subscription: Some(subscription_request::Subscription::Cluster(
112                decode_cluster_subscription(value)?,
113            )),
114        });
115    }
116    if let Some(value) = subscription.get("transcript") {
117        return Ok(SubscriptionRequest {
118            subscription: Some(subscription_request::Subscription::Transcript(
119                decode_transcript_subscription(value)?,
120            )),
121        });
122    }
123
124    Err(WireError::invalid_input(
125        "websocket subscription must contain per_workflow, filtered, firehose, cluster, or transcript",
126    )
127    .into())
128}
129
130fn decode_per_workflow_subscription(value: &Value) -> Result<PerWorkflowSubscription, ServerError> {
131    let object = subscription_object(value, "per-workflow")?;
132    Ok(PerWorkflowSubscription {
133        namespace: required_string(object, "namespace", "per-workflow subscription")?.to_owned(),
134        workflow_id: Some(decode_workflow_id_value(
135            object.get("workflow_id").ok_or_else(|| {
136                WireError::invalid_input("per-workflow subscription requires workflow_id")
137            })?,
138        )?),
139        resume_from_seq: decode_resume_from_seq(object)?,
140    })
141}
142
143/// Decode the optional resume cursor. Presence only: range validation against
144/// the recorded history head happens after the namespace guard verdict, in
145/// `stream::resume`, so decoding can never leak existence information.
146fn decode_resume_from_seq(object: &Map<String, Value>) -> Result<Option<u64>, ServerError> {
147    match object.get("resume_from_seq") {
148        None | Some(Value::Null) => Ok(None),
149        Some(value) => value.as_u64().map(Some).ok_or_else(|| {
150            WireError::invalid_input(
151                "per-workflow subscription resume_from_seq must be an unsigned integer",
152            )
153            .into()
154        }),
155    }
156}
157
158fn decode_filtered_subscription(value: &Value) -> Result<FilteredSubscription, ServerError> {
159    let object = subscription_object(value, "filtered")?;
160    let status = match object.get("status") {
161        Some(Value::String(status)) => Some(decode_status_name(status)?),
162        Some(Value::Number(status)) => status.as_i64().and_then(|value| i32::try_from(value).ok()),
163        Some(Value::Null) | None => None,
164        Some(_other) => None,
165    };
166    Ok(FilteredSubscription {
167        namespace: required_string(object, "namespace", "filtered subscription")?.to_owned(),
168        workflow_type: object
169            .get("workflow_type")
170            .and_then(Value::as_str)
171            .map(str::to_owned),
172        status,
173        namespace_selector: object
174            .get("namespace_selector")
175            .and_then(Value::as_str)
176            .map(str::to_owned),
177    })
178}
179
180/// Decode the WS3 cluster subscription. The only field is the optional
181/// `after_seq` resume cursor (presence-only; `0`/absent both request the full
182/// in-flight backlog). The cluster subscription carries no namespace — it is
183/// deployment-scoped and authorized by the caller's deploy grant.
184fn decode_cluster_subscription(value: &Value) -> Result<ClusterSubscription, ServerError> {
185    // An empty object `{}` is valid (after_seq defaults to 0). A bare absent
186    // value object is also accepted.
187    let after_seq = match value.as_object().and_then(|object| object.get("after_seq")) {
188        None | Some(Value::Null) => 0,
189        Some(seq) => seq.as_u64().ok_or_else(|| {
190            WireError::invalid_input("cluster subscription after_seq must be an unsigned integer")
191        })?,
192    };
193    Ok(ClusterSubscription { after_seq })
194}
195
196/// Decode the NOI-5b transcript subscription. Namespace-scoped like the
197/// per-workflow arm: it carries `namespace` + `workflow_id`, plus the
198/// `activity_id`/`attempt` axes that pin the `O`-keyspace stream, and an optional
199/// `after_seq` resume cursor (presence-only; range/validity is irrelevant since
200/// `store_seq` is a durable read that returns an empty tail past the head).
201fn decode_transcript_subscription(value: &Value) -> Result<TranscriptSubscription, ServerError> {
202    let object = subscription_object(value, "transcript")?;
203    let workflow_id = decode_workflow_id_value(object.get("workflow_id").ok_or_else(|| {
204        WireError::invalid_input("transcript subscription requires workflow_id")
205    })?)?;
206    let activity_id = decode_activity_id_value(object.get("activity_id").ok_or_else(|| {
207        WireError::invalid_input("transcript subscription requires activity_id")
208    })?)?;
209    let attempt = decode_attempt(object)?;
210    Ok(TranscriptSubscription {
211        namespace: required_string(object, "namespace", "transcript subscription")?.to_owned(),
212        workflow_id: Some(workflow_id),
213        activity_id: Some(activity_id),
214        attempt,
215        after_seq: decode_after_seq(object)?,
216    })
217}
218
219/// Decode the transcript `activity_id`: either a bare unsigned sequence position
220/// or the structured `{ "sequence_position": n }` proto shape.
221fn decode_activity_id_value(value: &Value) -> Result<ProtoActivityId, ServerError> {
222    if let Some(sequence_position) = value.as_u64() {
223        return Ok(ProtoActivityId { sequence_position });
224    }
225    serde_json::from_value::<ProtoActivityId>(value.clone()).map_err(|source| {
226        WireError::invalid_input(format!(
227            "invalid transcript subscription activity_id: {source}"
228        ))
229        .into()
230    })
231}
232
233/// Decode the required transcript `attempt` axis as a `u32`.
234fn decode_attempt(object: &Map<String, Value>) -> Result<u32, ServerError> {
235    match object.get("attempt") {
236        // Absent attempt defaults to 0 (the first attempt's stream), matching the
237        // envelope's default attempt for a not-yet-retried activity.
238        None | Some(Value::Null) => Ok(0),
239        Some(value) => value
240            .as_u64()
241            .and_then(|attempt| u32::try_from(attempt).ok())
242            .ok_or_else(|| {
243                WireError::invalid_input(
244                    "transcript subscription attempt must be an unsigned 32-bit integer",
245                )
246                .into()
247            }),
248    }
249}
250
251/// Decode the optional transcript resume cursor `after_seq` (presence-only).
252fn decode_after_seq(object: &Map<String, Value>) -> Result<Option<u64>, ServerError> {
253    match object.get("after_seq") {
254        None | Some(Value::Null) => Ok(None),
255        Some(value) => value.as_u64().map(Some).ok_or_else(|| {
256            WireError::invalid_input(
257                "transcript subscription after_seq must be an unsigned integer",
258            )
259            .into()
260        }),
261    }
262}
263
264fn decode_firehose_subscription(value: &Value) -> Result<FirehoseSubscription, ServerError> {
265    let object = subscription_object(value, "firehose")?;
266    let namespace = object
267        .get("namespace")
268        .or_else(|| object.get("namespace_selector"))
269        .and_then(Value::as_str)
270        .ok_or_else(|| WireError::invalid_input("firehose subscription requires namespace"))?;
271    Ok(FirehoseSubscription {
272        namespace: namespace.to_owned(),
273    })
274}
275
276fn subscription_object<'a>(
277    value: &'a Value,
278    subscription_name: &str,
279) -> Result<&'a Map<String, Value>, ServerError> {
280    value.as_object().ok_or_else(|| {
281        WireError::invalid_input(format!(
282            "{subscription_name} subscription must be a JSON object"
283        ))
284        .into()
285    })
286}
287
288fn required_string<'a>(
289    object: &'a Map<String, Value>,
290    key: &str,
291    context: &str,
292) -> Result<&'a str, ServerError> {
293    object
294        .get(key)
295        .and_then(Value::as_str)
296        .ok_or_else(|| WireError::invalid_input(format!("{context} requires {key}")).into())
297}
298
299fn decode_workflow_id_value(value: &Value) -> Result<ProtoWorkflowId, ServerError> {
300    if let Some(uuid) = value.as_str() {
301        return Ok(ProtoWorkflowId {
302            uuid: uuid.to_owned(),
303        });
304    }
305    serde_json::from_value::<ProtoWorkflowId>(value.clone()).map_err(|source| {
306        WireError::invalid_input(format!(
307            "invalid per-workflow subscription workflow_id: {source}"
308        ))
309        .into()
310    })
311}
312
313fn decode_status_name(status: &str) -> Result<i32, ServerError> {
314    match status {
315        "running" | "Running" => Ok(aion_proto::ProtoWorkflowStatus::Running as i32),
316        "completed" | "Completed" => Ok(aion_proto::ProtoWorkflowStatus::Completed as i32),
317        "failed" | "Failed" => Ok(aion_proto::ProtoWorkflowStatus::Failed as i32),
318        "cancelled" | "Cancelled" | "canceled" | "Canceled" => {
319            Ok(aion_proto::ProtoWorkflowStatus::Cancelled as i32)
320        }
321        "timed_out" | "TimedOut" => Ok(aion_proto::ProtoWorkflowStatus::TimedOut as i32),
322        "continued_as_new" | "ContinuedAsNew" => {
323            Ok(aion_proto::ProtoWorkflowStatus::ContinuedAsNew as i32)
324        }
325        "paused" | "Paused" => Ok(aion_proto::ProtoWorkflowStatus::Paused as i32),
326        other => Err(WireError::invalid_input(format!(
327            "invalid workflow status in websocket subscription: {other}"
328        ))
329        .into()),
330    }
331}
332
333#[cfg(test)]
334mod tests {
335    use aion_proto::{WireErrorCode, subscription_request};
336    use serde_json::json;
337
338    use super::decode_subscription_request;
339    use crate::error::ServerError;
340
341    fn decode(value: &serde_json::Value) -> Result<aion_proto::SubscriptionRequest, ServerError> {
342        decode_subscription_request(value.to_string().as_bytes())
343    }
344
345    fn per_workflow(
346        request: aion_proto::SubscriptionRequest,
347    ) -> Result<aion_proto::PerWorkflowSubscription, Box<dyn std::error::Error>> {
348        match request.subscription {
349            Some(subscription_request::Subscription::PerWorkflow(subscription)) => Ok(subscription),
350            other => Err(format!("expected a per-workflow subscription, got {other:?}").into()),
351        }
352    }
353
354    #[test]
355    fn per_workflow_resume_from_seq_is_decoded() -> Result<(), Box<dyn std::error::Error>> {
356        let workflow_id = uuid::Uuid::from_u128(7).to_string();
357        let request = decode(&json!({
358            "per_workflow": {
359                "namespace": "tenant-a",
360                "workflow_id": workflow_id,
361                "resume_from_seq": 42,
362            }
363        }))?;
364
365        assert_eq!(per_workflow(request)?.resume_from_seq, Some(42));
366        Ok(())
367    }
368
369    #[test]
370    fn per_workflow_resume_from_seq_zero_passes_decode_for_post_guard_validation()
371    -> Result<(), Box<dyn std::error::Error>> {
372        // Decode is presence-only; the 0-is-invalid range check belongs after
373        // the namespace guard so probes can never distinguish existence.
374        let request = decode(&json!({
375            "per_workflow": {
376                "namespace": "tenant-a",
377                "workflow_id": uuid::Uuid::from_u128(7).to_string(),
378                "resume_from_seq": 0,
379            }
380        }))?;
381
382        assert_eq!(per_workflow(request)?.resume_from_seq, Some(0));
383        Ok(())
384    }
385
386    #[test]
387    fn per_workflow_resume_from_seq_absent_or_null_is_none()
388    -> Result<(), Box<dyn std::error::Error>> {
389        let workflow_id = uuid::Uuid::from_u128(7).to_string();
390        let absent = decode(&json!({
391            "per_workflow": { "namespace": "tenant-a", "workflow_id": workflow_id }
392        }))?;
393        let null = decode(&json!({
394            "per_workflow": {
395                "namespace": "tenant-a",
396                "workflow_id": workflow_id,
397                "resume_from_seq": null,
398            }
399        }))?;
400
401        assert_eq!(per_workflow(absent)?.resume_from_seq, None);
402        assert_eq!(per_workflow(null)?.resume_from_seq, None);
403        Ok(())
404    }
405
406    #[test]
407    fn per_workflow_resume_from_seq_rejects_non_unsigned_values() {
408        for bad in [json!(-1), json!(1.5), json!("7")] {
409            let result = decode(&json!({
410                "per_workflow": {
411                    "namespace": "tenant-a",
412                    "workflow_id": uuid::Uuid::from_u128(7).to_string(),
413                    "resume_from_seq": bad,
414                }
415            }));
416            let error = result.err().map(|error| error.to_wire_error());
417            assert_eq!(
418                error.as_ref().map(|error| error.code),
419                Some(WireErrorCode::InvalidInput),
420                "expected invalid_input, got {error:?}"
421            );
422        }
423    }
424
425    #[test]
426    fn wrapped_subscription_shape_is_accepted() -> Result<(), Box<dyn std::error::Error>> {
427        let request = decode(&json!({
428            "subscription": {
429                "per_workflow": {
430                    "namespace": "tenant-a",
431                    "workflow_id": { "uuid": uuid::Uuid::from_u128(7).to_string() },
432                    "resume_from_seq": 3,
433                }
434            }
435        }))?;
436
437        let subscription = per_workflow(request)?;
438        assert_eq!(subscription.namespace, "tenant-a");
439        assert_eq!(subscription.resume_from_seq, Some(3));
440        Ok(())
441    }
442
443    #[test]
444    fn filtered_and_firehose_shapes_still_decode() -> Result<(), Box<dyn std::error::Error>> {
445        let filtered = decode(&json!({
446            "filtered": { "namespace": "tenant-a", "status": "Completed" }
447        }))?;
448        let firehose = decode(&json!({ "firehose": { "namespace": "tenant-a" } }))?;
449
450        assert!(matches!(
451            filtered.subscription,
452            Some(subscription_request::Subscription::Filtered(_))
453        ));
454        assert!(matches!(
455            firehose.subscription,
456            Some(subscription_request::Subscription::Firehose(_))
457        ));
458        Ok(())
459    }
460
461    /// NOI-5b: the transcript arm decodes its namespace + workflow/activity/
462    /// attempt axes and the optional `after_seq` cursor. A bare unsigned
463    /// `activity_id` and an absent `attempt` (defaulting to 0) are both accepted.
464    #[test]
465    fn transcript_subscription_decodes_axes_and_cursor() -> Result<(), Box<dyn std::error::Error>> {
466        let workflow_id = uuid::Uuid::from_u128(7).to_string();
467        let request = decode(&json!({
468            "transcript": {
469                "namespace": "tenant-a",
470                "workflow_id": workflow_id,
471                "activity_id": 3,
472                "attempt": 2,
473                "after_seq": 5,
474            }
475        }))?;
476        let Some(subscription_request::Subscription::Transcript(transcript)) = request.subscription
477        else {
478            return Err("expected a transcript subscription".into());
479        };
480        assert_eq!(transcript.namespace, "tenant-a");
481        assert_eq!(
482            transcript.activity_id.map(|id| id.sequence_position),
483            Some(3)
484        );
485        assert_eq!(transcript.attempt, 2);
486        assert_eq!(transcript.after_seq, Some(5));
487        Ok(())
488    }
489
490    #[test]
491    fn transcript_subscription_defaults_attempt_and_cursor()
492    -> Result<(), Box<dyn std::error::Error>> {
493        let request = decode(&json!({
494            "transcript": {
495                "namespace": "tenant-a",
496                "workflow_id": uuid::Uuid::from_u128(7).to_string(),
497                "activity_id": 3,
498            }
499        }))?;
500        let Some(subscription_request::Subscription::Transcript(transcript)) = request.subscription
501        else {
502            return Err("expected a transcript subscription".into());
503        };
504        assert_eq!(transcript.attempt, 0, "absent attempt defaults to 0");
505        assert_eq!(
506            transcript.after_seq, None,
507            "absent after_seq is a fresh subscriber"
508        );
509        Ok(())
510    }
511
512    #[test]
513    fn transcript_subscription_requires_activity_id() {
514        let error = decode(&json!({
515            "transcript": {
516                "namespace": "tenant-a",
517                "workflow_id": uuid::Uuid::from_u128(7).to_string(),
518            }
519        }))
520        .err()
521        .map(|error| error.to_wire_error());
522        assert_eq!(
523            error.map(|error| error.code),
524            Some(WireErrorCode::InvalidInput)
525        );
526    }
527
528    #[test]
529    fn unknown_subscription_shape_is_invalid_input() {
530        let error = decode(&json!({ "mystery": {} }))
531            .err()
532            .map(|error| error.to_wire_error());
533        assert_eq!(
534            error.map(|error| error.code),
535            Some(WireErrorCode::InvalidInput)
536        );
537    }
538}