OXYGENHUB
# 396891fd2dda oxygen / crates / oxy-core / src / repo / sync.rs
72.5 KiB · Rust · last changed Strata: a repository kept on a store, as a remote 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 push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
}
34
35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub struct PullReport {
37
    /// The current bookmark's heads after the pull.
38
    pub heads: Vec<ChangeHash>,
39
    /// Whether the current bookmark changed.
40
    pub changed: bool,
41
    pub checked_out: bool,
42
    /// Other bookmarks the pull moved: each local bookmark tracks the
43
    /// remote's of the same name.
44
    pub others: Vec<String>,
45
}
46
47
impl Repo {
48
    // ------------------------------------------------------------ serving (spec §16)
49
50
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
51
        self.oxy.join("attest").join(name_file(bookmark))
52
    }
53
54
    /// The latest reference attestation stored for a bookmark.
55
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
56
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
57
            Ok(h) => {
58
                let r = ObjectRef::from_hex(h.trim())
59
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
60
                Ok(Some((
61
                    r,
62
                    SignedAttest {
63
                        attest: self.store.get_attest(&r)?,
64
                        sigs: self.store.signatures(&r)?,
65
                    },
66
                )))
67
            }
68
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
69
            Err(e) => Err(e.into()),
70
        }
71
    }
72
73
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
74
        fs::create_dir_all(self.oxy.join("attest"))?;
75
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
76
    }
77
78
    pub fn remote_refs(&self) -> Result<RefsResponse> {
79
        let view = self.view()?;
80
        let mut out = Vec::new();
81
        for (name, state) in &view.bookmarks {
82
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
83
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
84
                AttestBody::Ref { serial, .. } => Some(serial),
85
                _ => None,
86
            });
87
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
88
            out.push(RemoteRef {
89
                name: name.clone(),
90
                state: *state,
91
                heads: self.store.get_state(state)?.heads,
92
                attestation,
93
                last_serial,
94
            });
95
        }
96
        let policy = self.current_policy()?.map(|(_, sp)| sp);
97
        let history = self
98
            .policy_history()?
99
            .into_iter()
100
            .filter(|sp| {
101
                policy
102
                    .as_ref()
103
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
104
            })
105
            .collect();
106
        Ok(RefsResponse {
107
            refs: out,
108
            policy,
109
            tags: self.tag_refs()?,
110
            history,
111
            default_bookmark: Some(self.config.bookmark.clone()),
112
        })
113
    }
114
115
    /// Every change reachable from `heads` that is in the store.
116
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
117
        let mut seen = BTreeSet::new();
118
        let mut stack: Vec<ChangeHash> = heads.to_vec();
119
        while let Some(h) = stack.pop() {
120
            if seen.contains(&h) || !self.store.has(&h) {
121
                continue;
122
            }
123
            seen.insert(h);
124
            stack.extend(self.store.get_change_meta(&h)?.deps);
125
        }
126
        Ok(seen)
127
    }
128
129
    /// The changes within `depth` dependency steps of `heads` (spec §17),
130
    /// nearest first; depth 1 is the heads themselves.
131
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
132
        let mut out = Vec::new();
133
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
134
        let mut layer: Vec<ChangeHash> = heads.to_vec();
135
        for _ in 0..depth.max(1) {
136
            let mut next = Vec::new();
137
            for h in layer {
138
                if !seen.insert(h) || !self.store.has(&h) {
139
                    continue;
140
                }
141
                let c = self.store.get_change(&h)?;
142
                next.extend(c.deps.iter().copied());
143
                out.push(h);
144
            }
145
            if next.is_empty() {
146
                break;
147
            }
148
            layer = next;
149
        }
150
        out.reverse();
151
        Ok(out)
152
    }
153
154
    fn shallow_path(&self) -> PathBuf {
155
        self.oxy.join("shallow")
156
    }
157
158
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
159
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
160
        fs::read_to_string(self.shallow_path())
161
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
162
            .unwrap_or_default()
163
    }
164
165
    pub fn is_shallow(&self) -> bool {
166
        !self.boundary().is_empty()
167
    }
168
169
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
170
        if boundary.is_empty() {
171
            let _ = fs::remove_file(self.shallow_path());
172
            return Ok(());
173
        }
174
        let text: String = boundary
175
            .iter()
176
            .map(|h| format!("{}\n", h.to_hex()))
177
            .collect();
178
        write_atomic(&self.shallow_path(), text.as_bytes())
179
    }
180
181
    /// Recompute the boundary from what is stored: every dependency of a
182
    /// stored change that is not itself stored.
183
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
184
        let mut boundary = self.boundary();
185
        boundary.retain(|h| !self.store.has(h));
186
        for h in imported {
187
            for d in self.store.get_change_meta(h)?.deps {
188
                if !self.store.has(&d) {
189
                    boundary.insert(d);
190
                }
191
            }
192
        }
193
        self.write_boundary(&boundary)
194
    }
195
196
    /// Fetch `depth` more levels of history below the shallow boundary.
197
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
198
        let boundary = self.boundary();
199
        if boundary.is_empty() {
200
            return Ok(0);
201
        }
202
        let remote = self.open_named_remote(remote_name)?;
203
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
204
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
205
        let imported = self.import_bundle_shallow(&bundle, false)?;
206
        if self.config.max_blob.is_some() {
207
            self.register_missing_blobs(&imported, remote_name)?;
208
        }
209
        self.refresh_boundary(&imported)?;
210
        Ok(imported.len())
211
    }
212
213
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
214
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
215
        let have = self.closure_in_store(have)?;
216
        // In a shallow repository the walk stops at the boundary, whose
217
        // changes the remote is assumed to hold.
218
        let boundary = self.boundary();
219
        let mut out = Vec::new();
220
        let mut done: BTreeSet<ChangeHash> = have.clone();
221
        done.extend(boundary.iter().copied());
222
        // Iterative post-order DFS.
223
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
224
        while let Some((h, expanded)) = stack.pop() {
225
            if done.contains(&h) {
226
                continue;
227
            }
228
            if !self.store.has(&h) {
229
                return fail(format!("change {} is not in this repository", h.short(12)));
230
            }
231
            if expanded {
232
                done.insert(h);
233
                out.push(h);
234
                continue;
235
            }
236
            stack.push((h, true));
237
            for d in self.store.get_change_meta(&h)?.deps {
238
                if !done.contains(&d) {
239
                    stack.push((d, false));
240
                }
241
            }
242
        }
243
        Ok(out)
244
    }
245
246
    /// Bundle changes (in the given dependency order) with their signatures,
247
    /// seals, identities, blobs, chunks.
248
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
249
        self.bundle_for_filtered(changes, None)
250
    }
251
252
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
253
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
254
        let mut out = Vec::new();
255
        for r in refs {
256
            let (ty, body) = match self.store.get(r) {
257
                Ok(x) => x,
258
                Err(StoreError::NotFound(_)) => continue,
259
                Err(e) => return Err(e.into()),
260
            };
261
            if ty == ObjectType::Blob {
262
                for c in Blob::decode(&body)?.chunks {
263
                    if let Ok((cty, cb)) = self.store.get(&c) {
264
                        out.push((cty, cb));
265
                    }
266
                }
267
            }
268
            out.push((ty, body));
269
        }
270
        Ok(out)
271
    }
272
273
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
274
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
275
    pub fn bundle_for_filtered(
276
        &self,
277
        changes: &[ChangeHash],
278
        max_blob: Option<u64>,
279
    ) -> Result<Bundle> {
280
        self.bundle_of(changes, max_blob, false)
281
    }
