OXYGENHUB

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

1388 of 1563 lines run, 198 of 282 functions · run #252 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
impl Repo {
48
    // ------------------------------------------------------------ serving (spec §16)
49
501249×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
511249×
        self.oxy.join("attest").join(name_file(bookmark))
521249×
    }
53
54
    /// The latest reference attestation stored for a bookmark.
551175×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
561175×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
57195×
            Ok(h) => {
58195×
                let r = ObjectRef::from_hex(h.trim())
59195×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
60
                Ok(Some((
61195×
                    r,
62
                    SignedAttest {
63195×
                        attest: self.store.get_attest(&r)?,
64195×
                        sigs: self.store.signatures(&r)?,
65
                    },
66
                )))
67
            }
68980×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
690×
            Err(e) => Err(e.into()),
70
        }
711175×
    }
72
7374×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7474×
        fs::create_dir_all(self.oxy.join("attest"))?;
7574×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
7674×
    }
77
78968×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
79968×
        let view = self.view()?;
80968×
        let mut out = Vec::new();
81990×
        for (name, state) in &view.bookmarks {
82990×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
83990×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
84104×
                AttestBody::Ref { serial, .. } => Some(serial),
850×
                _ => None,
86104×
            });
87990×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
88990×
            out.push(RemoteRef {
89990×
                name: name.clone(),
90990×
                state: *state,
91990×
                heads: self.store.get_state(state)?.heads,
92990×
                attestation,
93990×
                last_serial,
94
            });
95
        }
96968×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
97968×
        let history = self
98968×
            .policy_history()?
99968×
            .into_iter()
100968×
            .filter(|sp| {
10166×
                policy
10266×
                    .as_ref()
10366×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10466×
            })
105968×
            .collect();
106
        Ok(RefsResponse {
107968×
            refs: out,
108968×
            policy,
109968×
            tags: self.tag_refs()?,
110968×
            history,
111968×
            default_bookmark: Some(self.config.bookmark.clone()),
112
        })
113968×
    }
114
115
    /// Every change reachable from `heads` that is in the store.
1161266×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1171266×
        let mut seen = BTreeSet::new();
1181266×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1194660×
        while let Some(h) = stack.pop() {
1203394×
            if seen.contains(&h) || !self.store.has(&h) {
1211005×
                continue;
1222389×
            }
1232389×
            seen.insert(h);
1242389×
            stack.extend(self.store.get_change_meta(&h)?.deps);
125
        }
1261266×
        Ok(seen)
1271266×
    }
128
129
    /// The changes within `depth` dependency steps of `heads` (spec §17),
130
    /// nearest first; depth 1 is the heads themselves.
1313×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1323×
        let mut out = Vec::new();
1333×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1343×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1353×
        for _ in 0..depth.max(1) {
1368×
            let mut next = Vec::new();
13712×
            for h in layer {
13812×
                if !seen.insert(h) || !self.store.has(&h) {
1392×
                    continue;
14010×
                }
14110×
                let c = self.store.get_change(&h)?;
14210×
                next.extend(c.deps.iter().copied());
14310×
                out.push(h);
144
            }
1458×
            if next.is_empty() {
1461×
                break;
1477×
            }
1487×
            layer = next;
149
        }
1503×
        out.reverse();
1513×
        Ok(out)
1523×
    }
153
1541819×
    fn shallow_path(&self) -> PathBuf {
1551819×
        self.oxy.join("shallow")
1561819×
    }
157
158
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1591816×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1601816×
        fs::read_to_string(self.shallow_path())
1611816×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1621816×
            .unwrap_or_default()
1631816×
    }
164
165169×
    pub fn is_shallow(&self) -> bool {
166169×
        !self.boundary().is_empty()
167169×
    }
168
1693×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1703×
        if boundary.is_empty() {
1711×
            let _ = fs::remove_file(self.shallow_path());
1721×
            return Ok(());
1732×
        }
1742×
        let text: String = boundary
1752×
            .iter()
1762×
            .map(|h| format!("{}\n", h.to_hex()))
1772×
            .collect();
1782×
        write_atomic(&self.shallow_path(), text.as_bytes())
1793×
    }
180
181
    /// Recompute the boundary from what is stored: every dependency of a
182
    /// stored change that is not itself stored.
1833×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1843×
        let mut boundary = self.boundary();
1853×
        boundary.retain(|h| !self.store.has(h));
18610×
        for h in imported {
18713×
            for d in self.store.get_change_meta(h)?.deps {
18813×
                if !self.store.has(&d) {
1892×
                    boundary.insert(d);
19011×
                }
191
            }
192
        }
1933×
        self.write_boundary(&boundary)
1943×
    }
195
196
    /// Fetch `depth` more levels of history below the shallow boundary.
1972×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
1982×
        let boundary = self.boundary();
1992×
        if boundary.is_empty() {
2000×
            return Ok(0);
2012×
        }
2022×
        let remote = self.open_named_remote(remote_name)?;
2032×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2042×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2052×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2062×
        if self.config.max_blob.is_some() {
2070×
            self.register_missing_blobs(&imported, remote_name)?;
2082×
        }
2092×
        self.refresh_boundary(&imported)?;
2102×
        Ok(imported.len())
2112×
    }
212
213
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
214723×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
215723×
        let have = self.closure_in_store(have)?;
216
        // In a shallow repository the walk stops at the boundary, whose
217
        // changes the remote is assumed to hold.
218723×
        let boundary = self.boundary();
219723×
        let mut out = Vec::new();
220723×
        let mut done: BTreeSet<ChangeHash> = have.clone();
221723×
        done.extend(boundary.iter().copied());
222
        // Iterative post-order DFS.
2231222×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2243191×
        while let Some((h, expanded)) = stack.pop() {
2252468×
            if done.contains(&h) {
226406×
                continue;
2272062×
            }
2282062×
            if !self.store.has(&h) {
2290×
                return fail(format!("change {} is not in this repository", h.short(12)));
2302062×
            }
2312062×
            if expanded {
2321031×
                done.insert(h);
2331031×
                out.push(h);
2341031×
                continue;
2351031×
            }
2361031×
            stack.push((h, true));
2371031×
            for d in self.store.get_change_meta(&h)?.deps {
238756×
                if !done.contains(&d) {
239215×
                    stack.push((d, false));
240541×
                }
241
            }
242
        }
243723×
        Ok(out)
244723×
    }
245
246
    /// Bundle changes (in the given dependency order) with their signatures,
247
    /// seals, identities, blobs, chunks.
248352×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
249352×
        self.bundle_for_filtered(changes, None)
250352×
    }
251
252
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2534×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2544×
        let mut out = Vec::new();
2554×
        for r in refs {
2564×
            let (ty, body) = match self.store.get(r) {
2574×
                Ok(x) => x,
2580×
                Err(StoreError::NotFound(_)) => continue,
2590×
                Err(e) => return Err(e.into()),
260
            };
2614×
            if ty == ObjectType::Blob {
2625×
                for c in Blob::decode(&body)?.chunks {
2635×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2645×
                        out.push((cty, cb));
2655×
                    }
266
                }
2670×
            }
2684×
            out.push((ty, body));
269
        }
2704×
        Ok(out)
2714×
    }
272
273
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
274
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
275399×
    pub fn bundle_for_filtered(
276399×
        &self,
277399×
        changes: &[ChangeHash],
278399×
        max_blob: Option<u64>,
279399×
    ) -> Result<Bundle> {
280399×
        self.bundle_of(changes, max_blob, false)
281399×
    }
282
283
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
284
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
285
    /// with their text blobs and chunks among the objects, so neither side
286
    /// decodes or encodes their text.
287308×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
288308×
        self.bundle_of(changes, max_blob, true)
289308×
    }
290
291707×
    fn bundle_of(
292707×
        &self,
293707×
        changes: &[ChangeHash],
294707×
        max_blob: Option<u64>,
295707×
        raw: bool,
296707×
    ) -> Result<Bundle> {
297707×
        let mut bundle = Bundle::default();
298707×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
299707×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3001142×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3011142×
            if !r.is_zero() && self.store.has(r) {
302263×
                objects.insert(*r);
303879×
            }
3041142×
        };
