OXYGENHUB
◆ only-help-103 oxygen / crates / oxy-core / src / repo / sync.rs
81.9 KiB · Rust · last changed remote remove: remove all of the remote 25 days ago source blame history raw
98286406 Andy McCall ↶ 1
//! Serving and talking to remotes (spec §10.2, §16).
2
3
use super::*;
4
7aa2dc93 Andy McCall ↶ 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
83e0677b Andy McCall ↶ 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)>,
132b884b Andy McCall ↶ 28
    /// Tags adopted from the remote.
29
    pub new_tags: usize,
83e0677b Andy McCall ↶ 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
98286406 Andy McCall ↶ 35
#[derive(Debug, Clone, PartialEq, Eq)]
36
pub struct PullReport {
14edbaaf Andy McCall ↶ 37
    /// The current bookmark's heads after the pull.
98286406 Andy McCall ↶ 38
    pub heads: Vec<ChangeHash>,
14edbaaf Andy McCall ↶ 39
    /// Whether the current bookmark changed.
98286406 Andy McCall ↶ 40
    pub changed: bool,
41
    pub checked_out: bool,
14edbaaf Andy McCall ↶ 42
    /// Other bookmarks the pull moved: each local bookmark tracks the
43
    /// remote's of the same name.
44
    pub others: Vec<String>,
98286406 Andy McCall ↶ 45
}
46
cb8b8082 Andy McCall ↶ 47
/// The result a push of objects alone reports (a batch of a long history):
48
/// not a reference.
49
pub const OBJECTS_RESULT: &str = "objects";
50
98286406 Andy McCall ↶ 51
impl Repo {
52
    // ------------------------------------------------------------ serving (spec §16)
53
54
    fn ref_attest_path(&self, bookmark: &str) -> PathBuf {
54cd08a1 Andy McCall ↶ 55
        self.oxy.join("attest").join(name_file(bookmark))
98286406 Andy McCall ↶ 56
    }
57
58
    /// The latest reference attestation stored for a bookmark.
59
    pub fn latest_ref_attest(&self, bookmark: &str) -> Result<Option<(ObjectRef, SignedAttest)>> {
60
        match fs::read_to_string(self.ref_attest_path(bookmark)) {
61
            Ok(h) => {
75167672 Andy McCall 62
                let r = ObjectRef::from_hex(h.trim())
63
                    .ok_or_else(|| RepoError::Msg("corrupt attestation pointer".into()))?;
64
                Ok(Some((
65
                    r,
66
                    SignedAttest {
67
                        attest: self.store.get_attest(&r)?,
68
                        sigs: self.store.signatures(&r)?,
69
                    },
70
                )))
98286406 Andy McCall ↶ 71
            }
72
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
73
            Err(e) => Err(e.into()),
74
        }
75
    }
76
9f9e72b9 Andy McCall ↶ 77
    pub(crate) fn set_ref_attest(&self, bookmark: &str, r: &ObjectRef) -> Result<()> {
98286406 Andy McCall ↶ 78
        fs::create_dir_all(self.oxy.join("attest"))?;
79
        write_atomic(&self.ref_attest_path(bookmark), r.to_hex().as_bytes())
80
    }
81
83e0677b Andy McCall ↶ 82
    pub fn remote_refs(&self) -> Result<RefsResponse> {
98286406 Andy McCall ↶ 83
        let view = self.view()?;
84
        let mut out = Vec::new();
85
        for (name, state) in &view.bookmarks {
86
            let latest = self.latest_ref_attest(name)?.map(|(_, a)| a);
87
            let last_serial = latest.as_ref().and_then(|a| match a.attest.body {
88
                AttestBody::Ref { serial, .. } => Some(serial),
89
                _ => None,
90
            });
91
            let attestation = latest.filter(|a| matches!(&a.attest.body, AttestBody::Ref { new_state, .. } if new_state == state));
75167672 Andy McCall 92
            out.push(RemoteRef {
93
                name: name.clone(),
94
                state: *state,
95
                heads: self.store.get_state(state)?.heads,
96
                attestation,
97
                last_serial,
98
            });
98286406 Andy McCall ↶ 99
        }
28fc23d7 Andy McCall ↶ 100
        let policy = self.current_policy()?.map(|(_, sp)| sp);
75167672 Andy McCall 101
        let history = self
102
            .policy_history()?
103
            .into_iter()
104
            .filter(|sp| {
105
                policy
106
                    .as_ref()
107
                    .is_some_and(|p| sp.policy.serial < p.policy.serial)
108
            })
109
            .collect();
110
        Ok(RefsResponse {
111
            refs: out,
112
            policy,
113
            tags: self.tag_refs()?,
114
            history,
14edbaaf Andy McCall ↶ 115
            default_bookmark: Some(self.config.bookmark.clone()),
75167672 Andy McCall 116
        })
98286406 Andy McCall ↶ 117
    }
118
119
    /// Every change reachable from `heads` that is in the store.
120
    fn closure_in_store(&self, heads: &[ChangeHash]) -> Result<BTreeSet<ChangeHash>> {
121
        let mut seen = BTreeSet::new();
122
        let mut stack: Vec<ChangeHash> = heads.to_vec();
123
        while let Some(h) = stack.pop() {
124
            if seen.contains(&h) || !self.store.has(&h) {
125
                continue;
126
            }
127
            seen.insert(h);
69816d68 Andy McCall ↶ 128
            stack.extend(self.store.get_change_meta(&h)?.deps);
98286406 Andy McCall ↶ 129
        }
130
        Ok(seen)
131
    }
132
2863456a Andy McCall ↶ 133
    /// The changes within `depth` dependency steps of `heads` (spec §17),
134
    /// nearest first; depth 1 is the heads themselves.
135
    pub fn shallow_changes(&self, heads: &[ChangeHash], depth: u32) -> Result<Vec<ChangeHash>> {
136
        let mut out = Vec::new();
137
        let mut seen: BTreeSet<ChangeHash> = BTreeSet::new();
138
        let mut layer: Vec<ChangeHash> = heads.to_vec();
139
        for _ in 0..depth.max(1) {
140
            let mut next = Vec::new();
141
            for h in layer {
142
                if !seen.insert(h) || !self.store.has(&h) {
143
                    continue;
144
                }
145
                let c = self.store.get_change(&h)?;
146
                next.extend(c.deps.iter().copied());
147
                out.push(h);
148
            }
149
            if next.is_empty() {
150
                break;
151
            }
152
            layer = next;
153
        }
154
        out.reverse();
155
        Ok(out)
156
    }
157
158
    fn shallow_path(&self) -> PathBuf {
159
        self.oxy.join("shallow")
160
    }
161
162
    /// The shallow boundary: dependencies this repository does not hold (spec §17).
163
    pub fn boundary(&self) -> BTreeSet<ChangeHash> {
75167672 Andy McCall 164
        fs::read_to_string(self.shallow_path())
165
            .map(|t| t.lines().filter_map(ObjectRef::from_hex).collect())
166
            .unwrap_or_default()
2863456a Andy McCall ↶ 167
    }
168
169
    pub fn is_shallow(&self) -> bool {
170
        !self.boundary().is_empty()
171
    }
172
173
    fn write_boundary(&self, boundary: &BTreeSet<ChangeHash>) -> Result<()> {
174
        if boundary.is_empty() {
175
            let _ = fs::remove_file(self.shallow_path());
176
            return Ok(());
177
        }
75167672 Andy McCall 178
        let text: String = boundary
179
            .iter()
180
            .map(|h| format!("{}\n", h.to_hex()))
181
            .collect();
2863456a Andy McCall ↶ 182
        write_atomic(&self.shallow_path(), text.as_bytes())
183
    }
184
185
    /// Recompute the boundary from what is stored: every dependency of a
186
    /// stored change that is not itself stored.
187
    fn refresh_boundary(&self, imported: &[ChangeHash]) -> Result<()> {
188
        let mut boundary = self.boundary();
189
        boundary.retain(|h| !self.store.has(h));
190
        for h in imported {
69816d68 Andy McCall ↶ 191
            for d in self.store.get_change_meta(h)?.deps {
2863456a Andy McCall ↶ 192
                if !self.store.has(&d) {
193
                    boundary.insert(d);
194
                }
195
            }
196
        }
197
        self.write_boundary(&boundary)
198
    }
199
200
    /// Fetch `depth` more levels of history below the shallow boundary.
201
    pub fn deepen(&self, remote_name: &str, depth: u32) -> Result<usize> {
202
        let boundary = self.boundary();
203
        if boundary.is_empty() {
204
            return Ok(0);
205
        }
206
        let remote = self.open_named_remote(remote_name)?;
207
        let wanted = remote.shallow(&boundary.iter().copied().collect::<Vec<_>>(), depth)?;
208
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
209
        let imported = self.import_bundle_shallow(&bundle, false)?;
210
        if self.config.max_blob.is_some() {
211
            self.register_missing_blobs(&imported, remote_name)?;
212
        }
213
        self.refresh_boundary(&imported)?;
214
        Ok(imported.len())
215
    }
216
98286406 Andy McCall ↶ 217
    /// `closure(want) \ closure(have)`, dependencies first (spec §16.2).
218
    pub fn negotiate(&self, have: &[ChangeHash], want: &[ChangeHash]) -> Result<Vec<ChangeHash>> {
219
        let have = self.closure_in_store(have)?;
2863456a Andy McCall ↶ 220
        // In a shallow repository the walk stops at the boundary, whose
221
        // changes the remote is assumed to hold.
222
        let boundary = self.boundary();
98286406 Andy McCall ↶ 223
        let mut out = Vec::new();
224
        let mut done: BTreeSet<ChangeHash> = have.clone();
2863456a Andy McCall ↶ 225
        done.extend(boundary.iter().copied());
98286406 Andy McCall ↶ 226
        // Iterative post-order DFS.
227
        let mut stack: Vec<(ChangeHash, bool)> = want.iter().rev().map(|h| (*h, false)).collect();
228
        while let Some((h, expanded)) = stack.pop() {
229
            if done.contains(&h) {
230
                continue;
231
            }
232
            if !self.store.has(&h) {
233
                return fail(format!("change {} is not in this repository", h.short(12)));
234
            }
235
            if expanded {
236
                done.insert(h);
237
                out.push(h);
238
                continue;
239
            }
240
            stack.push((h, true));
69816d68 Andy McCall ↶ 241
            for d in self.store.get_change_meta(&h)?.deps {
98286406 Andy McCall ↶ 242
                if !done.contains(&d) {
243
                    stack.push((d, false));
244
                }
245
            }
246
        }
247
        Ok(out)
248
    }
249
250
    /// Bundle changes (in the given dependency order) with their signatures,
251
    /// seals, identities, blobs, chunks.
252
    pub fn bundle_for(&self, changes: &[ChangeHash]) -> Result<Bundle> {
b3c5a59a Andy McCall ↶ 253
        self.bundle_for_filtered(changes, None)
254
    }
255
256
    /// Objects by reference for the `objects` endpoint; a blob brings its chunks.
257
    pub fn objects_for(&self, refs: &[ObjectRef]) -> Result<Vec<(ObjectType, Vec<u8>)>> {
258
        let mut out = Vec::new();
259
        for r in refs {
260
            let (ty, body) = match self.store.get(r) {
261
                Ok(x) => x,
262
                Err(StoreError::NotFound(_)) => continue,
263
                Err(e) => return Err(e.into()),
264
            };
265
            if ty == ObjectType::Blob {
266
                for c in Blob::decode(&body)?.chunks {
267
                    if let Ok((cty, cb)) = self.store.get(&c) {
268
                        out.push((cty, cb));
269
                    }
270
                }
271
            }
272
            out.push((ty, body));
273
        }
274
        Ok(out)
275
    }
276
277
    /// Like `bundle_for`, leaving out blobs larger than `max_blob` bytes
278
    /// (and their chunks) so the receiver fetches them lazily (spec §13.5).
75167672 Andy McCall 279
    pub fn bundle_for_filtered(
280
        &self,
281
        changes: &[ChangeHash],
282
        max_blob: Option<u64>,
283
    ) -> Result<Bundle> {
2c75672f Andy McCall ↶ 284
        self.bundle_of(changes, max_blob, false)
285
    }
286
287
    /// Like [`Repo::bundle_for_filtered`] for a fetch between repositories
288
    /// on one machine: changes as they are stored ([`Bundle::raw_changes`]),
289
    /// with their text blobs and chunks among the objects, so neither side
290
    /// decodes or encodes their text.
291
    pub fn bundle_raw_for(&self, changes: &[ChangeHash], max_blob: Option<u64>) -> Result<Bundle> {
292
        self.bundle_of(changes, max_blob, true)
293
    }
294
295
    fn bundle_of(
296
        &self,
297
        changes: &[ChangeHash],
298
        max_blob: Option<u64>,
299
        raw: bool,
300
    ) -> Result<Bundle> {
98286406 Andy McCall ↶ 301
        let mut bundle = Bundle::default();
302
        let mut objects: BTreeSet<ObjectRef> = BTreeSet::new();
303
        let mut seals: BTreeSet<ObjectRef> = BTreeSet::new();
304
        let add_object = |r: &ObjectRef, objects: &mut BTreeSet<ObjectRef>| {
305
            if !r.is_zero() && self.store.has(r) {
306
                objects.insert(*r);
307
            }
308
        };
309
        for h in changes {
2c75672f Andy McCall ↶ 310
            // Raw: the stored bytes, and a skeleton for the rest.
311
            let (c, encoded) = if raw {
312
                let bytes = self.store.get_typed(h, ObjectType::Change)?;
313
                let (skel, texts) = Change::decode_skeleton(&bytes, *h)?;
314
                for t in texts {
0f93f49c Andy McCall ↶ 315
                    if let crate::objects::TextRef::Blob(r, _, _) = t {
2c75672f Andy McCall ↶ 316
                        let blob = Blob::decode(&self.store.get_typed(&r, ObjectType::Blob)?)?;
317
                        objects.insert(r);
318
                        objects.extend(blob.chunks);
319
                    }
320
                }
321
                (skel, Some(bytes))
322
            } else {
323
                (self.store.get_change(h)?, None)
324
            };
98286406 Andy McCall ↶ 325
            let sigs = self.store.signatures(h)?;
326
            add_object(&c.author, &mut objects);
327
            for s in &sigs {
328
                add_object(&s.key, &mut objects);
329
            }
330
            for e in &c.edits {
331
                if let Edit::Replace { old, new, .. } = e {
332
                    for b in [old, new].into_iter().flatten() {
333
                        if self.store.has(b) {
75167672 Andy McCall 334
                            if let Ok(blob) =
335
                                Blob::decode(&self.store.get_typed(b, ObjectType::Blob)?)
336
                            {
b3c5a59a Andy McCall ↶ 337
                                if max_blob.is_some_and(|m| blob.length > m) {
338
                                    continue;
339
                                }
340
                                objects.insert(*b);
98286406 Andy McCall ↶ 341
                                objects.extend(blob.chunks.iter().copied());
342
                            }
343
                        }
344
                    }
345
                }
346
            }
347
            for s in self.store.seals_for(h)? {
348
                seals.insert(s);
2c75672f Andy McCall ↶ 349
            }
350
            match encoded {
351
                Some(bytes) => bundle.raw_changes.push((bytes, sigs)),
352
                None => {
353
                    bundle.changes.push((c, sigs));
354
                    bundle.hashes.push(*h);
355
                }
98286406 Andy McCall ↶ 356
            }
357
        }
358
        for r in seals {
359
            let attest = self.store.get_attest(&r)?;
360
            let sigs = self.store.signatures(&r)?;
361
            for s in &sigs {
362
                add_object(&s.key, &mut objects);
363
            }
364
            bundle.attests.push(SignedAttest { attest, sigs });
365
        }
366
        for r in objects {
367
            let (ty, body) = self.store.get(&r)?;
368
            bundle.objects.push((ty, body));
369
        }
370
        Ok(bundle)
371
    }
372
373
    /// Store a bundle's contents. With `strict`, every change must
374
    /// authenticate (signature or seal by its author or a delegate).
375
    pub fn import_bundle(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
2863456a Andy McCall ↶ 376
        self.import_bundle_inner(bundle, strict, false)
377
    }
378
379
    /// Like `import_bundle`, accepting changes whose dependencies are absent
380
    /// (they join the shallow boundary).
381
    pub fn import_bundle_shallow(&self, bundle: &Bundle, strict: bool) -> Result<Vec<ChangeHash>> {
382
        self.import_bundle_inner(bundle, strict, true)
383
    }
384
75167672 Andy McCall 385
    fn import_bundle_inner(
386
        &self,
387
        bundle: &Bundle,
388
        strict: bool,
389
        shallow: bool,
390
    ) -> Result<Vec<ChangeHash>> {
8f10a07a Andy McCall ↶ 391
        let batch = self.store.begin_batch()?;
392
        let result = self.import_bundle_batched(bundle, strict, shallow);
393
        batch.finish()?;
394
        result
395
    }
396
75167672 Andy McCall 397
    fn import_bundle_batched(
398
        &self,
399
        bundle: &Bundle,
400
        strict: bool,
401
        shallow: bool,
402
    ) -> Result<Vec<ChangeHash>> {
2c75672f Andy McCall ↶ 403
        for (ty, _) in &bundle.objects {
404
            if !matches!(
405
                ty,
75167672 Andy McCall 406
                ObjectType::Chunk
2c75672f Andy McCall ↶ 407
                    | ObjectType::Blob
408
                    | ObjectType::Identity
409
                    | ObjectType::State
410
                    | ObjectType::Checkpoint
411
            ) {
412
                return fail(format!("bundle may not carry {} objects", ty.name()));
98286406 Andy McCall ↶ 413
            }
414
        }
2c75672f Andy McCall ↶ 415
        // All at once: in a large batch they are compressed on every core.
416
        let objects: Vec<(ObjectType, &[u8])> = bundle
417
            .objects
418
            .iter()
419
            .map(|(ty, body)| (*ty, body.as_slice()))
420
            .collect();
421
        self.store.put_many(&objects)?;
98286406 Andy McCall ↶ 422
        for sa in &bundle.attests {
423
            let r = self.store.put_attest(&sa.attest)?;
424
            for sig in &sa.sigs {
425
                self.store.put_signature(&r, sig)?;
426
            }
427
            if let AttestBody::Seal { hashes } = &sa.attest.body {
428
                for h in hashes {
429
                    self.store.index_seal(h, &r)?;
430
                }
431
            }
432
        }
598009a7 Andy McCall ↶ 433
        // Each change's hash: from the bundle when its maker knew it, else
434
        // worked out once (for a change adding a whole tree, hashing is
435
        // chunking all its text).
436
        let hashes: Vec<ChangeHash> = if bundle.hashes.len() == bundle.changes.len() {
437
            bundle.hashes.clone()
438
        } else {
439
            bundle.changes.iter().map(|(c, _)| c.hash()).collect()
440
        };
2c75672f Andy McCall ↶ 441
        let raw_hashes: Vec<ChangeHash> = bundle
442
            .raw_changes
443
            .iter()
444
            .map(|(b, _)| hash_object(ObjectType::Change, b))
445
            .collect();
446
        let incoming: BTreeSet<ChangeHash> = hashes.iter().chain(&raw_hashes).copied().collect();
2863456a Andy McCall ↶ 447
        let boundary = self.boundary();
98286406 Andy McCall ↶ 448
        let mut imported = Vec::new();
2c75672f Andy McCall ↶ 449
        // Changes as stored: checked, then stored as they are, their text
450
        // blobs having come with the objects.
451
        for ((bytes, sigs), h) in bundle.raw_changes.iter().zip(raw_hashes) {
452
            let (skel, texts) = Change::decode_skeleton(bytes, h)?;
453
            for d in &skel.deps {
454
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
455
                {
456
                    return fail(format!(
457
                        "change {} depends on {}, which is neither stored nor in the bundle",
458
                        h.short(12),
459
                        d.short(12)
460
                    ));
461
                }
462
            }
463
            for t in texts {
0f93f49c Andy McCall ↶ 464
                if let crate::objects::TextRef::Blob(r, _, _) = t {
2c75672f Andy McCall ↶ 465
                    if !self.store.has(&r) {
466
                        return fail(format!(
467
                            "change {} came without its text blob {}",
468
                            h.short(12),
469
                            r.short(12)
470
                        ));
471
                    }
472
                }
473
            }
474
            self.store.put(ObjectType::Change, bytes)?;
475
            for sig in sigs {
476
                self.store.put_signature(&h, sig)?;
477
            }
478
            imported.push(h);
479
        }
598009a7 Andy McCall ↶ 480
        for ((c, sigs), h) in bundle.changes.iter().zip(hashes) {
98286406 Andy McCall ↶ 481
            for d in &c.deps {
75167672 Andy McCall 482
                if !self.store.has(d) && !incoming.contains(d) && !shallow && !boundary.contains(d)
483
                {
484
                    return fail(format!(
485
                        "change {} depends on {}, which is neither stored nor in the bundle",
486
                        h.short(12),
487
                        d.short(12)
488
                    ));
98286406 Andy McCall ↶ 489
                }
490
            }
598009a7 Andy McCall ↶ 491
            let stored = self.store.put_change(c)?;
492
            if stored != h {
493
                return fail(format!(
494
                    "change {} is not the change the bundle names",
495
                    h.short(12)
496
                ));
497
            }
98286406 Andy McCall ↶ 498
            for sig in sigs {
499
                self.store.put_signature(&h, sig)?;
500
            }
501
            imported.push(h);
502
        }
503
        if strict {
504
            for h in &imported {
505
                if !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. }) {
75167672 Andy McCall 506
                    return fail(format!(
507
                        "change {} is not authenticated by its author",
508
                        h.short(12)
509
                    ));
98286406 Andy McCall ↶ 510
                }
511
            }
512
        }
