OXYGENHUB

Coverage / crates/oxy-core/src/repo/sync.rs 89.1%

1669 of 1873 lines run, 244 of 350 functions · run #312 on main · run missed

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
/// The result a push of objects alone reports (a batch of a long history):
48
/// not a reference.
49
pub const OBJECTS_RESULT: &str = "objects";
50
51
impl Repo {
52
    // ------------------------------------------------------------ serving (spec §16)
53
541315×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551315×
        self.oxy.join("attest").join(name_file(bookmark))
561315×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591234×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601234×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61215×
            Ok(h) => {
62215×
                let r = ObjectRef::from_hex(h.trim())
63215×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65215×
                    r,
66
                    SignedAttest {
67215×
                        attest: self.store.get_attest(&r)?,
68215×
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
71
            }
721019×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751234×
    }
76
7781×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7881×
        fs::create_dir_all(self.oxy.join("attest"))?;
7981×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8081×
    }
81
821014×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
831014×
        let view = self.view()?;
841014×
        let mut out = Vec::new();
851036×
        for (name, state) in &view.bookmarks {
861036×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
871036×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88120×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90120×
            });
911036×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
921036×
            out.push(RemoteRef {
931036×
                name: name.clone(),
941036×
                state: *state,
951036×
                heads: self.store.get_state(state)?.heads,
961036×
                attestation,
971036×
                last_serial,
98
            });
99
        }
1001014×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
1011014×
        let history = self
1021014×
            .policy_history()?
1031014×
            .into_iter()
1041014×
            .filter(|sp| {
10595×
                policy
10695×
                    .as_ref()
10795×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10895×
            })
1091014×
            .collect();
110
        Ok(RefsResponse {
1111014×
            refs: out,
1121014×
            policy,
1131014×
            tags: self.tag_refs()?,
1141014×
            history,
1151014×
            default_bookmark: Some(self.config.bookmark.clone()),
116
        })
1171014×
    }
118
119
    /// Every change reachable from `heads` that is in the store.
1201343×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1211343×
        let mut seen = BTreeSet::new();
1221343×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1234829×
        while let Some(h) = stack.pop() {
1243486×
            if seen.contains(&h) || !self.store.has(&h) {
1251032×
                continue;
1262454×
            }
1272454×
            seen.insert(h);
1282454×
            stack.extend(self.store.get_change_meta(&h)?.deps);
129
        }
1301343×
        Ok(seen)
1311343×
    }
132
133
    /// The changes within `depth` dependency steps of `heads` (spec §17),
134
    /// nearest first; depth 1 is the heads themselves.
1353×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1363×
        let mut out = Vec::new();
1373×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1383×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1393×
        for _ in 0..depth.max(1) {
1408×
            let mut next = Vec::new();
14112×
            for h in layer {
14212×
                if !seen.insert(h) || !self.store.has(&h) {
1432×
                    continue;
14410×
                }
14510×
                let c = self.store.get_change(&h)?;
14610×
                next.extend(c.deps.iter().copied());
14710×
                out.push(h);
148
            }
1498×
            if next.is_empty() {
1501×
                break;
1517×
            }
1527×
            layer = next;
153
        }
1543×
        out.reverse();
1553×
        Ok(out)
1563×
    }
157
1581928×
    fn shallow_path(&self) -> PathBuf {
1591928×
        self.oxy.join("shallow")
1601928×
    }
161
162
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1631925×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1641925×
        fs::read_to_string(self.shallow_path())
1651925×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1661925×
            .unwrap_or_default()
1671925×
    }
168
169183×
    pub fn is_shallow(&self) -> bool {
170183×
        !self.boundary().is_empty()
171183×
    }
172
1733×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1743×
        if boundary.is_empty() {
1751×
            let _ = fs::remove_file(self.shallow_path());
1761×
            return Ok(());
1772×
        }
1782×
        let text: String = boundary
1792×
            .iter()
1802×
            .map(|h| format!("{}\n", h.to_hex()))
1812×
            .collect();
1822×
        write_atomic(&self.shallow_path(), text.as_bytes())
1833×
    }
184
185
    /// Recompute the boundary from what is stored: every dependency of a
186
    /// stored change that is not itself stored.
1873×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1883×
        let mut boundary = self.boundary();
1893×
        boundary.retain(|h| !self.store.has(h));
19010×
        for h in imported {
19113×
            for d in self.store.get_change_meta(h)?.deps {
19213×
                if !self.store.has(&d) {
1932×
                    boundary.insert(d);
19411×
                }
195
            }
196
        }
1973×
        self.write_boundary(&boundary)
1983×
    }
199
200
    /// Fetch `depth` more levels of history below the shallow boundary.
2012×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2022×
        let boundary = self.boundary();
2032×
        if boundary.is_empty() {
2040×
            return Ok(0);
2052×
        }
2062×
        let remote = self.open_named_remote(remote_name)?;
2072×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2082×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2092×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2102×
        if self.config.max_blob.is_some() {
2110×
            self.register_missing_blobs(&imported, remote_name)?;
2122×
        }
2132×
        self.refresh_boundary(&imported)?;
2142×
        Ok(imported.len())
2152×
    }
216
217
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
218765×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
219765×
        let have = self.closure_in_store(have)?;
220
        // In a shallow repository the walk stops at the boundary, whose
221
        // changes the remote is assumed to hold.
222765×
        let boundary = self.boundary();
223765×
        let mut out = Vec::new();
224765×
        let mut done: BTreeSet<ChangeHash> = have.clone();
225765×
        done.extend(boundary.iter().copied());
226
        // Iterative post-order DFS.
2271277×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2283286×
        while let Some((h, expanded)) = stack.pop() {
2292521×
            if done.contains(&h) {
230425×
                continue;
2312096×
            }
2322096×
            if !self.store.has(&h) {
2330×
                return fail(format!("change {} is not in this repository", h.short(12)));
2342096×
            }
2352096×
            if expanded {
2361048×
                done.insert(h);
2371048×
                out.push(h);
2381048×
                continue;
2391048×
            }
2401048×
            stack.push((h, true));
2411048×
            for d in self.store.get_change_meta(&h)?.deps {
242726×
                if !done.contains(&d) {
243196×
                    stack.push((d, false));
244530×
                }
245
            }
246
        }
247765×
        Ok(out)
248765×
    }
249
250
    /// Bundle changes (in the given dependency order) with their signatures,
251
    /// seals, identities, blobs, chunks.
252302×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
253302×
        self.bundle_for_filtered(changes, None)
254302×
    }
255
256
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2574×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2584×
        let mut out = Vec::new();
2594×
        for r in refs {
2604×
            let (ty, body) = match self.store.get(r) {
2614×
                Ok(x) => x,
2620×
                Err(StoreError::NotFound(_)) => continue,
2630×
                Err(e) => return Err(e.into()),
264
            };
2654×
            if ty == ObjectType::Blob {
2665×
                for c in Blob::decode(&body)?.chunks {
2675×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2685×
                        out.push((cty, cb));
2695×
                    }
270
                }
2710×
            }
2724×
            out.push((ty, body));
273
        }
2744×
        Ok(out)
2754×
    }
276
277
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
278
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
279349×
    pub fn bundle_for_filtered(
280349×
        &self,
281349×
        changes: &[ChangeHash],
282349×
        max_blob: Option<u64>,
283349×
    ) -> Result<Bundle> {
284349×
        self.bundle_of(changes, max_blob, false)
285349×
    }
286
287
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
288
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
289
    /// with their text blobs and chunks among the objects, so neither side
290
    /// decodes or encodes their text.
291324×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
292324×
        self.bundle_of(changes, max_blob, true)
293324×
    }
294
295673×
    fn bundle_of(
296673×
        &self,
297673×
        changes: &[ChangeHash],
298673×
        max_blob: Option<u64>,
299673×
        raw: bool,
300673×
    ) -> Result<Bundle> {
301673×
        let mut bundle = Bundle::default();
302673×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
303673×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3041069×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3051069×
            if !r.is_zero() && self.store.has(r) {
306193×
                objects.insert(*r);
307876×
            }
3081069×
        };
309975×
        for h in changes {
310
            // Raw: the stored bytes, and a skeleton for the rest.
311975×
            let (c, encoded) = if raw {
312527×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
313527×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3144990×
                for t in texts {
3154990×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3163×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3173×
                        objects.insert(r);
3183×
                        objects.extend(blob.chunks);
3194987×
                    }
320
                }
321527×
                (skel, Some(bytes))
322
            } else {
323448×
                (self.store.get_change(h)?, None)
324
            };
325975×
            let sigs = self.store.signatures(h)?;
326975×
            add_object(&c.author, &mut objects);
327975×
            for s in &sigs {
32822×
                add_object(&s.key, &mut objects);
32922×
            }
3305950×
            for e in &c.edits {
3315950×
                if let Edit::Replace { old, new, .. } = e {
33214×
                    for b in [old, new].into_iter().flatten() {
33314×
                        if self.store.has(b) {
33414×
                            if let Ok(blob) =
33514×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
336
                            {
33714×
                                if max_blob.is_some_and(|m| blob.length > m) {
3384×
                                    continue;
33910×
                                }
34010×
                                objects.insert(*b);
34110×
                                objects.extend(blob.chunks.iter().copied());
3420×
                            }
3430×
                        }
344
                    }
3455938×
                }
346
            }
347975×
            for s in self.store.seals_for(h)? {
34877×
                seals.insert(s);
34977×
            }
350975×
            match encoded {
351527×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
352448×
                None => {
353448×
                    bundle.changes.push((c, sigs));
354448×
                    bundle.hashes.push(*h);
355448×
                }
356
            }
357
        }
