Skip to main content

wire/frames/
monitor.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4// Copyright (c) 2026 2youg1 and the sprawling contributors
5
6//! The performance monitor's pair of frames (`crates/wire/spec/Frames/Monitor.lean` §8-47g):
7//! whether a session is watching, and one reading sent to it; and the
8//! sampling beat a page sets for the city (§8-47i).
9
10use kernel::{AxCode, AxError};
11use serde::{Deserialize, Serialize};
12
13/// The shortest beat a page may set, in milliseconds.
14pub const BEAT_MIN_MS: u32 = 10;
15/// The longest beat a page may set, in milliseconds.
16pub const BEAT_MAX_MS: u32 = 1_000;
17
18/// How often the monitor reads this process's private bytes, and a tenth
19/// of how often it sends a reading (§8-47i). Only a beat inside
20/// [`BEAT_MIN_MS`]`..=`[`BEAT_MAX_MS`] can be made, on the wire as off it.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(try_from = "u32", into = "u32")]
23#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
24pub struct BeatMs(u32);
25
26impl BeatMs {
27    /// The beat a city samples at until a page sets another (Roadmap M0
28    /// item 7).
29    pub const DEFAULT: BeatMs = BeatMs(100);
30
31    /// # Errors
32    /// `InvalidArgs` for a beat outside the range a page may set.
33    pub fn new(ms: u32) -> Result<BeatMs, AxError> {
34        if (BEAT_MIN_MS..=BEAT_MAX_MS).contains(&ms) {
35            Ok(BeatMs(ms))
36        } else {
37            Err(AxError::failure(
38                AxCode::InvalidArgs,
39                "set the monitor's beat",
40                format!("{ms} ms"),
41            )
42            .with_recovery(format!(
43                "choose a beat from {BEAT_MIN_MS} to {BEAT_MAX_MS} milliseconds"
44            )))
45        }
46    }
47
48    #[must_use]
49    pub fn ms(self) -> u32 {
50        self.0
51    }
52}
53
54impl TryFrom<u32> for BeatMs {
55    type Error = AxError;
56
57    fn try_from(ms: u32) -> Result<BeatMs, AxError> {
58        BeatMs::new(ms)
59    }
60}
61
62impl From<BeatMs> for u32 {
63    fn from(beat: BeatMs) -> u32 {
64        beat.0
65    }
66}
67
68/// Whether this session counts as somebody watching the monitor.
69#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(rename_all = "snake_case")]
71#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
72pub enum Monitoring {
73    /// Watch the whole monitor page.
74    Watch,
75    /// Watch only the one-line summary beside the settings tree's performance entry, which reads this process alone.
76    WatchSummary,
77    Release,
78    /// Sample at this beat from now on, and remember it for this city.
79    Beat(BeatMs),
80}
81
82/// What one watcher looks at, which decides how much the city reads for
83/// it. It does not travel: it is what `MonitorFeed::watch` is told.
84#[derive(Debug, Clone, Copy, PartialEq, Eq)]
85pub enum Watched {
86    Everything,
87    Summary,
88}
89
90/// One reading of every counter the monitor shows, in integers because
91/// it travels on the wire (`crates/sprawling/Spec.lean` §8-94, §8-129-6).
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
93#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
94pub struct Sample {
95    pub core_cpu_permille: u64,
96    pub core_private_bytes: u64,
97    pub core_working_set_bytes: u64,
98    pub core_read_bytes: u64,
99    pub core_written_bytes: u64,
100    pub machine_cpu_permille: u64,
101    pub machine_available_bytes: u64,
102    pub volume_free_bytes: u64,
103    pub ledger_queue_depth: u64,
104    pub durable_lag: u64,
105    pub relay_p50_nanos: u64,
106    pub event_to_screen_p50_nanos: u64,
107    pub queued_runs: u64,
108    /// Committed records the writer has handed the view thread that are
109    /// not yet folded and broadcast (`crates/sprawling/Spec.lean` §8-123).
110    pub view_backlog: u64,
111    /// How long the beat before this one took to read the counters, by
112    /// the sampler's own monotonic clock; 0 on the first beat
113    /// (`crates/sprawling/Spec.lean` §8-129-6).
114    pub read_nanos: u64,
115    /// The beat this reading was sampled at, in milliseconds (§8-47i):
116    /// what the page's beat control reads as the current setting.
117    pub beat_ms: u64,
118}
119
120#[cfg(all(test, feature = "server"))]
121#[allow(clippy::unwrap_used, clippy::panic, reason = "test code")]
122mod tests {
123    use crate::frames::ClientFrame;
124    use crate::reception::{BindFace, SessionState, SessionStep, WelcomeFacts, decide_frame};
125
126    /// A beat inside the range reaches the shell as the step that sets it;
127    /// one outside it is not a frame at all, so the shell never holds a
128    /// beat it has to judge again (§8-47i).
129    #[test]
130    fn a_beat_in_range_is_a_step_and_one_outside_is_no_frame() {
131        let read = |text: &str| serde_json::from_str::<ClientFrame>(text);
132        let frame = read(r#"{"monitor":{"beat":250}}"#).unwrap();
133        let face = BindFace::Loopback { token: None };
134        let step = decide_frame(SessionState::Live, frame, &face, WelcomeFacts::default());
135        let SessionStep::Beat(beat) = step else {
136            panic!("a live session's beat is a step: {step:?}");
137        };
138        assert_eq!(
139            (
140                beat.ms(),
141                read(r#"{"monitor":{"beat":5}}"#).is_err(),
142                read(r#"{"monitor":{"beat":1001}}"#).is_err()
143            ),
144            (250, true, true)
145        );
146    }
147}