Skip to main content

zaun_community_protocol/client/
session.rs

1//! One connection to one host (§6): state, outbound queue and accessors.
2
3mod outbound;
4mod receive;
5mod respond;
6mod sync;
7mod timers;
8mod welcome;
9
10use std::collections::VecDeque;
11use std::fmt;
12
13use super::ack::AckClock;
14use super::pending::PendingTable;
15use super::{CursorTable, SessionConfig, VerifiedWelcome, WelcomeError};
16use crate::command::object::Binding;
17use crate::framing::Reassembler;
18use crate::ids::{Challenge, ChannelId, CommunityId, RequestId};
19use crate::signed::ValidPair;
20
21/// Where the session is in its lifecycle (§6.1, §6.2).
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum SessionState {
24    /// No `session.hello` sent yet.
25    Idle,
26    /// `session.hello` sent; commands wait for the welcome.
27    AwaitingWelcome,
28    /// The welcome verified; commands flow.
29    Ready,
30    /// The welcome failed verification; nothing more may be sent on this session.
31    Failed(WelcomeError),
32}
33
34/// How long a due `sync.ack` waits for a command to go with (§10.5). A SimpleX connection
35/// sends one message at a time, so a command sent right after a lone ack would wait a relay
36/// round trip behind it; the cadence (8 frames or 30 s) has room for this.
37pub const ACK_LINGER_MS: u64 = 250;
38
39/// A sans-IO client session. See the [module documentation](super).
40pub struct Session {
41    config: SessionConfig,
42    state: SessionState,
43    welcome: Option<VerifiedWelcome>,
44    /// The latest `session.hello`'s id and nonce, for later answers to its resends.
45    hello_sent: Option<(RequestId, crate::ids::Nonce)>,
46    /// The `held_descriptor` the latest hello named (§6.2).
47    held_sent: Option<crate::ids::DescriptorHash>,
48    binding: Option<Binding>,
49    pending: PendingTable,
50    reassembler: Reassembler,
51    cursors: CursorTable,
52    ack: AckClock,
53    /// Recent `sync.ack` request ids and the channels each carried. Their responses are not
54    /// counted as frames; a transient refusal schedules `ack_retry_ms`.
55    ack_ids: VecDeque<(RequestId, Vec<ChannelId>)>,
56    /// When a new `sync.ack` replaces one the host refused (§10.5); at most one at a time.
57    ack_retry_ms: Option<u64>,
58    /// When the cadence first made an ack due: it waits [`ACK_LINGER_MS`] for a command to go
59    /// with, so the two share a SimpleX message instead of the command queueing behind it.
60    ack_ripe_ms: Option<u64>,
61    /// `sync.resume` requests awaiting their response.
62    resumes_in_flight: usize,
63    gap_pending: bool,
64    /// `sync.events` requests continuing streams a `sync.resume` (or such a request) left
65    /// with `has_more`, sent on the next input.
66    follow_ups: Vec<crate::command::sync::Events>,
67    transmit: VecDeque<String>,
68    /// When the host last sent anything (a whole frame or a fragment): resends wait while
69    /// it is still sending (§7.3).
70    heard_ms: Option<u64>,
71}
72
73impl fmt::Debug for Session {
74    /// Shows no envelope text: pending bodies and queued texts may hold an invitation secret.
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.debug_struct("Session")
77            .field("state", &self.state)
78            .field("version", &self.negotiated_version())
79            .field("binding", &self.binding)
80            .field("pending", &self.pending.len())
81            .field("transmit", &self.transmit.len())
82            .field("member_cursor", &self.cursors.member())
83            .finish_non_exhaustive()
84    }
85}
86
87impl Session {
88    /// A session that has sent nothing yet; call [`Session::hello`] first.
89    #[must_use]
90    pub fn new(config: SessionConfig) -> Self {
91        let ack = AckClock::new(config.ack_every_frames, config.ack_every_ms);
92        Self {
93            binding: config.binding,
94            config,
95            state: SessionState::Idle,
96            welcome: None,
97            hello_sent: None,
98            held_sent: None,
99            pending: PendingTable::default(),
100            reassembler: Reassembler::new(),
101            cursors: CursorTable::default(),
102            ack,
103            ack_ids: VecDeque::new(),
104            ack_retry_ms: None,
105            ack_ripe_ms: None,
106            resumes_in_flight: 0,
107            gap_pending: false,
108            follow_ups: Vec::new(),
109            transmit: VecDeque::new(),
110            heard_ms: None,
111        }
112    }
113
114    /// The lifecycle state.
115    #[must_use]
116    pub const fn state(&self) -> &SessionState {
117        &self.state
118    }
119
120    /// The verified welcome of the current hello.
121    #[must_use]
122    pub const fn welcome(&self) -> Option<&VerifiedWelcome> {
123        self.welcome.as_ref()
124    }
125
126    /// The verified descriptor and delegation; persist its `state()` (§4.3 rule 5).
127    #[must_use]
128    pub fn community(&self) -> Option<&ValidPair> {
129        self.welcome.as_ref().and_then(|w| w.community.as_ref())
130    }
131
132    /// Holds `pair` (a verified signed descriptor and delegation) for this connection's
133    /// community: the next hello names it, so its welcome may leave it out (§6.2). For a
134    /// creator, whose welcome carried no pair.
135    pub fn hold_pair(&mut self, pair: (crate::json::SignedJson, crate::json::SignedJson)) {
136        self.config.held_pair = Some(pair);
137    }
138
139    /// The connection's binding, from the welcome or a successful create/redeem/request.
140    #[must_use]
141    pub const fn binding(&self) -> Option<Binding> {
142        self.binding
143    }
144
145    /// The negotiated protocol version.
146    #[must_use]
147    pub fn negotiated_version(&self) -> Option<u16> {
148        self.welcome.as_ref().map(|w| w.version)
149    }
150
151    /// The challenge to sign into a `MemberKeyRegistration` (§4.4).
152    #[must_use]
153    pub fn host_challenge(&self) -> Option<Challenge> {
154        self.welcome.as_ref().map(|w| w.host_challenge)
155    }
156
157    /// The stream cursors (§10).
158    #[must_use]
159    pub const fn cursors(&self) -> &CursorTable {
160        &self.cursors
161    }
162
163    /// The stream cursors, for seeding after a snapshot or history paging.
164    pub const fn cursors_mut(&mut self) -> &mut CursorTable {
165        &mut self.cursors
166    }
167
168    /// Unanswered requests (hello and commands).
169    #[must_use]
170    pub fn pending_count(&self) -> usize {
171        self.pending.len()
172    }
173
174    /// The next transport text to send, in order.
175    pub fn poll_transmit(&mut self) -> Option<String> {
176        self.transmit.pop_front()
177    }
178
179    /// Every queued transport text, in order.
180    pub fn drain_transmit(&mut self) -> Vec<String> {
181        self.transmit.drain(..).collect()
182    }
183
184    /// The bound community, else the configured target.
185    fn community_id(&self) -> Option<CommunityId> {
186        self.binding
187            .map(|b| b.community_id)
188            .or(self.config.community_id)
189    }
190}