358673×
        for r in seals {
35972×
            let attest = self.store.get_attest(&r)?;
36072×
            let sigs = self.store.signatures(&r)?;
36172×
            for s in &sigs {
36272×
                add_object(&s.key, &mut objects);
36372×
            }
36472×
            bundle.attests.push(SignedAttest { attest, sigs });
365
        }
366673×
        for r in objects {
367116×
            let (ty, body) = self.store.get(&r)?;
368116×
            bundle.objects.push((ty, body));
369
        }
370673×
        self.attach_certificates(&mut bundle)?;
371673×
        Ok(bundle)
372673×
    }
373
374
    /// Add the certificates of short-lived keys that signed what `bundle`
375
    /// carries, and their issuers' identities, so a receiver can tell who
376
    /// they stand for (spec §14.7). `also` names more signers (a reference
377
    /// attestation sent beside the bundle).
378752×
    pub(crate) fn attach_certificates_for(
379752×
        &self,
380752×
        bundle: &mut Bundle,
381752×
        also: &[KeyId],
382752×
    ) -> Result<()> {
383752×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
384752×
        keys.extend(
385752×
            bundle
386752×
                .changes
387752×
                .iter()
388752×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
389
        );
390752×
        keys.extend(
391752×
            bundle
392752×
                .raw_changes
393752×
                .iter()
394752×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
395
        );
396752×
        keys.extend(
397752×
            bundle
398752×
                .attests
399752×
                .iter()
400752×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
401
        );
402752×
        for k in keys {
403174×
            let Some(r) = self.store.certificate_of(&k)? else {
404165×
                continue;
405
            };
4069×
            let cert = self.store.get_certificate(&r)?;
4079×
            if bundle
4089×
                .certificates
4099×
                .iter()
4109×
                .any(|c| c.cert.hash() == cert.cert.hash())
411
            {
4123×
                continue;
4136×
            }
41412×
            for id in [&k, &cert.cert.issuer] {
41512×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
41612×
                    if !bundle
41712×
                        .objects
41812×
                        .iter()
41914×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
4206×
                    {
4216×
                        bundle.objects.push((ObjectType::Identity, body));
4226×
                    }
4230×
                }
424
            }
4256×
            bundle.certificates.push(cert);
426
        }
427752×
        Ok(())
428752×
    }
429
430673×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
431673×
        self.attach_certificates_for(bundle, &[])
432673×
    }
433
434
    /// Keep the certificates a bundle brings once each verifies with the
435
    /// identity of the issuer it names; one that does not refuses the bundle.
436718×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
437718×
        for c in certs {
4386×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4390×
                RepoError::Msg(format!(
4400×
                    "a certificate names issuer {}, whose identity did not come with it",
4410×
                    c.cert.issuer.short(12)
4420×
                ))
4430×
            })?;
4446×
            c.verify(&issuer)
4456×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
4466×
            self.store.put_identity(&c.cert.key)?;
4476×
            self.store.put_certificate(c)?;
448
        }
449718×
        Ok(())
450718×
    }
451
452
    /// A signer authorized for `reference` by what an issuer certified it
453
    /// as (spec §14.7): a short-lived key with a kept certificate that
454
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
455
    /// signer did not choose) and names a subject the policy grants.
45612×
    pub(crate) fn certified_authorized(
45712×
        &self,
45812×
        p: &crate::policy::Policy,
45912×
        signer: &KeyId,
46012×
        reference: &str,
46112×
        scope: Scope,
46212×
        at_ms: u64,
46312×
    ) -> bool {
46412×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
4655×
            return false;
466
        };
4677×
        let Ok(c) = self.store.get_certificate(&r) else {
4680×
            return false;
469
        };
4707×
        let Some(issuer) = p
4717×
            .identity(&c.cert.issuer)
4727×
            .cloned()
4737×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
474
        else {
4750×
            return false;
476
        };
4777×
        c.verify(&issuer).is_ok()
4787×
            && c.cert.key_id() == *signer
4797×
            && c.cert.covers(scope, at_ms)
4806×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
48112×
    }
482
483
    /// Store a bundle's contents. With `strict`, every change must
484
    /// authenticate (signature or seal by its author or a delegate).
485715×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
486715×
        self.import_bundle_inner(bundle, strict, false)
487715×
    }
488
489
    /// Like `import_bundle`, accepting changes whose dependencies are absent
490
    /// (they join the shallow boundary).
4913×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
4923×
        self.import_bundle_inner(bundle, strict, true)
4933×
    }
494
495718×
    fn import_bundle_inner(
496718×
        &self,
497718×
        bundle: &Bundle,
498718×
        strict: bool,
499718×
        shallow: bool,
500718×
    ) -> Result<Vec<ChangeHash>> {
501718×
        let batch = self.store.begin_batch()?;
502718×
        let result = self.import_bundle_batched(bundle, strict, shallow);
503718×
        batch.finish()?;
504716×
        result
505718×
    }
506
507718×
    fn import_bundle_batched(
508718×
        &self,
509718×
        bundle: &Bundle,
510718×
        strict: bool,
511718×
        shallow: bool,
512718×
    ) -> Result<Vec<ChangeHash>> {
513718×
        for (ty, _) in &bundle.objects {
5140×
            if !matches!(
515497×
                ty,
516
                ObjectType::Chunk
517
                    | ObjectType::Blob
518
                    | ObjectType::Identity
519
                    | ObjectType::State
520
                    | ObjectType::Checkpoint
521
            ) {
5220×
                return fail(format!("bundle may not carry {} objects", ty.name()));
523497×
            }
524
        }
525
        // All at once: in a large batch they are compressed on every core.
526718×
        let objects: Vec<(ObjectType, &[u8])> = bundle
527718×
            .objects
528718×
            .iter()
529718×
            .map(|(ty, body)| (*ty, body.as_slice()))
530718×
            .collect();
531718×
        self.store.put_many(&objects)?;
532718×
        self.adopt_certificates(&bundle.certificates)?;
533718×
        for sa in &bundle.attests {
53475×
            let r = self.store.put_attest(&sa.attest)?;
53575×
            for sig in &sa.sigs {
53675×
                self.store.put_signature(&r, sig)?;
537
            }
53875×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
53980×
                for h in hashes {
54080×
                    self.store.index_seal(h, &r)?;
541
                }
5420×
            }
543
        }
544
        // Each change's hash: from the bundle when its maker knew it, else
545
        // worked out once (for a change adding a whole tree, hashing is
546
        // chunking all its text).
547718×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
548709×
            bundle.hashes.clone()
549
        } else {
5509×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
551
        };
552718×
        let raw_hashes: Vec<ChangeHash> = bundle
553718×
            .raw_changes
554718×
            .iter()
555718×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
556718×
            .collect();
557718×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
558718×
        let boundary = self.boundary();
559718×
        let mut imported = Vec::new();
560
        // Changes as stored: checked, then stored as they are, their text
561
        // blobs having come with the objects.
562718×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
563528×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
564528×
            for d in &skel.deps {
565391×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
566
                {
5670×
                    return fail(format!(
568
                        "change {} depends on {}, which is neither stored nor in the bundle",
5690×
                        h.short(12),
5700×
                        d.short(12)
571
                    ));
572391×
                }
573
            }
5744991×
            for t in texts {
5754991×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
5764×
                    if !self.store.has(&r) {
5771×
                        return fail(format!(
578
                            "change {} came without its text blob {}",
5791×
                            h.short(12),
5801×
                            r.short(12)
581
                        ));
5823×
                    }
5834987×
                }
584
            }
585527×
            self.store.put(ObjectType::Change, bytes)?;
586527×
            for sig in sigs {
5874×
                self.store.put_signature(&h, sig)?;
588
            }
589527×
            imported.push(h);
590
        }
591717×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
592476×
            for d in &c.deps {
593289×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
594
                {
5953×
                    return fail(format!(
596
                        "change {} depends on {}, which is neither stored nor in the bundle",
5973×
                        h.short(12),
5983×
                        d.short(12)
599
                    ));
600286×
                }
601
            }
602473×
            let stored = self.store.put_change(c)?;
603473×
            if stored != h {
6040×
                return fail(format!(
605
                    "change {} is not the change the bundle names",
6060×
                    h.short(12)
607
                ));
608473×
            }
609473×
            for sig in sigs {
61027×
                self.store.put_signature(&h, sig)?;
611
            }
612473×
            imported.push(h);
613
        }
614714×
        if strict {
61537×
            for h in &imported {
61625×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6171×
                    return fail(format!(
618
                        "change {} is not authenticated by its author",
6191×
                        h.short(12)
620
                    ));
62124×
                }
622
            }
623677×
        }
624713×
        Ok(imported)
625718×
    }
626
627
    /// Verify a reference attestation against an update it claims to describe.
628
    /// `allow_equal` lets a client re-read the attestation it already has; a
629
    /// server receiving a push requires a strictly greater serial.
630
    /// A reference attestation signed by a delegate of an identity the
631
    /// rule lists is authorized as that identity (spec §14.5): the identity
632
    /// named the delegate with the `refs` scope, still in force at `at_ms`
633
    /// (the attestation's wall time), and the policy names the identity.
634
    /// Revoked keys authorize nothing either way.
63516×
    pub(crate) fn delegate_authorized(
63616×
        &self,
63716×
        p: &crate::policy::Policy,
63816×
        signer: &KeyId,
63916×
        reference: &str,
64016×
        at_ms: u64,
64116×
    ) -> bool {
64216×
        if p.is_revoked(signer) {
6431×
            return false;
64415×
        }
64515×
        let Some(rule) = p.rule_for(reference) else {
6460×
            return false;
647
        };
64816×
        rule.keys.iter().any(|k| {
64916×
            !p.is_revoked(k)
65016×
                && p.identity(k)
65116×
                    .cloned()
65216×
                    .or_else(|| self.store.get_identity(k).ok())
65316×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
65416×
        })
65516×
    }
