Skip to main content

zaun_community_protocol/client/session/
receive.rs

1//! Receiving: transport text → envelopes → cursor-ordered events (§5, §9.4, §10).
2
3use super::{Session, SessionState};
4use crate::client::cursors::{Held, Key, Offer};
5use crate::client::inbound::{self, Envelope};
6use crate::client::{ClientEvent, Gap, ProtocolError, ReceivedEvent};
7use crate::command::object::Stream;
8use crate::envelope::{EventEnvelope, Stream as WireStream};
9use crate::event::{Event, Parsed};
10
11impl Session {
12    /// Processes one received transport text at `now_ms`: reassembles fragments, parses the
13    /// envelope, correlates responses, orders events by their stream cursors, and queues any
14    /// `sync.resume` (after a gap) or `sync.ack` (§10.5) that became due.
15    ///
16    /// Events are only applied on a verified session; before the welcome (or after a failed
17    /// one) they are dropped and the resume after the welcome recovers them.
18    ///
19    /// SPEC: §10.5 acks what the client has "durably applied". An ack queued here covers the
20    /// events returned by this call, so the caller must apply (persist) them before sending
21    /// the texts it drains next.
22    pub fn receive(&mut self, text: &str, now_ms: u64) -> Vec<ClientEvent> {
23        let mut out = Vec::new();
24        self.heard_ms = Some(self.heard_ms.map_or(now_ms, |h| h.max(now_ms)));
25        let json = match inbound::reassemble(&mut self.reassembler, text, now_ms) {
26            Ok(Some(json)) => json,
27            Ok(None) => return out,
28            Err(e) => {
29                out.push(ClientEvent::ProtocolError(e));
30                return out;
31            }
32        };
33        let (envelope, errors) = match inbound::parse(&json) {
34            Ok(parsed) => parsed,
35            Err(e) => {
36                out.push(ClientEvent::ProtocolError(e));
37                return out;
38            }
39        };
40        out.extend(errors.into_iter().map(ClientEvent::ProtocolError));
41        match envelope {
42            Envelope::Response(response) => self.on_response(response, now_ms, &mut out),
43            Envelope::Events(events) => {
44                self.ack.frame(now_ms);
45                for event in events {
46                    self.on_event(event, &mut out);
47                }
48            }
49        }
50        self.after_input(now_ms, &mut out);
51        out
52    }
53
54    /// Applies one event envelope: version and community checks, body decoding, then
55    /// dedup/gap handling on its stream (§10). Unknown types advance the cursor only (§9.4).
56    pub(super) fn on_event(&mut self, envelope: EventEnvelope, out: &mut Vec<ClientEvent>) {
57        if self.state != SessionState::Ready {
58            out.push(ClientEvent::ProtocolError(ProtocolError::NotReady));
59            return;
60        }
61        if self.negotiated_version().is_some_and(|v| v != envelope.v) {
62            out.push(ClientEvent::ProtocolError(ProtocolError::WrongVersion(
63                envelope.v,
64            )));
65            return;
66        }
67        if self
68            .community_id()
69            .is_some_and(|c| c != envelope.community_id)
70        {
71            out.push(ClientEvent::ProtocolError(ProtocolError::WrongCommunity));
72            return;
73        }
74        // SPEC: §9.4 says only unknown types are ignored. A known type with a malformed body
75        // cannot be applied; it is reported and its cursor still advances, so a bad event
76        // cannot wedge the stream in an endless resync.
77        let event = match Event::parse(&envelope.kind, envelope.body.get()) {
78            Ok(Parsed::Known(event)) => Some(event),
79            Ok(Parsed::Unknown) => None,
80            Err(_) => {
81                let kind = envelope.kind.clone();
82                out.push(ClientEvent::ProtocolError(ProtocolError::MalformedEvent(
83                    kind,
84                )));
85                None
86            }
87        };
88        let (key, seq) = match (envelope.stream, envelope.sequence, envelope.channel_id) {
89            (WireStream::Member, Some(seq), _) => (Key::Member, seq),
90            (WireStream::Channel, Some(seq), Some(id)) => (Key::Channel(id), seq),
91            // Live events (validated: no sequence) are delivered as they come.
92            _ => return deliver(Held { envelope, event }, out),
93        };
94        match self.cursors.offer(key, seq, Held { envelope, event }) {
95            Offer::Duplicate => {}
96            Offer::Ready(ready) => ready.into_iter().for_each(|h| deliver(h, out)),
97            Offer::Gap { expected } => {
98                let (stream, channel_id) = match key {
99                    Key::Member => (Stream::Member, None),
100                    Key::Channel(id) => (Stream::Channel, Some(id)),
101                };
102                out.push(ClientEvent::Gap(Gap {
103                    stream,
104                    channel_id,
105                    expected,
106                    received: seq,
107                }));
108                self.gap_pending = true;
109            }
110        }
111    }
112
113    /// Queues a `sync.resume` for a pending gap and a `sync.ack` when one is due. Both need
114    /// a verified, bound session.
115    pub(super) fn after_input(&mut self, now_ms: u64, out: &mut Vec<ClientEvent>) {
116        if self.state != SessionState::Ready || self.binding.is_none() {
117            return;
118        }
119        for body in std::mem::take(&mut self.follow_ups) {
120            match self.submit_resume(&body, now_ms) {
121                Ok(_) => self.resumes_in_flight += 1,
122                Err(e) => out.push(ClientEvent::ProtocolError(ProtocolError::AutoSend(e))),
123            }
124        }
125        if self.gap_pending && self.resumes_in_flight == 0 {
126            self.gap_pending = false;
127            if let Err(e) = self.resume_request(now_ms) {
128                out.push(ClientEvent::ProtocolError(ProtocolError::AutoSend(e)));
129            }
130        }
131        if self.ack_due(now_ms) {
132            // A retry goes when its time comes; the cadence waits a moment for a command.
133            let ripe = *self.ack_ripe_ms.get_or_insert(now_ms);
134            let go =
135                self.ack_retry_ms.is_some() || now_ms >= ripe.saturating_add(super::ACK_LINGER_MS);
136            if go && let Err(e) = self.send_acks() {
137                out.push(ClientEvent::ProtocolError(ProtocolError::AutoSend(e)));
138            }
139        }
140    }
141}
142
143/// Reports an applied event; unknown or malformed ones only moved the cursor.
144pub(super) fn deliver(held: Held, out: &mut Vec<ClientEvent>) {
145    if let Some(event) = held.event {
146        out.push(ClientEvent::Event(Box::new(ReceivedEvent {
147            envelope: held.envelope,
148            event,
149        })));
150    }
151}