513
        Ok(imported)
514
    }
515
516
    /// Verify a reference attestation against an update it claims to describe.
517
    /// `allow_equal` lets a client re-read the attestation it already has; a
518
    /// server receiving a push requires a strictly greater serial.
84b9e9ac Andy McCall ↶ 519
    /// A reference attestation signed by a delegate of an identity the
520
    /// rule lists is authorized as that identity (spec §14.5): the identity
7ba155f2 Andy McCall ↶ 521
    /// named the delegate with the `refs` scope, still in force at `at_ms`
522
    /// (the attestation's wall time), and the policy names the identity.
523
    /// Revoked keys authorize nothing either way.
eae59556 Andy McCall ↶ 524
    pub(crate) fn delegate_authorized(
525
        &self,
526
        p: &crate::policy::Policy,
527
        signer: &KeyId,
528
        reference: &str,
7ba155f2 Andy McCall ↶ 529
        at_ms: u64,
eae59556 Andy McCall ↶ 530
    ) -> bool {
84b9e9ac Andy McCall ↶ 531
        if p.is_revoked(signer) {
532
            return false;
533
        }
eae59556 Andy McCall ↶ 534
        let Some(rule) = p.rule_for(reference) else {
535
            return false;
536
        };
84b9e9ac Andy McCall ↶ 537
        rule.keys.iter().any(|k| {
538
            !p.is_revoked(k)
539
                && p.identity(k)
540
                    .cloned()
541
                    .or_else(|| self.store.get_identity(k).ok())
7ba155f2 Andy McCall ↶ 542
                    .is_some_and(|id| id.delegates_to(signer, Scope::REFS, at_ms))
84b9e9ac Andy McCall ↶ 543
        })
544
    }
545
75167672 Andy McCall 546
    fn check_ref_attest(
547
        &self,
548
        sa: &SignedAttest,
549
        name: &str,
550
        old_state: &ObjectRef,
551
        new_state: &ObjectRef,
552
        last_serial: Option<u64>,
553
        allow_equal: bool,
554
    ) -> std::result::Result<u64, String> {
555
        let AttestBody::Ref {
556
            name: n,
557
            old_state: o,
558
            new_state: nw,
559
            serial,
560
        } = &sa.attest.body
561
        else {
98286406 Andy McCall ↶ 562
            return Err("attestation is not a ref attestation".into());
563
        };
564
        if n != name || o != old_state || nw != new_state {
565
            return Err("attestation does not describe this update".into());
566
        }
567
        if sa.attest.repo != self.id().map_err(|e| e.to_string())? {
568
            return Err("attestation is for a different repository".into());
569
        }
570
        if let Some(last) = last_serial {
571
            if *serial < last || (*serial == last && !allow_equal) {
75167672 Andy McCall 572
                return Err(format!(
573
                    "attestation serial {serial} is not greater than the last seen {last}"
574
                ));
98286406 Andy McCall ↶ 575
            }
576
        }
577
        let r = sa.attest.hash();
578
        let sig = sa.sigs.first().ok_or("attestation carries no signature")?;
75167672 Andy McCall 579
        let id = self
580
            .store
581
            .get_identity(&sig.key)
582
            .map_err(|_| format!("unknown key {}", sig.key.short(12)))?;
98286406 Andy McCall ↶ 583
        verify_signature(&id, sig, Domain::Attest, &r).map_err(|e| e.to_string())?;
584
        Ok(*serial)
585
    }
