Skip to main content

zaun_community_protocol/client/session/
outbound.rs

1//! Sending: hello, commands, signals, resume, acks and retries.
2
3use super::{Session, SessionState};
4use crate::client::ClientError;
5use crate::client::outbound::{envelope_text, frame};
6use crate::client::pending::{Origin, Pending};
7use crate::command::Body;
8use crate::command::session::{Hello, Versions};
9use crate::crypto;
10use crate::ids::{ChannelId, CommunityId, DescriptorHash, Nonce, RequestId};
11
12/// `type` prefix of ephemeral signals (§10.5).
13const SIGNAL_PREFIX: &str = "signal.";
14
15impl Session {
16    /// Sends `session.hello` with a fresh nonce (§6.2). Call it first, and again after every
17    /// reconnect; commands then wait for the new welcome and are resent after it (§6.3).
18    ///
19    /// SPEC: `community_id` is "unbound only"; it is sent when the session has no binding
20    /// and is `null` otherwise.
21    ///
22    /// # Errors
23    /// [`ClientError::Failed`] after a failed welcome (§6.2: use a new [`Session`]),
24    /// [`ClientError::Rng`] or a framing error.
25    pub fn hello(&mut self, now_ms: u64) -> Result<RequestId, ClientError> {
26        if let SessionState::Failed(e) = &self.state {
27            return Err(ClientError::Failed(e.clone()));
28        }
29        let nonce = Nonce::random()?;
30        let body = Hello {
31            versions: Versions {
32                min: self.config.versions.min,
33                max: self.config.versions.max,
34            },
35            client_nonce: nonce,
36            capabilities: self.config.capabilities.clone(),
37            community_id: self.config.community_id.filter(|_| self.binding.is_none()),
38            held_descriptor: self.held_descriptor(),
39        };
40        self.pending.remove_where(|o| matches!(o, Origin::Hello(_)));
41        self.pending.clear_early();
42        // A new session resumes from the cursors; a refused ack's retry is not held over
43        // (its channels stay marked for the next ack).
44        self.ack_retry_ms = None;
45        let id = self.submit(&body, None, None, Origin::Hello(nonce), now_ms)?;
46        self.hello_sent = Some((id, nonce));
47        self.held_sent = body.held_descriptor;
48        self.state = SessionState::AwaitingWelcome;
49        self.welcome = None;
50        Ok(id)
51    }
52
53    /// The hash of the held pair's descriptor, named in a hello that concerns a community.
54    fn held_descriptor(&self) -> Option<DescriptorHash> {
55        let (descriptor, _) = self.config.held_pair.as_ref()?;
56        self.community_id()
57            .map(|_| DescriptorHash::from_bytes(crypto::content_hash(&descriptor.bytes)))
58    }
59
60    /// Sends a command (§7.1) and tracks it for retries with the same `request_id` and
61    /// byte-identical body (§7.3). The body is validated first (§12).
62    ///
63    /// # Errors
64    /// [`ClientError::NotReady`] before a verified welcome, [`ClientError::Failed`] after a
65    /// failed one, [`ClientError::WrongCommunity`], [`ClientError::WrongKind`] for a signal,
66    /// or a body, size, framing or RNG error.
67    pub fn send<B: Body>(
68        &mut self,
69        body: &B,
70        community: Option<CommunityId>,
71        channel: Option<ChannelId>,
72        now_ms: u64,
73    ) -> Result<RequestId, ClientError> {
74        self.check_ready(community)?;
75        if B::NAME.starts_with(SIGNAL_PREFIX) {
76            return Err(ClientError::WrongKind(B::NAME));
77        }
78        self.submit(body, community, channel, Origin::User, now_ms)
79    }
80
81    /// Sends a read-only sync command (`sync.snapshot`, `sync.resume`, `sync.events`) right
82    /// behind the hello of a bound session, without waiting for the welcome (§6.3 "Pipelined
83    /// resumption"): the host runs the connection's commands in order, so it answers after the
84    /// welcome. The answer is reported only once the welcome verified. After the welcome this
85    /// is [`Session::send`].
86    ///
87    /// # Errors
88    /// As [`Session::send`]; [`ClientError::NotReady`] for another command, or before a hello
89    /// or without a binding.
90    pub fn send_behind_hello<B: Body>(
91        &mut self,
92        body: &B,
93        now_ms: u64,
94    ) -> Result<RequestId, ClientError> {
95        let community = self.community_id();
96        if self.state == SessionState::Ready {
97            return self.send(body, community, None, now_ms);
98        }
99        let read_only = [
100            <crate::command::sync::Snapshot as Body>::NAME,
101            <crate::command::sync::Resume as Body>::NAME,
102            <crate::command::sync::Events as Body>::NAME,
103        ];
104        if self.state != SessionState::AwaitingWelcome
105            || self.binding.is_none()
106            || !read_only.contains(&B::NAME)
107        {
108            return Err(ClientError::NotReady);
109        }
110        let id = self.submit(body, community, None, Origin::User, now_ms)?;
111        if let Some(p) = self.pending.get_mut(&id) {
112            p.early = true;
113        }
114        Ok(id)
115    }
116
117    /// Sends an ephemeral signal (`signal.*`): `request_id: null`, no response, no retry
118    /// (§10.5).
119    ///
120    /// # Errors
121    /// As [`Session::send`]; [`ClientError::WrongKind`] for a non-signal body.
122    pub fn send_signal<B: Body>(
123        &mut self,
124        body: &B,
125        community: Option<CommunityId>,
126        channel: Option<ChannelId>,
127    ) -> Result<(), ClientError> {
128        self.check_ready(community)?;
129        if !B::NAME.starts_with(SIGNAL_PREFIX) {
130            return Err(ClientError::WrongKind(B::NAME));
131        }
132        let text = envelope_text(body, None, community, channel)?;
133        self.transmit.extend(frame(&text, self.config.text_budget)?);
134        Ok(())
135    }
136
137    /// Sends `sync.resume` for every tracked stream (§10.3), in chunks of 100 channels. Call
138    /// it after the welcome of a reconnect (§6.3).
139    ///
140    /// # Errors
141    /// As [`Session::send`].
142    pub fn resume_request(&mut self, now_ms: u64) -> Result<Vec<RequestId>, ClientError> {
143        let community = self.community_id();
144        self.check_ready(community)?;
145        let mut ids = Vec::new();
146        for body in self.cursors.resume_bodies() {
147            ids.push(self.submit(&body, community, None, Origin::Resume, now_ms)?);
148            self.resumes_in_flight += 1;
149        }
150        Ok(ids)
151    }
152
153    /// Sends a `sync.events` the session itself needs, tracked like a resume.
154    pub(super) fn submit_resume(
155        &mut self,
156        body: &crate::command::sync::Events,
157        now_ms: u64,
158    ) -> Result<RequestId, ClientError> {
159        let community = self.community_id();
160        self.check_ready(community)?;
161        self.submit(body, community, None, Origin::Resume, now_ms)
162    }
163
164    fn check_ready(&self, community: Option<CommunityId>) -> Result<(), ClientError> {
165        match &self.state {
166            SessionState::Ready => {}
167            SessionState::Failed(e) => return Err(ClientError::Failed(e.clone())),
168            SessionState::Idle | SessionState::AwaitingWelcome => {
169                return Err(ClientError::NotReady);
170            }
171        }
172        match (self.binding, community) {
173            (Some(b), Some(c)) if b.community_id != c => Err(ClientError::WrongCommunity),
174            _ => Ok(()),
175        }
176    }
177
178    /// Serialises once, frames, queues and records a tracked request.
179    fn submit<B: Body>(
180        &mut self,
181        body: &B,
182        community: Option<CommunityId>,
183        channel: Option<ChannelId>,
184        origin: Origin,
185        now_ms: u64,
186    ) -> Result<RequestId, ClientError> {
187        let id = RequestId::random()?;
188        let text = envelope_text(body, Some(id), community, channel)?;
189        self.transmit.extend(frame(&text, self.config.text_budget)?);
190        // A due ack goes with the command, in the same flush (§10.5).
191        if self.state == SessionState::Ready
192            && !matches!(origin, Origin::Hello(_))
193            && self.ack_retry_ms.is_none()
194            && self.ack.due(now_ms)
195        {
196            self.send_acks()?;
197        }
198        let pending = Pending {
199            kind: B::NAME,
200            community,
201            text,
202            origin,
203            first_ms: now_ms,
204            attempt: 1,
205            next_ms: self.config.retry.next_at(now_ms, 1, None),
206            refused: false,
207            early: false,
208        };
209        self.pending.insert(id, pending);
210        Ok(id)
211    }
212}
213
214/// Sends a [`Command`](crate::command::Command) through [`Session::send`] or
215/// [`Session::send_signal`] by its type.
216struct SendVisitor<'a> {
217    session: &'a mut Session,
218    community: Option<CommunityId>,
219    channel: Option<ChannelId>,
220    now_ms: u64,
221}
222
223impl crate::command::BodyVisitor for SendVisitor<'_> {
224    type Output = Result<Option<RequestId>, ClientError>;
225    fn visit<B: Body>(self, body: &B) -> Self::Output {
226        if B::NAME.starts_with(SIGNAL_PREFIX) {
227            self.session
228                .send_signal(body, self.community, self.channel)
229                .map(|()| None)
230        } else {
231            self.session
232                .send(body, self.community, self.channel, self.now_ms)
233                .map(Some)
234        }
235    }
236}
237
238impl Session {
239    /// Sends a command known only at run time (a bot's, an application's raw command):
240    /// [`Session::send`], or [`Session::send_signal`] for a `signal.*` (no request id).
241    ///
242    /// # Errors
243    /// As [`Session::send`].
244    pub fn send_command(
245        &mut self,
246        command: &crate::command::Command,
247        community: Option<CommunityId>,
248        channel: Option<ChannelId>,
249        now_ms: u64,
250    ) -> Result<Option<RequestId>, ClientError> {
251        command.visit(SendVisitor {
252            session: self,
253            community,
254            channel,
255            now_ms,
256        })
257    }
258}