OXYGENHUB
# be0161a88dd7 oxygen / crates / oxy-core / src / repo / sync.rs
53.3 KiB · Rust · last changed State is Send + Sync; shared lane layout; log_window 1 month ago source blame history raw
1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
5
/// What a push did, for hosts (hub spec §6.12).
6
#[derive(Clone, Debug, Default)]
7
pub struct PushReport {
8
    pub results: Vec<RefResult>,
9
    /// Accepted reference updates, in request order.
10
    pub updated: Vec<RefUpdated>,
11
    /// Changes this push stored that were not already present.
12
    pub imported: Vec<ChangeHash>,
13
}
14
15
#[derive(Clone, Debug)]
16
pub struct RefUpdated {
17
    pub name: String,
18
    pub old_state: ObjectRef,
19
    pub new_state: ObjectRef,
20
    pub heads: Vec<ChangeHash>,
21
}
22
23
/// What a fetch brought in.
24
#[derive(Debug, Clone, PartialEq, Eq, Default)]
25
pub struct FetchReport {
26
    /// Bookmark name, its heads, and how many changes were new.
27
    pub refs: Vec<(String, Vec<ChangeHash>, usize)>,
28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
30
    /// The remote has never presented a policy, so nothing was verified
31
    /// against one (spec §14.5: warn loudly).
32
    pub unverified: bool,
33
}
34
35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub struct PullReport {
37
    pub heads: Vec<ChangeHash>,
38
    pub changed: bool,
39
    pub checked_out: bool,
40
}
41
42
impl Repo {
43
    // ------------------------------------------------------------ serving (spec §16)
44
45
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
46
        self.oxy.join("attest").join(bookmark)
47
    }
48
49
    /// The latest reference attestation stored for a bookmark.
50
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
51
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
52
            Ok(h) => {
53
                let r = ObjectRef::from_hex(h.trim())
54
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
55
                Ok(Some((
56
                    r,
57
                    SignedAttest {
58
                        attest: self.store.get_attest(&r)?,
59
                        sigs: self.store.signatures(&r)?,
60
                    },
61
                )))
62
            }
63
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
64
            Err(e) => Err(e.into()),
65
        }
66
    }
67
68
    fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
69
        fs::create_dir_all(self.oxy.join("attest"))?;
70
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
71
    }
72
73
    pub fn remote_refs(&self) -> Result<RefsResponse> {
74
        let view = self.view()?;
75
        let mut out = Vec::new();
76
        for (name, state) in &view.bookmarks {
77
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
78
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
79
                AttestBody::Ref { serial, .. } => Some(serial),
80
                _ => None,
81
            });
82
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
83
            out.push(RemoteRef {
84
                name: name.clone(),
85
                state: *state,
86
                heads: self.store.get_state(state)?.heads,
87
                attestation,
88
                last_serial,
89
            });
90
        }
91
        let policy = self.current_policy()?.map(|(_, sp)| sp);
92
        let history = self
93
            .policy_history()?
94
            .into_iter()
95
            .filter(|sp| {
96
                policy
97
                    .as_ref()
98
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
99
            })
100
            .collect();
101
        Ok(RefsResponse {
102
            refs: out,
103
            policy,
104
            tags: self.tag_refs()?,
105
            history,
106
        })
107
    }
108
109
    /// Every change reachable from `heads` that is in the store.
110
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
111
        let mut seen = BTreeSet::new();
112
        let mut stack: Vec<ChangeHash> = heads.to_vec();
113
        while let Some(h) = stack.pop() {
114
            if seen.contains(&h) || !self.store.has(&h) {
115
                continue;
116
            }
117
            seen.insert(h);
118
            stack.extend(self.store.get_change(&h)?.deps);
119
        }
120
        Ok(seen)
121
    }
122
123
    /// The changes within `depth` dependency steps of `heads` (spec §17),
124
    /// nearest first; depth 1 is the heads themselves.
125
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
126
        let mut out = Vec::new();
127
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
128
        let mut layer: Vec<ChangeHash> = heads.to_vec();
129
        for _ in 0..depth.max(1) {
130
            let mut next = Vec::new();
131
            for h in layer {
132
                if !seen.insert(h) || !self.store.has(&h) {
133
                    continue;
134
                }
135
                let c = self.store.get_change(&h)?;
136
                next.extend(c.deps.iter().copied());
137
                out.push(h);
138
            }
139
            if next.is_empty() {
140
                break;
141
            }
142
            layer = next;
143
        }
144
        out.reverse();
145
        Ok(out)
146
    }
147
148
    fn shallow_path(&self) -> PathBuf {
149
        self.oxy.join("shallow")
150
    }
151
152
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
153
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
154
        fs::read_to_string(self.shallow_path())
155
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
156
            .unwrap_or_default()
157
    }
158
159
    pub fn is_shallow(&self) -> bool {
160
        !self.boundary().is_empty()
161
    }
162
163
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
164
        if boundary.is_empty() {
165
            let _ = fs::remove_file(self.shallow_path());
166
            return Ok(());
167
        }
168
        let text: String = boundary
169
            .iter()
170
            .map(|h| format!("{}\n", h.to_hex()))
171
            .collect();
172
        write_atomic(&self.shallow_path(), text.as_bytes())
173
    }
174
175
    /// Recompute the boundary from what is stored: every dependency of a
176
    /// stored change that is not itself stored.
177
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
178
        let mut boundary = self.boundary();
179
        boundary.retain(|h| !self.store.has(h));
180
        for h in imported {
181
            for d in self.store.get_change(h)?.deps {
182
                if !self.store.has(&d) {
183
                    boundary.insert(d);
184
                }
185
            }
186
        }
187
        self.write_boundary(&boundary)
188
    }
