OXYGENHUB
◆ v0.5.1 oxygen / crates / oxy-core / src / repo / strata.rs
51.7 KiB · Rust · last changed Keyless agents create release tags: receive and fetch authorize certified tag keys 16 days ago source blame history raw
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 {
47
    fn from(e: StoreError) -> RepoError {
48
        RepoError::Msg(e.to_string())
49
    }
50
}
51
52
/// The `oxygen.toml` marker: two lines, written once.
53
fn marker(id: [u8; 16]) -> Vec<u8> {
54
    format!("format = {FORMAT}\nrepo = \"{}\"\n", hex::encode(id)).into_bytes()
55
}
56
57
fn parse_marker(bytes: &[u8], what: &str) -> Result<[u8; 16]> {
58
    let text = String::from_utf8_lossy(bytes);
59
    let mut format = None;
60
    let mut repo = None;
61
    for line in text.lines() {
62
        let Some((k, v)) = line.split_once('=') else {
63
            continue;
64
        };
65
        let v = v.trim().trim_matches('"');
66
        match k.trim() {
67
            "format" => format = v.parse::<u32>().ok(),
68
            "repo" => {
69
                repo = hex::decode(v)
70
                    .ok()
71
                    .and_then(|b| <[u8; 16]>::try_from(b).ok())
72
            }
73
            _ => {}
74
        }
75
    }
76
    match (format, repo) {
77
        (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
        )),
80
        (Some(_), Some(id)) => Ok(id),
81
        _ => fail(format!("{what}: its oxygen.toml is not a Strata marker")),
82
    }