656
657
    /// A lasting attestation (a tag) signed by a key the policy has since
658
    /// rotated away from (spec §14.2) is authorized as the key that
659
    /// succeeded it: a key the rule lists reaches the signer through
660
    /// `previous` links, and the attestation is dated (`at_ms`) before the
661
    /// signer's successor was made, so a superseded key makes nothing new.
662
    /// Revoked keys authorize nothing.
6636×
    pub(crate) fn predecessor_authorized(
6646×
        &self,
6656×
        p: &crate::policy::Policy,
6666×
        signer: &KeyId,
6676×
        reference: &str,
6686×
        at_ms: u64,
6696×
    ) -> bool {
6706×
        if p.is_revoked(signer) {
6710×
            return false;
6726×
        }
6736×
        let Some(rule) = p.rule_for(reference) else {
6740×
            return false;
675
        };
6767×
        let identity = |k: &KeyId| {
6777×
            p.identity(k)
6787×
                .cloned()
6797×
                .or_else(|| self.store.get_identity(k).ok())
6807×
        };
6816×
        rule.keys.iter().any(|k| {
6826×
            if p.is_revoked(k) {
6830×
                return false;
6846×
            }
6856×
            let mut cur = identity(k);
6866×
            for _ in 0..32 {
6877×
                let Some(id) = cur else {
6880×
                    return false;
689
                };
6901×
                match id.previous {
6916×
                    Some(prev) if prev == *signer => return at_ms < id.created,
6921×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
6931×
                    _ => return false,
694
                }
695
            }
6960×
            false
6976×
        })
6986×
    }
699
700105×
    fn check_ref_attest(
701105×
        &self,
702105×
        sa: &SignedAttest,
703105×
        name: &str,
704105×
        old_state: &ObjectRef,
705105×
        new_state: &ObjectRef,
706105×
        last_serial: Option<u64>,
707105×
        allow_equal: bool,
708105×
    ) -> std::result::Result<u64, String> {
709
        let AttestBody::Ref {
710105×
            name: n,
711105×
            old_state: o,
712105×
            new_state: nw,
713105×
            serial,
714105×
        } = &sa.attest.body
715
        else {
7160×
            return Err("attestation is not a ref attestation".into());
717
        };
718105×
        if n != name || o != old_state || nw != new_state {
7191×
            return Err("attestation does not describe this update".into());
720104×
        }
721104×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7220×
            return Err("attestation is for a different repository".into());
723104×
        }
724104×
        if let Some(last) = last_serial {
72564×
            if *serial < last || (*serial == last && !allow_equal) {
7261×
                return Err(format!(
7271×
                    "attestation serial {serial} is not greater than the last seen {last}"
7281×
                ));
72963×
            }
73040×
        }
731103×
        let r = sa.attest.hash();
732103×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
733103×
        let id = self
734103×
            .store
735103×
            .get_identity(&sig.key)
736103×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
737103×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
738103×
        Ok(*serial)
739105×
    }
740
741
    /// Accept a push (spec §16.4). Without a trust policy every repository
742
    /// is unverified, so unsigned changes and unattested updates are accepted;
743
    /// attestations that are present must still be valid. With a policy,
744
    /// every change and update is checked against it. A newer policy in the
745
    /// push is applied first when it is signed by the current roots.
746282×
    pub fn receive_push(
747282×
        &self,
748282×
        bundle: Bundle,
749282×
        updates: Vec<RefUpdate>,
750282×
        policy: Option<SignedPolicy>,
751282×
        tags: Vec<crate::protocol::TagRef>,
752282×
    ) -> Result<Vec<RefResult>> {
753282×
        Ok(self
754282×
            .receive_push_report(bundle, updates, policy, tags)?
755
            .results)
756282×
    }
757
758
    /// `receive_push` with what a host wants to log: each accepted
759
    /// reference's old and new state and heads, and the changes this push
760
    /// stored (hub spec §6.12).
761320×
    pub fn receive_push_report(
762320×
        &self,
763320×
        bundle: Bundle,
764320×
        updates: Vec<RefUpdate>,
765320×
        policy: Option<SignedPolicy>,
766320×
        tags: Vec<crate::protocol::TagRef>,
767320×
    ) -> Result<PushReport> {
768320×
        let mut report = PushReport::default();
769320×
        let results = &mut report.results;
770320×
        if let Some(sp) = policy {
77123×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
77221×
                Ok(()) => {
77321×
                    results.push(RefResult {
77421×
                        name: "policy".into(),
77521×
                        ok: true,
77621×
                        reason: format!("serial {}", sp.policy.serial),
77721×
                    });
77821×
                }
7792×
                Err(e) => {
7802×
                    results.push(RefResult {
7812×
                        name: "policy".into(),
7822×
                        ok: false,
7832×
                        reason: e,
7842×
                    });
7852×
                    for u in updates {
7860×
                        results.push(RefResult {
7870×
                            name: u.name,
7880×
                            ok: false,
7890×
                            reason: "policy update was rejected".into(),
7900×
                        });
7910×
                    }
7922×
                    return Ok(report);
793
                }
794
            }
795297×
        }
796318×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
797
        // A push of objects alone (one batch of a long history, oxygen#95)
798
        // names no reference: its outcome is reported as `objects`.
799318×
        let objects_only = updates.is_empty() && tags.is_empty();
800318×
        match self.import_bundle(&bundle, policy.is_some()) {
801315×
            Ok(imported) => {
802315×
                if objects_only {
8037×
                    results.push(RefResult {
8047×
                        name: OBJECTS_RESULT.into(),
8057×
                        ok: true,
8067×
                        reason: format!("{} changes stored", imported.len()),
8077×
                    });
808308×
                }
809315×
                report.imported = imported;
810
            }
8113×
            Err(e) => {
8123×
                if objects_only {
8130×
                    results.push(RefResult {
8140×
                        name: OBJECTS_RESULT.into(),
8150×
                        ok: false,
8160×
                        reason: e.to_string(),
8170×
                    });
8183×
                }
8193×
                for u in updates {
8203×
                    results.push(RefResult {
8213×
                        name: u.name,
8223×
                        ok: false,
8233×
                        reason: e.to_string(),
8243×
                    });
8253×
                }
8263×
                return Ok(report);
827
            }
828
        }
829315×
        let (op_ref, op) = self.head_op()?;
830315×
        let mut view = op.view.clone();
831315×
        let mut names = Vec::new();
832315×
        for u in updates {
833306×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
834306×
            let (ok, reason) = match outcome {
835282×
                Ok(()) => (true, String::new()),
83624×
                Err(e) => (false, e),
837
            };
838306×
            if ok {
839282×
                names.push(u.name.clone());
840282×
                let heads = self
841282×
                    .store
842282×
                    .get_state(&u.new_state)
843282×
                    .map(|s| s.heads)
844282×
                    .unwrap_or_default();
845282×
                report.updated.push(RefUpdated {
846282×
                    name: u.name.clone(),
847282×
                    old_state: u.old_state,
848282×
                    new_state: u.new_state,
849282×
                    heads,
850282×
                });
85124×
            }
852306×
            results.push(RefResult {
853306×
                name: u.name,
854306×
                ok,
855306×
                reason,
856306×
            });
857
        }
858315×
        for t in &tags {
8598×
            let name = format!("tags/{}", t.name);
8608×
            let new = !view.tags.contains_key(&t.name);
8618×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
862
                Ok(()) => {
863
                    // A tag new here is an update too, so a hub can start
864
                    // its pipeline's tag jobs (oxygenflow#24); one it
865
                    // already had, sent again, is not.
8666×
                    if new {
8676×
                        report.updated.push(RefUpdated {
8686×
                            name: name.clone(),
8696×
                            old_state: ObjectRef::ZERO,
8706×
                            new_state: t.state,
8716×
                            heads: t.heads.clone(),
8726×
                        });
8736×
                    }
8746×
                    names.push(name.clone());
8756×
                    results.push(RefResult {
8766×
                        name,
8776×
                        ok: true,
8786×
                        reason: String::new(),
8796×
                    });
880
                }
8812×
                Err(e) => results.push(RefResult {
8822×
                    name,
8832×
                    ok: false,
8842×
                    reason: e,
8852×
                }),
886
            }
887
        }
888315×
        if !names.is_empty() {
889282×
            self.record_op(
890282×
                &[op_ref],
891282×
                &format!("push received: {}", names.join(" ")),
892282×
                view,
8933×
            )?;
89433×
        }
895312×
        Ok(report)
896320×
    }
897
898
    /// Check an update's attestation against the latest one for its
899
    /// reference and store it as the new latest. Failures say what was
900
    /// being done, for which reference, so a refused push can be diagnosed
901
    /// from its reason alone.
90281×
    fn record_update_attest(
90381×
        &self,
90481×
        u: &RefUpdate,
90581×
        sa: &SignedAttest,
90681×
    ) -> std::result::Result<(), String> {
90781×
        let name = &u.name;
90881×
        let last = self
90981×
            .latest_ref_attest(name)
91081×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
91181×
            .and_then(|(_, a)| match a.attest.body {
91253×
                AttestBody::Ref { serial, .. } => Some(serial),
9130×
                _ => None,
91453×
            });
91581×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
91679×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
91779×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
91878×
        for sig in &sa.sigs {
91978×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
920
        }
92178×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
92281×
    }
923
924
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
925
    /// at `old_state`, is never the bookmark a non-bare repository has
926
    /// checked out (a bare one's default is its host's to protect, see
927
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
928
    /// an attestation by a key that may update it.
929
    /// The deletion's attestation stays the bookmark's latest, so an older
930
    /// one cannot be replayed to bring it back.
