OXYGENHUB

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

1719 of 1928 lines run, 251 of 362 functions · run #313 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
541293×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551293×
        self.oxy.join("attest").join(name_file(bookmark))
561293×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591212×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601212×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61219×
            Ok(h) => {
62219×
                let r = ObjectRef::from_hex(h.trim())
63219×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65219×
                    r,
66
                    SignedAttest {
67219×
                        attest: self.store.get_attest(&r)?,
68219×
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
71
            }
72993×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751212×
    }
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
82990×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
83990×
        let view = self.view()?;
84990×
        let mut out = Vec::new();
851012×
        for (name, state) in &view.bookmarks {
861012×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
871012×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88122×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90122×
            });
911012×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
921012×
            let accepted = match &attestation {
93111×
                Some(a) => self.acceptance_of(&a.attest.hash())?,
94901×
                None => None,
95
            };
961012×
            out.push(RemoteRef {
971012×
                name: name.clone(),
981012×
                state: *state,
991012×
                heads: self.store.get_state(state)?.heads,
1001012×
                attestation,
1011012×
                last_serial,
1021012×
                accepted,
103
            });
104
        }
105990×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
106990×
        let history = self
107990×
            .policy_history()?
108990×
            .into_iter()
109990×
            .filter(|sp| {
11099×
                policy
11199×
                    .as_ref()
11299×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
11399×
            })
114990×
            .collect();
115
        Ok(RefsResponse {
116990×
            refs: out,
117990×
            policy,
118990×
            tags: self.tag_refs()?,
119990×
            history,
120990×
            default_bookmark: Some(self.config.bookmark.clone()),
121
        })
122990×
    }
123
124
    /// Every change reachable from `heads` that is in the store.
1251314×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1261314×
        let mut seen = BTreeSet::new();
1271314×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1284428×
        while let Some(h) = stack.pop() {
1293114×
            if seen.contains(&h) || !self.store.has(&h) {
130865×
                continue;
1312249×
            }
1322249×
            seen.insert(h);
1332249×
            stack.extend(self.store.get_change_meta(&h)?.deps);
134
        }
1351314×
        Ok(seen)
1361314×
    }
137
138
    /// The changes within `depth` dependency steps of `heads` (spec §17),
139
    /// nearest first; depth 1 is the heads themselves.
1403×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1413×
        let mut out = Vec::new();
1423×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1433×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1443×
        for _ in 0..depth.max(1) {
1458×
            let mut next = Vec::new();
14612×
            for h in layer {
14712×
                if !seen.insert(h) || !self.store.has(&h) {
1482×
                    continue;
14910×
                }
15010×
                let c = self.store.get_change(&h)?;
15110×
                next.extend(c.deps.iter().copied());
15210×
                out.push(h);
153
            }
1548×
            if next.is_empty() {
1551×
                break;
1567×
            }
1577×
            layer = next;
158
        }
1593×
        out.reverse();
1603×
        Ok(out)
1613×
    }
162
1631898×
    fn shallow_path(&self) -> PathBuf {
1641898×
        self.oxy.join("shallow")
1651898×
    }
166
167
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1681895×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1691895×
        fs::read_to_string(self.shallow_path())
1701895×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1711895×
            .unwrap_or_default()
1721895×
    }
173
174183×
    pub fn is_shallow(&self) -> bool {
175183×
        !self.boundary().is_empty()
176183×
    }
177
1783×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1793×
        if boundary.is_empty() {
1801×
            let _ = fs::remove_file(self.shallow_path());
1811×
            return Ok(());
1822×
        }
1832×
        let text: String = boundary
1842×
            .iter()
1852×
            .map(|h| format!("{}\n", h.to_hex()))
1862×
            .collect();
1872×
        write_atomic(&self.shallow_path(), text.as_bytes())
1883×
    }
189
190
    /// Recompute the boundary from what is stored: every dependency of a
191
    /// stored change that is not itself stored.
1923×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1933×
        let mut boundary = self.boundary();
1943×
        boundary.retain(|h| !self.store.has(h));
19510×
        for h in imported {
19613×
            for d in self.store.get_change_meta(h)?.deps {
19713×
                if !self.store.has(&d) {
1982×
                    boundary.insert(d);
19911×
                }
200
            }
201
        }
2023×
        self.write_boundary(&boundary)
2033×
    }
204
205
    /// Fetch `depth` more levels of history below the shallow boundary.
2062×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2072×
        let boundary = self.boundary();
2082×
        if boundary.is_empty() {
2090×
            return Ok(0);
2102×
        }
2112×
        let remote = self.open_named_remote(remote_name)?;
2122×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2132×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2142×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2152×
        if self.config.max_blob.is_some() {
2160×
            self.register_missing_blobs(&imported, remote_name)?;
2172×
        }
2182×
        self.refresh_boundary(&imported)?;
2192×
        Ok(imported.len())
2202×
    }
221
222
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
223750×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
224750×
        let have = self.closure_in_store(have)?;
225
        // In a shallow repository the walk stops at the boundary, whose
226
        // changes the remote is assumed to hold.
227750×
        let boundary = self.boundary();
228750×
        let mut out = Vec::new();
229750×
        let mut done: BTreeSet<ChangeHash> = have.clone();
230750×
        done.extend(boundary.iter().copied());
231
        // Iterative post-order DFS.
2321177×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2333082×
        while let Some((h, expanded)) = stack.pop() {
2342332×
            if done.contains(&h) {
235384×
                continue;
2361948×
            }
2371948×
            if !self.store.has(&h) {
2380×
                return fail(format!("change {} is not in this repository", h.short(12)));
2391948×
            }
2401948×
            if expanded {
241974×
                done.insert(h);
242974×
                out.push(h);
243974×
                continue;
244974×
            }
245974×
            stack.push((h, true));
246974×
            for d in self.store.get_change_meta(&h)?.deps {
247628×
                if !done.contains(&d) {
248181×
                    stack.push((d, false));
249447×
                }
250
            }
251
        }
252750×
        Ok(out)
253750×
    }
254
255
    /// Bundle changes (in the given dependency order) with their signatures,
256
    /// seals, identities, blobs, chunks.
257296×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
258296×
        self.bundle_for_filtered(changes, None)
259296×
    }
260
261
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2624×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2634×
        let mut out = Vec::new();
2644×
        for r in refs {
2654×
            let (ty, body) = match self.store.get(r) {
2664×
                Ok(x) => x,
2670×
                Err(StoreError::NotFound(_)) => continue,
2680×
                Err(e) => return Err(e.into()),
269
            };
2704×
            if ty == ObjectType::Blob {
2715×
                for c in Blob::decode(&body)?.chunks {
2725×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2735×
                        out.push((cty, cb));
2745×
                    }
275
                }
2760×
            }
2774×
            out.push((ty, body));
278
        }
2794×
        Ok(out)
2804×
    }
281
282
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
283
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
284345×
    pub fn bundle_for_filtered(
285345×
        &self,
286345×
        changes: &[ChangeHash],
287345×
        max_blob: Option<u64>,
288345×
    ) -> Result<Bundle> {
289345×
        self.bundle_of(changes, max_blob, false)
290345×
    }
291
292
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
293
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
294
    /// with their text blobs and chunks among the objects, so neither side
295
    /// decodes or encodes their text.
296313×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
297313×
        self.bundle_of(changes, max_blob, true)
298313×
    }
299
300658×
    fn bundle_of(
301658×
        &self,
302658×
        changes: &[ChangeHash],
303658×
        max_blob: Option<u64>,
304658×
        raw: bool,
305658×
    ) -> Result<Bundle> {
306658×
        let mut bundle = Bundle::default();
307658×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
308658×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
309995×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
310995×
            if !r.is_zero() && self.store.has(r) {
311193×
                objects.insert(*r);
312802×
            }
313995×
        };
314901×
        for h in changes {
315
            // Raw: the stored bytes, and a skeleton for the rest.
316901×
            let (c, encoded) = if raw {
317472×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
318472×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3194913×
                for t in texts {
3204913×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3213×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3223×
                        objects.insert(r);
3233×
                        objects.extend(blob.chunks);
3244910×
                    }
325
                }
326472×
                (skel, Some(bytes))
327
            } else {
328429×
                (self.store.get_change(h)?, None)
329
            };
330901×
            let sigs = self.store.signatures(h)?;
331901×
            add_object(&c.author, &mut objects);
332901×
            for s in &sigs {
33322×
                add_object(&s.key, &mut objects);
33422×
            }
3355811×
            for e in &c.edits {
3365811×
                if let Edit::Replace { old, new, .. } = e {
33714×
                    for b in [old, new].into_iter().flatten() {
33814×
                        if self.store.has(b) {
33914×
                            if let Ok(blob) =
34014×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
341
                            {
34214×
                                if max_blob.is_some_and(|m| blob.length > m) {
3434×
                                    continue;
34410×
                                }
34510×
                                objects.insert(*b);
34610×
                                objects.extend(blob.chunks.iter().copied());
3470×
                            }
3480×
                        }
349
                    }
3505799×
                }
351
            }
352901×
            for s in self.store.seals_for(h)? {
35377×
                seals.insert(s);
35477×
            }
355901×
            match encoded {
356472×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
357429×
                None => {
358429×
                    bundle.changes.push((c, sigs));
359429×
                    bundle.hashes.push(*h);
360429×
                }
361
            }
362
        }
363658×
        for r in seals {
36472×
            let attest = self.store.get_attest(&r)?;
36572×
            let sigs = self.store.signatures(&r)?;
36672×
            for s in &sigs {
36772×
                add_object(&s.key, &mut objects);
36872×
            }
36972×
            bundle.attests.push(SignedAttest { attest, sigs });
370
        }
371658×
        for r in objects {
372116×
            let (ty, body) = self.store.get(&r)?;
373116×
            bundle.objects.push((ty, body));
374
        }
375658×
        self.attach_certificates(&mut bundle)?;
376658×
        Ok(bundle)
377658×
    }
378
379
    /// Add the certificates of short-lived keys that signed what `bundle`
380
    /// carries, and their issuers' identities, so a receiver can tell who
381
    /// they stand for (spec §14.7). `also` names more signers (a reference
382
    /// attestation sent beside the bundle).