189
190
    /// Fetch `depth` more levels of history below the shallow boundary.
191
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
192
        let boundary = self.boundary();
193
        if boundary.is_empty() {
194
            return Ok(0);
195
        }
196
        let remote = self.open_named_remote(remote_name)?;
197
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
198
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
199
        let imported = self.import_bundle_shallow(&bundle, false)?;
200
        if self.config.max_blob.is_some() {
201
            self.register_missing_blobs(&imported, remote_name)?;
202
        }
203
        self.refresh_boundary(&imported)?;
204
        Ok(imported.len())
205
    }
206
207
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
208
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
209
        let have = self.closure_in_store(have)?;
210
        // In a shallow repository the walk stops at the boundary, whose
211
        // changes the remote is assumed to hold.
212
        let boundary = self.boundary();
213
        let mut out = Vec::new();
214
        let mut done: BTreeSet<ChangeHash> = have.clone();
215
        done.extend(boundary.iter().copied());
216
        // Iterative post-order DFS.
217
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
218
        while let Some((h, expanded)) = stack.pop() {
219
            if done.contains(&h) {
220
                continue;
221
            }
222
            if !self.store.has(&h) {
223
                return fail(format!("change {} is not in this repository", h.short(12)));
224
            }
225
            if expanded {
226
                done.insert(h);
227
                out.push(h);
228
                continue;
229
            }
230
            stack.push((h, true));
231
            for d in self.store.get_change(&h)?.deps {
232
                if !done.contains(&d) {
233
                    stack.push((d, false));
234
                }
235
            }
236
        }
237
        Ok(out)
238
    }
239
240
    /// Bundle changes (in the given dependency order) with their signatures,
241
    /// seals, identities, blobs, chunks.
242
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
243
        self.bundle_for_filtered(changes, None)
244
    }
245
246
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
247
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
248
        let mut out = Vec::new();
249
        for r in refs {
250
            let (ty, body) = match self.store.get(r) {
251
                Ok(x) => x,
252
                Err(StoreError::NotFound(_)) => continue,
253
                Err(e) => return Err(e.into()),
254
            };
255
            if ty == ObjectType::Blob {
256
                for c in Blob::decode(&body)?.chunks {
257
                    if let Ok((cty, cb)) = self.store.get(&c) {
258
                        out.push((cty, cb));
259
                    }
260
                }
261
            }
262
            out.push((ty, body));
263
        }
264
        Ok(out)
265
    }
266
267
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
268
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
269
    pub fn bundle_for_filtered(
270
        &self,
271
        changes: &[ChangeHash],
272
        max_blob: Option<u64>,
273
    ) -> Result<Bundle> {
274
        let mut bundle = Bundle::default();
275
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
276
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
277
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
278
            if !r.is_zero() && self.store.has(r) {
279
                objects.insert(*r);
280
            }
281
        };
282
        for h in changes {
283
            let c = self.store.get_change(h)?;
284
            let sigs = self.store.signatures(h)?;
285
            add_object(&c.author, &mut objects);
286
            for s in &sigs {
287
                add_object(&s.key, &mut objects);
288
            }
289
            for e in &c.edits {
290
                if let Edit::Replace { old, new, .. } = e {
291
                    for b in [old, new].into_iter().flatten() {
292
                        if self.store.has(b) {
293
                            if let Ok(blob) =
294
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
295
                            {
296
                                if max_blob.is_some_and(|m| blob.length > m) {
297
                                    continue;
298
                                }
299
                                objects.insert(*b);
300
                                objects.extend(blob.chunks.iter().copied());
301
                            }
302
                        }
303
                    }
304
                }
305
            }
306
            for s in self.store.seals_for(h)? {
307
                seals.insert(s);
308
            }
309
            bundle.changes.push((c, sigs));
310
        }
311
        for r in seals {
312
            let attest = self.store.get_attest(&r)?;
313
            let sigs = self.store.signatures(&r)?;
314
            for s in &sigs {
315
                add_object(&s.key, &mut objects);
316
            }
317
            bundle.attests.push(SignedAttest { attest, sigs });
318
        }
319
        for r in objects {
320
            let (ty, body) = self.store.get(&r)?;
321
            bundle.objects.push((ty, body));
322
        }
323
        Ok(bundle)
324
    }
325
326
    /// Store a bundle's contents. With `strict`, every change must
327
    /// authenticate (signature or seal by its author or a delegate).
328
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
329
        self.import_bundle_inner(bundle, strict, false)
330
    }
331
332
    /// Like `import_bundle`, accepting changes whose dependencies are absent
333
    /// (they join the shallow boundary).
334
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
335
        self.import_bundle_inner(bundle, strict, true)
336
    }
337
338
    fn import_bundle_inner(
339
        &self,
340
        bundle: &Bundle,
341
        strict: bool,
342
        shallow: bool,
343
    ) -> Result<Vec<ChangeHash>> {
344
        let batch = self.store.begin_batch()?;
345
        let result = self.import_bundle_batched(bundle, strict, shallow);
346
        batch.finish()?;
347
        result
348
    }
