OXYGENHUB

Coverage / crates/oxy-core/src/repo/strata.rs 91.5%

931 of 1018 lines run, 146 of 188 functions · run #343 on proposal/124 · run missed

1
//! A repository kept on a [`Store`] (Oxygen Strata, docs/stores.md): what
2
//! `oxy push dir://…` or `oxy clone s3://…` talk to.
3
//!
4
//! The store holds three kinds of key:
5
//!
6
//! - `oxygen.toml`: the layout's format and the repository's id, written
7
//!   once by the first push;
8
//! - `bundles/<seq>-<hash>.bundle`: each push's changes, signatures,
9
//!   seals, objects and policies, as the wire protocol encodes a bundle,
10
//!   written once and named by content;
11
//! - `refs`: every bookmark with its heads and attestation, every tag, the
12
//!   policy and its history, encoded as the protocol's `refs` response,
13
//!   moved by compare-and-swap.
14
//!
15
//! A store cannot run code, so the client does what a hub does on a push,
16
//! against a **mirror**: a bare repository of its own, kept beside the
17
//! remote's other state under `.oxy/remotes/<name>/strata/`, brought level
18
//! with the store before every use (the record read, the bundles it has
19
//! not seen imported, the view set from the record), and then used as a
20
//! [`LocalRemote`] would be. A push runs the hub's own checks
21
//! (`receive_push`) on the mirror, uploads the bundle, and moves `refs`
22
//! from the version it read; if the record moved meanwhile, the mirror is
23
//! put back and the push reports it, exactly as a hub reports a stale
24
//! push. Nothing in the store is trusted: every object is re-hashed as it
25
//! is imported, and the fetch that follows verifies each bookmark's
26
//! attestation under the policy, as it does for any remote.
27
28
use super::{fail, Repo, RepoError, Result};
29
use crate::hash::{ChangeHash, ObjectRef, ObjectType};
30
use crate::objects::StateObject;
31
use crate::protocol::{
32
    wire, Bundle, RefResult, RefUpdate, RefsResponse, Remote, RemoteOptions, SignedPolicy, TagRef,
33
    UNBOUND_ID,
34
};
35
use crate::strata::{Error as StoreError, Store, Version};
36
use std::cell::RefCell;
37
use std::collections::BTreeSet;
38
use std::fs;
39
use std::path::{Path, PathBuf};
40
41
const MARKER_KEY: &str = "oxygen.toml";
42
const REFS_KEY: &str = "refs";
43
const BUNDLES_PREFIX: &str = "bundles/";
44
const FORMAT: u32 = 1;
45
46
impl From<StoreError> for RepoError {
471×
    fn from(e: StoreError) -> RepoError {
481×
        RepoError::Msg(e.to_string())
491×
    }
50
}
51
52
/// The `oxygen.toml` marker: two lines, written once.
5311×
fn marker(id: [u8; 16]) -> Vec<u8> {
5411×
    format!("format = {FORMAT}\nrepo = \"{}\"\n", hex::encode(id)).into_bytes()
5511×
}
56
57115×
fn parse_marker(bytes: &[u8], what: &str) -> Result<[u8; 16]> {
58115×
    let text = String::from_utf8_lossy(bytes);
59115×
    let mut format = None;
60115×
    let mut repo = None;
61229×
    for line in text.lines() {
62229×
        let Some((k, v)) = line.split_once('=') else {
631×
            continue;
64
        };
65228×
        let v = v.trim().trim_matches('"');
66228×
        match k.trim() {
67228×
            "format" => format = v.parse::<u32>().ok(),
68114×
            "repo" => {
69114×
                repo = hex::decode(v)
70114×
                    .ok()
71114×
                    .and_then(|b| <[u8; 16]>::try_from(b).ok())
72
            }
730×
            _ => {}
74
        }
75
    }
76115×
    match (format, repo) {
77114×
        (Some(f), _) if f > FORMAT => fail(format!(
78
            "{what} holds a repository in Strata format {f}, newer than this oxy understands (format {FORMAT}): upgrade oxy"
79
        )),
80113×
        (Some(_), Some(id)) => Ok(id),
811×
        _ => fail(format!("{what}: its oxygen.toml is not a Strata marker")),
82
    }
83115×
}
84
85
/// A remote kept on a store.
86
pub struct BucketRemote {
87
    store: Box<dyn Store>,
88
    /// Where the mirror lives: the remote's directory under `.oxy/remotes`,
89
    /// or a temporary directory when there is no repository yet (a clone),
90
    /// removed on drop.
91
    dir: PathBuf,
92
    temporary: bool,
93
    claimed_id: Option<[u8; 16]>,
94
    mirror: RefCell<Option<Repo>>,
95
}
96
97
impl Drop for BucketRemote {
9859×
    fn drop(&mut self) {
9959×
        if self.temporary {
1009×
            let _ = fs::remove_dir_all(&self.dir);
10150×
        }
10259×
    }
103
}
104
105
/// What a sync found: the record's version (to move it from) and the
106
/// repository id the store holds, if any.
107
struct Synced {
108
    version: Option<Version>,
109
    id: Option<[u8; 16]>,
110
}
111
112
impl BucketRemote {
11359×
    pub fn open(store: Box<dyn Store>, options: &RemoteOptions) -> Result<BucketRemote> {
11459×
        let (dir, temporary) = match &options.cache_dir {
11550×
            Some(d) => (d.clone(), false),
116
            None => {
1179×
                let mut nonce = [0u8; 6];
1189×
                rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
1199×
                (
1209×
                    std::env::temp_dir().join(format!(
1219×
                        "oxy-strata-{}-{}",
1229×
                        std::process::id(),
1239×
                        hex::encode(nonce)
1249×
                    )),
1259×
                    true,
1269×
                )
127
            }
128
        };
12959×
        Ok(BucketRemote {
13059×
            store,
13159×
            dir,
13259×
            temporary,
13359×
            claimed_id: options.repo_id,
13459×
            mirror: RefCell::new(None),
13559×
        })
13659×
    }
137
138113×
    fn what(&self) -> String {
139113×
        self.store.describe()
140113×
    }
141
142
    /// The repository id the store holds: `None` until a first push.
143137×
    fn stored_id(&self) -> Result<Option<[u8; 16]>> {
144137×
        match self.store.get(MARKER_KEY) {
145111×
            Ok(b) => Ok(Some(parse_marker(&b, &self.what())?)),
14626×
            Err(StoreError::NotFound(_)) => Ok(None),
1470×
            Err(e) => Err(e.into()),
148
        }
149137×
    }
150
15148×
    fn mirror_dir(&self) -> PathBuf {
15248×
        self.dir.join("mirror")
15348×
    }
154
155179×
    fn seen_path(&self) -> PathBuf {
156179×
        self.dir.join("seen")
157179×
    }
158
159
    /// The bundles already imported into the mirror.
160128×
    fn seen(&self) -> BTreeSet<String> {
161128×
        fs::read_to_string(self.seen_path())
162128×
            .map(|s| s.lines().map(str::to_string).collect())
163128×
            .unwrap_or_default()
164128×
    }
165
16651×
    fn mark_seen(&self, key: &str) -> Result<()> {
16751×
        let mut seen = self.seen();
16851×
        if seen.insert(key.to_string()) {
169114×
            let text: String = seen.iter().map(|k| format!("{k}\n")).collect();
17051×
            crate::durable::write_atomic(&self.seen_path(), text.as_bytes())?;
1710×
        }
17251×
        Ok(())
17351×
    }
174
175
    /// Open the mirror for repository `id`, creating it on first use.
17677×
    fn open_mirror(&self, id: [u8; 16]) -> Result<()> {
17777×
        if self.mirror.borrow().is_some() {
17829×
            return Ok(());
17948×
        }
18048×
        let dir = self.mirror_dir();
18148×
        let repo = if dir.join(super::OXY_DIR).is_dir() {
18227×
            let repo = Repo::open(&dir)?;
18327×
            if repo.id()? != id {
184
                // The store was emptied and reused for another repository:
185
                // start the mirror over.
1860×
                drop(repo);
1870×
                fs::remove_dir_all(&self.dir)?;
1880×
                fs::create_dir_all(&self.dir)?;
1890×
                Repo::init_bare_with_id(&dir, id)?
190
            } else {
19127×
                repo
192
            }
193
        } else {
19421×
            fs::create_dir_all(&self.dir)?;
19521×
            Repo::init_bare_with_id(&dir, id)?
196
        };
19748×
        *self.mirror.borrow_mut() = Some(repo);
19848×
        Ok(())
19977×
    }
200
201230×
    fn with_mirror<T>(&self, f: impl FnOnce(&Repo) -> Result<T>) -> Result<T> {
202230×
        let m = self.mirror.borrow();
203230×
        match m.as_ref() {
204230×
            Some(repo) => f(repo),
2050×
            None => fail(format!(
206
                "{} holds no repository yet: push one to it first",
2070×
                self.what()
208
            )),
209
        }
210230×
    }
211
212
    /// Bring the mirror level with the store.
21396×
    fn sync(&self) -> Result<Synced> {
21496×
        let Some(id) = self.stored_id()? else {
21519×
            return Ok(Synced {
21619×
                version: None,
21719×
                id: None,
21819×
            });
219
        };
22077×
        self.open_mirror(id)?;
22177×
        let record = self.store.read_ref(REFS_KEY)?;
22277×
        let (resp, version) = match record {
22367×
            Some((bytes, version)) => {
22467×
                let (rid, resp) = wire::decode_refs(&bytes)?;
22567×
                if rid != id {
2260×
                    return fail(format!(
227
                        "{}: its refs record names a different repository than its oxygen.toml; the store is damaged",
2280×
                        self.what()
229
                    ));
23067×
                }
23167×
                (resp, Some(version))
232
            }
23310×
            None => (RefsResponse::default(), None),
234
        };
23577×
        self.with_mirror(|mirror| {
236
            // Another process may have brought the mirror level since this
237
            // handle read its head.
23877×
            mirror.refresh()?;
239
            // The policy first: bundles are then imported under it.
24077×
            if let Some(sp) = &resp.policy {
2410×
                let have = mirror.current_policy()?.map(|(_, p)| p.policy.serial);
2420×
                if have.is_none_or(|s| s < sp.policy.serial) {
2430×
                    mirror
2440×
                        .adopt_policy_chain(&resp.history, sp, "strata sync")
2450×
                        .map_err(|e| RepoError::Msg(format!("policy from {}: {e}", self.what())))?;
2460×
                }
24777×
            }
24877×
            self.import_new_bundles(mirror)?;
24976×
            self.set_view(mirror, &resp)?;
25075×
            Ok(())
25177×
        })?;
25275×
        Ok(Synced {
25375×
            version,
25475×
            id: Some(id),
25575×
        })
25696×
    }
257
258
    /// Import every bundle in the store the mirror has not seen. Bundles
259
    /// are named in the order they were pushed, but two pushes from the
260
    /// same base may interleave, so a bundle whose dependencies are not
261
    /// there yet is tried again after the others.
26277×
    fn import_new_bundles(&self, mirror: &Repo) -> Result<()> {
26377×
        let seen = self.seen();
26477×
        let mut pending: Vec<String> = self
26577×
            .store
26677×
            .list(BUNDLES_PREFIX)?
26777×
            .into_iter()
26877×
            .map(|e| e.key)
269116×
            .filter(|k| !seen.contains(k))
27077×
            .collect();
27177×
        let strict = mirror.current_policy()?.is_some();
27296×
        while !pending.is_empty() {
27320×
            let mut deferred = Vec::new();
27420×
            let mut last_error = None;
27520×
            let before = pending.len();
27628×
            for key in pending.drain(..) {
27728×
                let bytes = match self.store.get(&key) {
27827×
                    Ok(b) => b,
279
                    // Listed, then gone: a gc merged it into a newer
280
                    // bundle, which this listing holds too.
2811×
                    Err(StoreError::NotFound(_)) => continue,
2820×
                    Err(e) => return Err(e.into()),
283
                };
28427×
                let bundle = wire::decode_bundle(&bytes)
28527×
                    .map_err(|e| RepoError::Msg(format!("{}: {key}: {e}", self.what())))?;
28627×
                match mirror.import_bundle(&bundle, strict) {
28724×
                    Ok(_) => self.mark_seen(&key)?,
2883×
                    Err(RepoError::Msg(m)) if m.contains("neither stored nor in the bundle") => {
2893×
                        last_error = Some(m);
2903×
                        deferred.push(key);
2913×
                    }
2920×
                    Err(e) => return Err(RepoError::Msg(format!("{}: {key}: {e}", self.what()))),
293
                }
294
            }
29520×
            if deferred.len() == before {
296
                // No progress: something those bundles need was never
297
                // pushed, or a push is still in progress.
2981×
                return fail(format!(
299
                    "{}: {} cannot be imported ({}); a push may be in progress, so try again, else the store is missing changes",
3001×
                    self.what(),
3011×
                    deferred.join(", "),
3021×
                    last_error.unwrap_or_default()
303
                ));
30419×
            }
30519×
            pending = deferred;
306
        }
30776×
        Ok(())
30877×
    }
309
310
    /// Make the mirror's view say what the record says.
31176×
    fn set_view(&self, mirror: &Repo, resp: &RefsResponse) -> Result<()> {
31276×
        let (op_ref, op) = mirror.head_op()?;
31376×
        let mut view = op.view.clone();
31476×
        view.bookmarks.clear();
31576×
        for r in &resp.refs {
31671×
            for h in &r.heads {
31771×
                if !mirror.store.has(h) {
3181×
                    return fail(format!(
319
                        "{}: bookmark {:?} names change {}, which no bundle there holds; a push may be in progress, so try again",
3201×
                        self.what(),
321
                        r.name,
3221×
                        h.short(12)
323
                    ));
32470×
                }
325
            }
32667×
            let state = mirror.store.put_state(&StateObject::new(r.heads.clone()))?;
32767×
            if state != r.state {
3280×
                return fail(format!(
329
                    "{}: bookmark {:?} names a state that does not match its heads; the store is damaged",
3300×
                    self.what(),
331
                    r.name
332
                ));
33367×
            }
33467×
            if let Some(sa) = &r.attestation {
3358×
                let current = mirror.latest_ref_attest(&r.name)?.map(|(_, a)| a);
3368×
                if current.as_ref() != Some(sa) {
3373×
                    let a = mirror.store.put_attest(&sa.attest)?;
3383×
                    for sig in &sa.sigs {
3393×
                        mirror.store.put_signature(&a, sig)?;
340
                    }
3413×
                    mirror.set_ref_attest(&r.name, &a)?;
3425×
                }
34359×
            }
34467×
            view.bookmarks.insert(r.name.clone(), state);
345
        }
34675×
        let policy = mirror.current_policy()?.map(|(_, sp)| sp.policy);
34775×
        for t in &resp.tags {
34821×
            mirror.store.put_state(&StateObject::new(t.heads.clone()))?;
34921×
            mirror
35021×
                .adopt_tag(&mut view, t, policy.as_ref())
35121×
                .map_err(|e| RepoError::Msg(format!("{}: {e}", self.what())))?;
352
        }
35375×
        if view != op.view {
35426×
            mirror.record_op(&[op_ref], "strata sync", view)?;
35549×
        }
35675×
        Ok(())
35776×
    }
358
359
    /// The record for the mirror's current references.
36026×
    fn record(&self, id: [u8; 16]) -> Result<Vec<u8>> {
36126×
        self.with_mirror(|mirror| {
36226×
            let mut resp = mirror.remote_refs()?;
363
            // A mirror has no checkout; the store's clone picks a bookmark
364
            // as any other remote's does.
36526×
            resp.default_bookmark = None;
36626×
            Ok(wire::encode_refs(id, &resp))
36726×
        })
36826×
    }
369
370
    /// Store a bundle under the next sequence number; returns its key.
37128×
    fn upload(&self, bundle: &Bundle) -> Result<String> {
37228×
        let bytes = wire::encode_bundle(bundle);
37328×
        let hash = blake3::hash(&bytes).to_hex();
37428×
        let seq = self.store.list(BUNDLES_PREFIX)?.len() + 1;
37528×
        let key = format!("{BUNDLES_PREFIX}{seq:08}-{}.bundle", &hash[..16]);
37628×
        match self.store.put_new(&key, &bytes) {
37727×
            Ok(()) | Err(StoreError::Exists(_)) => {}
3781×
            Err(e) => return Err(e.into()),
379
        }
38027×
        self.mark_seen(&key)?;
38127×
        Ok(key)
38228×
    }
383
}
384
385
impl Remote for BucketRemote {
38641×
    fn repo_id(&self) -> Result<[u8; 16]> {
38741×
        Ok(self.stored_id()?.unwrap_or(UNBOUND_ID))
38841×
    }
389
39055×
    fn refs(&self) -> Result<RefsResponse> {
39155×
        let synced = self.sync()?;
39253×
        if synced.id.is_none() {
3939×
            return Ok(RefsResponse::default());
39444×
        }
39544×
        self.with_mirror(|mirror| {
39644×
            let mut resp = mirror.remote_refs()?;
39744×
            resp.default_bookmark = None;
39844×
            Ok(resp)
39944×
        })
40055×
    }
401
40212×
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
40312×
        self.with_mirror(|m| m.negotiate(have, want))
40412×
    }
