OXYGENHUB
# b4fa2bc1ca6a oxygen / crates / oxy-core / src / repo / sync.rs
44.5 KiB · Rust · last changed Lazy blobs: clone --max-blob / filter.max-blob, absent-blob registry fetched on first read, objects endpoint (spec 0.6e) 1 month ago source blame history raw
1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a fetch brought in.
6
#[derive(Debug, Clone, PartialEq, Eq, Default)]
7
pub struct FetchReport {
8
    /// Bookmark name, its heads, and how many changes were new.
9
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
10
    /// Tags adopted from the remote.
11
    pub new_tags: usize,
12
    /// The remote has never presented a policy, so nothing was verified
13
    /// against one (spec §14.5: warn loudly).
14
    pub unverified: bool,
15
}
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct PullReport {
19
    pub heads: Vec<ChangeHash>,
20
    pub changed: bool,
21
    pub checked_out: bool,
22
}
23
24
impl Repo {
25
    // ------------------------------------------------------------ serving (spec §16)
26
27
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
28
        self.oxy.join("attest").join(bookmark)
29
    }
30
31
    /// The latest reference attestation stored for a bookmark.
32
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
33
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
34
            Ok(h) => {
35
                let r = ObjectRef::from_hex(h.trim()).ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
36
                Ok(Some((r, SignedAttest { attest: self.store.get_attest(&r)?, sigs: self.store.signatures(&r)? })))
37
            }
38
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
39
            Err(e) => Err(e.into()),
40
        }
41
    }
42
43
    fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
44
        fs::create_dir_all(self.oxy.join("attest"))?;
45
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
46
    }
47
48
    pub fn remote_refs(&self) -> Result<RefsResponse> {
49
        let view = self.view()?;
50
        let mut out = Vec::new();
51
        for (name, state) in &view.bookmarks {
52
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
53
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
54
                AttestBody::Ref { serial, .. } => Some(serial),
55
                _ => None,
56
            });
57
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
58
            out.push(RemoteRef { name: name.clone(), state: *state, heads: self.store.get_state(state)?.heads, attestation, last_serial });
59
        }
60
        let policy = self.current_policy()?.map(|(_, sp)| sp);
61
        let history = self.policy_history()?.into_iter().filter(|sp| policy.as_ref().is_some_and(|p| sp.policy.serial < p.policy.serial)).collect();
62
        Ok(RefsResponse { refs: out, policy, tags: self.tag_refs()?, history })
63
    }
64
65
    /// Every change reachable from `heads` that is in the store.
66
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
67
        let mut seen = BTreeSet::new();
68
        let mut stack: Vec<ChangeHash> = heads.to_vec();
69
        while let Some(h) = stack.pop() {
70
            if seen.contains(&h) || !self.store.has(&h) {
71
                continue;
72
            }
73
            seen.insert(h);
74
            stack.extend(self.store.get_change(&h)?.deps);
75
        }
76
        Ok(seen)
77
    }
78
79
    /// The changes within `depth` dependency steps of `heads` (spec §17),
80
    /// nearest first; depth 1 is the heads themselves.
81
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
82
        let mut out = Vec::new();
83
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
84
        let mut layer: Vec<ChangeHash> = heads.to_vec();
85
        for _ in 0..depth.max(1) {
86
            let mut next = Vec::new();
87
            for h in layer {
88
                if !seen.insert(h) || !self.store.has(&h) {
89
                    continue;
90
                }
91
                let c = self.store.get_change(&h)?;
92
                next.extend(c.deps.iter().copied());
93
                out.push(h);
94
            }
95
            if next.is_empty() {
96
                break;
97
            }
98
            layer = next;
99
        }
100
        out.reverse();
101
        Ok(out)
102
    }
103
104
    fn shallow_path(&self) -> PathBuf {
105
        self.oxy.join("shallow")
106
    }
107
108
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
109
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
110
        fs::read_to_string(self.shallow_path()).map(|t| t.lines().filter_map(ObjectRef::from_hex).collect()).unwrap_or_default()
111
    }
112
113
    pub fn is_shallow(&self) -> bool {
114
        !self.boundary().is_empty()
115
    }
116
117
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
118
        if boundary.is_empty() {
119
            let _ = fs::remove_file(self.shallow_path());
120
            return Ok(());
121
        }
122
        let text: String = boundary.iter().map(|h| format!("{}\n", h.to_hex())).collect();
123
        write_atomic(&self.shallow_path(), text.as_bytes())
124
    }
125
126
    /// Recompute the boundary from what is stored: every dependency of a
127
    /// stored change that is not itself stored.
128
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
129
        let mut boundary = self.boundary();
130
        boundary.retain(|h| !self.store.has(h));
