Skip to main content

agentmux_srv_core/backend/
json_keep.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Saving a JSON file this build reads without losing what it could not read.
5//!
6//! A file under the person's configuration is read into a typed value, changed, and written back whole. When the typed read
7//! gives up on a piece (an entry a newer AgentMux wrote with a kind this build has never heard of, a topic it does not know) and
8//! the caller then saves the rest, the piece is gone from disk: a downgrade, or one build that is a version behind, quietly
9//! deletes what the newer one kept. These helpers keep that piece: an entry that does not read is written back exactly as it
10//! was, and a file that does not read at all is copied aside before it is replaced, never simply overwritten.
11
12use serde::de::DeserializeOwned;
13use serde::Serialize;
14use serde_json::Value;
15use std::collections::BTreeMap;
16use std::path::{Path, PathBuf};
17
18/// The name a file that could not be read is copied to before it is replaced.
19fn aside_path(path: &Path) -> PathBuf {
20    let mut name = path.file_name().map(|n| n.to_os_string()).unwrap_or_default();
21    name.push(".unreadable");
22    path.with_file_name(name)
23}
24
25/// When `path` holds bytes that are not a `T`, copies them to `<path>.unreadable` so the next save of the file does not destroy
26/// them. Nothing when the file is absent or reads fine. Best effort: a copy that fails is logged, not an error of the save.
27pub fn set_aside_if_unreadable<T: DeserializeOwned>(path: &Path) {
28    let Ok(bytes) = std::fs::read(path) else { return };
29    if serde_json::from_slice::<T>(&bytes).is_ok() {
30        return;
31    }
32    let aside = aside_path(path);
33    match std::fs::write(&aside, &bytes) {
34        Ok(()) => tracing::warn!(file = %path.display(), copy = %aside.display(), "config file could not be read; it was copied aside before it is replaced"),
35        Err(e) => tracing::warn!(file = %path.display(), error = %e, "config file could not be read, and the copy aside failed"),
36    }
37}
38
39/// A file that is a JSON object of records, each read on its own: the records that read, and none of the ones that do not. A
40/// missing or unreadable file is empty.
41pub fn read_entries<T: DeserializeOwned>(path: &Path) -> BTreeMap<String, T> {
42    let Some(raw) = read_raw_object(path) else { return BTreeMap::new() };
43    raw.into_iter().filter_map(|(k, v)| serde_json::from_value::<T>(v).ok().map(|t| (k, t))).collect()
44}
45
46/// Whether the file holds a record under `key`, readable by this build or not.
47pub fn has_record(path: &Path, key: &str) -> bool {
48    read_raw_object(path).is_some_and(|map| map.contains_key(key))
49}
50
51fn read_raw_object(path: &Path) -> Option<serde_json::Map<String, Value>> {
52    match serde_json::from_slice::<Value>(&std::fs::read(path).ok()?).ok()? {
53        Value::Object(map) => Some(map),
54        _ => None,
55    }
56}
57
58/// Writes `entries` as the file's records, plus every record already in the file that this build cannot read (they are not in
59/// `entries` because they never loaded, so the caller did not choose to drop them), exactly as they are. A file that is not an
60/// object of records is copied aside first. Written to a temp file and renamed.
61pub fn write_entries<T: Serialize + DeserializeOwned>(path: &Path, entries: &BTreeMap<String, T>) -> Result<(), String> {
62    write_entries_removing(path, entries, &[])
63}
64
65/// [`write_entries`] for a save that deletes records on purpose: each key of `removed` is dropped from the file even when this
66/// build cannot read its record (an uninstall must revoke what it names, not leave it for a later build to find).
67pub fn write_entries_removing<T: Serialize + DeserializeOwned>(path: &Path, entries: &BTreeMap<String, T>, removed: &[&str]) -> Result<(), String> {
68    if let Some(dir) = path.parent() {
69        std::fs::create_dir_all(dir).map_err(|e| e.to_string())?;
70    }
71    let mut out = serde_json::Map::new();
72    match read_raw_object(path) {
73        Some(on_disk) => {
74            for (key, value) in on_disk {
75                if !entries.contains_key(&key) && !removed.contains(&key.as_str()) && serde_json::from_value::<T>(value.clone()).is_err() {
76                    out.insert(key, value);
77                }
78            }
79        }
80        None => set_aside_if_unreadable::<serde_json::Map<String, Value>>(path),
81    }
82    for (key, entry) in entries {
83        out.insert(key.clone(), serde_json::to_value(entry).map_err(|e| e.to_string())?);
84    }
85    let tmp = path.with_extension("json.tmp");
86    std::fs::write(&tmp, serde_json::to_vec_pretty(&Value::Object(out)).map_err(|e| e.to_string())?).map_err(|e| e.to_string())?;
87    std::fs::rename(&tmp, path).map_err(|e| e.to_string())
88}
89
90/// The bytes of `path` as JSON, when it is JSON; the file as it was before this save, so the keys a typed value dropped can be
91/// carried over from it.
92pub fn read_old(path: &Path) -> Option<Value> {
93    serde_json::from_slice(&std::fs::read(path).ok()?).ok()
94}
95
96/// Copies into the object `new` every key of the object `old` that `new` lacks and that is not one of `known` (the keys this
97/// build owns: one of them missing from `new` was removed on purpose). What is left is what a newer AgentMux wrote.
98pub fn carry_unknown_keys(old: &Value, new: &mut Value, known: &[&str]) {
99    let (Some(old), Some(new)) = (old.as_object(), new.as_object_mut()) else { return };
100    for (key, value) in old {
101        if !known.contains(&key.as_str()) && !new.contains_key(key) {
102            new.insert(key.clone(), value.clone());
103        }
104    }
105}
106
107/// [`carry_unknown_keys`] for each object of the list `new`, from the object of the list `old` that has the same `id_key`.
108pub fn carry_unknown_keys_in_list(old: &Value, new: &mut Value, id_key: &str, known: &[&str]) {
109    let (Some(old), Some(new)) = (old.as_array(), new.as_array_mut()) else { return };
110    for item in new {
111        let Some(id) = item.get(id_key).cloned() else { continue };
112        if let Some(before) = old.iter().find(|o| o.get(id_key) == Some(&id)) {
113            carry_unknown_keys(before, item, known);
114        }
115    }
116}
117
118#[cfg(test)]
119#[path = "json_keep_tests.rs"]
120mod tests;