Skip to main content

lean_ctx_cloud/
resolution.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Local vault resolutions that no longer fit their checkout (dogfood
3//! 5.11.: one repository split across two vaults without a warning).
4//!
5//! `projects.json` ([`VaultMap`]) remembers which vault Cloud resolved for a
6//! checkout. That memory goes stale when
7//! - the link file now names another vault (`cloud link` after `cloud
8//!   connect`, or a pulled commit that changed `.lean-ctx-cloud.json`), or
9//! - the checkout's identity changed: a `.lean-ctx-id` that an earlier
10//!   `cloud link` wrote (32 random hex characters) no longer outranks the git
11//!   origin ([`crate::vault::project_identity`]), so every checkout of one
12//!   origin is one repository again.
13//!
14//! A stale record is never used: it is dropped, and the next resolve maps
15//! the checkout again (with the person's first-share consent where the gate
16//! holds). When Cloud still answers with another vault than the link file
17//! names, the resolve is refused ([`refuse_unlinked`]): nothing syncs into
18//! a vault the link file does not name.
19
20use std::path::Path;
21
22use lean_ctx::core::pathutil::same_project;
23use lean_ctx_protocol::cloud::status::CloudStatusVaultMismatchV1;
24use lean_ctx_protocol::cloud::vault::{VaultRefV1, stable_identity};
25
26use super::CloudError;
27use super::link::read_link;
28use super::vault::{VaultMap, VaultRecord, project_identity};
29
30/// Why a recorded resolution does not fit the checkout any more.
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum StaleReason {
33    /// The link file names `linked` (`ns/name`).
34    Link { linked: String },
35    /// The checkout's identity is not the one the record was resolved for.
36    Identity,
37}
38
39/// A resolution of `root` to `resolved` (`ns/name`) that does not hold.
40#[derive(Debug, Clone, PartialEq, Eq)]
41pub struct Stale {
42    pub root: String,
43    pub resolved: String,
44    pub reason: StaleReason,
45}
46
47impl Stale {
48    /// The linked vault, when the link file is the reason.
49    pub fn linked(&self) -> Option<&str> {
50        match &self.reason {
51            StaleReason::Link { linked } => Some(linked),
52            StaleReason::Identity => None,
53        }
54    }
55
56    /// `vault_mismatch` of `cloud status --json`.
57    pub fn wire(&self) -> CloudStatusVaultMismatchV1 {
58        CloudStatusVaultMismatchV1 {
59            project_root: self.root.clone(),
60            resolved: self.resolved.clone(),
61            linked: self.linked().map(str::to_string),
62            reason: match self.reason {
63                StaleReason::Link { .. } => "link",
64                StaleReason::Identity => "identity",
65            }
66            .into(),
67        }
68    }
69
70    /// One line for people (status, connect, link, sync).
71    pub fn describe(&self) -> String {
72        match &self.reason {
73            StaleReason::Link { linked } => format!(
74                "this machine resolved {} to the vault {}, but its link file names {linked}",
75                self.root, self.resolved
76            ),
77            StaleReason::Identity => format!(
78                "this machine resolved {} to the vault {} under an identity the checkout no longer has (a `.lean-ctx-id` written by an earlier `cloud link`; the git origin counts now)",
79                self.root, self.resolved
80            ),
81        }
82    }
83}
84
85fn address(record: &VaultRecord) -> String {
86    format!("{}/{}", record.ns, record.name)
87}
88
89/// The record `root` uses (its own, or its main checkout's), its key and
90/// the recorded root it was found by.
91fn recorded<'a>(map: &'a VaultMap, root: &Path) -> Option<(&'a str, &'a VaultRecord, String)> {
92    let find = |root: &str| {
93        map.vaults.iter().find_map(|(key, record)| {
94            record
95                .roots
96                .iter()
97                .find(|known| same_project(known, root))
98                .map(|known| (key.as_str(), record, known.clone()))
99        })
100    };
101    let root_str = root.to_string_lossy();
102    find(&root_str).or_else(|| {
103        let main = super::link::main_worktree_root(root)?;
104        find(&main.to_string_lossy())
105    })
106}
107
108/// Whether the recorded resolution of `root` is stale. Local files only;
109/// changes nothing.
110pub fn stale_for_root(map: &VaultMap, root: &Path) -> Option<Stale> {
111    let (key, record, _) = recorded(map, root)?;
112    let resolved = address(record);
113    let stale = |reason| Stale {
114        root: root.to_string_lossy().into_owned(),
115        resolved: resolved.clone(),
116        reason,
117    };
118    // A damaged link file is refused where the link is used; here it says
119    // nothing about the record.
120    if let Ok(Some(link)) = read_link(root)
121        && (link.vault.ns != record.ns || link.vault.name != record.name)
122    {
123        return Some(stale(StaleReason::Link {
124            linked: format!("{}/{}", link.vault.ns, link.vault.name),
125        }));
126    }
127    let current = project_identity(root).map(|identity| stable_identity(&identity));
128    if current.is_some_and(|current| current != key) {
129        return Some(stale(StaleReason::Identity));
130    }
131    None
132}
133
134/// Drop the stale resolution of `root` from `map`, if any. A link file that
135/// names another vault drops the whole record: one identity has one vault,
136/// so every checkout of it resolves again. An identity change drops only
137/// this checkout from the record of its old identity.
138pub fn forget_stale(map: &mut VaultMap, root: &Path) -> Option<Stale> {
139    let stale = stale_for_root(map, root)?;
140    let (key, _, known) = recorded(map, root)?;
141    let key = key.to_string();
142    match stale.reason {
143        StaleReason::Link { .. } => {
144            map.vaults.remove(&key);
145        }
146        StaleReason::Identity => {
147            if let Some(record) = map.vaults.get_mut(&key) {
148                record.roots.retain(|r| r != &known);
149                if record.roots.is_empty() {
150                    map.vaults.remove(&key);
151                }
152            }
153        }
154    }
155    Some(stale)
156}
157
158/// [`forget_stale`] for every checkout `map` knows.
159pub fn forget_all_stale(map: &mut VaultMap) -> Vec<Stale> {
160    let roots: Vec<String> = map
161        .vaults
162        .values()
163        .flat_map(|record| record.roots.iter().cloned())
164        .collect();
165    roots
166        .iter()
167        .filter_map(|root| forget_stale(map, Path::new(root)))
168        .collect()
169}
170
171/// The vault map at `data_dir` without stale resolutions; the file is
172/// rewritten when one was dropped. What every pass that sends (sync, task
173/// proposals) reads, so none sends into a vault the checkout left.
174pub fn load_current(data_dir: &Path) -> Result<(VaultMap, Vec<Stale>), CloudError> {
175    let mut map = VaultMap::load(data_dir);
176    let dropped = forget_all_stale(&mut map);
177    if !dropped.is_empty() {
178        map.save(data_dir)
179            .map_err(|e| CloudError::Local(format!("projects.json: {e}")))?;
180        for stale in &dropped {
181            tracing::info!(
182                "cloud: dropped a stale vault resolution: {}",
183                stale.describe()
184            );
185        }
186    }
187    Ok((map, dropped))
188}
189
190/// Drop the stale resolution of `root` in the map at `data_dir`.
191pub fn forget_stale_at(data_dir: &Path, root: &Path) -> Result<Option<Stale>, CloudError> {
192    let mut map = VaultMap::load(data_dir);
193    let Some(stale) = forget_stale(&mut map, root) else {
194        return Ok(None);
195    };
196    map.save(data_dir)
197        .map_err(|e| CloudError::Local(format!("projects.json: {e}")))?;
198    Ok(Some(stale))
199}
200
201/// The vault the checkout at `root` sends to, from the map at `data_dir`:
202/// `None` when it has none, refused (`vault_mismatch`) when its record is
203/// stale. The one lookup of every caller that writes to a vault (tasks, bus
204/// posts and leases, docs, the live bus), so a record the link file or the
205/// identity no longer backs is never written to, also before link, connect
206/// or sync dropped it (a `git pull` that changed the link file).
207pub fn vault_for_root(data_dir: &Path, root: &Path) -> Result<Option<VaultRecord>, CloudError> {
208    // A folder the person stopped sharing (`cloud unlink`) has no vault,
209    // also not through its main checkout or another checkout (rc4-6).
210    if crate::unlinked::contains(data_dir, root) {
211        return Ok(None);
212    }
213    vault_in(&VaultMap::load(data_dir), root).map(Option::<&VaultRecord>::cloned)
214}
215
216/// The map at `data_dir` without its stale records, the file unchanged:
217/// what the live bus subscribes and announces from, so it never joins a
218/// vault a checkout left.
219pub fn current_view(data_dir: &Path) -> VaultMap {
220    let mut map = VaultMap::load(data_dir);
221    forget_all_stale(&mut map);
222    map
223}
224
225/// [`vault_for_root`] in a loaded `map`.
226pub fn vault_in<'a>(map: &'a VaultMap, root: &Path) -> Result<Option<&'a VaultRecord>, CloudError> {
227    if let Some(stale) = stale_for_root(map, root) {
228        return Err(refuse_stale(&stale));
229    }
230    Ok(map.for_root(&root.to_string_lossy()))
231}
232
233/// Refused (`vault_mismatch`) when `record`, which a caller is about to
234/// sync for the checkout at `root`, is not what the checkout resolves to
235/// now: its link file names another vault, or the map's record of `root`
236/// at `data_dir` is stale. The guard of every vault sync (background pass
237/// and `cloud sync`), whatever map snapshot the caller planned from.
238pub fn refuse_stale_record(
239    data_dir: &Path,
240    record: &VaultRecord,
241    root: &Path,
242) -> Result<(), CloudError> {
243    if let Ok(Some(link)) = read_link(root)
244        && (link.vault.ns != record.ns || link.vault.name != record.name)
245    {
246        return Err(refuse_stale(&Stale {
247            root: root.to_string_lossy().into_owned(),
248            resolved: address(record),
249            reason: StaleReason::Link {
250                linked: format!("{}/{}", link.vault.ns, link.vault.name),
251            },
252        }));
253    }
254    match stale_for_root(&VaultMap::load(data_dir), root) {
255        Some(stale) => Err(refuse_stale(&stale)),
256        None => Ok(()),
257    }
258}
259
260/// The refusal for a write into the stale resolution `stale`.
261pub fn refuse_stale(stale: &Stale) -> CloudError {
262    CloudError::Refused(format!(
263        "vault_mismatch: {}. Nothing is sent to {} any more: run `lean-ctx cloud connect` here to resolve the project again",
264        stale.describe(),
265        stale.resolved
266    ))
267}
268
269/// Cloud answered `answered` for the checkout at `root`: refused when its
270/// link file names another vault. Cloud keeps the first binding of an
271/// identity (another Instance of the workspace may have made it), so a
272/// link to another vault cannot move it; syncing anyway would split the
273/// repository silently.
274pub fn refuse_unlinked(root: &Path, answered: &VaultRefV1) -> Result<(), CloudError> {
275    let Some(link) = read_link(root)? else {
276        return Ok(());
277    };
278    if link.vault == *answered {
279        return Ok(());
280    }
281    Err(CloudError::Refused(format!(
282        "vault_mismatch: LeanCTX Cloud keeps this repository in the vault {}/{} (bound there first, possibly by another Instance of the workspace), but {} names {}/{}. Nothing syncs for it until both agree: run `lean-ctx cloud link {}/{}` here, or move the repository to {}/{} in LeanCTX Cloud and run `lean-ctx cloud connect` again",
283        answered.ns,
284        answered.name,
285        super::link::LINK_FILE,
286        link.vault.ns,
287        link.vault.name,
288        answered.ns,
289        answered.name,
290        link.vault.ns,
291        link.vault.name,
292    )))
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    fn checkout(base: &Path, name: &str, origin: Option<&str>) -> std::path::PathBuf {
300        let root = base.join(name);
301        std::fs::create_dir_all(root.join(".git")).unwrap();
302        let config = origin.map_or(String::new(), |url| {
303            format!("[remote \"origin\"]\n\turl = {url}\n")
304        });
305        std::fs::write(root.join(".git/config"), config).unwrap();
306        root
307    }
308
309    fn record(map: &mut VaultMap, key: &str, vault: &str, roots: &[&Path]) {
310        let (ns, name) = vault.split_once('/').unwrap();
311        map.vaults.insert(
312            key.into(),
313            VaultRecord {
314                vault_id: format!("id-{name}"),
315                ns: ns.into(),
316                name: name.into(),
317                sealed: false,
318                roots: roots
319                    .iter()
320                    .map(|r| r.to_string_lossy().into_owned())
321                    .collect(),
322            },
323        );
324    }
325
326    fn stable(root: &Path) -> String {
327        stable_identity(&project_identity(root).unwrap())
328    }
329
330    /// The guard of `place::sync_vault`: a record planned from an older map
331    /// is refused once the link file names another vault, also when the map
332    /// on disk no longer has it.
333    #[test]
334    fn a_sync_of_a_record_the_link_file_left_is_refused() {
335        let base = tempfile::tempdir().unwrap();
336        let data = base.path().join("data");
337        std::fs::create_dir_all(&data).unwrap();
338        let a = checkout(
339            base.path(),
340            "a",
341            Some("git@github.com:yves/leanctx-cloud.git"),
342        );
343        let mut map = VaultMap::default();
344        record(&mut map, &stable(&a), "yves/cloud", &[&a]);
345        map.save(&data).unwrap();
346        let planned = map.vaults.values().next().unwrap().clone();
347        crate::link::link(&a, "yves/cloud").unwrap();
348        assert!(refuse_stale_record(&data, &planned, &a).is_ok());
349
350        crate::link::link(&a, "yves/leanctx-cloud").unwrap();
351        let refused = refuse_stale_record(&data, &planned, &a).unwrap_err();
352        assert!(refused.to_string().contains("vault_mismatch"), "{refused}");
353        VaultMap::default().save(&data).unwrap();
354        assert!(refuse_stale_record(&data, &planned, &a).is_err());
355    }
356
357    #[test]
358    fn a_link_that_names_another_vault_drops_the_whole_record() {
359        let base = tempfile::tempdir().unwrap();
360        let a = checkout(
361            base.path(),
362            "a",
363            Some("git@github.com:yves/leanctx-cloud.git"),
364        );
365        let b = checkout(
366            base.path(),
367            "b",
368            Some("git@github.com:yves/leanctx-cloud.git"),
369        );
370        let mut map = VaultMap::default();
371        record(&mut map, &stable(&a), "yves/cloud", &[&a, &b]);
372        assert_eq!(
373            stale_for_root(&map, &a),
374            None,
375            "no link file: nothing to compare"
376        );
377
378        super::super::link::link(&a, "yves/leanctx-cloud").unwrap();
379        let stale = stale_for_root(&map, &a).expect("stale");
380        assert_eq!(stale.resolved, "yves/cloud");
381        assert_eq!(stale.linked(), Some("yves/leanctx-cloud"));
382        assert!(
383            stale
384                .describe()
385                .contains("link file names yves/leanctx-cloud")
386        );
387        assert_eq!(forget_stale(&mut map, &a), Some(stale));
388        assert!(map.vaults.is_empty(), "b is the same repository");
389        assert!(map.for_root(&b.to_string_lossy()).is_none());
390    }
391
392    #[test]
393    fn an_identity_change_drops_only_that_checkout() {
394        let base = tempfile::tempdir().unwrap();
395        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
396        let mut map = VaultMap::default();
397        record(&mut map, "old-random-identity", "acme/pay", &[&a]);
398        let other = base.path().join("elsewhere");
399        record(&mut map, &stable(&a), "acme/pay", &[&other]);
400        let stale = forget_stale(&mut map, &a).expect("stale");
401        assert_eq!(stale.reason, StaleReason::Identity);
402        assert!(!map.vaults.contains_key("old-random-identity"));
403        assert!(map.vaults.contains_key(&stable(&a)));
404        assert_eq!(forget_stale(&mut map, &a), None);
405    }
406
407    #[test]
408    fn load_current_rewrites_the_map_once() {
409        let base = tempfile::tempdir().unwrap();
410        let data = base.path().join("data");
411        std::fs::create_dir_all(&data).unwrap();
412        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
413        let mut map = VaultMap::default();
414        record(&mut map, &stable(&a), "acme/old", &[&a]);
415        map.save(&data).unwrap();
416        super::super::link::link(&a, "acme/pay").unwrap();
417        let (map, dropped) = load_current(&data).unwrap();
418        assert_eq!(dropped.len(), 1);
419        assert!(map.vaults.is_empty());
420        assert!(VaultMap::load(&data).vaults.is_empty(), "saved");
421        assert!(load_current(&data).unwrap().1.is_empty());
422    }
423
424    #[test]
425    fn cloud_answering_another_vault_than_the_link_is_refused() {
426        let base = tempfile::tempdir().unwrap();
427        let a = checkout(base.path(), "a", Some("https://github.com/acme/pay.git"));
428        let answered = VaultRefV1 {
429            ns: "acme".into(),
430            name: "old".into(),
431        };
432        assert!(
433            refuse_unlinked(&a, &answered).is_ok(),
434            "no link: LeanCTX Cloud decides"
435        );
436        super::super::link::link(&a, "acme/pay").unwrap();
437        let refused = refuse_unlinked(&a, &answered).unwrap_err().to_string();
438        assert!(refused.contains("vault_mismatch"), "{refused}");
439        assert!(
440            refused.contains("acme/old") && refused.contains("acme/pay"),
441            "{refused}"
442        );
443        let linked = VaultRefV1 {
444            ns: "acme".into(),
445            name: "pay".into(),
446        };
447        assert!(refuse_unlinked(&a, &linked).is_ok());
448    }
449}