OXYGENHUB

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

1516 of 1700 lines run, 217 of 308 functions · run #283 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
541260×
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
551260×
        self.oxy.join("attest").join(name_file(bookmark))
561260×
    }
57
58
    /// The latest reference attestation stored for a bookmark.
591186×
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
601186×
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61195×
            Ok(h) => {
62195×
                let r = ObjectRef::from_hex(h.trim())
63195×
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65195×
                    r,
66
                    SignedAttest {
67195×
                        attest: self.store.get_attest(&r)?,
68195×
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
71
            }
72991×
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
730×
            Err(e) => Err(e.into()),
74
        }
751186×
    }
76
7774×
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
7874×
        fs::create_dir_all(self.oxy.join("attest"))?;
7974×
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
8074×
    }
81
82975×
    pub fn remote_refs(&self) -> Result<RefsResponse> {
83975×
        let view = self.view()?;
84975×
        let mut out = Vec::new();
85997×
        for (name, state) in &view.bookmarks {
86997×
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
87997×
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88104×
                AttestBody::Ref { serial, .. } => Some(serial),
890×
                _ => None,
90104×
            });
91997×
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
92997×
            out.push(RemoteRef {
93997×
                name: name.clone(),
94997×
                state: *state,
95997×
                heads: self.store.get_state(state)?.heads,
96997×
                attestation,
97997×
                last_serial,
98
            });
99
        }
100975×
        let policy = self.current_policy()?.map(|(_, sp)| sp);
101975×
        let history = self
102975×
            .policy_history()?
103975×
            .into_iter()
104975×
            .filter(|sp| {
10566×
                policy
10666×
                    .as_ref()
10766×
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
10866×
            })
109975×
            .collect();
110
        Ok(RefsResponse {
111975×
            refs: out,
112975×
            policy,
113975×
            tags: self.tag_refs()?,
114975×
            history,
115975×
            default_bookmark: Some(self.config.bookmark.clone()),
116
        })
117975×
    }
118
119
    /// Every change reachable from `heads` that is in the store.
1201293×
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
1211293×
        let mut seen = BTreeSet::new();
1221293×
        let mut stack: Vec<ChangeHash> = heads.to_vec();
1234717×
        while let Some(h) = stack.pop() {
1243424×
            if seen.contains(&h) || !self.store.has(&h) {
1251033×
                continue;
1262391×
            }
1272391×
            seen.insert(h);
1282391×
            stack.extend(self.store.get_change_meta(&h)?.deps);
129
        }
1301293×
        Ok(seen)
1311293×
    }
132
133
    /// The changes within `depth` dependency steps of `heads` (spec §17),
134
    /// nearest first; depth 1 is the heads themselves.
1353×
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
1363×
        let mut out = Vec::new();
1373×
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
1383×
        let mut layer: Vec<ChangeHash> = heads.to_vec();
1393×
        for _ in 0..depth.max(1) {
1408×
            let mut next = Vec::new();
14112×
            for h in layer {
14212×
                if !seen.insert(h) || !self.store.has(&h) {
1432×
                    continue;
14410×
                }
14510×
                let c = self.store.get_change(&h)?;
14610×
                next.extend(c.deps.iter().copied());
14710×
                out.push(h);
148
            }
1498×
            if next.is_empty() {
1501×
                break;
1517×
            }
1527×
            layer = next;
153
        }
1543×
        out.reverse();
1553×
        Ok(out)
1563×
    }
157
1581878×
    fn shallow_path(&self) -> PathBuf {
1591878×
        self.oxy.join("shallow")
1601878×
    }
161
162
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
1631875×
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
1641875×
        fs::read_to_string(self.shallow_path())
1651875×
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
1661875×
            .unwrap_or_default()
1671875×
    }
168
169182×
    pub fn is_shallow(&self) -> bool {
170182×
        !self.boundary().is_empty()
171182×
    }
172
1733×
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
1743×
        if boundary.is_empty() {
1751×
            let _ = fs::remove_file(self.shallow_path());
1761×
            return Ok(());
1772×
        }
1782×
        let text: String = boundary
1792×
            .iter()
1802×
            .map(|h| format!("{}\n", h.to_hex()))
1812×
            .collect();
1822×
        write_atomic(&self.shallow_path(), text.as_bytes())
1833×
    }
184
185
    /// Recompute the boundary from what is stored: every dependency of a
186
    /// stored change that is not itself stored.
1873×
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
1883×
        let mut boundary = self.boundary();
1893×
        boundary.retain(|h| !self.store.has(h));
19010×
        for h in imported {
19113×
            for d in self.store.get_change_meta(h)?.deps {
19213×
                if !self.store.has(&d) {
1932×
                    boundary.insert(d);
19411×
                }
195
            }
196
        }
1973×
        self.write_boundary(&boundary)
1983×
    }
199
200
    /// Fetch `depth` more levels of history below the shallow boundary.
2012×
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
2022×
        let boundary = self.boundary();
2032×
        if boundary.is_empty() {
2040×
            return Ok(0);
2052×
        }
2062×
        let remote = self.open_named_remote(remote_name)?;
2072×
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
2082×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
2092×
        let imported = self.import_bundle_shallow(&bundle, false)?;
2102×
        if self.config.max_blob.is_some() {
2110×
            self.register_missing_blobs(&imported, remote_name)?;
2122×
        }
2132×
        self.refresh_boundary(&imported)?;
2142×
        Ok(imported.len())
2152×
    }
216
217
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
218737×
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
219737×
        let have = self.closure_in_store(have)?;
220
        // In a shallow repository the walk stops at the boundary, whose
221
        // changes the remote is assumed to hold.
222737×
        let boundary = self.boundary();
223737×
        let mut out = Vec::new();
224737×
        let mut done: BTreeSet<ChangeHash> = have.clone();
225737×
        done.extend(boundary.iter().copied());
226
        // Iterative post-order DFS.
2271228×
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
2283212×
        while let Some((h, expanded)) = stack.pop() {
2292475×
            if done.contains(&h) {
230399×
                continue;
2312076×
            }
2322076×
            if !self.store.has(&h) {
2330×
                return fail(format!("change {} is not in this repository", h.short(12)));
2342076×
            }
2352076×
            if expanded {
2361038×
                done.insert(h);
2371038×
                out.push(h);
2381038×
                continue;
2391038×
            }
2401038×
            stack.push((h, true));
2411038×
            for d in self.store.get_change_meta(&h)?.deps {
242758×
                if !done.contains(&d) {
243209×
                    stack.push((d, false));
244549×
                }
245
            }
246
        }
247737×
        Ok(out)
248737×
    }
249
250
    /// Bundle changes (in the given dependency order) with their signatures,
251
    /// seals, identities, blobs, chunks.
252294×
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
253294×
        self.bundle_for_filtered(changes, None)
254294×
    }
255
256
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
2574×
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
2584×
        let mut out = Vec::new();
2594×
        for r in refs {
2604×
            let (ty, body) = match self.store.get(r) {
2614×
                Ok(x) => x,
2620×
                Err(StoreError::NotFound(_)) => continue,
2630×
                Err(e) => return Err(e.into()),
264
            };
2654×
            if ty == ObjectType::Blob {
2665×
                for c in Blob::decode(&body)?.chunks {
2675×
                    if let Ok((cty, cb)) = self.store.get(&c) {
2685×
                        out.push((cty, cb));
2695×
                    }
270
                }
2710×
            }
2724×
            out.push((ty, body));
273
        }
2744×
        Ok(out)
2754×
    }
276
277
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
278
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
279341×
    pub fn bundle_for_filtered(
280341×
        &self,
281341×
        changes: &[ChangeHash],
282341×
        max_blob: Option<u64>,
283341×
    ) -> Result<Bundle> {
284341×
        self.bundle_of(changes, max_blob, false)
285341×
    }
286
287
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
288
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
289
    /// with their text blobs and chunks among the objects, so neither side
290
    /// decodes or encodes their text.
291311×
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
292311×
        self.bundle_of(changes, max_blob, true)
293311×
    }
294
295652×
    fn bundle_of(
296652×
        &self,
297652×
        changes: &[ChangeHash],
298652×
        max_blob: Option<u64>,
299652×
        raw: bool,
300652×
    ) -> Result<Bundle> {
301652×
        let mut bundle = Bundle::default();
302652×
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
303652×
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
3041050×
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
3051050×
            if !r.is_zero() && self.store.has(r) {
306166×
                objects.insert(*r);
307884×
            }
3081050×
        };
309969×
        for h in changes {
310
            // Raw: the stored bytes, and a skeleton for the rest.
311969×
            let (c, encoded) = if raw {
312520×
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
313520×
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
3144978×
                for t in texts {
3154978×
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
3163×
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
3173×
                        objects.insert(r);
3183×
                        objects.extend(blob.chunks);
3194975×
                    }
320
                }
321520×
                (skel, Some(bytes))
322
            } else {
323449×
                (self.store.get_change(h)?, None)
324
            };
325969×
            let sigs = self.store.signatures(h)?;
326969×
            add_object(&c.author, &mut objects);
327969×
            for s in &sigs {
32820×
                add_object(&s.key, &mut objects);
32920×
            }