405
40612×
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
40712×
        self.with_mirror(|m| m.bundle_raw_for(changes, max_blob))
40812×
    }
409
4100×
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
4110×
        self.with_mirror(|m| m.objects_for(refs))
4120×
    }
413
4140×
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
4150×
        self.with_mirror(|m| m.checkpoint_bundle_for(heads))
4160×
    }
417
4180×
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
4190×
        self.with_mirror(|m| m.shallow_changes(heads, depth))
4200×
    }
421
42225×
    fn push(
42325×
        &self,
42425×
        bundle: Bundle,
42525×
        updates: Vec<RefUpdate>,
42625×
        policy: Option<SignedPolicy>,
42725×
        tags: Vec<TagRef>,
42825×
    ) -> Result<Vec<RefResult>> {
42925×
        let mut synced = self.sync()?;
43025×
        let id = match synced.id {
43115×
            Some(id) => id,
432
            None => {
433
                // The first push binds the store to this repository. Two
434
                // first pushes race on the marker; the loser reads the
435
                // winner's and goes on only if it is the same repository.
43610×
                let Some(id) = self.claimed_id else {
4370×
                    return fail(format!(
438
                        "{} is empty, and this client did not say which repository it is",
4390×
                        self.what()
440
                    ));
441
                };
44210×
                match self.store.put_new(MARKER_KEY, &marker(id)) {
44310×
                    Ok(()) => {}
4440×
                    Err(StoreError::Exists(_)) => {}
4450×
                    Err(e) => return Err(e.into()),
446
                }
44710×
                synced = self.sync()?;
44810×
                match synced.id {
44910×
                    Some(stored) if stored == id => id,
450
                    _ => {
4510×
                        return fail(format!(
452
                            "{} was just bound to another repository by a concurrent push",
4530×
                            self.what()
454
                        ))
455
                    }
456
                }
457
            }
458
        };
45925×
        if let Some(claimed) = self.claimed_id {
46025×
            if claimed != id {
4610×
                return fail(format!(
462
                    "{} holds a different repository (id {}) than this one ({}): a store holds one repository; use another prefix or bucket",
4630×
                    self.what(),
4640×
                    hex::encode(id),
4650×
                    hex::encode(claimed)
466
                ));
46725×
            }
4680×
        }
469
        // The bundle is checked against the mirror and uploaded once; the
470
        // record is then moved from the version read. If it moved
471
        // meanwhile (another push landed), the mirror is put back, brought
472
        // level again, and the updates applied over what landed: two
473
        // pushes to different bookmarks both get through, and one to the
474
        // same bookmark is told it is stale, as a hub would say.
47525×
        let mut uploaded = false;
47627×
        for attempt in 0..PUSH_ATTEMPTS {
47727×
            let (before_ref, before) = self.with_mirror(|m| m.head_op())?;
47827×
            let results = self.with_mirror(|m| {
47927×
                m.receive_push(
48027×
                    bundle.clone(),
48127×
                    updates.clone(),
48227×
                    policy.clone(),
48327×
                    tags.clone(),
484
                )
48527×
            })?;
48627×
            if !results.iter().any(|r| r.ok) {
4870×
                return Ok(results);
48827×
            }
48927×
            if !bundle.is_empty() && !uploaded {
49025×
                self.upload(&bundle)?;
49124×
                uploaded = true;
4922×
            }
49326×
            let record = self.record(id)?;
49426×
            match self
49526×
                .store
49626×
                .write_ref(REFS_KEY, &record, synced.version.as_ref())
497
            {
49824×
                Ok(_) => return Ok(results),
499
                Err(StoreError::Conflict(_)) => {
5002×
                    self.with_mirror(|m| {
5012×
                        let (now, _) = m.head_op()?;
5022×
                        if now != before_ref {
5032×
                            m.record_op(
5042×
                                &[now],
5052×
                                "strata push undone: the remote moved",
5062×
                                before.view.clone(),
5070×
                            )?;
5080×
                        }
5092×
                        Ok(())
5102×
                    })?;
5112×
                    synced = self.sync()?;
5122×
                    if attempt + 1 == PUSH_ATTEMPTS {
5130×
                        return Ok(results
5140×
                            .into_iter()
5150×
                            .map(|r| RefResult {
5160×
                                name: r.name,
517
                                ok: false,
5180×
                                reason: "the remote kept moving while pushing (other pushes landed first); pull, then push again".into(),
5190×
                            })
5200×
                            .collect());
5212×
                    }
522
                }
5230×
                Err(e) => return Err(e.into()),
524
            }
525
        }
5260×
        unreachable!("the loop returns")
52725×
    }