349
350
    fn import_bundle_batched(
351
        &self,
352
        bundle: &Bundle,
353
        strict: bool,
354
        shallow: bool,
355
    ) -> Result<Vec<ChangeHash>> {
356
        for (ty, body) in &bundle.objects {
357
            match ty {
358
                ObjectType::Chunk
359
                | ObjectType::Blob
360
                | ObjectType::Identity
361
                | ObjectType::State
362
                | ObjectType::Checkpoint => {
363
                    self.store.put(*ty, body)?;
364
                }
365
                other => return fail(format!("bundle may not carry {} objects", other.name())),
366
            }
367
        }
368
        for sa in &bundle.attests {
369
            let r = self.store.put_attest(&sa.attest)?;
370
            for sig in &sa.sigs {
371
                self.store.put_signature(&r, sig)?;
372
            }
373
            if let AttestBody::Seal { hashes } = &sa.attest.body {
374
                for h in hashes {
375
                    self.store.index_seal(h, &r)?;
376
                }
377
            }
378
        }
379
        let incoming: BTreeSet<ChangeHash> = bundle.changes.iter().map(|(c, _)| c.hash()).collect();
380
        let boundary = self.boundary();
381
        let mut imported = Vec::new();
382
        for (c, sigs) in &bundle.changes {
383
            let h = c.hash();
384
            for d in &c.deps {
385
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
386
                {
387
                    return fail(format!(
388
                        "change {} depends on {}, which is neither stored nor in the bundle",
389
                        h.short(12),
390
                        d.short(12)
391
                    ));
392
                }
393
            }
394
            self.store.put_change(c)?;
395
            for sig in sigs {
396
                self.store.put_signature(&h, sig)?;
397
            }
398
            imported.push(h);
399
        }
400
        if strict {
401
            for h in &imported {
402
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
403
                    return fail(format!(
404
                        "change {} is not authenticated by its author",
405
                        h.short(12)
406
                    ));
407
                }
408
            }
409
        }
410
        Ok(imported)
411
    }
412
413
    /// Verify a reference attestation against an update it claims to describe.
414
    /// `allow_equal` lets a client re-read the attestation it already has; a
415
    /// server receiving a push requires a strictly greater serial.
416
    fn check_ref_attest(
417
        &self,
418
        sa: &SignedAttest,
419
        name: &str,
420
        old_state: &ObjectRef,
421
        new_state: &ObjectRef,
422
        last_serial: Option<u64>,
423
        allow_equal: bool,
424
    ) -> std::result::Result<u64, String> {
425
        let AttestBody::Ref {
426
            name: n,
427
            old_state: o,
428
            new_state: nw,
429
            serial,
430
        } = &sa.attest.body
431
        else {
432
            return Err("attestation is not a ref attestation".into());
433
        };
434
        if n != name || o != old_state || nw != new_state {
435
            return Err("attestation does not describe this update".into());
436
        }
437
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
438
            return Err("attestation is for a different repository".into());
439
        }
440
        if let Some(last) = last_serial {
441
            if *serial < last || (*serial == last && !allow_equal) {
442
                return Err(format!(
443
                    "attestation serial {serial} is not greater than the last seen {last}"
444
                ));
445
            }
446
        }
447
        let r = sa.attest.hash();
448
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
449
        let id = self
450
            .store
451
            .get_identity(&sig.key)
452
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
453
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
454
        Ok(*serial)
455
    }
456
457
    /// Accept a push (spec §16.4). Without a trust policy every repository
458
    /// is unverified, so unsigned changes and unattested updates are accepted;
459
    /// attestations that are present must still be valid. With a policy,
460
    /// every change and update is checked against it. A newer policy in the
461
    /// push is applied first when it is signed by the current roots.
462
    pub fn receive_push(
463
        &self,
464
        bundle: Bundle,
465
        updates: Vec<RefUpdate>,
466
        policy: Option<SignedPolicy>,
467
        tags: Vec<crate::protocol::TagRef>,
468
    ) -> Result<Vec<RefResult>> {
469
        Ok(self
470
            .receive_push_report(bundle, updates, policy, tags)?
471
            .results)
472
    }
473
474
    /// `receive_push` with what a host wants to log: each accepted
475
    /// reference's old and new state and heads, and the changes this push
476
    /// stored (hub spec §6.12).
477
    pub fn receive_push_report(
478
        &self,
479
        bundle: Bundle,
480
        updates: Vec<RefUpdate>,
481
        policy: Option<SignedPolicy>,
482
        tags: Vec<crate::protocol::TagRef>,
483
    ) -> Result<PushReport> {
484
        let mut report = PushReport::default();
485
        let results = &mut report.results;
486
        if let Some(sp) = policy {
487
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
488
                Ok(()) => {
489
                    results.push(RefResult {
490
                        name: "policy".into(),
491
                        ok: true,
492
                        reason: format!("serial {}", sp.policy.serial),
493
                    });
494
                }
495
                Err(e) => {
496
                    results.push(RefResult {
497
                        name: "policy".into(),
498
                        ok: false,
499
                        reason: e,
500
                    });
501
                    for u in updates {
502
                        results.push(RefResult {
503
                            name: u.name,
504
                            ok: false,
505
                            reason: "policy update was rejected".into(),
506
                        });
507
                    }
508
                    return Ok(report);
509
                }
510
            }
511
        }
512
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
513
        match self.import_bundle(&bundle, policy.is_some()) {
514
            Ok(imported) => report.imported = imported,
515
            Err(e) => {
516
                for u in updates {
517
                    results.push(RefResult {
518
                        name: u.name,
519
                        ok: false,
520
                        reason: e.to_string(),
521
                    });
522
                }
523
                return Ok(report);
524
            }
525
        }
526
        let (op_ref, op) = self.head_op()?;
527
        let mut view = op.view.clone();
528
        let mut names = Vec::new();
529
        for u in updates {
530
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
531
            let (ok, reason) = match outcome {
532
                Ok(()) => (true, String::new()),
533
                Err(e) => (false, e),
534
            };
535
            if ok {
536
                names.push(u.name.clone());
537
                let heads = self
538
                    .store
539
                    .get_state(&u.new_state)
540
                    .map(|s| s.heads)
541
                    .unwrap_or_default();
542
                report.updated.push(RefUpdated {
543
                    name: u.name.clone(),
544
                    old_state: u.old_state,
545
                    new_state: u.new_state,
546
                    heads,
547
                });
548
            }
549
            results.push(RefResult {
550
                name: u.name,
551
                ok,
552
                reason,
553
            });
554
        }