3305939×
            for e in &c.edits {
3315939×
                if let Edit::Replace { old, new, .. } = e {
33214×
                    for b in [old, new].into_iter().flatten() {
33314×
                        if self.store.has(b) {
33414×
                            if let Ok(blob) =
33514×
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
336
                            {
33714×
                                if max_blob.is_some_and(|m| blob.length > m) {
3384×
                                    continue;
33910×
                                }
34010×
                                objects.insert(*b);
34110×
                                objects.extend(blob.chunks.iter().copied());
3420×
                            }
3430×
                        }
344
                    }
3455927×
                }
346
            }
347969×
            for s in self.store.seals_for(h)? {
34865×
                seals.insert(s);
34965×
            }
350969×
            match encoded {
351520×
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
352449×
                None => {
353449×
                    bundle.changes.push((c, sigs));
354449×
                    bundle.hashes.push(*h);
355449×
                }
356
            }
357
        }
358652×
        for r in seals {
35961×
            let attest = self.store.get_attest(&r)?;
36061×
            let sigs = self.store.signatures(&r)?;
36161×
            for s in &sigs {
36261×
                add_object(&s.key, &mut objects);
36361×
            }
36461×
            bundle.attests.push(SignedAttest { attest, sigs });
365
        }
366652×
        for r in objects {
367103×
            let (ty, body) = self.store.get(&r)?;
368103×
            bundle.objects.push((ty, body));
369
        }
370652×
        Ok(bundle)
371652×
    }
372
373
    /// Store a bundle's contents. With `strict`, every change must
374
    /// authenticate (signature or seal by its author or a delegate).
375695×
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
376695×
        self.import_bundle_inner(bundle, strict, false)
377695×
    }
378
379
    /// Like `import_bundle`, accepting changes whose dependencies are absent
380
    /// (they join the shallow boundary).
3813×
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
3823×
        self.import_bundle_inner(bundle, strict, true)
3833×
    }
384
385698×
    fn import_bundle_inner(
386698×
        &self,
387698×
        bundle: &Bundle,
388698×
        strict: bool,
389698×
        shallow: bool,
390698×
    ) -> Result<Vec<ChangeHash>> {
391698×
        let batch = self.store.begin_batch()?;
392698×
        let result = self.import_bundle_batched(bundle, strict, shallow);
393698×
        batch.finish()?;
394696×
        result
395698×
    }
396
397698×
    fn import_bundle_batched(
398698×
        &self,
399698×
        bundle: &Bundle,
400698×
        strict: bool,
401698×
        shallow: bool,
402698×
    ) -> Result<Vec<ChangeHash>> {
403698×
        for (ty, _) in &bundle.objects {
4040×
            if !matches!(
405455×
                ty,
406
                ObjectType::Chunk
407
                    | ObjectType::Blob
408
                    | ObjectType::Identity
409
                    | ObjectType::State
410
                    | ObjectType::Checkpoint
411
            ) {
4120×
                return fail(format!("bundle may not carry {} objects", ty.name()));
413455×
            }
414
        }
415
        // All at once: in a large batch they are compressed on every core.
416698×
        let objects: Vec<(ObjectType, &[u8])> = bundle
417698×
            .objects
418698×
            .iter()
419698×
            .map(|(ty, body)| (*ty, body.as_slice()))
420698×
            .collect();
421698×
        self.store.put_many(&objects)?;
422698×
        for sa in &bundle.attests {
42364×
            let r = self.store.put_attest(&sa.attest)?;
42464×
            for sig in &sa.sigs {
42564×
                self.store.put_signature(&r, sig)?;
426
            }
42764×
            if let AttestBody::Seal { hashes } = &sa.attest.body {
42868×
                for h in hashes {
42968×
                    self.store.index_seal(h, &r)?;
430
                }
4310×
            }
432
        }
433
        // Each change's hash: from the bundle when its maker knew it, else
434
        // worked out once (for a change adding a whole tree, hashing is
435
        // chunking all its text).
436698×
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
437689×
            bundle.hashes.clone()
438
        } else {
4399×
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
440
        };
441698×
        let raw_hashes: Vec<ChangeHash> = bundle
442698×
            .raw_changes
443698×
            .iter()
444698×
            .map(|(b, _)| hash_object(ObjectType::Change, b))
445698×
            .collect();
446698×
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
447698×
        let boundary = self.boundary();
448698×
        let mut imported = Vec::new();
449
        // Changes as stored: checked, then stored as they are, their text
450
        // blobs having come with the objects.
451698×
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
452521×
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
453521×
            for d in &skel.deps {
454412×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
455
                {
4560×
                    return fail(format!(
457
                        "change {} depends on {}, which is neither stored nor in the bundle",
4580×
                        h.short(12),
4590×
                        d.short(12)
460
                    ));
461412×
                }
462
            }
4634979×
            for t in texts {
4644979×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
4654×
                    if !self.store.has(&r) {
4661×
                        return fail(format!(
467
                            "change {} came without its text blob {}",
4681×
                            h.short(12),
4691×
                            r.short(12)
470
                        ));
4713×
                    }
4724975×
                }
473
            }
474520×
            self.store.put(ObjectType::Change, bytes)?;
475520×
            for sig in sigs {
4764×
                self.store.put_signature(&h, sig)?;
477
            }
478520×
            imported.push(h);
479
        }
480697×
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
481478×
            for d in &c.deps {
482300×
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
483
                {
4843×
                    return fail(format!(
485
                        "change {} depends on {}, which is neither stored nor in the bundle",
4863×
                        h.short(12),
4873×
                        d.short(12)
488
                    ));
489297×
                }
490
            }
491475×
            let stored = self.store.put_change(c)?;
492475×
            if stored != h {
4930×
                return fail(format!(
494
                    "change {} is not the change the bundle names",
4950×
                    h.short(12)
496
                ));
497475×
            }
498475×
            for sig in sigs {
49925×
                self.store.put_signature(&h, sig)?;
500
            }
501475×
            imported.push(h);
502
        }
503694×
        if strict {
50428×
            for h in &imported {
50519×
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
5061×
                    return fail(format!(
507
                        "change {} is not authenticated by its author",
5081×
                        h.short(12)
509
                    ));
51018×
                }
511
            }
512666×
        }
513693×
        Ok(imported)
514698×
    }
515
516
    /// Verify a reference attestation against an update it claims to describe.
517
    /// `allow_equal` lets a client re-read the attestation it already has; a
518
    /// server receiving a push requires a strictly greater serial.
519
    /// A reference attestation signed by a delegate of an identity the
520
    /// rule lists is authorized as that identity (spec §14.5): the identity
521
    /// named the delegate with the `refs` scope, still in force at `at_ms`
522
    /// (the attestation's wall time), and the policy names the identity.
523
    /// Revoked keys authorize nothing either way.
5246×
    pub(crate) fn delegate_authorized(
5256×
        &self,
5266×
        p: &crate::policy::Policy,
5276×
        signer: &KeyId,
5286×
        reference: &str,
5296×
        at_ms: u64,
5306×
    ) -> bool {
5316×
        if p.is_revoked(signer) {
5321×
            return false;
5335×
        }
5345×
        let Some(rule) = p.rule_for(reference) else {
5350×
            return false;
536
        };
5376×
        rule.keys.iter().any(|k| {
5386×
            !p.is_revoked(k)
5396×
                && p.identity(k)
5406×
                    .cloned()
5416×
                    .or_else(|| self.store.get_identity(k).ok())
5426×
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
5436×
        })
5446×
    }
545
54693×
    fn check_ref_attest(
54793×
        &self,
54893×
        sa: &SignedAttest,
54993×
        name: &str,
55093×
        old_state: &ObjectRef,
55193×
        new_state: &ObjectRef,
55293×
        last_serial: Option<u64>,
55393×
        allow_equal: bool,
55493×
    ) -> std::result::Result<u64, String> {
555
        let AttestBody::Ref {
55693×
            name: n,
55793×
            old_state: o,
55893×
            new_state: nw,
55993×
            serial,
56093×
        } = &sa.attest.body
561
        else {
5620×
            return Err("attestation is not a ref attestation".into());
563
        };
56493×
        if n != name || o != old_state || nw != new_state {
5651×
            return Err("attestation does not describe this update".into());
56692×
        }
56792×
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
5680×
            return Err("attestation is for a different repository".into());
56992×
        }
57092×
        if let Some(last) = last_serial {
57159×
            if *serial < last || (*serial == last && !allow_equal) {
5721×
                return Err(format!(
5731×
                    "attestation serial {serial} is not greater than the last seen {last}"
5741×
                ));
57558×
            }
57633×
        }
57791×
        let r = sa.attest.hash();
57891×
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
57991×
        let id = self
58091×
            .store
58191×
            .get_identity(&sig.key)
58291×
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
58391×
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
58491×
        Ok(*serial)
58593×
    }
586
587
    /// Accept a push (spec §16.4). Without a trust policy every repository
588
    /// is unverified, so unsigned changes and unattested updates are accepted;
589
    /// attestations that are present must still be valid. With a policy,