528
}
529
530
/// How often a push is applied over what landed meanwhile before giving up.
531
const PUSH_ATTEMPTS: usize = 4;
532
533
/// The grace period before `gc` removes a bundle it merged: a reader that
534
/// listed it before the merge can still fetch it.
535
pub const REMOTE_GC_GRACE: std::time::Duration = std::time::Duration::from_secs(7 * 86_400);
536
537
/// Key of the record naming the bundles a gc merged, with when.
538
const TRASH_KEY: &str = "gc";
539
540
/// The superseded bundles and when (milliseconds) each was superseded.
541
type Trash = Vec<(String, u64)>;
542
543
/// What a gc against a store did.
544
#[derive(Clone, Debug, Default, PartialEq, Eq)]
545
pub struct RemoteGc {
546
    /// Bundles folded into one new bundle.
547
    pub merged: usize,
548
    /// The merged bundle's size, bytes.
549
    pub bundle_bytes: usize,
550
    /// Changes in the merged bundle.
551
    pub changes: usize,
552
    /// Superseded bundles removed, past the grace period.
553
    pub deleted: usize,
554
    /// Superseded bundles kept for now by the grace period.
555
    pub deferred: usize,
556
}
557
5587×
fn now_ms() -> u64 {
5597×
    std::time::SystemTime::now()
5607×
        .duration_since(std::time::UNIX_EPOCH)
5617×
        .map(|d| d.as_millis() as u64)
5627×
        .unwrap_or(0)
5637×
}
564
565
impl BucketRemote {
566
    /// The bundles a gc superseded, with when: one `KEY\tMILLIS` per line.
5674×
    fn trash(&self) -> Result<(Trash, Option<Version>)> {
5684×
        match self.store.read_ref(TRASH_KEY)? {
5692×
            Some((bytes, v)) => {
5702×
                let text = String::from_utf8_lossy(&bytes);
5712×
                let list = text
5722×
                    .lines()
5734×
                    .filter_map(|l| {
5744×
                        let (k, t) = l.split_once('\t')?;
5754×
                        Some((k.to_string(), t.parse().ok()?))
5764×
                    })
5772×
                    .collect();
5782×
                Ok((list, Some(v)))
579
            }
5802×
            None => Ok((Vec::new(), None)),
581
        }
5824×
    }
583
5846×
    fn write_trash(&self, list: &[(String, u64)], expected: Option<&Version>) -> Result<Version> {
5858×
        let text: String = list.iter().map(|(k, t)| format!("{k}\t{t}\n")).collect();
5866×
        Ok(self.store.write_ref(TRASH_KEY, text.as_bytes(), expected)?)
5876×
    }
588
589
    /// Fold every bundle into one holding what the record reaches, and
590
    /// remove the bundles that made a gc redundant once `grace` has
591
    /// passed since they were superseded (stores.md §6).
5924×
    pub fn gc(&self, grace: std::time::Duration) -> Result<RemoteGc> {
5934×
        let synced = self.sync()?;
5944×
        let Some(id) = synced.id else {
5950×
            return fail(format!("{} holds no repository yet", self.what()));
596
        };
5974×
        let mut report = RemoteGc::default();
5984×
        let existing: Vec<String> = self
5994×
            .store
6004×
            .list(BUNDLES_PREFIX)?
6014×
            .into_iter()
6024×
            .map(|e| e.key)
6034×
            .collect();
6044×
        let (mut trash, mut trash_version) = self.trash()?;
6054×
        let live: Vec<&String> = existing
6064×
            .iter()
60714×
            .filter(|k| !trash.iter().any(|(t, _)| t == *k))
6084×
            .collect();
6094×
        if live.len() > 1 {
610
            // Everything the record reaches, in dependency order, with
611
            // the state objects the bookmarks and tags name.
6123×
            let (bundle, changes) = self.with_mirror(|m| {
6133×
                let resp = m.remote_refs()?;
6143×
                let mut heads: Vec<ChangeHash> = Vec::new();
6153×
                for r in &resp.refs {
6163×
                    heads.extend(r.heads.iter().copied());
6173×
                }
6183×
                for t in &resp.tags {
6192×
                    heads.extend(t.heads.iter().copied());
6202×
                }
6213×
                heads.sort();
6223×
                heads.dedup();
6233×
                let changes = m.negotiate(&[], &heads)?;
6243×
                let mut bundle = m.bundle_for(&changes)?;
6253×
                for r in &resp.refs {
6263×
                    bundle.objects.push((
6273×
                        ObjectType::State,
6283×
                        StateObject::new(r.heads.clone()).encode(),
6293×
                    ));
6303×
                }
6313×
                for t in &resp.tags {
6322×
                    bundle.objects.push((
6332×
                        ObjectType::State,
6342×
                        StateObject::new(t.heads.clone()).encode(),
6352×
                    ));
6362×
                }
6373×
                Ok((bundle, changes.len()))
6383×
            })?;
6393×
            report.changes = changes;
6403×
            report.bundle_bytes = wire::encode_bundle(&bundle).len();
6413×
            let merged_key = self.upload(&bundle)?;
6423×
            let now = now_ms();
6438×
            for k in live {
6448×
                if *k != merged_key {
6458×
                    trash.push((k.clone(), now));
6468×
                    report.merged += 1;
6478×
                }
648
            }
6493×
            trash_version = Some(self.write_trash(&trash, trash_version.as_ref())?);
6501×
        }
651
        // What the grace period has released.
6524×
        let now = now_ms();
6534×
        let mut kept = Vec::new();
65412×
        for (k, when) in trash {
65512×
            if now.saturating_sub(when) >= grace.as_millis() as u64 {
6568×
                self.store.delete(&k)?;
6578×
                report.deleted += 1;
6584×
            } else {
6594×
                kept.push((k, when));
6604×
                report.deferred += 1;
6614×
            }
662
        }
6634×
        if report.deleted > 0 {
6643×
            self.write_trash(&kept, trash_version.as_ref())?;
6651×
        }
6664×
        let _ = id;
6674×
        Ok(report)
6684×
    }
669
}
670
671
impl Repo {
672
    /// `oxy gc --remote NAME`: a gc against a remote kept on a store.
6736×
    pub fn gc_remote(&self, name: &str, now: bool) -> Result<RemoteGc> {
6746×
        let Some(url) = self.config.remotes.get(name).cloned() else {
6752×
            return fail(format!("no remote {name:?}"));
676
        };
6774×
        let options = self.remote_options(name);
6784×
        let Some(store) = crate::protocol::open_store(&url, &options) else {
6790×
            return fail(format!(
680
                "gc --remote works on a remote kept on a store (s3://, gs://, az://, dir://); {name} is {url}"
681
            ));
682
        };
6834×
        let remote = BucketRemote::open(store?, &options)?;
6844×
        let grace = if now {
6853×
            std::time::Duration::ZERO
686
        } else {
6871×
            REMOTE_GC_GRACE
688
        };
6894×
        remote.gc(grace)
6906×
    }
691
}
692
693
/// Open a remote on `store` for the local repository described by `options`.
69448×
pub fn open_store_remote(
69548×
    store: Box<dyn Store>,
69648×
    options: &RemoteOptions,
69748×
) -> Result<Box<dyn Remote>> {
69848×
    Ok(Box::new(BucketRemote::open(store, options)?))
69948×
}
700
701
/// Whether `path` holds a Strata store rather than a repository.
7020×
pub fn is_store_dir(path: &Path) -> bool {
7030×
    path.join(MARKER_KEY).is_file() || path.join(REFS_KEY).is_file()
7040×
}
705
706
#[cfg(test)]
707
mod tests {
708
    use super::*;
709
    use crate::repo::IdentityScope;
710
    use crate::strata::{Entry, LocalStore, MemoryStore};
711
    use std::ops::Range;
712
    use std::sync::Mutex;
713
7149×
    fn hermetic() {
715
        static ONCE: std::sync::Once = std::sync::Once::new();
716
        static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
7179×
        ONCE.call_once(|| {
7181×
            let d = tempfile::tempdir().unwrap();
7191×
            std::env::set_var("OXY_HOME", d.path());
7201×
            DIR.set(d).ok();
7211×
        });
7229×
    }
723
72422×
    fn write(root: &Path, rel: &str, content: &[u8]) {
72522×
        let p = root.join(rel);
72622×
        fs::create_dir_all(p.parent().unwrap()).unwrap();
72722×
        fs::write(p, content).unwrap();
72822×
    }
729
7306×
    fn add_remote(repo: &mut Repo, name: &str, url: &str) {
7316×
        repo.config.set(&format!("remote.{name}.url"), url).unwrap();
7326×
        repo.save_config().unwrap();
7336×
    }
734
73511×
    fn keys(store: &dyn Store, prefix: &str) -> Vec<String> {
73611×
        store
73711×
            .list(prefix)
73811×
            .unwrap()
73911×
            .into_iter()
74011×
            .map(|e| e.key)
74111×
            .collect()
74211×
    }
743
744
    #[test]
7451×
    fn push_clone_and_pull_through_a_directory_store() {
7461×
        hermetic();
7471×
        let dir = tempfile::tempdir().unwrap();
7481×
        let root = dir.path();
7491×
        let url = format!("dir://{}", root.join("bucket").display());
7501×
        let store = LocalStore::open(root.join("bucket")).unwrap();
751
752
        // A signs, commits, tags and pushes: the store gets the marker, one
753
        // bundle, and a record.
7541×
        let mut a = Repo::init(&root.join("a"))
7551×
            .unwrap()
7561×
            .with_home(root.join("home-a"));
7571×
        a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
7581×
            .unwrap();
7591×
        add_remote(&mut a, "bucket", &url);
7601×
        write(&root.join("a"), "f.txt", b"a\n");
7611×
        let h1 = a.commit("first", &[]).unwrap();
7621×
        a.tag_create("v1", &[h1], "one").unwrap();
7631×
        let results = a.push("bucket", false).unwrap();
7641×
        assert!(results.iter().all(|r| r.ok), "{results:?}");
7651×
        assert_eq!(
7661×
            keys(&store, ""),
7671×
            [
7681×
                "bundles/00000001-".to_string() + &keys(&store, "bundles/")[0][17..],
7691×
                "oxygen.toml".into(),
7701×
                "refs".into()
7711×
            ]
772
        );
7731×
        assert_eq!(
7741×
            parse_marker(&store.get("oxygen.toml").unwrap(), "t").unwrap(),
7751×
            a.id().unwrap()
776
        );
7771×
        let again = a.push("bucket", false).unwrap();
7781×
        assert!(
7791×
            again[0].ok && again[0].reason.contains("up to date"),
780
            "{again:?}"
781
        );
7821×
        assert_eq!(
7831×
            keys(&store, "bundles/").len(),
784
            1,
785
            "a no-op push uploads nothing"
786
        );
787
788
        // B clones from the store: same id, same file, the tag, and the
789
        // seal on the change.
7901×
        let b = Repo::clone(&url, &root.join("b")).unwrap();
7911×
        assert_eq!(b.id().unwrap(), a.id().unwrap());
7921×
        assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
7931×
        assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
7941×
        assert_eq!(
7951×
            b.tags()
7961×
                .unwrap()
7971×
                .iter()
7981×
                .map(|t| t.name.clone())
7991×
                .collect::<Vec<_>>(),
800
            ["v1"]
801
        );
8021×
        assert!(matches!(
8031×
            b.authenticate_change(&h1).unwrap(),
804
            crate::repo::SignatureStatus::Valid { sealed: true, .. }
805
        ));
8061×
        assert!(
8071×
            root.join("b/.oxy/remotes/origin/strata/mirror/.oxy")
8081×
                .is_dir(),
809
            "the mirror lives with the remote's state"
810
        );
8111×
        assert!(
8121×
            !std::env::temp_dir()
8131×
                .read_dir()
8141×
                .unwrap()
8151×
                .flatten()
8168×
                .any(|e| e.file_name().to_string_lossy().starts_with("oxy-strata-")),
817
            "a clone's temporary mirror is removed"
818
        );
819
820
        // B commits and pushes; A pulls it. A then commits and pushes.
8211×
        write(&root.join("b"), "f.txt", b"a\nb\n");
8221×
        let h2 = b.commit("second", &[]).unwrap();
8231×
        assert!(b.push("origin", false).unwrap()[0].ok);
8241×
        assert_eq!(keys(&store, "bundles/").len(), 2);
8251×
        let pr = a.pull("bucket").unwrap();
8261×
        assert!(pr.changed && pr.checked_out);
8271×
        assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
8281×
        write(&root.join("a"), "g.txt", b"g\n");
8291×
        let h3 = a.commit("third", &[]).unwrap();
8301×
        assert!(a.push("bucket", false).unwrap()[0].ok);
8311×
        let pr = b.pull("origin").unwrap();
8321×
        assert!(pr.changed);
833
        // g.txt is new, so its change commutes with B's: two heads.
8341×
        let mut want = vec![h2, h3];
8351×
        want.sort();
8361×
        assert_eq!(b.bookmark_heads().unwrap(), want);
8371×
        assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
838
839
        // A third clone gets everything from the three bundles.
8401×
        let c = Repo::clone(&url, &root.join("c")).unwrap();
8411×
        assert_eq!(c.bookmark_heads().unwrap(), want);
8421×
        assert_eq!(fs::read(root.join("c/f.txt")).unwrap(), b"a\nb\n");
8431×
    }
844
845
    #[test]
8461×
    fn a_push_behind_the_remote_is_refused_before_anything_is_uploaded() {
8471×
        hermetic();
8481×
        let dir = tempfile::tempdir().unwrap();
8491×
        let root = dir.path();
8501×
        let url = format!("dir://{}", root.join("bucket").display());
8511×
        let store = LocalStore::open(root.join("bucket")).unwrap();
8521×
        let mut a = Repo::init(&root.join("a")).unwrap();
8531×
        add_remote(&mut a, "bucket", &url);
8541×
        write(&root.join("a"), "f.txt", b"a\n");
8551×
        a.commit("first", &[]).unwrap();
8561×
        assert!(a.push("bucket", false).unwrap()[0].ok);
8571×
        let b = Repo::clone(&url, &root.join("b")).unwrap();
8581×
        write(&root.join("b"), "f.txt", b"b\n");
8591×
        b.commit("from b", &[]).unwrap();
8601×
        assert!(b.push("origin", false).unwrap()[0].ok);
8611×
        write(&root.join("a"), "g.txt", b"g\n");
8621×
        a.commit("from a", &[]).unwrap();
8631×
        let e = a.push("bucket", false).unwrap_err().to_string();
8641×
        assert!(e.contains("pull first"), "{e}");
8651×
        assert_eq!(keys(&store, "bundles/").len(), 2);
8661×
        assert!(a.pull("bucket").unwrap().changed);
8671×
        assert!(a.push("bucket", false).unwrap()[0].ok);
8681×
        assert_eq!(keys(&store, "bundles/").len(), 3);
8691×
    }
870
871
    /// A store whose record moves under a writer the first time it is
872
    /// written to: what a concurrent push looks like between the read and
873
    /// the compare-and-swap.
874
    struct Racing {
875
        inner: MemoryStore,
876
        raced: Mutex<bool>,
877
    }
878
879
    impl Store for Racing {
8804×
        fn describe(&self) -> String {
8814×
            "racing".into()
8824×
        }
8830×
        fn has(&self, key: &str) -> crate::strata::Result<bool> {
8840×
            self.inner.has(key)
8850×
        }
8865×
        fn get(&self, key: &str) -> crate::strata::Result<Vec<u8>> {
8875×
            self.inner.get(key)
8885×
        }
8890×
        fn get_range(&self, key: &str, range: Range<u64>) -> crate::strata::Result<Vec<u8>> {
8900×
            self.inner.get_range(key, range)
8910×
        }
8923×
        fn put_new(&self, key: &str, bytes: &[u8]) -> crate::strata::Result<()> {
8933×
            self.inner.put_new(key, bytes)
8943×
        }
8956×
        fn list(&self, prefix: &str) -> crate::strata::Result<Vec<Entry>> {
8966×
            self.inner.list(prefix)
8976×
        }
8980×
        fn delete(&self, key: &str) -> crate::strata::Result<()> {
8990×
            self.inner.delete(key)
9000×
        }
9014×
        fn read_ref(&self, key: &str) -> crate::strata::Result<Option<(Vec<u8>, Version)>> {
9024×
            self.inner.read_ref(key)
9034×
        }
9043×
        fn write_ref(
9053×
            &self,
9063×
            key: &str,
9073×
            bytes: &[u8],
9083×
            expected: Option<&Version>,
9093×
        ) -> crate::strata::Result<Version> {
9103×
            let mut raced = self.raced.lock().unwrap();
9113×
            if !*raced && expected.is_some() {
9121×
                *raced = true;
913
                // Someone else lands a record: the same references with a
914
                // different detail, so the version moves.
9151×
                let (current, v) = self.inner.read_ref(key)?.unwrap();
9161×
                let (id, mut resp) =
9171×
                    wire::decode_refs(&current).map_err(|e| StoreError::Backend(e.to_string()))?;
9181×
                resp.default_bookmark = Some("raced".into());
9191×
                self.inner
9201×
                    .write_ref(key, &wire::encode_refs(id, &resp), Some(&v))?;
9212×
            }
9223×
            self.inner.write_ref(key, bytes, expected)
9233×
        }
924
    }
925
926
    #[test]
9271×
    fn a_record_moved_during_a_push_is_applied_over_what_landed() {
9281×
        hermetic();
9291×
        let dir = tempfile::tempdir().unwrap();
9301×
        let root = dir.path();
9311×
        let a = Repo::init(&root.join("a")).unwrap();
9321×
        write(&root.join("a"), "f.txt", b"a\n");
9331×
        let h1 = a.commit("first", &[]).unwrap();
9341×
        let store = Box::new(Racing {
9351×
            inner: MemoryStore::new(),
9361×
            raced: Mutex::new(false),
9371×
        });
9381×
        let options = RemoteOptions {
9391×
            repo_id: Some(a.id().unwrap()),
9401×
            cache_dir: Some(root.join("cache")),
9411×
            ..Default::default()
9421×
        };
9431×
        let remote = BucketRemote::open(store, &options).unwrap();
944
        // The first push creates the record (expected None: no race yet).
9451×
        let state = a.store.put_state(&StateObject::new(vec![h1])).unwrap();
9461×
        let empty = a.store.put_state(&StateObject::new(vec![])).unwrap();
9471×
        let mut bundle = a.bundle_for(&[h1]).unwrap();
9481×
        bundle
9491×
            .objects
9501×
            .push((ObjectType::State, StateObject::new(vec![h1]).encode()));
9511×
        let update = |old, new| RefUpdate {
9522×
            name: "main".into(),
9532×
            old_state: old,
9542×
            new_state: new,
955
            force: false,
9562×
            attestation: None,
9572×
        };
9581×
        let r = remote
9591×
            .push(bundle, vec![update(empty, state)], None, vec![])
9601×
            .unwrap();
9611×
        assert!(r[0].ok, "{r:?}");
962
        // The second push meets the race: refused, nothing moved.
9631×
        write(&root.join("a"), "f.txt", b"ab\n");
9641×
        let h2 = a.commit("second", &[]).unwrap();
9651×
        let state2 = a.store.put_state(&StateObject::new(vec![h2])).unwrap();
9661×
        let mut bundle = a.bundle_for(&[h2]).unwrap();
9671×
        bundle
9681×
            .objects
9691×
            .push((ObjectType::State, StateObject::new(vec![h2]).encode()));
9701×
        let r = remote
9711×
            .push(bundle, vec![update(state, state2)], None, vec![])
9721×
            .unwrap();
9731×
        assert!(r[0].ok, "applied over what landed meanwhile: {r:?}");
9741×
        let refs = remote.refs().unwrap();
9751×
        assert_eq!(
9761×
            refs.refs[0].heads,
9771×
            vec![h2],
978
            "the store and the mirror both moved"
979
        );
9801×
    }
981
982
    #[test]
9831×
    fn a_store_holds_one_repository() {
9841×
        hermetic();
9851×
        let dir = tempfile::tempdir().unwrap();
9861×
        let root = dir.path();
9871×
        let url = format!("dir://{}", root.join("bucket").display());
9881×
        let mut a = Repo::init(&root.join("a")).unwrap();
9891×
        add_remote(&mut a, "bucket", &url);
9901×
        write(&root.join("a"), "f.txt", b"a\n");
9911×
        a.commit("first", &[]).unwrap();
9921×
        assert!(a.push("bucket", false).unwrap()[0].ok);
9931×
        let mut other = Repo::init(&root.join("other")).unwrap();
9941×
        add_remote(&mut other, "bucket", &url);
9951×
        write(&root.join("other"), "f.txt", b"o\n");
9961×
        other.commit("mine", &[]).unwrap();
9971×
        let e = other.push("bucket", false).unwrap_err().to_string();
9981×
        assert!(
9991×
            e.contains("different repository") || e.contains("another repository"),
1000
            "{e}"
1001
        );
10021×
        assert_eq!(
10031×
            keys(&LocalStore::open(root.join("bucket")).unwrap(), "bundles/").len(),
1004
            1
1005
        );
10061×
    }
1007
1008
    #[test]
10091×
    fn a_damaged_bundle_is_caught_and_an_empty_store_cannot_be_cloned() {
10101×
        hermetic();
10111×
        let dir = tempfile::tempdir().unwrap();
10121×
        let root = dir.path();
10131×
        let url = format!("dir://{}", root.join("bucket").display());
10141×
        let e = Repo::clone(&url, &root.join("nothing"))
10151×
            .err()
10161×
            .expect("refused")
10171×
            .to_string();
10181×
        assert!(e.contains("empty and unbound"), "{e}");
10191×
        let mut a = Repo::init(&root.join("a")).unwrap();
10201×
        add_remote(&mut a, "bucket", &url);
10211×
        write(&root.join("a"), "f.txt", b"a\n");
10221×
        a.commit("first", &[]).unwrap();
10231×
        assert!(a.push("bucket", false).unwrap()[0].ok);
10241×
        let store = LocalStore::open(root.join("bucket")).unwrap();
10251×
        let key = keys(&store, "bundles/").remove(0);
10261×
        let mut bytes = store.get(&key).unwrap();
10271×
        let mid = bytes.len() / 2;
10281×
        bytes[mid] ^= 0xff;
10291×
        store.delete(&key).unwrap();
10301×
        store.put_new(&key, &bytes).unwrap();
10311×
        let e = Repo::clone(&url, &root.join("b"))
10321×
            .err()
10331×
            .expect("refused")
10341×
            .to_string();
10351×
        assert!(
10361×
            e.contains(&key) || e.contains("bundle") || e.contains("hash"),
1037
            "{e}"
1038
        );
10391×
        assert!(!root.join("b/f.txt").exists());
10401×
    }
1041
1042
    /// A store shared by two remotes in one test, with a hook run once at
1043
    /// the first conditional write: what another push landing between a
1044
    /// read of the record and its compare-and-swap looks like.
1045
    struct Shared {
1046
        inner: std::sync::Arc<MemoryStore>,
1047
        fail_uploads: std::sync::atomic::AtomicBool,
1048
        vanish: Mutex<Option<String>>,
1049
    }
1050
1051
    thread_local! {
1052
        static HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
1053
    }
1054
1055
    impl Shared {
10566×
        fn new(inner: std::sync::Arc<MemoryStore>) -> Box<Shared> {
10576×
            Box::new(Shared {
10586×
                inner,
10596×
                fail_uploads: Default::default(),
10606×
                vanish: Mutex::new(None),
10616×
            })
10626×
        }
1063
    }
1064
1065
    impl Store for Shared {
106624×
        fn describe(&self) -> String {
106724×
            "shared".into()
106824×
        }
10690×
        fn has(&self, key: &str) -> crate::strata::Result<bool> {
10700×
            self.inner.has(key)
10710×
        }
107238×
        fn get(&self, key: &str) -> crate::strata::Result<Vec<u8>> {
107338×
            let mut vanish = self.vanish.lock().unwrap();
107438×
            if vanish.as_deref() == Some(key) {
10751×
                *vanish = None;
10761×
                return Err(StoreError::NotFound(key.to_string()));
107737×
            }
107837×
            self.inner.get(key)
107938×
        }
10800×
        fn get_range(&self, key: &str, range: Range<u64>) -> crate::strata::Result<Vec<u8>> {
10810×
            self.inner.get_range(key, range)
10820×
        }
108311×
        fn put_new(&self, key: &str, bytes: &[u8]) -> crate::strata::Result<()> {
108411×
            if key.starts_with("bundles/")
10858×
                && self.fail_uploads.load(std::sync::atomic::Ordering::SeqCst)
1086
            {
10871×
                return Err(StoreError::Backend("shared: the disk is full".into()));
108810×
            }
108910×
            self.inner.put_new(key, bytes)
109011×
        }
109131×
        fn list(&self, prefix: &str) -> crate::strata::Result<Vec<Entry>> {
109231×
            self.inner.list(prefix)
109331×
        }
10940×
        fn delete(&self, key: &str) -> crate::strata::Result<()> {
10950×
            self.inner.delete(key)
10960×
        }
109723×
        fn read_ref(&self, key: &str) -> crate::strata::Result<Option<(Vec<u8>, Version)>> {
109823×
            self.inner.read_ref(key)
109923×
        }
11008×
        fn write_ref(
11018×
            &self,
11028×
            key: &str,
11038×
            bytes: &[u8],
11048×
            expected: Option<&Version>,
11058×
        ) -> crate::strata::Result<Version> {
11068×
            if key == "refs" && expected.is_some() {
11075×
                if let Some(hook) = HOOK.with(|h| h.borrow_mut().take()) {
11081×
                    hook();
11094×
                }
11103×
            }
11118×
            self.inner.write_ref(key, bytes, expected)
11128×
        }
1113
    }
1114
11153×
    fn repo_with_commit(root: &Path, name: &str, file: &str, text: &[u8], msg: &str) -> Repo {
11163×
        let repo = Repo::init(&root.join(name)).unwrap();
11173×
        write(&root.join(name), file, text);
11183×
        repo.commit(msg, &[]).unwrap();
11193×
        repo
11203×
    }
1121
11226×
    fn remote_for(repo: &Repo, store: Box<dyn Store>, root: &Path, name: &str) -> BucketRemote {
11236×
        let options = RemoteOptions {
11246×
            repo_id: Some(repo.id().unwrap()),
11256×
            cache_dir: Some(root.join(format!("cache-{name}"))),
11266×
            ..Default::default()
11276×
        };
11286×
        BucketRemote::open(store, &options).unwrap()
11296×
    }
1130
11318×
    fn push_bookmark(
11328×
        repo: &Repo,
11338×
        remote: &BucketRemote,
11348×
        bookmark: &str,
11358×
        old: Option<ObjectRef>,
11368×
    ) -> Vec<RefResult> {
11378×
        let heads = repo.heads_of(&repo.view().unwrap(), bookmark).unwrap();
11388×
        let state = repo
11398×
            .store
11408×
            .put_state(&StateObject::new(heads.clone()))
11418×
            .unwrap();
11428×
        let empty = repo.store.put_state(&StateObject::new(vec![])).unwrap();
1143
        // Only what the remote lacks, as push_bookmark sends.
11448×
        let have: Vec<ChangeHash> = remote
11458×
            .refs()
11468×
            .unwrap()
11478×
            .refs
11488×
            .iter()
11498×
            .flat_map(|r| r.heads.clone())
11508×
            .collect();
11518×
        let changes = repo.negotiate(&have, &heads).unwrap();
11528×
        let mut bundle = repo.bundle_for(&changes).unwrap();
11538×
        bundle
11548×
            .objects
11558×
            .push((ObjectType::State, StateObject::new(heads).encode()));
11568×
        let update = RefUpdate {
11578×
            name: bookmark.into(),
11588×
            old_state: old.unwrap_or(empty),
11598×
            new_state: state,
11608×
            force: false,
11618×
            attestation: None,
11628×
        };
11638×
        remote.push(bundle, vec![update], None, vec![]).unwrap()
11648×
    }
1165
1166
    #[test]
11671×
    fn two_pushes_to_different_bookmarks_both_land() {
11681×
        hermetic();
11691×
        let dir = tempfile::tempdir().unwrap();
11701×
        let root = dir.path();
11711×
        let inner = std::sync::Arc::new(MemoryStore::new());
1172
        // A pushes main; B (a clone of the same repository) pushes a
1173
        // second bookmark between A's read and A's compare-and-swap.
11741×
        let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first");
11751×
        let ra = remote_for(&a, Shared::new(inner.clone()), root, "a");
11761×
        let r = push_bookmark(&a, &ra, "main", None);
11771×
        assert!(r[0].ok, "{r:?}");
11781×
        let b = Repo::init_with_id(&root.join("b"), a.id().unwrap()).unwrap();
11791×
        let rb = remote_for(&b, Shared::new(inner.clone()), root, "b");
11801×
        rb.refs().unwrap();
11811×
        write(&root.join("b"), "g.txt", b"g\n");
11821×
        b.commit("on b", &[]).unwrap();
11831×
        let (_, op) = b.head_op().unwrap();
11841×
        let mut view = op.view.clone();
11851×
        let feature_heads = b.heads_of(&view, "main").unwrap();
11861×
        view.bookmarks.insert(
11871×
            "feature".into(),
11881×
            b.store.put_state(&StateObject::new(feature_heads)).unwrap(),
1189
        );
11901×
        b.record_op(&[b.head_op().unwrap().0], "bookmark create feature", view)
11911×
            .unwrap();
1192
        // A's second push to main; B's push of feature lands in between.
11931×
        write(&root.join("a"), "f.txt", b"aa\n");
11941×
        a.commit("second", &[]).unwrap();
11951×
        let a_old = ra
11961×
            .refs()
11971×
            .unwrap()
11981×
            .refs
11991×
            .iter()
12001×
            .find(|r| r.name == "main")
12011×
            .unwrap()
1202
            .state;
12031×
        let b_remote = std::sync::Arc::new(std::sync::Mutex::new(Some(rb)));
12041×
        let b_handle = b_remote.clone();
12051×
        HOOK.with(|h| {
12061×
            *h.borrow_mut() = Some(Box::new(move || {
12071×
                let rb = b_handle.lock().unwrap().take().unwrap();
12081×
                let r = push_bookmark(&b, &rb, "feature", None);
12091×
                assert!(r[0].ok, "{r:?}");
12101×
            }))
12111×
        });
12121×
        let r = push_bookmark(&a, &ra, "main", Some(a_old));
12131×
        assert!(r[0].ok, "a's push is applied over b's: {r:?}");
12141×
        let refs = ra.refs().unwrap();
12152×
        let names: Vec<&str> = refs.refs.iter().map(|r| r.name.as_str()).collect();
12161×
        assert_eq!(names, ["feature", "main"], "both landed");
12171×
        assert_eq!(inner.list("bundles/").unwrap().len(), 3);
12181×
        let _ = b_remote;
12191×
    }
1220
1221
    #[test]
12221×
    fn an_interrupted_push_leaves_the_store_usable() {
12231×
        hermetic();
12241×
        let dir = tempfile::tempdir().unwrap();
12251×
        let root = dir.path();
12261×
        let inner = std::sync::Arc::new(MemoryStore::new());
12271×
        let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first");
12281×
        let shared = Shared::new(inner.clone());
12291×
        let fail = &shared.fail_uploads as *const std::sync::atomic::AtomicBool;
12301×
        let ra = remote_for(&a, shared, root, "a");
12311×
        assert!(push_bookmark(&a, &ra, "main", None)[0].ok);
12321×
        let old = ra.refs().unwrap().refs[0].state;
1233
        // The upload fails: nothing in the store changes, the mirror is
1234
        // honest, and the next push gets through.
12351×
        write(&root.join("a"), "f.txt", b"aa\n");
12361×
        let h2 = a.commit("second", &[]).unwrap();
12371×
        unsafe { (*fail).store(true, std::sync::atomic::Ordering::SeqCst) };
12381×
        let e = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
12391×
            push_bookmark(&a, &ra, "main", Some(old))
12401×
        }));