555
        for t in &tags {
556
            let name = format!("tags/{}", t.name);
557
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
558
                Ok(()) => {
559
                    names.push(name.clone());
560
                    results.push(RefResult {
561
                        name,
562
                        ok: true,
563
                        reason: String::new(),
564
                    });
565
                }
566
                Err(e) => results.push(RefResult {
567
                    name,
568
                    ok: false,
569
                    reason: e,
570
                }),
571
            }
572
        }
573
        if !names.is_empty() {
574
            self.record_op(
575
                &[op_ref],
576
                &format!("push received: {}", names.join(" ")),
577
                view,
578
            )?;
579
        }
580
        Ok(report)
581
    }
582
583
    fn apply_update(
584
        &self,
585
        view: &mut View,
586
        u: &RefUpdate,
587
        policy: Option<&crate::policy::Policy>,
588
    ) -> std::result::Result<(), String> {
589
        if u.name == "policy" {
590
            return Err(
591
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
592
            );
593
        }
594
        let empty = self
595
            .store
596
            .put_state(&StateObject::new(vec![]))
597
            .map_err(|e| e.to_string())?;
598
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
599
        if current != u.old_state {
600
            return Err("stale: the remote bookmark has moved; pull first".into());
601
        }
602
        let new_state = self
603
            .store
604
            .get_state(&u.new_state)
605
            .map_err(|_| "new state object is missing".to_string())?;
606
        for h in &new_state.heads {
607
            if !self.store.has(h) {
608
                return Err(format!("head {} is missing", h.short(12)));
609
            }
610
        }
611
        if !u.force {
612
            let old_heads = self
613
                .store
614
                .get_state(&current)
615
                .map_err(|e| e.to_string())?
616
                .heads;
617
            let closure = self
618
                .closure_in_store(&new_state.heads)
619
                .map_err(|e| e.to_string())?;
620
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
621
                return Err(format!(
622
                    "not a fast-forward: current head {} would be dropped (use --force)",
623
                    h.short(12)
624
                ));
625
            }
626
        }
627
        if let Some(p) = policy {
628
            let Some(sa) = &u.attestation else {
629
                return Err(format!(
630
                    "{:?} requires a signed reference attestation under this repository's policy",
631
                    u.name
632
                ));
633
            };
634
            let signer = sa
635
                .sigs
636
                .first()
637
                .map(|s| s.key)
638
                .ok_or("attestation carries no signature")?;
639
            if !p.authorizes(&signer, &u.name) {
640
                return Err(format!(
641
                    "key {} may not update {:?} under this repository's policy",
642
                    signer.short(12),
643
                    u.name
644
                ));
645
            }
646
            let old_heads = self
647
                .store
648
                .get_state(&current)
649
                .map_err(|e| e.to_string())?
650
                .heads;
651
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
652
        }
653
        if let Some(sa) = &u.attestation {
654
            let last = self
655
                .latest_ref_attest(&u.name)
656
                .map_err(|e| e.to_string())?
657
                .and_then(|(_, a)| match a.attest.body {
658
                    AttestBody::Ref { serial, .. } => Some(serial),
659
                    _ => None,
660
                });
661
            self.check_ref_attest(sa, &u.name, &u.old_state, &u.new_state, last, false)?;
662
            let r = self
663
                .store
664
                .put_attest(&sa.attest)
665
                .map_err(|e| e.to_string())?;
666
            for sig in &sa.sigs {
667
                self.store
668
                    .put_signature(&r, sig)
669
                    .map_err(|e| e.to_string())?;
670
            }
671
            self.set_ref_attest(&u.name, &r)
672
                .map_err(|e| e.to_string())?;
673
        }
674
        view.bookmarks.insert(u.name.clone(), u.new_state);
675
        Ok(())
676
    }
677
678
    // ------------------------------------------------------------ client side
679
680
    fn remote_url(&self, name: &str) -> Result<String> {
681
        self.config.remotes.get(name).cloned().ok_or_else(|| {
682
            RepoError::Msg(format!(
683
                "no remote named {name:?}; add one with `oxy remote add`"
684
            ))
685
        })
686
    }
687
688
    /// Credentials and trust for a remote: `remote.<name>.token` (else
689
    /// `$OXY_TOKEN`) and `remote.<name>.ca` (else `$OXY_CA`).
690
    /// Refuse a remote that is another repository. An **unbound** remote
691
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
692
    /// for pushes, which bind it to this repository's id (spec §16.1).
693
    fn check_remote_id(
694
        &self,
695
        remote: &dyn crate::protocol::Remote,
696
        remote_name: &str,
697
        allow_unbound: bool,
698
    ) -> Result<()> {
699
        let theirs = remote.repo_id()?;
700
        if theirs == self.id()? {
701
            return Ok(());
702
        }
703
        if theirs == crate::protocol::UNBOUND_ID {
704
            if allow_unbound {
705
                return Ok(());
706
            }
707
            return fail(format!(
708
                "remote {remote_name:?} is empty and unbound: push to it first"
709
            ));
710
        }
711
        fail(format!(
712
            "remote {remote_name:?} is a different repository (repository IDs differ)"
713
        ))
714
    }
715
716
    fn remote_options(&self, name: &str) -> RemoteOptions {
717
        RemoteOptions {
718
            repo_id: self.id().ok(),
719
            token: self
720
                .config
721
                .remote_tokens
722
                .get(name)
723
                .cloned()
724
                .or_else(|| std::env::var("OXY_TOKEN").ok()),
725
            ca: self
726
                .config
727
                .remote_cas
728
                .get(name)
729
                .map(PathBuf::from)
730
                .or_else(|| std::env::var("OXY_CA").ok().map(PathBuf::from)),
731
        }
732
    }