83
}
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 {
98
    fn drop(&mut self) {
99
        if self.temporary {
100
            let _ = fs::remove_dir_all(&self.dir);
101
        }
102
    }
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 {
113
    pub fn open(store: Box<dyn Store>, options: &RemoteOptions) -> Result<BucketRemote> {
114
        let (dir, temporary) = match &options.cache_dir {
115
            Some(d) => (d.clone(), false),
116
            None => {
117
                let mut nonce = [0u8; 6];
118
                rand::RngCore::fill_bytes(&mut rand::rngs::OsRng, &mut nonce);
119
                (
120
                    std::env::temp_dir().join(format!(
121
                        "oxy-strata-{}-{}",
122
                        std::process::id(),
123
                        hex::encode(nonce)
124
                    )),
125
                    true,
126
                )
127
            }
128
        };
129
        Ok(BucketRemote {
130
            store,
131
            dir,
132
            temporary,
133
            claimed_id: options.repo_id,
134
            mirror: RefCell::new(None),
135
        })
136
    }
137
138
    fn what(&self) -> String {
139
        self.store.describe()
140
    }
141
142
    /// The repository id the store holds: `None` until a first push.
143
    fn stored_id(&self) -> Result<Option<[u8; 16]>> {
144
        match self.store.get(MARKER_KEY) {
145
            Ok(b) => Ok(Some(parse_marker(&b, &self.what())?)),
146
            Err(StoreError::NotFound(_)) => Ok(None),
147
            Err(e) => Err(e.into()),
148
        }
149
    }
150
151
    fn mirror_dir(&self) -> PathBuf {
152
        self.dir.join("mirror")
153
    }
154
155
    fn seen_path(&self) -> PathBuf {
156
        self.dir.join("seen")
157
    }
158
159
    /// The bundles already imported into the mirror.
160
    fn seen(&self) -> BTreeSet<String> {
161
        fs::read_to_string(self.seen_path())
162
            .map(|s| s.lines().map(str::to_string).collect())
163
            .unwrap_or_default()
164
    }
165
166
    fn mark_seen(&self, key: &str) -> Result<()> {
167
        let mut seen = self.seen();
168
        if seen.insert(key.to_string()) {
169
            let text: String = seen.iter().map(|k| format!("{k}\n")).collect();
170
            crate::durable::write_atomic(&self.seen_path(), text.as_bytes())?;
171
        }
172
        Ok(())
173
    }
174
175
    /// Open the mirror for repository `id`, creating it on first use.
176
    fn open_mirror(&self, id: [u8; 16]) -> Result<()> {
177
        if self.mirror.borrow().is_some() {
178
            return Ok(());
179
        }
180
        let dir = self.mirror_dir();
181
        let repo = if dir.join(super::OXY_DIR).is_dir() {
182
            let repo = Repo::open(&dir)?;
183
            if repo.id()? != id {
184
                // The store was emptied and reused for another repository:
185
                // start the mirror over.
186
                drop(repo);
187
                fs::remove_dir_all(&self.dir)?;
188
                fs::create_dir_all(&self.dir)?;
189
                Repo::init_bare_with_id(&dir, id)?
190
            } else {
191
                repo
192
            }
193
        } else {
194
            fs::create_dir_all(&self.dir)?;
195
            Repo::init_bare_with_id(&dir, id)?
196
        };
197
        *self.mirror.borrow_mut() = Some(repo);
198
        Ok(())
199
    }
200
201
    fn with_mirror<T>(&self, f: impl FnOnce(&Repo) -> Result<T>) -> Result<T> {
202
        let m = self.mirror.borrow();
203
        match m.as_ref() {
204
            Some(repo) => f(repo),
205
            None => fail(format!(
206
                "{} holds no repository yet: push one to it first",
207
                self.what()
208
            )),
209
        }
210
    }
211
212
    /// Bring the mirror level with the store.
213
    fn sync(&self) -> Result<Synced> {
214
        let Some(id) = self.stored_id()? else {
215
            return Ok(Synced {
216
                version: None,
217
                id: None,
218
            });
219
        };
220
        self.open_mirror(id)?;
221
        let record = self.store.read_ref(REFS_KEY)?;
222
        let (resp, version) = match record {
223
            Some((bytes, version)) => {
224
                let (rid, resp) = wire::decode_refs(&bytes)?;
225
                if rid != id {
226
                    return fail(format!(
227
                        "{}: its refs record names a different repository than its oxygen.toml; the store is damaged",
228
                        self.what()
229
                    ));
230
                }
231
                (resp, Some(version))
232
            }
233
            None => (RefsResponse::default(), None),
234
        };
235
        self.with_mirror(|mirror| {
236
            // Another process may have brought the mirror level since this
237
            // handle read its head.
238
            mirror.refresh()?;
239
            // The policy first: bundles are then imported under it.
240
            if let Some(sp) = &resp.policy {
241
                let have = mirror.current_policy()?.map(|(_, p)| p.policy.serial);
242
                if have.is_none_or(|s| s < sp.policy.serial) {
243
                    mirror
244
                        .adopt_policy_chain(&resp.history, sp, "strata sync")
245
                        .map_err(|e| RepoError::Msg(format!("policy from {}: {e}", self.what())))?;
246
                }
247
            }
248
            self.import_new_bundles(mirror)?;
249
            self.set_view(mirror, &resp)?;
250
            Ok(())
251
        })?;
252
        Ok(Synced {
253
            version,
254
            id: Some(id),
255
        })
256
    }
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.
262
    fn import_new_bundles(&self, mirror: &Repo) -> Result<()> {
263
        let seen = self.seen();
264
        let mut pending: Vec<String> = self
265
            .store
266
            .list(BUNDLES_PREFIX)?
267
            .into_iter()
268
            .map(|e| e.key)
269
            .filter(|k| !seen.contains(k))
270
            .collect();
271
        let strict = mirror.current_policy()?.is_some();
272
        while !pending.is_empty() {
273
            let mut deferred = Vec::new();
274
            let mut last_error = None;
275
            let before = pending.len();
276
            for key in pending.drain(..) {
277
                let bytes = match self.store.get(&key) {
278
                    Ok(b) => b,
279
                    // Listed, then gone: a gc merged it into a newer
280
                    // bundle, which this listing holds too.
281
                    Err(StoreError::NotFound(_)) => continue,
282
                    Err(e) => return Err(e.into()),
283
                };
284
                let bundle = wire::decode_bundle(&bytes)
285
                    .map_err(|e| RepoError::Msg(format!("{}: {key}: {e}", self.what())))?;
286
                match mirror.import_bundle(&bundle, strict) {
287
                    Ok(_) => self.mark_seen(&key)?,
288
                    Err(RepoError::Msg(m)) if m.contains("neither stored nor in the bundle") => {
289
                        last_error = Some(m);
290
                        deferred.push(key);
291
                    }
292
                    Err(e) => return Err(RepoError::Msg(format!("{}: {key}: {e}", self.what()))),
293
                }
294
            }
295
            if deferred.len() == before {
296
                // No progress: something those bundles need was never
297
                // pushed, or a push is still in progress.
298
                return fail(format!(
299
                    "{}: {} cannot be imported ({}); a push may be in progress, so try again, else the store is missing changes",
300
                    self.what(),
301
                    deferred.join(", "),
302
                    last_error.unwrap_or_default()
303
                ));
304
            }
305
            pending = deferred;
306
        }
307
        Ok(())
308
    }
309
310
    /// Make the mirror's view say what the record says.
311
    fn set_view(&self, mirror: &Repo, resp: &RefsResponse) -> Result<()> {
312
        let (op_ref, op) = mirror.head_op()?;
313
        let mut view = op.view.clone();
314
        view.bookmarks.clear();
315
        for r in &resp.refs {
316
            for h in &r.heads {
317
                if !mirror.store.has(h) {
318
                    return fail(format!(
319
                        "{}: bookmark {:?} names change {}, which no bundle there holds; a push may be in progress, so try again",
320
                        self.what(),
321
                        r.name,
322
                        h.short(12)
323
                    ));
324
                }
325
            }
326
            let state = mirror.store.put_state(&StateObject::new(r.heads.clone()))?;
327
            if state != r.state {
328
                return fail(format!(
329
                    "{}: bookmark {:?} names a state that does not match its heads; the store is damaged",
330
                    self.what(),
331
                    r.name
332
                ));
333
            }
334
            if let Some(sa) = &r.attestation {
335
                let current = mirror.latest_ref_attest(&r.name)?.map(|(_, a)| a);
336
                if current.as_ref() != Some(sa) {
337
                    let a = mirror.store.put_attest(&sa.attest)?;
338
                    for sig in &sa.sigs {
339
                        mirror.store.put_signature(&a, sig)?;
340
                    }
341
                    mirror.set_ref_attest(&r.name, &a)?;
342
                }
343
            }
344
            view.bookmarks.insert(r.name.clone(), state);
345
        }
346
        let policy = mirror.current_policy()?.map(|(_, sp)| sp.policy);
347
        for t in &resp.tags {
348
            mirror.store.put_state(&StateObject::new(t.heads.clone()))?;
349
            mirror
350
                .adopt_tag(
351
                    &mut view,
352
                    t,
353
                    policy.as_ref(),
354
                    &mut super::tags::TagCheck::Mirrored,
355
                )
356
                .map_err(|e| RepoError::Msg(format!("{}: {}", self.what(), e.reason)))?;
357
        }
358
        if view != op.view {
359
            mirror.record_op(&[op_ref], "strata sync", view)?;
360
        }
361
        Ok(())
362
    }
363
364
    /// The record for the mirror's current references.
365
    fn record(&self, id: [u8; 16]) -> Result<Vec<u8>> {
366
        self.with_mirror(|mirror| {
367
            let mut resp = mirror.remote_refs()?;
368
            // A mirror has no checkout; the store's clone picks a bookmark
369
            // as any other remote's does.
370
            resp.default_bookmark = None;
371
            Ok(wire::encode_refs(id, &resp))
372
        })
373
    }
374
375
    /// Store a bundle under the next sequence number; returns its key.
376
    fn upload(&self, bundle: &Bundle) -> Result<String> {
377
        let bytes = wire::encode_bundle(bundle);
378
        let hash = blake3::hash(&bytes).to_hex();
379
        let seq = self.store.list(BUNDLES_PREFIX)?.len() + 1;
380
        let key = format!("{BUNDLES_PREFIX}{seq:08}-{}.bundle", &hash[..16]);
381
        match self.store.put_new(&key, &bytes) {
382
            Ok(()) | Err(StoreError::Exists(_)) => {}
383
            Err(e) => return Err(e.into()),
384
        }
385
        self.mark_seen(&key)?;
386
        Ok(key)
387
    }
388
}
389
390
impl Remote for BucketRemote {
391
    fn repo_id(&self) -> Result<[u8; 16]> {
392
        Ok(self.stored_id()?.unwrap_or(UNBOUND_ID))
393
    }
394
395
    fn refs(&self) -> Result<RefsResponse> {
396
        let synced = self.sync()?;
397
        if synced.id.is_none() {
398
            return Ok(RefsResponse::default());
399
        }
400
        self.with_mirror(|mirror| {
401
            let mut resp = mirror.remote_refs()?;
402
            resp.default_bookmark = None;
403
            Ok(resp)
404
        })
405
    }
406
407
    fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
408
        self.with_mirror(|m| m.negotiate(have, want))
409
    }
410
411
    fn fetch(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
412
        self.with_mirror(|m| m.bundle_raw_for(changes, max_blob))
413
    }
414
415
    fn objects(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
416
        self.with_mirror(|m| m.objects_for(refs))
417
    }
418
419
    fn checkpoint(&self, heads: &[ChangeHash]) -> Result<Bundle> {
420
        self.with_mirror(|m| m.checkpoint_bundle_for(heads))
421
    }
422
423
    fn shallow(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
424
        self.with_mirror(|m| m.shallow_changes(heads, depth))
425
    }
426
427
    fn push(
428
        &self,
429
        bundle: Bundle,
430
        updates: Vec<RefUpdate>,
431
        policy: Option<SignedPolicy>,
432
        tags: Vec<TagRef>,
433
    ) -> Result<Vec<RefResult>> {
434
        let mut synced = self.sync()?;
435
        let id = match synced.id {
436
            Some(id) => id,
437
            None => {
438
                // The first push binds the store to this repository. Two
439
                // first pushes race on the marker; the loser reads the
440
                // winner's and goes on only if it is the same repository.
441
                let Some(id) = self.claimed_id else {
442
                    return fail(format!(
443
                        "{} is empty, and this client did not say which repository it is",
444
                        self.what()
445
                    ));
446
                };
447
                match self.store.put_new(MARKER_KEY, &marker(id)) {
448
                    Ok(()) => {}
449
                    Err(StoreError::Exists(_)) => {}
450
                    Err(e) => return Err(e.into()),
451
                }
452
                synced = self.sync()?;
453
                match synced.id {
454
                    Some(stored) if stored == id => id,
455
                    _ => {
456
                        return fail(format!(
457
                            "{} was just bound to another repository by a concurrent push",
458
                            self.what()
459
                        ))
460
                    }
461
                }
462
            }
463
        };
464
        if let Some(claimed) = self.claimed_id {
465
            if claimed != id {
466
                return fail(format!(
467
                    "{} holds a different repository (id {}) than this one ({}): a store holds one repository; use another prefix or bucket",
468
                    self.what(),
469
                    hex::encode(id),
470
                    hex::encode(claimed)
471
                ));
472
            }
473
        }
474
        // The bundle is checked against the mirror and uploaded once; the
475
        // record is then moved from the version read. If it moved
476
        // meanwhile (another push landed), the mirror is put back, brought
477
        // level again, and the updates applied over what landed: two
478
        // pushes to different bookmarks both get through, and one to the
479
        // same bookmark is told it is stale, as a hub would say.
480
        let mut uploaded = false;
481
        for attempt in 0..PUSH_ATTEMPTS {
482
            let (before_ref, before) = self.with_mirror(|m| m.head_op())?;
483
            let results = self.with_mirror(|m| {
484
                m.receive_push(
485
                    bundle.clone(),
486
                    updates.clone(),
487
                    policy.clone(),
488
                    tags.clone(),
489
                )
490
            })?;
491
            if !results.iter().any(|r| r.ok) {
492
                return Ok(results);
493
            }
494
            if !bundle.is_empty() && !uploaded {
495
                self.upload(&bundle)?;
496
                uploaded = true;
497
            }
498
            let record = self.record(id)?;
499
            match self
500
                .store
501
                .write_ref(REFS_KEY, &record, synced.version.as_ref())
502
            {
503
                Ok(_) => return Ok(results),
504
                Err(StoreError::Conflict(_)) => {
505
                    self.with_mirror(|m| {
506
                        let (now, _) = m.head_op()?;
507
                        if now != before_ref {
508
                            m.record_op(
509
                                &[now],
510
                                "strata push undone: the remote moved",
511
                                before.view.clone(),
512
                            )?;
513
                        }
514
                        Ok(())
515
                    })?;
516
                    synced = self.sync()?;
517
                    if attempt + 1 == PUSH_ATTEMPTS {
518
                        return Ok(results
519
                            .into_iter()
520
                            .map(|r| RefResult {
521
                                name: r.name,
522
                                ok: false,
523
                                reason: "the remote kept moving while pushing (other pushes landed first); pull, then push again".into(),
524
                            })
525
                            .collect());
526
                    }
527
                }
528
                Err(e) => return Err(e.into()),
529
            }
530
        }
531
        unreachable!("the loop returns")
532
    }
533
}
534
535
/// How often a push is applied over what landed meanwhile before giving up.
536
const PUSH_ATTEMPTS: usize = 4;
537
538
/// The grace period before `gc` removes a bundle it merged: a reader that
539
/// listed it before the merge can still fetch it.
540
pub const REMOTE_GC_GRACE: std::time::Duration = std::time::Duration::from_secs(7 * 86_400);
541
542
/// Key of the record naming the bundles a gc merged, with when.
543
const TRASH_KEY: &str = "gc";
544
545
/// The superseded bundles and when (milliseconds) each was superseded.
546
type Trash = Vec<(String, u64)>;
547
548
/// What a gc against a store did.
549
#[derive(Clone, Debug, Default, PartialEq, Eq)]
550
pub struct RemoteGc {
551
    /// Bundles folded into one new bundle.
552
    pub merged: usize,
553
    /// The merged bundle's size, bytes.
554
    pub bundle_bytes: usize,
555
    /// Changes in the merged bundle.
556
    pub changes: usize,
557
    /// Superseded bundles removed, past the grace period.
558
    pub deleted: usize,
559
    /// Superseded bundles kept for now by the grace period.
560
    pub deferred: usize,
561
}
562
563
fn now_ms() -> u64 {
564
    std::time::SystemTime::now()
565
        .duration_since(std::time::UNIX_EPOCH)
566
        .map(|d| d.as_millis() as u64)
567
        .unwrap_or(0)
568
}
569
570
impl BucketRemote {
571
    /// The bundles a gc superseded, with when: one `KEY\tMILLIS` per line.
572
    fn trash(&self) -> Result<(Trash, Option<Version>)> {
573
        match self.store.read_ref(TRASH_KEY)? {
574
            Some((bytes, v)) => {
575
                let text = String::from_utf8_lossy(&bytes);
576
                let list = text
577
                    .lines()
578
                    .filter_map(|l| {
579
                        let (k, t) = l.split_once('\t')?;
580
                        Some((k.to_string(), t.parse().ok()?))
581
                    })
582
                    .collect();
583
                Ok((list, Some(v)))
584
            }
585
            None => Ok((Vec::new(), None)),
586
        }
587
    }
588
589
    fn write_trash(&self, list: &[(String, u64)], expected: Option<&Version>) -> Result<Version> {
590
        let text: String = list.iter().map(|(k, t)| format!("{k}\t{t}\n")).collect();
591
        Ok(self.store.write_ref(TRASH_KEY, text.as_bytes(), expected)?)
592
    }
593
594
    /// Fold every bundle into one holding what the record reaches, and
595
    /// remove the bundles that made a gc redundant once `grace` has
596
    /// passed since they were superseded (stores.md §6).
597
    pub fn gc(&self, grace: std::time::Duration) -> Result<RemoteGc> {
598
        let synced = self.sync()?;
599
        let Some(id) = synced.id else {
600
            return fail(format!("{} holds no repository yet", self.what()));
601
        };
602
        let mut report = RemoteGc::default();
603
        let existing: Vec<String> = self
604
            .store
605
            .list(BUNDLES_PREFIX)?
606
            .into_iter()
607
            .map(|e| e.key)
608
            .collect();
609
        let (mut trash, mut trash_version) = self.trash()?;
610
        let live: Vec<&String> = existing
611
            .iter()
612
            .filter(|k| !trash.iter().any(|(t, _)| t == *k))
613
            .collect();
614
        if live.len() > 1 {
615
            // Everything the record reaches, in dependency order, with
616
            // the state objects the bookmarks and tags name.
617
            let (bundle, changes) = self.with_mirror(|m| {
618
                let resp = m.remote_refs()?;
619
                let mut heads: Vec<ChangeHash> = Vec::new();
620
                for r in &resp.refs {
621
                    heads.extend(r.heads.iter().copied());
622
                }
623
                for t in &resp.tags {
624
                    heads.extend(t.heads.iter().copied());
625
                }
626
                heads.sort();
627
                heads.dedup();
628
                let changes = m.negotiate(&[], &heads)?;
629
                let mut bundle = m.bundle_for(&changes)?;
630
                for r in &resp.refs {
631
                    bundle.objects.push((
632
                        ObjectType::State,
633
                        StateObject::new(r.heads.clone()).encode(),
634
                    ));
635
                }
636
                for t in &resp.tags {
637
                    bundle.objects.push((
638
                        ObjectType::State,
639
                        StateObject::new(t.heads.clone()).encode(),
640
                    ));
641
                }
642
                Ok((bundle, changes.len()))
643
            })?;
644
            report.changes = changes;
645
            report.bundle_bytes = wire::encode_bundle(&bundle).len();
646
            let merged_key = self.upload(&bundle)?;
647
            let now = now_ms();
648
            for k in live {
649
                if *k != merged_key {
650
                    trash.push((k.clone(), now));
651
                    report.merged += 1;
652
                }
653
            }
654
            trash_version = Some(self.write_trash(&trash, trash_version.as_ref())?);
655
        }
656
        // What the grace period has released.
657
        let now = now_ms();
658
        let mut kept = Vec::new();
659
        for (k, when) in trash {
660
            if now.saturating_sub(when) >= grace.as_millis() as u64 {
661
                self.store.delete(&k)?;
662
                report.deleted += 1;
663
            } else {
664
                kept.push((k, when));
665
                report.deferred += 1;
666
            }
667
        }
668
        if report.deleted > 0 {
669
            self.write_trash(&kept, trash_version.as_ref())?;
670
        }
671
        let _ = id;
672
        Ok(report)
673
    }
674
}
675
676
impl Repo {
677
    /// `oxy gc --remote NAME`: a gc against a remote kept on a store.
678
    pub fn gc_remote(&self, name: &str, now: bool) -> Result<RemoteGc> {
679
        let Some(url) = self.config.remotes.get(name).cloned() else {
680
            return fail(format!("no remote {name:?}"));
681
        };
682
        let options = self.remote_options(name);
683
        let Some(store) = crate::protocol::open_store(&url, &options) else {
684
            return fail(format!(
685
                "gc --remote works on a remote kept on a store (s3://, gs://, az://, dir://); {name} is {url}"
686
            ));
687
        };
688
        let remote = BucketRemote::open(store?, &options)?;
689
        let grace = if now {
690
            std::time::Duration::ZERO
691
        } else {
692
            REMOTE_GC_GRACE
693
        };
694
        remote.gc(grace)
695
    }
696
}
697
698
/// Open a remote on `store` for the local repository described by `options`.
699
pub fn open_store_remote(
700
    store: Box<dyn Store>,
701
    options: &RemoteOptions,
702
) -> Result<Box<dyn Remote>> {
703
    Ok(Box::new(BucketRemote::open(store, options)?))
704
}
705
706
/// Whether `path` holds a Strata store rather than a repository.
707
pub fn is_store_dir(path: &Path) -> bool {
708
    path.join(MARKER_KEY).is_file() || path.join(REFS_KEY).is_file()
709
}
710
711
#[cfg(test)]
712
mod tests {
713
    use super::*;
714
    use crate::repo::IdentityScope;
715
    use crate::strata::{Entry, LocalStore, MemoryStore};
716
    use std::ops::Range;
717
    use std::sync::Mutex;
718
719
    fn hermetic() {
720
        static ONCE: std::sync::Once = std::sync::Once::new();
721
        static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
722
        ONCE.call_once(|| {
723
            let d = tempfile::tempdir().unwrap();
724
            std::env::set_var("OXY_HOME", d.path());
725
            DIR.set(d).ok();
726
        });
727
    }
728
729
    fn write(root: &Path, rel: &str, content: &[u8]) {
730
        let p = root.join(rel);
731
        fs::create_dir_all(p.parent().unwrap()).unwrap();
732
        fs::write(p, content).unwrap();
733
    }
734
735
    fn add_remote(repo: &mut Repo, name: &str, url: &str) {
736
        repo.config.set(&format!("remote.{name}.url"), url).unwrap();
737
        repo.save_config().unwrap();
738
    }
739
740
    fn keys(store: &dyn Store, prefix: &str) -> Vec<String> {
741
        store
742
            .list(prefix)
743
            .unwrap()
744
            .into_iter()
745
            .map(|e| e.key)
746
            .collect()
747
    }
748
749
    #[test]
750
    fn push_clone_and_pull_through_a_directory_store() {
751
        hermetic();
752
        let dir = tempfile::tempdir().unwrap();
753
        let root = dir.path();
754
        let url = format!("dir://{}", root.join("bucket").display());
755
        let store = LocalStore::open(root.join("bucket")).unwrap();
756
757
        // A signs, commits, tags and pushes: the store gets the marker, one
758
        // bundle, and a record.
759
        let mut a = Repo::init(&root.join("a"))
760
            .unwrap()
761
            .with_home(root.join("home-a"));
762
        a.create_identity("Ada", "[email protected]", IdentityScope::Repo)
763
            .unwrap();
764
        add_remote(&mut a, "bucket", &url);
765
        write(&root.join("a"), "f.txt", b"a\n");
766
        let h1 = a.commit("first", &[]).unwrap();
767
        a.tag_create("v1", &[h1], "one").unwrap();
768
        let results = a.push("bucket", false).unwrap();
769
        assert!(results.iter().all(|r| r.ok), "{results:?}");
770
        assert_eq!(
771
            keys(&store, ""),
772
            [
773
                "bundles/00000001-".to_string() + &keys(&store, "bundles/")[0][17..],
774
                "oxygen.toml".into(),
775
                "refs".into()
776
            ]
777
        );
778
        assert_eq!(
779
            parse_marker(&store.get("oxygen.toml").unwrap(), "t").unwrap(),
780
            a.id().unwrap()
781
        );
782
        let again = a.push("bucket", false).unwrap();
783
        assert!(
784
            again[0].ok && again[0].reason.contains("up to date"),
785
            "{again:?}"
786
        );
787
        assert_eq!(
788
            keys(&store, "bundles/").len(),
789
            1,
790
            "a no-op push uploads nothing"
791
        );
792
793
        // B clones from the store: same id, same file, the tag, and the
794
        // seal on the change.
795
        let b = Repo::clone(&url, &root.join("b")).unwrap();
796
        assert_eq!(b.id().unwrap(), a.id().unwrap());
797
        assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"a\n");
798
        assert_eq!(b.bookmark_heads().unwrap(), vec![h1]);
799
        assert_eq!(
800
            b.tags()
801
                .unwrap()
802
                .iter()
803
                .map(|t| t.name.clone())
804
                .collect::<Vec<_>>(),
805
            ["v1"]
806
        );
807
        assert!(matches!(
808
            b.authenticate_change(&h1).unwrap(),
809
            crate::repo::SignatureStatus::Valid { sealed: true, .. }
810
        ));
811
        assert!(
812
            root.join("b/.oxy/remotes/origin/strata/mirror/.oxy")
813
                .is_dir(),
814
            "the mirror lives with the remote's state"
815
        );
816
        assert!(
817
            !std::env::temp_dir()
818
                .read_dir()
819
                .unwrap()
820
                .flatten()
821
                .any(|e| e.file_name().to_string_lossy().starts_with("oxy-strata-")),
822
            "a clone's temporary mirror is removed"
823
        );
824
825
        // B commits and pushes; A pulls it. A then commits and pushes.
826
        write(&root.join("b"), "f.txt", b"a\nb\n");
827
        let h2 = b.commit("second", &[]).unwrap();
828
        assert!(b.push("origin", false).unwrap()[0].ok);
829
        assert_eq!(keys(&store, "bundles/").len(), 2);
830
        let pr = a.pull("bucket").unwrap();
831
        assert!(pr.changed && pr.checked_out);
832
        assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"a\nb\n");
