Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 17.2 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! Moving objects between a repository and a hub: which objects the hub
5//! lacks, how they are cut into `POST objects` bodies and streamed from the
6//! store, and how an object stream from the hub goes into the store.
7
8use std::collections::HashSet;
9use std::io::{self, Read};
10
11use anyhow::{Context, Result, bail};
12use braid_engine::{Reach, Reached, reachable, read_changeset};
13use braid_format::{Kind, ObjectId, Objects};
14use braid_hubproto::stream::{self, MAGIC};
15use braid_store::Store;
16
17use super::remote::{HubError, Remote};
18
19/// Bytes of a record before its payload: the kind, the id and the length.
20const RECORD_HEADER: u64 = 1 + ObjectId::LEN as u64 + 8;
21
22/// Bytes of a stream around its records: the magic and the terminator.
23const FRAME: u64 = MAGIC.len() as u64 + 1;
24
25/// The largest object taken from the hub. Objects reach a hub through
26/// bodies of at most 256 MiB, unless it imported them from git.
27const MAX_OBJECT: u64 = 1 << 30;
28
29/// The objects `reach` reaches that the hub lacks, in the walk's order: a
30/// changeset before the objects it names. `lacks` is asked about `batch`
31/// ids at a time.
32pub(crate) fn lacking<O: Objects>(
33 objects: &O,
34 reach: &Reach<'_>,
35 batch: usize,
36 mut lacks: impl FnMut(&[ObjectId]) -> Result<Vec<ObjectId>, HubError>,
37) -> Result<Vec<Reached>> {
38 let candidates = reachable(objects, reach)?;
39 let mut lacked = HashSet::new();
40 for chunk in candidates.chunks(batch.max(1)) {
41 let ids: Vec<ObjectId> = chunk.iter().map(|reached| reached.id).collect();
42 lacked.extend(lacks(&ids)?);
43 }
44 Ok(candidates
45 .into_iter()
46 .filter(|reached| lacked.contains(&reached.id))
47 .collect())
48}
49
50/// Bytes of the stream that holds `objects`.
51pub(crate) fn stream_len(objects: &[Reached]) -> u64 {
52 FRAME
53 + objects
54 .iter()
55 .map(|object| RECORD_HEADER + object.size)
56 .sum::<u64>()
57}
58
59/// Cuts `objects` into runs whose streams take at most `max_body` bytes
60/// each. An object too large for any body is an error.
61pub(crate) fn batches(objects: &[Reached], max_body: u64) -> Result<Vec<&[Reached]>> {
62 let mut runs = Vec::new();
63 let mut start = 0;
64 let mut size = FRAME;
65 for (index, object) in objects.iter().enumerate() {
66 let record = RECORD_HEADER + object.size;
67 if FRAME + record > max_body {
68 bail!(
69 "{} {} is {} bytes: more than the hub takes in one request ({max_body} bytes)",
70 object.kind,
71 object.id,
72 object.size
73 );
74 }
75 if size + record > max_body {
76 runs.push(&objects[start..index]);
77 start = index;
78 size = FRAME;
79 }
80 size += record;
81 }
82 if start < objects.len() {
83 runs.push(&objects[start..]);
84 }
85 Ok(runs)
86}
87
88/// An object stream read from the store as it is sent, one object at a
89/// time: the body of a `POST objects`.
90pub(crate) struct StreamBody<'a, O> {
91 objects: &'a O,
92 list: &'a [Reached],
93 next: usize,
94 started: bool,
95 finished: bool,
96 buffer: Vec<u8>,
97 at: usize,
98}
99
100impl<'a, O: Objects> StreamBody<'a, O> {
101 /// The stream of `list`, which is [`stream_len`] bytes long.
102 pub(crate) fn new(objects: &'a O, list: &'a [Reached]) -> StreamBody<'a, O> {
103 StreamBody {
104 objects,
105 list,
106 next: 0,
107 started: false,
108 finished: false,
109 buffer: Vec::new(),
110 at: 0,
111 }
112 }
113
114 /// Puts the next piece in the buffer: the magic, a record, or the
115 /// terminator. `false` once the stream is over.
116 fn refill(&mut self) -> io::Result<bool> {
117 self.buffer.clear();
118 self.at = 0;
119 if !self.started {
120 self.started = true;
121 self.buffer.extend_from_slice(MAGIC);
122 } else if let Some(object) = self.list.get(self.next) {
123 self.next += 1;
124 let found = self.objects.get(&object.id).map_err(io::Error::other)?;
125 let Some((kind, payload)) = found else {
126 return Err(io::Error::other(format!(
127 "{} {} is not in the store",
128 object.kind, object.id
129 )));
130 };
131 // The length was announced: the payload must have it.
132 if kind != object.kind || payload.len() as u64 != object.size {
133 return Err(io::Error::other(format!(
134 "{} {} is not what the walk found",
135 object.kind, object.id
136 )));
137 }
138 self.buffer.push(kind.code());
139 self.buffer.extend_from_slice(object.id.as_bytes());
140 self.buffer
141 .extend_from_slice(&(payload.len() as u64).to_le_bytes());
142 self.buffer.extend_from_slice(&payload);
143 } else if !self.finished {
144 self.finished = true;
145 self.buffer.push(0);
146 } else {
147 return Ok(false);
148 }
149 Ok(true)
150 }
151}
152
153impl<O: Objects> Read for StreamBody<'_, O> {
154 fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
155 while self.at == self.buffer.len() {
156 if !self.refill()? {
157 return Ok(0);
158 }
159 }
160 let n = out.len().min(self.buffer.len() - self.at);
161 out[..n].copy_from_slice(&self.buffer[self.at..self.at + n]);
162 self.at += n;
163 Ok(n)
164 }
165}
166
167/// What a series of uploads sent.
168#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
169pub(crate) struct Sent {
170 /// Objects sent.
171 pub(crate) objects: u64,
172 /// Bytes of their payloads.
173 pub(crate) bytes: u64,
174}
175
176/// Sends `objects` to the hub in bodies of at most `max_body` bytes.
177pub(crate) fn send<O: Objects>(
178 objects: &O,
179 remote: &impl Remote,
180 list: &[Reached],
181 max_body: u64,
182) -> Result<Sent> {
183 let mut sent = Sent::default();
184 for run in batches(list, max_body)? {
185 let mut body = StreamBody::new(objects, run);
186 let len = stream_len(run);
187 match remote.send_objects(&mut body, len) {
188 Ok(_) => {}
189 // Bodies keep to what the hub says it takes: a refusal comes
190 // from a proxy in front of it, or a hub that did not say.
191 Err(err @ HubError::Api { status: 413, .. }) => {
192 return Err(anyhow::Error::new(err).context(format!(
193 "cannot upload objects to the hub: a body of {len} bytes was refused; set BRAID_HUB_MAX_BODY to a smaller size in bytes"
194 )));
195 }
196 // A proxy that refuses a body as soon as it reads its length
197 // answers 413 and closes before braid has sent it, which braid
198 // only sees as the connection breaking off.
199 Err(err @ HubError::Transport { .. }) if broke_off(&err) => {
200 return Err(anyhow::Error::new(err).context(format!(
201 "cannot upload objects to the hub: the connection broke off while a body of {len} bytes went up, as it does when the hub or a proxy in front of it refuses a body as too large before reading it; set BRAID_HUB_MAX_BODY to a smaller size in bytes, such as 1048576, and run the command again"
202 )));
203 }
204 Err(err) => return Err(err).context("cannot upload objects to the hub"),
205 }
206 sent.objects += run.len() as u64;
207 sent.bytes += run.iter().map(|object| object.size).sum::<u64>();
208 }
209 Ok(sent)
210}
211
212/// Whether a transfer failed because the other side closed the connection
213/// while braid was still writing.
214fn broke_off(err: &HubError) -> bool {
215 match err {
216 HubError::Transport { detail, .. } => {
217 let detail = detail.to_ascii_lowercase();
218 detail.contains("broken pipe") || detail.contains("connection reset")
219 }
220 _ => false,
221 }
222}
223
224/// Sends what the hub lacks of what `reach` reaches.
225pub(crate) fn upload(store: &Store, remote: &impl Remote, reach: &Reach<'_>) -> Result<Sent> {
226 let list = lacking(store, reach, remote.max_ids(), |ids| remote.lacks(ids))?;
227 if list.is_empty() {
228 return Ok(Sent::default());
229 }
230 send(store, remote, &list, remote.max_body())
231}
232
233/// Sends the objects `ids`, which the hub said it needs: each one, and for
234/// a changeset, what it adds to its first parent too, since a hub that
235/// lacks a changeset cannot tell what else it lacks of it.
236pub(crate) fn upload_missing(
237 store: &Store,
238 remote: &impl Remote,
239 ids: &[ObjectId],
240) -> Result<Sent> {
241 let mut list = Vec::with_capacity(ids.len());
242 let mut listed = HashSet::new();
243 for id in ids {
244 let Some((kind, size)) = store.stat(id)? else {
245 bail!("the hub needs object {id}, which this repository does not hold");
246 };
247 if kind != Kind::Changeset {
248 if listed.insert(*id) {
249 list.push(Reached {
250 id: *id,
251 kind,
252 size,
253 });
254 }
255 continue;
256 }
257 let parent: Vec<ObjectId> = read_changeset(store, *id)?
258 .parents
259 .first()
260 .copied()
261 .into_iter()
262 .collect();
263 let added = reachable(
264 store,
265 &Reach {
266 want: std::slice::from_ref(id),
267 have: &parent,
268 history: Some(0),
269 paths: None,
270 max_objects: None,
271 },
272 )?;
273 list.extend(added.into_iter().filter(|object| listed.insert(object.id)));
274 }
275 send(store, remote, &list, remote.max_body())
276}
277
278/// What an object stream from the hub brought.
279#[derive(Clone, Debug, Default, PartialEq, Eq)]
280pub(crate) struct Received {
281 /// Objects stored.
282 pub(crate) objects: u64,
283 /// The changesets among them.
284 pub(crate) changesets: Vec<ObjectId>,
285 /// The tree nodes among them.
286 pub(crate) trees: Vec<ObjectId>,
287}
288
289/// Reads an object stream into the store, every record checked against its
290/// id, and makes what it stored durable. A changeset's root tree and
291/// parents must be stored by the end: they come in the same stream, or the
292/// store held them already.
293pub(crate) fn store_stream(store: &Store, input: impl Read) -> Result<Received> {
294 let mut reader =
295 stream::Reader::new(input, MAX_OBJECT).context("the hub's object stream is not valid")?;
296 let mut received = Received::default();
297 while let Some(record) = reader
298 .next_record()
299 .context("the hub's object stream is not valid")?
300 {
301 let id = store.put(record.kind, &record.payload)?;
302 if id != record.id {
303 bail!("object {} was stored as {id}", record.id);
304 }
305 match record.kind {
306 Kind::Changeset => received.changesets.push(id),
307 Kind::Tree => received.trees.push(id),
308 _ => {}
309 }
310 received.objects += 1;
311 }
312 store.sync()?;
313 for id in &received.changesets {
314 let changeset = read_changeset(store, *id)?;
315 for needed in changeset.parents.iter().chain([&changeset.root]) {
316 if *needed != braid_engine::EMPTY_TREE && !store.contains(needed)? {
317 bail!("the hub sent changeset {id} without {needed}, which it needs");
318 }
319 }
320 }
321 Ok(received)
322}
323
324#[cfg(test)]
325mod tests {
326 use super::*;
327 use crate::hub::remote::LACKS_BATCH;
328 use crate::hub::testing::{Fixture, ada_change};
329 use braid_engine::Reach;
330
331 #[test]
332 fn the_hub_gets_only_what_it_lacks() {
333 let f = Fixture::new();
334 let one = ada_change(&f.repo, None, &[("a.txt", "1\n"), ("b.txt", "b\n")]);
335 let two = ada_change(&f.repo, Some(one), &[("a.txt", "2\n")]);
336 let three = ada_change(&f.repo, Some(two), &[("c.txt", "c\n")]);
337 let store = f.repo.store();
338 let all = reachable(
339 store,
340 &Reach {
341 want: &[three],
342 ..Reach::default()
343 },
344 )
345 .unwrap();
346 // A hub that holds everything `one` reaches.
347 let held: HashSet<ObjectId> = reachable(
348 store,
349 &Reach {
350 want: &[one],
351 ..Reach::default()
352 },
353 )
354 .unwrap()
355 .iter()
356 .map(|reached| reached.id)
357 .collect();
358 let mut asked = Vec::new();
359 let list = lacking(
360 store,
361 &Reach {
362 want: &[three],
363 ..Reach::default()
364 },
365 2,
366 |ids| {
367 assert!(ids.len() <= 2);
368 asked.extend_from_slice(ids);
369 Ok(ids
370 .iter()
371 .filter(|id| !held.contains(id))
372 .copied()
373 .collect())
374 },
375 )
376 .unwrap();
377 // Every candidate was asked about once, in batches of two.
378 assert_eq!(asked.len(), all.len());
379 let ids: HashSet<ObjectId> = list.iter().map(|reached| reached.id).collect();
380 assert!(ids.contains(&two) && ids.contains(&three));
381 assert!(!ids.contains(&one));
382 assert!(ids.iter().all(|id| !held.contains(id)));
383 assert_eq!(list.len(), all.len() - held.len());
384 // The walk's order is kept: the newest changeset first.
385 assert_eq!(list[0].id, three);
386 // Errors from the hub stop the walk.
387 let failed = lacking(
388 store,
389 &Reach {
390 want: &[three],
391 ..Reach::default()
392 },
393 LACKS_BATCH,
394 |_| Err(HubError::api(500, "internal", "down")),
395 );
396 assert!(failed.is_err());
397 }
398
399 fn reached(size: u64) -> Reached {
400 Reached {
401 id: ObjectId::hash(Kind::Blob, &size.to_le_bytes()),
402 kind: Kind::Blob,
403 size,
404 }
405 }
406
407 #[test]
408 fn bodies_stay_under_the_limit() {
409 let objects: Vec<Reached> = [10, 20, 30, 5, 60].into_iter().map(reached).collect();
410 let limit = FRAME + 2 * RECORD_HEADER + 35;
411 let runs = batches(&objects, limit).unwrap();
412 let sizes: Vec<Vec<u64>> = runs
413 .iter()
414 .map(|run| run.iter().map(|o| o.size).collect())
415 .collect();
416 assert_eq!(sizes, [vec![10, 20], vec![30, 5], vec![60]]);
417 for run in &runs {
418 assert!(stream_len(run) <= limit, "{run:?}");
419 }
420 assert!(batches(&[], limit).unwrap().is_empty());
421 let err = batches(&[reached(1000)], limit).unwrap_err().to_string();
422 assert!(err.contains("more than the hub takes"), "{err}");
423 }
424
425 #[test]
426 fn streams_go_out_and_come_back() {
427 let from = Fixture::new();
428 let one = ada_change(&from.repo, None, &[("a.txt", "1\n"), ("dir/b.txt", "b\n")]);
429 let two = ada_change(&from.repo, Some(one), &[("a.txt", "2\n")]);
430 let list = reachable(
431 from.repo.store(),
432 &Reach {
433 want: &[two],
434 ..Reach::default()
435 },
436 )
437 .unwrap();
438 let mut bytes = Vec::new();
439 StreamBody::new(from.repo.store(), &list)
440 .read_to_end(&mut bytes)
441 .unwrap();
442 assert_eq!(bytes.len() as u64, stream_len(&list));
443 // The protocol's own reader takes it, record by record.
444 let records: Vec<stream::Record> = stream::Reader::new(&bytes[..], 1 << 20)
445 .unwrap()
446 .collect::<Result<_, _>>()
447 .unwrap();
448 assert_eq!(records.len(), list.len());
449 assert!(records.iter().zip(&list).all(|(r, l)| r.id == l.id));
450
451 let to = Fixture::new();
452 let received = store_stream(to.repo.store(), &bytes[..]).unwrap();
453 assert_eq!(received.objects, list.len() as u64);
454 assert_eq!(received.changesets.len(), 2);
455 for object in &list {
456 assert!(to.repo.store().contains(&object.id).unwrap());
457 }
458 let read = read_changeset(to.repo.store(), two).unwrap();
459 braid_engine::read_tree(to.repo.store(), read.root).unwrap();
460
461 // A stream cut short, or with a changed byte, is refused.
462 let fresh = Fixture::new();
463 assert!(store_stream(fresh.repo.store(), &bytes[..bytes.len() - 1]).is_err());
464 let mut flipped = bytes.clone();
465 let at = flipped.len() - 3;
466 flipped[at] ^= 1;
467 assert!(store_stream(fresh.repo.store(), &flipped[..]).is_err());
468 // A changeset without its parent is refused.
469 let only_two = reachable(
470 from.repo.store(),
471 &Reach {
472 want: &[two],
473 history: Some(0),
474 ..Reach::default()
475 },
476 )
477 .unwrap();
478 assert!(only_two.iter().all(|object| object.id != one));
479 let mut partial = Vec::new();
480 StreamBody::new(from.repo.store(), &only_two)
481 .read_to_end(&mut partial)
482 .unwrap();
483 let err = store_stream(Fixture::new().repo.store(), &partial[..])
484 .unwrap_err()
485 .to_string();
486 assert!(err.contains("without"), "{err}");
487 }
488
489 #[test]
490 fn a_body_whose_object_vanished_fails() {
491 let f = Fixture::new();
492 let ghost = reached(5);
493 let mut body = StreamBody::new(f.repo.store(), std::slice::from_ref(&ghost));
494 let mut out = Vec::new();
495 assert!(body.read_to_end(&mut out).is_err());
496 }
497}