733
734
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
735
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
736
    }
737
738
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
739
        self.oxy
740
            .join("remotes")
741
            .join(remote)
742
            .join(format!("{bookmark}.serial"))
743
    }
744
745
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
746
        fs::read_to_string(self.serial_path(remote, bookmark))
747
            .ok()
748
            .and_then(|s| s.trim().parse().ok())
749
    }
750
751
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
752
        let p = self.serial_path(remote, bookmark);
753
        fs::create_dir_all(p.parent().unwrap())?;
754
        write_atomic(&p, serial.to_string().as_bytes())
755
    }
756
757
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
758
        self.oxy.join("remotes").join(remote).join("policy.serial")
759
    }
760
761
    /// The highest policy serial `remote` has ever presented.
762
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
763
        fs::read_to_string(self.policy_serial_path(remote))
764
            .ok()
765
            .and_then(|s| s.trim().parse().ok())
766
    }
767
768
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
769
        let p = self.policy_serial_path(remote);
770
        fs::create_dir_all(p.parent().unwrap())?;
771
        write_atomic(&p, serial.to_string().as_bytes())
772
    }
773
774
    fn lazy_dir(&self) -> PathBuf {
775
        self.oxy.join("lazy")
776
    }
777
778
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
779
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
780
        fs::create_dir_all(self.lazy_dir())?;
781
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
782
    }
783
784
    /// Which remote promised an absent blob, if any.
785
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
786
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
787
            .ok()
788
            .map(|s| s.trim().to_string())
789
    }
790
791
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
792
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
793
        let Some(remote_name) = self.lazy_remote(blob) else {
794
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
795
        };
796
        let remote = self.open_named_remote(&remote_name)?;
797
        let objects = remote.objects(&[*blob])?;
798
        for (ty, body) in objects {
799
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
800
                self.store.put(ty, &body)?;
801
            }
802
        }
803
        if !self.store.has(blob) {
804
            return fail(format!(
805
                "{remote_name} did not send blob {}",
806
                blob.short(12)
807
            ));
808
        }
809
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
810
        Ok(())
811
    }
812
813
    /// After importing from `remote`, record every blob the changes reference
814
    /// that the store lacks as lazily available from that remote.
815
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
816
        let mut n = 0;
817
        for h in changes {
818
            let c = self.store.get_change(h)?;
819
            for e in &c.edits {
820
                if let Edit::Replace { old, new, .. } = e {
821
                    for b in [old, new].into_iter().flatten() {
822
                        if !self.store.has(b) {
823
                            self.register_lazy(b, remote)?;
824
                            n += 1;
825
                        }
826
                    }
827
                }
828
            }
829
        }
830
        Ok(n)
831
    }
832
833
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
834
    fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
835
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
836
        for st in view
837
            .bookmarks
838
            .values()
839
            .chain(view.remotes.values().flat_map(|b| b.values()))
840
        {
841
            if let Ok(s) = self.store.get_state(st) {
842
                have.extend(s.heads);
843
            }
844
        }
845
        have.extend(view.workspaces.values().copied());
846
        Ok(have.into_iter().collect())
847
    }
848
849
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
850
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
851
        let remote = self.open_named_remote(remote_name)?;
852
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
853
        let resp = remote.refs()?;
854
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
855
        // and signed by roots we trust, or on first contact. A remote that
856
        // once presented a policy may never present none or an older one:
857
        // that is a downgrade. A remote that never presented one is
858
        // unverified, and this fetch is checked only as far as possible.
859
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
860
        let seen = self.remote_policy_serial(remote_name);
861
        let mut unverified = false;
862
        match &resp.policy {
863
            Some(sp) => {
864
                if seen.is_some_and(|s| sp.policy.serial < s) {
865
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
866
                }
867
                match &local_policy {
868
                    Some(l) if sp.policy.serial < l.serial => {}
869
                    Some(l) if sp.policy.serial == l.serial => {
870
                        if sp.policy.hash() != l.hash() {
871
                            return fail(format!(
872
                                "{remote_name} presents a different policy with the same serial {}",
873
                                l.serial
874
                            ));
875
                        }
876
                    }
877
                    _ => {
878
                        self.adopt_policy_chain(
879
                            &resp.history,
880
                            sp,
881
                            &format!("oxy fetch {remote_name}"),
882
                        )
883
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
884
                    }
885
                }
886
                self.record_policy_serial(remote_name, sp.policy.serial)?;
887
            }
888
            None => {
889
                if seen.is_some() {
890
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
891
                }
892
                unverified = true;
893
            }
894
        }
895
        let policy = if unverified {
896
            None
897
        } else {
898
            self.current_policy()?.map(|(_, sp)| sp.policy)
899
        };
900
        let (op_ref, op) = self.head_op()?;
901
        let mut view = op.view.clone();
902
        let have = self.known_heads(&view)?;
903
        let mut report = Vec::new();
904
        let max_blob = self.config.max_blob;