12411×
        assert!(e.is_err(), "the push reports the failed upload");
12421×
        assert_eq!(inner.list("bundles/").unwrap().len(), 1);
12431×
        let refs = ra.refs().unwrap();
12441×
        assert_eq!(refs.refs[0].state, old, "the record did not move");
12451×
        unsafe { (*fail).store(false, std::sync::atomic::Ordering::SeqCst) };
12461×
        let r = push_bookmark(&a, &ra, "main", Some(old));
12471×
        assert!(r[0].ok, "{r:?}");
12481×
        assert_eq!(ra.refs().unwrap().refs[0].heads, vec![h2]);
12491×
    }
1250
1251
    #[test]
12521×
    fn bundles_out_of_order_or_gone_are_handled() {
12531×
        hermetic();
12541×
        let dir = tempfile::tempdir().unwrap();
12551×
        let root = dir.path();
12561×
        let inner = std::sync::Arc::new(MemoryStore::new());
12571×
        let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first");
12581×
        let ra = remote_for(&a, Shared::new(inner.clone()), root, "a");
12591×
        assert!(push_bookmark(&a, &ra, "main", None)[0].ok);
12601×
        let old = ra.refs().unwrap().refs[0].state;
12611×
        write(&root.join("a"), "f.txt", b"aa\n");
12621×
        let h2 = a.commit("second", &[]).unwrap();
12631×
        assert!(push_bookmark(&a, &ra, "main", Some(old))[0].ok);
1264
        // The second bundle (which needs the first) renamed to sort first.
12651×
        let keys: Vec<String> = inner
12661×
            .list("bundles/")
12671×
            .unwrap()
12681×
            .into_iter()
12691×
            .map(|e| e.key)
12701×
            .collect();
12711×
        assert_eq!(keys.len(), 2);
12721×
        let bytes = inner.get(&keys[1]).unwrap();
12731×
        inner.delete(&keys[1]).unwrap();
12741×
        inner
12751×
            .put_new("bundles/00000000-first.bundle", &bytes)
12761×
            .unwrap();
12771×
        let shared = Shared::new(inner.clone());
12781×
        let c = Repo::init_with_id(&root.join("c"), a.id().unwrap()).unwrap();
12791×
        let rc = remote_for(&c, shared, root, "c");
12801×
        assert_eq!(
12811×
            rc.refs().unwrap().refs[0].heads,
12821×
            vec![h2],
1283
            "the dependent bundle waited for its dependency"
1284
        );
1285
        // A bundle gone between the listing and the read is skipped.
12861×
        let shared = Shared::new(inner.clone());
12871×
        *shared.vanish.lock().unwrap() = Some(keys[0].clone());
12881×
        let d = Repo::init_with_id(&root.join("d"), a.id().unwrap()).unwrap();
12891×
        let rd = remote_for(&d, shared, root, "d");
1290
        // Without the first bundle the second cannot be imported: the sync
1291
        // says so rather than failing silently.
12921×
        let e = rd.refs().expect_err("missing changes").to_string();
12931×
        assert!(e.contains("cannot be imported"), "{e}");
12941×
    }