833
        write(&root.join("a"), "g.txt", b"g\n");
834
        let h3 = a.commit("third", &[]).unwrap();
835
        assert!(a.push("bucket", false).unwrap()[0].ok);
836
        let pr = b.pull("origin").unwrap();
837
        assert!(pr.changed);
838
        // g.txt is new, so its change commutes with B's: two heads.
839
        let mut want = vec![h2, h3];
840
        want.sort();
841
        assert_eq!(b.bookmark_heads().unwrap(), want);
842
        assert_eq!(fs::read(root.join("b/g.txt")).unwrap(), b"g\n");
843
844
        // A third clone gets everything from the three bundles.
845
        let c = Repo::clone(&url, &root.join("c")).unwrap();
846
        assert_eq!(c.bookmark_heads().unwrap(), want);
847
        assert_eq!(fs::read(root.join("c/f.txt")).unwrap(), b"a\nb\n");
848
    }
849
850
    #[test]
851
    fn a_push_behind_the_remote_is_refused_before_anything_is_uploaded() {
852
        hermetic();
853
        let dir = tempfile::tempdir().unwrap();
854
        let root = dir.path();
855
        let url = format!("dir://{}", root.join("bucket").display());
856
        let store = LocalStore::open(root.join("bucket")).unwrap();
857
        let mut a = Repo::init(&root.join("a")).unwrap();
858
        add_remote(&mut a, "bucket", &url);
859
        write(&root.join("a"), "f.txt", b"a\n");
860
        a.commit("first", &[]).unwrap();
861
        assert!(a.push("bucket", false).unwrap()[0].ok);
862
        let b = Repo::clone(&url, &root.join("b")).unwrap();
863
        write(&root.join("b"), "f.txt", b"b\n");
864
        b.commit("from b", &[]).unwrap();
865
        assert!(b.push("origin", false).unwrap()[0].ok);
866
        write(&root.join("a"), "g.txt", b"g\n");
867
        a.commit("from a", &[]).unwrap();
868
        let e = a.push("bucket", false).unwrap_err().to_string();
869
        assert!(e.contains("pull first"), "{e}");
870
        assert_eq!(keys(&store, "bundles/").len(), 2);
871
        assert!(a.pull("bucket").unwrap().changed);
872
        assert!(a.push("bucket", false).unwrap()[0].ok);
873
        assert_eq!(keys(&store, "bundles/").len(), 3);
874
    }
