Skip to main content

subspace_core/
state.rs

1//! The state file (REQ-08): UI choices kept between runs. Keys are
2//! namespaced `<dashboard>.<name>`, such as `board.layout`. Values are
3//! strings; structured values are JSON text.
4
5use std::collections::BTreeMap;
6use std::fs;
7use std::io::{self, Write};
8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicBool, Ordering};
10
11use serde::Serialize;
12use serde_json::value::RawValue;
13use subspace_product::Channel;
14
15/// `<directory>/state.json` in the platform state directory:
16/// `$XDG_STATE_HOME` on Linux, the local data directory elsewhere
17/// (Application Support on macOS, `%LOCALAPPDATA%` on Windows).
18/// [`directory_name`] gives the directory.
19pub fn path() -> Option<PathBuf> {
20    dirs::state_dir()
21        .or_else(dirs::data_local_dir)
22        .map(|dir| dir.join(directory_name()).join("state.json"))
23}
24
25/// The Subspace data directory name of this build's channel: `subspace` on
26/// stable, `subspace-<type>` for a pre-release type. Config, state and
27/// caches that are not product-specific use it.
28pub fn directory_name() -> String {
29    directory_name_for(Channel::current())
30}
31
32fn directory_name_for(channel: Channel) -> String {
33    channel.name("subspace")
34}
35
36/// `name` beside the state file, such as `github-cache.json`. Large
37/// caches live in files of their own, so `state.json` stays small.
38pub fn sibling(name: &str) -> Option<PathBuf> {
39    path().and_then(|state| Some(state.parent()?.join(name)))
40}
41
42/// Writes `text` to `file` atomically: a temporary file in the same
43/// directory, then a rename over the old file.
44pub fn write_atomic(file: &Path, text: &str) -> io::Result<()> {
45    let dir = file
46        .parent()
47        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the file has no directory"))?;
48    fs::create_dir_all(dir)?;
49    let mut temp = tempfile::NamedTempFile::new_in(dir)?;
50    crate::private_file::set_owner_only(temp.path())?;
51    temp.write_all(text.as_bytes())?;
52    temp.as_file().sync_all()?;
53    temp.persist(file).map_err(|error| error.error)?;
54    Ok(())
55}
56
57/// True for bytes that hold only JSON whitespace (RFC 8259: space, tab,
58/// carriage return, line feed). Form feed and vertical tab are not JSON
59/// whitespace, so a file that holds only those is not blank.
60fn is_blank(bytes: &[u8]) -> bool {
61    bytes
62        .iter()
63        .all(|&byte| matches!(byte, b' ' | b'\t' | b'\r' | b'\n'))
64}
65
66/// The exact JSON text of a value that is not a string, so a save writes
67/// back every digit and is not limited to `f64` or `u64`/`i64`.
68#[derive(Debug, Clone, Serialize)]
69#[serde(transparent)]
70struct RawJson(Box<RawValue>);
71
72impl PartialEq for RawJson {
73    fn eq(&self, other: &Self) -> bool {
74        self.0.get() == other.0.get()
75    }
76}
77
78impl Eq for RawJson {}
79
80/// One value of the document that [`State::save`] writes.
81#[derive(Serialize)]
82#[serde(untagged)]
83enum Entry<'a> {
84    Text(&'a str),
85    Raw(&'a RawJson),
86}
87
88/// Whether [`State::load`] found a file it could not use, until a save
89/// succeeds. Interior mutability lets `save(&self)` clear it. It is not part
90/// of a state's equality.
91#[derive(Debug, Default)]
92struct LoadFailed(AtomicBool);
93
94impl LoadFailed {
95    fn new(failed: bool) -> Self {
96        Self(AtomicBool::new(failed))
97    }
98
99    fn is_set(&self) -> bool {
100        self.0.load(Ordering::Relaxed)
101    }
102
103    fn clear(&self) {
104        self.0.store(false, Ordering::Relaxed);
105    }
106}
107
108impl Clone for LoadFailed {
109    fn clone(&self) -> Self {
110        Self::new(self.is_set())
111    }
112}
113
114impl PartialEq for LoadFailed {
115    fn eq(&self, _: &Self) -> bool {
116        true
117    }
118}
119
120impl Eq for LoadFailed {}
121
122/// The state in the JSON object `bytes`, or `None` when they are not one.
123/// A string value is a usable value; every other value is kept as raw JSON.
124fn parse_state(bytes: &[u8]) -> Option<State> {
125    let fields: BTreeMap<String, Box<RawValue>> = serde_json::from_slice(bytes).ok()?;
126    let mut state = State::default();
127    for (key, raw) in fields {
128        if let Ok(text) = serde_json::from_str::<String>(raw.get()) {
129            state.values.insert(key, text);
130        } else {
131            state.invalid.insert(key, RawJson(raw));
132        }
133    }
134    Some(state)
135}
136
137/// The state of the file. A missing or blank file is a normal first run. A
138/// read error other than "not found", or content that is not a JSON object,
139/// gives an empty state with the failure recorded.
140fn read_state(file: &Path) -> State {
141    let unusable = |failed: bool| State {
142        load_failed: LoadFailed::new(failed),
143        ..State::default()
144    };
145    match fs::read(file) {
146        Ok(bytes) => parse_state(&bytes).unwrap_or_else(|| unusable(!is_blank(&bytes))),
147        Err(error) if error.kind() == io::ErrorKind::NotFound => State::default(),
148        Err(_) => unusable(true),
149    }
150}
151
152/// Copies the current state file to `<name>.invalid-<unix seconds>-<n>`
153/// beside it, so a save cannot destroy it, when it is not a JSON object or,
154/// given `unless_equal` (the state about to be saved), when it holds
155/// anything else. A missing or blank file needs no copy. Any other failure to
156/// read the file, or to write the copy, is an error and the caller must not
157/// replace the file.
158fn keep_unreadable_file(file: &Path, unless_equal: Option<&State>) -> io::Result<()> {
159    let seconds = std::time::SystemTime::now()
160        .duration_since(std::time::UNIX_EPOCH)
161        .map_or(0, |elapsed| elapsed.as_secs());
162    keep_unreadable_file_stamped(file, seconds, unless_equal)
163}
164
165fn keep_unreadable_file_stamped(
166    file: &Path,
167    stamp: u64,
168    unless_equal: Option<&State>,
169) -> io::Result<()> {
170    let bytes = match fs::read(file) {
171        Ok(bytes) => bytes,
172        Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
173        Err(error) => return Err(error),
174    };
175    let nothing_to_lose = parse_state(&bytes)
176        .is_some_and(|current| unless_equal.is_none_or(|state| *state == current));
177    if is_blank(&bytes) || nothing_to_lose {
178        return Ok(());
179    }
180    let dir = file
181        .parent()
182        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "the file has no directory"))?;
183    let name = file.file_name().unwrap_or_default().to_string_lossy();
184    // Written and synced under a private temporary name, then linked to the
185    // first free `<name>.invalid-<stamp>-<n>`: an earlier copy is never replaced.
186    let mut temp = tempfile::NamedTempFile::new_in(dir)?;
187    crate::private_file::set_owner_only(temp.path())?;
188    temp.write_all(&bytes)?;
189    temp.as_file().sync_all()?;
190    for attempt in 0_u32.. {
191        let copy = dir.join(format!("{name}.invalid-{stamp}-{attempt}"));
192        match temp.persist_noclobber(&copy) {
193            Ok(_) => return Ok(()),
194            Err(error) if error.error.kind() == io::ErrorKind::AlreadyExists => {
195                temp = error.file;
196            }
197            Err(error) => return Err(error.error),
198        }
199    }
200    Err(io::Error::new(
201        io::ErrorKind::AlreadyExists,
202        "no free name for the state file copy",
203    ))
204}
205
206#[derive(Debug, Clone, PartialEq, Eq, Default)]
207pub struct State {
208    values: BTreeMap<String, String>,
209    /// File entries whose value is not a string. They are not readable
210    /// through [`State::get`], but [`State::save`] writes them back
211    /// with their exact JSON text until [`State::set`] or [`State::remove`]
212    /// replaces them.
213    invalid: BTreeMap<String, RawJson>,
214    /// [`State::load`] found a file it could not use. Until a save succeeds,
215    /// [`State::save`] keeps a copy of any different file it finds on disk.
216    /// Ignored by equality.
217    load_failed: LoadFailed,
218}
219
220impl State {
221    /// Reads the state file. A missing or unreadable file gives the defaults.
222    /// An entry whose value is not a string is kept apart (see
223    /// [`State::has_invalid_value`]) and does not affect the other entries.
224    /// A file that cannot be used gives the defaults: a read error other than
225    /// "not found", or content that is not a JSON object. A missing or blank
226    /// file is a normal first run. After an unusable file, the next
227    /// [`State::save`] first copies whatever file it finds, unless it already
228    /// holds exactly the document to save, to
229    /// `<name>.invalid-<unix seconds>-<n>`. That covers a file that was
230    /// malformed, and one that was only unreadable or half-written at load
231    /// time and is valid by the time of the save. [`State::save`] fails,
232    /// without replacing the file, if it cannot read the file or write the
233    /// copy. Only space, tab, carriage return and line feed count as blank.
234    /// A non-string value keeps its exact JSON text, such as a number with
235    /// more digits than `u64` or `f64` hold.
236    pub fn load(file: &Path) -> Self {
237        read_state(file)
238    }
239
240    /// The string value of `key`. `None` for a missing key and for a key
241    /// whose stored value is not a string: use [`State::has_invalid_value`]
242    /// to tell them apart before calling [`State::set`].
243    pub fn get(&self, key: &str) -> Option<&str> {
244        self.values.get(key).map(String::as_str)
245    }
246
247    /// True when the file holds a non-string value for `key` that has not
248    /// been replaced or removed. A caller that must not overwrite unreadable
249    /// data skips [`State::set`] while this is true; calling [`State::set`] or
250    /// [`State::remove`] is the explicit reset.
251    pub fn has_invalid_value(&self, key: &str) -> bool {
252        self.invalid.contains_key(key)
253    }
254
255    /// Stores `value`, replacing any value, including an invalid one.
256    pub fn set(&mut self, key: impl Into<String>, value: impl Into<String>) {
257        let key = key.into();
258        self.invalid.remove(&key);
259        self.values.insert(key, value.into());
260    }
261
262    /// Deletes `key`, including an invalid value.
263    pub fn remove(&mut self, key: &str) {
264        self.invalid.remove(key);
265        self.values.remove(key);
266    }
267
268    fn document(&self) -> BTreeMap<&str, Entry<'_>> {
269        let kept = self
270            .invalid
271            .iter()
272            .map(|(key, raw)| (key.as_str(), Entry::Raw(raw)));
273        let strings = self
274            .values
275            .iter()
276            .map(|(key, text)| (key.as_str(), Entry::Text(text.as_str())));
277        kept.chain(strings).collect()
278    }
279
280    /// Writes the file atomically: a temporary file in the same directory,
281    /// then a rename over the old file. Invalid entries read by
282    /// [`State::load`] are written back with their exact JSON text. A current
283    /// file that is not a JSON object, or that differs from this state after
284    /// a failed load, is copied aside first (see [`State::load`]). The first
285    /// successful save after a failed load ends the check, so later saves
286    /// make no more copies.
287    pub fn save(&self, file: &Path) -> io::Result<()> {
288        let dir = file.parent().ok_or_else(|| {
289            io::Error::new(
290                io::ErrorKind::InvalidInput,
291                "the state file has no directory",
292            )
293        })?;
294        fs::create_dir_all(dir)?;
295        keep_unreadable_file(file, self.load_failed.is_set().then_some(self))?;
296        let mut temp = tempfile::NamedTempFile::new_in(dir)?;
297        serde_json::to_writer_pretty(&mut temp, &self.document())?;
298        temp.write_all(b"\n")?;
299        temp.as_file().sync_all()?;
300        temp.persist(file).map_err(|error| error.error)?;
301        self.load_failed.clear();
302        Ok(())
303    }
304}
305
306#[cfg(test)]
307mod tests {
308    use std::fs;
309
310    use subspace_product::Channel;
311
312    use super::{State, directory_name, directory_name_for};
313
314    #[test]
315    fn each_type_keeps_its_core_state_in_its_own_directory() {
316        assert_eq!(directory_name_for(Channel::Stable), "subspace");
317        assert_eq!(directory_name_for(Channel::Nightly), "subspace-nightly");
318        assert_eq!(directory_name_for(Channel::Alpha), "subspace-alpha");
319        assert_eq!(directory_name_for(Channel::Beta), "subspace-beta");
320        assert_eq!(directory_name(), directory_name_for(Channel::current()));
321    }
322
323    #[test]
324    fn values_survive_a_save_and_load() {
325        let dir = tempfile::tempdir().unwrap();
326        let file = dir.path().join("subspace").join("state.json");
327        let mut state = State::default();
328        state.set("board.layout", "board");
329        state.set("github.collapsed", r#"["mine"]"#);
330        state.save(&file).unwrap();
331
332        state.set("board.layout", "list");
333        state.remove("github.collapsed");
334        state.save(&file).unwrap();
335
336        let loaded = State::load(&file);
337        assert_eq!(loaded, state);
338        assert_eq!(loaded.get("board.layout"), Some("list"));
339        assert_eq!(loaded.get("github.collapsed"), None);
340        // Only the state file is left: the temporary file was renamed.
341        assert_eq!(fs::read_dir(file.parent().unwrap()).unwrap().count(), 1);
342    }
343
344    #[test]
345    fn write_atomic_replaces_the_file() {
346        let dir = tempfile::tempdir().unwrap();
347        let file = dir.path().join("sub").join("cache.json");
348        super::write_atomic(&file, "one").unwrap();
349        super::write_atomic(&file, "two").unwrap();
350        assert_eq!(fs::read_to_string(&file).unwrap(), "two");
351        assert_eq!(fs::read_dir(file.parent().unwrap()).unwrap().count(), 1);
352    }
353
354    #[cfg(unix)]
355    #[test]
356    fn atomic_cache_replaces_permissive_files_with_private_files() {
357        use std::os::unix::fs::PermissionsExt as _;
358        let dir = tempfile::tempdir().unwrap();
359        let file = dir.path().join("cache.json");
360        fs::write(&file, "old").unwrap();
361        fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
362        super::write_atomic(&file, "private").unwrap();
363        assert_eq!(
364            fs::metadata(file).unwrap().permissions().mode() & 0o777,
365            0o600
366        );
367    }
368
369    #[test]
370    fn a_missing_or_broken_file_gives_the_defaults_and_is_replaced() {
371        let dir = tempfile::tempdir().unwrap();
372        let file = dir.path().join("state.json");
373        assert_eq!(State::load(&file), State::default());
374
375        fs::write(&file, "{ broken").unwrap();
376        let mut state = State::load(&file);
377        assert!(state.values.is_empty() && state.invalid.is_empty());
378        state.set("wrap", "true");
379        state.save(&file).unwrap();
380        assert_eq!(State::load(&file).get("wrap"), Some("true"));
381    }
382
383    fn saved_json(file: &std::path::Path) -> serde_json::Value {
384        serde_json::from_str(&fs::read_to_string(file).unwrap()).unwrap()
385    }
386
387    #[test]
388    fn a_non_string_entry_is_kept_and_other_values_stay_usable() {
389        let dir = tempfile::tempdir().unwrap();
390        let file = dir.path().join("state.json");
391        fs::write(
392            &file,
393            r#"{"wrap":"true","example.dock-layout":{"version":1},"count":3}"#,
394        )
395        .unwrap();
396
397        let mut state = State::load(&file);
398        assert_eq!(state.get("wrap"), Some("true"));
399        assert_eq!(state.get("example.dock-layout"), None);
400        assert!(state.has_invalid_value("example.dock-layout"));
401        assert!(state.has_invalid_value("count"));
402        assert!(!state.has_invalid_value("wrap"));
403        assert!(!state.has_invalid_value("missing"));
404
405        state.set("board.layout", "list");
406        state.save(&file).unwrap();
407
408        assert_eq!(
409            saved_json(&file),
410            serde_json::json!({
411                "wrap": "true",
412                "board.layout": "list",
413                "example.dock-layout": {"version": 1},
414                "count": 3,
415            })
416        );
417        assert!(State::load(&file).has_invalid_value("example.dock-layout"));
418        // A readable file needs no copy.
419        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
420    }
421
422    #[test]
423    fn set_and_remove_explicitly_replace_a_non_string_entry() {
424        let dir = tempfile::tempdir().unwrap();
425        let file = dir.path().join("state.json");
426        fs::write(&file, r#"{"a":[1],"b":null,"keep":"yes"}"#).unwrap();
427
428        let mut state = State::load(&file);
429        state.set("a", "reset");
430        state.remove("b");
431        assert!(!state.has_invalid_value("a"));
432        assert!(!state.has_invalid_value("b"));
433        assert_eq!(state.get("a"), Some("reset"));
434        state.save(&file).unwrap();
435
436        assert_eq!(
437            saved_json(&file),
438            serde_json::json!({"a": "reset", "keep": "yes"})
439        );
440    }
441
442    #[test]
443    fn a_file_that_is_not_a_json_object_is_copied_aside_before_it_is_replaced() {
444        for broken in ["{ broken", "[\"not\",\"an object\"]"] {
445            let dir = tempfile::tempdir().unwrap();
446            let file = dir.path().join("state.json");
447            fs::write(&file, broken).unwrap();
448
449            let mut state = State::load(&file);
450            assert!(state.values.is_empty() && state.invalid.is_empty());
451            state.set("wrap", "true");
452            state.save(&file).unwrap();
453
454            assert_eq!(State::load(&file).get("wrap"), Some("true"));
455            assert_eq!(copy_contents(dir.path()), [broken]);
456        }
457    }
458
459    /// The contents of the `state.json.invalid-*` copies in `dir`, oldest name first.
460    fn copy_contents(dir: &std::path::Path) -> Vec<String> {
461        let mut copies: Vec<_> = fs::read_dir(dir)
462            .unwrap()
463            .map(|entry| entry.unwrap().path())
464            .filter(|path| {
465                path.file_name()
466                    .and_then(|name| name.to_str())
467                    .is_some_and(|name| name.starts_with("state.json.invalid-"))
468            })
469            .collect();
470        copies.sort();
471        copies
472            .iter()
473            .map(|path| fs::read_to_string(path).unwrap())
474            .collect()
475    }
476
477    #[test]
478    fn a_file_unreadable_at_load_but_valid_at_save_is_copied_before_it_is_replaced() {
479        let dir = tempfile::tempdir().unwrap();
480        let file = dir.path().join("state.json");
481        // Reading a directory fails with an error other than "not found".
482        fs::create_dir(&file).unwrap();
483        let mut state = State::load(&file);
484        assert!(state.values.is_empty() && state.invalid.is_empty());
485        fs::remove_dir(&file).unwrap();
486        let original = r#"{"keep":"yes","count":3}"#;
487        fs::write(&file, original).unwrap();
488
489        state.set("a", "b");
490        state.save(&file).unwrap();
491        assert_eq!(saved_json(&file), serde_json::json!({"a": "b"}));
492        assert_eq!(copy_contents(dir.path()), [original]);
493
494        // Saving the same document again loses nothing: no further copy.
495        state.save(&file).unwrap();
496        assert_eq!(copy_contents(dir.path()), [original]);
497
498        // The first successful save ended the check: later changes make no copy.
499        state.set("a", "c");
500        state.save(&file).unwrap();
501        assert_eq!(saved_json(&file), serde_json::json!({"a": "c"}));
502        assert_eq!(copy_contents(dir.path()), [original]);
503    }
504
505    #[test]
506    fn non_string_entries_keep_their_exact_json_text() {
507        let dir = tempfile::tempdir().unwrap();
508        let file = dir.path().join("state.json");
509        let numbers = [
510            "18446744073709551617",
511            "-9223372036854775809",
512            "1.000000000000000000001",
513            "0.1000000000000000055511151231257827",
514        ];
515        fs::write(
516            &file,
517            format!(
518                r#"{{"u":{},"i":{},"d":{},"f":{},"nested":{{"n":{}}},"keep":"x"}}"#,
519                numbers[0], numbers[1], numbers[2], numbers[3], numbers[0]
520            ),
521        )
522        .unwrap();
523
524        let mut state = State::load(&file);
525        assert!(state.has_invalid_value("u"));
526        state.set("other", "y");
527        state.save(&file).unwrap();
528
529        let saved = fs::read_to_string(&file).unwrap();
530        for number in numbers {
531            assert!(saved.contains(number), "{number} missing from {saved}");
532        }
533        assert!(saved.contains(&format!(r#"{{"n":{}}}"#, numbers[0])));
534        assert_eq!(State::load(&file), state);
535        // The file was already valid: no copy.
536        assert!(copy_contents(dir.path()).is_empty());
537    }
538
539    #[test]
540    fn only_json_whitespace_makes_a_file_blank() {
541        for content in ["\u{c}", "\u{b}", " \u{c}\n", "\u{b}\t"] {
542            let dir = tempfile::tempdir().unwrap();
543            let file = dir.path().join("state.json");
544            fs::write(&file, content).unwrap();
545
546            let mut state = State::load(&file);
547            state.set("a", "b");
548            state.save(&file).unwrap();
549
550            assert_eq!(copy_contents(dir.path()), [content]);
551        }
552        for content in [" ", "\t\r\n ", ""] {
553            let dir = tempfile::tempdir().unwrap();
554            let file = dir.path().join("state.json");
555            fs::write(&file, content).unwrap();
556            State::load(&file).save(&file).unwrap();
557            assert!(copy_contents(dir.path()).is_empty());
558        }
559    }
560
561    #[test]
562    fn a_normal_load_never_makes_a_copy() {
563        for content in [None, Some(""), Some(" \n"), Some(r#"{"a":"1","n":2}"#)] {
564            let dir = tempfile::tempdir().unwrap();
565            let file = dir.path().join("state.json");
566            if let Some(content) = content {
567                fs::write(&file, content).unwrap();
568            }
569            let mut state = State::load(&file);
570            state.set("a", "x");
571            state.save(&file).unwrap();
572            state.set("a", "y");
573            state.save(&file).unwrap();
574
575            assert!(copy_contents(dir.path()).is_empty());
576            assert_eq!(State::load(&file).get("a"), Some("y"));
577        }
578    }
579
580    #[test]
581    fn successive_copies_never_replace_an_earlier_copy() {
582        let dir = tempfile::tempdir().unwrap();
583        let file = dir.path().join("state.json");
584        for broken in ["{ first", "{ second", "{ third"] {
585            fs::write(&file, broken).unwrap();
586            // The same stamp each time forces the name collision.
587            super::keep_unreadable_file_stamped(&file, 7, None).unwrap();
588        }
589        for (index, broken) in ["{ first", "{ second", "{ third"].into_iter().enumerate() {
590            let copy = dir.path().join(format!("state.json.invalid-7-{index}"));
591            assert_eq!(fs::read_to_string(copy).unwrap(), broken);
592        }
593        // The state file and three copies; no temporary file is left.
594        assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 4);
595    }
596
597    #[cfg(unix)]
598    #[test]
599    fn a_copy_is_private() {
600        use std::os::unix::fs::PermissionsExt as _;
601        let dir = tempfile::tempdir().unwrap();
602        let file = dir.path().join("state.json");
603        fs::write(&file, "{ broken").unwrap();
604        fs::set_permissions(&file, fs::Permissions::from_mode(0o644)).unwrap();
605        super::keep_unreadable_file_stamped(&file, 1, None).unwrap();
606        let copy = dir.path().join("state.json.invalid-1-0");
607        assert_eq!(
608            fs::metadata(copy).unwrap().permissions().mode() & 0o777,
609            0o600
610        );
611    }
612
613    #[test]
614    fn a_file_that_cannot_be_inspected_is_not_treated_as_missing() {
615        let dir = tempfile::tempdir().unwrap();
616        // Reading a directory fails with an error other than "not found".
617        let file = dir.path().join("state.json");
618        fs::create_dir(&file).unwrap();
619        assert!(super::keep_unreadable_file(&file, None).is_err());
620        assert!(State::default().save(&file).is_err());
621        assert!(file.is_dir());
622
623        let missing = dir.path().join("absent.json");
624        assert!(super::keep_unreadable_file(&missing, None).is_ok());
625    }
626
627    #[cfg(unix)]
628    #[test]
629    fn a_failed_copy_fails_the_save_and_keeps_the_file() {
630        use std::os::unix::fs::PermissionsExt as _;
631        let dir = tempfile::tempdir().unwrap();
632        let file = dir.path().join("state.json");
633        fs::write(&file, "{ broken").unwrap();
634        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o500)).unwrap();
635
636        // Running as root ignores directory permissions: nothing to prove.
637        let can_write = tempfile::NamedTempFile::new_in(dir.path()).is_ok();
638        let result = State::default().save(&file);
639        fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o700)).unwrap();
640
641        if !can_write {
642            assert!(result.is_err());
643            assert_eq!(fs::read_to_string(&file).unwrap(), "{ broken");
644        }
645    }
646}