383737×
    pub(crate) fn attach_certificates_for(
384737×
        &self,
385737×
        bundle: &mut Bundle,
386737×
        also: &[KeyId],
387737×
    ) -> Result<()> {
388737×
        let mut keys: BTreeSet<KeyId> = also.iter().copied().collect();
389737×
        keys.extend(
390737×
            bundle
391737×
                .changes
392737×
                .iter()
393737×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
394
        );
395737×
        keys.extend(
396737×
            bundle
397737×
                .raw_changes
398737×
                .iter()
399737×
                .flat_map(|(_, s)| s.iter().map(|s| s.key)),
400
        );
401737×
        keys.extend(
402737×
            bundle
403737×
                .attests
404737×
                .iter()
405737×
                .flat_map(|a| a.sigs.iter().map(|s| s.key)),
406
        );
407737×
        for k in keys {
408174×
            let Some(r) = self.store.certificate_of(&k)? else {
409165×
                continue;
410
            };
4119×
            let cert = self.store.get_certificate(&r)?;
4129×
            if bundle
4139×
                .certificates
4149×
                .iter()
4159×
                .any(|c| c.cert.hash() == cert.cert.hash())
416
            {
4173×
                continue;
4186×
            }
41912×
            for id in [&k, &cert.cert.issuer] {
42012×
                if let Ok(body) = self.store.get_typed(id, ObjectType::Identity) {
42112×
                    if !bundle
42212×
                        .objects
42312×
                        .iter()
42414×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
4256×
                    {
4266×
                        bundle.objects.push((ObjectType::Identity, body));
4276×
                    }
4280×
                }
429
            }
4306×
            bundle.certificates.push(cert);
431
        }
432737×
        Ok(())
433737×
    }
434
435658×
    fn attach_certificates(&self, bundle: &mut Bundle) -> Result<()> {
436658×
        self.attach_certificates_for(bundle, &[])
437658×
    }
438
439
    /// Keep the certificates a bundle brings once each verifies with the
440
    /// identity of the issuer it names; one that does not refuses the bundle.
441703×
    fn adopt_certificates(&self, certs: &[crate::cert::SignedCertificate]) -> Result<()> {
442703×
        for c in certs {
4436×
            let issuer = self.store.get_identity(&c.cert.issuer).map_err(|_| {
4440×
                RepoError::Msg(format!(
4450×
                    "a certificate names issuer {}, whose identity did not come with it",
4460×
                    c.cert.issuer.short(12)
4470×
                ))
4480×
            })?;
4496×
            c.verify(&issuer)
4506×
                .map_err(|e| RepoError::Msg(format!("a certificate does not verify: {e}")))?;
4516×
            self.store.put_identity(&c.cert.key)?;
4526×
            self.store.put_certificate(c)?;
453
        }
454703×
        Ok(())
455703×
    }
456
457
    /// A signer authorized for `reference` by what an issuer certified it
458
    /// as (spec §14.7): a short-lived key with a kept certificate that
459
    /// verifies with its issuer, gives `scope`, covers `at_ms` (a time the
460
    /// signer did not choose) and names a subject the policy grants.
46113×
    pub(crate) fn certified_authorized(
46213×
        &self,
46313×
        p: &crate::policy::Policy,
46413×
        signer: &KeyId,
46513×
        reference: &str,
46613×
        scope: Scope,
46713×
        at_ms: u64,
46813×
    ) -> bool {
46913×
        let Ok(Some(r)) = self.store.certificate_of(signer) else {
4705×
            return false;
471
        };
4728×
        let Ok(c) = self.store.get_certificate(&r) else {
4730×
            return false;
474
        };
4758×
        let Some(issuer) = p
4768×
            .identity(&c.cert.issuer)
4778×
            .cloned()
4788×
            .or_else(|| self.store.get_identity(&c.cert.issuer).ok())
479
        else {
4800×
            return false;
481
        };
4828×
        c.verify(&issuer).is_ok()
4838×
            && c.cert.key_id() == *signer
4848×
            && c.cert.covers(scope, at_ms)
4857×
            && p.subject_grant(reference, &c.cert.issuer, &c.cert.subject, scope)
48613×
    }
487
488
    /// Store a bundle's contents. With `strict`, every change must
489
    /// authenticate (signature or seal by its author or a delegate).
490700×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
491700×
        self.import_bundle_inner(bundle, strict, false)
492700×
    }
493
494
    /// Like `import_bundle`, accepting changes whose dependencies are absent
495
    /// (they join the shallow boundary).
4963×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
4973×
        self.import_bundle_inner(bundle, strict, true)
4983×
    }
499
500703×
    fn import_bundle_inner(
501703×
        &self,
502703×
        bundle: &Bundle,
503703×
        strict: bool,
504703×
        shallow: bool,
505703×
    ) -> Result<Vec<ChangeHash>> {
506703×
        let batch = self.store.begin_batch()?;
507703×
        let result = self.import_bundle_batched(bundle, strict, shallow);
508703×
        batch.finish()?;
509701×
        result
510703×
    }
511
512703×
    fn import_bundle_batched(
513703×
        &self,
514703×
        bundle: &Bundle,
515703×
        strict: bool,
516703×
        shallow: bool,
517703×
    ) -> Result<Vec<ChangeHash>> {
518703×
        for (ty, _) in &bundle.objects {
5190×
            if !matches!(
520491×
                ty,
521
                ObjectType::Chunk
522
                    | ObjectType::Blob
523
                    | ObjectType::Identity
524
                    | ObjectType::State
525
                    | ObjectType::Checkpoint
526
            ) {
5270×
                return fail(format!("bundle may not carry {} objects", ty.name()));
528491×
            }
529
        }
530
        // All at once: in a large batch they are compressed on every core.
531703×
        let objects: Vec<(ObjectType, &[u8])> = bundle
532703×
            .objects
533703×
            .iter()
534703×
            .map(|(ty, body)| (*ty, body.as_slice()))
535703×
            .collect();
536703×
        self.store.put_many(&objects)?;
537703×
        self.adopt_certificates(&bundle.certificates)?;
538703×
        for sa in &bundle.attests {
53975×
            let r = self.store.put_attest(&sa.attest)?;
54075×
            for sig in &sa.sigs {
54175×
                self.store.put_signature(&r, sig)?;
542
            }
54375×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
54480×
                for h in hashes {
54580×
                    self.store.index_seal(h, &r)?;
546
                }
5470×
            }
548
        }
549
        // Each change's hash: from the bundle when its maker knew it, else
550
        // worked out once (for a change adding a whole tree, hashing is
551
        // chunking all its text).
552703×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
553694×
            bundle.hashes.clone()
554
        } else {
5559×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
556
        };
557703×
        let raw_hashes: Vec<ChangeHash> = bundle
558703×
            .raw_changes
559703×
            .iter()
560703×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
561703×
            .collect();
562703×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
563703×
        let boundary = self.boundary();
564703×
        let mut imported = Vec::new();
565
        // Changes as stored: checked, then stored as they are, their text
566
        // blobs having come with the objects.
567703×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
568473×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
569473×
            for d in &skel.deps {
570325×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
571
                {
5720×
                    return fail(format!(
573
                        "change {} depends on {}, which is neither stored nor in the bundle",
5740×
                        h.short(12),
5750×
                        d.short(12)
576
                    ));
577325×
                }
578
            }
5794914×
            for t in texts {
5804914×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
5814×
                    if !self.store.has(&r) {
5821×
                        return fail(format!(
583
                            "change {} came without its text blob {}",
5841×
                            h.short(12),
5851×
                            r.short(12)
586
                        ));
5873×
                    }
5884910×
                }
589
            }
590472×
            self.store.put(ObjectType::Change, bytes)?;
591472×
            for sig in sigs {
5924×
                self.store.put_signature(&h, sig)?;
593
            }
594472×
            imported.push(h);
595
        }
596702×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
597457×
            for d in &c.deps {
598257×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
599
                {
6003×
                    return fail(format!(
601
                        "change {} depends on {}, which is neither stored nor in the bundle",
6023×
                        h.short(12),
6033×
                        d.short(12)
604
                    ));
605254×
                }
606
            }
607454×
            let stored = self.store.put_change(c)?;
608454×
            if stored != h {
6090×
                return fail(format!(
610
                    "change {} is not the change the bundle names",
6110×
                    h.short(12)
612
                ));
613454×
            }
614454×
            for sig in sigs {
61527×
                self.store.put_signature(&h, sig)?;
616
            }
617454×
            imported.push(h);
618
        }
619699×
        if strict {
62037×
            for h in &imported {
62125×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
6221×
                    return fail(format!(
623
                        "change {} is not authenticated by its author",
6241×
                        h.short(12)
625
                    ));
62624×
                }
627
            }
628662×
        }
629698×
        Ok(imported)
630703×
    }
631
632
    /// Verify a reference attestation against an update it claims to describe.
633
    /// `allow_equal` lets a client re-read the attestation it already has; a
634
    /// server receiving a push requires a strictly greater serial.
635
    /// A reference attestation signed by a delegate of an identity the
636
    /// rule lists is authorized as that identity (spec §14.5): the identity
637
    /// named the delegate with the `refs` scope, still in force at `at_ms`
638
    /// (the attestation's wall time), and the policy names the identity.
639
    /// Revoked keys authorize nothing either way.
64017×
    pub(crate) fn delegate_authorized(
64117×
        &self,
64217×
        p: &crate::policy::Policy,
64317×
        signer: &KeyId,
64417×
        reference: &str,
64517×
        at_ms: u64,
64617×
    ) -> bool {
64717×
        if p.is_revoked(signer) {
6481×
            return false;
64916×
        }
65016×
        let Some(rule) = p.rule_for(reference) else {
6510×
            return false;
652
        };
65317×
        rule.keys.iter().any(|k| {
65417×
            !p.is_revoked(k)
65517×
                && p.identity(k)
65617×
                    .cloned()
65717×
                    .or_else(|| self.store.get_identity(k).ok())
65817×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
65917×
        })
66017×
    }
661
662
    /// A lasting attestation (a tag) signed by a key the policy has since
663
    /// rotated away from (spec §14.2) is authorized as the key that
664
    /// succeeded it: a key the rule lists reaches the signer through
665
    /// `previous` links, and the attestation is dated (`at_ms`) before the
666
    /// signer's successor was made, so a superseded key makes nothing new.
667
    /// Revoked keys authorize nothing.
