Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 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 verify: None,
624 });
625 let before = Snapshot::of(&s.local.repo, &ws);
626 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
627 assert!(err.contains("does not hold"), "{outcome}: {err}");
628 assert!(err.contains(&head.short()), "{outcome}: {err}");
629 assert_eq!(ws.state().unwrap().base, Some(mine), "{outcome}");
630 assert_eq!(
631 fs::read_to_string(ws.dir().join("c.txt")).unwrap(),
632 "c\n",
633 "{outcome}"
634 );
635 assert_eq!(refs(&s.local.repo), before.refs, "{outcome}");
636 before.left_alone(&s, &ws, outcome);
637
638 // The hub's real answer lands it, once.
639 *faulty.answer.borrow_mut() = None;
640 let landing = s.land(&faulty, &ws).unwrap();
641 assert_eq!(landing.response.unwrap().outcome, "fast-forward");
642 assert_eq!(s.hub_main(), Some(mine));
643 assert_eq!(on_chain(&s.hub.repo, s.hub_main(), "edit c.txt"), 1);
644 assert_eq!(ws.state().unwrap().base, Some(mine));
645 }
646}
647
648/// The same for a stack that carries a changeset landed here with
649/// `--local`: the local branch, which is that changeset, does not follow a
650/// head that lacks it.
651#[test]
652fn a_head_that_lacks_a_local_changeset_does_not_take_the_branch_back() {
653 let s = Setup::new();
654 let w1 = s.workspace("w1");
655 let local_only = commit(&w1, &[("local.txt", "l\n")], "landed here");
656 w1.land(None, "agent-1", &ada()).unwrap();
657 assert_eq!(s.local_main(), Some(local_only));
658 let w2 = s.workspace("w2");
659 let mine = commit(&w2, &[("c.txt", "c\n")], "edit c.txt");
660 let hub_main = s.hub_main().unwrap();
661 let faulty = Faulty::new(&s.hub);
662 *faulty.answer.borrow_mut() = Some(LandResponse {
663 reference: "main".to_owned(),
664 outcome: "rebased".to_owned(),
665 head_before: Some(hub_main),
666 head: Some(hub_main),
667 landed: Vec::new(),
668 merged_paths: Vec::new(),
669 conflicts: Vec::new(),
670 change: None,
671 git_commit: None,
672 operation: Some(7),
673 verify: None,
674 });
675 let err = format!("{:#}", s.land(&faulty, &w2).unwrap_err());
676 assert!(err.contains("does not hold"), "{err}");
677 assert_eq!(s.local_main(), Some(local_only), "the branch stayed");
678 assert_eq!(w2.state().unwrap().base, Some(mine));
679
680 *faulty.answer.borrow_mut() = None;
681 let landing = s.land(&faulty, &w2).unwrap();
682 let response = landing.response.unwrap();
683 assert_eq!(response.outcome, "fast-forward");
684 let froms: Vec<ObjectId> = response.landed.iter().map(|p| p.from).collect();
685 assert_eq!(froms, [local_only, mine]);
686 assert_eq!(s.local_main(), Some(mine));
687}
688
689/// An outcome a landing in rebase mode never has (`refused`), or one the
690/// protocol does not know, is an error that names it: nothing moved.
691#[test]
692fn a_refused_or_unknown_outcome_is_an_error() {
693 for outcome in ["refused", "queued"] {
694 let s = Setup::new();
695 let ws = s.workspace("w1");
696 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
697 let hub_main = s.hub_main().unwrap();
698 let faulty = Faulty::new(&s.hub);
699 *faulty.answer.borrow_mut() = Some(LandResponse {
700 reference: "main".to_owned(),
701 outcome: outcome.to_owned(),
702 head_before: Some(hub_main),
703 head: Some(hub_main),
704 landed: Vec::new(),
705 merged_paths: Vec::new(),
706 conflicts: Vec::new(),
707 change: None,
708 git_commit: None,
709 operation: None,
710 verify: None,
711 });
712 let before = Snapshot::of(&s.local.repo, &ws);
713 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
714 assert!(
715 err.contains(outcome) && err.contains("did not land"),
716 "{outcome}: {err}"
717 );
718 assert_eq!(ws.state().unwrap().base, Some(mine));
719 assert_eq!(refs(&s.local.repo), before.refs, "{outcome}");
720 before.left_alone(&s, &ws, outcome);
721
722 // `change create --land` too, naming the changeset.
723 let change = ada_change(&s.local.repo, Some(hub_main), &[("n.txt", "n\n")]);
724 let err = format!(
725 "{:#}",
726 land_change(
727 &s.local.repo,
728 &faulty,
729 &s.local.link,
730 "main",
731 change,
732 "agent-1",
733 "braid change create"
734 )
735 .unwrap_err()
736 );
737 assert!(
738 err.contains(outcome) && err.contains(&change.to_hex()) && err.contains("did not land"),
739 "{outcome}: {err}"
740 );
741 assert_eq!(s.local_main(), Some(hub_main));
742 }
743}
744
745/// A file edited in the workspace while a fast-forward is in flight: the
746/// landing went through and says so, the edit stays, and the next landing
747/// takes only the changeset that records it.
748#[test]
749fn an_edit_during_a_fast_forward_stays_and_lands_next() {
750 let s = Setup::new();
751 let ws = s.workspace("w1");
752 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
753 let faulty = Faulty::new(&s.hub);
754 let dir = ws.dir().to_path_buf();
755 *faulty.after_land.borrow_mut() = Some(Box::new(move || {
756 fs::write(dir.join("e.txt"), "edited meanwhile\n").unwrap();
757 }));
758 let landing = s.land(&faulty, &ws).unwrap();
759 assert_eq!(landing.response.as_ref().unwrap().outcome, "fast-forward");
760 assert_eq!(landing.base, Some(mine));
761 assert_eq!(s.hub_main(), Some(mine));
762 assert_eq!(s.local_main(), Some(mine));
763 assert_eq!(
764 fs::read_to_string(ws.dir().join("e.txt")).unwrap(),
765 "edited meanwhile\n"
766 );
767 *faulty.after_land.borrow_mut() = None;
768
769 let edit = commit(&ws, &[], "record the edit");
770 let landing = s.land(&faulty, &ws).unwrap();
771 let response = landing.response.unwrap();
772 assert_eq!(response.outcome, "fast-forward");
773 let froms: Vec<ObjectId> = response.landed.iter().map(|p| p.from).collect();
774 assert_eq!(froms, [edit]);
775 assert_eq!(s.hub_main(), Some(edit));
776}
777
778/// The same while a rebase is in flight: the workspace cannot move onto the
779/// rebased head without losing the edit, so it stays, and the error says
780/// that the change landed, where, and what to do; committing and landing
781/// again finishes it, with every change on the hub once.
782#[test]
783fn an_edit_during_a_rebase_stays_and_the_error_says_what_landed() {
784 let s = Setup::new();
785 let ws = s.workspace("w1");
786 let mine = commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
787 s.move_hub();
788 let faulty = Faulty::new(&s.hub);
789 let dir = ws.dir().to_path_buf();
790 *faulty.after_land.borrow_mut() = Some(Box::new(move || {
791 fs::write(dir.join("e.txt"), "edited meanwhile\n").unwrap();
792 }));
793 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
794 let head = s.hub_main().unwrap();
795 assert!(
796 err.contains(&head.short()) && err.contains("landed") && err.contains("braid land"),
797 "{err}"
798 );
799 assert_eq!(ws.state().unwrap().base, Some(mine));
800 assert_eq!(
801 fs::read_to_string(ws.dir().join("e.txt")).unwrap(),
802 "edited meanwhile\n"
803 );
804 assert!(!ws.dir().join("d.txt").exists());
805 *faulty.after_land.borrow_mut() = None;
806
807 commit(&ws, &[], "record the edit");
808 let landing = s.land(&faulty, &ws).unwrap();
809 assert_eq!(landing.response.unwrap().outcome, "rebased");
810 let head = s.hub_main();
811 assert_eq!(on_chain(&s.hub.repo, head, "edit c.txt"), 1);
812 assert_eq!(on_chain(&s.hub.repo, head, "record the edit"), 1);
813 assert_eq!(ws.state().unwrap().base, head);
814 assert_eq!(s.local_main(), head);
815 assert_eq!(
816 fs::read_to_string(ws.dir().join("d.txt")).unwrap(),
817 "theirs\n"
818 );
819}
820
821/// An object stream that leaves out a blob a tree names moves no ref; the
822/// next fetch, with the whole stream, brings everything.
823#[test]
824fn a_stream_with_a_hole_moves_no_ref_and_the_next_fetch_heals_it() {
825 let s = Setup::new();
826 let theirs = s.move_hub();
827 let faulty = Faulty::new(&s.hub);
828 faulty.drop_blob.set(true);
829 let before = refs(&s.local.repo);
830 let err = format!(
831 "{:#}",
832 fetch(&s.local.repo, &faulty, &s.local.link, "tester", None).unwrap_err()
833 );
834 let dropped = faulty.dropped.get().expect("a blob was left out");
835 assert!(err.contains(&dropped.to_hex()), "{err}");
836 assert_eq!(refs(&s.local.repo), before);
837
838 // The first fetch of a landing too: nothing moves, the workspace stays.
839 let ws = s.workspace("w1");
840 commit(&ws, &[("c.txt", "c\n")], "edit c.txt");
841 let snapshot = Snapshot::of(&s.local.repo, &ws);
842 let err = format!("{:#}", s.land(&faulty, &ws).unwrap_err());
843 assert!(err.contains("--local"), "{err}");
844 assert_eq!(refs(&s.local.repo), snapshot.refs);
845 snapshot.left_alone(&s, &ws, "landing");
846
847 faulty.drop_blob.set(false);
848 fetch(&s.local.repo, &faulty, &s.local.link, "tester", None).unwrap();
849 assert_eq!(s.local_main(), Some(theirs));
850 assert!(s.local.repo.store().contains(&dropped).unwrap());
851 assert!(s.local.repo.store().fsck().unwrap().is_clean());
852}
853
854/// A credentials file damaged in a way that puts the token where serde
855/// quotes what it found: the error names the file and what to do, and
856/// shows no part of the token.
857#[test]
858fn a_damaged_credentials_file_never_shows_the_token() {
859 let token = Token::from_random([7; 5], [9; 32]).expose();
860 let secret = &token["brd_".len() + 8 + 1..];
861 assert_eq!(secret.len(), 52);
862 let url = "https://hub.example.org";
863 let shows_none = |err: &str, what: &str| {
864 assert!(!err.contains(&token), "{what}: {err}");
865 for start in 0..=secret.len() - 16 {
866 let run = &secret[start..start + 16];
867 assert!(
868 !err.contains(run),
869 "{what}: part of the secret shows: {err}"
870 );
871 }
872 };
873 let variants = [
874 serde_json::json!({ "hubs": { url: token } }).to_string(),
875 serde_json::json!({ "hubs": token }).to_string(),
876 serde_json::json!({ "autopublish": token }).to_string(),
877 serde_json::json!({ "default": token }).to_string(),
878 serde_json::json!({ "default": url, "hubs": { url: { "token": token, "login": 7 } } })
879 .to_string(),
880 format!("{{\"hubs\": {{\"{url}\": {{\"token\": \"{token}\""),
881 format!("{{\"hubs\": {{\"{url}\": {{\"token\": \"{token}\"}}}}, {token}"),
882 ];
883 let dir = tempfile::tempdir().unwrap();
884 let path = dir.path().join("hub.json");
885 for text in &variants {
886 fs::write(&path, text).unwrap();
887 let err = format!("{:#}", Credentials::load(&path).unwrap_err());
888 assert!(
889 err.contains(&path.display().to_string()) && err.contains("fix it, or remove it"),
890 "{text}: {err}"
891 );
892 shows_none(&err, text);
893 }
894
895 // A token where the hub's URL goes, in the file or in BRAID_HUB_URL,
896 // is refused without being repeated.
897 let creds = Credentials {
898 default: Some(token.clone()),
899 ..Credentials::default()
900 };
901 let err = format!(
902 "{:#}",
903 hub_url(&HubEnv::default(), &creds, None).unwrap_err()
904 );
905 assert!(err.contains("not a hub URL"), "{err}");
906 shows_none(&err, "default");
907 let env = HubEnv {
908 url: Some(format!(" {token} ")),
909 ..HubEnv::default()
910 };
911 let err = format!(
912 "{:#}",
913 hub_url(&env, &Credentials::default(), None).unwrap_err()
914 );
915 assert!(err.contains("not a hub URL"), "{err}");
916 shows_none(&err, "BRAID_HUB_URL");
917 let err = format!(
918 "{:#}",
919 hub_url(&HubEnv::default(), &Credentials::default(), Some(&token)).unwrap_err()
920 );
921 shows_none(&err, "--hub");
922}