282
283
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
284
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
285
    /// with their text blobs and chunks among the objects, so neither side
286
    /// decodes or encodes their text.
287
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
288
        self.bundle_of(changes, max_blob, true)
289
    }
290
291
    fn bundle_of(
292
        &self,
293
        changes: &[ChangeHash],
294
        max_blob: Option<u64>,
295
        raw: bool,
296
    ) -> Result<Bundle> {
297
        let mut bundle = Bundle::default();
298
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
299
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
300
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
301
            if !r.is_zero() && self.store.has(r) {
302
                objects.insert(*r);
303
            }
304
        };
305
        for h in changes {
306
            // Raw: the stored bytes, and a skeleton for the rest.
307
            let (c, encoded) = if raw {
308
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
309
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
310
                for t in texts {
311
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
312
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
313
                        objects.insert(r);
314
                        objects.extend(blob.chunks);
315
                    }
316
                }
317
                (skel, Some(bytes))
318
            } else {
319
                (self.store.get_change(h)?, None)
320
            };
321
            let sigs = self.store.signatures(h)?;
322
            add_object(&c.author, &mut objects);
323
            for s in &sigs {
324
                add_object(&s.key, &mut objects);
325
            }
326
            for e in &c.edits {
327
                if let Edit::Replace { old, new, .. } = e {
328
                    for b in [old, new].into_iter().flatten() {
329
                        if self.store.has(b) {
330
                            if let Ok(blob) =
331
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
332
                            {
333
                                if max_blob.is_some_and(|m| blob.length > m) {
334
                                    continue;
335
                                }
336
                                objects.insert(*b);
337
                                objects.extend(blob.chunks.iter().copied());
338
                            }
339
                        }
340
                    }
341
                }
342
            }
343
            for s in self.store.seals_for(h)? {
344
                seals.insert(s);
345
            }
346
            match encoded {
347
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
348
                None => {
349
                    bundle.changes.push((c, sigs));
350
                    bundle.hashes.push(*h);
351
                }
352
            }
353
        }
354
        for r in seals {
355
            let attest = self.store.get_attest(&r)?;
356
            let sigs = self.store.signatures(&r)?;
357
            for s in &sigs {
358
                add_object(&s.key, &mut objects);
359
            }
360
            bundle.attests.push(SignedAttest { attest, sigs });
361
        }
362
        for r in objects {
363
            let (ty, body) = self.store.get(&r)?;
364
            bundle.objects.push((ty, body));
365
        }
366
        Ok(bundle)
367
    }
368
369
    /// Store a bundle's contents. With `strict`, every change must
370
    /// authenticate (signature or seal by its author or a delegate).
371
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
372
        self.import_bundle_inner(bundle, strict, false)
373
    }
374
375
    /// Like `import_bundle`, accepting changes whose dependencies are absent
376
    /// (they join the shallow boundary).
377
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
378
        self.import_bundle_inner(bundle, strict, true)
379
    }
380
381
    fn import_bundle_inner(
382
        &self,
383
        bundle: &Bundle,
384
        strict: bool,
385
        shallow: bool,
386
    ) -> Result<Vec<ChangeHash>> {
387
        let batch = self.store.begin_batch()?;
388
        let result = self.import_bundle_batched(bundle, strict, shallow);
389
        batch.finish()?;
390
        result
391
    }
392
393
    fn import_bundle_batched(
394
        &self,
395
        bundle: &Bundle,
396
        strict: bool,
397
        shallow: bool,
398
    ) -> Result<Vec<ChangeHash>> {
399
        for (ty, _) in &bundle.objects {
400
            if !matches!(
401
                ty,
402
                ObjectType::Chunk
403
                    | ObjectType::Blob
404
                    | ObjectType::Identity
405
                    | ObjectType::State
406
                    | ObjectType::Checkpoint
407
            ) {
408
                return fail(format!("bundle may not carry {} objects", ty.name()));
409
            }
410
        }
411
        // All at once: in a large batch they are compressed on every core.
412
        let objects: Vec<(ObjectType, &[u8])> = bundle
413
            .objects
414
            .iter()
415
            .map(|(ty, body)| (*ty, body.as_slice()))
416
            .collect();
417
        self.store.put_many(&objects)?;
418
        for sa in &bundle.attests {
419
            let r = self.store.put_attest(&sa.attest)?;
420
            for sig in &sa.sigs {
421
                self.store.put_signature(&r, sig)?;
422
            }
423
            if let AttestBody::Seal { hashes } = &sa.attest.body {
424
                for h in hashes {
425
                    self.store.index_seal(h, &r)?;
426
                }
427
            }
428
        }
429
        // Each change's hash: from the bundle when its maker knew it, else
430
        // worked out once (for a change adding a whole tree, hashing is
431
        // chunking all its text).
432
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
433
            bundle.hashes.clone()
434
        } else {
435
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
436
        };
437
        let raw_hashes: Vec<ChangeHash> = bundle
438
            .raw_changes
439
            .iter()
440
            .map(|(b, _)| hash_object(ObjectType::Change, b))
441
            .collect();
442
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
443
        let boundary = self.boundary();
444
        let mut imported = Vec::new();
445
        // Changes as stored: checked, then stored as they are, their text
446
        // blobs having come with the objects.
447
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
448
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
449
            for d in &skel.deps {
450
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
451
                {
452
                    return fail(format!(
453
                        "change {} depends on {}, which is neither stored nor in the bundle",
454
                        h.short(12),
455
                        d.short(12)
456
                    ));
457
                }
458
            }
459
            for t in texts {
460
                if let crate::objects::TextRef::Blob(r, _, _) = t {
461
                    if !self.store.has(&r) {
462
                        return fail(format!(
463
                            "change {} came without its text blob {}",
464
                            h.short(12),
465
                            r.short(12)
466
                        ));
467
                    }
468
                }
469
            }
470
            self.store.put(ObjectType::Change, bytes)?;
471
            for sig in sigs {
472
                self.store.put_signature(&h, sig)?;
473
            }
474
            imported.push(h);
475
        }
476
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
477
            for d in &c.deps {
478
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
479
                {
480
                    return fail(format!(
481
                        "change {} depends on {}, which is neither stored nor in the bundle",
482
                        h.short(12),
483
                        d.short(12)
484
                    ));
485
                }
486
            }
487
            let stored = self.store.put_change(c)?;
488
            if stored != h {
489
                return fail(format!(
490
                    "change {} is not the change the bundle names",
491
                    h.short(12)
492
                ));
493
            }
494
            for sig in sigs {
495
                self.store.put_signature(&h, sig)?;
496
            }
497
            imported.push(h);
498
        }
499
        if strict {
500
            for h in &imported {
501
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
502
                    return fail(format!(
503
                        "change {} is not authenticated by its author",
504
                        h.short(12)
505
                    ));
506
                }
507
            }
508
        }
509
        Ok(imported)
510
    }
511
512
    /// Verify a reference attestation against an update it claims to describe.
513
    /// `allow_equal` lets a client re-read the attestation it already has; a
514
    /// server receiving a push requires a strictly greater serial.
515
    /// A reference attestation signed by a delegate of an identity the
516
    /// rule lists is authorized as that identity (spec §14.5): the identity
517
    /// named the delegate, and the policy names the identity. Revoked keys
518
    /// authorize nothing either way.