905
        for r in resp.refs {
906
            let needed = remote.negotiate(&have, &r.heads)?;
907
            let bundle = remote.fetch(&needed, max_blob)?;
908
            // Changes are not individually re-verified here: the bookmark's
909
            // attestation (checked below) binds its whole state, and the
910
            // receiver of the push verified the added changes at that time.
911
            let imported = self.import_bundle(&bundle, false)?;
912
            if max_blob.is_some() {
913
                self.register_missing_blobs(&imported, remote_name)?;
914
            }
915
            for h in &r.heads {
916
                if !self.store.has(h) {
917
                    return fail(format!("remote did not send head {}", h.short(12)));
918
                }
919
            }
920
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
921
            if state != r.state {
922
                return fail(format!(
923
                    "remote state {} does not match its heads",
924
                    r.state.short(12)
925
                ));
926
            }
927
            if let Some(p) = &policy {
928
                let Some(sa) = &r.attestation else {
929
                    return fail(format!(
930
                        "{remote_name}/{} has no attestation, which its policy requires",
931
                        r.name
932
                    ));
933
                };
934
                let signer = sa
935
                    .sigs
936
                    .first()
937
                    .map(|s| s.key)
938
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
939
                if !p.authorizes(&signer, &r.name) {
940
                    return fail(format!(
941
                        "{remote_name}/{}: attested by {}, which the policy does not authorize",
942
                        r.name,
943
                        signer.short(12)
944
                    ));
945
                }
946
            }
947
            if let Some(sa) = &r.attestation {
948
                let AttestBody::Ref {
949
                    old_state,
950
                    new_state,
951
                    ..
952
                } = &sa.attest.body
953
                else {
954
                    return fail("remote sent a non-ref attestation for a bookmark");
955
                };
956
                let (old_state, new_state) = (*old_state, *new_state);
957
                let serial = self
958
                    .check_ref_attest(
959
                        sa,
960
                        &r.name,
961
                        &old_state,
962
                        &new_state,
963
                        self.last_seen_serial(remote_name, &r.name),
964
                        true,
965
                    )
966
                    .map_err(|e| {
967
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
968
                    })?;
969
                if new_state != r.state {
970
                    return fail(format!(
971
                        "attestation for {}/{} does not cover its current state",
972
                        remote_name, r.name
973
                    ));
974
                }
975
                let ar = self.store.put_attest(&sa.attest)?;
976
                for sig in &sa.sigs {
977
                    self.store.put_signature(&ar, sig)?;
978
                }
979
                self.record_serial(remote_name, &r.name, serial)?;
980
            }
981
            view.remotes
982
                .entry(remote_name.to_string())
983
                .or_default()
984
                .insert(r.name.clone(), state);
985
            report.push((r.name, r.heads, imported.len()));
986
        }
987
        let mut new_tags = 0;
988
        for t in &resp.tags {
989
            if view.tags.contains_key(&t.name) {
990
                continue;
991
            }
992
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
993
            let missing: Vec<ChangeHash> = t
994
                .heads
995
                .iter()
996
                .filter(|h| !self.store.has(h))
997
                .copied()
998
                .collect();
999
            if !missing.is_empty() {
1000
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1001
                let bundle = remote.fetch(&needed, max_blob)?;
1002
                self.import_bundle(&bundle, false)?;
1003
            }
1004
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
1005
            self.adopt_tag(&mut view, t, policy.as_ref())
1006
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
1007
            new_tags += 1;
1008
        }
1009
        if view != op.view {
1010
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1011
        }
1012
        let _ = self.run_hook(
1013
            "post-fetch",
1014
            &format!(
1015
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1016
                json_str(remote_name),
1017
                json_array(report.iter().map(|(n, heads, _)| format!(
1018
                    "{{\"name\":{},\"heads\":{}}}",
1019
                    json_str(n),
1020
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1021
                )))
1022
            ),
1023
        );
1024
        Ok(FetchReport {
1025
            refs: report,
1026
            unverified,
1027
            new_tags,
1028
        })
1029
    }
1030
1031
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1032
    /// the changes within `depth` steps of its heads, and the boundary below.
1033
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1034
        let remote = self.open_named_remote(remote_name)?;
1035
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1036
        let resp = remote.refs()?;
1037
        let bookmark = self.config.bookmark.clone();
1038
        if let Some(sp) = &resp.policy {
1039
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1040
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
1041
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1042
        }
1043
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1044
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1045
        };
1046
        if r.heads.is_empty() {
1047
            return Ok(0);
1048
        }
1049
        // Base: the remote's checkpoint of exactly these heads.
1050
        let cp_bundle = remote.checkpoint(&r.heads)?;
1051
        let mut cp_ref = None;
1052
        for (ty, body) in &cp_bundle.objects {
1053
            let put = self.store.put(*ty, body)?;
1054
            if *ty == ObjectType::Checkpoint {
1055
                cp_ref = Some(put);
1056
            }
1057
        }
1058
        let Some(cp_ref) = cp_ref else {
1059
            return fail(format!("{remote_name} sent no checkpoint"));
1060
        };
1061
        self.install_checkpoint(&bookmark, &cp_ref)?;
1062
        // History window.
1063
        let wanted = remote.shallow(&r.heads, depth)?;
1064
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1065
        let imported = self.import_bundle_shallow(&bundle, false)?;
1066
        if self.config.max_blob.is_some() {
1067
            self.register_missing_blobs(&imported, remote_name)?;
1068
        }
1069
        self.refresh_boundary(&imported)?;
1070
        if let Some(sa) = &r.attestation {
1071
            let ar = self.store.put_attest(&sa.attest)?;
1072
            for sig in &sa.sigs {
1073
                self.store.put_signature(&ar, sig)?;
1074
            }
1075
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1076
                self.record_serial(remote_name, &r.name, serial)?;
1077
            }
1078
        }
1079
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1080
        let (op_ref, op) = self.head_op()?;
1081
        let mut view = op.view.clone();
1082
        view.remotes
1083
            .entry(remote_name.to_string())
1084
            .or_default()
1085
            .insert(r.name.clone(), state);
1086
        self.record_op(
1087
            &[op_ref],
1088
            &format!("oxy fetch {remote_name} --depth {depth}"),
1089
            view,
1090
        )?;
1091
        Ok(imported.len())
1092
    }
1093
1094
    /// Fetch, then take the union of the local bookmark's state with the
1095
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1096
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
1097
        self.fetch(remote_name)?;
