Skip to main content

rusty_time_api/
lib.rs

1//! rusty_time-api — typed reports and ops.
2//!
3//! Everything a human sees through `rtimec` or `rtimed --json` is one of these
4//! types serialized as JSON: the CLI is a thin consumer, and a test or an agent
5//! is the same consumer with a different transport (mission plan §5). Internal
6//! wire moves to oxicode at M4; the public shape stays JSON.
7
8use serde::{Deserialize, Serialize};
9
10/// One measured exchange, as reported by `rtimed query`.
11#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
12pub struct SampleReport {
13    /// Seconds to ADD to the local clock.
14    pub offset_s: f64,
15    /// Round-trip delay, seconds.
16    pub delay_s: f64,
17    /// Server stratum.
18    pub stratum: u8,
19    /// Server-reported root delay + dispersion, seconds.
20    pub root_delay_s: f64,
21    pub root_dispersion_s: f64,
22}
23
24/// Where the control plane actually listens, resolved from what the operator
25/// typed.
26///
27/// Unix has domain sockets, Windows does not (its equivalent is a named pipe,
28/// which lands with the Win32 pipe server). Rather than make every script and
29/// CI job branch on the platform, the *same* `--control` argument resolves on
30/// both: a path becomes a deterministic loopback port on Windows, derived from
31/// the path text so the daemon and `rtimec` independently agree on it.
32///
33/// The daemon prints the resolved endpoint at startup, so the mapping is
34/// visible rather than a silent surprise.
35#[derive(Clone, Debug, PartialEq, Eq, Hash)]
36pub enum ControlEndpoint {
37    /// A Unix domain socket at this path.
38    UnixPath(String),
39    /// A TCP endpoint on loopback.
40    Loopback(u16),
41}
42
43/// Loopback ports we derive into: the IANA dynamic range, avoiding anything an
44/// OS is likely to hand out for an ephemeral connection.
45const DERIVED_PORT_BASE: u16 = 49_200;
46const DERIVED_PORT_SPAN: u16 = 300;
47
48/// The default control name.
49///
50/// Defined here, once, because the daemon and `rtimec` must agree: on Windows
51/// the name is hashed into a port, so two *different* default strings would
52/// resolve to two different ports and `rtimec` would quietly fail to find a
53/// daemon that is running perfectly well.
54pub fn default_control_spec() -> String {
55    #[cfg(windows)]
56    {
57        "rusty_time".to_string()
58    }
59    #[cfg(not(windows))]
60    {
61        match std::env::var("XDG_RUNTIME_DIR") {
62            Ok(dir) if !dir.is_empty() => format!("{dir}/rusty_time.sock"),
63            _ => "/tmp/rusty_time.sock".to_string(),
64        }
65    }
66}
67
68/// Resolve a `--control` argument for this platform.
69pub fn control_endpoint(spec: &str) -> ControlEndpoint {
70    // An explicit host:port is honoured everywhere.
71    if let Some((_, port)) = spec.rsplit_once(':')
72        && let Ok(port) = port.parse::<u16>()
73    {
74        return ControlEndpoint::Loopback(port);
75    }
76
77    if cfg!(windows) {
78        ControlEndpoint::Loopback(derive_port(spec))
79    } else {
80        ControlEndpoint::UnixPath(spec.to_string())
81    }
82}
83
84/// A stable port for a given control name. FNV-1a: tiny, dependency-free, and
85/// — the property that matters — identical in both processes and across runs.
86fn derive_port(spec: &str) -> u16 {
87    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
88    for byte in spec.as_bytes() {
89        hash ^= *byte as u64;
90        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
91    }
92    DERIVED_PORT_BASE + (hash % DERIVED_PORT_SPAN as u64) as u16
93}
94
95/// What NTS did during a query (`status.ntsdata`'s client half).
96#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
97pub struct NtsReport {
98    /// The host key establishment ran against.
99    pub ke_host: String,
100    /// The NTP server KE pointed us at — may differ from `ke_host`.
101    pub ntp_server: String,
102    pub ntp_port: u16,
103    /// Responses that passed AEAD verification.
104    pub authenticated: u32,
105    /// Responses dropped because they did not (forged, stale cookie, NAK).
106    pub rejected: u32,
107    /// Unspent cookies remaining when the query finished.
108    pub cookies_after: usize,
109}
110
111/// The result of a one-shot `rtimed query`.
112#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
113pub struct QueryReport {
114    pub server: String,
115    pub address: String,
116    /// Exchanges attempted and completed.
117    pub sent: u32,
118    pub received: u32,
119    pub samples: Vec<SampleReport>,
120    /// Minimum-delay sample's offset — the headline number.
121    pub best_offset_s: Option<f64>,
122    pub best_delay_s: Option<f64>,
123    /// Regression view when enough samples exist.
124    pub regress_offset_s: Option<f64>,
125    pub regress_freq_ppm: Option<f64>,
126    pub regress_sd_s: Option<f64>,
127    /// Reference ID of the server (textual for stratum 1, hex otherwise).
128    pub reference_id: String,
129    pub leap: String,
130    /// Present only when the query ran under NTS.
131    #[serde(skip_serializing_if = "Option::is_none", default)]
132    pub nts: Option<NtsReport>,
133}
134
135/// Daemon tracking state (the `status.tracking` op).
136///
137/// **Read `synchronized` first.** It is true only when a correction actually
138/// reached the clock, and the other fields are only meaningful when it is: an
139/// unsynchronized daemon is running an OPEN loop (a dry run never steers, and
140/// an acquiring loop has not converged), so its `freq_ppm` is not a drift
141/// measurement and its `offset_s` is an estimate nothing has acted on. A
142/// consumer deciding anything on this report — a capability expiry, a
143/// settlement timestamp — should treat `synchronized == false` as "no usable
144/// time from here" rather than reading the numbers beside it.
145#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
146pub struct TrackingReport {
147    /// Whether a correction actually reached the clock. See the type docs:
148    /// every other field is conditioned on this.
149    pub synchronized: bool,
150    pub offset_s: f64,
151    pub freq_ppm: f64,
152    pub error_bound_s: f64,
153    pub poll_log2: i8,
154}
155
156/// Server counters (`status.serverstats`) — the chronyc `serverstats` analog.
157#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
158pub struct ServerStatsReport {
159    pub ntp_requests: u64,
160    pub ntp_responses: u64,
161    pub dropped_rate_limit: u64,
162    pub kiss_of_death: u64,
163    pub interleaved_responses: u64,
164    pub refused: u64,
165    pub clients_tracked: usize,
166    pub clients_evicted: u64,
167    pub uptime_s: u64,
168    pub stratum: u8,
169}
170
171/// One row of the MRU client log (`debug.clients`).
172#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
173pub struct ClientRow {
174    pub address: String,
175    /// Seconds since this client was last seen.
176    pub last_seen_ago_s: f64,
177    pub requests: u64,
178    pub responses: u64,
179    pub dropped: u64,
180    /// Whether this client is currently using interleaved mode.
181    pub interleaved: bool,
182}
183
184/// A request on the control socket. One variant per op (mission plan §5): the
185/// CLI, a test and an agent are all just clients of these.
186#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
187#[serde(tag = "op", rename_all = "snake_case")]
188pub enum ControlRequest {
189    /// `status.serverstats`
190    ServerStats,
191    /// `debug.clients`
192    Clients { limit: usize },
193    /// `status.ntsdata` — key ids only, never key material.
194    NtsData,
195    /// `status.tracking` — the client discipline loop's current estimate:
196    /// how far off this clock believes it is, how well it knows that, and
197    /// whether it is synchronized at all.
198    ///
199    /// Answered by `rtimed sync`; a `rtimed serve` daemon has no discipline
200    /// loop and reports that rather than inventing a number.
201    Tracking,
202    /// Liveness.
203    Ping,
204}
205
206/// The answer to a [`ControlRequest`].
207#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
208#[serde(tag = "result", rename_all = "snake_case")]
209pub enum ControlResponse {
210    ServerStats(ServerStatsReport),
211    /// A struct variant, not `Clients(Vec<..>)`, deliberately: serde's
212    /// internally-tagged representation cannot encode a newtype variant that
213    /// wraps a *sequence*, and the failure appears only at serialization —
214    /// the op works in-process and returns an empty reply over the socket.
215    Clients {
216        rows: Vec<ClientRow>,
217    },
218    NtsData {
219        /// Master key identifiers currently held. Key material is never
220        /// serialized — an operator needs to know rotation happened, not what
221        /// the keys are.
222        master_key_ids: Vec<u32>,
223    },
224    /// A newtype over a STRUCT, which the internally-tagged representation
225    /// flattens to `{"result":"tracking", <fields>}` — the same shape
226    /// `ServerStats` already produces. (Contrast `Clients` above, which cannot
227    /// be a newtype because it wraps a sequence.)
228    Tracking(TrackingReport),
229    Pong {
230        version: String,
231    },
232    Error {
233        message: String,
234    },
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn query_report_json_shape_is_stable() {
243        let r = QueryReport {
244            server: "pool.ntp.org".into(),
245            address: "1.2.3.4:123".into(),
246            sent: 4,
247            received: 4,
248            samples: vec![SampleReport {
249                offset_s: 0.0012,
250                delay_s: 0.031,
251                stratum: 2,
252                root_delay_s: 0.01,
253                root_dispersion_s: 0.002,
254            }],
255            best_offset_s: Some(0.0012),
256            best_delay_s: Some(0.031),
257            regress_offset_s: None,
258            regress_freq_ppm: None,
259            regress_sd_s: None,
260            reference_id: "c0a80101".into(),
261            leap: "no-warning".into(),
262            nts: None,
263        };
264        let json = serde_json::to_string(&r).expect("serialize");
265        let back: QueryReport = serde_json::from_str(&json).expect("deserialize");
266        assert_eq!(r, back);
267        // Public wire fields are snake_case with explicit units in the name.
268        assert!(json.contains("\"best_offset_s\""));
269        // A plain query must not emit an empty nts object.
270        assert!(!json.contains("\"nts\""));
271    }
272
273    #[test]
274    fn the_default_spec_resolves_the_same_way_for_everyone() {
275        // The daemon and rtimec each call this independently. If they ever
276        // produced different strings, Windows would hash them to different
277        // ports and rtimec would report "is rtimed running?" about a daemon
278        // that is running fine.
279        let a = control_endpoint(&default_control_spec());
280        let b = control_endpoint(&default_control_spec());
281        assert_eq!(a, b);
282    }
283
284    #[test]
285    fn an_explicit_port_is_honoured_on_every_platform() {
286        assert_eq!(
287            control_endpoint("127.0.0.1:9999"),
288            ControlEndpoint::Loopback(9999)
289        );
290    }
291
292    #[test]
293    fn the_same_path_resolves_identically_in_both_processes() {
294        // The daemon and rtimec each resolve independently; if they disagreed,
295        // rtimec would connect to a port nothing is listening on.
296        let a = control_endpoint("/run/rusty_time.sock");
297        let b = control_endpoint("/run/rusty_time.sock");
298        assert_eq!(a, b, "resolution must be deterministic");
299    }
300
301    #[test]
302    fn different_names_get_different_endpoints() {
303        // Two daemons with different control names must not collide, or the
304        // second would fail to bind and the first would answer for both.
305        let mut seen = std::collections::HashSet::new();
306        let names = [
307            "/run/rusty_time.sock",
308            "/tmp/a.sock",
309            "/tmp/b.sock",
310            "rusty_time",
311            "test-rig-1",
312            "test-rig-2",
313        ];
314        for name in names {
315            seen.insert(control_endpoint(name));
316        }
317        assert!(
318            seen.len() >= names.len() - 1,
319            "control names collided: {seen:?}"
320        );
321    }
322
323    #[test]
324    fn derived_ports_stay_in_the_intended_range() {
325        for name in ["a", "b", "/very/long/path/to/a/socket", ""] {
326            let port = derive_port(name);
327            assert!(
328                (DERIVED_PORT_BASE..DERIVED_PORT_BASE + DERIVED_PORT_SPAN).contains(&port),
329                "{name} derived out-of-range port {port}"
330            );
331        }
332    }
333
334    #[cfg(unix)]
335    #[test]
336    fn a_path_stays_a_unix_socket_on_unix() {
337        assert_eq!(
338            control_endpoint("/run/rusty_time.sock"),
339            ControlEndpoint::UnixPath("/run/rusty_time.sock".into())
340        );
341    }
342
343    #[test]
344    fn control_ops_round_trip_over_the_wire() {
345        // Every op must survive the JSON hop unchanged: rtimec, a test and an
346        // agent are the same client with different transports.
347        let requests = vec![
348            ControlRequest::Ping,
349            ControlRequest::ServerStats,
350            ControlRequest::Clients { limit: 10 },
351            ControlRequest::NtsData,
352        ];
353        for req in requests {
354            let json = serde_json::to_string(&req).expect("serialize");
355            let back: ControlRequest = serde_json::from_str(&json).expect("deserialize");
356            assert_eq!(req, back, "op did not survive the wire: {json}");
357        }
358
359        let responses = vec![
360            ControlResponse::Pong {
361                version: "0.1.0".into(),
362            },
363            ControlResponse::ServerStats(ServerStatsReport {
364                ntp_requests: 10,
365                ntp_responses: 8,
366                dropped_rate_limit: 2,
367                ..ServerStatsReport::default()
368            }),
369            ControlResponse::Clients {
370                rows: vec![ClientRow {
371                    address: "192.0.2.1:123".into(),
372                    last_seen_ago_s: 1.5,
373                    requests: 3,
374                    responses: 3,
375                    dropped: 0,
376                    interleaved: true,
377                }],
378            },
379            ControlResponse::NtsData {
380                master_key_ids: vec![1, 2],
381            },
382            ControlResponse::Error {
383                message: "nope".into(),
384            },
385        ];
386        for resp in responses {
387            let json = serde_json::to_string(&resp).expect("serialize");
388            let back: ControlResponse = serde_json::from_str(&json).expect("deserialize");
389            assert_eq!(resp, back);
390        }
391    }
392
393    #[test]
394    fn nts_data_never_carries_key_material() {
395        // The type makes it unrepresentable: there is nowhere to put a key.
396        let resp = ControlResponse::NtsData {
397            master_key_ids: vec![0xDEAD_BEEF],
398        };
399        let json = serde_json::to_string(&resp).expect("serialize");
400        assert!(json.contains("master_key_ids"));
401        assert!(!json.contains("key\":\"") && !json.to_lowercase().contains("secret"));
402    }
403
404    #[test]
405    fn nts_report_round_trips() {
406        let mut r = QueryReport {
407            server: "time.cloudflare.com".into(),
408            address: "1.1.1.1:123".into(),
409            sent: 4,
410            received: 4,
411            samples: Vec::new(),
412            best_offset_s: Some(-0.002),
413            best_delay_s: Some(0.02),
414            regress_offset_s: None,
415            regress_freq_ppm: None,
416            regress_sd_s: None,
417            reference_id: "0a0a0a0a".into(),
418            leap: "no-warning".into(),
419            nts: Some(NtsReport {
420                ke_host: "time.cloudflare.com".into(),
421                ntp_server: "time.cloudflare.com".into(),
422                ntp_port: 123,
423                authenticated: 4,
424                rejected: 0,
425                cookies_after: 8,
426            }),
427        };
428        let json = serde_json::to_string(&r).expect("serialize");
429        assert!(json.contains("\"authenticated\":4"));
430        let back: QueryReport = serde_json::from_str(&json).expect("deserialize");
431        assert_eq!(r, back);
432        r.nts = None;
433        assert_ne!(r, back);
434    }
435}