519
    pub(crate) fn delegate_authorized(
520
        &self,
521
        p: &crate::policy::Policy,
522
        signer: &KeyId,
523
        reference: &str,
524
    ) -> bool {
525
        if p.is_revoked(signer) {
526
            return false;
527
        }
528
        let Some(rule) = p.rule_for(reference) else {
529
            return false;
530
        };
531
        rule.keys.iter().any(|k| {
532
            !p.is_revoked(k)
533
                && p.identity(k)
534
                    .cloned()
535
                    .or_else(|| self.store.get_identity(k).ok())
536
                    .is_some_and(|id| id.delegates.contains(signer))
537
        })
538
    }
539
540
    fn check_ref_attest(
541
        &self,
542
        sa: &SignedAttest,
543
        name: &str,
544
        old_state: &ObjectRef,
545
        new_state: &ObjectRef,
546
        last_serial: Option<u64>,
547
        allow_equal: bool,
548
    ) -> std::result::Result<u64, String> {
549
        let AttestBody::Ref {
550
            name: n,
551
            old_state: o,
552
            new_state: nw,
553
            serial,
554
        } = &sa.attest.body
555
        else {
556
            return Err("attestation is not a ref attestation".into());
557
        };
558
        if n != name || o != old_state || nw != new_state {
559
            return Err("attestation does not describe this update".into());
560
        }
561
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
562
            return Err("attestation is for a different repository".into());
563
        }
564
        if let Some(last) = last_serial {
565
            if *serial < last || (*serial == last && !allow_equal) {
566
                return Err(format!(
567
                    "attestation serial {serial} is not greater than the last seen {last}"
568
                ));
569
            }
570
        }
571
        let r = sa.attest.hash();
572
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
573
        let id = self
574
            .store
575
            .get_identity(&sig.key)
576
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
577
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
578
        Ok(*serial)
579
    }
580
581
    /// Accept a push (spec §16.4). Without a trust policy every repository
582
    /// is unverified, so unsigned changes and unattested updates are accepted;
583
    /// attestations that are present must still be valid. With a policy,
584
    /// every change and update is checked against it. A newer policy in the
585
    /// push is applied first when it is signed by the current roots.
586
    pub fn receive_push(
587
        &self,
588
        bundle: Bundle,
589
        updates: Vec<RefUpdate>,
590
        policy: Option<SignedPolicy>,
591
        tags: Vec<crate::protocol::TagRef>,
592
    ) -> Result<Vec<RefResult>> {
593
        Ok(self
594
            .receive_push_report(bundle, updates, policy, tags)?
595
            .results)
596
    }
597
598
    /// `receive_push` with what a host wants to log: each accepted
599
    /// reference's old and new state and heads, and the changes this push
600
    /// stored (hub spec §6.12).
601
    pub fn receive_push_report(
602
        &self,
603
        bundle: Bundle,
604
        updates: Vec<RefUpdate>,
605
        policy: Option<SignedPolicy>,
606
        tags: Vec<crate::protocol::TagRef>,
607
    ) -> Result<PushReport> {
608
        let mut report = PushReport::default();
609
        let results = &mut report.results;
610
        if let Some(sp) = policy {
611
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
612
                Ok(()) => {
613
                    results.push(RefResult {
614
                        name: "policy".into(),
615
                        ok: true,
616
                        reason: format!("serial {}", sp.policy.serial),
617
                    });
618
                }
619
                Err(e) => {
620
                    results.push(RefResult {
621
                        name: "policy".into(),
622
                        ok: false,
623
                        reason: e,
624
                    });
625
                    for u in updates {
626
                        results.push(RefResult {
627
                            name: u.name,
628
                            ok: false,
629
                            reason: "policy update was rejected".into(),
630
                        });
631
                    }
632
                    return Ok(report);
633
                }
634
            }
635
        }
636
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
637
        match self.import_bundle(&bundle, policy.is_some()) {
638
            Ok(imported) => report.imported = imported,
639
            Err(e) => {
640
                for u in updates {
641
                    results.push(RefResult {
642
                        name: u.name,
643
                        ok: false,
644
                        reason: e.to_string(),
645
                    });
646
                }
647
                return Ok(report);
648
            }
649
        }
650
        let (op_ref, op) = self.head_op()?;
651
        let mut view = op.view.clone();
652
        let mut names = Vec::new();
653
        for u in updates {
654
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
655
            let (ok, reason) = match outcome {
656
                Ok(()) => (true, String::new()),
657
                Err(e) => (false, e),
658
            };
659
            if ok {
660
                names.push(u.name.clone());
661
                let heads = self
662
                    .store
663
                    .get_state(&u.new_state)
664
                    .map(|s| s.heads)
665
                    .unwrap_or_default();
666
                report.updated.push(RefUpdated {
667
                    name: u.name.clone(),
668
                    old_state: u.old_state,
669
                    new_state: u.new_state,
670
                    heads,
671
                });
672
            }
673
            results.push(RefResult {
674
                name: u.name,
675
                ok,
676
                reason,
677
            });
678
        }
679
        for t in &tags {
680
            let name = format!("tags/{}", t.name);
681
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
682
                Ok(()) => {
683
                    names.push(name.clone());
684
                    results.push(RefResult {
685
                        name,
686
                        ok: true,
687
                        reason: String::new(),
688
                    });
689
                }
690
                Err(e) => results.push(RefResult {
691
                    name,
692
                    ok: false,
693
                    reason: e,
694
                }),
695
            }
696
        }
697
        if !names.is_empty() {
698
            self.record_op(
699
                &[op_ref],
700
                &format!("push received: {}", names.join(" ")),
701
                view,
702
            )?;
703
        }
704
        Ok(report)
705
    }
706
707
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
708
    /// at `old_state`, is never the repository's own bookmark (its default),
709
    /// and under a policy needs an attestation by a key that may update it.
710
    /// The deletion's attestation stays the bookmark's latest, so an older
711
    /// one cannot be replayed to bring it back.
712
    fn apply_deletion(
713
        &self,
714
        view: &mut View,
715
        u: &RefUpdate,
716
        policy: Option<&crate::policy::Policy>,
717
    ) -> std::result::Result<(), String> {
718
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
719
            return Err(format!("no bookmark {:?} to delete", u.name));
720
        };
721
        if current != u.old_state {
722
            return Err("stale: the remote bookmark has moved; pull first".into());
723
        }
724
        if u.name == self.config.bookmark {
725
            return Err(format!(
726
                "{:?} is this repository's default bookmark and cannot be deleted",
727
                u.name
728
            ));
729
        }
730
        if let Some(p) = policy {
731
            let Some(sa) = &u.attestation else {
732
                return Err(format!(
733
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
734
                    u.name
735
                ));
736
            };
737
            let signer = sa
738
                .sigs
739
                .first()
740
                .map(|s| s.key)
741
                .ok_or("attestation carries no signature")?;
742
            if !p.authorizes(&signer, &u.name) && !self.delegate_authorized(p, &signer, &u.name) {
743
                return Err(format!(
744
                    "key {} may not delete {:?} under this repository's policy",
745
                    signer.short(12),
746
                    u.name
747
                ));
748
            }
749
        }
750
        if let Some(sa) = &u.attestation {
751
            let last = self
752
                .latest_ref_attest(&u.name)
753
                .map_err(|e| e.to_string())?
754
                .and_then(|(_, a)| match a.attest.body {
755
                    AttestBody::Ref { serial, .. } => Some(serial),
756
                    _ => None,
757
                });
758
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
759
            let r = self
760
                .store
761
                .put_attest(&sa.attest)
762
                .map_err(|e| e.to_string())?;
763
            for sig in &sa.sigs {
764
                self.store
765
                    .put_signature(&r, sig)
766
                    .map_err(|e| e.to_string())?;
767
            }
768
            self.set_ref_attest(&u.name, &r)
769
                .map_err(|e| e.to_string())?;
770
        }