586
83e0677b Andy McCall ↶ 587
    /// Accept a push (spec §16.4). Without a trust policy every repository
98286406 Andy McCall ↶ 588
    /// is unverified, so unsigned changes and unattested updates are accepted;
83e0677b Andy McCall ↶ 589
    /// attestations that are present must still be valid. With a policy,
590
    /// every change and update is checked against it. A newer policy in the
591
    /// push is applied first when it is signed by the current roots.
75167672 Andy McCall 592
    pub fn receive_push(
593
        &self,
594
        bundle: Bundle,
595
        updates: Vec<RefUpdate>,
596
        policy: Option<SignedPolicy>,
597
        tags: Vec<crate::protocol::TagRef>,
598
    ) -> Result<Vec<RefResult>> {
119bbf50 Andy McCall ↶ 599
        Ok(self
600
            .receive_push_report(bundle, updates, policy, tags)?
601
            .results)
7aa2dc93 Andy McCall ↶ 602
    }
603
604
    /// `receive_push` with what a host wants to log: each accepted
605
    /// reference's old and new state and heads, and the changes this push
606
    /// stored (hub spec §6.12).
607
    pub fn receive_push_report(
608
        &self,
609
        bundle: Bundle,
610
        updates: Vec<RefUpdate>,
611
        policy: Option<SignedPolicy>,
612
        tags: Vec<crate::protocol::TagRef>,
613
    ) -> Result<PushReport> {
614
        let mut report = PushReport::default();
615
        let results = &mut report.results;
83e0677b Andy McCall ↶ 616
        if let Some(sp) = policy {
28fc23d7 Andy McCall ↶ 617
            match self.adopt_policy_chain(&bundle.policies, &sp, "push received") {
83e0677b Andy McCall ↶ 618
                Ok(()) => {
75167672 Andy McCall 619
                    results.push(RefResult {
620
                        name: "policy".into(),
621
                        ok: true,
622
                        reason: format!("serial {}", sp.policy.serial),
623
                    });
83e0677b Andy McCall ↶ 624
                }
625
                Err(e) => {
75167672 Andy McCall 626
                    results.push(RefResult {
627
                        name: "policy".into(),
628
                        ok: false,
629
                        reason: e,
630
                    });
83e0677b Andy McCall ↶ 631
                    for u in updates {
75167672 Andy McCall 632
                        results.push(RefResult {
633
                            name: u.name,
634
                            ok: false,
635
                            reason: "policy update was rejected".into(),
636
                        });
83e0677b Andy McCall ↶ 637
                    }
7aa2dc93 Andy McCall ↶ 638
                    return Ok(report);
83e0677b Andy McCall ↶ 639
                }
640
            }
641
        }
642
        let policy = self.current_policy()?.map(|(_, sp)| sp.policy);
cb8b8082 Andy McCall ↶ 643
        // A push of objects alone (one batch of a long history, oxygen#95)
644
        // names no reference: its outcome is reported as `objects`.
645
        let objects_only = updates.is_empty() && tags.is_empty();
7aa2dc93 Andy McCall ↶ 646
        match self.import_bundle(&bundle, policy.is_some()) {
cb8b8082 Andy McCall ↶ 647
            Ok(imported) => {
648
                if objects_only {
649
                    results.push(RefResult {
650
                        name: OBJECTS_RESULT.into(),
651
                        ok: true,
652
                        reason: format!("{} changes stored", imported.len()),
653
                    });
654
                }
655
                report.imported = imported;
656
            }
7aa2dc93 Andy McCall ↶ 657
            Err(e) => {
cb8b8082 Andy McCall ↶ 658
                if objects_only {
659
                    results.push(RefResult {
660
                        name: OBJECTS_RESULT.into(),
661
                        ok: false,
662
                        reason: e.to_string(),
663
                    });
664
                }
7aa2dc93 Andy McCall ↶ 665
                for u in updates {
666
                    results.push(RefResult {
667
                        name: u.name,
668
                        ok: false,
669
                        reason: e.to_string(),
670
                    });
671
                }
672
                return Ok(report);
83e0677b Andy McCall ↶ 673
            }
674
        }
98286406 Andy McCall ↶ 675
        let (op_ref, op) = self.head_op()?;
676
        let mut view = op.view.clone();
677
        let mut names = Vec::new();
678
        for u in updates {
83e0677b Andy McCall ↶ 679
            let outcome = self.apply_update(&mut view, &u, policy.as_ref());
98286406 Andy McCall ↶ 680
            let (ok, reason) = match outcome {
681
                Ok(()) => (true, String::new()),
682
                Err(e) => (false, e),
683
            };
684
            if ok {
685
                names.push(u.name.clone());
119bbf50 Andy McCall ↶ 686
                let heads = self
687
                    .store
688
                    .get_state(&u.new_state)
689
                    .map(|s| s.heads)
690
                    .unwrap_or_default();
691
                report.updated.push(RefUpdated {
692
                    name: u.name.clone(),
693
                    old_state: u.old_state,
694
                    new_state: u.new_state,
695
                    heads,
696
                });
98286406 Andy McCall ↶ 697
            }
75167672 Andy McCall 698
            results.push(RefResult {
699
                name: u.name,
700
                ok,
701
                reason,
702
            });
98286406 Andy McCall ↶ 703
        }
132b884b Andy McCall ↶ 704
        for t in &tags {
705
            let name = format!("tags/{}", t.name);
b2ef93bb Andy McCall ↶ 706
            let new = !view.tags.contains_key(&t.name);
132b884b Andy McCall ↶ 707
            match self.adopt_tag(&mut view, t, policy.as_ref()) {
708
                Ok(()) => {
b2ef93bb Andy McCall ↶ 709
                    // A tag new here is an update too, so a hub can start
710
                    // its pipeline's tag jobs (oxygenflow#24); one it
711
                    // already had, sent again, is not.
712
                    if new {
713
                        report.updated.push(RefUpdated {
714
                            name: name.clone(),
715
                            old_state: ObjectRef::ZERO,
716
                            new_state: t.state,
717
                            heads: t.heads.clone(),
718
                        });
719
                    }
132b884b Andy McCall ↶ 720
                    names.push(name.clone());
75167672 Andy McCall 721
                    results.push(RefResult {
722
                        name,
723
                        ok: true,
724
                        reason: String::new(),
725
                    });
132b884b Andy McCall ↶ 726
                }
75167672 Andy McCall 727
                Err(e) => results.push(RefResult {
728
                    name,
729
                    ok: false,
730
                    reason: e,
731
                }),
132b884b Andy McCall ↶ 732
            }
733
        }
98286406 Andy McCall ↶ 734
        if !names.is_empty() {
75167672 Andy McCall 735
            self.record_op(
736
                &[op_ref],
737
                &format!("push received: {}", names.join(" ")),
738
                view,
739
            )?;
98286406 Andy McCall ↶ 740
        }
7aa2dc93 Andy McCall ↶ 741
        Ok(report)
98286406 Andy McCall ↶ 742
    }
743
be451356 Andy McCall ↶ 744
    /// Check an update's attestation against the latest one for its
745
    /// reference and store it as the new latest. Failures say what was
746
    /// being done, for which reference, so a refused push can be diagnosed
747
    /// from its reason alone.
748
    fn record_update_attest(
749
        &self,
750
        u: &RefUpdate,
751
        sa: &SignedAttest,
752
    ) -> std::result::Result<(), String> {
753
        let name = &u.name;
754
        let last = self
755
            .latest_ref_attest(name)
756
            .map_err(|e| format!("reading the last attestation of {name:?}: {e}"))?
757
            .and_then(|(_, a)| match a.attest.body {
758
                AttestBody::Ref { serial, .. } => Some(serial),
759
                _ => None,
760
            });
761
        self.check_ref_attest(sa, name, &u.old_state, &u.new_state, last, false)?;
762
        let store = |e: &dyn std::fmt::Display| format!("storing the attestation of {name:?}: {e}");
763
        let r = self.store.put_attest(&sa.attest).map_err(|e| store(&e))?;
764
        for sig in &sa.sigs {
765
            self.store.put_signature(&r, sig).map_err(|e| store(&e))?;
766
        }
767
        self.set_ref_attest(name, &r).map_err(|e| store(&e))
768
    }
769
f8c69576 Andy McCall ↶ 770
    /// A deletion (spec §16.4): `new_state` is zero. The bookmark must exist
8c30d814 Andy McCall ↶ 771
    /// at `old_state`, is never the bookmark a non-bare repository has
772
    /// checked out (a bare one's default is its host's to protect, see
773
    /// `oxy_server::Backend::default_bookmark`), and under a policy needs
774
    /// an attestation by a key that may update it.
f8c69576 Andy McCall ↶ 775
    /// The deletion's attestation stays the bookmark's latest, so an older
776
    /// one cannot be replayed to bring it back.
777
    fn apply_deletion(
778
        &self,
779
        view: &mut View,
780
        u: &RefUpdate,
781
        policy: Option<&crate::policy::Policy>,
782
    ) -> std::result::Result<(), String> {
783
        let Some(current) = view.bookmarks.get(&u.name).copied() else {
784
            return Err(format!("no bookmark {:?} to delete", u.name));
785
        };
786
        if current != u.old_state {
787
            return Err("stale: the remote bookmark has moved; pull first".into());
788
        }
8c30d814 Andy McCall ↶ 789
        if !self.is_bare() && u.name == self.config.bookmark {
f8c69576 Andy McCall ↶ 790
            return Err(format!(
8c30d814 Andy McCall ↶ 791
                "{:?} is this repository's default bookmark (checked out there) and cannot be deleted",
f8c69576 Andy McCall ↶ 792
                u.name
793
            ));
794
        }
795
        if let Some(p) = policy {
796
            let Some(sa) = &u.attestation else {
797
                return Err(format!(
798
                    "deleting {:?} requires a signed reference attestation under this repository's policy",
799
                    u.name
800
                ));
801
            };
802
            let signer = sa
803
                .sigs
804
                .first()
805
                .map(|s| s.key)
806
                .ok_or("attestation carries no signature")?;
7ba155f2 Andy McCall ↶ 807
            if !p.authorizes(&signer, &u.name)
808
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
809
            {
f8c69576 Andy McCall ↶ 810
                return Err(format!(
811
                    "key {} may not delete {:?} under this repository's policy",
812
                    signer.short(12),
813
                    u.name
814
                ));
815
            }
816
        }
817
        if let Some(sa) = &u.attestation {
be451356 Andy McCall ↶ 818
            self.record_update_attest(u, sa)?;
f8c69576 Andy McCall ↶ 819
        }
820
        view.bookmarks.remove(&u.name);
821
        Ok(())
822
    }
823
75167672 Andy McCall 824
    fn apply_update(
825
        &self,
826
        view: &mut View,
827
        u: &RefUpdate,
828
        policy: Option<&crate::policy::Policy>,
829
    ) -> std::result::Result<(), String> {
83e0677b Andy McCall ↶ 830
        if u.name == "policy" {
75167672 Andy McCall 831
            return Err(
832
                "the policy reference is updated by sending a policy, not a bookmark update".into(),
833
            );
83e0677b Andy McCall ↶ 834
        }
75167672 Andy McCall 835
        let empty = self
836
            .store
837
            .put_state(&StateObject::new(vec![]))
838
            .map_err(|e| e.to_string())?;
f8c69576 Andy McCall ↶ 839
        if u.new_state.is_zero() {
840
            return self.apply_deletion(view, u, policy);
841
        }
98286406 Andy McCall ↶ 842
        let current = view.bookmarks.get(&u.name).copied().unwrap_or(empty);
843
        if current != u.old_state {
844
            return Err("stale: the remote bookmark has moved; pull first".into());
845
        }
75167672 Andy McCall 846
        let new_state = self
847
            .store
848
            .get_state(&u.new_state)
849
            .map_err(|_| "new state object is missing".to_string())?;
98286406 Andy McCall ↶ 850
        for h in &new_state.heads {
851
            if !self.store.has(h) {
852
                return Err(format!("head {} is missing", h.short(12)));
853
            }
854
        }
855
        if !u.force {
75167672 Andy McCall 856
            let old_heads = self
857
                .store
858
                .get_state(&current)
859
                .map_err(|e| e.to_string())?
860
                .heads;
861
            let closure = self
862
                .closure_in_store(&new_state.heads)
863
                .map_err(|e| e.to_string())?;
98286406 Andy McCall ↶ 864
            if let Some(h) = old_heads.iter().find(|h| !closure.contains(h)) {
75167672 Andy McCall 865
                return Err(format!(
866
                    "not a fast-forward: current head {} would be dropped (use --force)",
867
                    h.short(12)
868
                ));
98286406 Andy McCall ↶ 869
            }
870
        }
83e0677b Andy McCall ↶ 871
        if let Some(p) = policy {
872
            let Some(sa) = &u.attestation else {
75167672 Andy McCall 873
                return Err(format!(
874
                    "{:?} requires a signed reference attestation under this repository's policy",
875
                    u.name
876
                ));
83e0677b Andy McCall ↶ 877
            };
75167672 Andy McCall 878
            let signer = sa
879
                .sigs
880
                .first()
881
                .map(|s| s.key)
882
                .ok_or("attestation carries no signature")?;
7ba155f2 Andy McCall ↶ 883
            if !p.authorizes(&signer, &u.name)
884
                && !self.delegate_authorized(p, &signer, &u.name, sa.attest.hlc.wall_ms)
885
            {
75167672 Andy McCall 886
                return Err(format!(
887
                    "key {} may not update {:?} under this repository's policy",
888
                    signer.short(12),
889
                    u.name
890
                ));
83e0677b Andy McCall ↶ 891
            }
75167672 Andy McCall 892
            let old_heads = self
893
                .store
894
                .get_state(&current)
895
                .map_err(|e| e.to_string())?
896
                .heads;
83e0677b Andy McCall ↶ 897
            self.state_allowed(&old_heads, &new_state.heads, p, &u.name)?;
898
        }
98286406 Andy McCall ↶ 899
        if let Some(sa) = &u.attestation {
be451356 Andy McCall ↶ 900
            self.record_update_attest(u, sa)?;
98286406 Andy McCall ↶ 901
        }
902
        view.bookmarks.insert(u.name.clone(), u.new_state);
903
        Ok(())
904
    }