3051031×
        for h in changes {
306
            // Raw: the stored bytes, and a skeleton for the rest.
3071031×
            let (c, encoded) = if raw {
308527×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
309527×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3105006×
                for t in texts {
3115006×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3123×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3133×
                        objects.insert(r);
3143×
                        objects.extend(blob.chunks);
3155003×
                    }
316
                }
317527×
                (skel, Some(bytes))
318
            } else {
319504×
                (self.store.get_change(h)?, None)
320
            };
3211031×
            let sigs = self.store.signatures(h)?;
3221031×
            add_object(&c.author, &mut objects);
3231031×
            for s in &sigs {
32436×
                add_object(&s.key, &mut objects);
32536×
            }
3266114×
            for e in &c.edits {
3276114×
                if let Edit::Replace { old, new, .. } = e {
32815×
                    for b in [old, new].into_iter().flatten() {
32915×
                        if self.store.has(b) {
33015×
                            if let Ok(blob) =
33115×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
332
                            {
33315×
                                if max_blob.is_some_and(|m| blob.length > m) {
3344×
                                    continue;
33511×
                                }
33611×
                                objects.insert(*b);
33711×
                                objects.extend(blob.chunks.iter().copied());
3380×
                            }
3390×
                        }
340
                    }
3416101×
                }
342
            }
3431031×
            for s in self.store.seals_for(h)? {
34479×
                seals.insert(s);
34579×
            }
3461031×
            match encoded {
347527×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
348504×
                None => {
349504×
                    bundle.changes.push((c, sigs));
350504×
                    bundle.hashes.push(*h);
351504×
                }
352
            }
353
        }
354707×
        for r in seals {
35575×
            let attest = self.store.get_attest(&r)?;
35675×
            let sigs = self.store.signatures(&r)?;
35775×
            for s in &sigs {
35875×
                add_object(&s.key, &mut objects);
35975×
            }
36075×
            bundle.attests.push(SignedAttest { attest, sigs });
361
        }
362707×
        for r in objects {
363170×
            let (ty, body) = self.store.get(&r)?;
364170×
            bundle.objects.push((ty, body));
365
        }
366707×
        Ok(bundle)
367707×
    }
368
369
    /// Store a bundle's contents. With `strict`, every change must
370
    /// authenticate (signature or seal by its author or a delegate).
371677×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
372677×
        self.import_bundle_inner(bundle, strict, false)
373677×
    }
374
375
    /// Like `import_bundle`, accepting changes whose dependencies are absent
376
    /// (they join the shallow boundary).
3773×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
3783×
        self.import_bundle_inner(bundle, strict, true)
3793×
    }
380
381680×
    fn import_bundle_inner(
382680×
        &self,
383680×
        bundle: &Bundle,
384680×
        strict: bool,
385680×
        shallow: bool,
386680×
    ) -> Result<Vec<ChangeHash>> {
387680×
        let batch = self.store.begin_batch()?;
388680×
        let result = self.import_bundle_batched(bundle, strict, shallow);
389680×
        batch.finish()?;
390678×
        result
391680×
    }
392
393680×
    fn import_bundle_batched(
394680×
        &self,
395680×
        bundle: &Bundle,
396680×
        strict: bool,
397680×
        shallow: bool,
398680×
    ) -> Result<Vec<ChangeHash>> {
399680×
        for (ty, _) in &bundle.objects {
4000×
            if !matches!(
401446×
                ty,
402
                ObjectType::Chunk
403
                    | ObjectType::Blob
404
                    | ObjectType::Identity
405
                    | ObjectType::State
406
                    | ObjectType::Checkpoint
407
            ) {
4080×
                return fail(format!("bundle may not carry {} objects", ty.name()));
409446×
            }
410
        }
411
        // All at once: in a large batch they are compressed on every core.
412680×
        let objects: Vec<(ObjectType, &[u8])> = bundle
413680×
            .objects
414680×
            .iter()
415680×
            .map(|(ty, body)| (*ty, body.as_slice()))
416680×
            .collect();
417680×
        self.store.put_many(&objects)?;
418680×
        for sa in &bundle.attests {
41964×
            let r = self.store.put_attest(&sa.attest)?;
42064×
            for sig in &sa.sigs {
42164×
                self.store.put_signature(&r, sig)?;
422
            }
42364×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
42468×
                for h in hashes {
42568×
                    self.store.index_seal(h, &r)?;
426
                }
4270×
            }
428
        }
429
        // Each change's hash: from the bundle when its maker knew it, else
430
        // worked out once (for a change adding a whole tree, hashing is
431
        // chunking all its text).
432680×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
433671×
            bundle.hashes.clone()
434
        } else {
4359×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
436
        };
437680×
        let raw_hashes: Vec<ChangeHash> = bundle
438680×
            .raw_changes
439680×
            .iter()
440680×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
441680×
            .collect();
442680×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
443680×
        let boundary = self.boundary();
444680×
        let mut imported = Vec::new();
445
        // Changes as stored: checked, then stored as they are, their text
446
        // blobs having come with the objects.
447680×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
448528×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
449528×
            for d in &skel.deps {
450405×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
451
                {
4520×
                    return fail(format!(
453
                        "change {} depends on {}, which is neither stored nor in the bundle",
4540×
                        h.short(12),
4550×
                        d.short(12)
456
                    ));
457405×
                }
458
            }
4595007×
            for t in texts {
4605007×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
4614×
                    if !self.store.has(&r) {
4621×
                        return fail(format!(
463
                            "change {} came without its text blob {}",
4641×
                            h.short(12),
4651×
                            r.short(12)
466
                        ));
4673×
                    }
4685003×
                }
469
            }
470527×
            self.store.put(ObjectType::Change, bytes)?;
471527×
            for sig in sigs {
4724×
                self.store.put_signature(&h, sig)?;
473
            }
474527×
            imported.push(h);
475
        }
476679×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
477465×
            for d in &c.deps {
478305×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
479
                {
4803×
                    return fail(format!(
481
                        "change {} depends on {}, which is neither stored nor in the bundle",
4823×
                        h.short(12),
4833×
                        d.short(12)
484
                    ));
485302×
                }
486
            }
487462×
            let stored = self.store.put_change(c)?;
488462×
            if stored != h {
4890×
                return fail(format!(
490
                    "change {} is not the change the bundle names",
4910×
                    h.short(12)
492
                ));
493462×
            }
494462×
            for sig in sigs {
49525×
                self.store.put_signature(&h, sig)?;
496
            }
497462×
            imported.push(h);
498
        }
499676×
        if strict {
50028×
            for h in &imported {
50119×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
5021×
                    return fail(format!(
503
                        "change {} is not authenticated by its author",
5041×
                        h.short(12)
505
                    ));
50618×
                }
507
            }
508648×
        }
509675×
        Ok(imported)
510680×
    }
511
512
    /// Verify a reference attestation against an update it claims to describe.
513
    /// `allow_equal` lets a client re-read the attestation it already has; a
514
    /// server receiving a push requires a strictly greater serial.
515
    /// A reference attestation signed by a delegate of an identity the
516
    /// rule lists is authorized as that identity (spec §14.5): the identity
517
    /// named the delegate with the `refs` scope, still in force at `at_ms`
518
    /// (the attestation's wall time), and the policy names the identity.
519
    /// Revoked keys authorize nothing either way.
5206×
    pub(crate) fn delegate_authorized(
5216×
        &self,
5226×
        p: &crate::policy::Policy,
5236×
        signer: &KeyId,
5246×
        reference: &str,
5256×
        at_ms: u64,
5266×
    ) -> bool {
5276×
        if p.is_revoked(signer) {
5281×
            return false;
5295×
        }
5305×
        let Some(rule) = p.rule_for(reference) else {
5310×
            return false;
532
        };
5336×
        rule.keys.iter().any(|k| {
5346×
            !p.is_revoked(k)
5356×
                && p.identity(k)
5366×
                    .cloned()
5376×
                    .or_else(|| self.store.get_identity(k).ok())
5386×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
5396×
        })
5406×
    }
