Skip to main content

isothrum_machine/install/
record.rs

1//! What setups added, on record, so a clean-up removes what they added and only that: each
2//! install's [`Installed`] ([`super::added`]), never the items that were there before it. A tool
3//! whose install only opened its vendor's installer (a macOS cask), or which isn't found yet,
4//! counts once a later check finds it ([`settle`]). The rules are here; the caller keeps the
5//! records where it keeps its data, and reads and writes them in one transaction around
6//! [`remember`] and [`settle`].
7
8use serde::{Deserialize, Serialize};
9
10use super::Dependency;
11use super::added::{Installed, Item};
12
13/// What setups added of a tool, on record.
14#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
15#[serde(rename_all = "camelCase")]
16pub struct InstalledTool {
17    /// The tool.
18    pub dependency: Dependency,
19    /// When an install last added to it, in seconds since the Unix epoch.
20    pub at: u64,
21    /// What its installs added: what a clean-up removes ([`super::removal`]), and nothing else.
22    pub added: Vec<Item>,
23    /// What an install left to its vendor's installer, or didn't find yet ([`Installed::waiting`]):
24    /// added once a later check finds it ([`settle`]).
25    #[serde(default, skip_serializing_if = "Vec::is_empty")]
26    pub waiting: Vec<Item>,
27}
28
29/// How long an opened installer may take to be finished before what waits for it is dropped: a
30/// tool that shows up later than that was most likely installed some other way.
31pub const PENDING_FOR_SECS: u64 = 24 * 3600;
32
33/// `tools` with what an install of `dependency` added (`installed`) recorded at `now`, beside what
34/// earlier installs added: one record a tool. An install that added nothing, nor left anything
35/// waiting, records nothing.
36pub fn remember(tools: &mut Vec<InstalledTool>, dependency: Dependency, installed: &Installed, now: u64) {
37    if installed.is_empty() {
38        return;
39    }
40    let mut added = tools.iter().find(|t| t.dependency == dependency).map(|t| t.added.clone()).unwrap_or_default();
41    for item in &installed.added {
42        if !added.contains(item) {
43            added.push(item.clone());
44        }
45    }
46    let waiting = installed.waiting.iter().filter(|item| !added.contains(item)).cloned().collect();
47    tools.retain(|t| t.dependency != dependency);
48    tools.push(InstalledTool {
49        dependency,
50        at: now,
51        added,
52        waiting,
53    });
54}
55
56/// Adds to each record the items it waited for that are now there (`there`, by tool), and drops
57/// what has waited longer than [`PENDING_FOR_SECS`] at `now`; a record left with nothing goes.
58pub fn settle(tools: &mut Vec<InstalledTool>, there: &[(Dependency, Vec<Item>)], now: u64) {
59    for t in tools.iter_mut() {
60        let found = there.iter().filter(|(d, _)| *d == t.dependency).flat_map(|(_, items)| items);
61        for item in found {
62            if t.waiting.contains(item) {
63                t.waiting.retain(|w| w != item);
64                t.added.push(item.clone());
65            }
66        }
67        if now.saturating_sub(t.at) >= PENDING_FOR_SECS {
68            t.waiting.clear();
69        }
70    }
71    tools.retain(|t| !t.added.is_empty() || !t.waiting.is_empty());
72}
73
74/// The records of tools something was added to: what a clean-up may offer to remove.
75#[must_use]
76pub fn removable(tools: Vec<InstalledTool>) -> Vec<InstalledTool> {
77    tools.into_iter().filter(|t| !t.added.is_empty()).collect()
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    fn package(name: &str) -> Item {
85        Item::Package(name.to_owned())
86    }
87
88    #[test]
89    fn an_install_that_added_nothing_records_nothing() {
90        let mut tools = Vec::new();
91        remember(&mut tools, Dependency::Qemu, &Installed::default(), 10);
92        assert_eq!(tools, []);
93    }
94
95    #[test]
96    fn a_tool_is_recorded_once_with_what_each_install_added() {
97        let mut tools = Vec::new();
98        remember(&mut tools, Dependency::Qemu, &Installed::new(vec![package("genisoimage")], vec![]), 10);
99        remember(
100            &mut tools,
101            Dependency::Qemu,
102            &Installed::new(vec![package("virtiofsd"), package("genisoimage")], vec![]),
103            20,
104        );
105        assert_eq!(
106            tools,
107            [InstalledTool {
108                dependency: Dependency::Qemu,
109                at: 20,
110                added: vec![package("genisoimage"), package("virtiofsd")],
111                waiting: vec![],
112            }]
113        );
114        let json = serde_json::to_value(&tools[0]).unwrap();
115        assert_eq!(
116            json,
117            serde_json::json!({ "dependency": "qemu", "at": 20, "added": [{ "package": "genisoimage" }, { "package": "virtiofsd" }] }),
118            "nothing waiting: no key"
119        );
120    }
121
122    #[test]
123    fn what_waits_is_never_removable_until_found_and_is_dropped_once_stale() {
124        let utm = Item::Tool(Dependency::Utm);
125        let docker = Item::Tool(Dependency::Docker);
126        let mut tools = Vec::new();
127        remember(&mut tools, Dependency::Utm, &Installed::new(vec![], vec![utm.clone()]), 0);
128        remember(&mut tools, Dependency::Docker, &Installed::new(vec![], vec![docker.clone()]), PENDING_FOR_SECS);
129        assert_eq!(removable(tools.clone()), [], "waiting isn't removable");
130        settle(&mut tools, &[(Dependency::Docker, vec![docker.clone()])], PENDING_FOR_SECS);
131        assert_eq!(tools.len(), 1, "UTM's waited too long");
132        assert_eq!(removable(tools.clone())[0].added, [docker]);
133    }
134}