1295
1296
    #[test]
12971×
    fn gc_merges_bundles_and_prunes_after_the_grace_period() {
12981×
        hermetic();
12991×
        let dir = tempfile::tempdir().unwrap();
13001×
        let root = dir.path();
13011×
        let url = format!("dir://{}", root.join("bucket").display());
13021×
        let store = LocalStore::open(root.join("bucket")).unwrap();
13031×
        let mut a = Repo::init(&root.join("a")).unwrap();
13041×
        add_remote(&mut a, "bucket", &url);
13053×
        for i in 1..=3 {
13063×
            write(&root.join("a"), "f.txt", format!("{i}\n").as_bytes());
13073×
            a.commit(&format!("change {i}"), &[]).unwrap();
13083×
            assert!(a.push("bucket", false).unwrap()[0].ok);
1309
        }
13101×
        a.tag_create("v3", &a.bookmark_heads().unwrap(), "three")
13111×
            .unwrap();
13121×
        assert!(a.push("bucket", false).unwrap().iter().all(|r| r.ok));
13131×
        assert_eq!(
13141×
            keys(&store, "bundles/").len(),
1315
            4,
1316
            "three pushes and the tag's"
1317
        );
1318
        // A gc folds the four into one; the old ones wait out the grace.
13191×
        let r = a.gc_remote("bucket", false).unwrap();
13201×
        assert_eq!(
13211×
            (r.merged, r.changes, r.deleted, r.deferred),
1322
            (4, 3, 0, 4),
1323
            "{r:?}"
1324
        );
13251×
        assert!(r.bundle_bytes > 0);
13261×
        assert_eq!(keys(&store, "bundles/").len(), 5);
13271×
        let b = Repo::clone(&url, &root.join("b")).unwrap();
13281×
        assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"3\n");
