Skip to main content

s2_kit/session/
set.rs

1//! Many sessions, one loop.
2//!
3//! A Customer Energy Manager talks to every flexible device in a building, and a fleet
4//! manager to every device in a thousand. Each of those sessions has its own
5//! acknowledgement deadlines, its own timers and its own validity windows, and the
6//! obvious implementation — one task per session — turns a hundred devices into a hundred
7//! stacks and a hundred timers.
8//!
9//! [`SessionSet`] keeps them in one map and answers the only question a single-threaded
10//! event loop actually needs: **when must I next wake up, and for whom?**
11//!
12//! ```
13//! use s2_kit::prelude::*;
14//! use s2_kit::session::SessionSet;
15//!
16//! let mut fleet: SessionSet<String, CemSession> = SessionSet::new();
17//! fleet.insert("battery".to_string(), CemSession::new(CemConfig::default()));
18//! fleet.insert("heatpump".to_string(), CemSession::new(CemConfig::default()));
19//!
20//! let now = Timestamp::UNIX_EPOCH;
21//! fleet.open_all(now);
22//!
23//! // One deadline for the whole fleet — the soonest of all of them.
24//! if let Some(deadline) = fleet.poll_timeout() {
25//!     // sleep until `deadline`, then:
26//!     fleet.handle_timeout(deadline);
27//! }
28//!
29//! // And one drain, tagged with whose session each frame belongs to.
30//! for (device, out) in fleet.drain_transmit() {
31//!     assert!(!out.text.is_empty());
32//!     let _ = device;
33//! }
34//! ```
35
36use alloc::collections::BTreeMap;
37use alloc::vec::Vec;
38
39use crate::types::Timestamp;
40
41use super::{Outgoing, Session};
42
43/// A keyed collection of sessions driven as one.
44///
45/// `K` is whatever identifies a peer to the application: a node id, a serial number, a
46/// database row id. The set never interprets it.
47#[derive(Debug, Default)]
48pub struct SessionSet<K, S> {
49    sessions: BTreeMap<K, S>,
50}
51
52impl<K: Ord, S: Session> SessionSet<K, S> {
53    /// An empty set.
54    #[must_use]
55    pub fn new() -> Self {
56        Self {
57            sessions: BTreeMap::new(),
58        }
59    }
60
61    /// Add a session, returning whatever was under that key.
62    pub fn insert(&mut self, key: K, session: S) -> Option<S> {
63        self.sessions.insert(key, session)
64    }
65
66    /// Take a session out — when its transport has gone, for instance.
67    pub fn remove(&mut self, key: &K) -> Option<S> {
68        self.sessions.remove(key)
69    }
70
71    /// One session.
72    pub fn get(&self, key: &K) -> Option<&S> {
73        self.sessions.get(key)
74    }
75
76    /// One session, mutably, to feed a frame into.
77    pub fn get_mut(&mut self, key: &K) -> Option<&mut S> {
78        self.sessions.get_mut(key)
79    }
80
81    /// How many sessions there are.
82    #[must_use]
83    pub fn len(&self) -> usize {
84        self.sessions.len()
85    }
86
87    /// Whether there are none.
88    #[must_use]
89    pub fn is_empty(&self) -> bool {
90        self.sessions.is_empty()
91    }
92
93    /// Every session, in key order.
94    pub fn iter(&self) -> impl Iterator<Item = (&K, &S)> {
95        self.sessions.iter()
96    }
97
98    /// Every session, mutably, in key order.
99    pub fn iter_mut(&mut self) -> impl Iterator<Item = (&K, &mut S)> {
100        self.sessions.iter_mut()
101    }
102
103    /// Open every session that has not been opened.
104    pub fn open_all(&mut self, now: Timestamp) {
105        for session in self.sessions.values_mut() {
106            session.open(now);
107        }
108    }
109
110    /// The soonest deadline across the whole set.
111    ///
112    /// This is the number an event loop sleeps on. A set of a thousand sessions still
113    /// has exactly one timer.
114    #[must_use]
115    pub fn poll_timeout(&self) -> Option<Timestamp> {
116        self.sessions
117            .values()
118            .filter_map(Session::poll_timeout)
119            .min()
120    }
121
122    /// Which session owns the soonest deadline, for a caller that would rather wake one
123    /// session than sweep them all.
124    #[must_use]
125    pub fn next_deadline(&self) -> Option<(&K, Timestamp)> {
126        self.sessions
127            .iter()
128            .filter_map(|(key, session)| session.poll_timeout().map(|at| (key, at)))
129            .min_by_key(|(_, at)| *at)
130    }
131
132    /// Fire every deadline that has come due.
133    ///
134    /// Sweeping the whole set rather than only the session that woke us is deliberate:
135    /// several deadlines commonly fall in the same millisecond, and a loop that handles
136    /// one per wake-up turns a burst into a long tail of timer round-trips.
137    pub fn handle_timeout(&mut self, now: Timestamp) {
138        for session in self.sessions.values_mut() {
139            if session.poll_timeout().is_some_and(|at| at <= now) {
140                session.handle_timeout(now);
141            }
142        }
143    }
144
145    /// Everything every session wants to send, tagged with whose it is.
146    ///
147    /// The key is **cloned**, not borrowed. Draining and then acting on what was drained
148    /// is the only thing a caller does with the result — write the frame to the socket it
149    /// looks up by that key, close the session that just emitted it, remove one whose
150    /// transport has gone — and a borrowed key would hold the set immutably for exactly as
151    /// long as the result lives.
152    pub fn drain_transmit(&mut self) -> Vec<(K, Outgoing)>
153    where
154        K: Clone,
155    {
156        let mut out = Vec::new();
157        for (key, session) in &mut self.sessions {
158            while let Some(frame) = session.poll_transmit() {
159                out.push((key.clone(), frame));
160            }
161        }
162        out
163    }
164
165    /// Everything every session wants to tell the application, tagged with whose it is.
166    ///
167    /// Cloned for the same reason [`drain_transmit`](Self::drain_transmit) clones: acting
168    /// on an event usually means touching the set the event came from.
169    pub fn drain_events(&mut self) -> Vec<(K, S::Event)>
170    where
171        K: Clone,
172    {
173        let mut out = Vec::new();
174        for (key, session) in &mut self.sessions {
175            while let Some(event) = session.poll_event() {
176                out.push((key.clone(), event));
177            }
178        }
179        out
180    }
181
182    /// Drop every session whose state machine has finished.
183    ///
184    /// A set that is never pruned is a memory leak with extra steps: a reconnecting
185    /// device produces a new session each time, and the closed ones have nothing left to
186    /// say.
187    pub fn retain_open(&mut self) -> usize {
188        let before = self.sessions.len();
189        self.sessions
190            .retain(|_, session| !session.state().is_closed());
191        before - self.sessions.len()
192    }
193
194    /// Close every session.
195    pub fn close_all(&mut self) {
196        for session in self.sessions.values_mut() {
197            session.close();
198        }
199    }
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205    use crate::session::{CemConfig, CemSession, RmConfig, RmSession};
206    use alloc::string::{String, ToString};
207    use alloc::vec;
208
209    fn t(secs: i64) -> Timestamp {
210        Timestamp::from_unix(1_700_000_000 + secs, 0)
211    }
212
213    fn fleet() -> SessionSet<String, CemSession> {
214        let mut set = SessionSet::new();
215        set.insert("a".to_string(), CemSession::new(CemConfig::default()));
216        set.insert("b".to_string(), CemSession::new(CemConfig::default()));
217        set
218    }
219
220    #[test]
221    fn a_drain_can_be_acted_on_while_the_set_is_still_there() {
222        // The reason the keys are cloned: draining and then acting on what was drained is
223        // the only thing a caller ever does with the result, and every one of those
224        // actions needs the set back.
225        let mut set = fleet();
226        set.open_all(t(0));
227        let frames = set.drain_transmit();
228        assert_eq!(frames.len(), 2, "one handshake each");
229        for (key, frame) in frames {
230            assert!(frame.text.contains("Handshake"));
231            // Borrowed keys would have made this line a borrow-check error.
232            set.get_mut(&key).expect("still there").close();
233        }
234        assert_eq!(set.retain_open(), 2);
235    }
236
237    #[test]
238    fn a_fleet_has_one_deadline_not_a_thousand() {
239        let mut set = fleet();
240        set.open_all(t(0));
241        // Both sessions are waiting on a handshake acknowledgement.
242        let soonest = set.poll_timeout().expect("both are waiting on something");
243        let (_, same) = set.next_deadline().expect("and one of them owns it");
244        assert_eq!(soonest, same);
245        assert!(soonest > t(0));
246    }
247
248    #[test]
249    fn every_due_deadline_fires_in_one_sweep() {
250        let mut set = fleet();
251        set.open_all(t(0));
252        let _ = set.drain_transmit();
253        let deadline = set.poll_timeout().expect("a deadline");
254
255        set.handle_timeout(deadline);
256        // Both sessions reacted, not just the first one found.
257        let events = set.drain_events();
258        let mut keys: Vec<&str> = events.iter().map(|(k, _)| k.as_str()).collect();
259        keys.sort_unstable();
260        keys.dedup();
261        assert_eq!(keys.len(), 2, "both sessions should have timed out");
262    }
263
264    #[test]
265    fn transmissions_are_tagged_with_whose_they_are() {
266        let mut set = fleet();
267        set.open_all(t(0));
268        let frames = set.drain_transmit();
269        assert!(!frames.is_empty());
270        for (key, out) in &frames {
271            assert!(key.as_str() == "a" || key.as_str() == "b");
272            assert!(out.text.contains("message_type"));
273        }
274        // Draining twice yields nothing the second time.
275        assert!(set.drain_transmit().is_empty());
276    }
277
278    #[test]
279    fn closed_sessions_are_pruned_rather_than_accumulated() {
280        let mut set = fleet();
281        set.open_all(t(0));
282        assert_eq!(set.retain_open(), 0);
283        set.get_mut(&"a".to_string()).expect("session a").close();
284        let _ = set.drain_transmit();
285        assert_eq!(set.retain_open(), 1);
286        assert_eq!(set.len(), 1);
287        assert!(set.get(&"a".to_string()).is_none());
288    }
289
290    /// The 20 kWh battery, without the `testing` feature's fixture, so this module's
291    /// tests run under `--no-default-features` as well.
292    fn details() -> crate::types::common::ResourceManagerDetails {
293        use crate::types::common::{
294            Commodity, CommodityQuantity, ControlType, ResourceManagerDetails, Role, RoleType,
295        };
296        use crate::types::{Duration, Id};
297        ResourceManagerDetails::builder()
298            .message_id(Id::new_const("rmd-1"))
299            .resource_id(Id::new_const("battery-1"))
300            .roles(vec![Role::new(
301                RoleType::EnergyStorage,
302                Commodity::Electricity,
303            )])
304            .instruction_processing_delay(Duration::from_millis(500))
305            .available_control_types(vec![ControlType::FillRateBasedControl])
306            .provides_forecast(false)
307            .provides_power_measurement_types(vec![CommodityQuantity::ElectricPower3PhaseSymmetric])
308            .build()
309    }
310
311    #[test]
312    fn the_set_works_for_resource_managers_too() {
313        // The point of the trait: a gateway fronting many devices is the mirror image of
314        // a CEM managing many, and neither should need its own collection type.
315        let mut set: SessionSet<u32, RmSession> = SessionSet::new();
316        set.insert(1, RmSession::new(RmConfig::default(), details()));
317        set.insert(2, RmSession::new(RmConfig::default(), details()));
318        set.open_all(t(0));
319        assert_eq!(set.len(), 2);
320        assert!(set.poll_timeout().is_some());
321        assert!(!set.drain_transmit().is_empty());
322        set.close_all();
323        let _ = set.drain_transmit();
324        assert_eq!(set.retain_open(), 2);
325        assert!(set.is_empty());
326    }
327}