875
876
    /// A store whose record moves under a writer the first time it is
877
    /// written to: what a concurrent push looks like between the read and
878
    /// the compare-and-swap.
879
    struct Racing {
880
        inner: MemoryStore,
881
        raced: Mutex<bool>,
882
    }
883
884
    impl Store for Racing {
885
        fn describe(&self) -> String {
886
            "racing".into()
887
        }
888
        fn has(&self, key: &str) -> crate::strata::Result<bool> {
889
            self.inner.has(key)
890
        }
891
        fn get(&self, key: &str) -> crate::strata::Result<Vec<u8>> {
892
            self.inner.get(key)
893
        }
894
        fn get_range(&self, key: &str, range: Range<u64>) -> crate::strata::Result<Vec<u8>> {
895
            self.inner.get_range(key, range)
896
        }
897
        fn put_new(&self, key: &str, bytes: &[u8]) -> crate::strata::Result<()> {
898
            self.inner.put_new(key, bytes)
899
        }
900
        fn list(&self, prefix: &str) -> crate::strata::Result<Vec<Entry>> {
901
            self.inner.list(prefix)
902
        }
903
        fn delete(&self, key: &str) -> crate::strata::Result<()> {
904
            self.inner.delete(key)
905
        }
906
        fn read_ref(&self, key: &str) -> crate::strata::Result<Option<(Vec<u8>, Version)>> {
907
            self.inner.read_ref(key)
908
        }
909
        fn write_ref(
910
            &self,
911
            key: &str,
912
            bytes: &[u8],
913
            expected: Option<&Version>,
914
        ) -> crate::strata::Result<Version> {
915
            let mut raced = self.raced.lock().unwrap();
916
            if !*raced && expected.is_some() {
917
                *raced = true;
918
                // Someone else lands a record: the same references with a
919
                // different detail, so the version moves.
920
                let (current, v) = self.inner.read_ref(key)?.unwrap();
921
                let (id, mut resp) =
922
                    wire::decode_refs(&current).map_err(|e| StoreError::Backend(e.to_string()))?;
923
                resp.default_bookmark = Some("raced".into());
924
                self.inner
925
                    .write_ref(key, &wire::encode_refs(id, &resp), Some(&v))?;
926
            }
927
            self.inner.write_ref(key, bytes, expected)
928
        }
929
    }