6686×
    pub(crate) fn predecessor_authorized(
6696×
        &self,
6706×
        p: &crate::policy::Policy,
6716×
        signer: &KeyId,
6726×
        reference: &str,
6736×
        at_ms: u64,
6746×
    ) -> bool {
6756×
        if p.is_revoked(signer) {
6760×
            return false;
6776×
        }
6786×
        let Some(rule) = p.rule_for(reference) else {
6790×
            return false;
680
        };
6817×
        let identity = |k: &KeyId| {
6827×
            p.identity(k)
6837×
                .cloned()
6847×
                .or_else(|| self.store.get_identity(k).ok())
6857×
        };
6866×
        rule.keys.iter().any(|k| {
6876×
            if p.is_revoked(k) {
6880×
                return false;
6896×
            }
6906×
            let mut cur = identity(k);
6916×
            for _ in 0..32 {
6927×
                let Some(id) = cur else {
6930×
                    return false;
694
                };
6951×
                match id.previous {
6966×
                    Some(prev) if prev == *signer => return at_ms < id.created,
6971×
                    Some(prev) if !p.is_revoked(&prev) => cur = identity(&prev),
6981×
                    _ => return false,
699
                }
700
            }
7010×
            false
7026×
        })
7036×
    }
704
705106×
    fn check_ref_attest(
706106×
        &self,
707106×
        sa: &SignedAttest,
708106×
        name: &str,
709106×
        old_state: &ObjectRef,
710106×
        new_state: &ObjectRef,
711106×
        last_serial: Option<u64>,
712106×
        allow_equal: bool,
713106×
    ) -> std::result::Result<u64, String> {
714
        let AttestBody::Ref {
715106×
            name: n,
716106×
            old_state: o,
717106×
            new_state: nw,
718106×
            serial,
719106×
        } = &sa.attest.body
720
        else {
7210×
            return Err("attestation is not a ref attestation".into());
722
        };
723106×
        if n != name || o != old_state || nw != new_state {
7241×
            return Err("attestation does not describe this update".into());
725105×
        }
726105×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
7270×
            return Err("attestation is for a different repository".into());
728105×
        }
729105×
        if let Some(last) = last_serial {
73065×
            if *serial < last || (*serial == last && !allow_equal) {
7311×
                return Err(format!(
7321×
                    "attestation serial {serial} is not greater than the last seen {last}"
7331×
                ));
73464×
            }
73540×
        }
736104×
        let r = sa.attest.hash();
737104×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
738104×
        let id = self
739104×
            .store
740104×
            .get_identity(&sig.key)
741104×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
742104×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
743104×
        Ok(*serial)
744106×
    }
745
746
    /// Accept a push (spec §16.4). Without a trust policy every repository
747
    /// is unverified, so unsigned changes and unattested updates are accepted;
748
    /// attestations that are present must still be valid. With a policy,
749
    /// every change and update is checked against it. A newer policy in the
750
    /// push is applied first when it is signed by the current roots.
751274×
    pub fn receive_push(
752274×
        &self,
753274×
        bundle: Bundle,
754274×
        updates: Vec<RefUpdate>,
755274×
        policy: Option<SignedPolicy>,
756274×
        tags: Vec<crate::protocol::TagRef>,
757274×
    ) -> Result<Vec<RefResult>> {
758274×
        Ok(self
759274×
            .receive_push_report(bundle, updates, policy, tags)?
760
            .results)
761274×
    }
762
763
    /// `receive_push` with what a host wants to log: each accepted
764
    /// reference's old and new state and heads, and the changes this push
765
    /// stored (hub spec §6.12).
766314×
    pub fn receive_push_report(
767314×
        &self,
768314×
        bundle: Bundle,
769314×
        updates: Vec<RefUpdate>,
770314×
        policy: Option<SignedPolicy>,
771314×
        tags: Vec<crate::protocol::TagRef>,
772314×
    ) -> Result<PushReport> {
773314×
        let mut report = PushReport::default();
774314×
        let results = &mut report.results;
775314×
        if let Some(sp) = policy {
77623×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
77721×
                Ok(()) => {
77821×
                    results.push(RefResult {
77921×
                        name: "policy".into(),
78021×
                        ok: true,
78121×
                        reason: format!("serial {}", sp.policy.serial),
78221×
                    });
78321×
                }
7842×
                Err(e) => {
7852×
                    results.push(RefResult {
7862×
                        name: "policy".into(),
7872×
                        ok: false,
7882×
                        reason: e,
7892×
                    });
7902×
                    for u in updates {
7910×
                        results.push(RefResult {
7920×
                            name: u.name,
7930×
                            ok: false,
7940×
                            reason: "policy update was rejected".into(),
7950×
                        });
7960×
                    }
7972×
                    return Ok(report);
798
                }
799
            }
800291×
        }
801312×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
802
        // A push of objects alone (one batch of a long history, oxygen#95)
803
        // names no reference: its outcome is reported as `objects`.
804312×
        let objects_only = updates.is_empty() && tags.is_empty();
805312×
        match self.import_bundle(&bundle, policy.is_some()) {
806309×
            Ok(imported) => {
807309×
                if objects_only {
8087×
                    results.push(RefResult {
8097×
                        name: OBJECTS_RESULT.into(),
8107×
                        ok: true,
8117×
                        reason: format!("{} changes stored", imported.len()),
8127×
                    });
813302×
                }
814309×
                report.imported = imported;
815
            }
8163×
            Err(e) => {
8173×
                if objects_only {
8180×
                    results.push(RefResult {
8190×
                        name: OBJECTS_RESULT.into(),
8200×
                        ok: false,
8210×
                        reason: e.to_string(),
8220×
                    });
8233×
                }
8243×
                for u in updates {
8253×
                    results.push(RefResult {
8263×
                        name: u.name,
8273×
                        ok: false,
8283×
                        reason: e.to_string(),
8293×
                    });
8303×
                }
8313×
                return Ok(report);
832
            }
833
        }
834309×
        let (op_ref, op) = self.head_op()?;
835309×
        let mut view = op.view.clone();
836309×
        let mut names = Vec::new();
837309×
        for u in updates {
838300×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
839300×
            let (ok, reason) = match outcome {
840274×
                Ok(()) => (true, String::new()),
84126×
                Err(e) => (false, e),
842
            };
843300×
            if ok {
844274×
                names.push(u.name.clone());
845274×
                let heads = self
846274×
                    .store
847274×
                    .get_state(&u.new_state)
848274×
                    .map(|s| s.heads)
849274×
                    .unwrap_or_default();
850274×
                report.updated.push(RefUpdated {
851274×
                    name: u.name.clone(),
852274×
                    old_state: u.old_state,
853274×
                    new_state: u.new_state,
854274×
                    heads,
855274×
                });
85626×
            }
857300×
            results.push(RefResult {
858300×
                name: u.name,
859300×
                ok,
860300×
                reason,
861300×
            });
862
        }
863309×
        for t in &tags {
8648×
            let name = format!("tags/{}", t.name);
8658×
            let new = !view.tags.contains_key(&t.name);
8668×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
867
                Ok(()) => {
868
                    // A tag new here is an update too, so a hub can start
869
                    // its pipeline's tag jobs (oxygenflow#24); one it
870
                    // already had, sent again, is not.
8716×
                    if new {
8726×
                        report.updated.push(RefUpdated {
8736×
                            name: name.clone(),
8746×
                            old_state: ObjectRef::ZERO,
8756×
                            new_state: t.state,
8766×
                            heads: t.heads.clone(),
8776×
                        });
8786×
                    }
8796×
                    names.push(name.clone());
8806×
                    results.push(RefResult {
8816×
                        name,
8826×
                        ok: true,
8836×
                        reason: String::new(),
8846×
                    });
885
                }
8862×
                Err(e) => results.push(RefResult {
8872×
                    name,
8882×
                    ok: false,
8892×
                    reason: e,
8902×
                }),
891
            }
892
        }
893309×
        if !names.is_empty() {
894274×
            self.record_op(
895274×
                &[op_ref],
896274×
                &format!("push received: {}", names.join(" ")),
897274×
                view,
8983×
            )?;
89935×
        }
900306×
        Ok(report)
901314×
    }
902
903
    /// Check an update's attestation against the latest one for its
904
    /// reference and store it as the new latest. Failures say what was
905
    /// being done, for which reference, so a refused push can be diagnosed
906
    /// from its reason alone.
90781×
    fn record_update_attest(
90881×
        &self,
90981×
        u: &RefUpdate,
91081×
        sa: &SignedAttest,
91181×
    ) -> std::result::Result<(), String> {
91281×
        let name = &u.name;
91381×
        let last = self
91481×
            .latest_ref_attest(name)
91581×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
91681×
            .and_then(|(_, a)| match a.attest.body {
91753×
                AttestBody::Ref { serial, .. } => Some(serial),
9180×
                _ => None,
91953×
            });
92081×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
92179×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
92279×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
92378×
        for sig in &sa.sigs {
92478×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
925
        }
92678×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))?;
927
        // Signed by a short-lived key: a host records when it accepted it.
92875×
        let certified = sa
92975×
            .sigs
93075×
            .first()
93175×
            .is_some_and(|s| self.store.certificate_of(&s.key).ok().flatten().is_some());
93275×
        if certified {
9331×
            self.record_acceptance(&r).map_err(|e| store(&e))?;
93474×
        }
93575×
        Ok(())
93681×
    }
937
938
    /// Record that this host accepted attestation `r` now, signed with its
939
    /// acceptor key (spec §14.7); nothing without one.
9402×
    pub(crate) fn record_acceptance(&self, r: &ObjectRef) -> Result<()> {
9412×
        let Some(acceptor) = &self.acceptor else {
9421×
            return Ok(());
943
        };
9441×
        let (id, sk) = (&acceptor.0, &acceptor.1);
9451×
        let attest = Attest {
9461×
            repo: self.id()?,
9471×
            hlc: Hlc::now(),
9481×
            body: AttestBody::Accepted { attest: *r },
949
        };
9501×
        let sig = sk.sign(Domain::Attest, &id.hash(), &attest.hash());
9511×
        self.store.put_identity(id)?;
9521×
        let a = self.store.put_attest(&attest)?;
9531×
        self.store.put_signature(&a, &sig)?;
9541×
        self.store.index_add_pub("accepted", r, &a)?;
9551×
        Ok(())
9562×
    }
957
958
    /// The host's acceptance of attestation `r`, if one was recorded.
959113×
    pub fn acceptance_of(&self, r: &ObjectRef) -> Result<Option<SignedAttest>> {
960113×
        let Some(a) = self.store.index_get_pub("accepted", r)?.into_iter().next() else {
961103×
            return Ok(None);
962
        };
963
        Ok(Some(SignedAttest {
96410×
            attest: self.store.get_attest(&a)?,
96510×
            sigs: self.store.signatures(&a)?,
966
        }))
967113×
    }
