Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 31.9 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The hub client when the hub, or the way to it, fails. A fault at any
5//! step of a landing leaves the local repository and the workspace as they
6//! were, or where the hub is, says what to run next, and running the same
7//! landing again finishes the job. An answer that does not hold the stack
8//! it claims to hold, an outcome the protocol does not have, an edit made
9//! while a landing is in flight, an object stream with a hole, and a
10//! damaged credentials file each fail without losing anything and without
11//! showing a token.
12//!
13//! The hub is [`FakeHub`] behind [`Faulty`], a [`Remote`] that fails as it
14//! is told: the `nth` call of a route, before the hub does anything or
15//! after the call took effect (objects stored, a stack landed), as when an
16//! answer is lost on its way back.
17
18use std::cell::{Cell, RefCell};
19use std::collections::BTreeMap;
20use std::fs;
21use std::io::{Cursor, Read};
22use std::path::{Path, PathBuf};
23
24use anyhow::Result;
25use braid_engine::read_changeset;
26use braid_format::{Kind, ObjectId, Objects};
27use braid_hubproto::api::{LandRequest, LandResponse, MissingRequest, Refs, RepoInfo};
28use braid_hubproto::{Token, stream};
29use braid_repo::Repo;
30use braid_wc::{CommitRequest, Workspace};
31
32use super::creds::{Credentials, HubEnv, hub_url};
33use super::fetch::fetch;
34use super::land::{HubLanding, land_change, land_workspace};
35use super::remote::{HubError, Remote};
36use super::testing::{FakeHub, Fixture, ada, ada_change, set_ref};
37
38/// A route of the hub, as [`Remote`] names them.
39#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
40enum Route {
41 Refs,
42 Info,
43 Kind,
44 Lacks,
45 Objects,
46 Missing,
47 Land,
48}
49
50/// When a fault strikes: before the hub does anything, or once the call
51/// took effect, as when the answer is lost on its way back.
52#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53enum When {
54 Before,
55 After,
56}
57
58/// How a call fails.
59#[derive(Clone, Copy, Debug, PartialEq, Eq)]
60enum Failure {
61 /// The connection broke.
62 Transport,
63 /// 500 `internal`.
64 Internal,
65 /// 502 from a proxy in front of the hub, with its HTML page.
66 ProxyPage,
67 /// 429 `rate_limited`, to try again in a second.
68 RateLimited,
69 /// 401 `unauthorized`: the token was revoked meanwhile.
70 Unauthorized,
71}
72
73const FAILURES: [Failure; 5] = [
74 Failure::Transport,
75 Failure::Internal,
76 Failure::ProxyPage,
77 Failure::RateLimited,
78 Failure::Unauthorized,
79];
80
81impl Failure {
82 fn error(self) -> HubError {
83 match self {
84 Failure::Transport => HubError::Transport {
85 hub: "http://127.0.0.1:9".to_owned(),
86 detail: "io: Connection reset by peer (os error 54)".to_owned(),
87 },
88 Failure::Internal => HubError::api(500, "internal", "the hub failed"),
89 Failure::ProxyPage => HubError::api(
90 502,
91 "http_502",
92 "<html><head><title>502 Bad Gateway</title></head><body><center>502 Bad Gateway</center></body></html>",
93 ),
94 Failure::RateLimited => {
95 let mut err = HubError::api(429, "rate_limited", "too many requests");
96 if let HubError::Api { body, .. } = &mut err {
97 body.retry_after = Some(1);
98 }
99 err
100 }
101 Failure::Unauthorized => HubError::api(401, "unauthorized", "the token was revoked"),
102 }
103 }
104}
105
106/// One fault: the `nth` call of `route` fails with `failure`, `when`.
107#[derive(Clone, Copy, Debug)]
108struct Fault {
109 route: Route,
110 nth: usize,
111 when: When,
112 failure: Failure,
113}
114
115/// A [`FakeHub`] that fails as told.
116struct Faulty<'h> {
117 hub: &'h FakeHub,
118 /// The fault to strike, if any.
119 fault: Cell<Option<Fault>>,
120 /// Whether it struck.
121 fired: Cell<bool>,
122 /// Calls of each route so far, faults included.
123 calls: RefCell<BTreeMap<Route, usize>>,
124 /// The largest upload body the hub takes; bigger ones are 413.
125 max_body: Cell<Option<u64>>,
126 /// Answers every landing with this, without landing anything.
127 answer: RefCell<Option<LandResponse>>,
128 /// Runs once the hub has landed a stack, before the answer goes back.
129 after_land: RefCell<Option<Box<dyn Fn() + 'h>>>,
130 /// Leaves the first blob out of every `missing` stream.
131 drop_blob: Cell<bool>,
132 /// The blob it left out last.
133 dropped: Cell<Option<ObjectId>>,
134}
135
136impl<'h> Faulty<'h> {
137 fn new(hub: &'h FakeHub) -> Faulty<'h> {
138 Faulty {
139 hub,
140 fault: Cell::new(None),
141 fired: Cell::new(false),
142 calls: RefCell::new(BTreeMap::new()),
143 max_body: Cell::new(None),
144 answer: RefCell::new(None),
145 after_land: RefCell::new(None),
146 drop_blob: Cell::new(false),
147 dropped: Cell::new(None),
148 }
149 }
150
151 /// Counts a call of `route`, and returns which call it is.
152 fn count(&self, route: Route) -> usize {
153 let mut calls = self.calls.borrow_mut();
154 let n = calls.entry(route).or_insert(0);
155 *n += 1;
156 *n
157 }
158
159 fn called(&self, route: Route) -> usize {
160 self.calls.borrow().get(&route).copied().unwrap_or(0)
161 }
162
163 /// The fault for the `nth` call of `route` at `when`, if one is set.
164 fn strike(&self, route: Route, nth: usize, when: When) -> Result<(), HubError> {
165 match self.fault.get() {
166 Some(fault) if fault.route == route && fault.nth == nth && fault.when == when => {
167 self.fired.set(true);
168 Err(fault.failure.error())
169 }
170 _ => Ok(()),
171 }
172 }
173
174 /// Runs `call` against the hub as the `nth` call of `route`, with the
175 /// fault around it.
176 fn around<T>(
177 &self,
178 route: Route,
179 call: impl FnOnce() -> Result<T, HubError>,
180 ) -> Result<T, HubError> {
181 let nth = self.count(route);
182 self.strike(route, nth, When::Before)?;
183 let answer = call()?;
184 self.strike(route, nth, When::After)?;
185 Ok(answer)
186 }
187}
188
189/// `bytes`, an object stream, without its first blob; and that blob.
190fn without_first_blob(bytes: &[u8]) -> (Vec<u8>, Option<ObjectId>) {
191 let mut writer = stream::Writer::new(Vec::new()).unwrap();
192 let mut dropped = None;
193 for record in stream::Reader::new(bytes, 1 << 30).unwrap() {
194 let record = record.unwrap();
195 if record.kind == Kind::Blob && dropped.is_none() {
196 dropped = Some(record.id);
197 continue;
198 }
199 writer
200 .object(record.kind, &record.id, &record.payload)
201 .unwrap();
202 }
203 (writer.finish().unwrap(), dropped)
204}
205
206impl Remote for Faulty<'_> {
207 fn refs(&self) -> Result<Refs, HubError> {
208 self.around(Route::Refs, || self.hub.refs())
209 }
210
211 fn info(&self) -> Result<RepoInfo, HubError> {
212 self.around(Route::Info, || self.hub.info())
213 }
214
215 fn kind(&self, id: &ObjectId) -> Result<Option<Kind>, HubError> {
216 self.around(Route::Kind, || self.hub.kind(id))
217 }
218
219 fn lacks(&self, ids: &[ObjectId]) -> Result<Vec<ObjectId>, HubError> {
220 self.around(Route::Lacks, || self.hub.lacks(ids))
221 }
222
223 fn send_objects(&self, body: &mut dyn Read, len: u64) -> Result<u64, HubError> {
224 if let Some(max) = self.max_body.get()
225 && len > max
226 {
227 return Err(HubError::api(
228 413,
229 "too_large",
230 format!("a body of {len} bytes is more than {max}"),
231 ));
232 }
233 self.around(Route::Objects, || self.hub.send_objects(body, len))
234 }
235
236 fn missing(&self, request: &MissingRequest) -> Result<Box<dyn Read + '_>, HubError> {
237 let mut bytes = self.around(Route::Missing, || {
238 let mut bytes = Vec::new();
239 self.hub.missing(request)?.read_to_end(&mut bytes)?;
240 Ok(bytes)
241 })?;
242 if self.drop_blob.get() {
243 let (cut, dropped) = without_first_blob(&bytes);
244 bytes = cut;
245 self.dropped.set(dropped);
246 }
247 Ok(Box::new(Cursor::new(bytes)))
248 }
249
250 fn land(&self, request: &LandRequest) -> Result<LandResponse, HubError> {
251 self.around(Route::Land, || {
252 if let Some(answer) = self.answer.borrow().clone() {
253 return Ok(answer);
254 }
255 let response = self.hub.land(request)?;
256 if let Some(hook) = &*self.after_land.borrow() {
257 hook();
258 }
259 Ok(response)
260 })
261 }
262
263 fn max_body(&self) -> u64 {
264 self.max_body.get().unwrap_or_else(|| self.hub.max_body())
265 }
266}
267
268/// A linked repository holding the hub's `main`, as [`land`](super::land)'s
269/// own tests set it up.
270struct Setup {
271 hub: FakeHub,
272 local: Fixture,
273}
274
275impl Setup {
276 fn new() -> Setup {
277 let hub = FakeHub::new();
278 let root = ada_change(
279 &hub.repo,
280 None,
281 &[("a.txt", "one\ntwo\nthree\n"), ("b.txt", "b\n")],
282 );
283 set_ref(&hub.repo, "main", root);
284 let local = Fixture::linked(&hub);
285 fetch(&local.repo, &hub, &local.link, "tester", None).unwrap();
286 Setup { hub, local }
287 }
288
289 fn workspace(&self, name: &str) -> Workspace<'_> {
290 let repo = &self.local.repo;
291 let head = repo.store().refs().unwrap().get("main");
292 let dir = Workspace::default_dir(repo, name);
293 Workspace::create(repo, name, &dir, head, "main").unwrap().0
294 }
295
296 fn hub_main(&self) -> Option<ObjectId> {
297 self.hub.repo.store().refs().unwrap().get("main")
298 }
299
300 fn local_main(&self) -> Option<ObjectId> {
301 self.local.repo.store().refs().unwrap().get("main")
302 }
303
304 /// Someone else lands on the hub's main: a new file, so that what lands
305 /// next is rebased.
306 fn move_hub(&self) -> ObjectId {
307 let theirs = ada_change(&self.hub.repo, self.hub_main(), &[("d.txt", "theirs\n")]);
308 set_ref(&self.hub.repo, "main", theirs);
309 theirs
310 }
311
312 fn land(&self, remote: &impl Remote, ws: &Workspace<'_>) -> Result<HubLanding> {
313 land_workspace(
314 &self.local.repo,
315 ws,
316 remote,
317 &self.local.link,
318 None,
319 "agent-1",
320 )
321 }
322}
323
324/// Writes `files` in the workspace and commits them with `message`.
325fn commit(ws: &Workspace<'_>, files: &[(&str, &str)], message: &str) -> ObjectId {
326 for (path, content) in files {
327 fs::write(ws.dir().join(path), content).unwrap();
328 }
329 ws.commit(&CommitRequest {
330 message: Some(message.as_bytes().to_vec()),
331 paths: Vec::new(),
332 author: None,
333 committer: ada(),
334 agent: "agent-1".to_owned(),
335 force: false,
336 })
337 .unwrap()
338 .changeset
339 .unwrap()
340}
341
342/// Every file of a directory, by path, with its bytes.
343fn files(dir: &Path) -> BTreeMap<PathBuf, Vec<u8>> {
344 fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<PathBuf, Vec<u8>>) {
345 for entry in fs::read_dir(dir).unwrap() {
346 let entry = entry.unwrap();
347 let path = entry.path();
348 if entry.file_type().unwrap().is_dir() {
349 walk(root, &path, out);
350 } else {
351 let name = path.strip_prefix(root).unwrap().to_path_buf();
352 out.insert(name, fs::read(&path).unwrap());
353 }
354 }
355 }
356 let mut out = BTreeMap::new();
357 walk(dir, dir, &mut out);
358 out
359}
360
361fn refs(repo: &Repo) -> BTreeMap<String, ObjectId> {
362 repo.store().refs().unwrap().as_map().clone()
363}
364
365/// What a landing that fails must leave as it was: every local ref, the
366/// workspace's base and its files.
367struct Snapshot {
368 refs: BTreeMap<String, ObjectId>,
369 base: Option<ObjectId>,
370 files: BTreeMap<PathBuf, Vec<u8>>,
371}
372
373impl Snapshot {
374 fn of(repo: &Repo, ws: &Workspace<'_>) -> Snapshot {
375 Snapshot {
376 refs: refs(repo),
377 base: ws.state().unwrap().base,
378 files: files(ws.dir()),
379 }
380 }
381
382 /// Asserts that every local ref is as it was, or names a changeset the
383 /// hub holds, and that the workspace did not move.
384 fn left_alone(&self, s: &Setup, ws: &Workspace<'_>, what: &str) {
385 for (name, id) in refs(&s.local.repo) {
386 if self.refs.get(&name) != Some(&id) {
387 assert!(
388 matches!(
389 s.hub.repo.store().stat(&id).unwrap(),
390 Some((Kind::Changeset, _))
391 ),
392 "{what}: {name} moved to {id}, which the hub does not hold"
393 );
394 }
395 }
396 assert_eq!(
397 ws.state().unwrap().base,
398 self.base,
399 "{what}: the base moved"
400 );
401 assert_eq!(files(ws.dir()), self.files, "{what}: the files changed");
402 }
403}
404
405/// How many changesets along the first parents of `head` have `message`.
406fn on_chain(repo: &Repo, head: Option<ObjectId>, message: &str) -> usize {
407 let store = repo.store();
408 let mut found = 0;
409 let mut current = head;
410 while let Some(id) = current {
411 let changeset = read_changeset(store, id).unwrap();
412 if changeset.message == message.as_bytes() {
413 found += 1;
414 }
415 current = changeset.parents.first().copied();
416 }
417 found
418}
419
420/// Four files of different content, each a body of its own under a limit
421/// of 1,024 bytes, so that an upload of them takes more than three bodies.
422fn change() -> Vec<(String, String)> {
423 (1..=4)
424 .map(|n| {
425 let line = format!("file {n}: the quick brown fox jumps over the lazy dog\n");
426 (format!("c{n}.txt"), line.repeat(16))
427 })
428 .collect()
429}
430
431/// [`commit`], with owned names and contents.
432fn commit_owned(ws: &Workspace<'_>, files: &[(String, String)], message: &str) -> ObjectId {
433 let files: Vec<(&str, &str)> = files
434 .iter()
435 .map(|(path, content)| (path.as_str(), content.as_str()))
436 .collect();
437 commit(ws, &files, message)
438}
439
440/// One landing with `fault` set, on a hub that took nothing meanwhile
441/// (`rebase` false) or that someone else landed on first; then the same
442/// landing again without it, then once more.
443fn one_fault(rebase: bool, fault: Fault) {
444 let what = format!(
445 "{} with {fault:?}",
446 if rebase { "a rebase" } else { "a fast-forward" }
447 );
448 let s = Setup::new();
449 let ws = s.workspace("w1");
450 let files = change();
451 let mine = commit_owned(&ws, &files, "the change");
452 if rebase {
453 s.move_hub();
454 }
455 let faulty = Faulty::new(&s.hub);
456 faulty.max_body.set(Some(1024));
457 faulty.fault.set(Some(fault));
458 let before = Snapshot::of(&s.local.repo, &ws);
459
460 let err = match s.land(&faulty, &ws) {
461 Ok(landing) => panic!("{what}: landed anyway: {landing:?}"),
462 Err(err) => format!("{err:#}"),
463 };
464 assert!(faulty.fired.get(), "{what}: the fault never struck");
465 assert!(
466 err.contains("braid land") || err.contains("braid update"),
467 "{what}: the error names no command to run next: {err}"
468 );
469 before.left_alone(&s, &ws, &what);
470 let hub_landed = matches!(
471 (fault.route, fault.nth, fault.when),
472 (Route::Land, _, When::After) | (Route::Refs, 2, _) | (Route::Missing, 2, _)
473 );
474 let hub_before = s.hub_main();
475 assert_eq!(
476 on_chain(&s.hub.repo, hub_before, "the change"),
477 usize::from(hub_landed),
478 "{what}: the hub's main"
479 );
480
481 // The same landing again finishes the job.
482 faulty.fault.set(None);
483 let again = s
484 .land(&faulty, &ws)
485 .unwrap_or_else(|err| panic!("{what}: landing again failed: {err:#}"));
486 let outcome = again.response.as_ref().map(|r| r.outcome.as_str());
487 let expected = match (hub_landed, rebase) {
488 (false, false) => Some("fast-forward"),
489 (false, true) => Some("rebased"),
490 (true, false) => None,
491 (true, true) => Some("already-applied"),
492 };
493 assert_eq!(outcome, expected, "{what}: landing again: {again:?}");
494 let head = s.hub_main();
495 assert_eq!(
496 on_chain(&s.hub.repo, head, "the change"),
497 1,
498 "{what}: the change is on the hub's main once"
499 );
500 assert_eq!(s.local_main(), head, "{what}: the local main");
501 assert_eq!(ws.state().unwrap().base, head, "{what}: the workspace");
502 if !rebase {
503 assert_eq!(head, Some(mine), "{what}");
504 }
505 for (path, content) in &files {
506 assert_eq!(
507 &fs::read_to_string(ws.dir().join(path)).unwrap(),
508 content,
509 "{what}"
510 );
511 }
512
513 // And once more: nothing to land, and nothing is asked of the hub.
514 let lands = faulty.called(Route::Land);
515 let third = s.land(&faulty, &ws).unwrap();
516 assert!(third.response.is_none(), "{what}: {third:?}");
517 assert_eq!(faulty.called(Route::Land), lands, "{what}");
518}
519
520#[test]
521fn a_fault_at_any_step_of_a_landing_leaves_nothing_half_way() {
522 let rows = [
523 (Route::Refs, 1, When::Before),
524 (Route::Missing, 1, When::Before),
525 (Route::Lacks, 1, When::Before),
526 (Route::Objects, 1, When::Before),
527 (Route::Objects, 3, When::After),
528 (Route::Land, 1, When::Before),
529 (Route::Land, 1, When::After),
530 (Route::Refs, 2, When::Before),
531 (Route::Missing, 2, When::Before),
532 ];
533 for rebase in [false, true] {
534 for (route, nth, when) in rows {
535 // A fast-forward needs nothing from the hub: no `missing` call.
536 if !rebase && route == Route::Missing {
537 continue;
538 }
539 for failure in FAILURES {
540 one_fault(
541 rebase,
542 Fault {
543 route,
544 nth,
545 when,
546 failure,
547 },
548 );
549 }
550 }
551 }
552}
553
554/// A landing whose answer was lost after the hub fast-forwarded, landed
555/// again, leaves the workspace ready for the next one: what it lands next
556/// is its new changeset alone.
557#[test]
558fn after_a_lost_answer_the_next_landing_takes_only_what_is_new() {
559 for nth_refs in [None, Some(2)] {
560 let s = Setup::new();
561 let ws = s.workspace("w1");
562 let first = commit(&ws, &[("c.txt", "c\n")], "first");
563 let faulty = Faulty::new(&s.hub);
564 faulty.fault.set(Some(match nth_refs {
565 None => Fault {
566 route: Route::Land,
567 nth: 1,
568 when: When::After,
569 failure: Failure::Transport,
570 },
571 Some(nth) => Fault {
572 route: Route::Refs,
573 nth,
574 when: When::Before,
575 failure: Failure::ProxyPage,
576 },
577 }));
578 assert!(s.land(&faulty, &ws).is_err());
579 faulty.fault.set(None);
580 assert!(s.land(&faulty, &ws).unwrap().response.is_none());
581 assert_eq!(ws.state().unwrap().base, Some(first));
582
583 let second = commit(&ws, &[("e.txt", "e\n")], "second");
584 s.move_hub();
585 let landing = s.land(&faulty, &ws).unwrap();
586 let response = landing.response.unwrap();
587 assert_eq!(response.outcome, "rebased", "{response:?}");
588 let froms: Vec<ObjectId> = response.landed.iter().map(|p| p.from).collect();
589 assert_eq!(froms, [second], "only the new changeset goes up");
590 assert_eq!(on_chain(&s.hub.repo, s.hub_main(), "first"), 1);
591 assert_eq!(on_chain(&s.hub.repo, s.hub_main(), "second"), 1);
592 }
593}
594
595/// An answer that says the stack landed, with a head that does not hold
596/// it, moves nothing: not the workspace, its files, nor the local branch.
597#[test]
598fn an_answer_whose_head_lacks_the_stack_moves_nothing() {
599 for outcome in ["already-applied", "fast-forward", "rebased"] {
600 let s = Setup::new();
601 let ws = s.workspace("w1");
602 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
603 let hub_main = s.hub_main().unwrap();
604 // Someone else's changeset, on no branch of the hub.
605 let unrelated = ada_change(&s.hub.repo, None, &[("x.txt", "unrelated\n")]);
606 let head = if outcome == "rebased" {
607 unrelated
608 } else {
609 hub_main
610 };
611 let faulty = Faulty::new(&s.hub);
612 *faulty.answer.borrow_mut() = Some(LandResponse {
613 reference: "main".to_owned(),
614 outcome: outcome.to_owned(),
615 head_before: Some(hub_main),
616 head: Some(head),
617 landed: Vec::new(),
618 merged_paths: Vec::new(),
619 conflicts: Vec::new(),
620 change: None,
621 git_commit: None,
622 operation: Some(7),
623 });
624 let before = Snapshot::of(&s.local.repo, &ws);
625 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
626 assert!(err.contains("does not hold"), "{outcome}: {err}");
627 assert!(err.contains(&head.short()), "{outcome}: {err}");
628 assert_eq!(ws.state().unwrap().base, Some(mine), "{outcome}");
629 assert_eq!(
630 fs::read_to_string(ws.dir().join("c.txt")).unwrap(),
631 "c\n",
632 "{outcome}"
633 );
634 assert_eq!(refs(&s.local.repo), before.refs, "{outcome}");
635 before.left_alone(&s, &ws, outcome);
636
637 // The hub's real answer lands it, once.
638 *faulty.answer.borrow_mut() = None;
639 let landing = s.land(&faulty, &ws).unwrap();
640 assert_eq!(landing.response.unwrap().outcome, "fast-forward");
641 assert_eq!(s.hub_main(), Some(mine));
642 assert_eq!(on_chain(&s.hub.repo, s.hub_main(), "edit c.txt"), 1);
643 assert_eq!(ws.state().unwrap().base, Some(mine));
644 }
645}
646
647/// The same for a stack that carries a changeset landed here with
648/// `--local`: the local branch, which is that changeset, does not follow a
649/// head that lacks it.
650#[test]
651fn a_head_that_lacks_a_local_changeset_does_not_take_the_branch_back() {
652 let s = Setup::new();
653 let w1 = s.workspace("w1");
654 let local_only = commit(&w1, &[("local.txt", "l\n")], "landed here");
655 w1.land(None, "agent-1", &ada()).unwrap();
656 assert_eq!(s.local_main(), Some(local_only));
657 let w2 = s.workspace("w2");
658 let mine = commit(&w2, &[("c.txt", "c\n")], "edit c.txt");
659 let hub_main = s.hub_main().unwrap();
660 let faulty = Faulty::new(&s.hub);
661 *faulty.answer.borrow_mut() = Some(LandResponse {
662 reference: "main".to_owned(),
663 outcome: "rebased".to_owned(),
664 head_before: Some(hub_main),
665 head: Some(hub_main),
666 landed: Vec::new(),
667 merged_paths: Vec::new(),
668 conflicts: Vec::new(),
669 change: None,
670 git_commit: None,
671 operation: Some(7),
672 });
673 let err = format!("{:#}", s.land(&faulty, &w2).unwrap_err());
674 assert!(err.contains("does not hold"), "{err}");
675 assert_eq!(s.local_main(), Some(local_only), "the branch stayed");
676 assert_eq!(w2.state().unwrap().base, Some(mine));
677
678 *faulty.answer.borrow_mut() = None;
679 let landing = s.land(&faulty, &w2).unwrap();
680 let response = landing.response.unwrap();
681 assert_eq!(response.outcome, "fast-forward");
682 let froms: Vec<ObjectId> = response.landed.iter().map(|p| p.from).collect();
683 assert_eq!(froms, [local_only, mine]);
684 assert_eq!(s.local_main(), Some(mine));
685}
686
687/// An outcome a landing in rebase mode never has (`refused`), or one the
688/// protocol does not know, is an error that names it: nothing moved.
689#[test]
690fn a_refused_or_unknown_outcome_is_an_error() {
691 for outcome in ["refused", "queued"] {
692 let s = Setup::new();
693 let ws = s.workspace("w1");
694 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
695 let hub_main = s.hub_main().unwrap();
696 let faulty = Faulty::new(&s.hub);
697 *faulty.answer.borrow_mut() = Some(LandResponse {
698 reference: "main".to_owned(),
699 outcome: outcome.to_owned(),
700 head_before: Some(hub_main),
701 head: Some(hub_main),
702 landed: Vec::new(),
703 merged_paths: Vec::new(),
704 conflicts: Vec::new(),
705 change: None,
706 git_commit: None,
707 operation: None,
708 });
709 let before = Snapshot::of(&s.local.repo, &ws);
710 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
711 assert!(
712 err.contains(outcome) && err.contains("did not land"),
713 "{outcome}: {err}"
714 );
715 assert_eq!(ws.state().unwrap().base, Some(mine));
716 assert_eq!(refs(&s.local.repo), before.refs, "{outcome}");
717 before.left_alone(&s, &ws, outcome);
718
719 // `change create --land` too, naming the changeset.
720 let change = ada_change(&s.local.repo, Some(hub_main), &[("n.txt", "n\n")]);
721 let err = format!(
722 "{:#}",
723 land_change(
724 &s.local.repo,
725 &faulty,
726 &s.local.link,
727 "main",
728 change,
729 "agent-1",
730 "braid change create"
731 )
732 .unwrap_err()
733 );
734 assert!(
735 err.contains(outcome) && err.contains(&change.to_hex()) && err.contains("did not land"),
736 "{outcome}: {err}"
737 );
738 assert_eq!(s.local_main(), Some(hub_main));
739 }
740}
741
742/// A file edited in the workspace while a fast-forward is in flight: the
743/// landing went through and says so, the edit stays, and the next landing
744/// takes only the changeset that records it.
745#[test]
746fn an_edit_during_a_fast_forward_stays_and_lands_next() {
747 let s = Setup::new();
748 let ws = s.workspace("w1");
749 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
750 let faulty = Faulty::new(&s.hub);
751 let dir = ws.dir().to_path_buf();
752 *faulty.after_land.borrow_mut() = Some(Box::new(move || {
753 fs::write(dir.join("e.txt"), "edited meanwhile\n").unwrap();
754 }));
755 let landing = s.land(&faulty, &ws).unwrap();
756 assert_eq!(landing.response.as_ref().unwrap().outcome, "fast-forward");
757 assert_eq!(landing.base, Some(mine));
758 assert_eq!(s.hub_main(), Some(mine));
759 assert_eq!(s.local_main(), Some(mine));
760 assert_eq!(
761 fs::read_to_string(ws.dir().join("e.txt")).unwrap(),
762 "edited meanwhile\n"
763 );
764 *faulty.after_land.borrow_mut() = None;
765
766 let edit = commit(&ws, &[], "record the edit");
767 let landing = s.land(&faulty, &ws).unwrap();
768 let response = landing.response.unwrap();
769 assert_eq!(response.outcome, "fast-forward");
770 let froms: Vec<ObjectId> = response.landed.iter().map(|p| p.from).collect();
771 assert_eq!(froms, [edit]);
772 assert_eq!(s.hub_main(), Some(edit));
773}
774
775/// The same while a rebase is in flight: the workspace cannot move onto the
776/// rebased head without losing the edit, so it stays, and the error says
777/// that the change landed, where, and what to do; committing and landing
778/// again finishes it, with every change on the hub once.
779#[test]
780fn an_edit_during_a_rebase_stays_and_the_error_says_what_landed() {
781 let s = Setup::new();
782 let ws = s.workspace("w1");
783 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
784 s.move_hub();
785 let faulty = Faulty::new(&s.hub);
786 let dir = ws.dir().to_path_buf();
787 *faulty.after_land.borrow_mut() = Some(Box::new(move || {
788 fs::write(dir.join("e.txt"), "edited meanwhile\n").unwrap();
789 }));
790 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
791 let head = s.hub_main().unwrap();
792 assert!(
793 err.contains(&head.short()) && err.contains("landed") && err.contains("braid land"),
794 "{err}"
795 );
796 assert_eq!(ws.state().unwrap().base, Some(mine));
797 assert_eq!(
798 fs::read_to_string(ws.dir().join("e.txt")).unwrap(),
799 "edited meanwhile\n"
800 );
801 assert!(!ws.dir().join("d.txt").exists());
802 *faulty.after_land.borrow_mut() = None;
803
804 commit(&ws, &[], "record the edit");
805 let landing = s.land(&faulty, &ws).unwrap();
806 assert_eq!(landing.response.unwrap().outcome, "rebased");
807 let head = s.hub_main();
808 assert_eq!(on_chain(&s.hub.repo, head, "edit c.txt"), 1);
809 assert_eq!(on_chain(&s.hub.repo, head, "record the edit"), 1);
810 assert_eq!(ws.state().unwrap().base, head);
811 assert_eq!(s.local_main(), head);
812 assert_eq!(
813 fs::read_to_string(ws.dir().join("d.txt")).unwrap(),
814 "theirs\n"
815 );
816}
817
818/// An object stream that leaves out a blob a tree names moves no ref; the
819/// next fetch, with the whole stream, brings everything.
820#[test]
821fn a_stream_with_a_hole_moves_no_ref_and_the_next_fetch_heals_it() {
822 let s = Setup::new();
823 let theirs = s.move_hub();
824 let faulty = Faulty::new(&s.hub);
825 faulty.drop_blob.set(true);
826 let before = refs(&s.local.repo);
827 let err = format!(
828 "{:#}",
829 fetch(&s.local.repo, &faulty, &s.local.link, "tester", None).unwrap_err()
830 );
831 let dropped = faulty.dropped.get().expect("a blob was left out");
832 assert!(err.contains(&dropped.to_hex()), "{err}");
833 assert_eq!(refs(&s.local.repo), before);
834
835 // The first fetch of a landing too: nothing moves, the workspace stays.
836 let ws = s.workspace("w1");
837 commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
838 let snapshot = Snapshot::of(&s.local.repo, &ws);
839 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
840 assert!(err.contains("--local"), "{err}");
841 assert_eq!(refs(&s.local.repo), snapshot.refs);
842 snapshot.left_alone(&s, &ws, "landing");
843
844 faulty.drop_blob.set(false);
845 fetch(&s.local.repo, &faulty, &s.local.link, "tester", None).unwrap();
846 assert_eq!(s.local_main(), Some(theirs));
847 assert!(s.local.repo.store().contains(&dropped).unwrap());
848 assert!(s.local.repo.store().fsck().unwrap().is_clean());
849}
850
851/// A credentials file damaged in a way that puts the token where serde
852/// quotes what it found: the error names the file and what to do, and
853/// shows no part of the token.
854#[test]
855fn a_damaged_credentials_file_never_shows_the_token() {
856 let token = Token::from_random([7; 5], [9; 32]).expose();
857 let secret = &token["brd_".len() + 8 + 1..];
858 assert_eq!(secret.len(), 52);
859 let url = "https://hub.example.org";
860 let shows_none = |err: &str, what: &str| {
861 assert!(!err.contains(&token), "{what}: {err}");
862 for start in 0..=secret.len() - 16 {
863 let run = &secret[start..start + 16];
864 assert!(
865 !err.contains(run),
866 "{what}: part of the secret shows: {err}"
867 );
868 }
869 };
870 let variants = [
871 serde_json::json!({ "hubs": { url: token } }).to_string(),
872 serde_json::json!({ "hubs": token }).to_string(),
873 serde_json::json!({ "autopublish": token }).to_string(),
874 serde_json::json!({ "default": token }).to_string(),
875 serde_json::json!({ "default": url, "hubs": { url: { "token": token, "login": 7 } } })
876 .to_string(),
877 format!("{{\"hubs\": {{\"{url}\": {{\"token\": \"{token}\""),
878 format!("{{\"hubs\": {{\"{url}\": {{\"token\": \"{token}\"}}}}, {token}"),
879 ];
880 let dir = tempfile::tempdir().unwrap();
881 let path = dir.path().join("hub.json");
882 for text in &variants {
883 fs::write(&path, text).unwrap();
884 let err = format!("{:#}", Credentials::load(&path).unwrap_err());
885 assert!(
886 err.contains(&path.display().to_string()) && err.contains("fix it, or remove it"),
887 "{text}: {err}"
888 );
889 shows_none(&err, text);
890 }
891
892 // A token where the hub's URL goes, in the file or in BRAID_HUB_URL,
893 // is refused without being repeated.
894 let creds = Credentials {
895 default: Some(token.clone()),
896 ..Credentials::default()
897 };
898 let err = format!(
899 "{:#}",
900 hub_url(&HubEnv::default(), &creds, None).unwrap_err()
901 );
902 assert!(err.contains("not a hub URL"), "{err}");
903 shows_none(&err, "default");
904 let env = HubEnv {
905 url: Some(format!(" {token} ")),
906 ..HubEnv::default()
907 };
908 let err = format!(
909 "{:#}",
910 hub_url(&env, &Credentials::default(), None).unwrap_err()
911 );
912 assert!(err.contains("not a hub URL"), "{err}");
913 shows_none(&err, "BRAID_HUB_URL");
914 let err = format!(
915 "{:#}",
916 hub_url(&HubEnv::default(), &Credentials::default(), Some(&token)).unwrap_err()
917 );
918 shows_none(&err, "--hub");
919}