771
        view.bookmarks.remove(&u.name);
772
        Ok(())
773
    }
774
775
    fn apply_update(
776
        &self,
777
        view: &mut View,
778
        u: &RefUpdate,
779
        policy: Option<&crate::policy::Policy>,
780
    ) -> std::result::Result<(), String> {
781
        if u.name == "policy" {
782
            return Err(
783
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
784
            );
785
        }
786
        let empty = self
787
            .store
788
            .put_state(&StateObject::new(vec![]))
789
            .map_err(|e| e.to_string())?;
790
        if u.new_state.is_zero() {
791
            return self.apply_deletion(view, u, policy);
792
        }
793
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
794
        if current != u.old_state {
795
            return Err("stale: the remote bookmark has moved; pull first".into());
796
        }
797
        let new_state = self
798
            .store
799
            .get_state(&u.new_state)
800
            .map_err(|_| "new state object is missing".to_string())?;
801
        for h in &new_state.heads {
802
            if !self.store.has(h) {
803
                return Err(format!("head {} is missing", h.short(12)));
804
            }
805
        }
806
        if !u.force {
807
            let old_heads = self
808
                .store
809
                .get_state(&current)
810
                .map_err(|e| e.to_string())?
811
                .heads;
812
            let closure = self
813
                .closure_in_store(&new_state.heads)
814
                .map_err(|e| e.to_string())?;
815
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
816
                return Err(format!(
817
                    "not a fast-forward: current head {} would be dropped (use --force)",
818
                    h.short(12)
819
                ));
820
            }
821
        }
822
        if let Some(p) = policy {
823
            let Some(sa) = &u.attestation else {
824
                return Err(format!(
825
                    "{:?} requires a signed reference attestation under this repository's policy",
826
                    u.name
827
                ));
828
            };
829
            let signer = sa
830
                .sigs
831
                .first()
832
                .map(|s| s.key)
833
                .ok_or("attestation carries no signature")?;
834
            if !p.authorizes(&signer, &u.name) && !self.delegate_authorized(p, &signer, &u.name) {
835
                return Err(format!(
836
                    "key {} may not update {:?} under this repository's policy",
837
                    signer.short(12),
838
                    u.name
839
                ));
840
            }
841
            let old_heads = self
842
                .store
843
                .get_state(&current)
844
                .map_err(|e| e.to_string())?
845
                .heads;
846
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
847
        }
848
        if let Some(sa) = &u.attestation {
849
            let last = self
850
                .latest_ref_attest(&u.name)
851
                .map_err(|e| e.to_string())?
852
                .and_then(|(_, a)| match a.attest.body {
853
                    AttestBody::Ref { serial, .. } => Some(serial),
854
                    _ => None,
855
                });
856
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
857
            let r = self
858
                .store
859
                .put_attest(&sa.attest)
860
                .map_err(|e| e.to_string())?;
861
            for sig in &sa.sigs {
862
                self.store
863
                    .put_signature(&r, sig)
864
                    .map_err(|e| e.to_string())?;
865
            }
866
            self.set_ref_attest(&u.name, &r)
867
                .map_err(|e| e.to_string())?;
868
        }
869
        view.bookmarks.insert(u.name.clone(), u.new_state);
870
        Ok(())
871
    }
872
873
    // ------------------------------------------------------------ client side
874
875
    fn remote_url(&self, name: &str) -> Result<String> {
876
        self.config.remotes.get(name).cloned().ok_or_else(|| {
877
            RepoError::Msg(format!(
878
                "no remote named {name:?}; add one with `oxy remote add`"
879
            ))
880
        })
881
    }
882
883
    /// Refuse a remote that is another repository. An **unbound** remote
884
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
885
    /// for pushes, which bind it to this repository's id (spec §16.1).
886
    fn check_remote_id(
887
        &self,
888
        remote: &dyn crate::protocol::Remote,
889
        remote_name: &str,
890
        allow_unbound: bool,
891
    ) -> Result<()> {
892
        let theirs = remote.repo_id()?;
893
        if theirs == self.id()? {
894
            return Ok(());
895
        }
896
        if theirs == crate::protocol::UNBOUND_ID {
897
            if allow_unbound {
898
                return Ok(());
899
            }
900
            return fail(format!(
901
                "remote {remote_name:?} is empty and unbound: push to it first"
902
            ));
903
        }
904
        fail(format!(
905
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
906
        ))
907
    }
908
909
    /// Credentials and trust for a remote: `remote.<name>.token` and
910
    /// `remote.<name>.ca`, else the defaults for its URL
911
    /// ([`Repo::fill_credentials`]).
912
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
913
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
914
        let mut options = RemoteOptions {
915
            repo_id: self.id().ok(),
916
            token: self.config.remote_tokens.get(name).cloned(),
917
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
918
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
919
        };
920
        self.fill_credentials(&url, &mut options);
921
        options
922
    }
923
924
    /// The user's credential store (`credentials.toml` beside the user
925
    /// configuration file).
926
    pub fn credentials(&self) -> crate::credentials::Credentials {
927
        crate::credentials::Credentials::at(
928
            self.user_config
929
                .parent()
930
                .map(Path::to_path_buf)
931
                .unwrap_or_else(default_home),
932
        )
933
    }
934
935
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
936
    /// then the user's credential store for its hub, then a remote on the
937
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
938
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
939
        if options.token.is_some() && options.ca.is_some() {
940
            return;
941
        }
942
        let stored = self.credentials().options_for(url);
943
        options.token = options.token.take().or(stored.token);
944
        options.ca = options.ca.take().or(stored.ca);
945
        if options.token.is_some() && options.ca.is_some() {
946
            return;
947
        }
948
        let Some(hub) = crate::credentials::hub_of(url) else {
949
            return;
950
        };
951
        let mut at = self.root.parent();
952
        while let Some(dir) = at {
953
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
954
                break;
955
            };
956
            for (key, remote_url) in &cfg {
957
                let Some(name) = key
958
                    .strip_prefix("remote.")
959
                    .and_then(|k| k.strip_suffix(".url"))
960
                else {
961
                    continue;
962
                };
963
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
964
                    continue;
965
                }
966
                if options.token.is_none() {
967
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
968
                }
969
                if options.ca.is_none() {
970
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
971
                }
972
            }
973
            if options.token.is_some() && options.ca.is_some() {
974
                return;
975
            }
976
            at = dir.parent();
977
        }
978
    }
979
980
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
981
    /// no changes and no reference updates, which the receiver stores.
982
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
983
        let remote = self.open_named_remote(remote_name)?;
984
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
985
        let mut bundle = Bundle::default();
986
        for r in seals {
987
            let attest = self.store.get_attest(r)?;
988
            let sigs = self.store.signatures(r)?;
989
            bundle
990
                .attests
991
                .push(crate::protocol::SignedAttest { attest, sigs });
992
        }
993
        let results = remote.push(bundle, vec![], None, vec![])?;
994
        if let Some(r) = results.iter().find(|r| !r.ok) {
995
            return fail(format!("{}: {}", r.name, r.reason));
996
        }
997
        Ok(())
998
    }
999
1000
    /// The remote whose URL starts with `base` (a hub), if configured.
1001
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
1002
        let base = base.trim_end_matches('/');
1003
        self.config
1004
            .remotes
1005
            .iter()