968
969
    /// When a certified signer's attestation `sa` is checked on a fetch: the
970
    /// host's acceptance time, if `accepted` is signed by the issuer of the
971
    /// signer's certificate and accepts `sa`; else the attestation's own
972
    /// time, which the signer chose.
97318×
    pub(crate) fn certified_time(
97418×
        &self,
97518×
        signer: &KeyId,
97618×
        sa: &SignedAttest,
97718×
        accepted: Option<&SignedAttest>,
97818×
    ) -> u64 {
97918×
        let own = sa.attest.hlc.wall_ms;
98018×
        let Some(acc) = accepted else {
98112×
            return own;
982
        };
9836×
        let Ok(Some(c)) = self.store.certificate_of(signer) else {
9840×
            return own;
985
        };
9866×
        let Ok(cert) = self.store.get_certificate(&c) else {
9870×
            return own;
988
        };
9896×
        let AttestBody::Accepted { attest } = &acc.attest.body else {
9900×
            return own;
991
        };
9926×
        let Some(sig) = acc.sigs.iter().find(|s| s.key == cert.cert.issuer) else {
9931×
            return own;
994
        };
9955×
        let Ok(issuer) = self.store.get_identity(&cert.cert.issuer) else {
9960×
            return own;
997
        };
9985×
        if *attest == sa.attest.hash()
9994×
            && verify_signature(&issuer, sig, Domain::Attest, &acc.attest.hash()).is_ok()
1000
        {
10014×
            acc.attest.hlc.wall_ms
1002
        } else {
10031×
            own
1004
        }
100518×
    }
1006
1007
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
1008
    /// at `old_state`, is never the bookmark a non-bare repository has
1009
    /// checked out (a bare one's default is its host's to protect, see
1010
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
1011
    /// an attestation by a key that may update it.
1012
    /// The deletion's attestation stays the bookmark's latest, so an older
1013
    /// one cannot be replayed to bring it back.
10143×
    fn apply_deletion(
10153×
        &self,
10163×
        view: &mut View,
10173×
        u: &RefUpdate,
10183×
        policy: Option<&crate::policy::Policy>,
10193×
    ) -> std::result::Result<(), String> {
10203×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
10210×
            return Err(format!("no bookmark {:?} to delete", u.name));
1022
        };
10233×
        if current != u.old_state {
10240×
            return Err("stale: the remote bookmark has moved; pull first".into());
10253×
        }
10263×
        if !self.is_bare() && u.name == self.config.bookmark {
10271×
            return Err(format!(
10281×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
10291×
                u.name
10301×
            ));
10312×
        }
10322×
        if let Some(p) = policy {
10330×
            let Some(sa) = &u.attestation else {
10340×
                return Err(format!(
10350×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
10360×
                    u.name
10370×
                ));
1038
            };
10390×
            let signer = sa
10400×
                .sigs
10410×
                .first()
10420×
                .map(|s| s.key)
10430×
                .ok_or("attestation carries no signature")?;
1044
            // Received now: the receiver's own clock is the trusted time.
10450×
            let now = Hlc::now().wall_ms;
10460×
            if !p.authorizes(&signer, &u.name)
10470×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
10480×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1049
            {
10500×
                return Err(format!(
10510×
                    "key {} may not delete {:?} under this repository's policy",
10520×
                    signer.short(12),
10530×
                    u.name
10540×
                ));
10550×
            }
10562×
        }
10572×
        if let Some(sa) = &u.attestation {
10581×
            self.record_update_attest(u, sa)?;
10591×
        }
10602×
        view.bookmarks.remove(&u.name);
10612×
        Ok(())
10623×
    }
1063
1064300×
    fn apply_update(
1065300×
        &self,
1066300×
        view: &mut View,
1067300×
        u: &RefUpdate,
1068300×
        policy: Option<&crate::policy::Policy>,
1069300×
    ) -> std::result::Result<(), String> {
1070300×
        if u.name == "policy" {
10710×
            return Err(
10720×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
10730×
            );
1074300×
        }
1075300×
        let empty = self
1076300×
            .store
1077300×
            .put_state(&StateObject::new(vec![]))
1078300×
            .map_err(|e| e.to_string())?;
1079300×
        if u.new_state.is_zero() {
10803×
            return self.apply_deletion(view, u, policy);
1081297×
        }
1082297×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
1083297×
        if current != u.old_state {
10849×
            return Err("stale: the remote bookmark has moved; pull first".into());
1085288×
        }
1086288×
        let new_state = self
1087288×
            .store
1088288×
            .get_state(&u.new_state)
1089288×
            .map_err(|_| "new state object is missing".to_string())?;
1090548×
        for h in &new_state.heads {
1091548×
            if !self.store.has(h) {
10921×
                return Err(format!("head {} is missing", h.short(12)));
1093547×
            }
1094
        }
1095287×
        if !u.force {
1096286×
            let old_heads = self
1097286×
                .store
1098286×
                .get_state(&current)
1099286×
                .map_err(|e| e.to_string())?
1100
                .heads;
1101286×
            let closure = self
1102286×
                .closure_in_store(&new_state.heads)
1103286×
                .map_err(|e| e.to_string())?;
1104291×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
11051×
                return Err(format!(
11061×
                    "not a fast-forward: current head {} would be dropped (use --force)",
11071×
                    h.short(12)
11081×
                ));
1109285×
            }
11101×
        }
1111286×
        if let Some(p) = policy {
111235×
            let Some(sa) = &u.attestation else {
11131×
                return Err(format!(
11141×
                    "{:?} requires a signed reference attestation under this repository's policy",
11151×
                    u.name
11161×
                ));
1117
            };
111834×
            let signer = sa
111934×
                .sigs
112034×
                .first()
112134×
                .map(|s| s.key)
112234×
                .ok_or("attestation carries no signature")?;
1123
            // Received now: the receiver's own clock is the trusted time.
112434×
            let now = Hlc::now().wall_ms;
112534×
            if !p.authorizes(&signer, &u.name)
112610×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
11278×
                && !self.certified_authorized(p, &signer, &u.name, Scope::REFS, now)
1128
            {
11297×
                return Err(format!(
11307×
                    "key {} may not update {:?} under this repository's policy",
11317×
                    signer.short(12),
11327×
                    u.name
11337×
                ));
113427×
            }
113527×
            let old_heads = self
113627×
                .store
113727×
                .get_state(&current)
113827×
                .map_err(|e| e.to_string())?
1139
                .heads;
114027×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
1141251×
        }
1142278×
        if let Some(sa) = &u.attestation {
114380×
            self.record_update_attest(u, sa)?;
1144198×
        }
1145272×
        view.bookmarks.insert(u.name.clone(), u.new_state);
1146272×
        Ok(())
1147300×
    }
1148
1149
    // ------------------------------------------------------------ client side
1150
1151967×
    fn remote_url(&self, name: &str) -> Result<String> {
1152967×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
11533×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
11543×
            RepoError::Msg(match names.as_slice() {
11553×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
11561×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
1157
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
11581×
                    names.join(", "),
11591×
                    names[0],
11601×
                    names[0]
1161
                ),
11620×
                _ => format!(
1163
                    "no remote named {name:?}; this repository has {}",
11640×
                    names.join(", ")
1165
                ),
1166
            })
11673×
        })
1168967×
    }
1169
1170
    /// Refuse a remote that is another repository. An **unbound** remote
1171
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
1172
    /// for pushes, which bind it to this repository's id (spec §16.1).
1173719×
    fn check_remote_id(
1174719×
        &self,
1175719×
        remote: &dyn crate::protocol::Remote,
1176719×
        remote_name: &str,
1177719×
        allow_unbound: bool,
1178719×
    ) -> Result<()> {
1179719×
        let theirs = remote.repo_id()?;
1180718×
        if theirs == self.id()? {
1181695×
            return Ok(());
118223×
        }
118323×
        if theirs == crate::protocol::UNBOUND_ID {
118420×
            if allow_unbound {
118519×
                return Ok(());
11861×
            }
11871×
            return fail(format!(
1188
                "remote {remote_name:?} is empty and unbound: push to it first"
1189
            ));
11903×
        }
11913×
        fail(format!(
1192
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
1193
        ))
1194719×
    }
1195
1196
    /// Credentials and trust for a remote: `remote.<name>.token` and
1197
    /// `remote.<name>.ca`, else the defaults for its URL
1198
    /// ([`Repo::fill_credentials`]).
1199984×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
1200984×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
1201984×
        let mut options = RemoteOptions {
1202984×
            repo_id: self.id().ok(),
1203984×
            token: self.config.remote_tokens.get(name).cloned(),
1204984×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
1205984×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
1206984×
            ..RemoteOptions::default()
1207984×
        };
1208984×
        self.fill_credentials(&url, &mut options);
1209984×
        options
1210984×
    }
1211
1212
    /// The user's credential store (`credentials.toml` beside the user
1213
    /// configuration file).
12141003×
    pub fn credentials(&self) -> crate::credentials::Credentials {
12151003×
        crate::credentials::Credentials::at(
12161003×
            self.user_config
12171003×
                .parent()
12181003×
                .map(Path::to_path_buf)
12191003×
                .unwrap_or_else(default_home),
1220
        )
12211003×
    }
1222
1223
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
1224
    /// then the user's credential store for its hub, then a remote on the
1225
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
1226
    /// When the token is not this remote's own or the environment's, the
1227
    /// other tokens enclosing checkouts hold for the hub are kept to try
1228
    /// if it is refused: a stale stored login must not hide a parent's
1229
    /// good token (oxygen#112).
12301004×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
12311004×
        if options.token.is_some() && options.ca.is_some() {
12321×
            return;
12331003×
        }
12341003×
        let explicit =
12351003×
            options.token.is_some() || std::env::var("OXY_TOKEN").is_ok_and(|t| !t.is_empty());
12361003×
        let stored = self.credentials().options_for(url);
12371003×
        options.token = options.token.take().or(stored.token);
12381003×
        options.ca = options.ca.take().or(stored.ca);
12391003×
        let enclosing = self.enclosing_credentials(url);
12401003×
        if options.token.is_none() {
1241993×
            options.token = enclosing.iter().find_map(|(t, _)| t.clone());
124210×
        }
12431003×
        if options.ca.is_none() {
1244969×
            options.ca = enclosing.iter().find_map(|(_, c)| c.clone());
124534×
        }