905
906
    // ------------------------------------------------------------ client side
907
908
    fn remote_url(&self, name: &str) -> Result<String> {
75167672 Andy McCall 909
        self.config.remotes.get(name).cloned().ok_or_else(|| {
42ccf504 Andy McCall ↶ 910
            let names: Vec<&str> = self.config.remotes.keys().map(String::as_str).collect();
911
            RepoError::Msg(match names.as_slice() {
912
                [] => format!("no remote named {name:?}; add one with `oxy remote add`"),
913
                _ if name == "origin" && names.len() > 1 && self.config.default_remote.is_none() => format!(
914
                    "this repository has no remote named origin, and several others ({}): name one (`oxy pull {}`), or make one the default with `oxy config core.remote {}`",
915
                    names.join(", "),
916
                    names[0],
917
                    names[0]
918
                ),
919
                _ => format!(
920
                    "no remote named {name:?}; this repository has {}",
921
                    names.join(", ")
922
                ),
923
            })
75167672 Andy McCall 924
        })
98286406 Andy McCall ↶ 925
    }
926
75167672 Andy McCall 927
    /// Refuse a remote that is another repository. An **unbound** remote
928
    /// (id all zero: a hosted repository nobody has pushed to) is accepted
929
    /// for pushes, which bind it to this repository's id (spec §16.1).
05e71ed6 Andy McCall ↶ 930
    fn check_remote_id(
931
        &self,
932
        remote: &dyn crate::protocol::Remote,
933
        remote_name: &str,
934
        allow_unbound: bool,
935
    ) -> Result<()> {
75167672 Andy McCall 936
        let theirs = remote.repo_id()?;
937
        if theirs == self.id()? {
938
            return Ok(());
939
        }
940
        if theirs == crate::protocol::UNBOUND_ID {
941
            if allow_unbound {
942
                return Ok(());
943
            }
05e71ed6 Andy McCall ↶ 944
            return fail(format!(
945
                "remote {remote_name:?} is empty and unbound: push to it first"
946
            ));
75167672 Andy McCall 947
        }
05e71ed6 Andy McCall ↶ 948
        fail(format!(
3e5772cc Andy McCall ↶ 949
            "remote {remote_name:?} is a different repository (repository IDs differ); check its URL with `oxy remote list`"
05e71ed6 Andy McCall ↶ 950
        ))
75167672 Andy McCall 951
    }
952
ff1f62fe Andy McCall ↶ 953
    /// Credentials and trust for a remote: `remote.<name>.token` and
954
    /// `remote.<name>.ca`, else the defaults for its URL
955
    /// ([`Repo::fill_credentials`]).
3e5772cc Andy McCall ↶ 956
    pub(crate) fn remote_options(&self, name: &str) -> RemoteOptions {
ff1f62fe Andy McCall ↶ 957
        let url = self.config.remotes.get(name).cloned().unwrap_or_default();
958
        let mut options = RemoteOptions {
75167672 Andy McCall 959
            repo_id: self.id().ok(),
ff1f62fe Andy McCall ↶ 960
            token: self.config.remote_tokens.get(name).cloned(),
961
            ca: self.config.remote_cas.get(name).map(PathBuf::from),
9f9e72b9 Andy McCall ↶ 962
            cache_dir: Some(self.oxy.join("remotes").join(name).join("strata")),
ff1f62fe Andy McCall ↶ 963
        };
964
        self.fill_credentials(&url, &mut options);
965
        options
966
    }
967
968
    /// The user's credential store (`credentials.toml` beside the user
969
    /// configuration file).
970
    pub fn credentials(&self) -> crate::credentials::Credentials {
971
        crate::credentials::Credentials::at(
972
            self.user_config
973
                .parent()
974
                .map(Path::to_path_buf)
975
                .unwrap_or_else(default_home),
976
        )
977
    }
978
979
    /// Fill in what `options` lacks for `url`: `$OXY_TOKEN` and `$OXY_CA`,
980
    /// then the user's credential store for its hub, then a remote on the
981
    /// same hub in an enclosing checkout (a subrepo borrows its parent's).
982
    fn fill_credentials(&self, url: &str, options: &mut RemoteOptions) {
983
        if options.token.is_some() && options.ca.is_some() {
984
            return;
985
        }
986
        let stored = self.credentials().options_for(url);
987
        options.token = options.token.take().or(stored.token);
988
        options.ca = options.ca.take().or(stored.ca);
989
        if options.token.is_some() && options.ca.is_some() {
990
            return;
2b5ee371 Andy McCall ↶ 991
        }
ff1f62fe Andy McCall ↶ 992
        let Some(hub) = crate::credentials::hub_of(url) else {
993
            return;
994
        };
995
        let mut at = self.root.parent();
996
        while let Some(dir) = at {
997
            let Ok(cfg) = read_config_file(&dir.join(OXY_DIR).join("config")) else {
998
                break;
999
            };
1000
            for (key, remote_url) in &cfg {
1001
                let Some(name) = key
1002
                    .strip_prefix("remote.")
1003
                    .and_then(|k| k.strip_suffix(".url"))
1004
                else {
1005
                    continue;
1006
                };
1007
                if crate::credentials::hub_of(remote_url).as_deref() != Some(hub.as_str()) {
1008
                    continue;
1009
                }
1010
                if options.token.is_none() {
1011
                    options.token = cfg.get(&format!("remote.{name}.token")).cloned();
1012
                }
1013
                if options.ca.is_none() {
1014
                    options.ca = cfg.get(&format!("remote.{name}.ca")).map(PathBuf::from);
1015
                }
1016
            }
1017
            if options.token.is_some() && options.ca.is_some() {
1018
                return;
1019
            }
1020
            at = dir.parent();
1021
        }
98286406 Andy McCall ↶ 1022
    }
1023
d82e4409 Andy McCall ↶ 1024
    /// Push seal attestations on their own (hub spec §7.4): a bundle with
1025
    /// no changes and no reference updates, which the receiver stores.
1026
    pub fn push_seals(&self, remote_name: &str, seals: &[ObjectRef]) -> Result<()> {
1027
        let remote = self.open_named_remote(remote_name)?;
1028
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
1029
        let mut bundle = Bundle::default();
1030
        for r in seals {
1031
            let attest = self.store.get_attest(r)?;
1032
            let sigs = self.store.signatures(r)?;
4213c41d Andy McCall ↶ 1033
            bundle
1034
                .attests
1035
                .push(crate::protocol::SignedAttest { attest, sigs });
d82e4409 Andy McCall ↶ 1036
        }
1037
        let results = remote.push(bundle, vec![], None, vec![])?;
1038
        if let Some(r) = results.iter().find(|r| !r.ok) {
1039
            return fail(format!("{}: {}", r.name, r.reason));
1040
        }
1041
        Ok(())
1042
    }
1043
1044
    /// The remote whose URL starts with `base` (a hub), if configured.
1045
    pub fn remote_for_url(&self, base: &str) -> Option<String> {
1046
        let base = base.trim_end_matches('/');
4213c41d Andy McCall ↶ 1047
        self.config
1048
            .remotes
1049
            .iter()
1050
            .find(|(_, url)| url.trim_end_matches('/') == base)
1051
            .map(|(name, _)| name.clone())
d82e4409 Andy McCall ↶ 1052
    }
1053
1054
    /// Open a remote by name or, failing that, by URL with the default
ff1f62fe Andy McCall ↶ 1055
    /// credentials (see [`Repo::credentials_for`]).
d82e4409 Andy McCall ↶ 1056
    pub fn open_remote_at(&self, url: &str) -> Result<(String, Box<dyn crate::protocol::Remote>)> {
1057
        if let Some(name) = self.remote_for_url(url) {
1058
            return Ok((name.clone(), self.open_named_remote(&name)?));
1059
        }
1060
        let options = RemoteOptions {
1061
            repo_id: self.id().ok(),
ff1f62fe Andy McCall ↶ 1062
            ..self.credentials_for(url)
d82e4409 Andy McCall ↶ 1063
        };
1064
        Ok((url.to_string(), open_remote(url, &options)?))
1065
    }
1066
1067
    /// Credentials for a URL: those of the configured remote with that
1068
    /// URL, else the environment's.
1069
    pub fn options_for_url(&self, url: &str) -> RemoteOptions {
1070
        match self.remote_for_url(url) {
1071
            Some(name) => self.remote_options(&name),
1072
            None => RemoteOptions {
1073
                repo_id: self.id().ok(),
ff1f62fe Andy McCall ↶ 1074
                ..self.credentials_for(url)
d82e4409 Andy McCall ↶ 1075
            },
1076
        }
1077
    }
1078
98286406 Andy McCall ↶ 1079
    fn open_named_remote(&self, name: &str) -> Result<Box<dyn crate::protocol::Remote>> {
2b5ee371 Andy McCall ↶ 1080
        open_remote(&self.remote_url(name)?, &self.remote_options(name))
98286406 Andy McCall ↶ 1081
    }
1082
1083
    fn serial_path(&self, remote: &str, bookmark: &str) -> PathBuf {
75167672 Andy McCall 1084
        self.oxy
1085
            .join("remotes")
1086
            .join(remote)
1087
            .join(format!("{bookmark}.serial"))
98286406 Andy McCall ↶ 1088
    }
1089
1090
    fn last_seen_serial(&self, remote: &str, bookmark: &str) -> Option<u64> {
75167672 Andy McCall 1091
        fs::read_to_string(self.serial_path(remote, bookmark))
1092
            .ok()
1093
            .and_then(|s| s.trim().parse().ok())
98286406 Andy McCall ↶ 1094
    }
1095
1096
    fn record_serial(&self, remote: &str, bookmark: &str, serial: u64) -> Result<()> {
1097
        let p = self.serial_path(remote, bookmark);
1098
        fs::create_dir_all(p.parent().unwrap())?;
1099
        write_atomic(&p, serial.to_string().as_bytes())
1100
    }
1101
83e0677b Andy McCall ↶ 1102
    fn policy_serial_path(&self, remote: &str) -> PathBuf {
1103
        self.oxy.join("remotes").join(remote).join("policy.serial")
1104
    }
1105
1106
    /// The highest policy serial `remote` has ever presented.
1107
    fn remote_policy_serial(&self, remote: &str) -> Option<u64> {
75167672 Andy McCall 1108
        fs::read_to_string(self.policy_serial_path(remote))
1109
            .ok()
1110
            .and_then(|s| s.trim().parse().ok())
83e0677b Andy McCall ↶ 1111
    }
1112
1113
    fn record_policy_serial(&self, remote: &str, serial: u64) -> Result<()> {
1114
        let p = self.policy_serial_path(remote);
1115
        fs::create_dir_all(p.parent().unwrap())?;
1116
        write_atomic(&p, serial.to_string().as_bytes())
1117
    }
1118
b3c5a59a Andy McCall ↶ 1119
    fn lazy_dir(&self) -> PathBuf {
1120
        self.oxy.join("lazy")
1121
    }
1122
1123
    /// Remember that `blob` was withheld by `remote` (spec §13.5).