590
    /// every change and update is checked against it. A newer policy in the
591
    /// push is applied first when it is signed by the current roots.
592269×
    pub fn receive_push(
593269×
        &self,
594269×
        bundle: Bundle,
595269×
        updates: Vec<RefUpdate>,
596269×
        policy: Option<SignedPolicy>,
597269×
        tags: Vec<crate::protocol::TagRef>,
598269×
    ) -> Result<Vec<RefResult>> {
599269×
        Ok(self
600269×
            .receive_push_report(bundle, updates, policy, tags)?
601
            .results)
602269×
    }
603
604
    /// `receive_push` with what a host wants to log: each accepted
605
    /// reference's old and new state and heads, and the changes this push
606
    /// stored (hub spec §6.12).
607313×
    pub fn receive_push_report(
608313×
        &self,
609313×
        bundle: Bundle,
610313×
        updates: Vec<RefUpdate>,
611313×
        policy: Option<SignedPolicy>,
612313×
        tags: Vec<crate::protocol::TagRef>,
613313×
    ) -> Result<PushReport> {
614313×
        let mut report = PushReport::default();
615313×
        let results = &mut report.results;
616313×
        if let Some(sp) = policy {
61718×
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
61816×
                Ok(()) => {
61916×
                    results.push(RefResult {
62016×
                        name: "policy".into(),
62116×
                        ok: true,
62216×
                        reason: format!("serial {}", sp.policy.serial),
62316×
                    });
62416×
                }
6252×
                Err(e) => {
6262×
                    results.push(RefResult {
6272×
                        name: "policy".into(),
6282×
                        ok: false,
6292×
                        reason: e,
6302×
                    });
6312×
                    for u in updates {
6320×
                        results.push(RefResult {
6330×
                            name: u.name,
6340×
                            ok: false,
6350×
                            reason: "policy update was rejected".into(),
6360×
                        });
6370×
                    }
6382×
                    return Ok(report);
639
                }
640
            }
641295×
        }
642311×
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
643
        // A push of objects alone (one batch of a long history, oxygen#95)
644
        // names no reference: its outcome is reported as `objects`.
645311×
        let objects_only = updates.is_empty() && tags.is_empty();
646311×
        match self.import_bundle(&bundle, policy.is_some()) {
647308×
            Ok(imported) => {
648308×
                if objects_only {
6497×
                    results.push(RefResult {
6507×
                        name: OBJECTS_RESULT.into(),
6517×
                        ok: true,
6527×
                        reason: format!("{} changes stored", imported.len()),
6537×
                    });
654301×
                }
655308×
                report.imported = imported;
656
            }
6573×
            Err(e) => {
6583×
                if objects_only {
6590×
                    results.push(RefResult {
6600×
                        name: OBJECTS_RESULT.into(),
6610×
                        ok: false,
6620×
                        reason: e.to_string(),
6630×
                    });
6643×
                }
6653×
                for u in updates {
6663×
                    results.push(RefResult {
6673×
                        name: u.name,
6683×
                        ok: false,
6693×
                        reason: e.to_string(),
6703×
                    });
6713×
                }
6723×
                return Ok(report);
673
            }
674
        }
675308×
        let (op_ref, op) = self.head_op()?;
676308×
        let mut view = op.view.clone();
677308×
        let mut names = Vec::new();
678308×
        for u in updates {
679299×
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
680299×
            let (ok, reason) = match outcome {
681270×
                Ok(()) => (true, String::new()),
68229×
                Err(e) => (false, e),
683
            };
684299×
            if ok {
685270×
                names.push(u.name.clone());
686270×
                let heads = self
687270×
                    .store
688270×
                    .get_state(&u.new_state)
689270×
                    .map(|s| s.heads)
690270×
                    .unwrap_or_default();
691270×
                report.updated.push(RefUpdated {
692270×
                    name: u.name.clone(),
693270×
                    old_state: u.old_state,
694270×
                    new_state: u.new_state,
695270×
                    heads,
696270×
                });
69729×
            }
698299×
            results.push(RefResult {
699299×
                name: u.name,
700299×
                ok,
701299×
                reason,
702299×
            });
703
        }
704308×
        for t in &tags {
7058×
            let name = format!("tags/{}", t.name);
7068×
            let new = !view.tags.contains_key(&t.name);
7078×
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
708
                Ok(()) => {
709
                    // A tag new here is an update too, so a hub can start
710
                    // its pipeline's tag jobs (oxygenflow#24); one it
711
                    // already had, sent again, is not.
7126×
                    if new {
7136×
                        report.updated.push(RefUpdated {
7146×
                            name: name.clone(),
7156×
                            old_state: ObjectRef::ZERO,
7166×
                            new_state: t.state,
7176×
                            heads: t.heads.clone(),
7186×
                        });
7196×
                    }
7206×
                    names.push(name.clone());
7216×
                    results.push(RefResult {
7226×
                        name,
7236×
                        ok: true,
7246×
                        reason: String::new(),
7256×
                    });
726
                }
7272×
                Err(e) => results.push(RefResult {
7282×
                    name,
7292×
                    ok: false,
7302×
                    reason: e,
7312×
                }),
732
            }
733
        }
734308×
        if !names.is_empty() {
735270×
            self.record_op(
736270×
                &[op_ref],
737270×
                &format!("push received: {}", names.join(" ")),
738270×
                view,
7393×
            )?;
74038×
        }
741305×
        Ok(report)
742313×
    }
743
744
    /// Check an update's attestation against the latest one for its
745
    /// reference and store it as the new latest. Failures say what was
746
    /// being done, for which reference, so a refused push can be diagnosed
747
    /// from its reason alone.
74874×
    fn record_update_attest(
74974×
        &self,
75074×
        u: &RefUpdate,
75174×
        sa: &SignedAttest,
75274×
    ) -> std::result::Result<(), String> {
75374×
        let name = &u.name;
75474×
        let last = self
75574×
            .latest_ref_attest(name)
75674×
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
75774×
            .and_then(|(_, a)| match a.attest.body {
75849×
                AttestBody::Ref { serial, .. } => Some(serial),
7590×
                _ => None,
76049×
            });
76174×
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
76272×
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
76372×
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
76471×
        for sig in &sa.sigs {
76571×
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
766
        }
76771×
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
76874×
    }
769
770
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
771
    /// at `old_state`, is never the bookmark a non-bare repository has
772
    /// checked out (a bare one's default is its host's to protect, see
773
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
774
    /// an attestation by a key that may update it.
775
    /// The deletion's attestation stays the bookmark's latest, so an older
776
    /// one cannot be replayed to bring it back.
7773×
    fn apply_deletion(
7783×
        &self,
7793×
        view: &mut View,
7803×
        u: &RefUpdate,
7813×
        policy: Option<&crate::policy::Policy>,
7823×
    ) -> std::result::Result<(), String> {
7833×
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
7840×
            return Err(format!("no bookmark {:?} to delete", u.name));
785
        };
7863×
        if current != u.old_state {
7870×
            return Err("stale: the remote bookmark has moved; pull first".into());
7883×
        }
7893×
        if !self.is_bare() && u.name == self.config.bookmark {
7901×
            return Err(format!(
7911×
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
7921×
                u.name
7931×
            ));
7942×
        }
7952×
        if let Some(p) = policy {
7960×
            let Some(sa) = &u.attestation else {
7970×
                return Err(format!(
7980×
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
7990×
                    u.name
8000×
                ));
801
            };
8020×
            let signer = sa
8030×
                .sigs
8040×
                .first()
8050×
                .map(|s| s.key)
8060×
                .ok_or("attestation carries no signature")?;
8070×
            if !p.authorizes(&signer, &u.name)
8080×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
809
            {
8100×
                return Err(format!(
8110×
                    "key {} may not delete {:?} under this repository's policy",
8120×
                    signer.short(12),
8130×
                    u.name
8140×
                ));
8150×
            }
8162×
        }
8172×
        if let Some(sa) = &u.attestation {
8181×
            self.record_update_attest(u, sa)?;
8191×
        }
8202×
        view.bookmarks.remove(&u.name);
8212×
        Ok(())
8223×
    }
823
824299×
    fn apply_update(
825299×
        &self,
826299×
        view: &mut View,
827299×
        u: &RefUpdate,
828299×
        policy: Option<&crate::policy::Policy>,
829299×
    ) -> std::result::Result<(), String> {
830299×
        if u.name == "policy" {
8310×
            return Err(
8320×
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
8330×
            );
834299×
        }
835299×
        let empty = self
836299×
            .store
837299×
            .put_state(&StateObject::new(vec![]))
838299×
            .map_err(|e| e.to_string())?;
839299×
        if u.new_state.is_zero() {
8403×
            return self.apply_deletion(view, u, policy);
841296×
        }
842296×
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
843296×
        if current != u.old_state {
84414×
            return Err("stale: the remote bookmark has moved; pull first".into());
845282×
        }
846282×
        let new_state = self
847282×
            .store
848282×
            .get_state(&u.new_state)
849282×
            .map_err(|_| "new state object is missing".to_string())?;
850564×
        for h in &new_state.heads {
851564×
            if !self.store.has(h) {
8521×
                return Err(format!("head {} is missing", h.short(12)));
853563×
            }
854
        }
855281×
        if !u.force {
856280×
            let old_heads = self
857280×
                .store
858280×
                .get_state(&current)
859280×
                .map_err(|e| e.to_string())?
860
                .heads;
861280×
            let closure = self
862280×
                .closure_in_store(&new_state.heads)
863280×
                .map_err(|e| e.to_string())?;
864303×
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
8651×
                return Err(format!(
8661×
                    "not a fast-forward: current head {} would be dropped (use --force)",
8671×
                    h.short(12)
8681×
                ));
869279×
            }
8701×
        }