930
931
    #[test]
932
    fn a_record_moved_during_a_push_is_applied_over_what_landed() {
933
        hermetic();
934
        let dir = tempfile::tempdir().unwrap();
935
        let root = dir.path();
936
        let a = Repo::init(&root.join("a")).unwrap();
937
        write(&root.join("a"), "f.txt", b"a\n");
938
        let h1 = a.commit("first", &[]).unwrap();
939
        let store = Box::new(Racing {
940
            inner: MemoryStore::new(),
941
            raced: Mutex::new(false),
942
        });
943
        let options = RemoteOptions {
944
            repo_id: Some(a.id().unwrap()),
945
            cache_dir: Some(root.join("cache")),
946
            ..Default::default()
947
        };
948
        let remote = BucketRemote::open(store, &options).unwrap();
949
        // The first push creates the record (expected None: no race yet).
950
        let state = a.store.put_state(&StateObject::new(vec![h1])).unwrap();
951
        let empty = a.store.put_state(&StateObject::new(vec![])).unwrap();
952
        let mut bundle = a.bundle_for(&[h1]).unwrap();
953
        bundle
954
            .objects
955
            .push((ObjectType::State, StateObject::new(vec![h1]).encode()));
956
        let update = |old, new| RefUpdate {
957
            name: "main".into(),
958
            old_state: old,
959
            new_state: new,
960
            force: false,
961
            attestation: None,
962
        };
963
        let r = remote
964
            .push(bundle, vec![update(empty, state)], None, vec![])
965
            .unwrap();
966
        assert!(r[0].ok, "{r:?}");
967
        // The second push meets the race: refused, nothing moved.
968
        write(&root.join("a"), "f.txt", b"ab\n");
969
        let h2 = a.commit("second", &[]).unwrap();
970
        let state2 = a.store.put_state(&StateObject::new(vec![h2])).unwrap();
971
        let mut bundle = a.bundle_for(&[h2]).unwrap();
972
        bundle
973
            .objects
974
            .push((ObjectType::State, StateObject::new(vec![h2]).encode()));
975
        let r = remote
976
            .push(bundle, vec![update(state, state2)], None, vec![])
977
            .unwrap();
978
        assert!(r[0].ok, "applied over what landed meanwhile: {r:?}");
979
        let refs = remote.refs().unwrap();
980
        assert_eq!(
981
            refs.refs[0].heads,
982
            vec![h2],
983
            "the store and the mirror both moved"
984
        );
985
    }
