zaun_community_protocol/client/session/
outbound.rs1use 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
12const SIGNAL_PREFIX: &str = "signal.";
14
15impl Session {
16 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 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 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 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 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 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 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 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 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 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
214struct 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 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}