871280×
        if let Some(p) = policy {
87226×
            let Some(sa) = &u.attestation else {
8731×
                return Err(format!(
8741×
                    "{:?} requires a signed reference attestation under this repository's policy",
8751×
                    u.name
8761×
                ));
877
            };
87825×
            let signer = sa
87925×
                .sigs
88025×
                .first()
88125×
                .map(|s| s.key)
88225×
                .ok_or("attestation carries no signature")?;
88325×
            if !p.authorizes(&signer, &u.name)
8846×
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
885
            {
8865×
                return Err(format!(
8875×
                    "key {} may not update {:?} under this repository's policy",
8885×
                    signer.short(12),
8895×
                    u.name
8905×
                ));
89120×
            }
89220×
            let old_heads = self
89320×
                .store
89420×
                .get_state(&current)
89520×
                .map_err(|e| e.to_string())?
896
                .heads;
89720×
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
898254×
        }
899274×
        if let Some(sa) = &u.attestation {
90073×
            self.record_update_attest(u, sa)?;
901201×
        }
902268×
        view.bookmarks.insert(u.name.clone(), u.new_state);
903268×
        Ok(())
904299×
    }
905
906
    // ------------------------------------------------------------ client side
907
908953×
    fn remote_url(&self, name: &str) -> Result<String> {
909953×
        self.config.remotes.get(name).cloned().ok_or_else(|| {
9103×
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
9113×
            RepoError::Msg(match names.as_slice() {
9123×
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
9131×
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
914
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
9151×
                    names.join(", "),
9161×
                    names[0],
9171×
                    names[0]
918
                ),
9190×
                _ => format!(
920
                    "no remote named {name:?}; this repository has {}",
9210×
                    names.join(", ")
922
                ),
923
            })
9243×
        })
925953×
    }
926
927
    /// Refuse a remote that is another repository. An **unbound** remote
928
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
929
    /// for pushes, which bind it to this repository's id (spec §16.1).
930711×
    fn check_remote_id(
931711×
        &self,
932711×
        remote: &dyn crate::protocol::Remote,
933711×
        remote_name: &str,
934711×
        allow_unbound: bool,
935711×
    ) -> Result<()> {
936711×
        let theirs = remote.repo_id()?;
937710×
        if theirs == self.id()? {
938688×
            return Ok(());
93922×
        }
94022×
        if theirs == crate::protocol::UNBOUND_ID {
94119×
            if allow_unbound {
94218×
                return Ok(());
9431×
            }
9441×
            return fail(format!(
945
                "remote {remote_name:?} is empty and unbound: push to it first"
946
            ));
9473×
        }
9483×
        fail(format!(
949
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
950
        ))
951711×
    }
952
953
    /// Credentials and trust for a remote: `remote.<name>.token` and
954
    /// `remote.<name>.ca`, else the defaults for its URL
955
    /// ([`Repo::fill_credentials`]).
956969×
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
957969×
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
958969×
        let mut options = RemoteOptions {
959969×
            repo_id: self.id().ok(),
960969×
            token: self.config.remote_tokens.get(name).cloned(),
961969×
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
962969×
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
963969×
        };
964969×
        self.fill_credentials(&url, &mut options);
965969×
        options
966969×
    }
967
968
    /// The user's credential store (`credentials.toml` beside the user
969
    /// configuration file).
970986×
    pub fn credentials(&self) -> crate::credentials::Credentials {
971986×
        crate::credentials::Credentials::at(
972986×
            self.user_config
973986×
                .parent()
974986×
                .map(Path::to_path_buf)
975986×
                .unwrap_or_else(default_home),
976
        )
977986×
    }
978
979
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
980
    /// then the user's credential store for its hub, then a remote on the
981
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
982987×
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
983987×
        if options.token.is_some() && options.ca.is_some() {
9841×
            return;
985986×
        }
986986×
        let stored = self.credentials().options_for(url);
987986×
        options.token = options.token.take().or(stored.token);
988986×
        options.ca = options.ca.take().or(stored.ca);
989986×
        if options.token.is_some() && options.ca.is_some() {
9900×
            return;
991986×
        }
992986×
        let Some(hub) = crate::credentials::hub_of(url) else {
993853×
            return;
994
        };
995133×
        let mut at = self.root.parent();
996530×
        while let Some(dir) = at {
997397×
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
9980×
                break;
999
            };
1000397×
            for (key, remote_url) in &cfg {
10015×
                let Some(name) = key
10025×
                    .strip_prefix("remote.")
10035×
                    .and_then(|k| k.strip_suffix(".url"))
1004
                else {
10052×
                    continue;
1006
                };
10073×
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
10081×
                    continue;
10092×
                }
10102×
                if options.token.is_none() {
10112×
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
10122×
                }
10132×
                if options.ca.is_none() {
10142×
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
10152×
                }
1016
            }
1017397×
            if options.token.is_some() && options.ca.is_some() {
10180×
                return;
1019397×
            }
1020397×
            at = dir.parent();
1021
        }
1022987×
    }
1023
1024
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1025
    /// no changes and no reference updates, which the receiver stores.
10260×
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
10270×
        let remote = self.open_named_remote(remote_name)?;
10280×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
10290×
        let mut bundle = Bundle::default();
10300×
        for r in seals {
10310×
            let attest = self.store.get_attest(r)?;
10320×
            let sigs = self.store.signatures(r)?;
10330×
            bundle
10340×
                .attests
10350×
                .push(crate::protocol::SignedAttest { attest, sigs });
1036
        }
10370×
        let results = remote.push(bundle, vec![], None, vec![])?;
10380×
        if let Some(r) = results.iter().find(|r| !r.ok) {
10390×
            return fail(format!("{}: {}", r.name, r.reason));
10400×
        }
10410×
        Ok(())
10420×
    }
1043
1044
    /// The remote whose URL starts with `base` (a hub), if configured.
10453×
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
10463×
        let base = base.trim_end_matches('/');
10473×
        self.config
10483×
            .remotes
10493×
            .iter()
10503×
            .find(|(_, url)| url.trim_end_matches('/') == base)
10513×
            .map(|(name, _)| name.clone())
10523×
    }
1053
1054
    /// Open a remote by name or, failing that, by URL with the default
1055
    /// credentials (see [`Repo::credentials_for`]).
10560×
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
10570×
        if let Some(name) = self.remote_for_url(url) {
10580×
            return Ok((name.clone(), self.open_named_remote(&name)?));
10590×
        }
10600×
        let options = RemoteOptions {
10610×
            repo_id: self.id().ok(),
10620×
            ..self.credentials_for(url)
10630×
        };
10640×
        Ok((url.to_string(), open_remote(url, &options)?))
10650×
    }
1066
1067
    /// Credentials for a URL: those of the configured remote with that
1068
    /// URL, else the environment's.
10693×
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
10703×
        match self.remote_for_url(url) {
10713×
            Some(name) => self.remote_options(&name),
10720×
            None => RemoteOptions {
10730×
                repo_id: self.id().ok(),
10740×
                ..self.credentials_for(url)
10750×
            },
1076
        }
10773×
    }
1078
1079953×
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
1080953×
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
1081953×
    }
1082
108392×
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
108492×
        self.oxy
108592×
            .join("remotes")
108692×
            .join(remote)
108792×
            .join(format!("{bookmark}.serial"))
108892×
    }
1089
109019×
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
109119×
        fs::read_to_string(self.serial_path(remote, bookmark))
109219×
            .ok()
109319×
            .and_then(|s| s.trim().parse().ok())
109419×
    }
1095
109673×
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
109773×
        let p = self.serial_path(remote, bookmark);
109873×
        fs::create_dir_all(p.parent().unwrap())?;
109973×
        write_atomic(&p, serial.to_string().as_bytes())
110073×
    }
1101
1102371×
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1103371×
        self.oxy.join("remotes").join(remote).join("policy.serial")
1104371×
    }
1105
1106
    /// The highest policy serial `remote` has ever presented.
1107347×
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
1108347×
        fs::read_to_string(self.policy_serial_path(remote))
1109347×
            .ok()
1110347×
            .and_then(|s| s.trim().parse().ok())
1111347×
    }
1112
111324×
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
111424×
        let p = self.policy_serial_path(remote);
111524×
        fs::create_dir_all(p.parent().unwrap())?;
111624×
        write_atomic(&p, serial.to_string().as_bytes())
111724×
    }
1118
111927×
    fn lazy_dir(&self) -> PathBuf {
112027×
        self.oxy.join("lazy")
112127×
    }