1124
    fn register_lazy(&self, blob: &ObjectRef, remote: &str) -> Result<()> {
1125
        fs::create_dir_all(self.lazy_dir())?;
1126
        write_atomic(&self.lazy_dir().join(blob.to_hex()), remote.as_bytes())
1127
    }
1128
1129
    /// Which remote promised an absent blob, if any.
1130
    pub fn lazy_remote(&self, blob: &ObjectRef) -> Option<String> {
75167672 Andy McCall 1131
        fs::read_to_string(self.lazy_dir().join(blob.to_hex()))
1132
            .ok()
1133
            .map(|s| s.trim().to_string())
b3c5a59a Andy McCall ↶ 1134
    }
1135
1136
    /// Fetch an absent blob (and its chunks) from the remote that promised it.
1137
    pub(crate) fn fetch_lazy_blob(&self, blob: &ObjectRef) -> Result<()> {
1138
        let Some(remote_name) = self.lazy_remote(blob) else {
1139
            return Err(RepoError::Store(StoreError::NotFound(*blob)));
1140
        };
1141
        let remote = self.open_named_remote(&remote_name)?;
1142
        let objects = remote.objects(&[*blob])?;
1143
        for (ty, body) in objects {
1144
            if matches!(ty, ObjectType::Blob | ObjectType::Chunk) {
1145
                self.store.put(ty, &body)?;
1146
            }
1147
        }
1148
        if !self.store.has(blob) {
75167672 Andy McCall 1149
            return fail(format!(
1150
                "{remote_name} did not send blob {}",
1151
                blob.short(12)
1152
            ));
b3c5a59a Andy McCall ↶ 1153
        }
1154
        let _ = fs::remove_file(self.lazy_dir().join(blob.to_hex()));
1155
        Ok(())
1156
    }
1157
1158
    /// After importing from `remote`, record every blob the changes reference
1159
    /// that the store lacks as lazily available from that remote.
1160
    fn register_missing_blobs(&self, changes: &[ChangeHash], remote: &str) -> Result<usize> {
1161
        let mut n = 0;
1162
        for h in changes {
1163
            let c = self.store.get_change(h)?;
1164
            for e in &c.edits {
1165
                if let Edit::Replace { old, new, .. } = e {
1166
                    for b in [old, new].into_iter().flatten() {
1167
                        if !self.store.has(b) {
1168
                            self.register_lazy(b, remote)?;
1169
                            n += 1;
1170
                        }
1171
                    }
1172
                }
1173
            }
1174
        }
1175
        Ok(n)
1176
    }
1177
98286406 Andy McCall ↶ 1178
    /// Every head this repository knows: bookmarks, remote tracking, working copy.
d82e4409 Andy McCall ↶ 1179
    pub fn known_heads(&self, view: &View) -> Result<Vec<ChangeHash>> {
98286406 Andy McCall ↶ 1180
        let mut have: BTreeSet<ChangeHash> = BTreeSet::new();
75167672 Andy McCall 1181
        for st in view
1182
            .bookmarks
1183
            .values()
1184
            .chain(view.remotes.values().flat_map(|b| b.values()))
1185
        {
98286406 Andy McCall ↶ 1186
            if let Ok(s) = self.store.get_state(st) {
1187
                have.extend(s.heads);
1188
            }
1189
        }
1190
        have.extend(view.workspaces.values().copied());
1191
        Ok(have.into_iter().collect())
1192
    }
1193
1194
    /// Fetch every bookmark of a remote into `remotes/<name>/bookmarks/*` (spec §10.2).
83e0677b Andy McCall ↶ 1195
    pub fn fetch(&self, remote_name: &str) -> Result<FetchReport> {
98286406 Andy McCall ↶ 1196
        let remote = self.open_named_remote(remote_name)?;
75167672 Andy McCall 1197
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
83e0677b Andy McCall ↶ 1198
        let resp = remote.refs()?;
1199
        // Trust policy (spec §14.5). Adopt the remote's policy when it is newer
1200
        // and signed by roots we trust, or on first contact. A remote that
1201
        // once presented a policy may never present none or an older one:
1202
        // that is a downgrade. A remote that never presented one is
1203
        // unverified, and this fetch is checked only as far as possible.
1204
        let local_policy = self.current_policy()?.map(|(_, sp)| sp.policy);
1205
        let seen = self.remote_policy_serial(remote_name);
1206
        let mut unverified = false;
1207
        match &resp.policy {
1208
            Some(sp) => {
1209
                if seen.is_some_and(|s| sp.policy.serial < s) {
1210
                    return fail(format!("{remote_name} presents policy serial {} but presented {} before: refusing the downgrade", sp.policy.serial, seen.unwrap()));
1211
                }
1212
                match &local_policy {
1213
                    Some(l) if sp.policy.serial < l.serial => {}
1214
                    Some(l) if sp.policy.serial == l.serial => {
1215
                        if sp.policy.hash() != l.hash() {
75167672 Andy McCall 1216
                            return fail(format!(
1217
                                "{remote_name} presents a different policy with the same serial {}",
1218
                                l.serial
1219
                            ));
83e0677b Andy McCall ↶ 1220
                        }
1221
                    }
28fc23d7 Andy McCall ↶ 1222
                    _ => {
75167672 Andy McCall 1223
                        self.adopt_policy_chain(
1224
                            &resp.history,
1225
                            sp,
1226
                            &format!("oxy fetch {remote_name}"),
1227
                        )
1228
                        .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
83e0677b Andy McCall ↶ 1229
                    }
1230
                }
1231
                self.record_policy_serial(remote_name, sp.policy.serial)?;
1232
            }
1233
            None => {
1234
                if seen.is_some() {
1235
                    return fail(format!("{remote_name} presented a policy before but has none now: refusing the downgrade"));
1236
                }
1237
                unverified = true;
1238
            }
1239
        }
75167672 Andy McCall 1240
        let policy = if unverified {
1241
            None
1242
        } else {
1243
            self.current_policy()?.map(|(_, sp)| sp.policy)
1244
        };
98286406 Andy McCall ↶ 1245
        let (op_ref, op) = self.head_op()?;
1246
        let mut view = op.view.clone();
1247
        let have = self.known_heads(&view)?;
1248
        let mut report = Vec::new();
b3c5a59a Andy McCall ↶ 1249
        let max_blob = self.config.max_blob;
83e0677b Andy McCall ↶ 1250
        for r in resp.refs {
091fef80 Andy McCall ↶ 1251
            let needed = {
1252
                let _t = crate::timing::phase("fetch: negotiate");
1253
                remote.negotiate(&have, &r.heads)?
1254
            };
1255
            let bundle = {
1256
                let _t = crate::timing::phase("fetch: bundle");
1257
                remote.fetch(&needed, max_blob)?
1258
            };
83e0677b Andy McCall ↶ 1259
            // Changes are not individually re-verified here: the bookmark's
1260
            // attestation (checked below) binds its whole state, and the
1261
            // receiver of the push verified the added changes at that time.
091fef80 Andy McCall ↶ 1262
            let imported = {
1263
                let _t = crate::timing::phase("fetch: import");
1264
                self.import_bundle(&bundle, false)?
1265
            };
b3c5a59a Andy McCall ↶ 1266
            if max_blob.is_some() {
1267
                self.register_missing_blobs(&imported, remote_name)?;
1268
            }
98286406 Andy McCall ↶ 1269
            for h in &r.heads {
1270
                if !self.store.has(h) {
1271
                    return fail(format!("remote did not send head {}", h.short(12)));
1272
                }
1273
            }
1274
            let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1275
            if state != r.state {
75167672 Andy McCall 1276
                return fail(format!(
1277
                    "remote state {} does not match its heads",
1278
                    r.state.short(12)
1279
                ));
98286406 Andy McCall ↶ 1280
            }
83e0677b Andy McCall ↶ 1281
            if let Some(p) = &policy {
1282
                let Some(sa) = &r.attestation else {
75167672 Andy McCall 1283
                    return fail(format!(
1284
                        "{remote_name}/{} has no attestation, which its policy requires",
1285
                        r.name
1286
                    ));
83e0677b Andy McCall ↶ 1287
                };
75167672 Andy McCall 1288
                let signer = sa
1289
                    .sigs
1290
                    .first()
1291
                    .map(|s| s.key)
1292
                    .ok_or_else(|| RepoError::Msg("attestation carries no signature".into()))?;
7ba155f2 Andy McCall ↶ 1293
                if !p.authorizes(&signer, &r.name)
1294
                    && !self.delegate_authorized(p, &signer, &r.name, sa.attest.hlc.wall_ms)
3526d339 Andy McCall ↶ 1295
                {
75167672 Andy McCall 1296
                    return fail(format!(
3e5772cc Andy McCall ↶ 1297
                        "{remote_name}/{}: attested by {}, which the policy does not authorize for this bookmark; a policy owner can grant it with `oxy policy grant`",
75167672 Andy McCall 1298
                        r.name,
1299
                        signer.short(12)
1300
                    ));
83e0677b Andy McCall ↶ 1301
                }
1302
            }
98286406 Andy McCall ↶ 1303
            if let Some(sa) = &r.attestation {
75167672 Andy McCall 1304
                let AttestBody::Ref {
1305
                    old_state,
1306
                    new_state,
1307
                    ..
1308
                } = &sa.attest.body
1309
                else {
98286406 Andy McCall ↶ 1310
                    return fail("remote sent a non-ref attestation for a bookmark");
1311
                };
1312
                let (old_state, new_state) = (*old_state, *new_state);
1313
                let serial = self
75167672 Andy McCall 1314
                    .check_ref_attest(
1315
                        sa,
1316
                        &r.name,
1317
                        &old_state,
1318
                        &new_state,
1319
                        self.last_seen_serial(remote_name, &r.name),
1320
                        true,
1321
                    )
1322
                    .map_err(|e| {
1323
                        RepoError::Msg(format!("attestation for {}/{}: {e}", remote_name, r.name))
1324
                    })?;
98286406 Andy McCall ↶ 1325
                if new_state != r.state {
75167672 Andy McCall 1326
                    return fail(format!(
1327
                        "attestation for {}/{} does not cover its current state",
1328
                        remote_name, r.name
1329
                    ));
98286406 Andy McCall ↶ 1330
                }
1331
                let ar = self.store.put_attest(&sa.attest)?;
1332
                for sig in &sa.sigs {
1333
                    self.store.put_signature(&ar, sig)?;
1334
                }
1335
                self.record_serial(remote_name, &r.name, serial)?;
1336
            }
75167672 Andy McCall 1337
            view.remotes
1338
                .entry(remote_name.to_string())
1339
                .or_default()
1340
                .insert(r.name.clone(), state);
98286406 Andy McCall ↶ 1341
            report.push((r.name, r.heads, imported.len()));
1342
        }
132b884b Andy McCall ↶ 1343
        let mut new_tags = 0;
1344
        for t in &resp.tags {
1345
            if view.tags.contains_key(&t.name) {
1346
                continue;
1347
            }
1348
            // The tag's changes must be here: fetch them if the bookmarks did not bring them.
75167672 Andy McCall 1349
            let missing: Vec<ChangeHash> = t
1350
                .heads
1351
                .iter()
1352
                .filter(|h| !self.store.has(h))
1353
                .copied()
1354
                .collect();
132b884b Andy McCall ↶ 1355
            if !missing.is_empty() {
1356
                let needed = remote.negotiate(&self.known_heads(&view)?, &missing)?;
1357
                let bundle = remote.fetch(&needed, max_blob)?;
1358
                self.import_bundle(&bundle, false)?;
1359
            }
1360
            self.store.put_state(&StateObject::new(t.heads.clone()))?;
75167672 Andy McCall 1361
            self.adopt_tag(&mut view, t, policy.as_ref())
1362
                .map_err(|e| RepoError::Msg(format!("{remote_name} {}: {e}", t.name)))?;
132b884b Andy McCall ↶ 1363
            new_tags += 1;
1364
        }
98286406 Andy McCall ↶ 1365
        if view != op.view {
1366
            self.record_op(&[op_ref], &format!("oxy fetch {remote_name}"), view)?;
1367
        }
6d3eefbc Andy McCall ↶ 1368
        let _ = self.run_hook(
1369
            "post-fetch",
1370
            &format!(
1371
                "{{\"event\":\"post-fetch\",\"remote\":{},\"bookmarks\":{}}}",
1372
                json_str(remote_name),
75167672 Andy McCall 1373
                json_array(report.iter().map(|(n, heads, _)| format!(
1374
                    "{{\"name\":{},\"heads\":{}}}",
1375
                    json_str(n),
1376
                    json_array(heads.iter().map(|h| json_str(&h.to_hex())))
1377
                )))
6d3eefbc Andy McCall ↶ 1378
            ),
1379
        );
75167672 Andy McCall 1380
        Ok(FetchReport {
1381
            refs: report,
1382
            unverified,
1383
            new_tags,
1384
        })
98286406 Andy McCall ↶ 1385
    }