131
        for h in imported {
132
            for d in self.store.get_change(h)?.deps {
133
                if !self.store.has(&d) {
134
                    boundary.insert(d);
135
                }
136
            }
137
        }
138
        self.write_boundary(&boundary)
139
    }
140
141
    /// Fetch `depth` more levels of history below the shallow boundary.
142
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
143
        let boundary = self.boundary();
144
        if boundary.is_empty() {
145
            return Ok(0);
146
        }
147
        let remote = self.open_named_remote(remote_name)?;
148
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
149
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
150
        let imported = self.import_bundle_shallow(&bundle, false)?;
151
        if self.config.max_blob.is_some() {
152
            self.register_missing_blobs(&imported, remote_name)?;
153
        }
154
        self.refresh_boundary(&imported)?;
155
        Ok(imported.len())
156
    }
157
158
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
159
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
160
        let have = self.closure_in_store(have)?;
161
        // In a shallow repository the walk stops at the boundary, whose
162
        // changes the remote is assumed to hold.
163
        let boundary = self.boundary();
164
        let mut out = Vec::new();
165
        let mut done: BTreeSet<ChangeHash> = have.clone();
166
        done.extend(boundary.iter().copied());
167
        // Iterative post-order DFS.
168
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
169
        while let Some((h, expanded)) = stack.pop() {
170
            if done.contains(&h) {
171
                continue;
172
            }
173
            if !self.store.has(&h) {
174
                return fail(format!("change {} is not in this repository", h.short(12)));
175
            }
176
            if expanded {
177
                done.insert(h);
178
                out.push(h);
179
                continue;
180
            }
181
            stack.push((h, true));
182
            for d in self.store.get_change(&h)?.deps {
183
                if !done.contains(&d) {
184
                    stack.push((d, false));
185
                }
186
            }
187
        }
188
        Ok(out)
189
    }
190
191
    /// Bundle changes (in the given dependency order) with their signatures,
192
    /// seals, identities, blobs, chunks.
193
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
194
        self.bundle_for_filtered(changes, None)
195
    }
196
197
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
198
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
199
        let mut out = Vec::new();
200
        for r in refs {
201
            let (ty, body) = match self.store.get(r) {
202
                Ok(x) => x,
203
                Err(StoreError::NotFound(_)) => continue,
204
                Err(e) => return Err(e.into()),
205
            };
206
            if ty == ObjectType::Blob {
207
                for c in Blob::decode(&body)?.chunks {
208
                    if let Ok((cty, cb)) = self.store.get(&c) {
209
                        out.push((cty, cb));
210
                    }
211
                }
212
            }
213
            out.push((ty, body));
214
        }
215
        Ok(out)
216
    }
217
218
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
219
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
220
    pub fn bundle_for_filtered(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
221
        let mut bundle = Bundle::default();
222
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
223
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
224
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
225
            if !r.is_zero() && self.store.has(r) {
226
                objects.insert(*r);
227
            }
228
        };
229
        for h in changes {
230
            let c = self.store.get_change(h)?;
231
            let sigs = self.store.signatures(h)?;
232
            add_object(&c.author, &mut objects);
233
            for s in &sigs {
234
                add_object(&s.key, &mut objects);
235
            }
236
            for e in &c.edits {
237
                if let Edit::Replace { old, new, .. } = e {
238
                    for b in [old, new].into_iter().flatten() {
239
                        if self.store.has(b) {
240
                            if let Ok(blob) = Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?) {
241
                                if max_blob.is_some_and(|m| blob.length > m) {
242
                                    continue;
243
                                }
244
                                objects.insert(*b);
245
                                objects.extend(blob.chunks.iter().copied());
246
                            }
247
                        }
248
                    }
249
                }
250
            }
251
            for s in self.store.seals_for(h)? {
252
                seals.insert(s);
253
            }
254
            bundle.changes.push((c, sigs));
255
        }
256
        for r in seals {
257
            let attest = self.store.get_attest(&r)?;
258
            let sigs = self.store.signatures(&r)?;
259
            for s in &sigs {
260
                add_object(&s.key, &mut objects);
261
            }
262
            bundle.attests.push(SignedAttest { attest, sigs });
263
        }
264
        for r in objects {
265
            let (ty, body) = self.store.get(&r)?;
266
            bundle.objects.push((ty, body));
267
        }
268
        Ok(bundle)
269
    }
270
271
    /// Store a bundle's contents. With `strict`, every change must
272
    /// authenticate (signature or seal by its author or a delegate).
273
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
274
        self.import_bundle_inner(bundle, strict, false)
275
    }
276
277
    /// Like `import_bundle`, accepting changes whose dependencies are absent
278
    /// (they join the shallow boundary).