1006
            .find(|(_, url)| url.trim_end_matches('/') == base)
1007
            .map(|(name, _)| name.clone())
1008
    }
1009
1010
    /// Open a remote by name or, failing that, by URL with the default
1011
    /// credentials (see [`Repo::credentials_for`]).
1012
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
1013
        if let Some(name) = self.remote_for_url(url) {
1014
            return Ok((name.clone(), self.open_named_remote(&name)?));
1015
        }
1016
        let options = RemoteOptions {
1017
            repo_id: self.id().ok(),
1018
            ..self.credentials_for(url)
1019
        };
1020
        Ok((url.to_string(), open_remote(url, &options)?))
1021
    }
1022
1023
    /// Credentials for a URL: those of the configured remote with that
1024
    /// URL, else the environment's.
1025
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
1026
        match self.remote_for_url(url) {
1027
            Some(name) => self.remote_options(&name),
1028
            None => RemoteOptions {
1029
                repo_id: self.id().ok(),
1030
                ..self.credentials_for(url)
1031
            },
1032
        }
1033
    }
1034
1035
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1036
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1037
    }
1038
1039
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1040
        self.oxy
1041
            .join("remotes")
1042
            .join(remote)
1043
            .join(format!("{bookmark}.serial"))
1044
    }
1045
1046
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
1047
        fs::read_to_string(self.serial_path(remote, bookmark))
1048
            .ok()
1049
            .and_then(|s| s.trim().parse().ok())
1050
    }
1051
1052
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1053
        let p = self.serial_path(remote, bookmark);
1054
        fs::create_dir_all(p.parent().unwrap())?;
1055
        write_atomic(&p, serial.to_string().as_bytes())
1056
    }
1057
1058
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1059
        self.oxy.join("remotes").join(remote).join("policy.serial")
1060
    }
1061
1062
    /// The highest policy serial `remote` has ever presented.
1063
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1064
        fs::read_to_string(self.policy_serial_path(remote))
1065
            .ok()
1066
            .and_then(|s| s.trim().parse().ok())
1067
    }
1068
1069
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
1070
        let p = self.policy_serial_path(remote);
1071
        fs::create_dir_all(p.parent().unwrap())?;
1072
        write_atomic(&p, serial.to_string().as_bytes())
1073
    }
1074
1075
    fn lazy_dir(&self) -> PathBuf {
1076
        self.oxy.join("lazy")
1077
    }
1078
1079
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
1080
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
1081
        fs::create_dir_all(self.lazy_dir())?;
1082
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
1083
    }
1084
1085
    /// Which remote promised an absent blob, if any.
1086
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
1087
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
1088
            .ok()
1089
            .map(|s| s.trim().to_string())
1090
    }
1091
1092
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
1093
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
1094
        let Some(remote_name) = self.lazy_remote(blob) else {
1095
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1096
        };
1097
        let remote = self.open_named_remote(&remote_name)?;
1098
        let objects = remote.objects(&[*blob])?;
1099
        for (ty, body) in objects {
1100
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
1101
                self.store.put(ty, &body)?;
1102
            }
1103
        }
1104
        if !self.store.has(blob) {
1105
            return fail(format!(
1106
                "{remote_name} did not send blob {}",
1107
                blob.short(12)
1108
            ));
1109
        }
1110
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
1111
        Ok(())
1112
    }
1113
1114
    /// After importing from `remote`, record every blob the changes reference
1115
    /// that the store lacks as lazily available from that remote.
1116
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
1117
        let mut n = 0;
1118
        for h in changes {
1119
            let c = self.store.get_change(h)?;
1120
            for e in &c.edits {
1121
                if let Edit::Replace { old, new, .. } = e {
1122
                    for b in [old, new].into_iter().flatten() {
1123
                        if !self.store.has(b) {
1124
                            self.register_lazy(b, remote)?;
1125
                            n += 1;
1126
                        }
1127
                    }
1128
                }
1129
            }
1130
        }
1131
        Ok(n)
1132
    }
1133
1134
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1135
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1136
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1137
        for st in view
1138
            .bookmarks
1139
            .values()
1140
            .chain(view.remotes.values().flat_map(|b| b.values()))
1141
        {
1142
            if let Ok(s) = self.store.get_state(st) {
1143
                have.extend(s.heads);
1144
            }
1145
        }
1146
        have.extend(view.workspaces.values().copied());
1147
        Ok(have.into_iter().collect())
1148
    }
1149
1150
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1151
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1152
        let remote = self.open_named_remote(remote_name)?;
1153
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1154
        let resp = remote.refs()?;
1155
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1156
        // and signed by roots we trust, or on first contact. A remote that
1157
        // once presented a policy may never present none or an older one:
1158
        // that is a downgrade. A remote that never presented one is
1159
        // unverified, and this fetch is checked only as far as possible.
1160
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1161
        let seen = self.remote_policy_serial(remote_name);
1162
        let mut unverified = false;
1163
        match &resp.policy {
1164
            Some(sp) => {
1165
                if seen.is_some_and(|s| sp.policy.serial < s) {
1166
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
1167
                }
1168
                match &local_policy {
1169
                    Some(l) if sp.policy.serial < l.serial => {}
1170
                    Some(l) if sp.policy.serial == l.serial => {
1171
                        if sp.policy.hash() != l.hash() {
1172
                            return fail(format!(
1173
                                "{remote_name} presents a different policy with the same serial {}",
1174
                                l.serial
1175
                            ));
1176
                        }
1177
                    }
1178
                    _ => {
1179
                        self.adopt_policy_chain(
1180
                            &resp.history,
1181
                            sp,
1182
                            &format!("oxy fetch {remote_name}"),
1183
                        )
1184
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1185
                    }
1186
                }
1187
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1188
            }
1189
            None => {
1190
                if seen.is_some() {
1191
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1192
                }
1193
                unverified = true;
1194
            }
1195
        }
1196
        let policy = if unverified {
1197
            None
1198
        } else {
1199
            self.current_policy()?.map(|(_, sp)| sp.policy)
1200
        };
1201
        let (op_ref, op) = self.head_op()?;
1202
        let mut view = op.view.clone();
1203
        let have = self.known_heads(&view)?;
1204
        let mut report = Vec::new();
1205
        let max_blob = self.config.max_blob;