1386
2863456a Andy McCall ↶ 1387
    /// Shallow fetch of the remote's bookmark: its checkpoint as our base,
1388
    /// the changes within `depth` steps of its heads, and the boundary below.
1389
    pub fn fetch_shallow(&self, remote_name: &str, depth: u32) -> Result<usize> {
1390
        let remote = self.open_named_remote(remote_name)?;
75167672 Andy McCall 1391
        self.check_remote_id(remote.as_ref(), remote_name, false)?;
2863456a Andy McCall ↶ 1392
        let resp = remote.refs()?;
1393
        let bookmark = self.config.bookmark.clone();
1394
        if let Some(sp) = &resp.policy {
75167672 Andy McCall 1395
            self.adopt_policy_chain(&resp.history, sp, "oxy clone --depth")
1396
                .map_err(|e| RepoError::Msg(format!("policy from {remote_name}: {e}")))?;
2863456a Andy McCall ↶ 1397
            self.record_policy_serial(remote_name, sp.policy.serial)?;
1398
        }
1399
        let Some(r) = resp.refs.into_iter().find(|r| r.name == bookmark) else {
1400
            return fail(format!("{remote_name} has no bookmark {bookmark:?}"));
1401
        };
1402
        if r.heads.is_empty() {
1403
            return Ok(0);
1404
        }
1405
        // Base: the remote's checkpoint of exactly these heads.
1406
        let cp_bundle = remote.checkpoint(&r.heads)?;
1407
        let mut cp_ref = None;
1408
        for (ty, body) in &cp_bundle.objects {
1409
            let put = self.store.put(*ty, body)?;
1410
            if *ty == ObjectType::Checkpoint {
1411
                cp_ref = Some(put);
1412
            }
1413
        }
75167672 Andy McCall 1414
        let Some(cp_ref) = cp_ref else {
1415
            return fail(format!("{remote_name} sent no checkpoint"));
1416
        };
2863456a Andy McCall ↶ 1417
        self.install_checkpoint(&bookmark, &cp_ref)?;
1418
        // History window.
1419
        let wanted = remote.shallow(&r.heads, depth)?;
1420
        let bundle = remote.fetch(&wanted, self.config.max_blob)?;
1421
        let imported = self.import_bundle_shallow(&bundle, false)?;
1422
        if self.config.max_blob.is_some() {
1423
            self.register_missing_blobs(&imported, remote_name)?;
1424
        }
1425
        self.refresh_boundary(&imported)?;
1426
        if let Some(sa) = &r.attestation {
1427
            let ar = self.store.put_attest(&sa.attest)?;
1428
            for sig in &sa.sigs {
1429
                self.store.put_signature(&ar, sig)?;
1430
            }
1431
            if let AttestBody::Ref { serial, .. } = sa.attest.body {
1432
                self.record_serial(remote_name, &r.name, serial)?;
1433
            }
1434
        }
1435
        let state = self.store.put_state(&StateObject::new(r.heads.clone()))?;
1436
        let (op_ref, op) = self.head_op()?;
1437
        let mut view = op.view.clone();
75167672 Andy McCall 1438
        view.remotes
1439
            .entry(remote_name.to_string())
1440
            .or_default()
1441
            .insert(r.name.clone(), state);
1442
        self.record_op(
1443
            &[op_ref],
1444
            &format!("oxy fetch {remote_name} --depth {depth}"),
1445
            view,
1446
        )?;
2863456a Andy McCall ↶ 1447
        Ok(imported.len())
1448
    }
1449
98286406 Andy McCall ↶ 1450
    /// Fetch, then take the union of the local bookmark's state with the
1451
    /// remote's: no merge change, conflicts become reified (spec §9.4).
1452
    pub fn pull(&self, remote_name: &str) -> Result<PullReport> {
6caacfff Andy McCall ↶ 1453
        let _wc = self.lock_working_copy()?;
98286406 Andy McCall ↶ 1454
        self.fetch(remote_name)?;
1455
        let (op_ref, op) = self.head_op()?;
14edbaaf Andy McCall ↶ 1456
        let current = self.config.bookmark.clone();
1457
        let mut local_current = self.heads_of(&op.view, &current)?;
1458
        local_current.sort();
1459
        let mut view = op.view.clone();
1460
        let mut current_heads = local_current.clone();
1461
        let mut changed = false;
1462
        let mut others = Vec::new();
1463
        let tracked = op
75167672 Andy McCall 1464
            .view
1465
            .remotes
1466
            .get(remote_name)
14edbaaf Andy McCall ↶ 1467
            .cloned()
1468
            .unwrap_or_default();
1469
        for (name, remote_state) in tracked {
1470
            // Every local bookmark tracks the remote's of the same name;
1471
            // the current one may be new here.
1472
            let local_state = op.view.bookmarks.get(&name).copied();
1473
            if local_state.is_none() && name != current {
1474
                continue;
1475
            }
1476
            if local_state == Some(remote_state) {
1477
                continue;
1478
            }
1479
            let local = self.heads_of(&op.view, &name)?;
1480
            let remote_heads = self.store.get_state(&remote_state)?.heads;
1481
            if remote_heads.iter().all(|h| local.contains(h)) {
1482
                continue;
1483
            }
1484
            let mut all = local.clone();
1485
            all.extend(remote_heads);
1486
            let st = self.load_state_history(&all)?;
1487
            let mut heads = st.maximal(&all);
1488
            heads.sort();
1489
            let mut sorted_local = local;
1490
            sorted_local.sort();
1491
            if heads == sorted_local {
1492
                continue;
1493
            }
1494
            view.bookmarks.insert(
1495
                name.clone(),
1496
                self.store.put_state(&StateObject::new(heads.clone()))?,
1497
            );
1498
            if name == current {
1499
                changed = true;
1500
                current_heads = heads;
1501
            } else {
1502
                others.push(name);
1503
            }
1504
        }
f6dccc45 Andy McCall ↶ 1505
        if changed || !others.is_empty() {
1506
            self.record_op(&[op_ref], &format!("oxy pull {remote_name}"), view)?;
98286406 Andy McCall ↶ 1507
        }
f6dccc45 Andy McCall ↶ 1508
        // The working copy follows its bookmark whenever nothing would be
1509
        // lost, also when this pull brought nothing new but it had been
1510
        // left behind (oxygen#89).
1511
        let checked_out = self.follow_bookmark(&current_heads, &current, "oxy pull")?;
75167672 Andy McCall 1512
        Ok(PullReport {
f6dccc45 Andy McCall ↶ 1513
            heads: if changed {
1514
                current_heads
1515
            } else {
1516
                local_current
1517
            },
14edbaaf Andy McCall ↶ 1518
            changed,
75167672 Andy McCall 1519
            checked_out,
14edbaaf Andy McCall ↶ 1520
            others,
75167672 Andy McCall 1521
        })
f6dccc45 Andy McCall ↶ 1522
    }
1523
1524
    /// How many changes the working copy's bookmark has that its base
1525
    /// lacks, when the base is part of the bookmark's state (it fell behind,
1526
    /// and `oxy checkout` or `oxy pull` brings it up); `None` when it is on
1527
    /// the bookmark or holds changes the bookmark lacks. History is read
1528
    /// only when the base and the bookmark's heads differ (oxygen#89).
1529
    pub fn working_copy_behind(&self) -> Result<Option<usize>> {
1530
        let (_, wc) = self.working_copy()?;
1531
        let mut base = wc.deps.clone();
1532
        base.sort();
1533
        let mut heads = self.bookmark_heads()?;
1534
        heads.sort();
1535
        if base == heads || heads.is_empty() {
1536
            return Ok(None);
1537
        }
1538
        let state = self.load_state_history(&heads)?;
1539
        if !base.iter().all(|h| state.contains(h)) {
1540
            return Ok(None);
1541
        }
1542
        let had = if base.is_empty() {
1543
            0
1544
        } else {
1545
            self.load_state_history(&base)?.len()
1546
        };
1547
        Ok(Some(state.len().saturating_sub(had)).filter(|n| *n > 0))
1548
    }
1549
1550
    /// Bring the working copy to `heads`, the state of its bookmark
1551
    /// `bookmark`, when nothing would be lost: its base is part of that
1552
    /// state, so the bookmark only adds to it. Clean, it is checked out;
1553
    /// with uncommitted work, the work comes along when the new changes
1554
    /// leave its paths alone (as `git pull` does), else it stays. Before,
1555
    /// it followed only from exactly the bookmark's old heads, so a working
1556
    /// copy already behind (the bookmark moved by `bookmark set`, a landing
1557
    /// or a pull from another workspace) never caught up, and nothing said
1558
    /// so (oxygen#74, #89). Returns whether it moved.
1559
    pub fn follow_bookmark(
1560
        &self,
1561
        heads: &[ChangeHash],
1562
        bookmark: &str,
1563
        command: &str,
1564
    ) -> Result<bool> {
1565
        let snap = self.snapshot(command)?;
1566
        let clean = snap.wc.tree_ops.is_empty() && snap.wc.edits.is_empty();
1567
        let mut base = snap.base.maximal(&snap.wc.deps);
1568
        base.sort();
1569
        let mut target = heads.to_vec();
1570
        target.sort();
1571
        if base == target {
1572
            return Ok(false);
1573
        }
1574
        let state = self.load_state_history(heads)?;
1575
        if !base.iter().all(|h| state.contains(h)) {
1576
            // The working copy holds changes the bookmark lacks: not ours to move.
1577
            return Ok(false);
1578
        }
1579
        if clean {
1580
            self.checkout(heads, false, &format!("{command} (checkout)"))?;
1581
            Ok(true)
1582
        } else {
1583
            Ok(self
1584
                .checkout_carry(heads, bookmark, &format!("{command} (checkout --carry)"))
1585
                .is_ok())
1586
        }
98286406 Andy McCall ↶ 1587
    }
1588
1589
    /// Push the current bookmark (spec §16.3), sealing this author's unsigned
1590
    /// changes and attesting the reference when a key is available.
f8c69576 Andy McCall ↶ 1591
    /// Delete `bookmark` on a remote (spec §16.4): an update to the zero
1592
    /// state, attested when we have an identity. The local bookmark, if
1593
    /// any, is kept; only the remote-tracking entry goes.
1594
    pub fn push_delete(&self, remote_name: &str, bookmark: &str) -> Result<Vec<RefResult>> {
1595
        let remote = self.open_named_remote(remote_name)?;
1596
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
1597
        let resp = remote.refs()?;
1598
        let Some(r) = resp.refs.iter().find(|r| r.name == bookmark) else {
1599
            return fail(format!("{remote_name} has no bookmark {bookmark}"));
1600
        };
1601
        if resp.policy.is_some() && self.secret_key()?.is_none() {
1602
            return fail(format!("{remote_name} enforces a trust policy; deleting needs an identity (`oxy identity create`)"));
1603
        }
1604
        let attestation = match self.secret_key()? {
1605
            Some(_) => Some(self.sign_attest(&Attest {
1606
                repo: self.id()?,
1607
                hlc: Hlc::now(),
1608
                body: AttestBody::Ref {
1609
                    name: bookmark.to_string(),
1610
                    old_state: r.state,
1611
                    new_state: ObjectRef::ZERO,
1612
                    serial: r.last_serial.unwrap_or(0) + 1,
1613
                },
1614
            })?),
1615
            None => None,
1616
        };
1617
        let results = remote.push(
1618
            Bundle::default(),
1619
            vec![RefUpdate {
1620
                name: bookmark.to_string(),
1621
                old_state: r.state,
1622
                new_state: ObjectRef::ZERO,
1623
                force: true,
1624
                attestation,
1625
            }],
1626
            None,
1627
            vec![],
1628
        )?;
1629
        if results.iter().any(|x| x.ok && x.name == bookmark) {
1630
            let (op_ref, op) = self.head_op()?;
1631
            let mut view = op.view.clone();
1632
            if let Some(m) = view.remotes.get_mut(remote_name) {
1633
                m.remove(bookmark);
1634
            }
1635
            self.record_op(
1636
                &[op_ref],
1637
                &format!("oxy push {remote_name} --delete {bookmark}"),
1638
                view,
1639
            )?;
1640
        }
1641
        Ok(results)
1642
    }
1643
34fad4a9 Andy McCall ↶ 1644
    /// Remove remote `name` (oxygen#86): every `remote.NAME.*` key of this
1645
    /// repository's config (its URL, token, CA and store settings), its
1646
    /// tracking bookmarks in the view, and a store remote's mirror under