1122
1123
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
11244×
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
11254×
        fs::create_dir_all(self.lazy_dir())?;
11264×
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
11274×
    }
1128
1129
    /// Which remote promised an absent blob, if any.
113015×
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
113115×
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
113215×
            .ok()
113315×
            .map(|s| s.trim().to_string())
113415×
    }
1135
1136
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
11374×
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
11384×
        let Some(remote_name) = self.lazy_remote(blob) else {
11390×
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1140
        };
11414×
        let remote = self.open_named_remote(&remote_name)?;
11424×
        let objects = remote.objects(&[*blob])?;
11439×
        for (ty, body) in objects {
11449×
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
11459×
                self.store.put(ty, &body)?;
11460×
            }
1147
        }
11484×
        if !self.store.has(blob) {
11490×
            return fail(format!(
1150
                "{remote_name} did not send blob {}",
11510×
                blob.short(12)
1152
            ));
11534×
        }
11544×
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
11554×
        Ok(())
11564×
    }
1157
1158
    /// After importing from `remote`, record every blob the changes reference
1159
    /// that the store lacks as lazily available from that remote.
11604×
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
11614×
        let mut n = 0;
11624×
        for h in changes {
11634×
            let c = self.store.get_change(h)?;
116413×
            for e in &c.edits {
116513×
                if let Edit::Replace { old, new, .. } = e {
11666×
                    for b in [old, new].into_iter().flatten() {
11676×
                        if !self.store.has(b) {
11684×
                            self.register_lazy(b, remote)?;
11694×
                            n += 1;
11702×
                        }
1171
                    }
11727×
                }
1173
            }
1174
        }
11754×
        Ok(n)
11764×
    }
1177
1178
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
1179347×
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
1180347×
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
1181471×
        for st in view
1182347×
            .bookmarks
1183347×
            .values()
1184347×
            .chain(view.remotes.values().flat_map(|b| b.values()))
1185
        {
1186471×
            if let Ok(s) = self.store.get_state(st) {
1187471×
                have.extend(s.heads);
1188471×
            }
1189
        }
1190347×
        have.extend(view.workspaces.values().copied());
1191347×
        Ok(have.into_iter().collect())
1192347×
    }
1193
1194
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
1195353×
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
1196353×
        let remote = self.open_named_remote(remote_name)?;
1197350×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1198348×
        let resp = remote.refs()?;
1199
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1200
        // and signed by roots we trust, or on first contact. A remote that
1201
        // once presented a policy may never present none or an older one:
1202
        // that is a downgrade. A remote that never presented one is
1203
        // unverified, and this fetch is checked only as far as possible.
1204347×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1205347×
        let seen = self.remote_policy_serial(remote_name);
1206347×
        let mut unverified = false;
1207347×
        match &resp.policy {
12088×
            Some(sp) => {
12098×
                if seen.is_some_and(|s| sp.policy.serial < s) {
12100×
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
12118×
                }
12125×
                match &local_policy {
12135×
                    Some(l) if sp.policy.serial < l.serial => {}
12145×
                    Some(l) if sp.policy.serial == l.serial => {
12151×
                        if sp.policy.hash() != l.hash() {
12160×
                            return fail(format!(
1217
                                "{remote_name} presents a different policy with the same serial {}",
1218
                                l.serial
1219
                            ));
12201×
                        }
1221
                    }
1222
                    _ => {
12237×
                        self.adopt_policy_chain(
12247×
                            &resp.history,
12257×
                            sp,
12267×
                            &format!("oxy fetch {remote_name}"),
1227
                        )
12287×
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1229
                    }
1230
                }
12318×
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1232
            }
1233
            None => {
1234339×
                if seen.is_some() {
12350×
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1236339×
                }
1237339×
                unverified = true;
1238
            }
1239
        }
1240347×
        let policy = if unverified {
1241339×
            None
1242
        } else {
12438×
            self.current_policy()?.map(|(_, sp)| sp.policy)
1244
        };
1245347×
        let (op_ref, op) = self.head_op()?;
1246347×
        let mut view = op.view.clone();
1247347×
        let have = self.known_heads(&view)?;
1248347×
        let mut report = Vec::new();
1249347×
        let max_blob = self.config.max_blob;
1250354×
        for r in resp.refs {
1251354×
            let needed = {
1252354×
                let _t = crate::timing::phase("fetch: negotiate");
1253354×
                remote.negotiate(&have, &r.heads)?
1254
            };
1255354×
            let bundle = {
1256354×
                let _t = crate::timing::phase("fetch: bundle");
1257354×
                remote.fetch(&needed, max_blob)?
1258
            };
1259
            // Changes are not individually re-verified here: the bookmark's
1260
            // attestation (checked below) binds its whole state, and the
1261
            // receiver of the push verified the added changes at that time.
1262354×
            let imported = {
1263354×
                let _t = crate::timing::phase("fetch: import");
1264354×
                self.import_bundle(&bundle, false)?
1265
            };
1266354×
            if max_blob.is_some() {
12674×
                self.register_missing_blobs(&imported, remote_name)?;
1268350×
            }
1269515×
            for h in &r.heads {
1270515×
                if !self.store.has(h) {
12710×
                    return fail(format!("remote did not send head {}", h.short(12)));
1272515×
                }
1273
            }
1274354×
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1275354×
            if state != r.state {
12760×
                return fail(format!(
1277
                    "remote state {} does not match its heads",
12780×
                    r.state.short(12)
1279
                ));
1280354×
            }
1281354×
            if let Some(p) = &policy {
12828×
                let Some(sa) = &r.attestation else {
12830×
                    return fail(format!(
1284
                        "{remote_name}/{} has no attestation, which its policy requires",
1285
                        r.name
1286
                    ));
1287
                };
12888×
                let signer = sa
12898×
                    .sigs
12908×
                    .first()
12918×
                    .map(|s| s.key)
12928×
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
12938×
                if !p.authorizes(&signer, &r.name)
12940×
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
1295
                {
12960×
                    return fail(format!(
1297
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
1298
                        r.name,
12990×
                        signer.short(12)
1300
                    ));
13018×
                }
1302346×
            }
1303354×
            if let Some(sa) = &r.attestation {
1304
                let AttestBody::Ref {
130519×
                    old_state,
130619×
                    new_state,
1307
                    ..
130819×
                } = &sa.attest.body
1309
                else {
13100×
                    return fail("remote sent a non-ref attestation for a bookmark");
1311
                };
131219×
                let (old_state, new_state) = (*old_state, *new_state);
131319×
                let serial = self
131419×
                    .check_ref_attest(
131519×
                        sa,
131619×
                        &r.name,
131719×
                        &old_state,
131819×
                        &new_state,
131919×
                        self.last_seen_serial(remote_name, &r.name),
1320
                        true,
1321
                    )
132219×
                    .map_err(|e| {
13230×
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
13240×
                    })?;
132519×
                if new_state != r.state {
13260×
                    return fail(format!(
1327
                        "attestation for {}/{} does not cover its current state",
1328
                        remote_name, r.name
1329
                    ));
133019×
                }
133119×
                let ar = self.store.put_attest(&sa.attest)?;
133219×
                for sig in &sa.sigs {
133319×
                    self.store.put_signature(&ar, sig)?;
1334
                }
133519×
                self.record_serial(remote_name, &r.name, serial)?;
1336335×
            }
1337354×
            view.remotes
1338354×
                .entry(remote_name.to_string())
1339354×
                .or_default()
1340354×
                .insert(r.name.clone(), state);
1341354×
            report.push((r.name, r.heads, imported.len()));
1342
        }
1343347×
        let mut new_tags = 0;
1344347×
        for t in &resp.tags {
134510×
            if view.tags.contains_key(&t.name) {
13464×
                continue;
13476×
            }
1348
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
13496×
            let missing: Vec<ChangeHash> = t
13506×
                .heads
13516×
                .iter()
13526×
                .filter(|h| !self.store.has(h))
13536×
                .copied()
13546×
                .collect();
13556×
            if !missing.is_empty() {
13560×
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
13570×
                let bundle = remote.fetch(&needed, max_blob)?;
13580×
                self.import_bundle(&bundle, false)?;
13596×
            }
13606×
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
13616×
            self.adopt_tag(&mut view, t, policy.as_ref())
13626×
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
13636×
            new_tags += 1;
1364
        }
1365347×
        if view != op.view {
1366337×
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
136710×
        }
1368347×
        let _ = self.run_hook(
1369347×
            "post-fetch",
1370347×
            &format!(
1371
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1372347×
                json_str(remote_name),
1373354×
                json_array(report.iter().map(|(n, heads, _)| format!(
1374
                    "{{\"name\":{},\"heads\":{}}}",
1375354×
                    json_str(n),
1376515×
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1377
                )))
1378
            ),
1379
        );
1380347×
        Ok(FetchReport {
1381347×
            refs: report,
1382347×
            unverified,
1383347×
            new_tags,
1384347×
        })
1385353×
    }
1386
1387
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1388
    /// the changes within `depth` steps of its heads, and the boundary below.
13891×
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
13901×
        let remote = self.open_named_remote(remote_name)?;