986
987
    #[test]
988
    fn a_store_holds_one_repository() {
989
        hermetic();
990
        let dir = tempfile::tempdir().unwrap();
991
        let root = dir.path();
992
        let url = format!("dir://{}", root.join("bucket").display());
993
        let mut a = Repo::init(&root.join("a")).unwrap();
994
        add_remote(&mut a, "bucket", &url);
995
        write(&root.join("a"), "f.txt", b"a\n");
996
        a.commit("first", &[]).unwrap();
997
        assert!(a.push("bucket", false).unwrap()[0].ok);
998
        let mut other = Repo::init(&root.join("other")).unwrap();
999
        add_remote(&mut other, "bucket", &url);
1000
        write(&root.join("other"), "f.txt", b"o\n");
1001
        other.commit("mine", &[]).unwrap();
1002
        let e = other.push("bucket", false).unwrap_err().to_string();
1003
        assert!(
1004
            e.contains("different repository") || e.contains("another repository"),
1005
            "{e}"
1006
        );
1007
        assert_eq!(
1008
            keys(&LocalStore::open(root.join("bucket")).unwrap(), "bundles/").len(),
1009
            1
1010
        );
1011
    }
1012
1013
    #[test]
1014
    fn a_damaged_bundle_is_caught_and_an_empty_store_cannot_be_cloned() {
1015
        hermetic();
1016
        let dir = tempfile::tempdir().unwrap();
1017
        let root = dir.path();
1018
        let url = format!("dir://{}", root.join("bucket").display());
1019
        let e = Repo::clone(&url, &root.join("nothing"))
1020
            .err()
1021
            .expect("refused")
1022
            .to_string();
1023
        assert!(e.contains("empty and unbound"), "{e}");
1024
        let mut a = Repo::init(&root.join("a")).unwrap();
1025
        add_remote(&mut a, "bucket", &url);
1026
        write(&root.join("a"), "f.txt", b"a\n");
1027
        a.commit("first", &[]).unwrap();
1028
        assert!(a.push("bucket", false).unwrap()[0].ok);
1029
        let store = LocalStore::open(root.join("bucket")).unwrap();
1030
        let key = keys(&store, "bundles/").remove(0);
1031
        let mut bytes = store.get(&key).unwrap();
1032
        let mid = bytes.len() / 2;
1033
        bytes[mid] ^= 0xff;
1034
        store.delete(&key).unwrap();
1035
        store.put_new(&key, &bytes).unwrap();
1036
        let e = Repo::clone(&url, &root.join("b"))
1037
            .err()
1038
            .expect("refused")
1039
            .to_string();
1040
        assert!(
1041
            e.contains(&key) || e.contains("bundle") || e.contains("hash"),
1042
            "{e}"
1043
        );
1044
        assert!(!root.join("b/f.txt").exists());
1045
    }
1046
1047
    /// A store shared by two remotes in one test, with a hook run once at
1048
    /// the first conditional write: what another push landing between a
1049
    /// read of the record and its compare-and-swap looks like.
1050
    struct Shared {
1051
        inner: std::sync::Arc<MemoryStore>,
1052
        fail_uploads: std::sync::atomic::AtomicBool,
1053
        vanish: Mutex<Option<String>>,
1054
    }
1055
1056
    thread_local! {
1057
        static HOOK: std::cell::RefCell<Option<Box<dyn FnOnce()>>> = const { std::cell::RefCell::new(None) };
1058
    }
1059
1060
    impl Shared {
1061
        fn new(inner: std::sync::Arc<MemoryStore>) -> Box<Shared> {
1062
            Box::new(Shared {
1063
                inner,
1064
                fail_uploads: Default::default(),
1065
                vanish: Mutex::new(None),
1066
            })
1067
        }
1068
    }
1069
1070
    impl Store for Shared {
1071
        fn describe(&self) -> String {
1072
            "shared".into()
1073
        }
1074
        fn has(&self, key: &str) -> crate::strata::Result<bool> {
1075
            self.inner.has(key)
1076
        }
1077
        fn get(&self, key: &str) -> crate::strata::Result<Vec<u8>> {
1078
            let mut vanish = self.vanish.lock().unwrap();
1079
            if vanish.as_deref() == Some(key) {
1080
                *vanish = None;
1081
                return Err(StoreError::NotFound(key.to_string()));
1082
            }
1083
            self.inner.get(key)
1084
        }
1085
        fn get_range(&self, key: &str, range: Range<u64>) -> crate::strata::Result<Vec<u8>> {
1086
            self.inner.get_range(key, range)
1087
        }
1088
        fn put_new(&self, key: &str, bytes: &[u8]) -> crate::strata::Result<()> {
1089
            if key.starts_with("bundles/")
1090
                && self.fail_uploads.load(std::sync::atomic::Ordering::SeqCst)
1091
            {
1092
                return Err(StoreError::Backend("shared: the disk is full".into()));
1093
            }
1094
            self.inner.put_new(key, bytes)
1095
        }
1096
        fn list(&self, prefix: &str) -> crate::strata::Result<Vec<Entry>> {
1097
            self.inner.list(prefix)
1098
        }
1099
        fn delete(&self, key: &str) -> crate::strata::Result<()> {
1100
            self.inner.delete(key)
1101
        }
1102
        fn read_ref(&self, key: &str) -> crate::strata::Result<Option<(Vec<u8>, Version)>> {
1103
            self.inner.read_ref(key)
1104
        }
1105
        fn write_ref(
1106
            &self,
1107
            key: &str,
1108
            bytes: &[u8],
1109
            expected: Option<&Version>,
1110
        ) -> crate::strata::Result<Version> {
1111
            if key == "refs" && expected.is_some() {
1112
                if let Some(hook) = HOOK.with(|h| h.borrow_mut().take()) {
1113
                    hook();
1114
                }
1115
            }
1116
            self.inner.write_ref(key, bytes, expected)
1117
        }
1118
    }