9313×
    fn apply_deletion(
9323×
        &self,
9333×
        view: &mut View,
9343×
        u: &RefUpdate,
9353×
        policy: Option<&crate::policy::Policy>,
9363×
    ) -> std::result::Result<(), String> {
9373×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
9380×
            return Err(format!("no bookmark {:?} to delete", u.name));
939
        };
9403×
        if current != u.old_state {
9410×
            return Err("stale: the remote bookmark has moved; pull first".into());
9423×
        }
9433×
        if !self.is_bare() && u.name == self.config.bookmark {
9441×
            return Err(format!(
9451×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
9461×
                u.name
9471×
            ));
9482×
        }
9492×
        if let Some(p) = policy {
9500×
            let Some(sa) = &u.attestation else {
9510×
                return Err(format!(
9520×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
9530×
                    u.name
9540×
                ));
955
            };
9560×
            let signer = sa
9570×
                .sigs
9580×
                .first()
9590×
                .map(|s| s.key)
9600×
                .ok_or("attestation carries no signature")?;
961
            // Received now: the receiver's own clock is the trusted time.
9620×
            let now = Hlc::now().wall_ms;
9630×
            if !p.authorizes(&signer, &u.name)
9640×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
9650×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
966
            {
9670×
                return Err(format!(
9680×
                    "key {} may not delete {:?} under this repository's policy",
9690×
                    signer.short(12),
9700×
                    u.name
9710×
                ));
9720×
            }
9732×
        }
9742×
        if let Some(sa) = &u.attestation {
9751×
            self.record_update_attest(u, sa)?;
9761×
        }
9772×
        view.bookmarks.remove(&u.name);
9782×
        Ok(())
9793×
    }
980
981306×
    fn apply_update(
982306×
        &self,
983306×
        view: &mut View,
984306×
        u: &RefUpdate,
985306×
        policy: Option<&crate::policy::Policy>,
986306×
    ) -> std::result::Result<(), String> {
987306×
        if u.name == "policy" {
9880×
            return Err(
9890×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
9900×
            );
991306×
        }
992306×
        let empty = self
993306×
            .store
994306×
            .put_state(&StateObject::new(vec![]))
995306×
            .map_err(|e| e.to_string())?;
996306×
        if u.new_state.is_zero() {
9973×
            return self.apply_deletion(view, u, policy);
998303×
        }
999303×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1000303×
        if current != u.old_state {
10017×
            return Err("stale: the remote bookmark has moved; pull first".into());
1002296×
        }
1003296×
        let new_state = self
1004296×
            .store
1005296×
            .get_state(&u.new_state)
1006296×
            .map_err(|_| "new state object is missing".to_string())?;
1007609×
        for h in &new_state.heads {
1008609×
            if !self.store.has(h) {
10091×
                return Err(format!("head {} is missing", h.short(12)));
1010608×
            }
1011
        }
1012295×
        if !u.force {
1013294×
            let old_heads = self
1014294×
                .store
1015294×
                .get_state(&current)
1016294×
                .map_err(|e| e.to_string())?
1017
                .heads;
1018294×
            let closure = self
1019294×
                .closure_in_store(&new_state.heads)
1020294×
                .map_err(|e| e.to_string())?;
1021337×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
10221×
                return Err(format!(
10231×
                    "not a fast-forward: current head {} would be dropped (use --force)",
10241×
                    h.short(12)
10251×
                ));
1026293×
            }
10271×
        }
1028294×
        if let Some(p) = policy {
102935×
            let Some(sa) = &u.attestation else {
10301×
                return Err(format!(
10311×
                    "{:?} requires a signed reference attestation under this repository's policy",
10321×
                    u.name
10331×
                ));
1034
            };
103534×
            let signer = sa
103634×
                .sigs
103734×
                .first()
103834×
                .map(|s| s.key)
103934×
                .ok_or("attestation carries no signature")?;
1040
            // Received now: the receiver's own clock is the trusted time.
104134×
            let now = Hlc::now().wall_ms;
104234×
            if !p.authorizes(&signer, &u.name)
104310×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
10448×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1045
            {
10467×
                return Err(format!(
10477×
                    "key {} may not update {:?} under this repository's policy",
10487×
                    signer.short(12),
10497×
                    u.name
10507×
                ));
105127×
            }
105227×
            let old_heads = self
105327×
                .store
105427×
                .get_state(&current)
105527×
                .map_err(|e| e.to_string())?
1056
                .heads;
105727×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1058259×
        }
1059286×
        if let Some(sa) = &u.attestation {
106080×
            self.record_update_attest(u, sa)?;
1061206×
        }
1062280×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1063280×
        Ok(())
1064306×
    }
1065
1066
    // ------------------------------------------------------------ client side
1067
1068992×
    fn remote_url(&self, name: &str) -> Result<String> {
1069992×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
10703×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
10713×
            RepoError::Msg(match names.as_slice() {
10723×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
10731×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1074
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
10751×
                    names.join(", "),
10761×
                    names[0],
10771×
                    names[0]
1078
                ),
10790×
                _ => format!(
1080
                    "no remote named {name:?}; this repository has {}",
10810×
                    names.join(", ")
1082
                ),
1083
            })
10843×
        })
1085992×
    }
1086
1087
    /// Refuse a remote that is another repository. An **unbound** remote
1088
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1089
    /// for pushes, which bind it to this repository's id (spec §16.1).
1090738×
    fn check_remote_id(
1091738×
        &self,
1092738×
        remote: &dyn crate::protocol::Remote,
1093738×
        remote_name: &str,
1094738×
        allow_unbound: bool,
1095738×
    ) -> Result<()> {
1096738×
        let theirs = remote.repo_id()?;
1097737×
        if theirs == self.id()? {
1098714×
            return Ok(());
109923×
        }
110023×
        if theirs == crate::protocol::UNBOUND_ID {
110120×
            if allow_unbound {
110219×
                return Ok(());
11031×
            }
11041×
            return fail(format!(
1105
                "remote {remote_name:?} is empty and unbound: push to it first"
1106
            ));
11073×
        }
11083×
        fail(format!(
1109
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1110
        ))
1111738×
    }
1112
1113
    /// Credentials and trust for a remote: `remote.<name>.token` and
1114
    /// `remote.<name>.ca`, else the defaults for its URL
1115
    /// ([`Repo::fill_credentials`]).
11161009×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
11171009×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
11181009×
        let mut options = RemoteOptions {
11191009×
            repo_id: self.id().ok(),
11201009×
            token: self.config.remote_tokens.get(name).cloned(),
11211009×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
11221009×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
11231009×
            ..RemoteOptions::default()
11241009×
        };
11251009×
        self.fill_credentials(&url, &mut options);
11261009×
        options
11271009×
    }
1128
1129
    /// The user's credential store (`credentials.toml` beside the user
1130
    /// configuration file).
11311028×
    pub fn credentials(&self) -> crate::credentials::Credentials {
11321028×
        crate::credentials::Credentials::at(
11331028×
            self.user_config
11341028×
                .parent()
11351028×
                .map(Path::to_path_buf)
11361028×
                .unwrap_or_else(default_home),
1137
        )
11381028×
    }
1139
1140
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1141
    /// then the user's credential store for its hub, then a remote on the
1142
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1143
    /// When the token is not this remote's own or the environment's, the
1144
    /// other tokens enclosing checkouts hold for the hub are kept to try
1145
    /// if it is refused: a stale stored login must not hide a parent's
1146
    /// good token (oxygen#112).
11471029×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
11481029×
        if options.token.is_some() && options.ca.is_some() {
11491×
            return;
11501028×
        }
11511028×
        let explicit =
11521028×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
11531028×
        let stored = self.credentials().options_for(url);
11541028×
        options.token = options.token.take().or(stored.token);
11551028×
        options.ca = options.ca.take().or(stored.ca);
11561028×
        let enclosing = self.enclosing_credentials(url);
11571028×
        if options.token.is_none() {
11581018×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
115910×
        }
11601028×
        if options.ca.is_none() {
1161961×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
116267×
        }
11631028×
        if !explicit {
11641021×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
11655×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
11662×
                    options.fallback_tokens.push(t);
11673×
                }
1168
            }
11697×
        }
11701029×
    }
1171
1172
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1173
    /// checkouts, nearest first.
11741028×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
11751028×
        let mut out = Vec::new();
11761028×
        let Some(hub) = crate::credentials::hub_of(url) else {
1177892×
            return out;
1178
        };
1179136×
        let mut at = self.root.parent();
1180552×
        while let Some(dir) = at {
1181416×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
11820×
                break;
1183
            };
1184416×
            for (key, remote_url) in &cfg {
118515×
                let Some(name) = key
118615×
                    .strip_prefix("remote.")
118715×
                    .and_then(|k| k.strip_suffix(".url"))
1188
                else {
11897×
                    continue;
1190
                };
11918×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
11921×
                    continue;
11937×
                }
11947×
                out.push((
11957×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
11967×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
11977×
                ));
1198
            }
1199416×
            at = dir.parent();
1200
        }
1201136×
        out
12021028×
    }
1203
1204
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1205
    /// no changes and no reference updates, which the receiver stores.
12060×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
12070×
        let remote = self.open_named_remote(remote_name)?;
12080×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
12090×
        let mut bundle = Bundle::default();
12100×
        for r in seals {
12110×
            let attest = self.store.get_attest(r)?;
12120×
            let sigs = self.store.signatures(r)?;
12130×
            bundle
12140×
                .attests
12150×
                .push(crate::protocol::SignedAttest { attest, sigs });
1216
        }
12170×
        let results = remote.push(bundle, vec![], None, vec![])?;
12180×
        if let Some(r) = results.iter().find(|r| !r.ok) {
12190×
            return fail(format!("{}: {}", r.name, r.reason));
12200×
        }
12210×
        Ok(())
12220×
    }
1223
1224
    /// The remote whose URL starts with `base` (a hub), if configured.