13911×
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
13921×
        let resp = remote.refs()?;
13931×
        let bookmark = self.config.bookmark.clone();
13941×
        if let Some(sp) = &resp.policy {
13950×
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
13960×
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
13970×
            self.record_policy_serial(remote_name, sp.policy.serial)?;
13981×
        }
13991×
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
14000×
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1401
        };
14021×
        if r.heads.is_empty() {
14030×
            return Ok(0);
14041×
        }
1405
        // Base: the remote's checkpoint of exactly these heads.
14061×
        let cp_bundle = remote.checkpoint(&r.heads)?;
14071×
        let mut cp_ref = None;
14083×
        for (ty, body) in &cp_bundle.objects {
14093×
            let put = self.store.put(*ty, body)?;
14103×
            if *ty == ObjectType::Checkpoint {
14111×
                cp_ref = Some(put);
14122×
            }
1413
        }
14141×
        let Some(cp_ref) = cp_ref else {
14150×
            return fail(format!("{remote_name} sent no checkpoint"));
1416
        };
14171×
        self.install_checkpoint(&bookmark, &cp_ref)?;
1418
        // History window.
14191×
        let wanted = remote.shallow(&r.heads, depth)?;
14201×
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
14211×
        let imported = self.import_bundle_shallow(&bundle, false)?;
14221×
        if self.config.max_blob.is_some() {
14230×
            self.register_missing_blobs(&imported, remote_name)?;
14241×
        }
14251×
        self.refresh_boundary(&imported)?;
14261×
        if let Some(sa) = &r.attestation {
14270×
            let ar = self.store.put_attest(&sa.attest)?;
14280×
            for sig in &sa.sigs {
14290×
                self.store.put_signature(&ar, sig)?;
1430
            }
14310×
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
14320×
                self.record_serial(remote_name, &r.name, serial)?;
14330×
            }
14341×
        }
14351×
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
14361×
        let (op_ref, op) = self.head_op()?;
14371×
        let mut view = op.view.clone();
14381×
        view.remotes
14391×
            .entry(remote_name.to_string())
14401×
            .or_default()
14411×
            .insert(r.name.clone(), state);
14421×
        self.record_op(
14431×
            &[op_ref],
14441×
            &format!("oxy fetch {remote_name} --depth {depth}"),
14451×
            view,
14460×
        )?;
14471×
        Ok(imported.len())
14481×
    }
1449
1450
    /// Fetch, then take the union of the local bookmark's state with the
1451
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1452107×
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1453107×
        let _wc = self.lock_working_copy()?;
1454107×
        self.fetch(remote_name)?;
1455104×
        let (op_ref, op) = self.head_op()?;
1456104×
        let current = self.config.bookmark.clone();
1457104×
        let mut local_current = self.heads_of(&op.view, &current)?;
1458104×
        local_current.sort();
1459104×
        let mut view = op.view.clone();
1460104×
        let mut current_heads = local_current.clone();
1461104×
        let mut changed = false;
1462104×
        let mut others = Vec::new();
1463104×
        let tracked = op
1464104×
            .view
1465104×
            .remotes
1466104×
            .get(remote_name)
1467104×
            .cloned()
1468104×
            .unwrap_or_default();
1469108×
        for (name, remote_state) in tracked {
1470
            // Every local bookmark tracks the remote's of the same name;
1471
            // the current one may be new here.
1472108×
            let local_state = op.view.bookmarks.get(&name).copied();
1473108×
            if local_state.is_none() && name != current {
14740×
                continue;
1475108×
            }
1476108×
            if local_state == Some(remote_state) {
14778×
                continue;
1478100×
            }
1479100×
            let local = self.heads_of(&op.view, &name)?;
1480100×
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1481137×
            if remote_heads.iter().all(|h| local.contains(h)) {
14820×
                continue;
1483100×
            }
1484100×
            let mut all = local.clone();
1485100×
            all.extend(remote_heads);
1486100×
            let st = self.load_state_history(&all)?;
1487100×
            let mut heads = st.maximal(&all);
1488100×
            heads.sort();
1489100×
            let mut sorted_local = local;
1490100×
            sorted_local.sort();
1491100×
            if heads == sorted_local {
14921×
                continue;
149399×
            }
149499×
            view.bookmarks.insert(
149599×
                name.clone(),
149699×
                self.store.put_state(&StateObject::new(heads.clone()))?,
1497
            );
149899×
            if name == current {
149997×
                changed = true;
150097×
                current_heads = heads;
150197×
            } else {
15022×
                others.push(name);
15032×
            }
1504
        }
1505104×
        if changed || !others.is_empty() {
150698×
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
15076×
        }
1508
        // The working copy follows its bookmark whenever nothing would be
1509
        // lost, also when this pull brought nothing new but it had been
1510
        // left behind (oxygen#89).
1511104×
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
1512
        Ok(PullReport {
1513104×
            heads: if changed {
151497×
                current_heads
1515
            } else {
15167×
                local_current
1517
            },
1518104×
            changed,
1519104×
            checked_out,
1520104×
            others,
1521
        })
1522107×
    }
1523
1524
    /// How many changes the working copy's bookmark has that its base
1525
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1526
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1527
    /// the bookmark or holds changes the bookmark lacks. History is read
1528
    /// only when the base and the bookmark's heads differ (oxygen#89).
15297×
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
15307×
        let (_, wc) = self.working_copy()?;
15317×
        let mut base = wc.deps.clone();
15327×
        base.sort();
15337×
        let mut heads = self.bookmark_heads()?;
15347×
        heads.sort();
15357×
        if base == heads || heads.is_empty() {
15366×
            return Ok(None);
15371×
        }
15381×
        let state = self.load_state_history(&heads)?;
15391×
        if !base.iter().all(|h| state.contains(h)) {
15400×
            return Ok(None);
15411×
        }
15421×
        let had = if base.is_empty() {
15430×
            0
1544
        } else {
15451×
            self.load_state_history(&base)?.len()
1546
        };
15471×
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
15487×
    }
1549
1550
    /// Bring the working copy to `heads`, the state of its bookmark
1551
    /// `bookmark`, when nothing would be lost: its base is part of that
1552
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1553
    /// with uncommitted work, the work comes along when the new changes
1554
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1555
    /// it followed only from exactly the bookmark's old heads, so a working
1556
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1557
    /// or a pull from another workspace) never caught up, and nothing said
1558
    /// so (oxygen#74, #89). Returns whether it moved.
1559104×
    pub fn follow_bookmark(
1560104×
        &self,
1561104×
        heads: &[ChangeHash],
1562104×
        bookmark: &str,
1563104×
        command: &str,
1564104×
    ) -> Result<bool> {
1565104×
        let snap = self.snapshot(command)?;
1566104×
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1567104×
        let mut base = snap.base.maximal(&snap.wc.deps);
1568104×
        base.sort();
1569104×
        let mut target = heads.to_vec();
1570104×
        target.sort();
1571104×
        if base == target {
15726×
            return Ok(false);
157398×
        }
157498×
        let state = self.load_state_history(heads)?;
1575187×
        if !base.iter().all(|h| state.contains(h)) {
1576
            // The working copy holds changes the bookmark lacks: not ours to move.
15770×
            return Ok(false);
157898×
        }
157998×
        if clean {
158098×
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
158198×
            Ok(true)
1582
        } else {
15830×
            Ok(self
15840×
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
15850×
                .is_ok())
1586
        }
1587104×
    }
1588
1589
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1590
    /// changes and attesting the reference when a key is available.
1591
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1592
    /// state, attested when we have an identity. The local bookmark, if
1593
    /// any, is kept; only the remote-tracking entry goes.
15945×
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
15955×
        let remote = self.open_named_remote(remote_name)?;
15965×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
15975×
        let resp = remote.refs()?;
15987×
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
15991×
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1600
        };
16014×
        if resp.policy.is_some() && self.secret_key()?.is_none() {
16020×
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
16034×
        }
16044×
        let attestation = match self.secret_key()? {
16052×
            Some(_) => Some(self.sign_attest(&Attest {
16062×
                repo: self.id()?,
16072×
                hlc: Hlc::now(),
16082×
                body: AttestBody::Ref {
16092×
                    name: bookmark.to_string(),
16102×
                    old_state: r.state,
16112×
                    new_state: ObjectRef::ZERO,
16122×
                    serial: r.last_serial.unwrap_or(0) + 1,
16132×
                },
16140×
            })?),
16152×
            None => None,
1616
        };
16174×
        let results = remote.push(
16184×
            Bundle::default(),
16194×
            vec![RefUpdate {
16204×
                name: bookmark.to_string(),
16214×
                old_state: r.state,
16224×
                new_state: ObjectRef::ZERO,
16234×
                force: true,
16244×
                attestation,
16254×
            }],
16264×
            None,
16274×
            vec![],
16280×
        )?;
16294×
        if results.iter().any(|x| x.ok && x.name == bookmark) {
16302×
            let (op_ref, op) = self.head_op()?;
16312×
            let mut view = op.view.clone();
16322×
            if let Some(m) = view.remotes.get_mut(remote_name) {
16332×
                m.remove(bookmark);
16342×
            }
16352×
            self.record_op(
16362×
                &[op_ref],
16372×
                &format!("oxy push {remote_name} --delete {bookmark}"),
16382×
                view,
16390×
            )?;
16402×
        }