1098
        let (op_ref, op) = self.head_op()?;
1099
        let bookmark = self.config.bookmark.clone();
1100
        let local = self.heads_of(&op.view, &bookmark)?;
1101
        let Some(remote_state) = op
1102
            .view
1103
            .remotes
1104
            .get(remote_name)
1105
            .and_then(|b| b.get(&bookmark))
1106
            .copied()
1107
        else {
1108
            return Ok(PullReport {
1109
                heads: local,
1110
                changed: false,
1111
                checked_out: false,
1112
            });
1113
        };
1114
        let remote_heads = self.store.get_state(&remote_state)?.heads;
1115
        let mut all = local.clone();
1116
        all.extend(remote_heads);
1117
        let st = self.load_state(&all)?;
1118
        let mut heads = st.maximal(&all);
1119
        heads.sort();
1120
        let mut sorted_local = local.clone();
1121
        sorted_local.sort();
1122
        if heads == sorted_local {
1123
            return Ok(PullReport {
1124
                heads,
1125
                changed: false,
1126
                checked_out: false,
1127
            });
1128
        }
1129
        let mut view = op.view.clone();
1130
        view.bookmarks.insert(
1131
            bookmark.clone(),
1132
            self.store.put_state(&StateObject::new(heads.clone()))?,
1133
        );
1134
        self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
1135
        // Follow along if the working copy was clean and on the old heads.
1136
        let snap = self.snapshot("oxy pull")?;
1137
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1138
        let mut base = snap.base.maximal(&snap.wc.deps);
1139
        base.sort();
1140
        let mut checked_out = false;
1141
        if clean && base == sorted_local {
1142
            self.checkout(&heads, false, "oxy pull (checkout)")?;
1143
            checked_out = true;
1144
        }
1145
        Ok(PullReport {
1146
            heads,
1147
            changed: true,
1148
            checked_out,
1149
        })
1150
    }
1151
1152
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1153
    /// changes and attesting the reference when a key is available.
1154
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
1155
        let bookmark = self.config.bookmark.clone();
1156
        self.push_bookmark(remote_name, &bookmark, force)
1157
    }
1158
1159
    /// `push` for a named bookmark (`oxy push -b NAME`).
1160
    pub fn push_bookmark(
1161
        &self,
1162
        remote_name: &str,
1163
        bookmark: &str,
1164
        force: bool,
1165
    ) -> Result<Vec<RefResult>> {
1166
        let (op_ref, op) = self.head_op()?;
1167
        if !op.view.bookmarks.contains_key(bookmark) {
1168
            return fail(format!("no bookmark {bookmark}"));
1169
        }
1170
        let bookmark = bookmark.to_string();
1171
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1172
        // pre-push hook: may veto before the remote is contacted.
1173
        self.run_hook(
1174
            "pre-push",
1175
            &format!(
1176
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1177
                json_str(remote_name),
1178
                json_str(&bookmark),
1179
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1180
            ),
1181
        )?;
1182
        let remote = self.open_named_remote(remote_name)?;
1183
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1184
        let resp = remote.refs()?;
1185
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
1186
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
1187
        let policy_to_send = match (&local_policy, &resp.policy) {
1188
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1189
            (Some(l), None) => Some(l.clone()),
1190
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
1191
                return fail(format!(
1192
                    "{remote_name} has a newer policy (serial {}); fetch first",
1193
                    r.policy.serial
1194
                ));
1195
            }
1196
            _ => None,
1197
        };
1198
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1199
        if remote_has_policy && self.secret_key()?.is_none() {
1200
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1201
        }
1202
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
1203
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1204
            .tag_refs()?
1205
            .into_iter()
1206
            .filter(|t| !remote_tags.contains(&t.name))
1207
            .collect();
1208
        let refs = resp.refs;
1209
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
1210
        let (remote_state, remote_heads, last_serial) =
1211
            match refs.iter().find(|r| r.name == bookmark) {
1212
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1213
                None => (empty, vec![], None),
1214
            };
1215
        let new_state = self
1216
            .store
1217
            .put_state(&StateObject::new(local_heads.clone()))?;
1218
        // A push that carries a policy re-attests the bookmark even when its
1219
        // state is unchanged, so the current attestation is always by a key
1220
        // the current policy authorizes (a revoked key's attestation would
1221
        // otherwise be refused by every later fetch).
1222
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
1223
            return Ok(vec![RefResult {
1224
                name: bookmark,
1225
                ok: true,
1226
                reason: "already up to date".into(),
1227
            }]);
1228
        }
1229
        for h in &remote_heads {
1230
            if !self.store.has(h) {
1231
                return fail(format!(
1232
                    "the remote has change {} which you do not; pull first",
1233
                    h.short(12)
1234
                ));
1235
            }
1236
        }
1237
        if !force {
1238
            let closure = self.closure_in_store(&local_heads)?;
1239
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1240
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1241
            }
1242
        }
1243
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1244
        let mut bundle = self.bundle_for(&to_send)?;
1245
        let key = self.secret_key()?.map(|(k, _)| k);
1246
        if let Some(key) = key {
1247
            // Seal this author's changes that carry no valid authenticator,
1248
            // and adopt anonymous ones (zero author, spec §14.4).
1249
            let mut unsigned = Vec::new();
1250
            for h in &to_send {
1251
                let c = self.store.get_change(h)?;
1252
                if (c.author == key || c.author.is_zero())
1253
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1254
                {
1255
                    unsigned.push(*h);
1256
                }
1257
            }
1258
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
1259
                let sa = self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
1260
                bundle.attests.push(sa);
1261
            }
1262
            bundle = self.bundle_for(&to_send)?;
1263
        }