12254×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
12264×
        let base = base.trim_end_matches('/');
12274×
        self.config
12284×
            .remotes
12294×
            .iter()
12304×
            .find(|(_, url)| url.trim_end_matches('/') == base)
12314×
            .map(|(name, _)| name.clone())
12324×
    }
1233
1234
    /// Open a remote by name or, failing that, by URL with the default
1235
    /// credentials (see [`Repo::credentials_for`]).
12360×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
12370×
        if let Some(name) = self.remote_for_url(url) {
12380×
            return Ok((name.clone(), self.open_named_remote(&name)?));
12390×
        }
12400×
        let options = RemoteOptions {
12410×
            repo_id: self.id().ok(),
12420×
            ..self.credentials_for(url)
12430×
        };
12440×
        Ok((url.to_string(), open_remote(url, &options)?))
12450×
    }
1246
1247
    /// Credentials for a URL: those of the configured remote with that
1248
    /// URL, else the environment's.
12494×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
12504×
        match self.remote_for_url(url) {
12514×
            Some(name) => self.remote_options(&name),
12520×
            None => RemoteOptions {
12530×
                repo_id: self.id().ok(),
12540×
                ..self.credentials_for(url)
12550×
            },
1256
        }
12574×
    }
1258
1259992×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1260992×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1261992×
    }
1262
1263109×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1264109×
        self.oxy
1265109×
            .join("remotes")
1266109×
            .join(remote)
1267109×
            .join(format!("{bookmark}.serial"))
1268109×
    }
1269
127024×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
127124×
        fs::read_to_string(self.serial_path(remote, bookmark))
127224×
            .ok()
127324×
            .and_then(|s| s.trim().parse().ok())
127424×
    }
1275
127685×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
127785×
        let p = self.serial_path(remote, bookmark);
127885×
        fs::create_dir_all(p.parent().unwrap())?;
127985×
        write_atomic(&p, serial.to_string().as_bytes())
128085×
    }
1281
1282394×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1283394×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1284394×
    }
1285
1286
    /// The highest policy serial `remote` has ever presented.
1287360×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1288360×
        fs::read_to_string(self.policy_serial_path(remote))
1289360×
            .ok()
1290360×
            .and_then(|s| s.trim().parse().ok())
1291360×
    }
1292
129334×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
129434×
        let p = self.policy_serial_path(remote);
129534×
        fs::create_dir_all(p.parent().unwrap())?;
129634×
        write_atomic(&p, serial.to_string().as_bytes())
129734×
    }
1298
129927×
    fn lazy_dir(&self) -> PathBuf {
130027×
        self.oxy.join("lazy")
130127×
    }
1302
1303
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
13044×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
13054×
        fs::create_dir_all(self.lazy_dir())?;
13064×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
13074×
    }
1308
1309
    /// Which remote promised an absent blob, if any.
131015×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
131115×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
131215×
            .ok()
131315×
            .map(|s| s.trim().to_string())
131415×
    }
1315
1316
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
13174×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
13184×
        let Some(remote_name) = self.lazy_remote(blob) else {
13190×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1320
        };
13214×
        let remote = self.open_named_remote(&remote_name)?;
13224×
        let objects = remote.objects(&[*blob])?;
13239×
        for (ty, body) in objects {
13249×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
13259×
                self.store.put(ty, &body)?;
13260×
            }
1327
        }
13284×
        if !self.store.has(blob) {
13290×
            return fail(format!(
1330
                "{remote_name} did not send blob {}",
13310×
                blob.short(12)
1332
            ));
13334×
        }
13344×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
13354×
        Ok(())
13364×
    }
1337
1338
    /// After importing from `remote`, record every blob the changes reference
1339
    /// that the store lacks as lazily available from that remote.
13404×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
13414×
        let mut n = 0;
13424×
        for h in changes {
13434×
            let c = self.store.get_change(h)?;
134413×
            for e in &c.edits {
134513×
                if let Edit::Replace { old, new, .. } = e {
13466×
                    for b in [old, new].into_iter().flatten() {
13476×
                        if !self.store.has(b) {
13484×
                            self.register_lazy(b, remote)?;
13494×
                            n += 1;
13502×
                        }
1351
                    }
13527×
                }
1353
            }
1354
        }
13554×
        Ok(n)
13564×
    }
1357
1358
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1359360×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1360360×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1361485×
        for st in view
1362360×
            .bookmarks
1363360×
            .values()
1364360×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1365
        {
1366485×
            if let Ok(s) = self.store.get_state(st) {
1367485×
                have.extend(s.heads);
1368485×
            }
1369
        }
1370360×
        have.extend(view.workspaces.values().copied());
1371360×
        Ok(have.into_iter().collect())
1372360×
    }
1373
1374
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1375366×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1376366×
        let remote = self.open_named_remote(remote_name)?;
1377363×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1378361×
        let resp = remote.refs()?;
1379
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1380
        // and signed by roots we trust, or on first contact. A remote that
1381
        // once presented a policy may never present none or an older one:
1382
        // that is a downgrade. A remote that never presented one is
1383
        // unverified, and this fetch is checked only as far as possible.
1384360×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1385360×
        let seen = self.remote_policy_serial(remote_name);
1386360×
        let mut unverified = false;
1387360×
        match &resp.policy {
138813×
            Some(sp) => {
138913×
                if seen.is_some_and(|s| sp.policy.serial < s) {
13900×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
139113×
                }
13926×
                match &local_policy {
13936×
                    Some(l) if sp.policy.serial < l.serial => {}
13946×
                    Some(l) if sp.policy.serial == l.serial => {
13952×
                        if sp.policy.hash() != l.hash() {
13960×
                            return fail(format!(
1397
                                "{remote_name} presents a different policy with the same serial {}",
1398
                                l.serial
1399
                            ));
14002×
                        }
1401
                    }
1402
                    _ => {
140311×
                        self.adopt_policy_chain(
140411×
                            &resp.history,
140511×
                            sp,
140611×
                            &format!("oxy fetch {remote_name}"),
1407
                        )
140811×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1409
                    }
1410
                }
141113×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1412
            }
1413
            None => {
1414347×
                if seen.is_some() {
14150×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1416347×
                }
1417347×
                unverified = true;
1418
            }
1419
        }
1420360×
        let policy = if unverified {
1421347×
            None
1422
        } else {
142313×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1424
        };
1425360×
        let (op_ref, op) = self.head_op()?;
1426360×
        let mut view = op.view.clone();
1427360×
        let have = self.known_heads(&view)?;
1428360×
        let mut report = Vec::new();
1429360×
        let max_blob = self.config.max_blob;
1430367×
        for r in resp.refs {
1431367×
            let needed = {
1432367×
                let _t = crate::timing::phase("fetch: negotiate");
1433367×
                remote.negotiate(&have, &r.heads)?
1434
            };
1435367×
            let bundle = {
1436367×
                let _t = crate::timing::phase("fetch: bundle");
1437367×
                remote.fetch(&needed, max_blob)?
1438
            };
1439
            // Changes are not individually re-verified here: the bookmark's
1440
            // attestation (checked below) binds its whole state, and the
1441
            // receiver of the push verified the added changes at that time.
1442367×
            let imported = {
1443367×
                let _t = crate::timing::phase("fetch: import");
1444367×
                self.import_bundle(&bundle, false)?
1445
            };
1446367×
            if max_blob.is_some() {
14474×
                self.register_missing_blobs(&imported, remote_name)?;
1448363×
            }
1449527×
            for h in &r.heads {
1450527×
                if !self.store.has(h) {
14510×
                    return fail(format!("remote did not send head {}", h.short(12)));
1452527×
                }
1453
            }
1454367×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1455367×
            if state != r.state {
14560×
                return fail(format!(
1457
                    "remote state {} does not match its heads",
14580×
                    r.state.short(12)
1459
                ));
1460367×
            }
1461367×
            if let Some(p) = &policy {
146213×
                let Some(sa) = &r.attestation else {
14630×
                    return fail(format!(
1464
                        "{remote_name}/{} has no attestation, which its policy requires",
1465
                        r.name
1466
                    ));
1467
                };
146813×
                let signer = sa
146913×
                    .sigs
147013×
                    .first()
147113×
                    .map(|s| s.key)
147213×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1473
                // Until the host countersigns when it accepted the update,
1474
                // the attestation's own time is all a fetch has.
147513×
                if !p.authorizes(&signer, &r.name)
14763×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
14773×
                    && !self.certified_authorized(
14783×
                        p,
14793×
                        &signer,
14803×
                        &r.name,
14813×
                        Scope::REFS,
14823×
                        sa.attest.hlc.wall_ms,
14833×
                    )
1484
                {
14850×
                    return fail(format!(
1486
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1487
                        r.name,
14880×
                        signer.short(12)
1489
                    ));
149013×
                }
1491354×
            }
1492367×
            if let Some(sa) = &r.attestation {
1493
                let AttestBody::Ref {
149424×
                    old_state,
149524×
                    new_state,
1496
                    ..
149724×
                } = &sa.attest.body
1498
                else {
14990×
                    return fail("remote sent a non-ref attestation for a bookmark");
1500
                };
150124×
                let (old_state, new_state) = (*old_state, *new_state);
150224×
                let serial = self
150324×
                    .check_ref_attest(
150424×
                        sa,
150524×
                        &r.name,
150624×
                        &old_state,
150724×
                        &new_state,
150824×
                        self.last_seen_serial(remote_name, &r.name),
1509
                        true,
1510
                    )
151124×
                    .map_err(|e| {
15120×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
15130×
                    })?;
151424×
                if new_state != r.state {
15150×
                    return fail(format!(
1516
                        "attestation for {}/{} does not cover its current state",
1517
                        remote_name, r.name
1518
                    ));
151924×
                }
152024×
                let ar = self.store.put_attest(&sa.attest)?;
152124×
                for sig in &sa.sigs {
152224×
                    self.store.put_signature(&ar, sig)?;
1523
                }
152424×
                self.record_serial(remote_name, &r.name, serial)?;
1525343×
            }
1526367×
            view.remotes
1527367×
                .entry(remote_name.to_string())
1528367×
                .or_default()
1529367×
                .insert(r.name.clone(), state);
1530367×
            report.push((r.name, r.heads, imported.len()));
1531
        }
