Skip to main content

djs_rs/sharding/
stats.rs

1//! The built-in values of a cluster (D-286, D-310): [`ClusterStats`] and the [`Stats`]
2//! command behind `stats()`.
3
4use core::{
5    sync::atomic::{AtomicU8, AtomicU64, Ordering},
6    time::Duration,
7};
8use std::sync::Arc;
9
10use djs_gateway::ShardState;
11use serde::{Deserialize, Serialize};
12
13use super::ClusterCommand;
14
15/// The built-in command that returns a cluster's [`ClusterStats`]; every cluster process
16/// handles it. [`ClusterManager::stats`](super::ClusterManager::stats) and
17/// [`ClusterClient::stats`](super::ClusterClient::stats) broadcast it; `send::<Stats>(id, ())`
18/// asks one cluster.
19///
20/// discord.js counterpart: `fetchClientValues`.
21#[derive(Clone, Copy, Debug)]
22pub struct Stats;
23
24impl ClusterCommand for Stats {
25    const NAME: &'static str = "djs-rs:stats";
26    type Input = ();
27    type Output = ClusterStats;
28}
29
30/// What a cluster reports about itself (D-310). Returned by `stats()`.
31///
32/// discord.js counterpart: the values `fetchClientValues` reads (`guilds.cache.size`,
33/// `ws.ping`, `uptime`, …), and discord-hybrid-sharding's cluster info.
34#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[non_exhaustive]
36pub struct ClusterStats {
37    /// The cluster's ID.
38    pub cluster: u32,
39    /// Its shards, by shard ID.
40    pub shards: Vec<ShardStats>,
41    /// The number of guilds in its cache; `None` without a cache.
42    pub guilds: Option<u64>,
43    /// The number of users in its cache; `None` without a cache.
44    pub users: Option<u64>,
45    /// How long its client has been logged in.
46    pub uptime: Duration,
47    /// The memory its process uses (resident set size, in bytes); `None` where the system
48    /// does not tell (only Linux does for now).
49    pub memory: Option<u64>,
50}
51
52/// One shard of a [`ClusterStats`].
53///
54/// discord.js counterpart: `WebSocketShard#status` and `#ping`.
55#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
56#[non_exhaustive]
57pub struct ShardStats {
58    /// The shard's ID.
59    pub id: u32,
60    /// Its connection state.
61    pub status: ShardStatus,
62    /// The round trip of its last acknowledged heartbeat; `None` before the first.
63    pub latency: Option<Duration>,
64}
65
66/// The connection state of a shard in a [`ShardStats`]: its
67/// [`ShardState`](djs_gateway::ShardState), which crosses the processes.
68///
69/// discord.js counterpart: `Status`.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72#[non_exhaustive]
73pub enum ShardStatus {
74    /// Not connected (it reconnects by itself).
75    Disconnected,
76    /// Connected and identifying.
77    Identifying,
78    /// Connected and resuming.
79    Resuming,
80    /// The session is established and events are flowing.
81    Active,
82    /// Closed, by the client or by Discord with a code that forbids reconnecting.
83    Closed,
84}
85
86impl From<ShardState> for ShardStatus {
87    fn from(state: ShardState) -> Self {
88        match state {
89            ShardState::Identifying => Self::Identifying,
90            ShardState::Resuming => Self::Resuming,
91            ShardState::Active => Self::Active,
92            ShardState::FatallyClosed(_) | ShardState::Closed => Self::Closed,
93            // `Disconnected`, and any state added later until it is mapped here.
94            _ => Self::Disconnected,
95        }
96    }
97}
98
99/// A shard's state and latency as its task last saw them, for [`Stats`]: written by the
100/// shard's task when they change, read when a cluster is asked.
101#[derive(Debug)]
102pub(crate) struct ShardSlot {
103    number: u32,
104    status: AtomicU8,
105    /// In nanoseconds; `u64::MAX` before the first heartbeat acknowledgement.
106    latency: AtomicU64,
107}
108
109impl ShardSlot {
110    pub(crate) const fn new(number: u32) -> Self {
111        Self {
112            number,
113            status: AtomicU8::new(ShardStatus::Disconnected as u8),
114            latency: AtomicU64::new(u64::MAX),
115        }
116    }
117
118    pub(crate) const fn number(&self) -> u32 {
119        self.number
120    }
121
122    pub(crate) fn set_state(&self, state: ShardState) {
123        self.status
124            .store(ShardStatus::from(state) as u8, Ordering::Relaxed);
125    }
126
127    pub(crate) fn set_latency(&self, latency: Option<Duration>) {
128        let nanos = latency.map_or(u64::MAX, |latency| {
129            u64::try_from(latency.as_nanos()).unwrap_or(u64::MAX - 1)
130        });
131        self.latency.store(nanos, Ordering::Relaxed);
132    }
133
134    pub(crate) fn stats(&self) -> ShardStats {
135        let status = match self.status.load(Ordering::Relaxed) {
136            1 => ShardStatus::Identifying,
137            2 => ShardStatus::Resuming,
138            3 => ShardStatus::Active,
139            4 => ShardStatus::Closed,
140            _ => ShardStatus::Disconnected,
141        };
142        let latency = match self.latency.load(Ordering::Relaxed) {
143            u64::MAX => None,
144            nanos => Some(Duration::from_nanos(nanos)),
145        };
146        ShardStats {
147            id: self.number,
148            status,
149            latency,
150        }
151    }
152}
153
154/// What a shard's task reports to its [`ShardSlot`]: nothing outside a cluster process.
155/// The state is written only when it changes.
156#[derive(Debug)]
157pub(crate) struct Reporter {
158    slot: Option<Arc<ShardSlot>>,
159    reported: ShardState,
160}
161
162impl Reporter {
163    pub(crate) const fn new(slot: Option<Arc<ShardSlot>>) -> Self {
164        Self {
165            slot,
166            reported: ShardState::Disconnected,
167        }
168    }
169
170    pub(crate) fn latency(&self, latency: Option<Duration>) {
171        if let Some(slot) = &self.slot {
172            slot.set_latency(latency);
173        }
174    }
175
176    pub(crate) fn state(&mut self, state: ShardState) {
177        if state != self.reported
178            && let Some(slot) = &self.slot
179        {
180            slot.set_state(state);
181            self.reported = state;
182        }
183    }
184}
185
186/// The resident set size of this process, in bytes.
187pub(crate) fn resident_memory() -> Option<u64> {
188    #[cfg(target_os = "linux")]
189    {
190        // A small file the kernel writes on read: no disk access.
191        let status = std::fs::read_to_string("/proc/self/status").ok()?;
192        let line = status.lines().find(|line| line.starts_with("VmRSS:"))?;
193        let kib: u64 = line
194            .trim_start_matches("VmRSS:")
195            .trim()
196            .trim_end_matches("kB")
197            .trim()
198            .parse()
199            .ok()?;
200        kib.checked_mul(1024)
201    }
202    #[cfg(not(target_os = "linux"))]
203    {
204        None
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use core::time::Duration;
211
212    use djs_gateway::ShardState;
213    use djs_model::gateway::CloseCode;
214
215    use super::{ShardSlot, ShardStatus, resident_memory};
216
217    #[test]
218    fn slots_report_the_last_state_and_latency() {
219        let slot = ShardSlot::new(3);
220        let stats = slot.stats();
221        assert_eq!(
222            (stats.id, stats.status, stats.latency),
223            (3, ShardStatus::Disconnected, None)
224        );
225        for (state, status) in [
226            (ShardState::Identifying, ShardStatus::Identifying),
227            (ShardState::Resuming, ShardStatus::Resuming),
228            (ShardState::Active, ShardStatus::Active),
229            (ShardState::Closed, ShardStatus::Closed),
230            (
231                ShardState::FatallyClosed(CloseCode::AuthenticationFailed),
232                ShardStatus::Closed,
233            ),
234            (ShardState::Disconnected, ShardStatus::Disconnected),
235        ] {
236            slot.set_state(state);
237            assert_eq!(slot.stats().status, status);
238        }
239        slot.set_latency(Some(Duration::from_millis(42)));
240        assert_eq!(slot.stats().latency, Some(Duration::from_millis(42)));
241        slot.set_latency(None);
242        assert_eq!(slot.stats().latency, None);
243    }
244
245    #[test]
246    fn statuses_have_a_stable_wire_format() {
247        assert_eq!(
248            serde_json::to_string(&ShardStatus::Active).unwrap(),
249            r#""active""#
250        );
251    }
252
253    #[cfg(target_os = "linux")]
254    #[test]
255    fn the_resident_memory_is_read_on_linux() {
256        let memory = resident_memory().unwrap();
257        // More than a megabyte and less than the 6 GiB the guard allows.
258        assert!((1 << 20..6 << 30).contains(&memory), "{memory}");
259    }
260}