279
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
280
        self.import_bundle_inner(bundle, strict, true)
281
    }
282
283
    fn import_bundle_inner(&self, bundle: &Bundle, strict: bool, shallow: bool) -> Result<Vec<ChangeHash>> {
284
        for (ty, body) in &bundle.objects {
285
            match ty {
286
                ObjectType::Chunk | ObjectType::Blob | ObjectType::Identity | ObjectType::State | ObjectType::Checkpoint => {
287
                    self.store.put(*ty, body)?;
288
                }
289
                other => return fail(format!("bundle may not carry {} objects", other.name())),
290
            }
291
        }
292
        for sa in &bundle.attests {
293
            let r = self.store.put_attest(&sa.attest)?;
294
            for sig in &sa.sigs {
295
                self.store.put_signature(&r, sig)?;
296
            }
297
            if let AttestBody::Seal { hashes } = &sa.attest.body {
298
                for h in hashes {
299
                    self.store.index_seal(h, &r)?;
300
                }
301
            }
302
        }
303
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
304
        let boundary = self.boundary();
305
        let mut imported = Vec::new();
306
        for (c, sigs) in &bundle.changes {
307
            let h = c.hash();
308
            for d in &c.deps {
309
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d) {
310
                    return fail(format!("change {} depends on {}, which is neither stored nor in the bundle", h.short(12), d.short(12)));
311
                }
312
            }
313
            self.store.put_change(c)?;
314
            for sig in sigs {
315
                self.store.put_signature(&h, sig)?;
316
            }
317
            imported.push(h);
318
        }
319
        if strict {
320
            for h in &imported {
321
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
322
                    return fail(format!("change {} is not authenticated by its author", h.short(12)));
323
                }
324
            }
325
        }
326
        Ok(imported)
327
    }
328
329
    /// Verify a reference attestation against an update it claims to describe.
330
    /// `allow_equal` lets a client re-read the attestation it already has; a
331
    /// server receiving a push requires a strictly greater serial.
332
    fn check_ref_attest(&self, sa: &SignedAttest, name: &str, old_state: &ObjectRef, new_state: &ObjectRef, last_serial: Option<u64>, allow_equal: bool) -> std::result::Result<u64, String> {
333
        let AttestBody::Ref { name: n, old_state: o, new_state: nw, serial } = &sa.attest.body else {
334
            return Err("attestation is not a ref attestation".into());
335
        };
336
        if n != name || o != old_state || nw != new_state {
337
            return Err("attestation does not describe this update".into());
338
        }
339
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
340
            return Err("attestation is for a different repository".into());
341
        }
342
        if let Some(last) = last_serial {
343
            if *serial < last || (*serial == last && !allow_equal) {
344
                return Err(format!("attestation serial {serial} is not greater than the last seen {last}"));
345
            }
346
        }
347
        let r = sa.attest.hash();
348
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
349
        let id = self.store.get_identity(&sig.key).map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
350
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
351
        Ok(*serial)
352
    }
353
354
    /// Accept a push (spec §16.4). Without a trust policy every repository
355
    /// is unverified, so unsigned changes and unattested updates are accepted;
356
    /// attestations that are present must still be valid. With a policy,
357
    /// every change and update is checked against it. A newer policy in the
358
    /// push is applied first when it is signed by the current roots.
359
    pub fn receive_push(&self, bundle: Bundle, updates: Vec<RefUpdate>, policy: Option<SignedPolicy>, tags: Vec<crate::protocol::TagRef>) -> Result<Vec<RefResult>> {
360
        let mut results = Vec::new();
361
        if let Some(sp) = policy {
362
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
363
                Ok(()) => {
364
                    results.push(RefResult { name: "policy".into(), ok: true, reason: format!("serial {}", sp.policy.serial) });
365
                }
366
                Err(e) => {
367
                    results.push(RefResult { name: "policy".into(), ok: false, reason: e });
368
                    for u in updates {
369
                        results.push(RefResult { name: u.name, ok: false, reason: "policy update was rejected".into() });
370
                    }
371
                    return Ok(results);
372
                }
373
            }
374
        }
375
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
376
        if let Err(e) = self.import_bundle(&bundle, policy.is_some()) {
377
            for u in updates {
378
                results.push(RefResult { name: u.name, ok: false, reason: e.to_string() });
379
            }
380
            return Ok(results);
381
        }
382
        let (op_ref, op) = self.head_op()?;
383
        let mut view = op.view.clone();
384
        let mut names = Vec::new();
385
        for u in updates {
386
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
387
            let (ok, reason) = match outcome {
388
                Ok(()) => (true, String::new()),
389
                Err(e) => (false, e),
390
            };
391
            if ok {
392
                names.push(u.name.clone());
393
            }
394
            results.push(RefResult { name: u.name, ok, reason });
395
        }
