1use 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#[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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
35#[non_exhaustive]
36pub struct ClusterStats {
37 pub cluster: u32,
39 pub shards: Vec<ShardStats>,
41 pub guilds: Option<u64>,
43 pub users: Option<u64>,
45 pub uptime: Duration,
47 pub memory: Option<u64>,
50}
51
52#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
56#[non_exhaustive]
57pub struct ShardStats {
58 pub id: u32,
60 pub status: ShardStatus,
62 pub latency: Option<Duration>,
64}
65
66#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
71#[serde(rename_all = "snake_case")]
72#[non_exhaustive]
73pub enum ShardStatus {
74 Disconnected,
76 Identifying,
78 Resuming,
80 Active,
82 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 _ => Self::Disconnected,
95 }
96 }
97}
98
99#[derive(Debug)]
102pub(crate) struct ShardSlot {
103 number: u32,
104 status: AtomicU8,
105 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#[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
186pub(crate) fn resident_memory() -> Option<u64> {
188 #[cfg(target_os = "linux")]
189 {
190 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 assert!((1 << 20..6 << 30).contains(&memory), "{memory}");
259 }
260}