541
54293×
    fn check_ref_attest(
54393×
        &self,
54493×
        sa: &SignedAttest,
54593×
        name: &str,
54693×
        old_state: &ObjectRef,
54793×
        new_state: &ObjectRef,
54893×
        last_serial: Option<u64>,
54993×
        allow_equal: bool,
55093×
    ) -> std::result::Result<u64, String> {
551
        let AttestBody::Ref {
55293×
            name: n,
55393×
            old_state: o,
55493×
            new_state: nw,
55593×
            serial,
55693×
        } = &sa.attest.body
557
        else {
5580×
            return Err("attestation is not a ref attestation".into());
559
        };
56093×
        if n != name || o != old_state || nw != new_state {
5611×
            return Err("attestation does not describe this update".into());
56292×
        }
56392×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
5640×
            return Err("attestation is for a different repository".into());
56592×
        }
56692×
        if let Some(last) = last_serial {
56759×
            if *serial < last || (*serial == last && !allow_equal) {
5681×
                return Err(format!(
5691×
                    "attestation serial {serial} is not greater than the last seen {last}"
5701×
                ));
57158×
            }
57233×
        }
57391×
        let r = sa.attest.hash();
57491×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
57591×
        let id = self
57691×
            .store
57791×
            .get_identity(&sig.key)
57891×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
57991×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
58091×
        Ok(*serial)
58193×
    }
582
583
    /// Accept a push (spec §16.4). Without a trust policy every repository
584
    /// is unverified, so unsigned changes and unattested updates are accepted;
585
    /// attestations that are present must still be valid. With a policy,
586
    /// every change and update is checked against it. A newer policy in the
587
    /// push is applied first when it is signed by the current roots.
588259×
    pub fn receive_push(
589259×
        &self,
590259×
        bundle: Bundle,
591259×
        updates: Vec<RefUpdate>,
592259×
        policy: Option<SignedPolicy>,
593259×
        tags: Vec<crate::protocol::TagRef>,
594259×
    ) -> Result<Vec<RefResult>> {
595259×
        Ok(self
596259×
            .receive_push_report(bundle, updates, policy, tags)?
597
            .results)
598259×
    }
599
600
    /// `receive_push` with what a host wants to log: each accepted
601
    /// reference's old and new state and heads, and the changes this push
602
    /// stored (hub spec §6.12).
603298×
    pub fn receive_push_report(
604298×
        &self,
605298×
        bundle: Bundle,
606298×
        updates: Vec<RefUpdate>,
607298×
        policy: Option<SignedPolicy>,
608298×
        tags: Vec<crate::protocol::TagRef>,
609298×
    ) -> Result<PushReport> {
610298×
        let mut report = PushReport::default();
611298×
        let results = &mut report.results;
612298×
        if let Some(sp) = policy {
61318×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
61416×
                Ok(()) => {
61516×
                    results.push(RefResult {
61616×
                        name: "policy".into(),
61716×
                        ok: true,
61816×
                        reason: format!("serial {}", sp.policy.serial),
61916×
                    });
62016×
                }
6212×
                Err(e) => {
6222×
                    results.push(RefResult {
6232×
                        name: "policy".into(),
6242×
                        ok: false,
6252×
                        reason: e,
6262×
                    });
6272×
                    for u in updates {
6280×
                        results.push(RefResult {
6290×
                            name: u.name,
6300×
                            ok: false,
6310×
                            reason: "policy update was rejected".into(),
6320×
                        });
6330×
                    }
6342×
                    return Ok(report);
635
                }
636
            }
637280×
        }
638296×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
639296×
        match self.import_bundle(&bundle, policy.is_some()) {
640293×
            Ok(imported) => report.imported = imported,
6413×
            Err(e) => {
6423×
                for u in updates {
6433×
                    results.push(RefResult {
6443×
                        name: u.name,
6453×
                        ok: false,
6463×
                        reason: e.to_string(),
6473×
                    });
6483×
                }
6493×
                return Ok(report);
650
            }
651
        }
652293×
        let (op_ref, op) = self.head_op()?;
653293×
        let mut view = op.view.clone();
654293×
        let mut names = Vec::new();
655293×
        for u in updates {
656290×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
657290×
            let (ok, reason) = match outcome {
658266×
                Ok(()) => (true, String::new()),
65924×
                Err(e) => (false, e),
660
            };
661290×
            if ok {
662266×
                names.push(u.name.clone());
663266×
                let heads = self
664266×
                    .store
665266×
                    .get_state(&u.new_state)
666266×
                    .map(|s| s.heads)
667266×
                    .unwrap_or_default();
668266×
                report.updated.push(RefUpdated {
669266×
                    name: u.name.clone(),
670266×
                    old_state: u.old_state,
671266×
                    new_state: u.new_state,
672266×
                    heads,
673266×
                });
67424×
            }
675290×
            results.push(RefResult {
676290×
                name: u.name,
677290×
                ok,
678290×
                reason,
679290×
            });
680
        }
681293×
        for t in &tags {
6828×
            let name = format!("tags/{}", t.name);
6838×
            let new = !view.tags.contains_key(&t.name);
6848×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
685
                Ok(()) => {
686
                    // A tag new here is an update too, so a hub can start
687
                    // its pipeline's tag jobs (oxygenflow#24); one it
688
                    // already had, sent again, is not.
6896×
                    if new {
6906×
                        report.updated.push(RefUpdated {
6916×
                            name: name.clone(),
6926×
                            old_state: ObjectRef::ZERO,
6936×
                            new_state: t.state,
6946×
                            heads: t.heads.clone(),
6956×
                        });
6966×
                    }
6976×
                    names.push(name.clone());
6986×
                    results.push(RefResult {
6996×
                        name,
7006×
                        ok: true,
7016×
                        reason: String::new(),
7026×
                    });
703
                }
7042×
                Err(e) => results.push(RefResult {
7052×
                    name,
7062×
                    ok: false,
7072×
                    reason: e,
7082×
                }),
709
            }
710
        }
711293×
        if !names.is_empty() {
712266×
            self.record_op(
713266×
                &[op_ref],
714266×
                &format!("push received: {}", names.join(" ")),
715266×
                view,
7163×
            )?;
71727×
        }
718290×
        Ok(report)
719298×
    }
720
721
    /// Check an update's attestation against the latest one for its
722
    /// reference and store it as the new latest. Failures say what was
723
    /// being done, for which reference, so a refused push can be diagnosed
724
    /// from its reason alone.
72574×
    fn record_update_attest(
72674×
        &self,
72774×
        u: &RefUpdate,
72874×
        sa: &SignedAttest,
72974×
    ) -> std::result::Result<(), String> {
73074×
        let name = &u.name;
73174×
        let last = self
73274×
            .latest_ref_attest(name)
73374×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
73474×
            .and_then(|(_, a)| match a.attest.body {
73549×
                AttestBody::Ref { serial, .. } => Some(serial),
7360×
                _ => None,
73749×
            });
73874×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
73972×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
74072×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
74171×
        for sig in &sa.sigs {
74271×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
743
        }
74471×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
74574×
    }
746
747
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
748
    /// at `old_state`, is never the bookmark a non-bare repository has
749
    /// checked out (a bare one's default is its host's to protect, see
750
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
751
    /// an attestation by a key that may update it.
752
    /// The deletion's attestation stays the bookmark's latest, so an older
753
    /// one cannot be replayed to bring it back.
7543×
    fn apply_deletion(
7553×
        &self,
7563×
        view: &mut View,
7573×
        u: &RefUpdate,
7583×
        policy: Option<&crate::policy::Policy>,
7593×
    ) -> std::result::Result<(), String> {
7603×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
7610×
            return Err(format!("no bookmark {:?} to delete", u.name));
762
        };
7633×
        if current != u.old_state {
7640×
            return Err("stale: the remote bookmark has moved; pull first".into());
7653×
        }
7663×
        if !self.is_bare() && u.name == self.config.bookmark {
7671×
            return Err(format!(
7681×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
7691×
                u.name
7701×
            ));
7712×
        }