1119
1120
    fn repo_with_commit(root: &Path, name: &str, file: &str, text: &[u8], msg: &str) -> Repo {
1121
        let repo = Repo::init(&root.join(name)).unwrap();
1122
        write(&root.join(name), file, text);
1123
        repo.commit(msg, &[]).unwrap();
1124
        repo
1125
    }
1126
1127
    fn remote_for(repo: &Repo, store: Box<dyn Store>, root: &Path, name: &str) -> BucketRemote {
1128
        let options = RemoteOptions {
1129
            repo_id: Some(repo.id().unwrap()),
1130
            cache_dir: Some(root.join(format!("cache-{name}"))),
1131
            ..Default::default()
1132
        };
1133
        BucketRemote::open(store, &options).unwrap()
1134
    }
1135
1136
    fn push_bookmark(
1137
        repo: &Repo,
1138
        remote: &BucketRemote,
1139
        bookmark: &str,
1140
        old: Option<ObjectRef>,
1141
    ) -> Vec<RefResult> {
1142
        let heads = repo.heads_of(&repo.view().unwrap(), bookmark).unwrap();
1143
        let state = repo
1144
            .store
1145
            .put_state(&StateObject::new(heads.clone()))
1146
            .unwrap();
1147
        let empty = repo.store.put_state(&StateObject::new(vec![])).unwrap();
1148
        // Only what the remote lacks, as push_bookmark sends.
1149
        let have: Vec<ChangeHash> = remote
1150
            .refs()
1151
            .unwrap()
1152
            .refs
1153
            .iter()
1154
            .flat_map(|r| r.heads.clone())
1155
            .collect();
1156
        let changes = repo.negotiate(&have, &heads).unwrap();
1157
        let mut bundle = repo.bundle_for(&changes).unwrap();
1158
        bundle
1159
            .objects
1160
            .push((ObjectType::State, StateObject::new(heads).encode()));
1161
        let update = RefUpdate {
1162
            name: bookmark.into(),
1163
            old_state: old.unwrap_or(empty),
1164
            new_state: state,
1165
            force: false,
1166
            attestation: None,
1167
        };
1168
        remote.push(bundle, vec![update], None, vec![]).unwrap()
1169
    }
1170
1171
    #[test]
1172
    fn two_pushes_to_different_bookmarks_both_land() {
1173
        hermetic();
1174
        let dir = tempfile::tempdir().unwrap();
1175
        let root = dir.path();
1176
        let inner = std::sync::Arc::new(MemoryStore::new());
1177
        // A pushes main; B (a clone of the same repository) pushes a
1178
        // second bookmark between A's read and A's compare-and-swap.
1179
        let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first");
1180
        let ra = remote_for(&a, Shared::new(inner.clone()), root, "a");
1181
        let r = push_bookmark(&a, &ra, "main", None);
1182
        assert!(r[0].ok, "{r:?}");
1183
        let b = Repo::init_with_id(&root.join("b"), a.id().unwrap()).unwrap();
1184
        let rb = remote_for(&b, Shared::new(inner.clone()), root, "b");
1185
        rb.refs().unwrap();
1186
        write(&root.join("b"), "g.txt", b"g\n");
1187
        b.commit("on b", &[]).unwrap();
1188
        let (_, op) = b.head_op().unwrap();
1189
        let mut view = op.view.clone();
1190
        let feature_heads = b.heads_of(&view, "main").unwrap();
1191
        view.bookmarks.insert(
1192
            "feature".into(),
1193
            b.store.put_state(&StateObject::new(feature_heads)).unwrap(),
1194
        );
1195
        b.record_op(&[b.head_op().unwrap().0], "bookmark create feature", view)
1196
            .unwrap();
1197
        // A's second push to main; B's push of feature lands in between.
1198
        write(&root.join("a"), "f.txt", b"aa\n");
1199
        a.commit("second", &[]).unwrap();
1200
        let a_old = ra
1201
            .refs()
1202
            .unwrap()
1203
            .refs
1204
            .iter()
1205
            .find(|r| r.name == "main")
1206
            .unwrap()
1207
            .state;
1208
        let b_remote = std::sync::Arc::new(std::sync::Mutex::new(Some(rb)));
1209
        let b_handle = b_remote.clone();
1210
        HOOK.with(|h| {
1211
            *h.borrow_mut() = Some(Box::new(move || {
1212
                let rb = b_handle.lock().unwrap().take().unwrap();
1213
                let r = push_bookmark(&b, &rb, "feature", None);
1214
                assert!(r[0].ok, "{r:?}");
1215
            }))
1216
        });
1217
        let r = push_bookmark(&a, &ra, "main", Some(a_old));
1218
        assert!(r[0].ok, "a's push is applied over b's: {r:?}");
1219
        let refs = ra.refs().unwrap();
1220
        let names: Vec<&str> = refs.refs.iter().map(|r| r.name.as_str()).collect();
1221
        assert_eq!(names, ["feature", "main"], "both landed");
1222
        assert_eq!(inner.list("bundles/").unwrap().len(), 3);
1223
        let _ = b_remote;
1224
    }
1225
1226
    #[test]
1227
    fn an_interrupted_push_leaves_the_store_usable() {
1228
        hermetic();
1229
        let dir = tempfile::tempdir().unwrap();
1230
        let root = dir.path();
1231
        let inner = std::sync::Arc::new(MemoryStore::new());
1232
        let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first");
1233
        let shared = Shared::new(inner.clone());
1234
        let fail = &shared.fail_uploads as *const std::sync::atomic::AtomicBool;
1235
        let ra = remote_for(&a, shared, root, "a");
1236
        assert!(push_bookmark(&a, &ra, "main", None)[0].ok);
1237
        let old = ra.refs().unwrap().refs[0].state;
1238
        // The upload fails: nothing in the store changes, the mirror is
1239
        // honest, and the next push gets through.
1240
        write(&root.join("a"), "f.txt", b"aa\n");
1241
        let h2 = a.commit("second", &[]).unwrap();
1242
        unsafe { (*fail).store(true, std::sync::atomic::Ordering::SeqCst) };
1243
        let e = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1244
            push_bookmark(&a, &ra, "main", Some(old))
1245
        }));