396
        for t in &tags {
397
            let name = format!("tags/{}", t.name);
398
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
399
                Ok(()) => {
400
                    names.push(name.clone());
401
                    results.push(RefResult { name, ok: true, reason: String::new() });
402
                }
403
                Err(e) => results.push(RefResult { name, ok: false, reason: e }),
404
            }
405
        }
406
        if !names.is_empty() {
407
            self.record_op(&[op_ref], &format!("push received: {}", names.join(" ")), view)?;
408
        }
409
        Ok(results)
410
    }
411
412
    fn apply_update(&self, view: &mut View, u: &RefUpdate, policy: Option<&crate::policy::Policy>) -> std::result::Result<(), String> {
413
        if u.name == "policy" {
414
            return Err("the policy reference is updated by sending a policy, not a bookmark update".into());
415
        }
416
        let empty = self.store.put_state(&StateObject::new(vec![])).map_err(|e| e.to_string())?;
417
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
418
        if current != u.old_state {
419
            return Err("stale: the remote bookmark has moved; pull first".into());
420
        }
421
        let new_state = self.store.get_state(&u.new_state).map_err(|_| "new state object is missing".to_string())?;
422
        for h in &new_state.heads {
423
            if !self.store.has(h) {
424
                return Err(format!("head {} is missing", h.short(12)));
425
            }
426
        }
427
        if !u.force {
428
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
429
            let closure = self.closure_in_store(&new_state.heads).map_err(|e| e.to_string())?;
430
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
431
                return Err(format!("not a fast-forward: current head {} would be dropped (use --force)", h.short(12)));
432
            }
433
        }
434
        if let Some(p) = policy {
435
            let Some(sa) = &u.attestation else {
436
                return Err(format!("{:?} requires a signed reference attestation under this repository's policy", u.name));
437
            };
438
            let signer = sa.sigs.first().map(|s| s.key).ok_or("attestation carries no signature")?;
439
            if !p.authorizes(&signer, &u.name) {
440
                return Err(format!("key {} may not update {:?} under this repository's policy", signer.short(12), u.name));
441
            }
442
            let old_heads = self.store.get_state(&current).map_err(|e| e.to_string())?.heads;
443
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
444
        }
445
        if let Some(sa) = &u.attestation {
446
            let last = self.latest_ref_attest(&u.name).map_err(|e| e.to_string())?.and_then(|(_, a)| match a.attest.body {
447
                AttestBody::Ref { serial, .. } => Some(serial),
448
                _ => None,
449
            });
450
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
451
            let r = self.store.put_attest(&sa.attest).map_err(|e| e.to_string())?;
452
            for sig in &sa.sigs {
453
                self.store.put_signature(&r, sig).map_err(|e| e.to_string())?;
454
            }
455
            self.set_ref_attest(&u.name, &r).map_err(|e| e.to_string())?;
456
        }
457
        view.bookmarks.insert(u.name.clone(), u.new_state);
458
        Ok(())
459
    }
460
461
    // ------------------------------------------------------------ client side
462
463
    fn remote_url(&self, name: &str) -> Result<String> {
464
        self.config.remotes.get(name).cloned().ok_or_else(|| RepoError::Msg(format!("no remote named {name:?}; add one with `oxy remote add`")))
465
    }
466
467
    /// Credentials and trust for a remote: `remote.<name>.token` (else
468
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
469
    fn remote_options(&self, name: &str) -> RemoteOptions {
470
        RemoteOptions {
471
            token: self.config.remote_tokens.get(name).cloned().or_else(|| std::env::var("OXY_TOKEN").ok()),
472
            ca: self.config.remote_cas.get(name).map(PathBuf::from).or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
473
        }
474
    }
475
476
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
477
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
478
    }
479
480
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
481
        self.oxy.join("remotes").join(remote).join(format!("{bookmark}.serial"))
482
    }
483
484
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
485
        fs::read_to_string(self.serial_path(remote, bookmark)).ok().and_then(|s| s.trim().parse().ok())
486
    }
487
488
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
489
        let p = self.serial_path(remote, bookmark);
490
        fs::create_dir_all(p.parent().unwrap())?;
491
        write_atomic(&p, serial.to_string().as_bytes())
492
    }
493
494
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
495
        self.oxy.join("remotes").join(remote).join("policy.serial")
496
    }
497
498
    /// The highest policy serial `remote` has ever presented.
499
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
500
        fs::read_to_string(self.policy_serial_path(remote)).ok().and_then(|s| s.trim().parse().ok())
501
    }
502
503
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
504
        let p = self.policy_serial_path(remote);
505
        fs::create_dir_all(p.parent().unwrap())?;