16414×
        Ok(results)
16425×
    }
1643
1644
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1645
    /// repository's config (its URL, token, CA and store settings), its
1646
    /// tracking bookmarks in the view, and a store remote's mirror under
1647
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
16483×
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
16493×
        if !self.config.remotes.contains_key(name) {
16501×
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
16512×
        }
16522×
        let prefix = format!("remote.{name}.");
16532×
        let keys: Vec<String> = self
16542×
            .config
16552×
            .repo_layer()
16562×
            .keys()
16574×
            .filter(|k| k.starts_with(&prefix))
16582×
            .cloned()
16592×
            .collect();
16603×
        for k in keys {
16613×
            self.config.set(&k, "")?;
1662
        }
16632×
        self.config.remotes.remove(name);
16642×
        self.save_config()?;
16652×
        let (op_ref, op) = self.head_op()?;
16662×
        if op.view.remotes.contains_key(name) {
16671×
            let mut view = op.view.clone();
16681×
            view.remotes.remove(name);
16691×
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
16701×
        }
16712×
        let mirror = self.oxy.join("remotes").join(name);
16722×
        if mirror.is_dir() {
16730×
            fs::remove_dir_all(&mirror)?;
16742×
        }
16752×
        Ok(())
16763×
    }
1677
1678
    /// `changes`, in dependency order, cut into batches of about
1679
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1680
    /// There is always one, perhaps empty.
1681275×
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1682275×
        let blob_len = |r: &ObjectRef| -> u64 {
168329×
            self.store
168429×
                .get_typed(r, ObjectType::Blob)
168529×
                .ok()
168629×
                .and_then(|b| Blob::decode(&b).ok())
168729×
                .map_or(0, |b| b.length)
168829×
        };
1689275×
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1690397×
        for h in changes {
1691397×
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1692397×
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1693397×
            let mut weight = raw.len() as u64;
1694506×
            for t in &texts {
1695506×
                if let crate::objects::TextRef::Blob(r, _, _) = t {
169626×
                    weight += blob_len(r);
1697480×
                }
1698
            }
1699647×
            for e in &c.edits {
17003×
                if let Edit::Replace { new: Some(b), .. } = e {
17013×
                    weight += blob_len(b);
1702644×
                }
1703
            }
1704397×
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
17055×
                out.push(std::mem::take(&mut batch));
17065×
                bytes = 0;
1707392×
            }
1708397×
            batch.push(*h);
1709397×
            bytes += weight;
1710
        }
1711275×
        out.push(batch);
1712275×
        Ok(out)
1713275×
    }
1714
1715341×
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1716341×
        let bookmark = self.config.bookmark.clone();
1717341×
        self.push_bookmark(remote_name, &bookmark, force)
1718341×
    }
1719
1720
    /// `push` for a named bookmark (`oxy push -b NAME`).
1721348×
    pub fn push_bookmark(
1722348×
        &self,
1723348×
        remote_name: &str,
1724348×
        bookmark: &str,
1725348×
        force: bool,
1726348×
    ) -> Result<Vec<RefResult>> {
1727348×
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1728348×
    }
1729
1730
    /// `push_bookmark`, saying how a long push is going: one line per
1731
    /// batch sent (oxygen#95).
1732356×
    pub fn push_bookmark_with(
1733356×
        &self,
1734356×
        remote_name: &str,
1735356×
        bookmark: &str,
1736356×
        force: bool,
1737356×
        progress: crate::store::Progress,
1738356×
    ) -> Result<Vec<RefResult>> {
1739356×
        let (op_ref, op) = self.head_op()?;
1740356×
        if !op.view.bookmarks.contains_key(bookmark) {
17410×
            return fail(format!("no bookmark {bookmark}"));
1742356×
        }
1743356×
        let bookmark = bookmark.to_string();
1744356×
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1745
        // pre-push hook: may veto before the remote is contacted.
1746356×
        self.run_hook(
1747356×
            "pre-push",
1748356×
            &format!(
1749
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1750356×
                json_str(remote_name),
1751356×
                json_str(&bookmark),
1752758×
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1753
            ),
17541×
        )?;
1755355×
        let remote = self.open_named_remote(remote_name)?;
1756355×
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1757352×
        let resp = remote.refs()?;
1758352×
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1759352×
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1760352×
        let policy_to_send = match (&local_policy, &resp.policy) {
176117×
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
17627×
            (Some(l), None) => Some(l.clone()),
17638×
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
17641×
                return fail(format!(
1765
                    "{remote_name} has a newer policy (serial {}); fetch first",
1766
                    r.policy.serial
1767
                ));
1768
            }
1769335×
            _ => None,
1770
        };
1771351×
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1772351×
        if remote_has_policy && self.secret_key()?.is_none() {
17731×
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1774350×
        }
1775350×
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1776350×
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1777350×
            .tag_refs()?
1778350×
            .into_iter()
1779350×
            .filter(|t| !remote_tags.contains(&t.name))
1780350×
            .collect();
1781350×
        let refs = resp.refs;
1782350×
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1783350×
        let (remote_state, remote_heads, last_serial) =
1784350×
            match refs.iter().find(|r| r.name == bookmark) {
1785334×
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
178616×
                None => (empty, vec![], None),
1787
            };
1788350×
        let new_state = self
1789350×
            .store
1790350×
            .put_state(&StateObject::new(local_heads.clone()))?;
1791
        // A push that carries a policy re-attests the bookmark even when its
1792
        // state is unchanged, so the current attestation is always by a key
1793
        // the current policy authorizes (a revoked key's attestation would
1794
        // otherwise be refused by every later fetch).
1795350×
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
17968×
            return Ok(vec![RefResult {
17978×
                name: bookmark,
17988×
                ok: true,
17998×
                reason: "already up to date".into(),
18008×
            }]);
1801342×
        }
1802393×
        for h in &remote_heads {
1803393×
            if !self.store.has(h) {
180466×
                return fail(format!(
1805
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
180666×
                    h.short(12)
1807
                ));
1808327×
            }
1809
        }
1810276×
        if !force {
1811276×
            let closure = self.closure_in_store(&local_heads)?;
1812312×
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
18130×
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1814276×
            }
18150×
        }
1816276×
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1817276×
        let key = self.secret_key()?.map(|(k, _)| k);
1818276×
        if let Some(key) = key {
1819
            // Seal this author's changes that carry no valid authenticator,
1820
            // and adopt anonymous ones (zero author, spec §14.4). The seals
1821
            // are stored, so each batch's bundle carries those it needs.
182272×
            let mut unsigned = Vec::new();
182372×
            for h in &to_send {
182468×
                let c = self.store.get_change_meta(h)?;
182568×
                if (c.author == key || c.author.is_zero())
182665×
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
182738×
                {
182838×
                    unsigned.push(*h);
182938×
                }
1830
            }
183172×
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
183235×
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1833
            }
1834204×
        }
1835
        // A long history goes in batches, in dependency order, so neither
1836
        // side holds it whole and no request passes the remote's limit:
1837
        // all but the last carry objects alone; the last moves the bookmark
1838
        // (oxygen#95).
1839275×
        let batches = self.push_batches(&to_send)?;
1840275×
        let (last, earlier) = batches.split_last().expect("at least one batch");
1841275×
        for (i, batch) in earlier.iter().enumerate() {
18425×
            progress(&format!(
18435×
                "part {} of {}: {} changes",
18445×
                i + 1,
18455×
                batches.len(),
18465×
                batch.len()
18475×
            ));
18485×
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
18495×
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
18505×
                Some(r) if r.ok => {}
18510×
                Some(r) => {
18520×
                    return fail(format!(
1853
                        "{remote_name} refused part {} of the push: {}",
18540×
                        i + 1,
1855
                        r.reason
1856
                    ))
1857
                }
1858
                None => {
18590×
                    return fail(format!(
1860
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
1861
                    ))
1862
                }
1863
            }
1864
        }
1865275×
        if batches.len() > 1 {
18661×
            progress(&format!(
18671×
                "part {} of {}: {} changes",
18681×
                batches.len(),
18691×
                batches.len(),
18701×
                last.len()
18711×
            ));
1872274×
        }
1873275×
        let mut bundle = self.bundle_for(last)?;
1874275×
        bundle.objects.push((
1875275×
            ObjectType::State,
1876275×
            StateObject::new(local_heads.clone()).encode(),
1877275×
        ));
1878275×
        let attestation = match key {
187971×
            Some(_) => Some(self.sign_attest(&Attest {
188071×
                repo: self.id()?,
188171×
                hlc: Hlc::now(),
188271×
                body: AttestBody::Ref {
188371×
                    name: bookmark.clone(),
188471×
                    old_state: remote_state,
188571×
                    new_state,
188671×
                    serial: next_serial(last_serial),
188771×
                },
18881×
            })?),
1889204×
            None => None,
1890
        };