1647
    /// `.oxy/remotes/NAME`. Nothing stays to be read as if it were current.
1648
    pub fn remove_remote(&mut self, name: &str) -> Result<()> {
1649
        if !self.config.remotes.contains_key(name) {
1650
            return fail(format!("no remote {name}: `oxy remote list` shows them"));
1651
        }
1652
        let prefix = format!("remote.{name}.");
1653
        let keys: Vec<String> = self
1654
            .config
1655
            .repo_layer()
1656
            .keys()
1657
            .filter(|k| k.starts_with(&prefix))
1658
            .cloned()
1659
            .collect();
1660
        for k in keys {
1661
            self.config.set(&k, "")?;
1662
        }
1663
        self.config.remotes.remove(name);
1664
        self.save_config()?;
1665
        let (op_ref, op) = self.head_op()?;
1666
        if op.view.remotes.contains_key(name) {
1667
            let mut view = op.view.clone();
1668
            view.remotes.remove(name);
1669
            self.record_op(&[op_ref], &format!("oxy remote remove {name}"), view)?;
1670
        }
1671
        let mirror = self.oxy.join("remotes").join(name);
1672
        if mirror.is_dir() {
1673
            fs::remove_dir_all(&mirror)?;
1674
        }
1675
        Ok(())
1676
    }
1677
cb8b8082 Andy McCall ↶ 1678
    /// `changes`, in dependency order, cut into batches of about
1679
    /// `push.batch-bytes` by what each change and its texts and blobs weigh.
1680
    /// There is always one, perhaps empty.
1681
    fn push_batches(&self, changes: &[ChangeHash]) -> Result<Vec<Vec<ChangeHash>>> {
1682
        let blob_len = |r: &ObjectRef| -> u64 {
1683
            self.store
1684
                .get_typed(r, ObjectType::Blob)
1685
                .ok()
1686
                .and_then(|b| Blob::decode(&b).ok())
1687
                .map_or(0, |b| b.length)
1688
        };
1689
        let (mut out, mut batch, mut bytes) = (Vec::new(), Vec::new(), 0u64);
1690
        for h in changes {
1691
            let raw = self.store.get_typed(h, ObjectType::Change)?;
1692
            let (c, texts) = Change::decode_skeleton(&raw, *h)?;
1693
            let mut weight = raw.len() as u64;
1694
            for t in &texts {
1695
                if let crate::objects::TextRef::Blob(r, _, _) = t {
1696
                    weight += blob_len(r);
1697
                }
1698
            }
1699
            for e in &c.edits {
1700
                if let Edit::Replace { new: Some(b), .. } = e {
1701
                    weight += blob_len(b);
1702
                }
1703
            }
1704
            if !batch.is_empty() && bytes + weight > self.config.push_batch_bytes {
1705
                out.push(std::mem::take(&mut batch));
1706
                bytes = 0;
1707
            }
1708
            batch.push(*h);
1709
            bytes += weight;
1710
        }
1711
        out.push(batch);
1712
        Ok(out)
1713
    }
1714
98286406 Andy McCall ↶ 1715
    pub fn push(&self, remote_name: &str, force: bool) -> Result<Vec<RefResult>> {
6d3eefbc Andy McCall ↶ 1716
        let bookmark = self.config.bookmark.clone();
7b9809e6 Andy McCall ↶ 1717
        self.push_bookmark(remote_name, &bookmark, force)
1718
    }
1719
1720
    /// `push` for a named bookmark (`oxy push -b NAME`).
75167672 Andy McCall 1721
    pub fn push_bookmark(
cb8b8082 Andy McCall ↶ 1722
        &self,
1723
        remote_name: &str,
1724
        bookmark: &str,
1725
        force: bool,
1726
    ) -> Result<Vec<RefResult>> {
1727
        self.push_bookmark_with(remote_name, bookmark, force, &mut |_| {})
1728
    }
1729
1730
    /// `push_bookmark`, saying how a long push is going: one line per
1731
    /// batch sent (oxygen#95).
1732
    pub fn push_bookmark_with(
75167672 Andy McCall 1733
        &self,
1734
        remote_name: &str,
1735
        bookmark: &str,
1736
        force: bool,
cb8b8082 Andy McCall ↶ 1737
        progress: crate::store::Progress,
75167672 Andy McCall 1738
    ) -> Result<Vec<RefResult>> {
7b9809e6 Andy McCall ↶ 1739
        let (op_ref, op) = self.head_op()?;
1740
        if !op.view.bookmarks.contains_key(bookmark) {
1741
            return fail(format!("no bookmark {bookmark}"));
1742
        }
1743
        let bookmark = bookmark.to_string();
6d3eefbc Andy McCall ↶ 1744
        let local_heads = self.heads_of(&op.view, &bookmark)?;
1745
        // pre-push hook: may veto before the remote is contacted.
1746
        self.run_hook(
1747
            "pre-push",
75167672 Andy McCall 1748
            &format!(
1749
                "{{\"event\":\"pre-push\",\"remote\":{},\"bookmark\":{},\"heads\":{}}}",
1750
                json_str(remote_name),
1751
                json_str(&bookmark),
1752
                json_array(local_heads.iter().map(|h| json_str(&h.to_hex())))
1753
            ),
6d3eefbc Andy McCall ↶ 1754
        )?;
98286406 Andy McCall ↶ 1755
        let remote = self.open_named_remote(remote_name)?;
75167672 Andy McCall 1756
        self.check_remote_id(remote.as_ref(), remote_name, true)?;
83e0677b Andy McCall ↶ 1757
        let resp = remote.refs()?;
1758
        let local_policy = self.current_policy()?.map(|(_, sp)| sp);
28fc23d7 Andy McCall ↶ 1759
        let resp_policy_serial = resp.policy.as_ref().map(|p| p.policy.serial);
83e0677b Andy McCall ↶ 1760
        let policy_to_send = match (&local_policy, &resp.policy) {
1761
            (Some(l), Some(r)) if l.policy.serial > r.policy.serial => Some(l.clone()),
1762
            (Some(l), None) => Some(l.clone()),
1763
            (Some(l), Some(r)) if l.policy.serial < r.policy.serial => {
75167672 Andy McCall 1764
                return fail(format!(
1765
                    "{remote_name} has a newer policy (serial {}); fetch first",
1766
                    r.policy.serial
1767
                ));
83e0677b Andy McCall ↶ 1768
            }
1769
            _ => None,
1770
        };
1771
        let remote_has_policy = resp.policy.is_some() || policy_to_send.is_some();
1772
        if remote_has_policy && self.secret_key()?.is_none() {
1773
            return fail(format!("{remote_name} enforces a trust policy; pushing needs an identity (`oxy identity create`)"));
1774
        }
132b884b Andy McCall ↶ 1775
        let remote_tags: BTreeSet<String> = resp.tags.iter().map(|t| t.name.clone()).collect();
75167672 Andy McCall 1776
        let tags_to_send: Vec<crate::protocol::TagRef> = self
1777
            .tag_refs()?
1778
            .into_iter()
1779
            .filter(|t| !remote_tags.contains(&t.name))
1780
            .collect();
83e0677b Andy McCall ↶ 1781
        let refs = resp.refs;
98286406 Andy McCall ↶ 1782
        let empty = self.store.put_state(&StateObject::new(vec![]))?;
75167672 Andy McCall 1783
        let (remote_state, remote_heads, last_serial) =
1784
            match refs.iter().find(|r| r.name == bookmark) {
1785
                Some(r) => (r.state, r.heads.clone(), r.last_serial),
1786
                None => (empty, vec![], None),
1787
            };
1788
        let new_state = self
1789
            .store
1790
            .put_state(&StateObject::new(local_heads.clone()))?;
83e0677b Andy McCall ↶ 1791
        // A push that carries a policy re-attests the bookmark even when its
1792
        // state is unchanged, so the current attestation is always by a key
1793
        // the current policy authorizes (a revoked key's attestation would
1794
        // otherwise be refused by every later fetch).
132b884b Andy McCall ↶ 1795
        if new_state == remote_state && policy_to_send.is_none() && tags_to_send.is_empty() {
75167672 Andy McCall 1796
            return Ok(vec![RefResult {
1797
                name: bookmark,
1798
                ok: true,
1799
                reason: "already up to date".into(),
1800
            }]);
98286406 Andy McCall ↶ 1801
        }
1802
        for h in &remote_heads {
1803
            if !self.store.has(h) {
75167672 Andy McCall 1804
                return fail(format!(
3e5772cc Andy McCall ↶ 1805
                    "the remote has change {} which you do not; pull first (`oxy pull {remote_name}`), then push again",
75167672 Andy McCall 1806
                    h.short(12)
1807
                ));
98286406 Andy McCall ↶ 1808
            }
1809
        }
1810
        if !force {
1811
            let closure = self.closure_in_store(&local_heads)?;
1812
            if let Some(h) = remote_heads.iter().find(|h| !closure.contains(h)) {
1813
                return fail(format!("not a fast-forward: remote head {} is not in your state; pull first or use --force", h.short(12)));
1814
            }
1815
        }
1816
        let to_send = self.negotiate(&remote_heads, &local_heads)?;
1817
        let key = self.secret_key()?.map(|(k, _)| k);
1818
        if let Some(key) = key {
05e71ed6 Andy McCall ↶ 1819
            // Seal this author's changes that carry no valid authenticator,
cb8b8082 Andy McCall ↶ 1820
            // and adopt anonymous ones (zero author, spec §14.4). The seals
1821
            // are stored, so each batch's bundle carries those it needs.
98286406 Andy McCall ↶ 1822
            let mut unsigned = Vec::new();
1823
            for h in &to_send {
cb8b8082 Andy McCall ↶ 1824
                let c = self.store.get_change_meta(h)?;
05e71ed6 Andy McCall ↶ 1825
                if (c.author == key || c.author.is_zero())
75167672 Andy McCall 1826
                    && !matches!(self.authenticate_change(h)?, SignatureStatus::Valid { .. })
1827
                {
98286406 Andy McCall ↶ 1828
                    unsigned.push(*h);
1829
                }
1830
            }
1831
            for chunk in unsigned.chunks(crate::attest::MAX_SEAL_HASHES) {
cb8b8082 Andy McCall ↶ 1832
                self.sign_attest(&Attest::seal(self.id()?, chunk.to_vec()))?;
98286406 Andy McCall ↶ 1833
            }
cb8b8082 Andy McCall ↶ 1834
        }
1835
        // A long history goes in batches, in dependency order, so neither
1836
        // side holds it whole and no request passes the remote's limit:
1837
        // all but the last carry objects alone; the last moves the bookmark
1838
        // (oxygen#95).
1839
        let batches = self.push_batches(&to_send)?;
1840
        let (last, earlier) = batches.split_last().expect("at least one batch");
1841
        for (i, batch) in earlier.iter().enumerate() {
1842
            progress(&format!(
1843
                "part {} of {}: {} changes",
1844
                i + 1,
1845
                batches.len(),
1846
                batch.len()
1847
            ));
1848
            let results = remote.push(self.bundle_for(batch)?, vec![], None, vec![])?;
1849
            match results.iter().find(|r| r.name == OBJECTS_RESULT) {
1850
                Some(r) if r.ok => {}
1851
                Some(r) => {
1852
                    return fail(format!(
1853
                        "{remote_name} refused part {} of the push: {}",
1854
                        i + 1,
1855
                        r.reason
1856
                    ))
1857
                }
1858
                None => {
1859
                    return fail(format!(
1860
                        "{remote_name} does not take a push in parts, and this one is too long for one: update the server's oxy"
1861
                    ))
1862
                }
1863
            }
1864
        }
1865
        if batches.len() > 1 {
1866
            progress(&format!(
1867
                "part {} of {}: {} changes",
1868
                batches.len(),
1869
                batches.len(),
1870
                last.len()
1871
            ));
98286406 Andy McCall ↶ 1872
        }
cb8b8082 Andy McCall ↶ 1873
        let mut bundle = self.bundle_for(last)?;
75167672 Andy McCall 1874
        bundle.objects.push((
1875
            ObjectType::State,
1876
            StateObject::new(local_heads.clone()).encode(),
1877
        ));
98286406 Andy McCall ↶ 1878
        let attestation = match key {
1879
            Some(_) => Some(self.sign_attest(&Attest {
1880
                repo: self.id()?,
1881
                hlc: Hlc::now(),
75167672 Andy McCall 1882
                body: AttestBody::Ref {
1883
                    name: bookmark.clone(),
1884
                    old_state: remote_state,
1885
                    new_state,
f8c69576 Andy McCall ↶ 1886
                    serial: next_serial(last_serial),
75167672 Andy McCall 1887
                },
98286406 Andy McCall ↶ 1888
            })?),
1889
            None => None,
1890
        };
1891
        let serial = attestation.as_ref().and_then(|a| match a.attest.body {
1892
            AttestBody::Ref { serial, .. } => Some(serial),
1893
            _ => None,
1894
        });
83e0677b Andy McCall ↶ 1895
        let sent_serial = policy_to_send.as_ref().map(|p| p.policy.serial);
132b884b Andy McCall ↶ 1896
        // Tag states must be present on the remote: bundle their changes too.
1897
        for t in &tags_to_send {
1898
            let extra = self.negotiate(&remote_heads, &t.heads)?;
75167672 Andy McCall 1899
            let extra: Vec<ChangeHash> =
1900
                extra.into_iter().filter(|h| !to_send.contains(h)).collect();
132b884b Andy McCall ↶ 1901
            if !extra.is_empty() {
1902
                let more = self.bundle_for(&extra)?;
1903
                bundle.changes.extend(more.changes);
2c75672f Andy McCall ↶ 1904
                bundle.hashes.extend(more.hashes);
132b884b Andy McCall ↶ 1905
                bundle.attests.extend(more.attests);
1906
                bundle.objects.extend(more.objects);
1907
            }
75167672 Andy McCall 1908
            bundle.objects.push((
1909
                ObjectType::State,
1910
                StateObject::new(t.heads.clone()).encode(),
1911
            ));
132b884b Andy McCall ↶ 1912
        }
28fc23d7 Andy McCall ↶ 1913
        if let Some(l) = &policy_to_send {
1914
            let remote_serial = resp_policy_serial;
75167672 Andy McCall 1915
            bundle.policies = self
1916
                .policy_history()?
1917
                .into_iter()
1918
                .filter(|sp| {
1919
                    remote_serial.is_none_or(|r| sp.policy.serial > r)
1920
                        && sp.policy.serial < l.policy.serial
1921
                })
1922
                .collect();
28fc23d7 Andy McCall ↶ 1923
        }
75167672 Andy McCall 1924
        let results = remote.push(
1925
            bundle,
1926
            vec![RefUpdate {
1927
                name: bookmark.clone(),
1928
                old_state: remote_state,
1929
                new_state,
1930
                force,
1931
                attestation,
1932
            }],
1933
            policy_to_send,
1934
            tags_to_send,
1935
        )?;
1936
        if let (Some(serial), true) = (
1937
            sent_serial,
1938
            results.iter().any(|r| r.ok && r.name == "policy"),
1939
        ) {
83e0677b Andy McCall ↶ 1940
            self.record_policy_serial(remote_name, serial)?;
1941
        }
1942
        if results.iter().any(|r| r.ok && r.name == bookmark) {
98286406 Andy McCall ↶ 1943
            let mut view = op.view.clone();
75167672 Andy McCall 1944
            view.remotes
1945
                .entry(remote_name.to_string())
1946
                .or_default()
1947
                .insert(bookmark.clone(), new_state);
98286406 Andy McCall ↶ 1948
            self.record_op(&[op_ref], &format!("oxy push {remote_name}"), view)?;
1949
            if let Some(s) = serial {
1950
                self.record_serial(remote_name, &bookmark, s)?;
1951
            }
1952
        }
1953
        Ok(results)
1954
    }