7722×
        if let Some(p) = policy {
7730×
            let Some(sa) = &u.attestation else {
7740×
                return Err(format!(
7750×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
7760×
                    u.name
7770×
                ));
778
            };
7790×
            let signer = sa
7800×
                .sigs
7810×
                .first()
7820×
                .map(|s| s.key)
7830×
                .ok_or("attestation carries no signature")?;
7840×
            if !p.authorizes(&signer, &u.name)
7850×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
786
            {
7870×
                return Err(format!(
7880×
                    "key {} may not delete {:?} under this repository's policy",
7890×
                    signer.short(12),
7900×
                    u.name
7910×
                ));
7920×
            }
7932×
        }
7942×
        if let Some(sa) = &u.attestation {
7951×
            self.record_update_attest(u, sa)?;
7961×
        }
7972×
        view.bookmarks.remove(&u.name);
7982×
        Ok(())
7993×
    }
800
801290×
    fn apply_update(
802290×
        &self,
803290×
        view: &mut View,
804290×
        u: &RefUpdate,
805290×
        policy: Option<&crate::policy::Policy>,
806290×
    ) -> std::result::Result<(), String> {
807290×
        if u.name == "policy" {
8080×
            return Err(
8090×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
8100×
            );
811290×
        }
812290×
        let empty = self
813290×
            .store
814290×
            .put_state(&StateObject::new(vec![]))
815290×
            .map_err(|e| e.to_string())?;
816290×
        if u.new_state.is_zero() {
8173×
            return self.apply_deletion(view, u, policy);
818287×
        }
819287×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
820287×
        if current != u.old_state {
8219×
            return Err("stale: the remote bookmark has moved; pull first".into());
822278×
        }
823278×
        let new_state = self
824278×
            .store
825278×
            .get_state(&u.new_state)
826278×
            .map_err(|_| "new state object is missing".to_string())?;
827575×
        for h in &new_state.heads {
828575×
            if !self.store.has(h) {
8291×
                return Err(format!("head {} is missing", h.short(12)));
830574×
            }
831
        }
832277×
        if !u.force {
833276×
            let old_heads = self
834276×
                .store
835276×
                .get_state(&current)
836276×
                .map_err(|e| e.to_string())?
837
                .heads;
838276×
            let closure = self
839276×
                .closure_in_store(&new_state.heads)
840276×
                .map_err(|e| e.to_string())?;
841323×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
8421×
                return Err(format!(
8431×
                    "not a fast-forward: current head {} would be dropped (use --force)",
8441×
                    h.short(12)
8451×
                ));
846275×
            }
8471×
        }
848276×
        if let Some(p) = policy {
84926×
            let Some(sa) = &u.attestation else {
8501×
                return Err(format!(
8511×
                    "{:?} requires a signed reference attestation under this repository's policy",
8521×
                    u.name
8531×
                ));
854
            };
85525×
            let signer = sa
85625×
                .sigs
85725×
                .first()
85825×
                .map(|s| s.key)
85925×
                .ok_or("attestation carries no signature")?;
86025×
            if !p.authorizes(&signer, &u.name)
8616×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
862
            {
8635×
                return Err(format!(
8645×
                    "key {} may not update {:?} under this repository's policy",
8655×
                    signer.short(12),
8665×
                    u.name
8675×
                ));
86820×
            }
86920×
            let old_heads = self
87020×
                .store
87120×
                .get_state(&current)
87220×
                .map_err(|e| e.to_string())?
873
                .heads;
87420×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
875250×
        }
876270×
        if let Some(sa) = &u.attestation {
87773×
            self.record_update_attest(u, sa)?;
878197×
        }
879264×
        view.bookmarks.insert(u.name.clone(), u.new_state);
880264×
        Ok(())
881290×
    }
882
883
    // ------------------------------------------------------------ client side
884
885945×
    fn remote_url(&self, name: &str) -> Result<String> {
886945×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
8872×
            RepoError::Msg(format!(
8882×
                "no remote named {name:?}; add one with `oxy remote add`"
8892×
            ))
8902×
        })
891945×
    }
892
893
    /// Refuse a remote that is another repository. An **unbound** remote
894
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
895
    /// for pushes, which bind it to this repository's id (spec §16.1).
896706×
    fn check_remote_id(
897706×
        &self,
898706×
        remote: &dyn crate::protocol::Remote,
899706×
        remote_name: &str,
900706×
        allow_unbound: bool,
901706×
    ) -> Result<()> {
902706×
        let theirs = remote.repo_id()?;
903705×
        if theirs == self.id()? {
904685×
            return Ok(());
90520×
        }
90620×
        if theirs == crate::protocol::UNBOUND_ID {
90717×
            if allow_unbound {
90816×
                return Ok(());
9091×
            }
9101×
            return fail(format!(
911
                "remote {remote_name:?} is empty and unbound: push to it first"
912
            ));
9133×
        }
9143×
        fail(format!(
915
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
916
        ))
917706×
    }
918
919
    /// Credentials and trust for a remote: `remote.<name>.token` and
920
    /// `remote.<name>.ca`, else the defaults for its URL
921
    /// ([`Repo::fill_credentials`]).
922962×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
923962×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
924962×
        let mut options = RemoteOptions {
925962×
            repo_id: self.id().ok(),
926962×
            token: self.config.remote_tokens.get(name).cloned(),
927962×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
928962×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
929962×
        };
930962×
        self.fill_credentials(&url, &mut options);
931962×
        options
932962×
    }
933
934
    /// The user's credential store (`credentials.toml` beside the user
935
    /// configuration file).
936979×
    pub fn credentials(&self) -> crate::credentials::Credentials {
937979×
        crate::credentials::Credentials::at(
938979×
            self.user_config
939979×
                .parent()
940979×
                .map(Path::to_path_buf)
941979×
                .unwrap_or_else(default_home),
942
        )
943979×
    }
944
945
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
946
    /// then the user's credential store for its hub, then a remote on the
947
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
948980×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
949980×
        if options.token.is_some() && options.ca.is_some() {
9501×
            return;
951979×
        }
952979×
        let stored = self.credentials().options_for(url);
953979×
        options.token = options.token.take().or(stored.token);
954979×
        options.ca = options.ca.take().or(stored.ca);
955979×
        if options.token.is_some() && options.ca.is_some() {
9560×
            return;
957979×
        }
958979×
        let Some(hub) = crate::credentials::hub_of(url) else {
959846×
            return;
960
        };
961133×
        let mut at = self.root.parent();
962530×
        while let Some(dir) = at {
963397×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
9640×
                break;
965
            };
966397×
            for (key, remote_url) in &cfg {
9675×
                let Some(name) = key
9685×
                    .strip_prefix("remote.")
9695×
                    .and_then(|k| k.strip_suffix(".url"))
970
                else {
9712×
                    continue;
972
                };
9733×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
9741×
                    continue;
9752×
                }
9762×
                if options.token.is_none() {
9772×
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
9782×
                }
9792×
                if options.ca.is_none() {
9802×
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
9812×
                }
982
            }
983397×
            if options.token.is_some() && options.ca.is_some() {
9840×
                return;
985397×
            }
986397×
            at = dir.parent();
987
        }
988980×
    }
989
990
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
991
    /// no changes and no reference updates, which the receiver stores.
9920×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
9930×
        let remote = self.open_named_remote(remote_name)?;
9940×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
9950×
        let mut bundle = Bundle::default();
9960×
        for r in seals {
9970×
            let attest = self.store.get_attest(r)?;
9980×
            let sigs = self.store.signatures(r)?;
9990×
            bundle
10000×
                .attests
10010×
                .push(crate::protocol::SignedAttest { attest, sigs });
1002
        }
10030×
        let results = remote.push(bundle, vec![], None, vec![])?;
10040×
        if let Some(r) = results.iter().find(|r| !r.ok) {
10050×
            return fail(format!("{}: {}", r.name, r.reason));
10060×
        }
10070×
        Ok(())
10080×
    }
1009
1010
    /// The remote whose URL starts with `base` (a hub), if configured.
10113×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
10123×
        let base = base.trim_end_matches('/');
10133×
        self.config
10143×
            .remotes
10153×
            .iter()
10163×
            .find(|(_, url)| url.trim_end_matches('/') == base)
