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    /// Collected rather than lazily iterated, so the caller can hold the frames while
148    /// mutating the set — closing a session, say, in response to what it just emitted.
149    pub fn drain_transmit(&mut self) -> Vec<(&K, Outgoing)>
150    where
151        K: Clone,
152    {
153        let mut out = Vec::new();
154        for (key, session) in &mut self.sessions {
155            while let Some(frame) = session.poll_transmit() {
156                out.push((key, frame));
157            }
158        }
159        out
160    }
161
162    /// Everything every session wants to tell the application, tagged with whose it is.
163    pub fn drain_events(&mut self) -> Vec<(&K, S::Event)> {
164        let mut out = Vec::new();
165        for (key, session) in &mut self.sessions {
166            while let Some(event) = session.poll_event() {
167                out.push((key, event));
168            }
169        }
170        out
171    }
172
173    /// Drop every session whose state machine has finished.
174    ///
175    /// A set that is never pruned is a memory leak with extra steps: a reconnecting
176    /// device produces a new session each time, and the closed ones have nothing left to
177    /// say.
178    pub fn retain_open(&mut self) -> usize {
179        let before = self.sessions.len();
180        self.sessions
181            .retain(|_, session| !session.state().is_closed());
182        before - self.sessions.len()
183    }
184
185    /// Close every session.
186    pub fn close_all(&mut self) {
187        for session in self.sessions.values_mut() {
188            session.close();
189        }
190    }
191}
192
193#[cfg(test)]
194mod tests {
195    use super::*;
196    use crate::session::{CemConfig, CemSession, RmConfig, RmSession};
197    use alloc::string::{String, ToString};
198    use alloc::vec;
199
200    fn t(secs: i64) -> Timestamp {
201        Timestamp::from_unix(1_700_000_000 + secs, 0)
202    }
203
204    fn fleet() -> SessionSet<String, CemSession> {
205        let mut set = SessionSet::new();
206        set.insert("a".to_string(), CemSession::new(CemConfig::default()));
207        set.insert("b".to_string(), CemSession::new(CemConfig::default()));
208        set
209    }
210
211    #[test]
212    fn a_fleet_has_one_deadline_not_a_thousand() {
213        let mut set = fleet();
214        set.open_all(t(0));
215        // Both sessions are waiting on a handshake acknowledgement.
216        let soonest = set.poll_timeout().expect("both are waiting on something");
217        let (_, same) = set.next_deadline().expect("and one of them owns it");
218        assert_eq!(soonest, same);
219        assert!(soonest > t(0));
220    }
221
222    #[test]
223    fn every_due_deadline_fires_in_one_sweep() {
224        let mut set = fleet();
225        set.open_all(t(0));
226        let _ = set.drain_transmit();
227        let deadline = set.poll_timeout().expect("a deadline");
228
229        set.handle_timeout(deadline);
230        // Both sessions reacted, not just the first one found.
231        let events = set.drain_events();
232        let mut keys: Vec<&String> = events.iter().map(|(k, _)| *k).collect();
233        keys.sort_unstable();
234        keys.dedup();
235        assert_eq!(keys.len(), 2, "both sessions should have timed out");
236    }
237
238    #[test]
239    fn transmissions_are_tagged_with_whose_they_are() {
240        let mut set = fleet();
241        set.open_all(t(0));
242        let frames = set.drain_transmit();
243        assert!(!frames.is_empty());
244        for (key, out) in &frames {
245            assert!(key.as_str() == "a" || key.as_str() == "b");
246            assert!(out.text.contains("message_type"));
247        }
248        // Draining twice yields nothing the second time.
249        assert!(set.drain_transmit().is_empty());
250    }
251
252    #[test]
253    fn closed_sessions_are_pruned_rather_than_accumulated() {
254        let mut set = fleet();
255        set.open_all(t(0));
256        assert_eq!(set.retain_open(), 0);
257        set.get_mut(&"a".to_string()).expect("session a").close();
258        let _ = set.drain_transmit();
259        assert_eq!(set.retain_open(), 1);
260        assert_eq!(set.len(), 1);
261        assert!(set.get(&"a".to_string()).is_none());
262    }
263
264    /// The 20 kWh battery, without the `testing` feature's fixture, so this module's
265    /// tests run under `--no-default-features` as well.
266    fn details() -> crate::types::common::ResourceManagerDetails {
267        use crate::types::common::{
268            Commodity, CommodityQuantity, ControlType, ResourceManagerDetails, Role, RoleType,
269        };
270        use crate::types::{Duration, Id};
271        ResourceManagerDetails::builder()
272            .message_id(Id::new_const("rmd-1"))
273            .resource_id(Id::new_const("battery-1"))
274            .roles(vec![Role::new(
275                RoleType::EnergyStorage,
276                Commodity::Electricity,
277            )])
278            .instruction_processing_delay(Duration::from_millis(500))
279            .available_control_types(vec![ControlType::FillRateBasedControl])
280            .provides_forecast(false)
281            .provides_power_measurement_types(vec![CommodityQuantity::ElectricPower3PhaseSymmetric])
282            .build()
283    }
284
285    #[test]
286    fn the_set_works_for_resource_managers_too() {
287        // The point of the trait: a gateway fronting many devices is the mirror image of
288        // a CEM managing many, and neither should need its own collection type.
289        let mut set: SessionSet<u32, RmSession> = SessionSet::new();
290        set.insert(1, RmSession::new(RmConfig::default(), details()));
291        set.insert(2, RmSession::new(RmConfig::default(), details()));
292        set.open_all(t(0));
293        assert_eq!(set.len(), 2);
294        assert!(set.poll_timeout().is_some());
295        assert!(!set.drain_transmit().is_empty());
296        set.close_all();
297        let _ = set.drain_transmit();
298        assert_eq!(set.retain_open(), 2);
299        assert!(set.is_empty());
300    }
301}