506
        write_atomic(&p, serial.to_string().as_bytes())
507
    }
508
509
    fn lazy_dir(&self) -> PathBuf {
510
        self.oxy.join("lazy")
511
    }
512
513
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
514
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
515
        fs::create_dir_all(self.lazy_dir())?;
516
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
517
    }
518
519
    /// Which remote promised an absent blob, if any.
520
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
521
        fs::read_to_string(self.lazy_dir().join(blob.to_hex())).ok().map(|s| s.trim().to_string())
522
    }
523
524
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
525
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
526
        let Some(remote_name) = self.lazy_remote(blob) else {
527
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
528
        };
529
        let remote = self.open_named_remote(&remote_name)?;
530
        let objects = remote.objects(&[*blob])?;
531
        for (ty, body) in objects {
532
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
533
                self.store.put(ty, &body)?;
534
            }
535
        }
536
        if !self.store.has(blob) {
537
            return fail(format!("{remote_name} did not send blob {}", blob.short(12)));
538
        }
539
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
540
        Ok(())
541
    }
542
543
    /// After importing from `remote`, record every blob the changes reference
544
    /// that the store lacks as lazily available from that remote.
545
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
546
        let mut n = 0;
547
        for h in changes {
548
            let c = self.store.get_change(h)?;
549
            for e in &c.edits {
550
                if let Edit::Replace { old, new, .. } = e {
551
                    for b in [old, new].into_iter().flatten() {
552
                        if !self.store.has(b) {
553
                            self.register_lazy(b, remote)?;
554
                            n += 1;
555
                        }
556
                    }
557
                }
558
            }
559
        }
560
        Ok(n)
561
    }
562
563
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
564
    fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
565
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
566
        for st in view.bookmarks.values().chain(view.remotes.values().flat_map(|b| b.values())) {
567
            if let Ok(s) = self.store.get_state(st) {
568
                have.extend(s.heads);
569
            }
570
        }
571
        have.extend(view.workspaces.values().copied());
572
        Ok(have.into_iter().collect())
573
    }
574
575
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
576
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
577
        let remote = self.open_named_remote(remote_name)?;
578
        if remote.repo_id()? != self.id()? {
579
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
580
        }
581
        let resp = remote.refs()?;
582
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
583
        // and signed by roots we trust, or on first contact. A remote that
584
        // once presented a policy may never present none or an older one:
585
        // that is a downgrade. A remote that never presented one is
586
        // unverified, and this fetch is checked only as far as possible.
587
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
588
        let seen = self.remote_policy_serial(remote_name);
589
        let mut unverified = false;
590
        match &resp.policy {
591
            Some(sp) => {
592
                if seen.is_some_and(|s| sp.policy.serial < s) {
593
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
594
                }
595
                match &local_policy {
596
                    Some(l) if sp.policy.serial < l.serial => {}
597
                    Some(l) if sp.policy.serial == l.serial => {
598
                        if sp.policy.hash() != l.hash() {
599
                            return fail(format!("{remote_name} presents a different policy with the same serial {}", l.serial));
600
                        }
601
                    }
602
                    _ => {
603
                        self.adopt_policy_chain(&resp.history, sp, &format!("oxy fetch {remote_name}")).map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
604
                    }
605
                }
606
                self.record_policy_serial(remote_name, sp.policy.serial)?;
607
            }
608
            None => {
609
                if seen.is_some() {
610
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
611
                }
612
                unverified = true;
613
            }
614
        }
615
        let policy = if unverified { None } else { self.current_policy()?.map(|(_, sp)| sp.policy) };
616
        let (op_ref, op) = self.head_op()?;
617
        let mut view = op.view.clone();
618
        let have = self.known_heads(&view)?;
619
        let mut report = Vec::new();
620
        let max_blob = self.config.max_blob;
621
        for r in resp.refs {
622
            let needed = remote.negotiate(&have, &r.heads)?;
623
            let bundle = remote.fetch(&needed, max_blob)?;
624
            // Changes are not individually re-verified here: the bookmark's
625
            // attestation (checked below) binds its whole state, and the
626
            // receiver of the push verified the added changes at that time.
627
            let imported = self.import_bundle(&bundle, false)?;
628
            if max_blob.is_some() {
629
                self.register_missing_blobs(&imported, remote_name)?;
630
            }
631
            for h in &r.heads {
632
                if !self.store.has(h) {
633
                    return fail(format!("remote did not send head {}", h.short(12)));
634
                }
635
            }
636
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
637
            if state != r.state {
638
                return fail(format!("remote state {} does not match its heads", r.state.short(12)));
639
            }
640
            if let Some(p) = &policy {
641
                let Some(sa) = &r.attestation else {
642
                    return fail(format!("{remote_name}/{} has no attestation, which its policy requires", r.name));
643
                };
644
                let signer = sa.sigs.first().map(|s| s.key).ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
645
                if !p.authorizes(&signer, &r.name) {
646
                    return fail(format!("{remote_name}/{}: attested by {}, which the policy does not authorize", r.name, signer.short(12)));
647
                }
648
            }
649
            if let Some(sa) = &r.attestation {
650
                let AttestBody::Ref { old_state, new_state, .. } = &sa.attest.body else {
651
                    return fail("remote sent a non-ref attestation for a bookmark");
652
                };
653
                let (old_state, new_state) = (*old_state, *new_state);
654
                let serial = self
655
                    .check_ref_attest(sa, &r.name, &old_state, &new_state, self.last_seen_serial(remote_name, &r.name), true)
656
                    .map_err(|e| RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name)))?;
