Skip to main content

lean_ctx_cloud/
unlinked.rs

1// SPDX-License-Identifier: Apache-2.0
2//! `<data_dir>/cloud/unlinked_roots.json` (rc4-6): the project folders the
3//! person stopped sharing with `cloud unlink`. A folder listed here is never
4//! shared again on its own: it resolves no vault (also not through its main
5//! checkout or another checkout of the same repository), `cloud sync` and the
6//! knowledge sync do not map it, a write does not push it, a task proposal
7//! or message from it is not sent, and capture queues no draft for it. Only
8//! an explicit `cloud link` in the folder that Cloud accepts takes it out of
9//! the list.
10//!
11//! Kept apart from `projects.json` (written by resolution and sync) so the
12//! opt-out survives every rewrite of the vault map.
13//!
14//! Fails closed: a store that cannot be read or parsed counts every folder
15//! as not shared ([`contains`] is `true`), and [`add`] / [`remove`] refuse,
16//! so `cloud unlink` and `cloud link` report the damage instead of starting
17//! from an empty list. Changes are made under a file lock and written
18//! atomically.
19
20use std::collections::BTreeSet;
21use std::path::Path;
22
23use lean_ctx::core::pathutil::same_project;
24use serde::{Deserialize, Serialize};
25
26use crate::CloudError;
27use crate::state::write_private;
28
29/// The file name in the cloud data dir.
30pub const FILE: &str = "unlinked_roots.json";
31
32/// The lock serializing changes of [`FILE`] between processes.
33const LOCK_FILE: &str = "unlinked_roots.lock";
34
35const SCHEMA: &str = "leanctx.cloud.unlinked_roots/v1";
36
37/// What a resolution of an opted-out folder answers.
38pub const REFUSAL: &str = "this project is not shared on this machine (`lean-ctx cloud unlink`); `lean-ctx cloud link` shares it again";
39
40#[derive(Debug, Default, Serialize, Deserialize)]
41struct Roots {
42    schema: String,
43    roots: BTreeSet<String>,
44}
45
46/// The canonical spelling of `root` (as given when it no longer exists).
47fn canonical(root: &Path) -> String {
48    std::fs::canonicalize(root)
49        .unwrap_or_else(|_| root.to_path_buf())
50        .to_string_lossy()
51        .into_owned()
52}
53
54/// The stored roots; a missing store is empty. A store that cannot be read,
55/// does not parse or names another schema is an error (and stays as it is).
56fn load(data_dir: &Path) -> Result<Roots, CloudError> {
57    let path = data_dir.join(FILE);
58    let bytes = match std::fs::read(&path) {
59        Ok(bytes) => bytes,
60        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
61            return Ok(Roots::default());
62        }
63        Err(error) => return Err(damaged(&path, &error.to_string())),
64    };
65    let roots: Roots =
66        serde_json::from_slice(&bytes).map_err(|e| damaged(&path, &e.to_string()))?;
67    if roots.schema != SCHEMA {
68        return Err(damaged(
69            &path,
70            &format!("unknown schema {:?}", roots.schema),
71        ));
72    }
73    Ok(roots)
74}
75
76fn damaged(path: &Path, why: &str) -> CloudError {
77    CloudError::Local(format!(
78        "the list of projects not shared on this machine ({}) cannot be read: {why}; until it is fixed or removed no project is shared",
79        path.display()
80    ))
81}
82
83fn save(data_dir: &Path, roots: &BTreeSet<String>) -> Result<(), CloudError> {
84    let bytes = serde_json::to_vec_pretty(&Roots {
85        schema: SCHEMA.into(),
86        roots: roots.clone(),
87    })
88    .map_err(|e| CloudError::Local(e.to_string()))?;
89    write_private(data_dir, FILE, &bytes)
90}
91
92/// Change the stored roots under the file lock; `change` answers whether
93/// it changed anything (then the store is written).
94fn update(
95    data_dir: &Path,
96    change: impl FnOnce(&mut BTreeSet<String>) -> bool,
97) -> Result<bool, CloudError> {
98    lean_ctx::core::secure_fs::private_dir(data_dir)
99        .map_err(|e| CloudError::Local(e.to_string()))?;
100    let _lock = lean_ctx::core::agents::FileLock::acquire(&data_dir.join(LOCK_FILE))
101        .map_err(|e| CloudError::Local(format!("unlinked projects lock: {e}")))?;
102    let mut roots = load(data_dir)?.roots;
103    if !change(&mut roots) {
104        return Ok(false);
105    }
106    save(data_dir, &roots)?;
107    Ok(true)
108}
109
110fn matches(stored: &str, root: &Path) -> bool {
111    same_project(stored, &canonical(root)) || same_project(stored, &root.to_string_lossy())
112}
113
114/// Whether `root` was unlinked and not linked again; an error names a
115/// damaged store (for `cloud status` and refusals).
116pub fn check(data_dir: &Path, root: &Path) -> Result<bool, CloudError> {
117    Ok(load(data_dir)?.roots.iter().any(|r| matches(r, root)))
118}
119
120/// The damage of the store, when it cannot be read (`None`: readable or
121/// absent). `cloud status` shows it, so the fail-closed state is visible.
122pub fn damage(data_dir: &Path) -> Option<String> {
123    load(data_dir).err().map(|error| error.to_string())
124}
125
126/// The vault record `root` is shared through, with the opt-out applied:
127/// [`VaultMap::for_root`](crate::vault::VaultMap::for_root) falls back from
128/// a worktree to its main checkout, which an unlinked worktree must not use
129/// (bd 40060). `None` for an unlinked folder and, fail closed, for every
130/// folder while the store is damaged.
131pub fn shared_record<'a>(
132    data_dir: &Path,
133    map: &'a crate::vault::VaultMap,
134    root: &str,
135) -> Option<&'a crate::vault::VaultRecord> {
136    if contains(data_dir, Path::new(root)) {
137        return None;
138    }
139    map.for_root(root)
140}
141
142/// The folder `root` was unlinked and not linked again; also `true` for
143/// every folder while the store is damaged (fail closed, warned once per
144/// process).
145pub fn contains(data_dir: &Path, root: &Path) -> bool {
146    static WARNED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
147    check(data_dir, root).unwrap_or_else(|error| {
148        if !WARNED.swap(true, std::sync::atomic::Ordering::Relaxed) {
149            tracing::warn!("cloud: {error}");
150        }
151        true
152    })
153}
154
155/// What a sender answers for a folder [`contains`] holds back: [`REFUSAL`],
156/// or the damage when the store cannot be read (`cloud link` would fail on
157/// it, so the refusal does not point there).
158pub fn refusal(data_dir: &Path) -> String {
159    damage(data_dir).unwrap_or_else(|| REFUSAL.to_owned())
160}
161
162/// Remember that the person stopped sharing `root`.
163pub fn add(data_dir: &Path, root: &Path) -> Result<(), CloudError> {
164    let canonical = canonical(root);
165    update(data_dir, |roots| roots.insert(canonical)).map(drop)
166}
167
168/// The person linked `root` again: drop its opt-out. `true` when it had one.
169pub fn remove(data_dir: &Path, root: &Path) -> Result<bool, CloudError> {
170    // No store, nothing to lift: a link writes no file and takes no lock.
171    if let Err(error) = std::fs::symlink_metadata(data_dir.join(FILE))
172        && error.kind() == std::io::ErrorKind::NotFound
173    {
174        return Ok(false);
175    }
176    update(data_dir, |roots| {
177        let before = roots.len();
178        roots.retain(|r| !matches(r, root));
179        roots.len() != before
180    })
181}
182
183/// Whether `root` has an opt-out in this machine's cloud data dir, read by
184/// `cloud link` before it writes anything: a damaged store fails the link.
185/// The opt-out stays in force through the link and its share (which
186/// resolves the vault through [`crate::knowledge::pull::resolve_for_link`]),
187/// so nothing is sent before Cloud took the link (bd 40060).
188pub fn before_link(root: &Path) -> Result<bool, CloudError> {
189    let store = crate::CloudStore::open()?;
190    check(store.data_dir(), root)
191}
192
193/// [`remove`] in this machine's cloud data dir, once `cloud link` kept the
194/// link (Cloud took the share, or it is shared once this machine
195/// connects). A link Cloud refuses never lifts it.
196pub fn forget_on_link(root: &Path) -> Result<bool, CloudError> {
197    let store = crate::CloudStore::open()?;
198    remove(store.data_dir(), root)
199}
200
201/// A main checkout and a linked git worktree of it laid out on disk the
202/// way `git worktree add` leaves them (what
203/// [`main_worktree_root`](lean_ctx::core::git_worktree::main_worktree_root)
204/// reads); returns `(main, worktree)` inside `base`. The one fixture for
205/// this crate's tests and, through `test-support`, the CLI's (bd 40158).
206#[cfg(any(test, feature = "test-support"))]
207#[doc(hidden)]
208pub fn fake_worktree(base: &Path) -> (std::path::PathBuf, std::path::PathBuf) {
209    let main = base.join("main");
210    let wt = base.join("wt");
211    let gitdir = main.join(".git/worktrees/wt");
212    let write = |path: std::path::PathBuf, text: String| {
213        std::fs::write(&path, text).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
214    };
215    for dir in [&gitdir, &wt] {
216        std::fs::create_dir_all(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display()));
217    }
218    write(wt.join(".git"), format!("gitdir: {}\n", gitdir.display()));
219    write(
220        gitdir.join("gitdir"),
221        format!("{}\n", wt.join(".git").display()),
222    );
223    write(gitdir.join("commondir"), "../..\n".to_string());
224    (main, wt)
225}
226
227#[cfg(test)]
228mod tests {
229    use super::*;
230
231    #[test]
232    fn unlink_opt_out_is_kept_until_the_folder_is_linked_again() {
233        let data = tempfile::tempdir().unwrap();
234        let repo = tempfile::tempdir().unwrap();
235        let other = tempfile::tempdir().unwrap();
236        assert!(!contains(data.path(), repo.path()));
237        add(data.path(), repo.path()).unwrap();
238        add(data.path(), repo.path()).unwrap();
239        assert!(contains(data.path(), repo.path()));
240        assert!(!contains(data.path(), other.path()));
241        assert!(remove(data.path(), repo.path()).unwrap());
242        assert!(!contains(data.path(), repo.path()));
243        assert!(!remove(data.path(), repo.path()).unwrap());
244    }
245
246    #[test]
247    fn unlink_store_damaged_fails_closed() {
248        let data = tempfile::tempdir().unwrap();
249        let repo = tempfile::tempdir().unwrap();
250        std::fs::write(data.path().join(FILE), b"{not json").unwrap();
251        // Every folder counts as not shared.
252        assert!(contains(data.path(), repo.path()));
253        // Neither unlink nor link works from an empty list.
254        assert!(add(data.path(), repo.path()).is_err());
255        assert!(remove(data.path(), repo.path()).is_err());
256        // The damaged store stays for the person to look at.
257        assert_eq!(std::fs::read(data.path().join(FILE)).unwrap(), b"{not json");
258        // The damage is named for status and refusals.
259        assert!(check(data.path(), repo.path()).is_err());
260        assert!(damage(data.path()).unwrap().contains(FILE));
261        assert!(refusal(data.path()).contains(FILE));
262        // Another schema is no list either.
263        std::fs::write(
264            data.path().join(FILE),
265            br#"{"schema":"leanctx.cloud.unlinked_roots/v9","roots":[]}"#,
266        )
267        .unwrap();
268        assert!(contains(data.path(), repo.path()));
269    }
270
271    /// bd 40060 MUST: an unlinked worktree is not shared through its main
272    /// checkout's record; the main checkout still is.
273    #[test]
274    fn unlink_of_a_worktree_holds_back_the_main_checkout_fallback() {
275        let base = tempfile::tempdir().unwrap();
276        let base = base.path().canonicalize().unwrap();
277        let (main, wt) = fake_worktree(&base);
278        let data = base.join("data");
279        let mut map = crate::vault::VaultMap::default();
280        map.vaults.insert(
281            "s".into(),
282            crate::vault::VaultRecord {
283                vault_id: "vlt_1".into(),
284                ns: "acme".into(),
285                name: "payments".into(),
286                sealed: false,
287                roots: vec![main.to_string_lossy().into_owned()],
288            },
289        );
290        let wt_text = wt.to_string_lossy();
291        assert!(map.for_root(&wt_text).is_some(), "the fallback this guards");
292        assert!(shared_record(&data, &map, &wt_text).is_some());
293
294        add(&data, &wt).unwrap();
295        assert!(shared_record(&data, &map, &wt_text).is_none());
296        assert!(shared_record(&data, &map, &main.to_string_lossy()).is_some());
297    }
298
299    #[test]
300    fn unlink_refusal_is_the_plain_one_for_a_readable_store() {
301        let data = tempfile::tempdir().unwrap();
302        assert_eq!(refusal(data.path()), REFUSAL);
303        assert_eq!(damage(data.path()), None);
304    }
305
306    #[test]
307    fn unlink_store_changes_from_threads_are_all_kept() {
308        let data = tempfile::tempdir().unwrap();
309        let folders: Vec<_> = (0..8).map(|_| tempfile::tempdir().unwrap()).collect();
310        std::thread::scope(|scope| {
311            for folder in &folders {
312                let data = data.path();
313                scope.spawn(move || add(data, folder.path()).unwrap());
314            }
315        });
316        for folder in &folders {
317            assert!(contains(data.path(), folder.path()));
318        }
319    }
320}