1206
        for r in resp.refs {
1207
            let needed = remote.negotiate(&have, &r.heads)?;
1208
            let bundle = remote.fetch(&needed, max_blob)?;
1209
            // Changes are not individually re-verified here: the bookmark's
1210
            // attestation (checked below) binds its whole state, and the
1211
            // receiver of the push verified the added changes at that time.
1212
            let imported = self.import_bundle(&bundle, false)?;
1213
            if max_blob.is_some() {
1214
                self.register_missing_blobs(&imported, remote_name)?;
1215
            }
1216
            for h in &r.heads {
1217
                if !self.store.has(h) {
1218
                    return fail(format!("remote did not send head {}", h.short(12)));
1219
                }
1220
            }
1221
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1222
            if state != r.state {
1223
                return fail(format!(
1224
                    "remote state {} does not match its heads",
1225
                    r.state.short(12)
1226
                ));
1227
            }
1228
            if let Some(p) = &policy {
1229
                let Some(sa) = &r.attestation else {
1230
                    return fail(format!(
1231
                        "{remote_name}/{} has no attestation, which its policy requires",
1232
                        r.name
1233
                    ));
1234
                };
1235
                let signer = sa
1236
                    .sigs
1237
                    .first()
1238
                    .map(|s| s.key)
1239
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1240
                if !p.authorizes(&signer, &r.name) && !self.delegate_authorized(p, &signer, &r.name) {
1241
                    return fail(format!(
1242
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1243
                        r.name,
1244
                        signer.short(12)
1245
                    ));
1246
                }
1247
            }
1248
            if let Some(sa) = &r.attestation {
1249
                let AttestBody::Ref {
1250
                    old_state,
1251
                    new_state,
1252
                    ..
1253
                } = &sa.attest.body
1254
                else {
1255
                    return fail("remote sent a non-ref attestation for a bookmark");
1256
                };
1257
                let (old_state, new_state) = (*old_state, *new_state);
1258
                let serial = self
1259
                    .check_ref_attest(
1260
                        sa,
1261
                        &r.name,
1262
                        &old_state,
1263
                        &new_state,
1264
                        self.last_seen_serial(remote_name, &r.name),
1265
                        true,
1266
                    )
1267
                    .map_err(|e| {
1268
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
1269
                    })?;
1270
                if new_state != r.state {
1271
                    return fail(format!(
1272
                        "attestation for {}/{} does not cover its current state",
1273
                        remote_name, r.name
1274
                    ));
1275
                }
1276
                let ar = self.store.put_attest(&sa.attest)?;
1277
                for sig in &sa.sigs {
1278
                    self.store.put_signature(&ar, sig)?;
1279
                }
1280
                self.record_serial(remote_name, &r.name, serial)?;
1281
            }
1282
            view.remotes
1283
                .entry(remote_name.to_string())
1284
                .or_default()
1285
                .insert(r.name.clone(), state);
1286
            report.push((r.name, r.heads, imported.len()));
1287
        }
1288
        let mut new_tags = 0;
1289
        for t in &resp.tags {
1290
            if view.tags.contains_key(&t.name) {
1291
                continue;
1292
            }
1293
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
1294
            let missing: Vec<ChangeHash> = t
1295
                .heads
1296
                .iter()
1297
                .filter(|h| !self.store.has(h))
1298
                .copied()
1299
                .collect();
1300
            if !missing.is_empty() {
1301
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1302
                let bundle = remote.fetch(&needed, max_blob)?;
1303
                self.import_bundle(&bundle, false)?;
1304
            }
1305
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1306
            self.adopt_tag(&mut view, t, policy.as_ref())
1307
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
1308
            new_tags += 1;
1309
        }
1310
        if view != op.view {
1311
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1312
        }
1313
        let _ = self.run_hook(
1314
            "post-fetch",
1315
            &format!(
1316
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1317
                json_str(remote_name),
1318
                json_array(report.iter().map(|(n, heads, _)| format!(
1319
                    "{{\"name\":{},\"heads\":{}}}",
1320
                    json_str(n),
1321
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1322
                )))
1323
            ),
1324
        );
1325
        Ok(FetchReport {
1326
            refs: report,
1327
            unverified,
1328
            new_tags,
1329
        })
1330
    }
1331
1332
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1333
    /// the changes within `depth` steps of its heads, and the boundary below.
1334
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1335
        let remote = self.open_named_remote(remote_name)?;
1336
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1337
        let resp = remote.refs()?;
1338
        let bookmark = self.config.bookmark.clone();
1339
        if let Some(sp) = &resp.policy {
1340
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1341
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1342
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1343
        }
1344
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1345
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1346
        };
1347
        if r.heads.is_empty() {
1348
            return Ok(0);
1349
        }
1350
        // Base: the remote's checkpoint of exactly these heads.
1351
        let cp_bundle = remote.checkpoint(&r.heads)?;
1352
        let mut cp_ref = None;
1353
        for (ty, body) in &cp_bundle.objects {
1354
            let put = self.store.put(*ty, body)?;
1355
            if *ty == ObjectType::Checkpoint {
1356
                cp_ref = Some(put);
1357
            }
1358
        }
1359
        let Some(cp_ref) = cp_ref else {
1360
            return fail(format!("{remote_name} sent no checkpoint"));
1361
        };
1362
        self.install_checkpoint(&bookmark, &cp_ref)?;
1363
        // History window.
1364
        let wanted = remote.shallow(&r.heads, depth)?;
1365
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1366
        let imported = self.import_bundle_shallow(&bundle, false)?;
1367
        if self.config.max_blob.is_some() {
1368
            self.register_missing_blobs(&imported, remote_name)?;
1369
        }
1370
        self.refresh_boundary(&imported)?;
1371
        if let Some(sa) = &r.attestation {
1372
            let ar = self.store.put_attest(&sa.attest)?;
1373
            for sig in &sa.sigs {
1374
                self.store.put_signature(&ar, sig)?;
1375
            }
1376
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1377
                self.record_serial(remote_name, &r.name, serial)?;
1378
            }
1379
        }
1380
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1381
        let (op_ref, op) = self.head_op()?;
1382
        let mut view = op.view.clone();
1383
        view.remotes
1384
            .entry(remote_name.to_string())
1385
            .or_default()
1386
            .insert(r.name.clone(), state);
1387
        self.record_op(
1388
            &[op_ref],
1389
            &format!("oxy fetch {remote_name} --depth {depth}"),
1390
            view,
1391
        )?;
1392
        Ok(imported.len())
1393
    }
1394
1395
    /// Fetch, then take the union of the local bookmark's state with the
1396
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1397
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1398
        let _wc = self.lock_working_copy()?;
1399
        self.fetch(remote_name)?;
1400
        let (op_ref, op) = self.head_op()?;
1401
        let current = self.config.bookmark.clone();
1402
        let mut local_current = self.heads_of(&op.view, &current)?;
1403
        local_current.sort();
1404
        let mut view = op.view.clone();
1405
        let mut current_heads = local_current.clone();
1406
        let mut changed = false;
1407
        let mut others = Vec::new();
1408
        let tracked = op
1409
            .view
1410
            .remotes
1411
            .get(remote_name)
1412
            .cloned()
1413
            .unwrap_or_default();
1414
        for (name, remote_state) in tracked {
1415
            // Every local bookmark tracks the remote's of the same name;
1416
            // the current one may be new here.
1417
            let local_state = op.view.bookmarks.get(&name).copied();
1418
            if local_state.is_none() && name != current {
1419
                continue;
1420
            }
1421
            if local_state == Some(remote_state) {
1422
                continue;
1423
            }
1424
            let local = self.heads_of(&op.view, &name)?;
1425
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1426
            if remote_heads.iter().all(|h| local.contains(h)) {
1427
                continue;
1428
            }
1429
            let mut all = local.clone();
1430
            all.extend(remote_heads);
1431
            let st = self.load_state_history(&all)?;
1432
            let mut heads = st.maximal(&all);
1433
            heads.sort();
1434
            let mut sorted_local = local;
1435
            sorted_local.sort();
1436
            if heads == sorted_local {
1437
                continue;
1438
            }
1439
            view.bookmarks.insert(
1440
                name.clone(),
1441
                self.store.put_state(&StateObject::new(heads.clone()))?,
1442
            );
1443
            if name == current {
1444
                changed = true;
1445
                current_heads = heads;
1446
            } else {
1447
                others.push(name);
1448
            }
1449
        }
1450
        if !changed && others.is_empty() {
1451
            return Ok(PullReport {
1452
                heads: local_current,
1453
                changed: false,
1454
                checked_out: false,
1455
                others,
1456
            });
1457
        }
1458
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1459
        let mut checked_out = false;