657
                if new_state != r.state {
658
                    return fail(format!("attestation for {}/{} does not cover its current state", remote_name, r.name));
659
                }
660
                let ar = self.store.put_attest(&sa.attest)?;
661
                for sig in &sa.sigs {
662
                    self.store.put_signature(&ar, sig)?;
663
                }
664
                self.record_serial(remote_name, &r.name, serial)?;
665
            }
666
            view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state);
667
            report.push((r.name, r.heads, imported.len()));
668
        }
669
        let mut new_tags = 0;
670
        for t in &resp.tags {
671
            if view.tags.contains_key(&t.name) {
672
                continue;
673
            }
674
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
675
            let missing: Vec<ChangeHash> = t.heads.iter().filter(|h| !self.store.has(h)).copied().collect();
676
            if !missing.is_empty() {
677
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
678
                let bundle = remote.fetch(&needed, max_blob)?;
679
                self.import_bundle(&bundle, false)?;
680
            }
681
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
682
            self.adopt_tag(&mut view, t, policy.as_ref()).map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
683
            new_tags += 1;
684
        }
685
        if view != op.view {
686
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
687
        }
688
        let _ = self.run_hook(
689
            "post-fetch",
690
            &format!(
691
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
692
                json_str(remote_name),
693
                json_array(report.iter().map(|(n, heads, _)| format!("{{\"name\":{},\"heads\":{}}}", json_str(n), json_array(heads.iter().map(|h| json_str(&h.to_hex()))))))
694
            ),
695
        );
696
        Ok(FetchReport { refs: report, unverified, new_tags })
697
    }
698
699
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
700
    /// the changes within `depth` steps of its heads, and the boundary below.
701
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
702
        let remote = self.open_named_remote(remote_name)?;
703
        if remote.repo_id()? != self.id()? {
704
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
705
        }
706
        let resp = remote.refs()?;
707
        let bookmark = self.config.bookmark.clone();
708
        if let Some(sp) = &resp.policy {
709
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth").map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
710
            self.record_policy_serial(remote_name, sp.policy.serial)?;
711
        }
712
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
713
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
714
        };
715
        if r.heads.is_empty() {
716
            return Ok(0);
717
        }
718
        // Base: the remote's checkpoint of exactly these heads.
719
        let cp_bundle = remote.checkpoint(&r.heads)?;
720
        let mut cp_ref = None;
721
        for (ty, body) in &cp_bundle.objects {
722
            let put = self.store.put(*ty, body)?;
723
            if *ty == ObjectType::Checkpoint {
724
                cp_ref = Some(put);
725
            }
726
        }
727
        let Some(cp_ref) = cp_ref else { return fail(format!("{remote_name} sent no checkpoint")) };
728
        self.install_checkpoint(&bookmark, &cp_ref)?;
729
        // History window.
730
        let wanted = remote.shallow(&r.heads, depth)?;
731
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
732
        let imported = self.import_bundle_shallow(&bundle, false)?;
733
        if self.config.max_blob.is_some() {
734
            self.register_missing_blobs(&imported, remote_name)?;
735
        }
736
        self.refresh_boundary(&imported)?;
737
        if let Some(sa) = &r.attestation {
738
            let ar = self.store.put_attest(&sa.attest)?;
739
            for sig in &sa.sigs {
740
                self.store.put_signature(&ar, sig)?;
741
            }
742
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
743
                self.record_serial(remote_name, &r.name, serial)?;
744
            }
745
        }
746
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
747
        let (op_ref, op) = self.head_op()?;
748
        let mut view = op.view.clone();
749
        view.remotes.entry(remote_name.to_string()).or_default().insert(r.name.clone(), state);
750
        self.record_op(&[op_ref], &format!("oxy fetch {remote_name} --depth {depth}"), view)?;
751
        Ok(imported.len())
752
    }