10173×
            .map(|(name, _)| name.clone())
10183×
    }
1019
1020
    /// Open a remote by name or, failing that, by URL with the default
1021
    /// credentials (see [`Repo::credentials_for`]).
10220×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
10230×
        if let Some(name) = self.remote_for_url(url) {
10240×
            return Ok((name.clone(), self.open_named_remote(&name)?));
10250×
        }
10260×
        let options = RemoteOptions {
10270×
            repo_id: self.id().ok(),
10280×
            ..self.credentials_for(url)
10290×
        };
10300×
        Ok((url.to_string(), open_remote(url, &options)?))
10310×
    }
1032
1033
    /// Credentials for a URL: those of the configured remote with that
1034
    /// URL, else the environment's.
10353×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
10363×
        match self.remote_for_url(url) {
10373×
            Some(name) => self.remote_options(&name),
10380×
            None => RemoteOptions {
10390×
                repo_id: self.id().ok(),
10400×
                ..self.credentials_for(url)
10410×
            },
1042
        }
10433×
    }
1044
1045945×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1046945×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1047945×
    }
1048
104992×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
105092×
        self.oxy
105192×
            .join("remotes")
105292×
            .join(remote)
105392×
            .join(format!("{bookmark}.serial"))
105492×
    }
1055
105619×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
105719×
        fs::read_to_string(self.serial_path(remote, bookmark))
105819×
            .ok()
105919×
            .and_then(|s| s.trim().parse().ok())
106019×
    }
1061
106273×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
106373×
        let p = self.serial_path(remote, bookmark);
106473×
        fs::create_dir_all(p.parent().unwrap())?;
106573×
        write_atomic(&p, serial.to_string().as_bytes())
106673×
    }
1067
1068368×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1069368×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1070368×
    }
1071
1072
    /// The highest policy serial `remote` has ever presented.
1073344×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1074344×
        fs::read_to_string(self.policy_serial_path(remote))
1075344×
            .ok()
1076344×
            .and_then(|s| s.trim().parse().ok())
1077344×
    }
1078
107924×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
108024×
        let p = self.policy_serial_path(remote);
108124×
        fs::create_dir_all(p.parent().unwrap())?;
108224×
        write_atomic(&p, serial.to_string().as_bytes())
108324×
    }
1084
108527×
    fn lazy_dir(&self) -> PathBuf {
108627×
        self.oxy.join("lazy")
108727×
    }
1088
1089
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
10904×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
10914×
        fs::create_dir_all(self.lazy_dir())?;
10924×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
10934×
    }
1094
1095
    /// Which remote promised an absent blob, if any.
109615×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
109715×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
109815×
            .ok()
109915×
            .map(|s| s.trim().to_string())
110015×
    }
1101
1102
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
11034×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
11044×
        let Some(remote_name) = self.lazy_remote(blob) else {
11050×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1106
        };
11074×
        let remote = self.open_named_remote(&remote_name)?;
11084×
        let objects = remote.objects(&[*blob])?;
11099×
        for (ty, body) in objects {
11109×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
11119×
                self.store.put(ty, &body)?;
11120×
            }
1113
        }
11144×
        if !self.store.has(blob) {
11150×
            return fail(format!(
1116
                "{remote_name} did not send blob {}",
11170×
                blob.short(12)
1118
            ));
11194×
        }
11204×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
11214×
        Ok(())
11224×
    }
1123
1124
    /// After importing from `remote`, record every blob the changes reference
1125
    /// that the store lacks as lazily available from that remote.
11264×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
11274×
        let mut n = 0;
11284×
        for h in changes {
11294×
            let c = self.store.get_change(h)?;
113013×
            for e in &c.edits {
113113×
                if let Edit::Replace { old, new, .. } = e {
11326×
                    for b in [old, new].into_iter().flatten() {
11336×
                        if !self.store.has(b) {
11344×
                            self.register_lazy(b, remote)?;
11354×
                            n += 1;
11362×
                        }
1137
                    }
11387×
                }
1139
            }
1140
        }
11414×
        Ok(n)
11424×
    }
1143
1144
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1145344×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1146344×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1147467×
        for st in view
1148344×
            .bookmarks
1149344×
            .values()
1150344×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1151
        {
1152467×
            if let Ok(s) = self.store.get_state(st) {
1153467×
                have.extend(s.heads);
1154467×
            }
1155
        }
1156344×
        have.extend(view.workspaces.values().copied());
1157344×
        Ok(have.into_iter().collect())
1158344×
    }
1159
1160
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1161349×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1162349×
        let remote = self.open_named_remote(remote_name)?;
1163347×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1164345×
        let resp = remote.refs()?;
1165
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1166
        // and signed by roots we trust, or on first contact. A remote that
1167
        // once presented a policy may never present none or an older one:
1168
        // that is a downgrade. A remote that never presented one is
1169
        // unverified, and this fetch is checked only as far as possible.
1170344×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1171344×
        let seen = self.remote_policy_serial(remote_name);
1172344×
        let mut unverified = false;
1173344×
        match &resp.policy {
11748×
            Some(sp) => {
11758×
                if seen.is_some_and(|s| sp.policy.serial < s) {
11760×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
11778×
                }
11785×
                match &local_policy {
11795×
                    Some(l) if sp.policy.serial < l.serial => {}
11805×
                    Some(l) if sp.policy.serial == l.serial => {
11811×
                        if sp.policy.hash() != l.hash() {
11820×
                            return fail(format!(
1183
                                "{remote_name} presents a different policy with the same serial {}",
1184
                                l.serial
1185
                            ));
11861×
                        }
1187
                    }
1188
                    _ => {
11897×
                        self.adopt_policy_chain(
11907×
                            &resp.history,
11917×
                            sp,
11927×
                            &format!("oxy fetch {remote_name}"),
1193
                        )
11947×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1195
                    }
1196
                }
11978×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1198
            }
1199
            None => {
1200336×
                if seen.is_some() {
12010×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1202336×
                }
1203336×
                unverified = true;
1204
            }
1205
        }
1206344×
        let policy = if unverified {
1207336×
            None
1208
        } else {
12098×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1210
        };
1211344×
        let (op_ref, op) = self.head_op()?;
1212344×
        let mut view = op.view.clone();
1213344×
        let have = self.known_heads(&view)?;
1214344×
        let mut report = Vec::new();
1215344×
        let max_blob = self.config.max_blob;
1216351×
        for r in resp.refs {
1217351×
            let needed = {
1218351×
                let _t = crate::timing::phase("fetch: negotiate");
1219351×
                remote.negotiate(&have, &r.heads)?
1220
            };
1221351×
            let bundle = {
1222351×
                let _t = crate::timing::phase("fetch: bundle");
1223351×
                remote.fetch(&needed, max_blob)?
1224
            };
1225
            // Changes are not individually re-verified here: the bookmark's
1226
            // attestation (checked below) binds its whole state, and the
1227
            // receiver of the push verified the added changes at that time.
1228351×
            let imported = {
1229351×
                let _t = crate::timing::phase("fetch: import");
1230351×
                self.import_bundle(&bundle, false)?
1231
            };
1232351×
            if max_blob.is_some() {
12334×
                self.register_missing_blobs(&imported, remote_name)?;
1234347×
            }
1235522×
            for h in &r.heads {
1236522×
                if !self.store.has(h) {
12370×
                    return fail(format!("remote did not send head {}", h.short(12)));
1238522×
                }
1239
            }
1240351×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1241351×
            if state != r.state {
12420×
                return fail(format!(
1243
                    "remote state {} does not match its heads",
12440×
                    r.state.short(12)
1245
                ));
1246351×
            }
1247351×
            if let Some(p) = &policy {
12488×
                let Some(sa) = &r.attestation else {
12490×
                    return fail(format!(
1250
                        "{remote_name}/{} has no attestation, which its policy requires",
1251
                        r.name
1252
                    ));
1253
                };
12548×
                let signer = sa
12558×
                    .sigs
12568×
                    .first()
12578×
                    .map(|s| s.key)
12588×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
12598×
                if !p.authorizes(&signer, &r.name)
12600×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1261
                {
12620×
                    return fail(format!(
1263
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1264
                        r.name,
12650×
                        signer.short(12)
1266
                    ));
12678×
                }
1268343×
            }
1269351×
            if let Some(sa) = &r.attestation {
1270
                let AttestBody::Ref {
127119×
                    old_state,
127219×
                    new_state,
1273
                    ..
127419×
                } = &sa.attest.body
1275
                else {
12760×
                    return fail("remote sent a non-ref attestation for a bookmark");
1277
                };
127819×
                let (old_state, new_state) = (*old_state, *new_state);
127919×
                let serial = self
128019×
                    .check_ref_attest(
128119×
                        sa,
128219×
                        &r.name,
128319×
                        &old_state,
128419×
                        &new_state,
128519×
                        self.last_seen_serial(remote_name, &r.name),
1286
                        true,
1287
                    )
128819×
                    .map_err(|e| {
12890×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
12900×
                    })?;
129119×
                if new_state != r.state {
12920×
                    return fail(format!(
1293
                        "attestation for {}/{} does not cover its current state",
1294
                        remote_name, r.name
1295
                    ));
129619×
                }
129719×
                let ar = self.store.put_attest(&sa.attest)?;
129819×
                for sig in &sa.sigs {
129919×
                    self.store.put_signature(&ar, sig)?;
1300
                }
130119×
                self.record_serial(remote_name, &r.name, serial)?;
1302332×
            }
1303351×
            view.remotes
1304351×
                .entry(remote_name.to_string())
1305351×
                .or_default()
1306351×
                .insert(r.name.clone(), state);
1307351×
            report.push((r.name, r.heads, imported.len()));
1308
        }