1264
        bundle.objects.push((
1265
            ObjectType::State,
1266
            StateObject::new(local_heads.clone()).encode(),
1267
        ));
1268
        let attestation = match key {
1269
            Some(_) => Some(self.sign_attest(&Attest {
1270
                repo: self.id()?,
1271
                hlc: Hlc::now(),
1272
                body: AttestBody::Ref {
1273
                    name: bookmark.clone(),
1274
                    old_state: remote_state,
1275
                    new_state,
1276
                    serial: last_serial.unwrap_or(0) + 1,
1277
                },
1278
            })?),
1279
            None => None,
1280
        };
1281
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1282
            AttestBody::Ref { serial, .. } => Some(serial),
1283
            _ => None,
1284
        });
1285
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
1286
        // Tag states must be present on the remote: bundle their changes too.
1287
        for t in &tags_to_send {
1288
            let extra = self.negotiate(&remote_heads, &t.heads)?;
1289
            let extra: Vec<ChangeHash> =
1290
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
1291
            if !extra.is_empty() {
1292
                let more = self.bundle_for(&extra)?;
1293
                bundle.changes.extend(more.changes);
1294
                bundle.attests.extend(more.attests);
1295
                bundle.objects.extend(more.objects);
1296
            }
1297
            bundle.objects.push((
1298
                ObjectType::State,
1299
                StateObject::new(t.heads.clone()).encode(),
1300
            ));
1301
        }
1302
        if let Some(l) = &policy_to_send {
1303
            let remote_serial = resp_policy_serial;
1304
            bundle.policies = self
1305
                .policy_history()?
1306
                .into_iter()
1307
                .filter(|sp| {
1308
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1309
                        && sp.policy.serial < l.policy.serial
1310
                })
1311
                .collect();
1312
        }
1313
        let results = remote.push(
1314
            bundle,
1315
            vec![RefUpdate {
1316
                name: bookmark.clone(),
1317
                old_state: remote_state,
1318
                new_state,
1319
                force,
1320
                attestation,
1321
            }],
1322
            policy_to_send,
1323
            tags_to_send,
1324
        )?;
1325
        if let (Some(serial), true) = (
1326
            sent_serial,
1327
            results.iter().any(|r| r.ok && r.name == "policy"),
1328
        ) {
1329
            self.record_policy_serial(remote_name, serial)?;
1330
        }
1331
        if results.iter().any(|r| r.ok && r.name == bookmark) {
1332
            let mut view = op.view.clone();
1333
            view.remotes
1334
                .entry(remote_name.to_string())
1335
                .or_default()
1336
                .insert(bookmark.clone(), new_state);
1337
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1338
            if let Some(s) = serial {
1339
                self.record_serial(remote_name, &bookmark, s)?;
1340
            }
1341
        }
1342
        Ok(results)
1343
    }
1344
1345
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1346
    /// bookmark set to the remote's, working copy checked out.
1347
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
1348
        Self::clone_with(url, dest, None, &[])
1349
    }
1350
1351
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1352
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1353
    /// unless a size is given, so out-of-scope binaries are never fetched).
1354
    pub fn clone_with(
1355
        url: &str,
1356
        dest: &Path,
1357
        max_blob: Option<u64>,
1358
        sparse: &[String],
1359
    ) -> Result<Repo> {
1360
        Self::clone_full(url, dest, max_blob, sparse, None)
1361
    }
1362
1363
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1364
    /// changes within `depth` steps of them; the rest is the boundary.
1365
    pub fn clone_shallow(
1366
        url: &str,
1367
        dest: &Path,
1368
        depth: u32,
1369
        max_blob: Option<u64>,
1370
        sparse: &[String],
1371
    ) -> Result<Repo> {
1372
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1373
    }
1374
1375
    fn clone_full(
1376
        url: &str,
1377
        dest: &Path,
1378
        max_blob: Option<u64>,
1379
        sparse: &[String],
1380
        depth: Option<u32>,
1381
    ) -> Result<Repo> {
1382
        let options = RemoteOptions {
1383
            token: std::env::var("OXY_TOKEN").ok(),
1384
            ca: std::env::var("OXY_CA").ok().map(PathBuf::from),
1385
            repo_id: None,
1386
        };
1387
        let remote = open_remote(url, &options)?;
1388
        let id = remote.repo_id()?;
1389
        if id == crate::protocol::UNBOUND_ID {
1390
            return fail(format!(
1391
                "{url} is empty and unbound: push a repository to it first"
1392
            ));
1393
        }
1394
        let mut repo = Repo::init_with_id(dest, id)?;
1395
        repo.config.set("remote.origin.url", url)?;
1396
        if let Some(m) = max_blob {
1397
            repo.config.set("filter.max-blob", &m.to_string())?;
1398
        } else if !sparse.is_empty() {
1399
            repo.config.set("filter.max-blob", "0")?;
1400
        }
1401
        if !sparse.is_empty() {
1402
            repo.config.set("filter.paths", &sparse.join(","))?;
1403
        }
1404
        repo.save_config()?;
1405
        if let Some(depth) = depth {
1406
            repo.fetch_shallow("origin", depth)?;
1407
        } else {
1408
            repo.fetch("origin")?;
1409
        }
1410
        let (op_ref, op) = repo.head_op()?;
1411
        let bookmark = repo.config.bookmark.clone();
1412
        if let Some(state) = op
1413
            .view
1414
            .remotes
1415
            .get("origin")
1416
            .and_then(|b| b.get(&bookmark))
1417
            .copied()
1418
        {
1419
            let heads = repo.store.get_state(&state)?.heads;
1420
            let mut view = op.view.clone();
1421
            view.bookmarks.insert(bookmark, state);
1422
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
1423
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
1424
        }
1425
        Ok(repo)
1426
    }
1427
}