1955
1956
    /// Clone a remote into `dest`: same repository ID, `origin` remote,
1957
    /// bookmark set to the remote's, working copy checked out.
1958
    pub fn clone(url: &str, dest: &Path) -> Result<Repo> {
7421309f Andy McCall ↶ 1959
        Self::clone_with(url, dest, None, &[])
b3c5a59a Andy McCall ↶ 1960
    }
1961
7421309f Andy McCall ↶ 1962
    /// Clone, leaving blobs above `max_blob` bytes to be fetched on first
1963
    /// read, and materializing only `sparse` paths (which implies lazy blobs
1964
    /// unless a size is given, so out-of-scope binaries are never fetched).
75167672 Andy McCall 1965
    pub fn clone_with(
1966
        url: &str,
1967
        dest: &Path,
1968
        max_blob: Option<u64>,
1969
        sparse: &[String],
1970
    ) -> Result<Repo> {
2863456a Andy McCall ↶ 1971
        Self::clone_full(url, dest, max_blob, sparse, None)
1972
    }
1973
1974
    /// Shallow clone (spec §17): a checkpoint of the bookmark's heads plus the
1975
    /// changes within `depth` steps of them; the rest is the boundary.
75167672 Andy McCall 1976
    pub fn clone_shallow(
1977
        url: &str,
1978
        dest: &Path,
1979
        depth: u32,
1980
        max_blob: Option<u64>,
1981
        sparse: &[String],
1982
    ) -> Result<Repo> {
2863456a Andy McCall ↶ 1983
        Self::clone_full(url, dest, max_blob, sparse, Some(depth))
1984
    }
1985
75167672 Andy McCall 1986
    fn clone_full(
1987
        url: &str,
1988
        dest: &Path,
1989
        max_blob: Option<u64>,
1990
        sparse: &[String],
1991
        depth: Option<u32>,
1992
    ) -> Result<Repo> {
ff1f62fe Andy McCall ↶ 1993
        let options = crate::credentials::Credentials::user().options_for(url);
1994
        Self::clone_using(url, dest, max_blob, sparse, depth, &options)
a07f60a3 Andy McCall ↶ 1995
    }
1996
ff1f62fe Andy McCall ↶ 1997
    /// Clone a subrepo with the credentials the parent would use for its
1998
    /// hub (see [`Repo::credentials_for`]). Nothing is recorded in the
1999
    /// subrepo: it finds the same ones again through its parent.
a07f60a3 Andy McCall ↶ 2000
    pub(crate) fn clone_as_subrepo(&self, url: &str, dest: &Path) -> Result<Repo> {
2001
        let options = self.credentials_for(url);
ff1f62fe Andy McCall ↶ 2002
        Self::clone_using(url, dest, None, &[], None, &options)
a07f60a3 Andy McCall ↶ 2003
    }
2004
2005
    /// The name of a remote of this repository on the same hub (scheme,
2006
    /// host and port) as `url`.
2007
    fn remote_on_same_hub(&self, url: &str) -> Option<String> {
2008
        let origin = |u: &str| -> Option<String> {
2009
            let (scheme, rest) = u.split_once("://")?;
9f9e72b9 Andy McCall ↶ 2010
            if !matches!(scheme, "http" | "https") {
2011
                return None;
2012
            }
a07f60a3 Andy McCall ↶ 2013
            let host = rest.split('/').next()?;
2014
            Some(format!(
2015
                "{}://{}",
2016
                scheme.to_ascii_lowercase(),
2017
                host.to_ascii_lowercase()
2018
            ))
2019
        };
2020
        let want = origin(url)?;
2021
        self.config
2022
            .remotes
2023
            .iter()
2024
            .find(|(_, u)| origin(u).as_deref() == Some(want.as_str()))
2025
            .map(|(name, _)| name.clone())
2026
    }
2027
2028
    /// The token and CA to reach `url` with: those of a remote of this
2029
    /// repository on the same hub (scheme, host and port), else the
ff1f62fe Andy McCall ↶ 2030
    /// environment's (`OXY_TOKEN`, `OXY_CA`), the user's credential store
2031
    /// and enclosing checkouts', as a clone would use them.
a07f60a3 Andy McCall ↶ 2032
    pub(crate) fn credentials_for(&self, url: &str) -> RemoteOptions {
2033
        match self.remote_on_same_hub(url) {
2034
            Some(name) => RemoteOptions {
2035
                repo_id: None,
9f9e72b9 Andy McCall ↶ 2036
                cache_dir: None,
a07f60a3 Andy McCall ↶ 2037
                ..self.remote_options(&name)
2038
            },
ff1f62fe Andy McCall ↶ 2039
            None => {
2040
                let mut options = RemoteOptions::default();
2041
                self.fill_credentials(url, &mut options);
2042
                options
2043
            }
a07f60a3 Andy McCall ↶ 2044
        }
2045
    }
2046
2047
    fn clone_using(
2048
        url: &str,
2049
        dest: &Path,
2050
        max_blob: Option<u64>,
2051
        sparse: &[String],
2052
        depth: Option<u32>,
2053
        options: &RemoteOptions,
2054
    ) -> Result<Repo> {
2055
        let remote = open_remote(url, options)?;
98286406 Andy McCall ↶ 2056
        let id = remote.repo_id()?;
75167672 Andy McCall 2057
        if id == crate::protocol::UNBOUND_ID {
05e71ed6 Andy McCall ↶ 2058
            return fail(format!(
2059
                "{url} is empty and unbound: push a repository to it first"
2060
            ));
75167672 Andy McCall 2061
        }
98286406 Andy McCall ↶ 2062
        let mut repo = Repo::init_with_id(dest, id)?;
827281ee Andy McCall ↶ 2063
        repo.config
2064
            .set("remote.origin.url", &crate::protocol::stored_url(url))?;
b3c5a59a Andy McCall ↶ 2065
        if let Some(m) = max_blob {
2066
            repo.config.set("filter.max-blob", &m.to_string())?;
7421309f Andy McCall ↶ 2067
        } else if !sparse.is_empty() {
2068
            repo.config.set("filter.max-blob", "0")?;
2069
        }
2070
        if !sparse.is_empty() {
2071
            repo.config.set("filter.paths", &sparse.join(","))?;
b3c5a59a Andy McCall ↶ 2072
        }
98286406 Andy McCall ↶ 2073
        repo.save_config()?;
2863456a Andy McCall ↶ 2074
        if let Some(depth) = depth {
2075
            repo.fetch_shallow("origin", depth)?;
2076
        } else {
2077
            repo.fetch("origin")?;
2078
        }
98286406 Andy McCall ↶ 2079
        let (op_ref, op) = repo.head_op()?;
14edbaaf Andy McCall ↶ 2080
        // The remote's default bookmark, else ours (main), else its only one.
2081
        let theirs = op.view.remotes.get("origin").cloned().unwrap_or_default();
9f9e72b9 Andy McCall ↶ 2082
        // Asked of the remote as now configured, so a store-backed one
2083
        // answers from the mirror the fetch just filled.
2084
        let advertised = repo
2085
            .open_named_remote("origin")
2086
            .ok()
2087
            .and_then(|r| r.refs().ok())
2088
            .and_then(|r| r.default_bookmark);
14edbaaf Andy McCall ↶ 2089
        let bookmark = advertised
2090
            .filter(|b| theirs.contains_key(b))
2091
            .or_else(|| {
2092
                theirs
2093
                    .contains_key(&repo.config.bookmark)
2094
                    .then(|| repo.config.bookmark.clone())
2095
            })
2096
            .or_else(|| {
2097
                (theirs.len() == 1)
2098
                    .then(|| theirs.keys().next().cloned())
2099
                    .flatten()
2100
            })
2101
            .unwrap_or_else(|| repo.config.bookmark.clone());
2102
        let initial = repo.config.bookmark.clone();
2103
        if bookmark != repo.config.bookmark {
2104
            fs::create_dir_all(repo.workspace_bookmark_path().parent().unwrap())?;
2105
            write_atomic(&repo.workspace_bookmark_path(), bookmark.as_bytes())?;
2106
            repo.config.bookmark = bookmark.clone();
2107
        }
2108
        if let Some(state) = theirs.get(&bookmark).copied() {
98286406 Andy McCall ↶ 2109
            let heads = repo.store.get_state(&state)?.heads;
2110
            let mut view = op.view.clone();
14edbaaf Andy McCall ↶ 2111
            // The empty bookmark `init` made goes when another is checked out.
2112
            if initial != bookmark && repo.heads_of(&view, &initial)?.is_empty() {
2113
                view.bookmarks.remove(&initial);
2114
            }
98286406 Andy McCall ↶ 2115
            view.bookmarks.insert(bookmark, state);
2116
            repo.record_op(&[op_ref], &format!("oxy clone {url}"), view)?;
2117
            repo.checkout(&heads, false, "oxy clone (checkout)")?;
2118
        }
2119
        Ok(repo)
f8c69576 Andy McCall ↶ 2120
    }
2121
}
2122
2123
/// The serial of a reference's next attestation: one more than the last the
2124
/// remote reports, or, for a bookmark the remote does not have, the clock in
2125
/// milliseconds, so a bookmark created again after a deletion goes past the
2126
/// deletion's serial the remote keeps.
2127
fn next_serial(last: Option<u64>) -> u64 {
2128
    match last {
2129
        Some(l) => l + 1,
2130
        None => Hlc::now().wall_ms.max(1),
98286406 Andy McCall ↶ 2131
    }
2132
}