1309344×
        let mut new_tags = 0;
1310344×
        for t in &resp.tags {
131110×
            if view.tags.contains_key(&t.name) {
13124×
                continue;
13136×
            }
1314
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
13156×
            let missing: Vec<ChangeHash> = t
13166×
                .heads
13176×
                .iter()
13186×
                .filter(|h| !self.store.has(h))
13196×
                .copied()
13206×
                .collect();
13216×
            if !missing.is_empty() {
13220×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
13230×
                let bundle = remote.fetch(&needed, max_blob)?;
13240×
                self.import_bundle(&bundle, false)?;
13256×
            }
13266×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
13276×
            self.adopt_tag(&mut view, t, policy.as_ref())
13286×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
13296×
            new_tags += 1;
1330
        }
1331344×
        if view != op.view {
1332335×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
13339×
        }
1334344×
        let _ = self.run_hook(
1335344×
            "post-fetch",
1336344×
            &format!(
1337
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1338344×
                json_str(remote_name),
1339351×
                json_array(report.iter().map(|(n, heads, _)| format!(
1340
                    "{{\"name\":{},\"heads\":{}}}",
1341351×
                    json_str(n),
1342522×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1343
                )))
1344
            ),
1345
        );
1346344×
        Ok(FetchReport {
1347344×
            refs: report,
1348344×
            unverified,
1349344×
            new_tags,
1350344×
        })
1351349×
    }
1352
1353
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1354
    /// the changes within `depth` steps of its heads, and the boundary below.
13551×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
13561×
        let remote = self.open_named_remote(remote_name)?;
13571×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13581×
        let resp = remote.refs()?;
13591×
        let bookmark = self.config.bookmark.clone();
13601×
        if let Some(sp) = &resp.policy {
13610×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
13620×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
13630×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
13641×
        }
13651×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
13660×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1367
        };
13681×
        if r.heads.is_empty() {
13690×
            return Ok(0);
13701×
        }
1371
        // Base: the remote's checkpoint of exactly these heads.
13721×
        let cp_bundle = remote.checkpoint(&r.heads)?;
13731×
        let mut cp_ref = None;
13743×
        for (ty, body) in &cp_bundle.objects {
13753×
            let put = self.store.put(*ty, body)?;
13763×
            if *ty == ObjectType::Checkpoint {
13771×
                cp_ref = Some(put);
13782×
            }
1379
        }
13801×
        let Some(cp_ref) = cp_ref else {
13810×
            return fail(format!("{remote_name} sent no checkpoint"));
1382
        };
13831×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1384
        // History window.
13851×
        let wanted = remote.shallow(&r.heads, depth)?;
13861×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
13871×
        let imported = self.import_bundle_shallow(&bundle, false)?;
13881×
        if self.config.max_blob.is_some() {
13890×
            self.register_missing_blobs(&imported, remote_name)?;
13901×
        }
13911×
        self.refresh_boundary(&imported)?;
13921×
        if let Some(sa) = &r.attestation {
13930×
            let ar = self.store.put_attest(&sa.attest)?;
13940×
            for sig in &sa.sigs {
13950×
                self.store.put_signature(&ar, sig)?;
1396
            }
13970×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
13980×
                self.record_serial(remote_name, &r.name, serial)?;
13990×
            }
14001×
        }
14011×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
14021×
        let (op_ref, op) = self.head_op()?;
14031×
        let mut view = op.view.clone();
14041×
        view.remotes
14051×
            .entry(remote_name.to_string())
14061×
            .or_default()
14071×
            .insert(r.name.clone(), state);
14081×
        self.record_op(
14091×
            &[op_ref],
14101×
            &format!("oxy fetch {remote_name} --depth {depth}"),
14111×
            view,
14120×
        )?;
14131×
        Ok(imported.len())
14141×
    }
1415
1416
    /// Fetch, then take the union of the local bookmark's state with the
1417
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1418107×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1419107×
        let _wc = self.lock_working_copy()?;
1420107×
        self.fetch(remote_name)?;
1421105×
        let (op_ref, op) = self.head_op()?;
1422105×
        let current = self.config.bookmark.clone();
1423105×
        let mut local_current = self.heads_of(&op.view, &current)?;
1424105×
        local_current.sort();
1425105×
        let mut view = op.view.clone();
1426105×
        let mut current_heads = local_current.clone();
1427105×
        let mut changed = false;
1428105×
        let mut others = Vec::new();
1429105×
        let tracked = op
1430105×
            .view
1431105×
            .remotes
1432105×
            .get(remote_name)
1433105×
            .cloned()
1434105×
            .unwrap_or_default();
1435109×
        for (name, remote_state) in tracked {
1436
            // Every local bookmark tracks the remote's of the same name;
1437
            // the current one may be new here.
1438109×
            let local_state = op.view.bookmarks.get(&name).copied();
1439109×
            if local_state.is_none() && name != current {
14400×
                continue;
1441109×
            }
1442109×
            if local_state == Some(remote_state) {
14437×
                continue;
1444102×
            }
1445102×
            let local = self.heads_of(&op.view, &name)?;
1446102×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1447136×
            if remote_heads.iter().all(|h| local.contains(h)) {
14480×
                continue;
1449102×
            }
1450102×
            let mut all = local.clone();
1451102×
            all.extend(remote_heads);
1452102×
            let st = self.load_state_history(&all)?;
1453102×
            let mut heads = st.maximal(&all);
1454102×
            heads.sort();
1455102×
            let mut sorted_local = local;
1456102×
            sorted_local.sort();
1457102×
            if heads == sorted_local {
14581×
                continue;
1459101×
            }
1460101×
            view.bookmarks.insert(
1461101×
                name.clone(),
1462101×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1463
            );
1464101×
            if name == current {
146599×
                changed = true;
146699×
                current_heads = heads;
146799×
            } else {
14682×
                others.push(name);
14692×
            }
1470
        }
1471105×
        if !changed && others.is_empty() {
14725×
            return Ok(PullReport {
14735×
                heads: local_current,
14745×
                changed: false,
14755×
                checked_out: false,
14765×
                others,
14775×
            });
1478100×
        }
1479100×
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1480100×
        let mut checked_out = false;