1532360×
        let mut new_tags = 0;
1533360×
        for t in &resp.tags {
153413×
            if view.tags.contains_key(&t.name) {
15354×
                continue;
15369×
            }
1537
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
15389×
            let missing: Vec<ChangeHash> = t
15399×
                .heads
15409×
                .iter()
15419×
                .filter(|h| !self.store.has(h))
15429×
                .copied()
15439×
                .collect();
15449×
            if !missing.is_empty() {
15450×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
15460×
                let bundle = remote.fetch(&needed, max_blob)?;
15470×
                self.import_bundle(&bundle, false)?;
15489×
            }
15499×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
15509×
            self.adopt_tag(&mut view, t, policy.as_ref())
15519×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
15529×
            new_tags += 1;
1553
        }
1554360×
        if view != op.view {
1555350×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
155610×
        }
1557360×
        let _ = self.run_hook(
1558360×
            "post-fetch",
1559360×
            &format!(
1560
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1561360×
                json_str(remote_name),
1562367×
                json_array(report.iter().map(|(n, heads, _)| format!(
1563
                    "{{\"name\":{},\"heads\":{}}}",
1564367×
                    json_str(n),
1565527×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1566
                )))
1567
            ),
1568
        );
1569360×
        Ok(FetchReport {
1570360×
            refs: report,
1571360×
            unverified,
1572360×
            new_tags,
1573360×
        })
1574366×
    }
1575
1576
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1577
    /// the changes within `depth` steps of its heads, and the boundary below.
15781×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
15791×
        let remote = self.open_named_remote(remote_name)?;
15801×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
15811×
        let resp = remote.refs()?;
15821×
        let bookmark = self.config.bookmark.clone();
15831×
        if let Some(sp) = &resp.policy {
15840×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
15850×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
15860×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
15871×
        }
15881×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
15890×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1590
        };
15911×
        if r.heads.is_empty() {
15920×
            return Ok(0);
15931×
        }
1594
        // Base: the remote's checkpoint of exactly these heads.
15951×
        let cp_bundle = remote.checkpoint(&r.heads)?;
15961×
        let mut cp_ref = None;
15973×
        for (ty, body) in &cp_bundle.objects {
15983×
            let put = self.store.put(*ty, body)?;
15993×
            if *ty == ObjectType::Checkpoint {
16001×
                cp_ref = Some(put);
16012×
            }
1602
        }
16031×
        let Some(cp_ref) = cp_ref else {
16040×
            return fail(format!("{remote_name} sent no checkpoint"));
1605
        };
16061×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1607
        // History window.
16081×
        let wanted = remote.shallow(&r.heads, depth)?;
16091×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
16101×
        let imported = self.import_bundle_shallow(&bundle, false)?;
16111×
        if self.config.max_blob.is_some() {
16120×
            self.register_missing_blobs(&imported, remote_name)?;
16131×
        }
16141×
        self.refresh_boundary(&imported)?;
16151×
        if let Some(sa) = &r.attestation {
16160×
            let ar = self.store.put_attest(&sa.attest)?;
16170×
            for sig in &sa.sigs {
16180×
                self.store.put_signature(&ar, sig)?;
1619
            }
16200×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
16210×
                self.record_serial(remote_name, &r.name, serial)?;
16220×
            }
16231×
        }
16241×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
16251×
        let (op_ref, op) = self.head_op()?;
16261×
        let mut view = op.view.clone();
16271×
        view.remotes
16281×
            .entry(remote_name.to_string())
16291×
            .or_default()
16301×
            .insert(r.name.clone(), state);
16311×
        self.record_op(
16321×
            &[op_ref],
16331×
            &format!("oxy fetch {remote_name} --depth {depth}"),
16341×
            view,
16350×
        )?;
16361×
        Ok(imported.len())
16371×
    }
1638
1639
    /// Fetch, then take the union of the local bookmark's state with the
1640
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1641108×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1642108×
        let _wc = self.lock_working_copy()?;
1643108×
        self.fetch(remote_name)?;
1644105×
        let (op_ref, op) = self.head_op()?;
1645105×
        let current = self.config.bookmark.clone();
1646105×
        let mut local_current = self.heads_of(&op.view, &current)?;
1647105×
        local_current.sort();
1648105×
        let mut view = op.view.clone();
1649105×
        let mut current_heads = local_current.clone();
1650105×
        let mut changed = false;
1651105×
        let mut others = Vec::new();
1652105×
        let tracked = op
1653105×
            .view
1654105×
            .remotes
1655105×
            .get(remote_name)
1656105×
            .cloned()
1657105×
            .unwrap_or_default();
1658109×
        for (name, remote_state) in tracked {
1659
            // Every local bookmark tracks the remote's of the same name;
1660
            // the current one may be new here.
1661109×
            let local_state = op.view.bookmarks.get(&name).copied();
1662109×
            if local_state.is_none() && name != current {
16630×
                continue;
1664109×
            }
1665109×
            if local_state == Some(remote_state) {
16668×
                continue;
1667101×
            }
1668101×
            let local = self.heads_of(&op.view, &name)?;
1669101×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1670138×
            if remote_heads.iter().all(|h| local.contains(h)) {
16710×
                continue;
1672101×
            }
1673101×
            let mut all = local.clone();
1674101×
            all.extend(remote_heads);
1675101×
            let st = self.load_state_history(&all)?;
1676101×
            let mut heads = st.maximal(&all);
1677101×
            heads.sort();
1678101×
            let mut sorted_local = local;
1679101×
            sorted_local.sort();
1680101×
            if heads == sorted_local {
16811×
                continue;
1682100×
            }
1683100×
            view.bookmarks.insert(
1684100×
                name.clone(),
1685100×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1686
            );
1687100×
            if name == current {
168898×
                changed = true;
168998×
                current_heads = heads;
169098×
            } else {
16912×
                others.push(name);
16922×
            }
1693
        }
1694105×
        if changed || !others.is_empty() {
169599×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
16966×
        }
1697
        // The working copy follows its bookmark whenever nothing would be
1698
        // lost, also when this pull brought nothing new but it had been
1699
        // left behind (oxygen#89).
1700105×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1701
        Ok(PullReport {
1702105×
            heads: if changed {
170398×
                current_heads
1704
            } else {
17057×
                local_current
1706
            },
1707105×
            changed,
1708105×
            checked_out,
1709105×
            others,
1710
        })
1711108×
    }
1712
1713
    /// How many changes the working copy's bookmark has that its base
1714
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1715
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1716
    /// the bookmark or holds changes the bookmark lacks. History is read
1717
    /// only when the base and the bookmark's heads differ (oxygen#89).
17187×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
17197×
        let (_, wc) = self.working_copy()?;
17207×
        let mut base = wc.deps.clone();
17217×
        base.sort();
17227×
        let mut heads = self.bookmark_heads()?;
17237×
        heads.sort();
17247×
        if base == heads || heads.is_empty() {
17256×
            return Ok(None);
17261×
        }
17271×
        let state = self.load_state_history(&heads)?;
17281×
        if !base.iter().all(|h| state.contains(h)) {
17290×
            return Ok(None);
17301×
        }
17311×
        let had = if base.is_empty() {
17320×
            0
1733
        } else {
17341×
            self.load_state_history(&base)?.len()
1735
        };
17361×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
17377×
    }
1738
1739
    /// Bring the working copy to `heads`, the state of its bookmark
1740
    /// `bookmark`, when nothing would be lost: its base is part of that
1741
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1742
    /// with uncommitted work, the work comes along when the new changes
1743
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1744
    /// it followed only from exactly the bookmark's old heads, so a working
1745
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1746
    /// or a pull from another workspace) never caught up, and nothing said
1747
    /// so (oxygen#74, #89). Returns whether it moved.
1748105×
    pub fn follow_bookmark(
1749105×
        &self,
1750105×
        heads: &[ChangeHash],
1751105×
        bookmark: &str,
1752105×
        command: &str,
1753105×
    ) -> Result<bool> {
1754105×
        let snap = self.snapshot(command)?;
1755105×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1756105×
        let mut base = snap.base.maximal(&snap.wc.deps);
1757105×
        base.sort();
1758105×
        let mut target = heads.to_vec();
1759105×
        target.sort();
1760105×
        if base == target {
17616×
            return Ok(false);
176299×
        }
176399×
        let state = self.load_state_history(heads)?;
1764182×
        if !base.iter().all(|h| state.contains(h)) {
1765
            // The working copy holds changes the bookmark lacks: not ours to move.
17660×
            return Ok(false);
176799×
        }
176899×
        if clean {
176999×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
177099×
            Ok(true)
1771
        } else {
17720×
            Ok(self
17730×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
17740×
                .is_ok())
1775
        }
1776105×
    }
1777
1778
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1779
    /// changes and attesting the reference when a key is available.
1780
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1781
    /// state, attested when we have an identity. The local bookmark, if
1782
    /// any, is kept; only the remote-tracking entry goes.
17835×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
17845×
        let remote = self.open_named_remote(remote_name)?;
17855×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
17865×
        let resp = remote.refs()?;
17877×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
17881×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1789
        };
17904×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
17910×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
17924×
        }
