Skip to main content

sew_e2ee/session/
buffer.rs

1//! The unknown-call buffer.
2//!
3//! A `call_keys_delivered` for a `call_id` the client does not know yet (the gateway can beat the
4//! join's HTTP answer) is buffered for `params.unknown_call_buffer_ms`, then applied once the
5//! session exists, or dropped. Bounded: at most 64 messages or 1 MiB per unknown call and at
6//! most 2 unknown calls; the oldest is dropped and counted.
7
8use std::collections::VecDeque;
9
10use sew_proto::e2ee::{CallId, CallKeysMessage};
11
12use crate::config::{E2eeConfig, Params};
13use crate::ids::Millis;
14
15/// The `call_id` a dispatch names (`revoked` names none).
16pub fn call_id_of(m: &CallKeysMessage) -> Option<&CallId> {
17    match m {
18        CallKeysMessage::Init(i) => Some(&i.call_id),
19        CallKeysMessage::Proposals { call_id, .. }
20        | CallKeysMessage::CommitRequest { call_id, .. }
21        | CallKeysMessage::Commit { call_id, .. }
22        | CallKeysMessage::Welcome { call_id, .. }
23        | CallKeysMessage::Activate { call_id, .. }
24        | CallKeysMessage::Reset { call_id, .. }
25        | CallKeysMessage::Recorder { call_id, .. }
26        | CallKeysMessage::Removed { call_id, .. }
27        | CallKeysMessage::Resync { call_id, .. } => Some(call_id),
28        CallKeysMessage::Revoked { .. } | CallKeysMessage::Unknown => None,
29    }
30}
31
32#[derive(Debug)]
33struct Pending {
34    call_id: CallId,
35    first_at: Millis,
36    bytes: usize,
37    messages: VecDeque<(Millis, usize, CallKeysMessage)>,
38}
39
40/// Buffers dispatches for calls not known yet.
41#[derive(Debug)]
42pub struct UnknownCallBuffer {
43    window_ms: u64,
44    max_messages: usize,
45    max_bytes: usize,
46    max_calls: usize,
47    calls: VecDeque<Pending>,
48    dropped: u64,
49}
50
51impl UnknownCallBuffer {
52    /// A buffer with the server's window and the local bounds.
53    pub fn new(params: &Params, cfg: &E2eeConfig) -> UnknownCallBuffer {
54        UnknownCallBuffer {
55            window_ms: params.unknown_call_buffer_ms,
56            max_messages: cfg.unknown_call_max_messages,
57            max_bytes: cfg.unknown_call_max_bytes,
58            max_calls: cfg.unknown_call_max_calls,
59            calls: VecDeque::new(),
60            dropped: 0,
61        }
62    }
63
64    /// Buffers `msg` (`size` = its raw JSON length) for `call_id`.
65    pub fn push(&mut self, now: Millis, call_id: CallId, msg: CallKeysMessage, size: usize) {
66        self.expire(now);
67        let idx = match self.calls.iter().position(|p| p.call_id == call_id) {
68            Some(i) => i,
69            None => {
70                while self.calls.len() >= self.max_calls {
71                    if let Some(old) = self.calls.pop_front() {
72                        self.dropped += old.messages.len() as u64;
73                    }
74                }
75                self.calls.push_back(Pending {
76                    call_id,
77                    first_at: now,
78                    bytes: 0,
79                    messages: VecDeque::new(),
80                });
81                self.calls.len() - 1
82            }
83        };
84        let (max_messages, max_bytes) = (self.max_messages, self.max_bytes);
85        let Some(p) = self.calls.get_mut(idx) else {
86            return;
87        };
88        p.messages.push_back((now, size, msg));
89        p.bytes += size;
90        while p.messages.len() > max_messages || p.bytes > max_bytes {
91            if let Some((_, s, _)) = p.messages.pop_front() {
92                p.bytes -= s;
93                self.dropped += 1;
94            } else {
95                break;
96            }
97        }
98    }
99
100    /// Drops everything older than the window.
101    pub fn expire(&mut self, now: Millis) {
102        let window = self.window_ms;
103        let mut dropped = 0u64;
104        for p in &mut self.calls {
105            while p
106                .messages
107                .front()
108                .is_some_and(|(t, _, _)| now.saturating_sub(*t) > window)
109            {
110                if let Some((_, s, _)) = p.messages.pop_front() {
111                    p.bytes -= s;
112                    dropped += 1;
113                }
114            }
115        }
116        self.dropped += dropped;
117        self.calls.retain(|p| !p.messages.is_empty());
118    }
119
120    /// Takes the buffered messages of `call_id`, in order (the session now exists).
121    pub fn take(&mut self, now: Millis, call_id: &CallId) -> Vec<CallKeysMessage> {
122        self.expire(now);
123        match self.calls.iter().position(|p| &p.call_id == call_id) {
124            Some(i) => self
125                .calls
126                .remove(i)
127                .map(|p| p.messages.into_iter().map(|(_, _, m)| m).collect())
128                .unwrap_or_default(),
129            None => Vec::new(),
130        }
131    }
132
133    /// Messages dropped (window, bounds, evicted calls): `unknown_call_dropped`.
134    pub fn dropped(&self) -> u64 {
135        self.dropped
136    }
137
138    /// Messages and bytes held for `call_id`.
139    pub fn held(&self, call_id: &CallId) -> (usize, usize) {
140        self.calls
141            .iter()
142            .find(|p| &p.call_id == call_id)
143            .map_or((0, 0), |p| (p.messages.len(), p.bytes))
144    }
145
146    /// Calls held.
147    pub fn calls(&self) -> usize {
148        self.calls.len()
149    }
150
151    /// When the oldest held message expires.
152    pub fn next_expiry(&self) -> Option<Millis> {
153        self.calls
154            .iter()
155            .filter_map(|p| p.messages.front().map(|(t, _, _)| t + self.window_ms + 1))
156            .min()
157            .or_else(|| self.calls.front().map(|p| p.first_at + self.window_ms + 1))
158    }
159}