Skip to main content

kizz_store/
machine.rs

1// Copyright (c) 2026 Sakura Industries LLC.
2//
3// SPDX-License-Identifier: AGPL-3.0-only
4
5//! The machine state that step records keep ("Machine state").
6//!
7//! Every step that runs records the [`MachineStateRecord`] that its command started
8//! with, in the six parts that [`MachinePart`] names. A step names, with
9//! `run(..., machine = [...])`, the parts that count as its inputs: the cache check
10//! compares only those, value by value, with [`machine_changes`], and `kizz why`
11//! shows their values, and with `--verbose` every part, with
12//! [`MachineStateRecord::text`].
13//!
14//! The host name, the credentials, the umask, the machine architecture and the CPU
15//! model are not per step: they are the [cache identity](crate::identity).
16
17use std::fmt;
18
19use minicbor::{Decode, Encode};
20
21/// One part of the machine state, as `run(..., machine = [...])` names it.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
23pub enum MachinePart {
24    /// `kernel`: the kernel release and version.
25    Kernel,
26    /// `limits`: every resource limit, soft and hard.
27    Limits,
28    /// `affinity`: the CPUs the command may run on.
29    Affinity,
30    /// `memory`: the total and the available memory.
31    Memory,
32    /// `filesystem`: the type and mount flags of the file system that holds the
33    /// working directory.
34    Filesystem,
35    /// `disk`: the size and free space of that file system.
36    Disk,
37}
38
39impl MachinePart {
40    /// Every part, in the order the spec lists them.
41    pub const ALL: [Self; 6] = [
42        Self::Kernel,
43        Self::Limits,
44        Self::Affinity,
45        Self::Memory,
46        Self::Filesystem,
47        Self::Disk,
48    ];
49
50    /// The name of the part, as `run()` takes it.
51    #[must_use]
52    pub const fn name(self) -> &'static str {
53        match self {
54            Self::Kernel => "kernel",
55            Self::Limits => "limits",
56            Self::Affinity => "affinity",
57            Self::Memory => "memory",
58            Self::Filesystem => "filesystem",
59            Self::Disk => "disk",
60        }
61    }
62
63    /// The part named `name`, or `None` when no part has that name.
64    #[must_use]
65    pub fn from_name(name: &str) -> Option<Self> {
66        Self::ALL.into_iter().find(|part| part.name() == name)
67    }
68
69    /// The parts named in `names`, in that order, leaving out a name that no part
70    /// has.
71    #[must_use]
72    pub fn parts(names: &[String]) -> Vec<Self> {
73        names
74            .iter()
75            .filter_map(|name| Self::from_name(name))
76            .collect()
77    }
78
79    /// The names of every part, as an error lists them: `kernel, limits, affinity,
80    /// memory, filesystem and disk`.
81    #[must_use]
82    pub fn names_text() -> String {
83        let names: Vec<&str> = Self::ALL.iter().map(|part| part.name()).collect();
84        match names.split_last() {
85            Some((last, rest)) => format!("{} and {last}", rest.join(", ")),
86            None => String::new(),
87        }
88    }
89}
90
91impl fmt::Display for MachinePart {
92    fn fmt(
93        &self,
94        f: &mut fmt::Formatter<'_>,
95    ) -> fmt::Result {
96        f.write_str(self.name())
97    }
98}
99
100/// The kernel that ran a command.
101#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
102pub struct KernelRecord {
103    /// The kernel release.
104    #[n(0)]
105    pub release: String,
106    /// The kernel version.
107    #[n(1)]
108    pub version: String,
109}
110
111/// One resource limit, soft and hard.
112#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
113pub struct LimitRecord {
114    /// The resource, as `prlimit` names it, such as `nofile`.
115    #[n(0)]
116    pub resource: String,
117    /// The soft limit, or `None` when it is unlimited.
118    #[n(1)]
119    pub soft: Option<u64>,
120    /// The hard limit, or `None` when it is unlimited.
121    #[n(2)]
122    pub hard: Option<u64>,
123}
124
125/// The memory of the machine, in bytes.
126#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encode, Decode)]
127pub struct MemoryRecord {
128    /// The total memory.
129    #[n(0)]
130    pub total: u64,
131    /// The memory available to start new work without swapping.
132    #[n(1)]
133    pub available: u64,
134}
135
136/// The file system that held the working directory.
137#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encode, Decode)]
138pub struct FileSystemRecord {
139    /// The type of the file system, as the platform numbers it.
140    #[n(0)]
141    pub kind: u64,
142    /// The mount flags, as the platform numbers them.
143    #[n(1)]
144    pub flags: u64,
145}
146
147/// The size and free space of the file system that held the working directory, in
148/// bytes.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Encode, Decode)]
150pub struct DiskRecord {
151    /// The size of the file system.
152    #[n(0)]
153    pub size: u64,
154    /// The free space that a process without privileges may use.
155    #[n(1)]
156    pub free: u64,
157}
158
159/// The machine and process state that a command started with, as its step record
160/// keeps it, in the six parts of [`MachinePart`]. A part that could not be read is
161/// `None`, which explanations show as `unknown`.
162#[derive(Debug, Clone, PartialEq, Eq, Hash, Default, Encode, Decode)]
163pub struct MachineStateRecord {
164    /// `kernel`: the kernel release and version.
165    #[n(0)]
166    pub kernel: Option<KernelRecord>,
167    /// `limits`: every resource limit, soft and hard, in the platform's order.
168    #[n(1)]
169    pub limits: Option<Vec<LimitRecord>>,
170    /// `affinity`: the CPUs the command could run on, by number, sorted.
171    #[n(2)]
172    pub affinity: Option<Vec<u32>>,
173    /// `memory`: the total and the available memory.
174    #[n(3)]
175    pub memory: Option<MemoryRecord>,
176    /// `filesystem`: the type and mount flags of the file system that held the
177    /// working directory.
178    #[n(4)]
179    pub filesystem: Option<FileSystemRecord>,
180    /// `disk`: the size and free space of that file system.
181    #[n(5)]
182    pub disk: Option<DiskRecord>,
183}
184
185/// A number of bytes as text, such as `1024 bytes`.
186fn bytes(number: u64) -> String {
187    format!("{number} bytes")
188}
189
190/// A resource limit as text: the number, or `unlimited`.
191fn limit_text(limit: Option<u64>) -> String {
192    limit.map_or_else(|| "unlimited".to_owned(), |limit| limit.to_string())
193}
194
195/// CPU numbers as the kernel lists them, with runs as ranges, such as `0-3,6`, or
196/// `none`.
197fn cpu_list(cpus: &[u32]) -> String {
198    let mut ranges: Vec<(u32, u32)> = Vec::new();
199    for &cpu in cpus {
200        match ranges.last_mut() {
201            Some((_, last)) if last.checked_add(1) == Some(cpu) => *last = cpu,
202            _ => ranges.push((cpu, cpu)),
203        }
204    }
205    if ranges.is_empty() {
206        return "none".to_owned();
207    }
208    let shown: Vec<String> = ranges
209        .iter()
210        .map(|&(first, last)| {
211            if first == last {
212                first.to_string()
213            } else {
214                format!("{first}-{last}")
215            }
216        })
217        .collect();
218    shown.join(",")
219}
220
221impl MachineStateRecord {
222    /// Each value of the part `part`, named, as text, in order, or `None` when the
223    /// part could not be read.
224    #[must_use]
225    pub fn values(
226        &self,
227        part: MachinePart,
228    ) -> Option<Vec<(String, String)>> {
229        let named = |name: &str, value: String| (name.to_owned(), value);
230        match part {
231            MachinePart::Kernel => {
232                self.kernel.as_ref().map(|kernel| {
233                    vec![
234                        named("kernel release", kernel.release.clone()),
235                        named("kernel version", kernel.version.clone()),
236                    ]
237                })
238            },
239            MachinePart::Limits => {
240                self.limits.as_ref().map(|limits| {
241                    limits
242                        .iter()
243                        .flat_map(|limit| {
244                            [
245                                (
246                                    format!("soft limit of {}", limit.resource),
247                                    limit_text(limit.soft),
248                                ),
249                                (
250                                    format!("hard limit of {}", limit.resource),
251                                    limit_text(limit.hard),
252                                ),
253                            ]
254                        })
255                        .collect()
256                })
257            },
258            MachinePart::Affinity => {
259                self.affinity
260                    .as_ref()
261                    .map(|cpus| vec![named("CPUs", cpu_list(cpus))])
262            },
263            MachinePart::Memory => {
264                self.memory.map(|memory| {
265                    vec![
266                        named("total memory", bytes(memory.total)),
267                        named("available memory", bytes(memory.available)),
268                    ]
269                })
270            },
271            MachinePart::Filesystem => {
272                self.filesystem.map(|filesystem| {
273                    vec![
274                        named("file system type", format!("{:#x}", filesystem.kind)),
275                        named("mount flags", format!("{:#x}", filesystem.flags)),
276                    ]
277                })
278            },
279            MachinePart::Disk => {
280                self.disk.map(|disk| {
281                    vec![
282                        named("file system size", bytes(disk.size)),
283                        named("free space", bytes(disk.free)),
284                    ]
285                })
286            },
287        }
288    }
289
290    /// The part `part` on one line: each value with its name, such as `kernel
291    /// release 6.12.0, kernel version #1 SMP`, or `unknown` when the part could not
292    /// be read.
293    #[must_use]
294    pub fn text(
295        &self,
296        part: MachinePart,
297    ) -> String {
298        self.values(part).map_or_else(
299            || "unknown".to_owned(),
300            |values| {
301                let shown: Vec<String> = values
302                    .iter()
303                    .map(|(name, value)| format!("{name} {value}"))
304                    .collect();
305                shown.join(", ")
306            },
307        )
308    }
309}
310
311/// One value of the machine state that changed since a step's record.
312#[derive(Debug, Clone, PartialEq, Eq, Hash, Encode, Decode)]
313pub struct MachineChange {
314    /// The name of the value, such as `kernel release`, or of the part when it could
315    /// not be read on one side.
316    #[n(0)]
317    pub value: String,
318    /// The recorded value, as text.
319    #[n(1)]
320    pub old: String,
321    /// The current value, as text.
322    #[n(2)]
323    pub new: String,
324}
325
326impl fmt::Display for MachineChange {
327    fn fmt(
328        &self,
329        f: &mut fmt::Formatter<'_>,
330    ) -> fmt::Result {
331        write!(f, "{} from {} to {}", self.value, self.old, self.new)
332    }
333}
334
335/// The value named `name` in `values`, or `none` when it is not there.
336fn value_of(
337    values: &[(String, String)],
338    name: &str,
339) -> String {
340    values
341        .iter()
342        .find(|(each, _)| each == name)
343        .map_or_else(|| "none".to_owned(), |(_, value)| value.clone())
344}
345
346/// Every value of the parts `parts` that differs between `old`, the recorded state,
347/// and `new`, the current one, in the order of `parts` and then of the values.
348///
349/// Each part is compared value by value; a value that only one side has is `none`
350/// on the other. A part that could be read on one side only is one change, named
351/// by the part, from or to `unknown`.
352#[must_use]
353pub fn machine_changes(
354    parts: &[MachinePart],
355    old: &MachineStateRecord,
356    new: &MachineStateRecord,
357) -> Vec<MachineChange> {
358    let mut changes = Vec::new();
359    for &part in parts {
360        let (Some(old_values), Some(new_values)) = (old.values(part), new.values(part)) else {
361            let (old_text, new_text) = (old.text(part), new.text(part));
362            if old_text != new_text {
363                changes.push(MachineChange {
364                    value: part.name().to_owned(),
365                    old: old_text,
366                    new: new_text,
367                });
368            }
369            continue;
370        };
371        let mut names: Vec<&str> = old_values.iter().map(|(name, _)| name.as_str()).collect();
372        for (name, _) in &new_values {
373            if !names.contains(&name.as_str()) {
374                names.push(name);
375            }
376        }
377        for name in names {
378            let (old_value, new_value) = (value_of(&old_values, name), value_of(&new_values, name));
379            if old_value != new_value {
380                changes.push(MachineChange {
381                    value: name.to_owned(),
382                    old: old_value,
383                    new: new_value,
384                });
385            }
386        }
387    }
388    changes
389}
390
391/// The changes `changes` on one line, such as `kernel release from 6.1 to 6.2,
392/// available memory from 1 bytes to 2 bytes`, or `nothing` for none.
393#[must_use]
394pub fn machine_changes_text(changes: &[MachineChange]) -> String {
395    if changes.is_empty() {
396        return "nothing".to_owned();
397    }
398    let shown: Vec<String> = changes.iter().map(ToString::to_string).collect();
399    shown.join(", ")
400}
401
402/// Unit tests for the machine state of step records.
403#[cfg(test)]
404#[allow(
405    clippy::disallowed_macros,
406    clippy::disallowed_methods,
407    reason = "test code: the tests assert and lock"
408)]
409mod tests {
410    use super::*;
411
412    /// A state with every part, as a test machine might report it.
413    fn state() -> MachineStateRecord {
414        MachineStateRecord {
415            kernel: Some(KernelRecord {
416                release: "6.12.0".to_owned(),
417                version: "#1 SMP".to_owned(),
418            }),
419            limits: Some(vec![
420                LimitRecord {
421                    resource: "cpu".to_owned(),
422                    soft: None,
423                    hard: None,
424                },
425                LimitRecord {
426                    resource: "nofile".to_owned(),
427                    soft: Some(1_024),
428                    hard: Some(524_288),
429                },
430            ]),
431            affinity: Some(vec![0, 1, 2, 3, 6]),
432            memory: Some(MemoryRecord {
433                total: 8_000,
434                available: 4_000,
435            }),
436            filesystem: Some(FileSystemRecord {
437                kind: 0xEF53,
438                flags: 0x1020,
439            }),
440            disk: Some(DiskRecord {
441                size: 100_000,
442                free: 40_000,
443            }),
444        }
445    }
446
447    /// Each part has the name that `run()` takes, a name maps back to its part and an
448    /// unknown one to none, and the names read as an error lists them.
449    #[test]
450    fn parts_have_their_names() {
451        let names: Vec<&str> = MachinePart::ALL.iter().map(|part| part.name()).collect();
452        assert_eq!(names, [
453            "kernel",
454            "limits",
455            "affinity",
456            "memory",
457            "filesystem",
458            "disk"
459        ]);
460        for part in MachinePart::ALL {
461            assert_eq!(MachinePart::from_name(part.name()), Some(part));
462            assert_eq!(part.to_string(), part.name());
463        }
464        assert_eq!(MachinePart::from_name("cpu"), None);
465        assert_eq!(MachinePart::from_name("Kernel"), None);
466        assert_eq!(
467            MachinePart::parts(&["disk".to_owned(), "x".to_owned(), "kernel".to_owned()]),
468            [MachinePart::Disk, MachinePart::Kernel]
469        );
470        assert_eq!(
471            MachinePart::names_text(),
472            "kernel, limits, affinity, memory, filesystem and disk"
473        );
474    }
475
476    /// Every part reads as text with its values named, a part that could not be read
477    /// reads as `unknown`, and an empty CPU list reads as `none`.
478    #[test]
479    fn every_part_reads_as_text() {
480        let state = state();
481        let shown: Vec<String> = MachinePart::ALL
482            .iter()
483            .map(|part| state.text(*part))
484            .collect();
485        assert_eq!(shown, [
486            "kernel release 6.12.0, kernel version #1 SMP",
487            "soft limit of cpu unlimited, hard limit of cpu unlimited, soft limit of nofile 1024, \
488             hard limit of nofile 524288",
489            "CPUs 0-3,6",
490            "total memory 8000 bytes, available memory 4000 bytes",
491            "file system type 0xef53, mount flags 0x1020",
492            "file system size 100000 bytes, free space 40000 bytes",
493        ]);
494        let unknown = MachineStateRecord::default();
495        for part in MachinePart::ALL {
496            assert_eq!(unknown.text(part), "unknown");
497            assert_eq!(unknown.values(part), None);
498        }
499        let none = MachineStateRecord {
500            affinity: Some(Vec::new()),
501            ..MachineStateRecord::default()
502        };
503        assert_eq!(none.text(MachinePart::Affinity), "CPUs none");
504    }
505
506    /// Only the named parts are compared, value by value: a changed, missing or
507    /// unreadable value is one change each, and equal or unknown states have none.
508    #[test]
509    fn only_the_named_parts_are_compared_value_by_value() {
510        let old = state();
511        let mut new = state();
512        new.kernel = Some(KernelRecord {
513            release: "6.13.0".to_owned(),
514            version: "#1 SMP".to_owned(),
515        });
516        new.memory = Some(MemoryRecord {
517            total: 8_000,
518            available: 3_000,
519        });
520        if let Some(limits) = &mut new.limits {
521            limits.retain(|limit| limit.resource != "cpu");
522        }
523        new.affinity = Some(vec![0, 1]);
524        new.disk = None;
525        assert_eq!(machine_changes(&[], &old, &new), []);
526        assert_eq!(machine_changes(&[MachinePart::Filesystem], &old, &new), []);
527        let change = |value: &str, old: &str, new: &str| {
528            MachineChange {
529                value: value.to_owned(),
530                old: old.to_owned(),
531                new: new.to_owned(),
532            }
533        };
534        assert_eq!(machine_changes(&MachinePart::ALL, &old, &new), [
535            change("kernel release", "6.12.0", "6.13.0"),
536            change("soft limit of cpu", "unlimited", "none"),
537            change("hard limit of cpu", "unlimited", "none"),
538            change("CPUs", "0-3,6", "0-1"),
539            change("available memory", "4000 bytes", "3000 bytes"),
540            change(
541                "disk",
542                "file system size 100000 bytes, free space 40000 bytes",
543                "unknown"
544            ),
545        ]);
546        assert_eq!(machine_changes(&MachinePart::ALL, &old, &old), []);
547        let unknown = MachineStateRecord::default();
548        assert_eq!(machine_changes(&MachinePart::ALL, &unknown, &unknown), []);
549    }
550
551    /// Changes read as one line, each from its old value to its new one, and no
552    /// changes read as `nothing`.
553    #[test]
554    fn changes_read_as_text() {
555        let changes = [
556            MachineChange {
557                value: "kernel release".to_owned(),
558                old: "6.12.0".to_owned(),
559                new: "6.13.0".to_owned(),
560            },
561            MachineChange {
562                value: "CPUs".to_owned(),
563                old: "0-3".to_owned(),
564                new: "0".to_owned(),
565            },
566        ];
567        assert_eq!(
568            machine_changes_text(&changes),
569            "kernel release from 6.12.0 to 6.13.0, CPUs from 0-3 to 0"
570        );
571        assert_eq!(machine_changes_text(&[]), "nothing");
572    }
573
574    /// The state and its changes encode with definite lengths, the same way every
575    /// time, and round-trip, a state whose parts could not be read included.
576    #[test]
577    fn states_and_changes_encode_deterministically_and_round_trip() {
578        for state in [state(), MachineStateRecord::default()] {
579            let first = minicbor::to_vec(&state).unwrap();
580            assert_eq!(first, minicbor::to_vec(state.clone()).unwrap());
581            assert_eq!(
582                minicbor::decode::<MachineStateRecord>(&first).unwrap(),
583                state
584            );
585        }
586        assert_eq!(minicbor::to_vec(state()).unwrap().first(), Some(&0x86));
587        let change = MachineChange {
588            value: "CPUs".to_owned(),
589            old: "0".to_owned(),
590            new: "1".to_owned(),
591        };
592        let bytes = minicbor::to_vec(&change).unwrap();
593        assert_eq!(bytes, b"\x83\x64CPUs\x610\x611");
594        assert_eq!(minicbor::decode::<MachineChange>(&bytes).unwrap(), change);
595    }
596}