17934×
        let attestation = match self.secret_key()? {
17942×
            Some(_) => Some(self.sign_attest(&Attest {
17952×
                repo: self.id()?,
17962×
                hlc: Hlc::now(),
17972×
                body: AttestBody::Ref {
17982×
                    name: bookmark.to_string(),
17992×
                    old_state: r.state,
18002×
                    new_state: ObjectRef::ZERO,
18012×
                    serial: r.last_serial.unwrap_or(0) + 1,
18022×
                },
18030×
            })?),
18042×
            None => None,
1805
        };
18064×
        let results = remote.push(
18074×
            Bundle::default(),
18084×
            vec![RefUpdate {
18094×
                name: bookmark.to_string(),
18104×
                old_state: r.state,
18114×
                new_state: ObjectRef::ZERO,
18124×
                force: true,
18134×
                attestation,
18144×
            }],
18154×
            None,
18164×
            vec![],
18170×
        )?;
18184×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
18192×
            let (op_ref, op) = self.head_op()?;
18202×
            let mut view = op.view.clone();
18212×
            if let Some(m) = view.remotes.get_mut(remote_name) {
18222×
                m.remove(bookmark);
18232×
            }
18242×
            self.record_op(
18252×
                &[op_ref],
18262×
                &format!("oxy push {remote_name} --delete {bookmark}"),
18272×
                view,
18280×
            )?;
18292×
        }
18304×
        Ok(results)
18315×
    }
1832
1833
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1834
    /// repository's config (its URL, token, CA and store settings), its
1835
    /// tracking bookmarks in the view, and a store remote's mirror under
1836
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
18373×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
18383×
        if !self.config.remotes.contains_key(name) {
18391×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
18402×
        }
18412×
        let prefix = format!("remote.{name}.");
18422×
        let keys: Vec<String> = self
18432×
            .config
18442×
            .repo_layer()
18452×
            .keys()
18464×
            .filter(|k| k.starts_with(&prefix))
18472×
            .cloned()
18482×
            .collect();
18493×
        for k in keys {
18503×
            self.config.set(&k, "")?;
1851
        }
18522×
        self.config.remotes.remove(name);
18532×
        self.save_config()?;
18542×
        let (op_ref, op) = self.head_op()?;
18552×
        if op.view.remotes.contains_key(name) {
18561×
            let mut view = op.view.clone();
18571×
            view.remotes.remove(name);
18581×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
18591×
        }
18602×
        let mirror = self.oxy.join("remotes").join(name);
18612×
        if mirror.is_dir() {
18620×
            fs::remove_dir_all(&mirror)?;
18632×
        }
18642×
        Ok(())
18653×
    }
1866
1867
    /// `changes`, in dependency order, cut into batches of about
1868
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1869
    /// There is always one, perhaps empty.
1870283×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1871283×
        let blob_len = |r: &ObjectRef| -> u64 {
187229×
            self.store
187329×
                .get_typed(r, ObjectType::Blob)
187429×
                .ok()
187529×
                .and_then(|b| Blob::decode(&b).ok())
187629×
                .map_or(0, |b| b.length)
187729×
        };
1878283×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1879396×
        for h in changes {
1880396×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1881396×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1882396×
            let mut weight = raw.len() as u64;
1883508×
            for t in &texts {
1884508×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
188526×
                    weight += blob_len(r);
1886482×
                }
1887
            }
1888651×
            for e in &c.edits {
18893×
                if let Edit::Replace { new: Some(b), .. } = e {
18903×
                    weight += blob_len(b);
1891648×
                }
1892
            }
1893396×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
18945×
                out.push(std::mem::take(&mut batch));
18955×
                bytes = 0;
1896391×
            }
1897396×
            batch.push(*h);
1898396×
            bytes += weight;
1899
        }
1900283×
        out.push(batch);
1901283×
        Ok(out)
1902283×
    }
1903
1904354×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1905354×
        let bookmark = self.config.bookmark.clone();
1906354×
        self.push_bookmark(remote_name, &bookmark, force)
1907354×
    }
1908
1909
    /// `push` for a named bookmark (`oxy push -b NAME`).
1910362×
    pub fn push_bookmark(
1911362×
        &self,
1912362×
        remote_name: &str,
1913362×
        bookmark: &str,
1914362×
        force: bool,
1915362×
    ) -> Result<Vec<RefResult>> {
1916362×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1917362×
    }
1918
1919
    /// `push_bookmark`, saying how a long push is going: one line per
1920
    /// batch sent (oxygen#95).
1921370×
    pub fn push_bookmark_with(
1922370×
        &self,
1923370×
        remote_name: &str,
1924370×
        bookmark: &str,
1925370×
        force: bool,
1926370×
        progress: crate::store::Progress,
1927370×
    ) -> Result<Vec<RefResult>> {
1928370×
        let (op_ref, op) = self.head_op()?;
1929370×
        if !op.view.bookmarks.contains_key(bookmark) {
19300×
            return fail(format!("no bookmark {bookmark}"));
1931370×
        }
1932370×
        let bookmark = bookmark.to_string();
1933370×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1934
        // pre-push hook: may veto before the remote is contacted.
1935370×
        self.run_hook(
1936370×
            "pre-push",
1937370×
            &format!(
1938
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1939370×
                json_str(remote_name),
1940370×
                json_str(&bookmark),
1941768×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1942
            ),
19431×
        )?;
1944369×
        let remote = self.open_named_remote(remote_name)?;
1945369×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1946366×
        let resp = remote.refs()?;
1947366×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1948366×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1949366×
        let policy_to_send = match (&local_policy, &resp.policy) {
195024×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
19519×
            (Some(l), None) => Some(l.clone()),
195212×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
19531×
                return fail(format!(
1954
                    "{remote_name} has a newer policy (serial {}); fetch first",
1955
                    r.policy.serial
1956
                ));
1957
            }
1958344×
            _ => None,
1959
        };
1960365×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1961365×
        if remote_has_policy && self.secret_key()?.is_none() {
19621×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1963364×
        }
1964364×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1965364×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1966364×
            .tag_refs()?
1967364×
            .into_iter()
1968364×
            .filter(|t| !remote_tags.contains(&t.name))
1969364×
            .collect();
1970364×
        let refs = resp.refs;
1971364×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1972364×
        let (remote_state, remote_heads, last_serial) =
1973364×
            match refs.iter().find(|r| r.name == bookmark) {
1974347×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
197517×
                None => (empty, vec![], None),
1976
            };
1977364×
        let new_state = self
1978364×
            .store
1979364×
            .put_state(&StateObject::new(local_heads.clone()))?;
1980
        // A push that carries a policy re-attests the bookmark even when its
1981
        // state is unchanged, so the current attestation is always by a key
1982
        // the current policy authorizes (a revoked key's attestation would
1983
        // otherwise be refused by every later fetch).
1984364×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
19857×
            return Ok(vec![RefResult {
19867×
                name: bookmark,
19877×
                ok: true,
19887×
                reason: "already up to date".into(),
19897×
            }]);
1990357×
        }
1991433×
        for h in &remote_heads {
1992433×
            if !self.store.has(h) {
199373×
                return fail(format!(
1994
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
199573×
                    h.short(12)
1996
                ));
1997360×
            }
1998
        }
1999284×
        if !force {
2000284×
            let closure = self.closure_in_store(&local_heads)?;
2001336×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
20020×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2003284×
            }
20040×
        }
2005284×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2006284×
        let key = self.secret_key()?.map(|(k, _)| k);
2007284×
        if let Some(key) = key {
2008
            // Seal this author's changes that carry no valid authenticator,
2009
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2010
            // are stored, so each batch's bundle carries those it needs.
201181×
            let mut unsigned = Vec::new();
201281×
            for h in &to_send {
201374×
                let c = self.store.get_change_meta(h)?;
201474×
                if (c.author == key || c.author.is_zero())
201570×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
201642×
                {
201742×
                    unsigned.push(*h);
201842×
                }
2019
            }
202081×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
202139×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2022
            }
2023203×
        }
2024
        // A long history goes in batches, in dependency order, so neither
2025
        // side holds it whole and no request passes the remote's limit:
2026
        // all but the last carry objects alone; the last moves the bookmark
2027
        // (oxygen#95).
2028283×
        let batches = self.push_batches(&to_send)?;
2029283×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2030283×
        for (i, batch) in earlier.iter().enumerate() {
20315×
            progress(&format!(
20325×
                "part {} of {}: {} changes",
20335×
                i + 1,
20345×
                batches.len(),
20355×
                batch.len()
20365×
            ));
20375×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
20385×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
20395×
                Some(r) if r.ok => {}
20400×
                Some(r) => {
20410×
                    return fail(format!(
2042
                        "{remote_name} refused part {} of the push: {}",
20430×
                        i + 1,
2044
                        r.reason
2045
                    ))
2046
                }
2047
                None => {
20480×
                    return fail(format!(
2049
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2050
                    ))
2051
                }
2052
            }
2053
        }
2054283×
        if batches.len() > 1 {
20551×
            progress(&format!(
20561×
                "part {} of {}: {} changes",
20571×
                batches.len(),
20581×
                batches.len(),
20591×
                last.len()
20601×
            ));
2061282×
        }
2062283×
        let mut bundle = self.bundle_for(last)?;
2063283×
        bundle.objects.push((
2064283×
            ObjectType::State,
2065283×
            StateObject::new(local_heads.clone()).encode(),
2066283×
        ));
2067283×
        let attestation = match key {
206880×
            Some(_) => Some(self.sign_attest(&Attest {
206980×
                repo: self.id()?,
207080×
                hlc: Hlc::now(),
207180×
                body: AttestBody::Ref {
207280×
                    name: bookmark.clone(),
207380×
                    old_state: remote_state,
207480×
                    new_state,
207580×
                    serial: next_serial(last_serial),
207680×
                },
20771×
            })?),
2078203×
            None => None,
2079
        };
2080
        // Whoever signed the move, and whom a delegate acts for, travel with