1460
        if changed {
1461
            // Follow along if the working copy was clean and on the old heads.
1462
            let snap = self.snapshot("oxy pull")?;
1463
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1464
            let mut base = snap.base.maximal(&snap.wc.deps);
1465
            base.sort();
1466
            if clean && base == local_current {
1467
                self.checkout(&current_heads, false, "oxy pull (checkout)")?;
1468
                checked_out = true;
1469
            }
1470
        }
1471
        Ok(PullReport {
1472
            heads: current_heads,
1473
            changed,
1474
            checked_out,
1475
            others,
1476
        })
1477
    }
1478
1479
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1480
    /// changes and attesting the reference when a key is available.
1481
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1482
    /// state, attested when we have an identity. The local bookmark, if
1483
    /// any, is kept; only the remote-tracking entry goes.
1484
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
1485
        let remote = self.open_named_remote(remote_name)?;
1486
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1487
        let resp = remote.refs()?;
1488
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
1489
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1490
        };
1491
        if resp.policy.is_some() && self.secret_key()?.is_none() {
1492
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
1493
        }
1494
        let attestation = match self.secret_key()? {
1495
            Some(_) => Some(self.sign_attest(&Attest {
1496
                repo: self.id()?,
1497
                hlc: Hlc::now(),
1498
                body: AttestBody::Ref {
1499
                    name: bookmark.to_string(),
1500
                    old_state: r.state,
1501
                    new_state: ObjectRef::ZERO,
1502
                    serial: r.last_serial.unwrap_or(0) + 1,
1503
                },
1504
            })?),
1505
            None => None,
1506
        };
1507
        let results = remote.push(
1508
            Bundle::default(),
1509
            vec![RefUpdate {
1510
                name: bookmark.to_string(),
1511
                old_state: r.state,
1512
                new_state: ObjectRef::ZERO,
1513
                force: true,
1514
                attestation,
1515
            }],
1516
            None,
1517
            vec![],
1518
        )?;
1519
        if results.iter().any(|x| x.ok && x.name == bookmark) {
1520
            let (op_ref, op) = self.head_op()?;
1521
            let mut view = op.view.clone();
1522
            if let Some(m) = view.remotes.get_mut(remote_name) {
1523
                m.remove(bookmark);
1524
            }
1525
            self.record_op(
1526
                &[op_ref],
1527
                &format!("oxy push {remote_name} --delete {bookmark}"),
1528
                view,
1529
            )?;
1530
        }
1531
        Ok(results)
1532
    }
1533
1534
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1535
        let bookmark = self.config.bookmark.clone();
1536
        self.push_bookmark(remote_name, &bookmark, force)
1537
    }
1538
1539
    /// `push` for a named bookmark (`oxy push -b NAME`).
1540
    pub fn push_bookmark(
1541
        &self,
1542
        remote_name: &str,
1543
        bookmark: &str,
1544
        force: bool,
1545
    ) -> Result<Vec<RefResult>> {
1546
        let (op_ref, op) = self.head_op()?;
1547
        if !op.view.bookmarks.contains_key(bookmark) {
1548
            return fail(format!("no bookmark {bookmark}"));
1549
        }
1550
        let bookmark = bookmark.to_string();
1551
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1552
        // pre-push hook: may veto before the remote is contacted.
1553
        self.run_hook(
1554
            "pre-push",
1555
            &format!(
1556
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1557
                json_str(remote_name),
1558
                json_str(&bookmark),
1559
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1560
            ),
1561
        )?;
1562
        let remote = self.open_named_remote(remote_name)?;
1563
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1564
        let resp = remote.refs()?;
1565
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1566
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1567
        let policy_to_send = match (&local_policy, &resp.policy) {
1568
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1569
            (Some(l), None) => Some(l.clone()),
1570
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
1571
                return fail(format!(
1572
                    "{remote_name} has a newer policy (serial {}); fetch first",
1573
                    r.policy.serial
1574
                ));
1575
            }
1576
            _ => None,
1577
        };
1578
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1579
        if remote_has_policy && self.secret_key()?.is_none() {
1580
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1581
        }
1582
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1583
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1584
            .tag_refs()?
1585
            .into_iter()
1586
            .filter(|t| !remote_tags.contains(&t.name))
1587
            .collect();
1588
        let refs = resp.refs;
1589
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1590
        let (remote_state, remote_heads, last_serial) =
1591
            match refs.iter().find(|r| r.name == bookmark) {
1592
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1593
                None => (empty, vec![], None),
1594
            };
1595
        let new_state = self
1596
            .store
1597
            .put_state(&StateObject::new(local_heads.clone()))?;
1598
        // A push that carries a policy re-attests the bookmark even when its
1599
        // state is unchanged, so the current attestation is always by a key
1600
        // the current policy authorizes (a revoked key's attestation would
1601
        // otherwise be refused by every later fetch).
1602
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
1603
            return Ok(vec![RefResult {
1604
                name: bookmark,
1605
                ok: true,
1606
                reason: "already up to date".into(),
1607
            }]);
1608
        }
1609
        for h in &remote_heads {
1610
            if !self.store.has(h) {
1611
                return fail(format!(
1612
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
1613
                    h.short(12)
1614
                ));
1615
            }
1616
        }
1617
        if !force {
1618
            let closure = self.closure_in_store(&local_heads)?;
1619
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1620
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1621
            }
1622
        }
1623
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1624
        let mut bundle = self.bundle_for(&to_send)?;
1625
        let key = self.secret_key()?.map(|(k, _)| k);
1626
        if let Some(key) = key {
1627
            // Seal this author's changes that carry no valid authenticator,
1628
            // and adopt anonymous ones (zero author, spec §14.4).
1629
            let mut unsigned = Vec::new();
1630
            for h in &to_send {
1631
                let c = self.store.get_change(h)?;
1632
                if (c.author == key || c.author.is_zero())
1633
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1634
                {
1635
                    unsigned.push(*h);
1636
                }
1637
            }
1638
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
1639
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1640
                bundle.attests.push(sa);
1641
            }
1642
            bundle = self.bundle_for(&to_send)?;
1643
        }
1644
        bundle.objects.push((
1645
            ObjectType::State,
1646
            StateObject::new(local_heads.clone()).encode(),
1647
        ));
1648
        let attestation = match key {
1649
            Some(_) => Some(self.sign_attest(&Attest {
1650
                repo: self.id()?,
1651
                hlc: Hlc::now(),
1652
                body: AttestBody::Ref {
1653
                    name: bookmark.clone(),
1654
                    old_state: remote_state,
1655
                    new_state,
1656
                    serial: next_serial(last_serial),
1657
                },
1658
            })?),
1659
            None => None,
1660
        };
1661
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1662
            AttestBody::Ref { serial, .. } => Some(serial),
1663
            _ => None,
1664
        });
1665
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1666
        // Tag states must be present on the remote: bundle their changes too.
1667
        for t in &tags_to_send {
1668
            let extra = self.negotiate(&remote_heads, &t.heads)?;
1669
            let extra: Vec<ChangeHash> =
1670
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
1671
            if !extra.is_empty() {
1672
                let more = self.bundle_for(&extra)?;
1673
                bundle.changes.extend(more.changes);
1674
                bundle.hashes.extend(more.hashes);
1675
                bundle.attests.extend(more.attests);
1676
                bundle.objects.extend(more.objects);
1677
            }
1678
            bundle.objects.push((
1679
                ObjectType::State,
1680
                StateObject::new(t.heads.clone()).encode(),
1681
            ));
1682
        }