1891274×
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
189270×
            AttestBody::Ref { serial, .. } => Some(serial),
18930×
            _ => None,
189470×
        });
1895274×
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1896
        // Tag states must be present on the remote: bundle their changes too.
1897274×
        for t in &tags_to_send {
18986×
            let extra = self.negotiate(&remote_heads, &t.heads)?;
18996×
            let extra: Vec<ChangeHash> =
19006×
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
19016×
            if !extra.is_empty() {
19020×
                let more = self.bundle_for(&extra)?;
19030×
                bundle.changes.extend(more.changes);
19040×
                bundle.hashes.extend(more.hashes);
19050×
                bundle.attests.extend(more.attests);
19060×
                bundle.objects.extend(more.objects);
19076×
            }
19086×
            bundle.objects.push((
19096×
                ObjectType::State,
19106×
                StateObject::new(t.heads.clone()).encode(),
19116×
            ));
1912
        }
1913274×
        if let Some(l) = &policy_to_send {
191416×
            let remote_serial = resp_policy_serial;
191516×
            bundle.policies = self
191616×
                .policy_history()?
191716×
                .into_iter()
191839×
                .filter(|sp| {
191939×
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
192018×
                        && sp.policy.serial < l.policy.serial
192139×
                })
192216×
                .collect();
1923258×
        }
1924274×
        let results = remote.push(
1925274×
            bundle,
1926274×
            vec![RefUpdate {
1927274×
                name: bookmark.clone(),
1928274×
                old_state: remote_state,
1929274×
                new_state,
1930274×
                force,
1931274×
                attestation,
1932274×
            }],
1933274×
            policy_to_send,
1934274×
            tags_to_send,
19356×
        )?;
193616×
        if let (Some(serial), true) = (
1937268×
            sent_serial,
1938274×
            results.iter().any(|r| r.ok && r.name == "policy"),
1939
        ) {
194016×
            self.record_policy_serial(remote_name, serial)?;
1941252×
        }
1942284×
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1943245×
            let mut view = op.view.clone();
1944245×
            view.remotes
1945245×
                .entry(remote_name.to_string())
1946245×
                .or_default()
1947245×
                .insert(bookmark.clone(), new_state);
1948245×
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1949242×
            if let Some(s) = serial {
195054×
                self.record_serial(remote_name, &bookmark, s)?;
1951188×
            }
195223×
        }
1953263×
        Ok(results)
1954356×
    }
1955
1956
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1957
    /// bookmark set to the remote's, working copy checked out.
1958223×
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1959223×
        Self::clone_with(url, dest, None, &[])
1960223×
    }
1961
1962
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1963
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1964
    /// unless a size is given, so out-of-scope binaries are never fetched).
1965231×
    pub fn clone_with(
1966231×
        url: &str,
1967231×
        dest: &Path,
1968231×
        max_blob: Option<u64>,
1969231×
        sparse: &[String],
1970231×
    ) -> Result<Repo> {
1971231×
        Self::clone_full(url, dest, max_blob, sparse, None)
1972231×
    }
1973
1974
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1975
    /// changes within `depth` steps of them; the rest is the boundary.
19761×
    pub fn clone_shallow(
19771×
        url: &str,
19781×
        dest: &Path,
19791×
        depth: u32,
19801×
        max_blob: Option<u64>,
19811×
        sparse: &[String],
19821×
    ) -> Result<Repo> {
19831×
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
19841×
    }
1985
1986232×
    fn clone_full(
1987232×
        url: &str,
1988232×
        dest: &Path,
1989232×
        max_blob: Option<u64>,
1990232×
        sparse: &[String],
1991232×
        depth: Option<u32>,
1992232×
    ) -> Result<Repo> {
1993232×
        let options = crate::credentials::Credentials::user().options_for(url);
1994232×
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
1995232×
    }
1996
1997
    /// Clone a subrepo with the credentials the parent would use for its
1998
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1999
    /// subrepo: it finds the same ones again through its parent.
20008×
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
20018×
        let options = self.credentials_for(url);
20028×
        Self::clone_using(url, dest, None, &[], None, &options)
20038×
    }
2004
2005
    /// The name of a remote of this repository on the same hub (scheme,
2006
    /// host and port) as `url`.
200719×
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
200823×
        let origin = |u: &str| -> Option<String> {
200923×
            let (scheme, rest) = u.split_once("://")?;
20108×
            if !matches!(scheme, "http" | "https") {
20110×
                return None;
20128×
            }
20138×
            let host = rest.split('/').next()?;
20148×
            Some(format!(
20158×
                "{}://{}",
20168×
                scheme.to_ascii_lowercase(),
20178×
                host.to_ascii_lowercase()
20188×
            ))
201923×
        };
202019×
        let want = origin(url)?;
20214×
        self.config
20224×
            .remotes
20234×
            .iter()
20244×
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
20254×
            .map(|(name, _)| name.clone())
202619×
    }
2027
2028
    /// The token and CA to reach `url` with: those of a remote of this
2029
    /// repository on the same hub (scheme, host and port), else the
2030
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2031
    /// and enclosing checkouts', as a clone would use them.
203219×
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
203319×
        match self.remote_on_same_hub(url) {
20341×
            Some(name) => RemoteOptions {
20351×
                repo_id: None,
20361×
                cache_dir: None,
20371×
                ..self.remote_options(&name)
20381×
            },
2039
            None => {
204018×
                let mut options = RemoteOptions::default();
204118×
                self.fill_credentials(url, &mut options);
204218×
                options
2043
            }
2044
        }
204519×
    }
2046
2047240×
    fn clone_using(
2048240×
        url: &str,
2049240×
        dest: &Path,
2050240×
        max_blob: Option<u64>,
2051240×
        sparse: &[String],
2052240×
        depth: Option<u32>,
2053240×
        options: &RemoteOptions,
2054240×
    ) -> Result<Repo> {
2055240×
        let remote = open_remote(url, options)?;
2056240×
        let id = remote.repo_id()?;
2057236×
        if id == crate::protocol::UNBOUND_ID {
20582×
            return fail(format!(
2059
                "{url} is empty and unbound: push a repository to it first"
2060
            ));
2061234×
        }
2062234×
        let mut repo = Repo::init_with_id(dest, id)?;
2063234×
        repo.config
2064234×
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
2065234×
        if let Some(m) = max_blob {
20662×
            repo.config.set("filter.max-blob", &m.to_string())?;
2067232×
        } else if !sparse.is_empty() {
20681×
            repo.config.set("filter.max-blob", "0")?;
2069231×
        }
2070234×
        if !sparse.is_empty() {
20711×
            repo.config.set("filter.paths", &sparse.join(","))?;
2072233×
        }
2073234×
        repo.save_config()?;
2074234×
        if let Some(depth) = depth {
20751×
            repo.fetch_shallow("origin", depth)?;
2076
        } else {
2077233×
            repo.fetch("origin")?;
2078
        }
2079233×
        let (op_ref, op) = repo.head_op()?;
2080
        // The remote's default bookmark, else ours (main), else its only one.
2081233×
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
2082
        // Asked of the remote as now configured, so a store-backed one
2083
        // answers from the mirror the fetch just filled.
2084233×
        let advertised = repo
2085233×
            .open_named_remote("origin")
2086233×
            .ok()
2087233×
            .and_then(|r| r.refs().ok())
2088233×
            .and_then(|r| r.default_bookmark);
2089233×
        let bookmark = advertised
2090233×
            .filter(|b| theirs.contains_key(b))
2091233×
            .or_else(|| {
20927×
                theirs
20937×
                    .contains_key(&repo.config.bookmark)
20947×
                    .then(|| repo.config.bookmark.clone())
20957×
            })
2096233×
            .or_else(|| {
20970×
                (theirs.len() == 1)
20980×
                    .then(|| theirs.keys().next().cloned())
20990×
                    .flatten()
21000×
            })
2101233×
            .unwrap_or_else(|| repo.config.bookmark.clone());
2102233×
        let initial = repo.config.bookmark.clone();
2103233×
        if bookmark != repo.config.bookmark {
21041×
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
21051×
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
21061×
            repo.config.bookmark = bookmark.clone();
2107232×
        }
2108233×
        if let Some(state) = theirs.get(&bookmark).copied() {
2109233×
            let heads = repo.store.get_state(&state)?.heads;
2110233×
            let mut view = op.view.clone();
2111
            // The empty bookmark `init` made goes when another is checked out.
2112233×
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
21131×
                view.bookmarks.remove(&initial);
2114232×
            }
2115233×
            view.bookmarks.insert(bookmark, state);
2116233×
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2117233×
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
21180×
        }
2119233×
        Ok(repo)
2120240×
    }
2121
}
2122
2123
/// The serial of a reference's next attestation: one more than the last the
2124
/// remote reports, or, for a bookmark the remote does not have, the clock in
2125
/// milliseconds, so a bookmark created again after a deletion goes past the
2126
/// deletion's serial the remote keeps.
212771×
fn next_serial(last: Option<u64>) -> u64 {
212871×
    match last {
212945×
        Some(l) => l + 1,
213026×
        None => Hlc::now().wall_ms.max(1),
2131
    }
213271×
}