iec61850_kit/common/machine.rs
1use alloc::collections::VecDeque;
2
3use super::UtcTime;
4
5/// A monotonic point in time, in nanoseconds from an arbitrary origin.
6///
7/// The protocol cores never read a clock: every input carries the caller's `now`. A plain
8/// integer keeps the type available in `no_std` and makes simulated time trivial.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
10pub struct Instant(pub u64);
11
12impl Instant {
13 /// The origin.
14 pub const ZERO: Instant = Instant(0);
15
16 /// This instant plus `ns` nanoseconds (saturating).
17 #[must_use]
18 pub const fn plus_nanos(self, ns: u64) -> Instant {
19 Instant(self.0.saturating_add(ns))
20 }
21
22 /// This instant plus `ms` milliseconds (saturating).
23 #[must_use]
24 pub const fn plus_millis(self, ms: u64) -> Instant {
25 Instant(self.0.saturating_add(ms.saturating_mul(1_000_000)))
26 }
27
28 /// Nanoseconds from `earlier` to `self`, or 0 if `earlier` is later.
29 pub const fn nanos_since(self, earlier: Instant) -> u64 {
30 self.0.saturating_sub(earlier.0)
31 }
32}
33
34/// The process's monotonic clock as an [`Instant`]: nanoseconds since the first call.
35///
36/// One epoch for the whole process, so the server, the CLI and a live link agree on what an
37/// instant means. Only the I/O edges read it; the cores take `now` as an argument.
38#[cfg(feature = "std")]
39pub fn monotonic_now() -> Instant {
40 use std::sync::OnceLock;
41 static EPOCH: OnceLock<std::time::Instant> = OnceLock::new();
42 Instant(EPOCH.get_or_init(std::time::Instant::now).elapsed().as_nanos().min(u128::from(u64::MAX)) as u64)
43}
44
45/// The two clocks a server needs at once, carried together so they cannot be swapped.
46///
47/// There are exactly two kinds of time here and they answer different questions:
48/// [`Now::mono`] is a monotonic [`Instant`] and is what every deadline, window and duration is
49/// measured on; [`Now::wall`] is an absolute [`UtcTime`] and is what every *published*
50/// timestamp carries — a report's `TimeOfEntry`, a log entry, an `SGCB`'s `LActTm`, the status
51/// timestamp an operate writes.
52///
53/// Neither may be derived from the other, and passing them as one value is what stops a
54/// signature from letting a caller pass the wrong one: a monotonic instant reinterpreted as a
55/// date reads as 1970-01-01 plus the process's uptime, which every test where both ends are
56/// ours will happily agree on.
57#[derive(Clone, Copy, Debug, PartialEq, Eq)]
58pub struct Now {
59 /// Monotonic, for deadlines and durations.
60 pub mono: Instant,
61 /// Absolute, for timestamps that leave the process.
62 pub wall: UtcTime,
63}
64
65impl Now {
66 /// Both readings, taken together.
67 pub const fn new(mono: Instant, wall: UtcTime) -> Now {
68 Now { mono, wall }
69 }
70
71 /// The wall reading as the six-octet `EntryTime` the report and log services publish.
72 pub const fn entry(self) -> super::EntryTime {
73 super::EntryTime::from_unix_millis(self.wall.to_unix_nanos() / 1_000_000)
74 }
75}
76
77/// A source of wall-clock time with quality, as IEC 61850 needs it.
78///
79/// Implementations: a PTP-disciplined PHC, an SNTP client, or [`ManualClock`] in tests.
80///
81/// `Debug` is a supertrait for the same reason [`FileStore`](crate::server::FileStore) has
82/// one: a clock is a field of a server that derives `Debug`, and a trait object that cannot
83/// be printed forces every holder to hand-write the impl.
84pub trait Clock: core::fmt::Debug {
85 /// The current UTC time with its quality bits.
86 fn now(&self) -> UtcTime;
87}
88
89/// The system's own wall clock, as [`std::time::SystemTime`] reports it.
90///
91/// This is the default clock of a server built on `std`. It reports
92/// [`TimeQuality::SYNCHRONIZED`](super::TimeQuality::SYNCHRONIZED) with no leap-second or
93/// accuracy claim, because a plain
94/// system clock knows nothing about how it is disciplined; a deployment that runs
95/// `ptp4l`/`phc2sys` replaces it with a clock that does.
96#[cfg(feature = "std")]
97#[derive(Clone, Copy, Debug, Default)]
98pub struct SystemClock;
99
100#[cfg(feature = "std")]
101impl Clock for SystemClock {
102 fn now(&self) -> UtcTime {
103 let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| u64::try_from(d.as_nanos()).unwrap_or(u64::MAX));
104 UtcTime::from_unix_nanos(nanos, super::TimeQuality::SYNCHRONIZED)
105 }
106}
107
108/// A clock that returns whatever it was last told. For tests and simulation.
109#[derive(Clone, Copy, Debug, Default)]
110pub struct ManualClock {
111 now: UtcTime,
112}
113
114impl ManualClock {
115 /// A manual clock reading `now`.
116 pub const fn new(now: UtcTime) -> Self {
117 ManualClock { now }
118 }
119
120 /// Set the time that subsequent [`Clock::now`] calls return.
121 pub fn set(&mut self, now: UtcTime) {
122 self.now = now;
123 }
124}
125
126impl Clock for ManualClock {
127 fn now(&self) -> UtcTime {
128 self.now
129 }
130}
131
132/// A bounded FIFO of pending events.
133///
134/// Every core in this crate hands events to the application through one of these. The bound
135/// matters: a 4.8 kHz sampled-value stream, or a publisher whose frames nobody collects,
136/// would otherwise grow an unbounded queue in a process that has stopped draining it. When
137/// the queue is full the **oldest** event is dropped — the newest state is the one that
138/// matters for protection — and [`EventQueue::dropped`] counts what was lost so the
139/// application can tell a quiet system from one it is not keeping up with.
140#[derive(Debug)]
141pub struct EventQueue<T> {
142 items: VecDeque<T>,
143 capacity: usize,
144 dropped: u64,
145}
146
147impl<T> EventQueue<T> {
148 /// A queue holding at most `capacity` events (at least one).
149 pub fn new(capacity: usize) -> Self {
150 EventQueue { items: VecDeque::new(), capacity: capacity.max(1), dropped: 0 }
151 }
152
153 /// Append an event, dropping the oldest if the queue is full.
154 pub fn push(&mut self, item: T) {
155 if self.items.len() >= self.capacity {
156 self.items.pop_front();
157 self.dropped = self.dropped.saturating_add(1);
158 }
159 self.items.push_back(item);
160 }
161
162 /// Take the oldest event.
163 pub fn pop(&mut self) -> Option<T> {
164 self.items.pop_front()
165 }
166
167 /// Number of events dropped because the application was not draining.
168 pub const fn dropped(&self) -> u64 {
169 self.dropped
170 }
171
172 /// Events waiting.
173 pub fn len(&self) -> usize {
174 self.items.len()
175 }
176
177 /// True when nothing is waiting.
178 pub fn is_empty(&self) -> bool {
179 self.items.is_empty()
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186
187 #[test]
188 fn queue_drops_oldest_and_counts() {
189 let mut q = EventQueue::new(2);
190 q.push(1);
191 q.push(2);
192 q.push(3);
193 assert_eq!(q.dropped(), 1);
194 assert_eq!(q.pop(), Some(2));
195 assert_eq!(q.pop(), Some(3));
196 assert_eq!(q.pop(), None);
197 assert!(q.is_empty());
198 // A zero capacity is clamped to one rather than dropping everything silently.
199 let mut q0 = EventQueue::new(0);
200 q0.push(7);
201 assert_eq!(q0.pop(), Some(7));
202 }
203
204 #[test]
205 fn instant_saturates() {
206 assert_eq!(Instant(u64::MAX).plus_millis(1), Instant(u64::MAX));
207 assert_eq!(Instant(5).nanos_since(Instant(9)), 0);
208 assert_eq!(Instant(9).nanos_since(Instant(5)), 4);
209 }
210}