1481100×
        if changed {
1482
            // Follow along if the working copy was clean and on the old heads.
148399×
            let snap = self.snapshot("oxy pull")?;
148499×
            let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
148599×
            let mut base = snap.base.maximal(&snap.wc.deps);
148699×
            base.sort();
148799×
            if base == local_current {
148899×
                if clean {
148999×
                    self.checkout(&current_heads, false, "oxy pull (checkout)")?;
149099×
                    checked_out = true;
14910×
                } else {
14920×
                    // Uncommitted work comes along when the pulled changes
14930×
                    // leave its paths alone, as `git pull` does; otherwise
14940×
                    // the working copy stays and the caller says so
14950×
                    // (oxygen#74).
14960×
                    checked_out = self
14970×
                        .checkout_carry(&current_heads, &current, "oxy pull (checkout --carry)")
14980×
                        .is_ok();
14990×
                }
15000×
            }
15011×
        }
1502100×
        Ok(PullReport {
1503100×
            heads: current_heads,
1504100×
            changed,
1505100×
            checked_out,
1506100×
            others,
1507100×
        })
1508107×
    }
1509
1510
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1511
    /// changes and attesting the reference when a key is available.
1512
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1513
    /// state, attested when we have an identity. The local bookmark, if
1514
    /// any, is kept; only the remote-tracking entry goes.
15155×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
15165×
        let remote = self.open_named_remote(remote_name)?;
15175×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
15185×
        let resp = remote.refs()?;
15197×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
15201×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1521
        };
15224×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
15230×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
15244×
        }
15254×
        let attestation = match self.secret_key()? {
15262×
            Some(_) => Some(self.sign_attest(&Attest {
15272×
                repo: self.id()?,
15282×
                hlc: Hlc::now(),
15292×
                body: AttestBody::Ref {
15302×
                    name: bookmark.to_string(),
15312×
                    old_state: r.state,
15322×
                    new_state: ObjectRef::ZERO,
15332×
                    serial: r.last_serial.unwrap_or(0) + 1,
15342×
                },
15350×
            })?),
15362×
            None => None,
1537
        };
15384×
        let results = remote.push(
15394×
            Bundle::default(),
15404×
            vec![RefUpdate {
15414×
                name: bookmark.to_string(),
15424×
                old_state: r.state,
15434×
                new_state: ObjectRef::ZERO,
15444×
                force: true,
15454×
                attestation,
15464×
            }],
15474×
            None,
15484×
            vec![],
15490×
        )?;
15504×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
15512×
            let (op_ref, op) = self.head_op()?;
15522×
            let mut view = op.view.clone();
15532×
            if let Some(m) = view.remotes.get_mut(remote_name) {
15542×
                m.remove(bookmark);
15552×
            }
15562×
            self.record_op(
15572×
                &[op_ref],
15582×
                &format!("oxy push {remote_name} --delete {bookmark}"),
15592×
                view,
15600×
            )?;
15612×
        }
15624×
        Ok(results)
15635×
    }
1564
1565346×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1566346×
        let bookmark = self.config.bookmark.clone();
1567346×
        self.push_bookmark(remote_name, &bookmark, force)
1568346×
    }
1569
1570
    /// `push` for a named bookmark (`oxy push -b NAME`).
1571354×
    pub fn push_bookmark(
1572354×
        &self,
1573354×
        remote_name: &str,
1574354×
        bookmark: &str,
1575354×
        force: bool,
1576354×
    ) -> Result<Vec<RefResult>> {
1577354×
        let (op_ref, op) = self.head_op()?;
1578354×
        if !op.view.bookmarks.contains_key(bookmark) {
15790×
            return fail(format!("no bookmark {bookmark}"));
1580354×
        }
1581354×
        let bookmark = bookmark.to_string();
1582354×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1583
        // pre-push hook: may veto before the remote is contacted.
1584354×
        self.run_hook(
1585354×
            "pre-push",
1586354×
            &format!(
1587
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1588354×
                json_str(remote_name),
1589354×
                json_str(&bookmark),
1590736×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1591
            ),
15921×
        )?;
1593353×
        let remote = self.open_named_remote(remote_name)?;
1594353×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1595350×
        let resp = remote.refs()?;
1596350×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1597350×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1598350×
        let policy_to_send = match (&local_policy, &resp.policy) {
159917×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
16007×
            (Some(l), None) => Some(l.clone()),
16018×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
16021×
                return fail(format!(
1603
                    "{remote_name} has a newer policy (serial {}); fetch first",
1604
                    r.policy.serial
1605
                ));
1606
            }
1607333×
            _ => None,
1608
        };
1609349×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1610349×
        if remote_has_policy && self.secret_key()?.is_none() {
16111×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1612348×
        }
1613348×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1614348×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1615348×
            .tag_refs()?
1616348×
            .into_iter()
1617348×
            .filter(|t| !remote_tags.contains(&t.name))
1618348×
            .collect();
1619348×
        let refs = resp.refs;
1620348×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1621348×
        let (remote_state, remote_heads, last_serial) =
1622348×
            match refs.iter().find(|r| r.name == bookmark) {
1623332×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
162416×
                None => (empty, vec![], None),
1625
            };
1626348×
        let new_state = self
1627348×
            .store
1628348×
            .put_state(&StateObject::new(local_heads.clone()))?;
1629
        // A push that carries a policy re-attests the bookmark even when its
1630
        // state is unchanged, so the current attestation is always by a key
1631
        // the current policy authorizes (a revoked key's attestation would
1632
        // otherwise be refused by every later fetch).
1633348×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
16348×
            return Ok(vec![RefResult {
16358×
                name: bookmark,
16368×
                ok: true,
16378×
                reason: "already up to date".into(),
16388×
            }]);
1639340×
        }
1640413×
        for h in &remote_heads {
1641413×
            if !self.store.has(h) {
164273×
                return fail(format!(
1643
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
164473×
                    h.short(12)
1645
                ));
1646340×
            }
1647
        }
1648267×
        if !force {
1649267×
            let closure = self.closure_in_store(&local_heads)?;
1650316×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
16510×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1652267×
            }
16530×
        }
1654267×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1655267×
        let mut bundle = self.bundle_for(&to_send)?;
1656267×
        let key = self.secret_key()?.map(|(k, _)| k);
1657267×
        if let Some(key) = key {
1658
            // Seal this author's changes that carry no valid authenticator,
1659
            // and adopt anonymous ones (zero author, spec §14.4).
166072×
            let mut unsigned = Vec::new();
166172×
            for h in &to_send {
166268×
                let c = self.store.get_change(h)?;
166368×
                if (c.author == key || c.author.is_zero())
166465×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
166538×
                {
166638×
                    unsigned.push(*h);
166738×
                }
1668
            }
166972×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
167035×
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
167134×
                bundle.attests.push(sa);
1672
            }
167371×
            bundle = self.bundle_for(&to_send)?;
1674195×
        }
1675266×
        bundle.objects.push((
1676266×
            ObjectType::State,
1677266×
            StateObject::new(local_heads.clone()).encode(),
1678266×
        ));
1679266×
        let attestation = match key {
168071×
            Some(_) => Some(self.sign_attest(&Attest {
168171×
                repo: self.id()?,
168271×
                hlc: Hlc::now(),
168371×
                body: AttestBody::Ref {
168471×
                    name: bookmark.clone(),
168571×
                    old_state: remote_state,
168671×
                    new_state,
168771×
                    serial: next_serial(last_serial),
168871×
                },
16891×
            })?),
1690195×
            None => None,
1691
        };
1692265×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
169370×
            AttestBody::Ref { serial, .. } => Some(serial),
16940×
            _ => None,
169570×
        });
1696265×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1697
        // Tag states must be present on the remote: bundle their changes too.
1698265×
        for t in &tags_to_send {
16996×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
17006×
            let extra: Vec<ChangeHash> =
17016×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
17026×
            if !extra.is_empty() {
17030×
                let more = self.bundle_for(&extra)?;
17040×
                bundle.changes.extend(more.changes);
17050×
                bundle.hashes.extend(more.hashes);
17060×
                bundle.attests.extend(more.attests);
17070×
                bundle.objects.extend(more.objects);
17086×
            }
17096×
            bundle.objects.push((
17106×
                ObjectType::State,
17116×
                StateObject::new(t.heads.clone()).encode(),
17126×
            ));
1713
        }