2081
        // it: a receiver that has never seen a change by this delegate could
2082
        // not otherwise check its signature (oxygenhub#129).
2083282×
        if attestation.is_some() {
2084158×
            for k in [self.signing_key(), self.config.author_key]
208579×
                .into_iter()
208679×
                .flatten()
2087
            {
2088158×
                if let Ok(id) = self.identity(&k) {
2089158×
                    let body = id.encode();
2090158×
                    if !bundle
2091158×
                        .objects
2092158×
                        .iter()
2093182×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
209416×
                    {
209516×
                        bundle.objects.push((ObjectType::Identity, body));
2096142×
                    }
20970×
                }
2098
            }
2099
            // A short-lived signing key's certificate goes with it (§14.7).
210079×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
210179×
            self.attach_certificates_for(&mut bundle, &signers)?;
2102203×
        }
2103282×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
210479×
            AttestBody::Ref { serial, .. } => Some(serial),
21050×
            _ => None,
210679×
        });
2107282×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2108
        // Tag states must be present on the remote: bundle their changes too.
2109282×
        for t in &tags_to_send {
21106×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
21116×
            let extra: Vec<ChangeHash> =
21126×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
21136×
            if !extra.is_empty() {
21140×
                let more = self.bundle_for(&extra)?;
21150×
                bundle.changes.extend(more.changes);
21160×
                bundle.hashes.extend(more.hashes);
21170×
                bundle.attests.extend(more.attests);
21180×
                bundle.objects.extend(more.objects);
21196×
            }
21206×
            bundle.objects.push((
21216×
                ObjectType::State,
21226×
                StateObject::new(t.heads.clone()).encode(),
21236×
            ));
2124
        }
2125282×
        if let Some(l) = &policy_to_send {
212621×
            let remote_serial = resp_policy_serial;
212721×
            bundle.policies = self
212821×
                .policy_history()?
212921×
                .into_iter()
213047×
                .filter(|sp| {
213147×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
213223×
                        && sp.policy.serial < l.policy.serial
213347×
                })
213421×
                .collect();
2135261×
        }
2136282×
        let results = remote.push(
2137282×
            bundle,
2138282×
            vec![RefUpdate {
2139282×
                name: bookmark.clone(),
2140282×
                old_state: remote_state,
2141282×
                new_state,
2142282×
                force,
2143282×
                attestation,
2144282×
            }],
2145282×
            policy_to_send,
2146282×
            tags_to_send,
21477×
        )?;
214821×
        if let (Some(serial), true) = (
2149275×
            sent_serial,
2150281×
            results.iter().any(|r| r.ok && r.name == "policy"),
2151
        ) {
215221×
            self.record_policy_serial(remote_name, serial)?;
2153254×
        }
2154296×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2155257×
            let mut view = op.view.clone();
2156257×
            view.remotes
2157257×
                .entry(remote_name.to_string())
2158257×
                .or_default()
2159257×
                .insert(bookmark.clone(), new_state);
2160257×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2161254×
            if let Some(s) = serial {
216261×
                self.record_serial(remote_name, &bookmark, s)?;
2163193×
            }
216418×
        }
2165270×
        Ok(results)
2166370×
    }
2167
2168
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2169
    /// bookmark set to the remote's, working copy checked out.
2170234×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2171234×
        Self::clone_with(url, dest, None, &[])
2172234×
    }
2173
2174
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2175
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2176
    /// unless a size is given, so out-of-scope binaries are never fetched).
2177242×
    pub fn clone_with(
2178242×
        url: &str,
2179242×
        dest: &Path,
2180242×
        max_blob: Option<u64>,
2181242×
        sparse: &[String],
2182242×
    ) -> Result<Repo> {
2183242×
        Self::clone_full(url, dest, max_blob, sparse, None)
2184242×
    }
2185
2186
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2187
    /// changes within `depth` steps of them; the rest is the boundary.
21881×
    pub fn clone_shallow(
21891×
        url: &str,
21901×
        dest: &Path,
21911×
        depth: u32,
21921×
        max_blob: Option<u64>,
21931×
        sparse: &[String],
21941×
    ) -> Result<Repo> {
21951×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
21961×
    }
2197
2198243×
    fn clone_full(
2199243×
        url: &str,
2200243×
        dest: &Path,
2201243×
        max_blob: Option<u64>,
2202243×
        sparse: &[String],
2203243×
        depth: Option<u32>,
2204243×
    ) -> Result<Repo> {
2205243×
        let options = crate::credentials::Credentials::user().options_for(url);
2206243×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2207243×
    }
2208
2209
    /// Clone a subrepo with the credentials the parent would use for its
2210
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2211
    /// subrepo: it finds the same ones again through its parent.
22129×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
22139×
        let options = self.credentials_for(url);
22149×
        Self::clone_using(url, dest, None, &[], None, &options)
22159×
    }
2216
2217
    /// The name of a remote of this repository on the same hub (scheme,
2218
    /// host and port) as `url`.
221921×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
222025×
        let origin = |u: &str| -> Option<String> {
222125×
            let (scheme, rest) = u.split_once("://")?;
22228×
            if !matches!(scheme, "http" | "https") {
22230×
                return None;
22248×
            }
22258×
            let host = rest.split('/').next()?;
22268×
            Some(format!(
22278×
                "{}://{}",
22288×
                scheme.to_ascii_lowercase(),
22298×
                host.to_ascii_lowercase()
22308×
            ))
223125×
        };
223221×
        let want = origin(url)?;
22334×
        self.config
22344×
            .remotes
22354×
            .iter()
22364×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
22374×
            .map(|(name, _)| name.clone())
223821×
    }
2239
2240
    /// The token and CA to reach `url` with: those of a remote of this
2241
    /// repository on the same hub (scheme, host and port), else the
2242
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2243
    /// and enclosing checkouts', as a clone would use them.
224421×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
224521×
        match self.remote_on_same_hub(url) {
22461×
            Some(name) => RemoteOptions {
22471×
                repo_id: None,
22481×
                cache_dir: None,
22491×
                ..self.remote_options(&name)
22501×
            },
2251
            None => {
225220×
                let mut options = RemoteOptions::default();
225320×
                self.fill_credentials(url, &mut options);
225420×
                options
2255
            }
2256
        }
225721×
    }
2258
2259252×
    fn clone_using(
2260252×
        url: &str,
2261252×
        dest: &Path,
2262252×
        max_blob: Option<u64>,
2263252×
        sparse: &[String],
2264252×
        depth: Option<u32>,
2265252×
        options: &RemoteOptions,
2266252×
    ) -> Result<Repo> {
2267252×
        let remote = open_remote(url, options)?;
2268252×
        let id = remote.repo_id()?;
2269248×
        if id == crate::protocol::UNBOUND_ID {
22702×
            return fail(format!(
2271
                "{url} is empty and unbound: push a repository to it first"
2272
            ));
2273246×
        }
2274246×
        let mut repo = Repo::init_with_id(dest, id)?;
2275246×
        repo.config
2276246×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2277246×
        if let Some(m) = max_blob {
22782×
            repo.config.set("filter.max-blob", &m.to_string())?;
2279244×
        } else if !sparse.is_empty() {
22801×
            repo.config.set("filter.max-blob", "0")?;
2281243×
        }
2282246×
        if !sparse.is_empty() {
22831×
            repo.config.set("filter.paths", &sparse.join(","))?;
2284245×
        }
2285246×
        repo.save_config()?;
2286246×
        if let Some(depth) = depth {
22871×
            repo.fetch_shallow("origin", depth)?;
2288
        } else {
2289245×
            repo.fetch("origin")?;
2290
        }
2291245×
        let (op_ref, op) = repo.head_op()?;
2292
        // The remote's default bookmark, else ours (main), else its only one.
2293245×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2294
        // Asked of the remote as now configured, so a store-backed one
2295
        // answers from the mirror the fetch just filled.
2296245×
        let advertised = repo
2297245×
            .open_named_remote("origin")
2298245×
            .ok()
2299245×
            .and_then(|r| r.refs().ok())
2300245×
            .and_then(|r| r.default_bookmark);
2301245×
        let bookmark = advertised
2302245×
            .filter(|b| theirs.contains_key(b))
2303245×
            .or_else(|| {
23047×
                theirs
23057×
                    .contains_key(&repo.config.bookmark)
23067×
                    .then(|| repo.config.bookmark.clone())
23077×
            })
2308245×
            .or_else(|| {
23090×
                (theirs.len() == 1)
23100×
                    .then(|| theirs.keys().next().cloned())
23110×
                    .flatten()
23120×
            })
2313245×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2314245×
        let initial = repo.config.bookmark.clone();
2315245×
        if bookmark != repo.config.bookmark {
23161×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
23171×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
23181×
            repo.config.bookmark = bookmark.clone();
2319244×
        }
2320245×
        if let Some(state) = theirs.get(&bookmark).copied() {
2321245×
            let heads = repo.store.get_state(&state)?.heads;
2322245×
            let mut view = op.view.clone();
2323
            // The empty bookmark `init` made goes when another is checked out.
2324245×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
23251×
                view.bookmarks.remove(&initial);
2326244×
            }
2327245×
            view.bookmarks.insert(bookmark, state);
2328245×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2329245×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
23300×
        }
2331245×
        Ok(repo)
2332252×
    }
2333
}
2334
2335
/// The serial of a reference's next attestation: one more than the last the
2336
/// remote reports, or, for a bookmark the remote does not have, the clock in
2337
/// milliseconds, so a bookmark created again after a deletion goes past the
2338
/// deletion's serial the remote keeps.
233980×
fn next_serial(last: Option<u64>) -> u64 {
234080×
    match last {
234151×
        Some(l) => l + 1,
234229×
        None => Hlc::now().wall_ms.max(1),
2343
    }
234480×
}