753
754
    /// Fetch, then take the union of the local bookmark's state with the
755
    /// remote's: no merge change, conflicts become reified (spec §9.4).
756
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
757
        self.fetch(remote_name)?;
758
        let (op_ref, op) = self.head_op()?;
759
        let bookmark = self.config.bookmark.clone();
760
        let local = self.heads_of(&op.view, &bookmark)?;
761
        let Some(remote_state) = op.view.remotes.get(remote_name).and_then(|b| b.get(&bookmark)).copied() else {
762
            return Ok(PullReport { heads: local, changed: false, checked_out: false });
763
        };
764
        let remote_heads = self.store.get_state(&remote_state)?.heads;
765
        let mut all = local.clone();
766
        all.extend(remote_heads);
767
        let st = self.load_state(&all)?;
768
        let mut heads = st.maximal(&all);
769
        heads.sort();
770
        let mut sorted_local = local.clone();
771
        sorted_local.sort();
772
        if heads == sorted_local {
773
            return Ok(PullReport { heads, changed: false, checked_out: false });
774
        }
775
        let mut view = op.view.clone();
776
        view.bookmarks.insert(bookmark.clone(), self.store.put_state(&StateObject::new(heads.clone()))?);
777
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
778
        // Follow along if the working copy was clean and on the old heads.
779
        let snap = self.snapshot("oxy pull")?;
780
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
781
        let mut base = snap.base.maximal(&snap.wc.deps);
782
        base.sort();
783
        let mut checked_out = false;
784
        if clean && base == sorted_local {
785
            self.checkout(&heads, false, "oxy pull (checkout)")?;
786
            checked_out = true;
787
        }
788
        Ok(PullReport { heads, changed: true, checked_out })
789
    }
790
791
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
792
    /// changes and attesting the reference when a key is available.
793
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
794
        let (op_ref, op) = self.head_op()?;
795
        let bookmark = self.config.bookmark.clone();
796
        let local_heads = self.heads_of(&op.view, &bookmark)?;
797
        // pre-push hook: may veto before the remote is contacted.
798
        self.run_hook(
799
            "pre-push",
800
            &format!("{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}", json_str(remote_name), json_str(&bookmark), json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))),
801
        )?;
802
        let remote = self.open_named_remote(remote_name)?;
803
        if remote.repo_id()? != self.id()? {
804
            return fail(format!("remote {remote_name:?} is a different repository (repository IDs differ)"));
805
        }
806
        let resp = remote.refs()?;
807
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
808
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
809
        let policy_to_send = match (&local_policy, &resp.policy) {
810
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
811
            (Some(l), None) => Some(l.clone()),
812
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
813
                return fail(format!("{remote_name} has a newer policy (serial {}); fetch first", r.policy.serial));
814
            }
815
            _ => None,
816
        };
817
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
818
        if remote_has_policy && self.secret_key()?.is_none() {
819
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
820
        }
821
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
822
        let tags_to_send: Vec<crate::protocol::TagRef> = self.tag_refs()?.into_iter().filter(|t| !remote_tags.contains(&t.name)).collect();
823
        let refs = resp.refs;
824
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
825
        let (remote_state, remote_heads, last_serial) = match refs.iter().find(|r| r.name == bookmark) {
826
            Some(r) => (r.state, r.heads.clone(), r.last_serial),
827
            None => (empty, vec![], None),
828
        };
829
        let new_state = self.store.put_state(&StateObject::new(local_heads.clone()))?;
830
        // A push that carries a policy re-attests the bookmark even when its
831
        // state is unchanged, so the current attestation is always by a key
832
        // the current policy authorizes (a revoked key's attestation would
833
        // otherwise be refused by every later fetch).
834
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
835
            return Ok(vec![RefResult { name: bookmark, ok: true, reason: "already up to date".into() }]);
836
        }
837
        for h in &remote_heads {
838
            if !self.store.has(h) {
839
                return fail(format!("the remote has change {} which you do not; pull first", h.short(12)));
840
            }
841
        }
842
        if !force {
843
            let closure = self.closure_in_store(&local_heads)?;
844
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
845
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
846
            }
847
        }
848
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
849
        let mut bundle = self.bundle_for(&to_send)?;
850
        let key = self.secret_key()?.map(|(k, _)| k);
851
        if let Some(key) = key {
852
            // Seal this author's changes that carry no valid authenticator.
853
            let mut unsigned = Vec::new();
854
            for h in &to_send {
855
                let c = self.store.get_change(h)?;
856
                if c.author == key && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
857
                    unsigned.push(*h);
858
                }
859
            }
860
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
861
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
862
                bundle.attests.push(sa);
863
            }
864
            bundle = self.bundle_for(&to_send)?;