1714265×
        if let Some(l) = &policy_to_send {
171516×
            let remote_serial = resp_policy_serial;
171616×
            bundle.policies = self
171716×
                .policy_history()?
171816×
                .into_iter()
171939×
                .filter(|sp| {
172039×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
172118×
                        && sp.policy.serial < l.policy.serial
172239×
                })
172316×
                .collect();
1724249×
        }
1725265×
        let results = remote.push(
1726265×
            bundle,
1727265×
            vec![RefUpdate {
1728265×
                name: bookmark.clone(),
1729265×
                old_state: remote_state,
1730265×
                new_state,
1731265×
                force,
1732265×
                attestation,
1733265×
            }],
1734265×
            policy_to_send,
1735265×
            tags_to_send,
17366×
        )?;
173716×
        if let (Some(serial), true) = (
1738259×
            sent_serial,
1739265×
            results.iter().any(|r| r.ok && r.name == "policy"),
1740
        ) {
174116×
            self.record_policy_serial(remote_name, serial)?;
1742243×
        }
1743275×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1744241×
            let mut view = op.view.clone();
1745241×
            view.remotes
1746241×
                .entry(remote_name.to_string())
1747241×
                .or_default()
1748241×
                .insert(bookmark.clone(), new_state);
1749241×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1750238×
            if let Some(s) = serial {
175154×
                self.record_serial(remote_name, &bookmark, s)?;
1752184×
            }
175318×
        }
1754254×
        Ok(results)
1755354×
    }
1756
1757
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1758
    /// bookmark set to the remote's, working copy checked out.
1759221×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1760221×
        Self::clone_with(url, dest, None, &[])
1761221×
    }
1762
1763
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1764
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1765
    /// unless a size is given, so out-of-scope binaries are never fetched).
1766229×
    pub fn clone_with(
1767229×
        url: &str,
1768229×
        dest: &Path,
1769229×
        max_blob: Option<u64>,
1770229×
        sparse: &[String],
1771229×
    ) -> Result<Repo> {
1772229×
        Self::clone_full(url, dest, max_blob, sparse, None)
1773229×
    }
1774
1775
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1776
    /// changes within `depth` steps of them; the rest is the boundary.
17771×
    pub fn clone_shallow(
17781×
        url: &str,
17791×
        dest: &Path,
17801×
        depth: u32,
17811×
        max_blob: Option<u64>,
17821×
        sparse: &[String],
17831×
    ) -> Result<Repo> {
17841×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
17851×
    }
1786
1787230×
    fn clone_full(
1788230×
        url: &str,
1789230×
        dest: &Path,
1790230×
        max_blob: Option<u64>,
1791230×
        sparse: &[String],
1792230×
        depth: Option<u32>,
1793230×
    ) -> Result<Repo> {
1794230×
        let options = crate::credentials::Credentials::user().options_for(url);
1795230×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1796230×
    }
1797
1798
    /// Clone a subrepo with the credentials the parent would use for its
1799
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1800
    /// subrepo: it finds the same ones again through its parent.
18018×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
18028×
        let options = self.credentials_for(url);
18038×
        Self::clone_using(url, dest, None, &[], None, &options)
18048×
    }
1805
1806
    /// The name of a remote of this repository on the same hub (scheme,
1807
    /// host and port) as `url`.
180819×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
180923×
        let origin = |u: &str| -> Option<String> {
181023×
            let (scheme, rest) = u.split_once("://")?;
18118×
            if !matches!(scheme, "http" | "https") {
18120×
                return None;
18138×
            }
18148×
            let host = rest.split('/').next()?;
18158×
            Some(format!(
18168×
                "{}://{}",
18178×
                scheme.to_ascii_lowercase(),
18188×
                host.to_ascii_lowercase()
18198×
            ))
182023×
        };
182119×
        let want = origin(url)?;
18224×
        self.config
18234×
            .remotes
18244×
            .iter()
18254×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
18264×
            .map(|(name, _)| name.clone())
182719×
    }
1828
1829
    /// The token and CA to reach `url` with: those of a remote of this
1830
    /// repository on the same hub (scheme, host and port), else the
1831
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
1832
    /// and enclosing checkouts', as a clone would use them.
183319×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
183419×
        match self.remote_on_same_hub(url) {
18351×
            Some(name) => RemoteOptions {
18361×
                repo_id: None,
18371×
                cache_dir: None,
18381×
                ..self.remote_options(&name)
18391×
            },
1840
            None => {
184118×
                let mut options = RemoteOptions::default();
184218×
                self.fill_credentials(url, &mut options);
184318×
                options
1844
            }
1845
        }
184619×
    }
1847
1848238×
    fn clone_using(
1849238×
        url: &str,
1850238×
        dest: &Path,
1851238×
        max_blob: Option<u64>,
1852238×
        sparse: &[String],
1853238×
        depth: Option<u32>,
1854238×
        options: &RemoteOptions,
1855238×
    ) -> Result<Repo> {
1856238×
        let remote = open_remote(url, options)?;
1857238×
        let id = remote.repo_id()?;
1858234×
        if id == crate::protocol::UNBOUND_ID {
18592×
            return fail(format!(
1860
                "{url} is empty and unbound: push a repository to it first"
1861
            ));
1862232×
        }
1863232×
        let mut repo = Repo::init_with_id(dest, id)?;
1864232×
        repo.config
1865232×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
1866232×
        if let Some(m) = max_blob {
18672×
            repo.config.set("filter.max-blob", &m.to_string())?;
1868230×
        } else if !sparse.is_empty() {
18691×
            repo.config.set("filter.max-blob", "0")?;
1870229×
        }
1871232×
        if !sparse.is_empty() {
18721×
            repo.config.set("filter.paths", &sparse.join(","))?;
1873231×
        }
1874232×
        repo.save_config()?;
1875232×
        if let Some(depth) = depth {
18761×
            repo.fetch_shallow("origin", depth)?;
1877
        } else {
1878231×
            repo.fetch("origin")?;
1879
        }
1880231×
        let (op_ref, op) = repo.head_op()?;
1881
        // The remote's default bookmark, else ours (main), else its only one.
1882231×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
1883
        // Asked of the remote as now configured, so a store-backed one
1884
        // answers from the mirror the fetch just filled.
1885231×
        let advertised = repo
1886231×
            .open_named_remote("origin")
1887231×
            .ok()
1888231×
            .and_then(|r| r.refs().ok())
1889231×
            .and_then(|r| r.default_bookmark);
1890231×
        let bookmark = advertised
1891231×
            .filter(|b| theirs.contains_key(b))
1892231×
            .or_else(|| {
18937×
                theirs
18947×
                    .contains_key(&repo.config.bookmark)
18957×
                    .then(|| repo.config.bookmark.clone())
18967×
            })
1897231×
            .or_else(|| {
18980×
                (theirs.len() == 1)
18990×
                    .then(|| theirs.keys().next().cloned())
19000×
                    .flatten()
19010×
            })
1902231×
            .unwrap_or_else(|| repo.config.bookmark.clone());
1903231×
        let initial = repo.config.bookmark.clone();
1904231×
        if bookmark != repo.config.bookmark {
19051×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
19061×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
19071×
            repo.config.bookmark = bookmark.clone();
1908230×
        }
1909231×
        if let Some(state) = theirs.get(&bookmark).copied() {
1910231×
            let heads = repo.store.get_state(&state)?.heads;
1911231×
            let mut view = op.view.clone();
1912
            // The empty bookmark `init` made goes when another is checked out.
1913231×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
19141×
                view.bookmarks.remove(&initial);
1915230×
            }
1916231×
            view.bookmarks.insert(bookmark, state);
1917231×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1918231×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
19190×
        }
1920231×
        Ok(repo)
1921238×
    }
1922
}
1923
1924
/// The serial of a reference's next attestation: one more than the last the
1925
/// remote reports, or, for a bookmark the remote does not have, the clock in
1926
/// milliseconds, so a bookmark created again after a deletion goes past the
1927
/// deletion's serial the remote keeps.
192871×
fn next_serial(last: Option<u64>) -> u64 {
192971×
    match last {
193045×
        Some(l) => l + 1,
193126×
        None => Hlc::now().wall_ms.max(1),
1932
    }
193371×
}