12461003×
        if !explicit {
1247996×
            for t in enclosing.into_iter().filter_map(|(t, _)| t) {
12485×
                if options.token.as_ref() != Some(&t) && !options.fallback_tokens.contains(&t) {
12492×
                    options.fallback_tokens.push(t);
12503×
                }
1251
            }
12527×
        }
12531004×
    }
1254
1255
    /// The tokens and CAs of remotes on `url`'s hub in enclosing
1256
    /// checkouts, nearest first.
12571003×
    fn enclosing_credentials(&self, url: &str) -> Vec<(Option<String>, Option<PathBuf>)> {
12581003×
        let mut out = Vec::new();
12591003×
        let Some(hub) = crate::credentials::hub_of(url) else {
1260863×
            return out;
1261
        };
1262140×
        let mut at = self.root.parent();
1263568×
        while let Some(dir) = at {
1264428×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
12650×
                break;
1266
            };
1267428×
            for (key, remote_url) in &cfg {
126815×
                let Some(name) = key
126915×
                    .strip_prefix("remote.")
127015×
                    .and_then(|k| k.strip_suffix(".url"))
1271
                else {
12727×
                    continue;
1273
                };
12748×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
12751×
                    continue;
12767×
                }
12777×
                out.push((
12787×
                    cfg.get(&format!("remote.{name}.token")).cloned(),
12797×
                    cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from),
12807×
                ));
1281
            }
1282428×
            at = dir.parent();
1283
        }
1284140×
        out
12851003×
    }
1286
1287
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1288
    /// no changes and no reference updates, which the receiver stores.
12890×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
12900×
        let remote = self.open_named_remote(remote_name)?;
12910×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
12920×
        let mut bundle = Bundle::default();
12930×
        for r in seals {
12940×
            let attest = self.store.get_attest(r)?;
12950×
            let sigs = self.store.signatures(r)?;
12960×
            bundle
12970×
                .attests
12980×
                .push(crate::protocol::SignedAttest { attest, sigs });
1299
        }
13000×
        let results = remote.push(bundle, vec![], None, vec![])?;
13010×
        if let Some(r) = results.iter().find(|r| !r.ok) {
13020×
            return fail(format!("{}: {}", r.name, r.reason));
13030×
        }
13040×
        Ok(())
13050×
    }
1306
1307
    /// The remote whose URL starts with `base` (a hub), if configured.
13084×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
13094×
        let base = base.trim_end_matches('/');
13104×
        self.config
13114×
            .remotes
13124×
            .iter()
13134×
            .find(|(_, url)| url.trim_end_matches('/') == base)
13144×
            .map(|(name, _)| name.clone())
13154×
    }
1316
1317
    /// Open a remote by name or, failing that, by URL with the default
1318
    /// credentials (see [`Repo::credentials_for`]).
13190×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
13200×
        if let Some(name) = self.remote_for_url(url) {
13210×
            return Ok((name.clone(), self.open_named_remote(&name)?));
13220×
        }
13230×
        let options = RemoteOptions {
13240×
            repo_id: self.id().ok(),
13250×
            ..self.credentials_for(url)
13260×
        };
13270×
        Ok((url.to_string(), open_remote(url, &options)?))
13280×
    }
1329
1330
    /// Credentials for a URL: those of the configured remote with that
1331
    /// URL, else the environment's.
13324×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
13334×
        match self.remote_for_url(url) {
13344×
            Some(name) => self.remote_options(&name),
13350×
            None => RemoteOptions {
13360×
                repo_id: self.id().ok(),
13370×
                ..self.credentials_for(url)
13380×
            },
1339
        }
13404×
    }
1341
1342967×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1343967×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1344967×
    }
1345
1346111×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
1347111×
        self.oxy
1348111×
            .join("remotes")
1349111×
            .join(remote)
1350111×
            .join(format!("{bookmark}.serial"))
1351111×
    }
1352
135325×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
135425×
        fs::read_to_string(self.serial_path(remote, bookmark))
135525×
            .ok()
135625×
            .and_then(|s| s.trim().parse().ok())
135725×
    }
1358
135986×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
136086×
        let p = self.serial_path(remote, bookmark);
136186×
        fs::create_dir_all(p.parent().unwrap())?;
136286×
        write_atomic(&p, serial.to_string().as_bytes())
136386×
    }
1364
1365386×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1366386×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1367386×
    }
1368
1369
    /// The highest policy serial `remote` has ever presented.
1370351×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1371351×
        fs::read_to_string(self.policy_serial_path(remote))
1372351×
            .ok()
1373351×
            .and_then(|s| s.trim().parse().ok())
1374351×
    }
1375
137635×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
137735×
        let p = self.policy_serial_path(remote);
137835×
        fs::create_dir_all(p.parent().unwrap())?;
137935×
        write_atomic(&p, serial.to_string().as_bytes())
138035×
    }
1381
138227×
    fn lazy_dir(&self) -> PathBuf {
138327×
        self.oxy.join("lazy")
138427×
    }
1385
1386
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
13874×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
13884×
        fs::create_dir_all(self.lazy_dir())?;
13894×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
13904×
    }
1391
1392
    /// Which remote promised an absent blob, if any.
139315×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
139415×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
139515×
            .ok()
139615×
            .map(|s| s.trim().to_string())
139715×
    }
1398
1399
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
14004×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
14014×
        let Some(remote_name) = self.lazy_remote(blob) else {
14020×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1403
        };
14044×
        let remote = self.open_named_remote(&remote_name)?;
14054×
        let objects = remote.objects(&[*blob])?;
14069×
        for (ty, body) in objects {
14079×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
14089×
                self.store.put(ty, &body)?;
14090×
            }
1410
        }
14114×
        if !self.store.has(blob) {
14120×
            return fail(format!(
1413
                "{remote_name} did not send blob {}",
14140×
                blob.short(12)
1415
            ));
14164×
        }
14174×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
14184×
        Ok(())
14194×
    }
1420
1421
    /// After importing from `remote`, record every blob the changes reference
1422
    /// that the store lacks as lazily available from that remote.
14234×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
14244×
        let mut n = 0;
14254×
        for h in changes {
14264×
            let c = self.store.get_change(h)?;
142713×
            for e in &c.edits {
142813×
                if let Edit::Replace { old, new, .. } = e {
14296×
                    for b in [old, new].into_iter().flatten() {
14306×
                        if !self.store.has(b) {
14314×
                            self.register_lazy(b, remote)?;
14324×
                            n += 1;
14332×
                        }
1434
                    }
14357×
                }
1436
            }
1437
        }
14384×
        Ok(n)
14394×
    }
1440
1441
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1442351×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1443351×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1444473×
        for st in view
1445351×
            .bookmarks
1446351×
            .values()
1447351×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1448
        {
1449473×
            if let Ok(s) = self.store.get_state(st) {
1450473×
                have.extend(s.heads);
1451473×
            }
1452
        }
1453351×
        have.extend(view.workspaces.values().copied());
1454351×
        Ok(have.into_iter().collect())
1455351×
    }
1456
1457
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1458357×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1459357×
        let remote = self.open_named_remote(remote_name)?;
1460354×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1461352×
        let resp = remote.refs()?;
1462
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1463
        // and signed by roots we trust, or on first contact. A remote that
1464
        // once presented a policy may never present none or an older one:
1465
        // that is a downgrade. A remote that never presented one is
1466
        // unverified, and this fetch is checked only as far as possible.
1467351×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1468351×
        let seen = self.remote_policy_serial(remote_name);
1469351×
        let mut unverified = false;
1470351×
        match &resp.policy {
147114×
            Some(sp) => {
147214×
                if seen.is_some_and(|s| sp.policy.serial < s) {
14730×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
147414×
                }
14757×
                match &local_policy {
14767×
                    Some(l) if sp.policy.serial < l.serial => {}
14777×
                    Some(l) if sp.policy.serial == l.serial => {
14783×
                        if sp.policy.hash() != l.hash() {
14790×
                            return fail(format!(
1480
                                "{remote_name} presents a different policy with the same serial {}",
1481
                                l.serial
1482
                            ));
14833×
                        }
1484
                    }
1485
                    _ => {
148611×
                        self.adopt_policy_chain(
148711×
                            &resp.history,
148811×
                            sp,
148911×
                            &format!("oxy fetch {remote_name}"),
1490
                        )
149111×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1492
                    }
1493
                }
149414×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1495
            }
1496
            None => {
1497337×
                if seen.is_some() {
14980×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1499337×
                }
1500337×
                unverified = true;
1501
            }
1502
        }
1503351×
        let policy = if unverified {
1504337×
            None
1505
        } else {
150614×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1507
        };
1508351×
        let (op_ref, op) = self.head_op()?;
1509351×
        let mut view = op.view.clone();
1510351×
        let have = self.known_heads(&view)?;
1511351×
        let mut report = Vec::new();
1512351×
        let max_blob = self.config.max_blob;