865
        }
866
        bundle.objects.push((ObjectType::State, StateObject::new(local_heads.clone()).encode()));
867
        let attestation = match key {
868
            Some(_) => Some(self.sign_attest(&Attest {
869
                repo: self.id()?,
870
                hlc: Hlc::now(),
871
                body: AttestBody::Ref { name: bookmark.clone(), old_state: remote_state, new_state, serial: last_serial.unwrap_or(0) + 1 },
872
            })?),
873
            None => None,
874
        };
875
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
876
            AttestBody::Ref { serial, .. } => Some(serial),
877
            _ => None,
878
        });
879
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
880
        // Tag states must be present on the remote: bundle their changes too.
881
        for t in &tags_to_send {
882
            let extra = self.negotiate(&remote_heads, &t.heads)?;
883
            let extra: Vec<ChangeHash> = extra.into_iter().filter(|h| !to_send.contains(h)).collect();
884
            if !extra.is_empty() {
885
                let more = self.bundle_for(&extra)?;
886
                bundle.changes.extend(more.changes);
887
                bundle.attests.extend(more.attests);
888
                bundle.objects.extend(more.objects);
889
            }
890
            bundle.objects.push((ObjectType::State, StateObject::new(t.heads.clone()).encode()));
891
        }
892
        if let Some(l) = &policy_to_send {
893
            let remote_serial = resp_policy_serial;
894
            bundle.policies = self.policy_history()?.into_iter().filter(|sp| remote_serial.is_none_or(|r| sp.policy.serial > r) && sp.policy.serial < l.policy.serial).collect();
895
        }
896
        let results = remote.push(bundle, vec![RefUpdate { name: bookmark.clone(), old_state: remote_state, new_state, force, attestation }], policy_to_send, tags_to_send)?;
897
        if let (Some(serial), true) = (sent_serial, results.iter().any(|r| r.ok && r.name == "policy")) {
898
            self.record_policy_serial(remote_name, serial)?;
899
        }
900
        if results.iter().any(|r| r.ok && r.name == bookmark) {
901
            let mut view = op.view.clone();
902
            view.remotes.entry(remote_name.to_string()).or_default().insert(bookmark.clone(), new_state);
903
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
904
            if let Some(s) = serial {
905
                self.record_serial(remote_name, &bookmark, s)?;
906
            }
907
        }
908
        Ok(results)
909
    }
910
911
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
912
    /// bookmark set to the remote's, working copy checked out.
913
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
914
        Self::clone_with(url, dest, None, &[])
915
    }
916
917
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
918
    /// read, and materializing only `sparse` paths (which implies lazy blobs
919
    /// unless a size is given, so out-of-scope binaries are never fetched).
920
    pub fn clone_with(url: &str, dest: &Path, max_blob: Option<u64>, sparse: &[String]) -> Result<Repo> {
921
        Self::clone_full(url, dest, max_blob, sparse, None)
922
    }
923
924
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
925
    /// changes within `depth` steps of them; the rest is the boundary.
926
    pub fn clone_shallow(url: &str, dest: &Path, depth: u32, max_blob: Option<u64>, sparse: &[String]) -> Result<Repo> {
927
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
928
    }
929
930
    fn clone_full(url: &str, dest: &Path, max_blob: Option<u64>, sparse: &[String], depth: Option<u32>) -> Result<Repo> {
931
        let options = RemoteOptions {
932
            token: std::env::var("OXY_TOKEN").ok(),
933
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
934
        };
935
        let remote = open_remote(url, &options)?;
936
        let id = remote.repo_id()?;
937
        let mut repo = Repo::init_with_id(dest, id)?;
938
        repo.config.set("remote.origin.url", url)?;
939
        if let Some(m) = max_blob {
940
            repo.config.set("filter.max-blob", &m.to_string())?;
941
        } else if !sparse.is_empty() {
942
            repo.config.set("filter.max-blob", "0")?;
943
        }
944
        if !sparse.is_empty() {
945
            repo.config.set("filter.paths", &sparse.join(","))?;
946
        }
947
        repo.save_config()?;
948
        if let Some(depth) = depth {
949
            repo.fetch_shallow("origin", depth)?;
950
        } else {
951
            repo.fetch("origin")?;
952
        }
953
        let (op_ref, op) = repo.head_op()?;
954
        let bookmark = repo.config.bookmark.clone();
955
        if let Some(state) = op.view.remotes.get("origin").and_then(|b| b.get(&bookmark)).copied() {
956
            let heads = repo.store.get_state(&state)?.heads;
957
            let mut view = op.view.clone();
958
            view.bookmarks.insert(bookmark, state);
959
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
960
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
961
        }
962
        Ok(repo)
963
    }
964
}