1683
        if let Some(l) = &policy_to_send {
1684
            let remote_serial = resp_policy_serial;
1685
            bundle.policies = self
1686
                .policy_history()?
1687
                .into_iter()
1688
                .filter(|sp| {
1689
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1690
                        && sp.policy.serial < l.policy.serial
1691
                })
1692
                .collect();
1693
        }
1694
        let results = remote.push(
1695
            bundle,
1696
            vec![RefUpdate {
1697
                name: bookmark.clone(),
1698
                old_state: remote_state,
1699
                new_state,
1700
                force,
1701
                attestation,
1702
            }],
1703
            policy_to_send,
1704
            tags_to_send,
1705
        )?;
1706
        if let (Some(serial), true) = (
1707
            sent_serial,
1708
            results.iter().any(|r| r.ok && r.name == "policy"),
1709
        ) {
1710
            self.record_policy_serial(remote_name, serial)?;
1711
        }
1712
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1713
            let mut view = op.view.clone();
1714
            view.remotes
1715
                .entry(remote_name.to_string())
1716
                .or_default()
1717
                .insert(bookmark.clone(), new_state);
1718
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1719
            if let Some(s) = serial {
1720
                self.record_serial(remote_name, &bookmark, s)?;
1721
            }
1722
        }
1723
        Ok(results)
1724
    }
1725
1726
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1727
    /// bookmark set to the remote's, working copy checked out.
1728
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1729
        Self::clone_with(url, dest, None, &[])
1730
    }
1731
1732
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1733
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1734
    /// unless a size is given, so out-of-scope binaries are never fetched).
1735
    pub fn clone_with(
1736
        url: &str,
1737
        dest: &Path,
1738
        max_blob: Option<u64>,
1739
        sparse: &[String],
1740
    ) -> Result<Repo> {
1741
        Self::clone_full(url, dest, max_blob, sparse, None)
1742
    }
1743
1744
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1745
    /// changes within `depth` steps of them; the rest is the boundary.
1746
    pub fn clone_shallow(
1747
        url: &str,
1748
        dest: &Path,
1749
        depth: u32,
1750
        max_blob: Option<u64>,
1751
        sparse: &[String],
1752
    ) -> Result<Repo> {
1753
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1754
    }
1755
1756
    fn clone_full(
1757
        url: &str,
1758
        dest: &Path,
1759
        max_blob: Option<u64>,
1760
        sparse: &[String],
1761
        depth: Option<u32>,
1762
    ) -> Result<Repo> {
1763
        let options = crate::credentials::Credentials::user().options_for(url);
1764
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1765
    }
1766
1767
    /// Clone a subrepo with the credentials the parent would use for its
1768
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1769
    /// subrepo: it finds the same ones again through its parent.
1770
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
1771
        let options = self.credentials_for(url);
1772
        Self::clone_using(url, dest, None, &[], None, &options)
1773
    }
1774
1775
    /// The name of a remote of this repository on the same hub (scheme,
1776
    /// host and port) as `url`.
1777
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
1778
        let origin = |u: &str| -> Option<String> {
1779
            let (scheme, rest) = u.split_once("://")?;
1780
            if !matches!(scheme, "http" | "https") {
1781
                return None;
1782
            }
1783
            let host = rest.split('/').next()?;
1784
            Some(format!(
1785
                "{}://{}",
1786
                scheme.to_ascii_lowercase(),
1787
                host.to_ascii_lowercase()
1788
            ))
1789
        };
1790
        let want = origin(url)?;
1791
        self.config
1792
            .remotes
1793
            .iter()
1794
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
1795
            .map(|(name, _)| name.clone())
1796
    }
1797
1798
    /// The token and CA to reach `url` with: those of a remote of this
1799
    /// repository on the same hub (scheme, host and port), else the
1800
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
1801
    /// and enclosing checkouts', as a clone would use them.
1802
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
1803
        match self.remote_on_same_hub(url) {
1804
            Some(name) => RemoteOptions {
1805
                repo_id: None,
1806
                cache_dir: None,
1807
                ..self.remote_options(&name)
1808
            },
1809
            None => {
1810
                let mut options = RemoteOptions::default();
1811
                self.fill_credentials(url, &mut options);
1812
                options
1813
            }
1814
        }
1815
    }
1816
1817
    fn clone_using(
1818
        url: &str,
1819
        dest: &Path,
1820
        max_blob: Option<u64>,
1821
        sparse: &[String],
1822
        depth: Option<u32>,
1823
        options: &RemoteOptions,
1824
    ) -> Result<Repo> {
1825
        let remote = open_remote(url, options)?;
1826
        let id = remote.repo_id()?;
1827
        if id == crate::protocol::UNBOUND_ID {
1828
            return fail(format!(
1829
                "{url} is empty and unbound: push a repository to it first"
1830
            ));
1831
        }
1832
        let mut repo = Repo::init_with_id(dest, id)?;
1833
        repo.config
1834
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
1835
        if let Some(m) = max_blob {
1836
            repo.config.set("filter.max-blob", &m.to_string())?;
1837
        } else if !sparse.is_empty() {
1838
            repo.config.set("filter.max-blob", "0")?;
1839
        }
1840
        if !sparse.is_empty() {
1841
            repo.config.set("filter.paths", &sparse.join(","))?;
1842
        }
1843
        repo.save_config()?;
1844
        if let Some(depth) = depth {
1845
            repo.fetch_shallow("origin", depth)?;
1846
        } else {
1847
            repo.fetch("origin")?;
1848
        }
1849
        let (op_ref, op) = repo.head_op()?;
1850
        // The remote's default bookmark, else ours (main), else its only one.
1851
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
1852
        // Asked of the remote as now configured, so a store-backed one
1853
        // answers from the mirror the fetch just filled.
1854
        let advertised = repo
1855
            .open_named_remote("origin")
1856
            .ok()
1857
            .and_then(|r| r.refs().ok())
1858
            .and_then(|r| r.default_bookmark);
1859
        let bookmark = advertised
1860
            .filter(|b| theirs.contains_key(b))
1861
            .or_else(|| {
1862
                theirs
1863
                    .contains_key(&repo.config.bookmark)
1864
                    .then(|| repo.config.bookmark.clone())
1865
            })
1866
            .or_else(|| {
1867
                (theirs.len() == 1)
1868
                    .then(|| theirs.keys().next().cloned())
1869
                    .flatten()
1870
            })
1871
            .unwrap_or_else(|| repo.config.bookmark.clone());
1872
        let initial = repo.config.bookmark.clone();
1873
        if bookmark != repo.config.bookmark {
1874
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
1875
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
1876
            repo.config.bookmark = bookmark.clone();
1877
        }
1878
        if let Some(state) = theirs.get(&bookmark).copied() {
1879
            let heads = repo.store.get_state(&state)?.heads;
1880
            let mut view = op.view.clone();
1881
            // The empty bookmark `init` made goes when another is checked out.
1882
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
1883
                view.bookmarks.remove(&initial);
1884
            }
1885
            view.bookmarks.insert(bookmark, state);
1886
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1887
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
1888
        }
1889
        Ok(repo)
1890
    }
1891
}
1892
1893
/// The serial of a reference's next attestation: one more than the last the
1894
/// remote reports, or, for a bookmark the remote does not have, the clock in
1895
/// milliseconds, so a bookmark created again after a deletion goes past the
1896
/// deletion's serial the remote keeps.
1897
fn next_serial(last: Option<u64>) -> u64 {
1898
    match last {
1899
        Some(l) => l + 1,
1900
        None => Hlc::now().wall_ms.max(1),
1901
    }
1902
}