1513358×
        for r in resp.refs {
1514358×
            let needed = {
1515358×
                let _t = crate::timing::phase("fetch: negotiate");
1516358×
                remote.negotiate(&have, &r.heads)?
1517
            };
1518358×
            let bundle = {
1519358×
                let _t = crate::timing::phase("fetch: bundle");
1520358×
                remote.fetch(&needed, max_blob)?
1521
            };
1522
            // Changes are not individually re-verified here: the bookmark's
1523
            // attestation (checked below) binds its whole state, and the
1524
            // receiver of the push verified the added changes at that time.
1525358×
            let imported = {
1526358×
                let _t = crate::timing::phase("fetch: import");
1527358×
                self.import_bundle(&bundle, false)?
1528
            };
1529358×
            if max_blob.is_some() {
15304×
                self.register_missing_blobs(&imported, remote_name)?;
1531354×
            }
1532492×
            for h in &r.heads {
1533492×
                if !self.store.has(h) {
15340×
                    return fail(format!("remote did not send head {}", h.short(12)));
1535492×
                }
1536
            }
1537358×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1538358×
            if state != r.state {
15390×
                return fail(format!(
1540
                    "remote state {} does not match its heads",
15410×
                    r.state.short(12)
1542
                ));
1543358×
            }
1544358×
            if let Some(p) = &policy {
154514×
                let Some(sa) = &r.attestation else {
15460×
                    return fail(format!(
1547
                        "{remote_name}/{} has no attestation, which its policy requires",
1548
                        r.name
1549
                    ));
1550
                };
155114×
                let signer = sa
155214×
                    .sigs
155314×
                    .first()
155414×
                    .map(|s| s.key)
155514×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
1556
                // A certified signer is checked at the host's acceptance,
1557
                // when it countersigned one; else at the attestation's time.
155814×
                let at = self.certified_time(&signer, sa, r.accepted.as_ref());
155914×
                if !p.authorizes(&signer, &r.name)
15604×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
15614×
                    && !self.certified_authorized(p, &signer, &r.name, Scope::REFS, at)
1562
                {
15630×
                    return fail(format!(
1564
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1565
                        r.name,
15660×
                        signer.short(12)
1567
                    ));
156814×
                }
1569344×
            }
1570358×
            if let Some(sa) = &r.attestation {
1571
                let AttestBody::Ref {
157225×
                    old_state,
157325×
                    new_state,
1574
                    ..
157525×
                } = &sa.attest.body
1576
                else {
15770×
                    return fail("remote sent a non-ref attestation for a bookmark");
1578
                };
157925×
                let (old_state, new_state) = (*old_state, *new_state);
158025×
                let serial = self
158125×
                    .check_ref_attest(
158225×
                        sa,
158325×
                        &r.name,
158425×
                        &old_state,
158525×
                        &new_state,
158625×
                        self.last_seen_serial(remote_name, &r.name),
1587
                        true,
1588
                    )
158925×
                    .map_err(|e| {
15900×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
15910×
                    })?;
159225×
                if new_state != r.state {
15930×
                    return fail(format!(
1594
                        "attestation for {}/{} does not cover its current state",
1595
                        remote_name, r.name
1596
                    ));
159725×
                }
159825×
                let ar = self.store.put_attest(&sa.attest)?;
159925×
                for sig in &sa.sigs {
160025×
                    self.store.put_signature(&ar, sig)?;
1601
                }
160225×
                self.record_serial(remote_name, &r.name, serial)?;
1603333×
            }
1604358×
            view.remotes
1605358×
                .entry(remote_name.to_string())
1606358×
                .or_default()
1607358×
                .insert(r.name.clone(), state);
1608358×
            report.push((r.name, r.heads, imported.len()));
1609
        }
1610351×
        let mut new_tags = 0;
1611351×
        for t in &resp.tags {
161213×
            if view.tags.contains_key(&t.name) {
16134×
                continue;
16149×
            }
1615
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
16169×
            let missing: Vec<ChangeHash> = t
16179×
                .heads
16189×
                .iter()
16199×
                .filter(|h| !self.store.has(h))
16209×
                .copied()
16219×
                .collect();
16229×
            if !missing.is_empty() {
16230×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
16240×
                let bundle = remote.fetch(&needed, max_blob)?;
16250×
                self.import_bundle(&bundle, false)?;
16269×
            }
16279×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
16289×
            self.adopt_tag(&mut view, t, policy.as_ref())
16299×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
16309×
            new_tags += 1;
1631
        }
1632351×
        if view != op.view {
1633340×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
163411×
        }
1635351×
        let _ = self.run_hook(
1636351×
            "post-fetch",
1637351×
            &format!(
1638
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1639351×
                json_str(remote_name),
1640358×
                json_array(report.iter().map(|(n, heads, _)| format!(
1641
                    "{{\"name\":{},\"heads\":{}}}",
1642358×
                    json_str(n),
1643492×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1644
                )))
1645
            ),
1646
        );
1647351×
        Ok(FetchReport {
1648351×
            refs: report,
1649351×
            unverified,
1650351×
            new_tags,
1651351×
        })
1652357×
    }
1653
1654
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1655
    /// the changes within `depth` steps of its heads, and the boundary below.
16561×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
16571×
        let remote = self.open_named_remote(remote_name)?;
16581×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
16591×
        let resp = remote.refs()?;
16601×
        let bookmark = self.config.bookmark.clone();
16611×
        if let Some(sp) = &resp.policy {
16620×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
16630×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
16640×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
16651×
        }
16661×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
16670×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1668
        };
16691×
        if r.heads.is_empty() {
16700×
            return Ok(0);
16711×
        }
1672
        // Base: the remote's checkpoint of exactly these heads.
16731×
        let cp_bundle = remote.checkpoint(&r.heads)?;
16741×
        let mut cp_ref = None;
16753×
        for (ty, body) in &cp_bundle.objects {
16763×
            let put = self.store.put(*ty, body)?;
16773×
            if *ty == ObjectType::Checkpoint {
16781×
                cp_ref = Some(put);
16792×
            }
1680
        }
16811×
        let Some(cp_ref) = cp_ref else {
16820×
            return fail(format!("{remote_name} sent no checkpoint"));
1683
        };
16841×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1685
        // History window.
16861×
        let wanted = remote.shallow(&r.heads, depth)?;
16871×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
16881×
        let imported = self.import_bundle_shallow(&bundle, false)?;
16891×
        if self.config.max_blob.is_some() {
16900×
            self.register_missing_blobs(&imported, remote_name)?;
16911×
        }
16921×
        self.refresh_boundary(&imported)?;
16931×
        if let Some(sa) = &r.attestation {
16940×
            let ar = self.store.put_attest(&sa.attest)?;
16950×
            for sig in &sa.sigs {
16960×
                self.store.put_signature(&ar, sig)?;
1697
            }
16980×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
16990×
                self.record_serial(remote_name, &r.name, serial)?;
17000×
            }
17011×
        }
17021×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
17031×
        let (op_ref, op) = self.head_op()?;
17041×
        let mut view = op.view.clone();
17051×
        view.remotes
17061×
            .entry(remote_name.to_string())
17071×
            .or_default()
17081×
            .insert(r.name.clone(), state);
17091×
        self.record_op(
17101×
            &[op_ref],
17111×
            &format!("oxy fetch {remote_name} --depth {depth}"),
17121×
            view,
17130×
        )?;
17141×
        Ok(imported.len())
17151×
    }
1716
1717
    /// Fetch, then take the union of the local bookmark's state with the
1718
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1719105×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1720105×
        let _wc = self.lock_working_copy()?;
1721105×
        self.fetch(remote_name)?;
1722102×
        let (op_ref, op) = self.head_op()?;
1723102×
        let current = self.config.bookmark.clone();
1724102×
        let mut local_current = self.heads_of(&op.view, &current)?;
1725102×
        local_current.sort();
1726102×
        let mut view = op.view.clone();
1727102×
        let mut current_heads = local_current.clone();
1728102×
        let mut changed = false;
1729102×
        let mut others = Vec::new();
1730102×
        let tracked = op
1731102×
            .view
1732102×
            .remotes
1733102×
            .get(remote_name)
1734102×
            .cloned()
1735102×
            .unwrap_or_default();
1736106×
        for (name, remote_state) in tracked {
1737
            // Every local bookmark tracks the remote's of the same name;
1738
            // the current one may be new here.
1739106×
            let local_state = op.view.bookmarks.get(&name).copied();
1740106×
            if local_state.is_none() && name != current {
17410×
                continue;
1742106×
            }
1743106×
            if local_state == Some(remote_state) {
17449×
                continue;
174597×
            }
174697×
            let local = self.heads_of(&op.view, &name)?;
174797×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1748131×
            if remote_heads.iter().all(|h| local.contains(h)) {
17490×
                continue;
175097×
            }
175197×
            let mut all = local.clone();
175297×
            all.extend(remote_heads);
175397×
            let st = self.load_state_history(&all)?;
175497×
            let mut heads = st.maximal(&all);
175597×
            heads.sort();
175697×
            let mut sorted_local = local;
175797×
            sorted_local.sort();
175897×
            if heads == sorted_local {
17591×
                continue;
176096×
            }
176196×
            view.bookmarks.insert(
176296×
                name.clone(),
176396×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1764
            );
176596×
            if name == current {
176694×
                changed = true;
176794×
                current_heads = heads;
176894×
            } else {
17692×
                others.push(name);
17702×
            }
1771
        }
1772102×
        if changed || !others.is_empty() {
177395×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
17747×
        }
1775
        // The working copy follows its bookmark whenever nothing would be
1776
        // lost, also when this pull brought nothing new but it had been
1777
        // left behind (oxygen#89).
1778102×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1779
        Ok(PullReport {
1780102×
            heads: if changed {
178194×
                current_heads
1782
            } else {
17838×
                local_current
1784
            },
1785102×
            changed,
1786102×
            checked_out,
1787102×
            others,
1788
        })
1789105×
    }
1790
1791
    /// How many changes the working copy's bookmark has that its base
1792
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1793
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1794
    /// the bookmark or holds changes the bookmark lacks. History is read
1795
    /// only when the base and the bookmark's heads differ (oxygen#89).
17967×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
17977×
        let (_, wc) = self.working_copy()?;
17987×
        let mut base = wc.deps.clone();
17997×
        base.sort();
18007×
        let mut heads = self.bookmark_heads()?;
18017×
        heads.sort();
18027×
        if base == heads || heads.is_empty() {
18036×
            return Ok(None);
18041×
        }
18051×
        let state = self.load_state_history(&heads)?;
18061×
        if !base.iter().all(|h| state.contains(h)) {
18070×
            return Ok(None);
18081×
        }
18091×
        let had = if base.is_empty() {
18100×
            0
1811
        } else {
18121×
            self.load_state_history(&base)?.len()
1813
        };
18141×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
18157×
    }
1816
1817
    /// Bring the working copy to `heads`, the state of its bookmark
1818
    /// `bookmark`, when nothing would be lost: its base is part of that
1819
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1820
    /// with uncommitted work, the work comes along when the new changes
1821
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1822
    /// it followed only from exactly the bookmark's old heads, so a working
1823
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1824
    /// or a pull from another workspace) never caught up, and nothing said
1825
    /// so (oxygen#74, #89). Returns whether it moved.
1826102×
    pub fn follow_bookmark(
1827102×
        &self,
1828102×
        heads: &[ChangeHash],
1829102×
        bookmark: &str,
1830102×
        command: &str,
1831102×
    ) -> Result<bool> {
1832102×
        let snap = self.snapshot(command)?;
1833102×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1834102×
        let mut base = snap.base.maximal(&snap.wc.deps);
1835102×
        base.sort();
1836102×
        let mut target = heads.to_vec();
1837102×
        target.sort();
1838102×
        if base == target {
18397×
            return Ok(false);
184095×
        }
184195×
        let state = self.load_state_history(heads)?;
1842182×
        if !base.iter().all(|h| state.contains(h)) {
1843
            // The working copy holds changes the bookmark lacks: not ours to move.
18440×
            return Ok(false);
184595×
        }
184695×
        if clean {
184795×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
184895×
            Ok(true)
1849
        } else {
18500×
            Ok(self
18510×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
18520×
                .is_ok())
1853
        }
1854102×
    }