1246
        assert!(e.is_err(), "the push reports the failed upload");
1247
        assert_eq!(inner.list("bundles/").unwrap().len(), 1);
1248
        let refs = ra.refs().unwrap();
1249
        assert_eq!(refs.refs[0].state, old, "the record did not move");
1250
        unsafe { (*fail).store(false, std::sync::atomic::Ordering::SeqCst) };
1251
        let r = push_bookmark(&a, &ra, "main", Some(old));
1252
        assert!(r[0].ok, "{r:?}");
1253
        assert_eq!(ra.refs().unwrap().refs[0].heads, vec![h2]);
1254
    }
1255
1256
    #[test]
1257
    fn bundles_out_of_order_or_gone_are_handled() {
1258
        hermetic();
1259
        let dir = tempfile::tempdir().unwrap();
1260
        let root = dir.path();
1261
        let inner = std::sync::Arc::new(MemoryStore::new());
1262
        let a = repo_with_commit(root, "a", "f.txt", b"a\n", "first");
1263
        let ra = remote_for(&a, Shared::new(inner.clone()), root, "a");
1264
        assert!(push_bookmark(&a, &ra, "main", None)[0].ok);
1265
        let old = ra.refs().unwrap().refs[0].state;
1266
        write(&root.join("a"), "f.txt", b"aa\n");
1267
        let h2 = a.commit("second", &[]).unwrap();
1268
        assert!(push_bookmark(&a, &ra, "main", Some(old))[0].ok);
1269
        // The second bundle (which needs the first) renamed to sort first.
1270
        let keys: Vec<String> = inner
1271
            .list("bundles/")
1272
            .unwrap()
1273
            .into_iter()
1274
            .map(|e| e.key)
1275
            .collect();
1276
        assert_eq!(keys.len(), 2);
1277
        let bytes = inner.get(&keys[1]).unwrap();
1278
        inner.delete(&keys[1]).unwrap();
1279
        inner
1280
            .put_new("bundles/00000000-first.bundle", &bytes)
1281
            .unwrap();
1282
        let shared = Shared::new(inner.clone());
1283
        let c = Repo::init_with_id(&root.join("c"), a.id().unwrap()).unwrap();
1284
        let rc = remote_for(&c, shared, root, "c");
1285
        assert_eq!(
1286
            rc.refs().unwrap().refs[0].heads,
1287
            vec![h2],
1288
            "the dependent bundle waited for its dependency"
1289
        );
1290
        // A bundle gone between the listing and the read is skipped.
1291
        let shared = Shared::new(inner.clone());
1292
        *shared.vanish.lock().unwrap() = Some(keys[0].clone());
1293
        let d = Repo::init_with_id(&root.join("d"), a.id().unwrap()).unwrap();
1294
        let rd = remote_for(&d, shared, root, "d");
1295
        // Without the first bundle the second cannot be imported: the sync
1296
        // says so rather than failing silently.
1297
        let e = rd.refs().expect_err("missing changes").to_string();
1298
        assert!(e.contains("cannot be imported"), "{e}");
1299
    }
1300
1301
    #[test]
1302
    fn gc_merges_bundles_and_prunes_after_the_grace_period() {
1303
        hermetic();
1304
        let dir = tempfile::tempdir().unwrap();
1305
        let root = dir.path();
1306
        let url = format!("dir://{}", root.join("bucket").display());
1307
        let store = LocalStore::open(root.join("bucket")).unwrap();
1308
        let mut a = Repo::init(&root.join("a")).unwrap();
1309
        add_remote(&mut a, "bucket", &url);
1310
        for i in 1..=3 {
1311
            write(&root.join("a"), "f.txt", format!("{i}\n").as_bytes());
1312
            a.commit(&format!("change {i}"), &[]).unwrap();
1313
            assert!(a.push("bucket", false).unwrap()[0].ok);
1314
        }
1315
        a.tag_create("v3", &a.bookmark_heads().unwrap(), "three")
1316
            .unwrap();
1317
        assert!(a.push("bucket", false).unwrap().iter().all(|r| r.ok));
1318
        assert_eq!(
1319
            keys(&store, "bundles/").len(),
1320
            4,
1321
            "three pushes and the tag's"
1322
        );
1323
        // A gc folds the four into one; the old ones wait out the grace.
1324
        let r = a.gc_remote("bucket", false).unwrap();
1325
        assert_eq!(
1326
            (r.merged, r.changes, r.deleted, r.deferred),
1327
            (4, 3, 0, 4),
1328
            "{r:?}"
1329
        );
1330
        assert!(r.bundle_bytes > 0);
1331
        assert_eq!(keys(&store, "bundles/").len(), 5);
1332
        let b = Repo::clone(&url, &root.join("b")).unwrap();
1333
        assert_eq!(fs::read(root.join("b/f.txt")).unwrap(), b"3\n");
1334
        assert_eq!(b.tags().unwrap().len(), 1);
1335
        // Past the grace period they go, and a clone needs only the one.
1336
        let r = a.gc_remote("bucket", true).unwrap();
1337
        assert_eq!((r.merged, r.deleted, r.deferred), (0, 4, 0), "{r:?}");
1338
        assert_eq!(keys(&store, "bundles/").len(), 1);
1339
        let c = Repo::clone(&url, &root.join("c")).unwrap();
1340
        assert_eq!(c.bookmark_heads().unwrap(), a.bookmark_heads().unwrap());
1341
        // The earlier clone, which saw the old bundles, carries on.
1342
        write(&root.join("b"), "f.txt", b"4\n");
1343
        b.commit("four", &[]).unwrap();
1344
        assert!(b.push("origin", false).unwrap()[0].ok);
1345
        assert!(a.pull("bucket").unwrap().changed);
1346
        assert_eq!(fs::read(root.join("a/f.txt")).unwrap(), b"4\n");
1347
        // Nothing more to merge: a second gc is a no-op.
1348
        let r = a.gc_remote("bucket", true).unwrap();
1349
        assert_eq!((r.merged, r.deleted), (2, 2));
1350
        assert!(a.gc_remote("nope", true).is_err());
1351
    }
1352
1353
    #[test]
1354
    fn markers_parse_and_refuse_newer_formats() {
1355
        let id = [7u8; 16];
1356
        assert_eq!(parse_marker(&marker(id), "s").unwrap(), id);
1357
        let e = parse_marker(
1358
            b"format = 9\nrepo = \"07070707070707070707070707070707\"\n",
1359
            "s",
1360
        )
1361
        .unwrap_err()
1362
        .to_string();
1363
        assert!(e.contains("format 9"), "{e}");
1364
        assert!(parse_marker(b"hello", "s").is_err());
1365
    }
1366
}