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