1855
1856
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1857
    /// changes and attesting the reference when a key is available.
1858
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1859
    /// state, attested when we have an identity. The local bookmark, if
1860
    /// any, is kept; only the remote-tracking entry goes.
18615×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
18625×
        let remote = self.open_named_remote(remote_name)?;
18635×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
18645×
        let resp = remote.refs()?;
18657×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
18661×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1867
        };
18684×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
18690×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
18704×
        }
18714×
        let attestation = match self.secret_key()? {
18722×
            Some(_) => Some(self.sign_attest(&Attest {
18732×
                repo: self.id()?,
18742×
                hlc: Hlc::now(),
18752×
                body: AttestBody::Ref {
18762×
                    name: bookmark.to_string(),
18772×
                    old_state: r.state,
18782×
                    new_state: ObjectRef::ZERO,
18792×
                    serial: r.last_serial.unwrap_or(0) + 1,
18802×
                },
18810×
            })?),
18822×
            None => None,
1883
        };
18844×
        let results = remote.push(
18854×
            Bundle::default(),
18864×
            vec![RefUpdate {
18874×
                name: bookmark.to_string(),
18884×
                old_state: r.state,
18894×
                new_state: ObjectRef::ZERO,
18904×
                force: true,
18914×
                attestation,
18924×
            }],
18934×
            None,
18944×
            vec![],
18950×
        )?;
18964×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
18972×
            let (op_ref, op) = self.head_op()?;
18982×
            let mut view = op.view.clone();
18992×
            if let Some(m) = view.remotes.get_mut(remote_name) {
19002×
                m.remove(bookmark);
19012×
            }
19022×
            self.record_op(
19032×
                &[op_ref],
19042×
                &format!("oxy push {remote_name} --delete {bookmark}"),
19052×
                view,
19060×
            )?;
19072×
        }
19084×
        Ok(results)
19095×
    }
1910
1911
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1912
    /// repository's config (its URL, token, CA and store settings), its
1913
    /// tracking bookmarks in the view, and a store remote's mirror under
1914
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
19153×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
19163×
        if !self.config.remotes.contains_key(name) {
19171×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
19182×
        }
19192×
        let prefix = format!("remote.{name}.");
19202×
        let keys: Vec<String> = self
19212×
            .config
19222×
            .repo_layer()
19232×
            .keys()
19244×
            .filter(|k| k.starts_with(&prefix))
19252×
            .cloned()
19262×
            .collect();
19273×
        for k in keys {
19283×
            self.config.set(&k, "")?;
1929
        }
19302×
        self.config.remotes.remove(name);
19312×
        self.save_config()?;
19322×
        let (op_ref, op) = self.head_op()?;
19332×
        if op.view.remotes.contains_key(name) {
19341×
            let mut view = op.view.clone();
19351×
            view.remotes.remove(name);
19361×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
19371×
        }
19382×
        let mirror = self.oxy.join("remotes").join(name);
19392×
        if mirror.is_dir() {
19400×
            fs::remove_dir_all(&mirror)?;
19412×
        }
19422×
        Ok(())
19433×
    }
1944
1945
    /// `changes`, in dependency order, cut into batches of about
1946
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1947
    /// There is always one, perhaps empty.
1948277×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1949277×
        let blob_len = |r: &ObjectRef| -> u64 {
195029×
            self.store
195129×
                .get_typed(r, ObjectType::Blob)
195229×
                .ok()
195329×
                .and_then(|b| Blob::decode(&b).ok())
195429×
                .map_or(0, |b| b.length)
195529×
        };
1956277×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1957377×
        for h in changes {
1958377×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1959377×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1960377×
            let mut weight = raw.len() as u64;
1961476×
            for t in &texts {
1962476×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
196326×
                    weight += blob_len(r);
1964450×
                }
1965
            }
1966608×
            for e in &c.edits {
19673×
                if let Edit::Replace { new: Some(b), .. } = e {
19683×
                    weight += blob_len(b);
1969605×
                }
1970
            }
1971377×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
19725×
                out.push(std::mem::take(&mut batch));
19735×
                bytes = 0;
1974372×
            }
1975377×
            batch.push(*h);
1976377×
            bytes += weight;
1977
        }
1978277×
        out.push(batch);
1979277×
        Ok(out)
1980277×
    }
1981
1982344×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1983344×
        let bookmark = self.config.bookmark.clone();
1984344×
        self.push_bookmark(remote_name, &bookmark, force)
1985344×
    }
1986
1987
    /// `push` for a named bookmark (`oxy push -b NAME`).
1988352×
    pub fn push_bookmark(
1989352×
        &self,
1990352×
        remote_name: &str,
1991352×
        bookmark: &str,
1992352×
        force: bool,
1993352×
    ) -> Result<Vec<RefResult>> {
1994352×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1995352×
    }
1996
1997
    /// `push_bookmark`, saying how a long push is going: one line per
1998
    /// batch sent (oxygen#95).
1999360×
    pub fn push_bookmark_with(
2000360×
        &self,
2001360×
        remote_name: &str,
2002360×
        bookmark: &str,
2003360×
        force: bool,
2004360×
        progress: crate::store::Progress,
2005360×
    ) -> Result<Vec<RefResult>> {
2006360×
        let (op_ref, op) = self.head_op()?;
2007360×
        if !op.view.bookmarks.contains_key(bookmark) {
20080×
            return fail(format!("no bookmark {bookmark}"));
2009360×
        }
2010360×
        let bookmark = bookmark.to_string();
2011360×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
2012
        // pre-push hook: may veto before the remote is contacted.
2013360×
        self.run_hook(
2014360×
            "pre-push",
2015360×
            &format!(
2016
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
2017360×
                json_str(remote_name),
2018360×
                json_str(&bookmark),
2019742×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
2020
            ),
20211×
        )?;
2022359×
        let remote = self.open_named_remote(remote_name)?;
2023359×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
2024356×
        let resp = remote.refs()?;
2025356×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
2026356×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
2027356×
        let policy_to_send = match (&local_policy, &resp.policy) {
202824×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
20299×
            (Some(l), None) => Some(l.clone()),
203012×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
20311×
                return fail(format!(
2032
                    "{remote_name} has a newer policy (serial {}); fetch first",
2033
                    r.policy.serial
2034
                ));
2035
            }
2036334×
            _ => None,
2037
        };
2038355×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
2039355×
        if remote_has_policy && self.secret_key()?.is_none() {
20401×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
2041354×
        }
2042354×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
2043354×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
2044354×
            .tag_refs()?
2045354×
            .into_iter()
2046354×
            .filter(|t| !remote_tags.contains(&t.name))
2047354×
            .collect();
2048354×
        let refs = resp.refs;
2049354×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
2050354×
        let (remote_state, remote_heads, last_serial) =
2051354×
            match refs.iter().find(|r| r.name == bookmark) {
2052337×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
205317×
                None => (empty, vec![], None),
2054
            };
2055354×
        let new_state = self
2056354×
            .store
2057354×
            .put_state(&StateObject::new(local_heads.clone()))?;
2058
        // A push that carries a policy re-attests the bookmark even when its
2059
        // state is unchanged, so the current attestation is always by a key
2060
        // the current policy authorizes (a revoked key's attestation would
2061
        // otherwise be refused by every later fetch).
2062354×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
20639×
            return Ok(vec![RefResult {
20649×
                name: bookmark,
20659×
                ok: true,
20669×
                reason: "already up to date".into(),
20679×
            }]);
2068345×
        }
2069375×
        for h in &remote_heads {
2070375×
            if !self.store.has(h) {
207167×
                return fail(format!(
2072
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
207367×
                    h.short(12)
2074
                ));
2075308×
            }
2076
        }
2077278×
        if !force {
2078278×
            let closure = self.closure_in_store(&local_heads)?;
2079284×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
20800×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
2081278×
            }
20820×
        }
2083278×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
2084278×
        let key = self.secret_key()?.map(|(k, _)| k);
2085278×
        if let Some(key) = key {
2086
            // Seal this author's changes that carry no valid authenticator,
2087
            // and adopt anonymous ones (zero author, spec §14.4). The seals
2088
            // are stored, so each batch's bundle carries those it needs.
208981×
            let mut unsigned = Vec::new();
209081×
            for h in &to_send {
209174×
                let c = self.store.get_change_meta(h)?;
209274×
                if (c.author == key || c.author.is_zero())
209370×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
209442×
                {
209542×
                    unsigned.push(*h);
209642×
                }
2097
            }
209881×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
209939×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
2100
            }
2101197×
        }
2102
        // A long history goes in batches, in dependency order, so neither
2103
        // side holds it whole and no request passes the remote's limit:
2104
        // all but the last carry objects alone; the last moves the bookmark
2105
        // (oxygen#95).
2106277×
        let batches = self.push_batches(&to_send)?;
2107277×
        let (last, earlier) = batches.split_last().expect("at least one batch");
2108277×
        for (i, batch) in earlier.iter().enumerate() {
21095×
            progress(&format!(
21105×
                "part {} of {}: {} changes",
21115×
                i + 1,
21125×
                batches.len(),
21135×
                batch.len()
21145×
            ));
21155×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
21165×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
21175×
                Some(r) if r.ok => {}
21180×
                Some(r) => {
21190×
                    return fail(format!(
2120
                        "{remote_name} refused part {} of the push: {}",
21210×
                        i + 1,
2122
                        r.reason
2123
                    ))
2124
                }
2125
                None => {
21260×
                    return fail(format!(
2127
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
2128
                    ))
2129
                }
2130
            }
2131
        }
2132277×
        if batches.len() > 1 {
21331×
            progress(&format!(
21341×
                "part {} of {}: {} changes",
21351×
                batches.len(),
21361×
                batches.len(),
21371×
                last.len()
21381×
            ));
2139276×
        }
2140277×
        let mut bundle = self.bundle_for(last)?;
2141277×
        bundle.objects.push((
2142277×
            ObjectType::State,
2143277×
            StateObject::new(local_heads.clone()).encode(),
2144277×
        ));