13291×
        assert_eq!(b.tags().unwrap().len(), 1);
1330
        // Past the grace period they go, and a clone needs only the one.
13311×
        let r = a.gc_remote("bucket", true).unwrap();
13321×
        assert_eq!((r.merged, r.deleted, r.deferred), (0, 4, 0), "{r:?}");
13331×
        assert_eq!(keys(&store, "bundles/").len(), 1);
13341×
        let c = Repo::clone(&url, &root.join("c")).unwrap();
13351×
        assert_eq!(c.bookmark_heads().unwrap(), a.bookmark_heads().unwrap());
1336
        // The earlier clone, which saw the old bundles, carries on.
13371×
        write(&root.join("b"), "f.txt", b"4\n");
13381×
        b.commit("four", &[]).unwrap();
13391×
        assert!(b.push("origin", false).unwrap()[0].ok);
13401×
        assert!(a.pull("bucket").unwrap().changed);
13411×
        assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"4\n");
1342
        // Nothing more to merge: a second gc is a no-op.
13431×
        let r = a.gc_remote("bucket", true).unwrap();
13441×
        assert_eq!((r.merged, r.deleted), (2, 2));
13451×
        assert!(a.gc_remote("nope", true).is_err());
13461×
    }
1347
1348
    #[test]
13491×
    fn markers_parse_and_refuse_newer_formats() {
13501×
        let id = [7u8; 16];
13511×
        assert_eq!(parse_marker(&marker(id), "s").unwrap(), id);
13521×
        let e = parse_marker(
13531×
            b"format = 9\nrepo = \"07070707070707070707070707070707\"\n",
13541×
            "s",
13551×
        )
13561×
        .unwrap_err()
13571×
        .to_string();
13581×
        assert!(e.contains("format 9"), "{e}");
13591×
        assert!(parse_marker(b"hello", "s").is_err());
13601×
    }
1361
}