2145277×
        let attestation = match key {
214680×
            Some(_) => Some(self.sign_attest(&Attest {
214780×
                repo: self.id()?,
214880×
                hlc: Hlc::now(),
214980×
                body: AttestBody::Ref {
215080×
                    name: bookmark.clone(),
215180×
                    old_state: remote_state,
215280×
                    new_state,
215380×
                    serial: next_serial(last_serial),
215480×
                },
21551×
            })?),
2156197×
            None => None,
2157
        };
2158
        // Whoever signed the move, and whom a delegate acts for, travel with
2159
        // it: a receiver that has never seen a change by this delegate could
2160
        // not otherwise check its signature (oxygenhub#129).
2161276×
        if attestation.is_some() {
2162158×
            for k in [self.signing_key(), self.config.author_key]
216379×
                .into_iter()
216479×
                .flatten()
2165
            {
2166158×
                if let Ok(id) = self.identity(&k) {
2167158×
                    let body = id.encode();
2168158×
                    if !bundle
2169158×
                        .objects
2170158×
                        .iter()
2171186×
                        .any(|(t, b)| *t == ObjectType::Identity && *b == body)
217216×
                    {
217316×
                        bundle.objects.push((ObjectType::Identity, body));
2174142×
                    }
21750×
                }
2176
            }
2177
            // A short-lived signing key's certificate goes with it (§14.7).
217879×
            let signers: Vec<KeyId> = self.signing_key().into_iter().collect();
217979×
            self.attach_certificates_for(&mut bundle, &signers)?;
2180197×
        }
2181276×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
218279×
            AttestBody::Ref { serial, .. } => Some(serial),
21830×
            _ => None,
218479×
        });
2185276×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
2186
        // Tag states must be present on the remote: bundle their changes too.
2187276×
        for t in &tags_to_send {
21886×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
21896×
            let extra: Vec<ChangeHash> =
21906×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
21916×
            if !extra.is_empty() {
21920×
                let more = self.bundle_for(&extra)?;
21930×
                bundle.changes.extend(more.changes);
21940×
                bundle.hashes.extend(more.hashes);
21950×
                bundle.attests.extend(more.attests);
21960×
                bundle.objects.extend(more.objects);
21976×
            }
21986×
            bundle.objects.push((
21996×
                ObjectType::State,
22006×
                StateObject::new(t.heads.clone()).encode(),
22016×
            ));
2202
        }
2203276×
        if let Some(l) = &policy_to_send {
220421×
            let remote_serial = resp_policy_serial;
220521×
            bundle.policies = self
220621×
                .policy_history()?
220721×
                .into_iter()
220847×
                .filter(|sp| {
220947×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
221023×
                        && sp.policy.serial < l.policy.serial
221147×
                })
221221×
                .collect();
2213255×
        }
2214276×
        let results = remote.push(
2215276×
            bundle,
2216276×
            vec![RefUpdate {
2217276×
                name: bookmark.clone(),
2218276×
                old_state: remote_state,
2219276×
                new_state,
2220276×
                force,
2221276×
                attestation,
2222276×
            }],
2223276×
            policy_to_send,
2224276×
            tags_to_send,
22257×
        )?;
222621×
        if let (Some(serial), true) = (
2227269×
            sent_serial,
2228275×
            results.iter().any(|r| r.ok && r.name == "policy"),
2229
        ) {
223021×
            self.record_policy_serial(remote_name, serial)?;
2231248×
        }
2232290×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
2233249×
            let mut view = op.view.clone();
2234249×
            view.remotes
2235249×
                .entry(remote_name.to_string())
2236249×
                .or_default()
2237249×
                .insert(bookmark.clone(), new_state);
2238249×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
2239246×
            if let Some(s) = serial {
224061×
                self.record_serial(remote_name, &bookmark, s)?;
2241185×
            }
224220×
        }
2243264×
        Ok(results)
2244360×
    }
2245
2246
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
2247
    /// bookmark set to the remote's, working copy checked out.
2248228×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
2249228×
        Self::clone_with(url, dest, None, &[])
2250228×
    }
2251
2252
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
2253
    /// read, and materializing only `sparse` paths (which implies lazy blobs
2254
    /// unless a size is given, so out-of-scope binaries are never fetched).
2255236×
    pub fn clone_with(
2256236×
        url: &str,
2257236×
        dest: &Path,
2258236×
        max_blob: Option<u64>,
2259236×
        sparse: &[String],
2260236×
    ) -> Result<Repo> {
2261236×
        Self::clone_full(url, dest, max_blob, sparse, None)
2262236×
    }
2263
2264
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
2265
    /// changes within `depth` steps of them; the rest is the boundary.
22661×
    pub fn clone_shallow(
22671×
        url: &str,
22681×
        dest: &Path,
22691×
        depth: u32,
22701×
        max_blob: Option<u64>,
22711×
        sparse: &[String],
22721×
    ) -> Result<Repo> {
22731×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
22741×
    }
2275
2276237×
    fn clone_full(
2277237×
        url: &str,
2278237×
        dest: &Path,
2279237×
        max_blob: Option<u64>,
2280237×
        sparse: &[String],
2281237×
        depth: Option<u32>,
2282237×
    ) -> Result<Repo> {
2283237×
        let options = crate::credentials::Credentials::user().options_for(url);
2284237×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
2285237×
    }
2286
2287
    /// Clone a subrepo with the credentials the parent would use for its
2288
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
2289
    /// subrepo: it finds the same ones again through its parent.
22909×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
22919×
        let options = self.credentials_for(url);
22929×
        Self::clone_using(url, dest, None, &[], None, &options)
22939×
    }
2294
2295
    /// The name of a remote of this repository on the same hub (scheme,
2296
    /// host and port) as `url`.
229721×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
229825×
        let origin = |u: &str| -> Option<String> {
229925×
            let (scheme, rest) = u.split_once("://")?;
23008×
            if !matches!(scheme, "http" | "https") {
23010×
                return None;
23028×
            }
23038×
            let host = rest.split('/').next()?;
23048×
            Some(format!(
23058×
                "{}://{}",
23068×
                scheme.to_ascii_lowercase(),
23078×
                host.to_ascii_lowercase()
23088×
            ))
230925×
        };
231021×
        let want = origin(url)?;
23114×
        self.config
23124×
            .remotes
23134×
            .iter()
23144×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
23154×
            .map(|(name, _)| name.clone())
231621×
    }
2317
2318
    /// The token and CA to reach `url` with: those of a remote of this
2319
    /// repository on the same hub (scheme, host and port), else the
2320
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2321
    /// and enclosing checkouts', as a clone would use them.
232221×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
232321×
        match self.remote_on_same_hub(url) {
23241×
            Some(name) => RemoteOptions {
23251×
                repo_id: None,
23261×
                cache_dir: None,
23271×
                ..self.remote_options(&name)
23281×
            },
2329
            None => {
233020×
                let mut options = RemoteOptions::default();
233120×
                self.fill_credentials(url, &mut options);
233220×
                options
2333
            }
2334
        }
233521×
    }
2336
2337246×
    fn clone_using(
2338246×
        url: &str,
2339246×
        dest: &Path,
2340246×
        max_blob: Option<u64>,
2341246×
        sparse: &[String],
2342246×
        depth: Option<u32>,
2343246×
        options: &RemoteOptions,
2344246×
    ) -> Result<Repo> {
2345246×
        let remote = open_remote(url, options)?;
2346246×
        let id = remote.repo_id()?;
2347242×
        if id == crate::protocol::UNBOUND_ID {
23482×
            return fail(format!(
2349
                "{url} is empty and unbound: push a repository to it first"
2350
            ));
2351240×
        }
2352240×
        let mut repo = Repo::init_with_id(dest, id)?;
2353240×
        repo.config
2354240×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2355240×
        if let Some(m) = max_blob {
23562×
            repo.config.set("filter.max-blob", &m.to_string())?;
2357238×
        } else if !sparse.is_empty() {
23581×
            repo.config.set("filter.max-blob", "0")?;
2359237×
        }
2360240×
        if !sparse.is_empty() {
23611×
            repo.config.set("filter.paths", &sparse.join(","))?;
2362239×
        }
2363240×
        repo.save_config()?;
2364240×
        if let Some(depth) = depth {
23651×
            repo.fetch_shallow("origin", depth)?;
2366
        } else {
2367239×
            repo.fetch("origin")?;
2368
        }
2369239×
        let (op_ref, op) = repo.head_op()?;
2370
        // The remote's default bookmark, else ours (main), else its only one.
2371239×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2372
        // Asked of the remote as now configured, so a store-backed one
2373
        // answers from the mirror the fetch just filled.
2374239×
        let advertised = repo
2375239×
            .open_named_remote("origin")
2376239×
            .ok()
2377239×
            .and_then(|r| r.refs().ok())
2378239×
            .and_then(|r| r.default_bookmark);
2379239×
        let bookmark = advertised
2380239×
            .filter(|b| theirs.contains_key(b))
2381239×
            .or_else(|| {
23827×
                theirs
23837×
                    .contains_key(&repo.config.bookmark)
23847×
                    .then(|| repo.config.bookmark.clone())
23857×
            })
2386239×
            .or_else(|| {
23870×
                (theirs.len() == 1)
23880×
                    .then(|| theirs.keys().next().cloned())
23890×
                    .flatten()
23900×
            })
2391239×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2392239×
        let initial = repo.config.bookmark.clone();
2393239×
        if bookmark != repo.config.bookmark {
23941×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
23951×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
23961×
            repo.config.bookmark = bookmark.clone();
2397238×
        }
2398239×
        if let Some(state) = theirs.get(&bookmark).copied() {
2399239×
            let heads = repo.store.get_state(&state)?.heads;
2400239×
            let mut view = op.view.clone();
2401
            // The empty bookmark `init` made goes when another is checked out.
2402239×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
24031×
                view.bookmarks.remove(&initial);
2404238×
            }
2405239×
            view.bookmarks.insert(bookmark, state);
2406239×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2407239×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
24080×
        }
2409239×
        Ok(repo)
2410246×
    }
2411
}
2412
2413
/// The serial of a reference's next attestation: one more than the last the
2414
/// remote reports, or, for a bookmark the remote does not have, the clock in
2415
/// milliseconds, so a bookmark created again after a deletion goes past the
2416
/// deletion's serial the remote keeps.
241780×
fn next_serial(last: Option<u64>) -> u64 {
241880×
    match last {
241951×
        Some(l) => l + 1,
242029×
        None => Hlc::now().wall_ms.max(1),
2421
    }
242280×
}