Elffuss BraidHub

utopia-ia/elffuss-braid public

2da7deeea818 · 11.3 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! What the hub client's tests share: repositories in temporary
5//! directories, and a hub in memory that answers the [`Remote`] calls the
6//! way `docs/hub.md` says, landing with [`land_stack`] as a hub does. No
7//! HTTP is involved.
8
9use std::cell::{Cell, RefCell};
10use std::convert::Infallible;
11use std::io::{Cursor, Read};
12
13use braid_engine::{Error as EngineError, Reach, reachable};
14use braid_format::{Kind, ObjectId, Objects};
15use braid_hubproto::api::{
16 LandMode, LandRequest, LandResponse, MissingRequest, Placed, Refs, RepoInfo,
17};
18use braid_hubproto::stream;
19use braid_repo::Repo;
20use braid_store::RefUpdate;
21use braid_wc::{ChangeRequest, Identity, LandReport, Landed, StackMode, land_stack};
22use tempfile::TempDir;
23
24use super::link::Link;
25use super::remote::{HubError, LACKS_BATCH, MAX_BODY, Remote};
26
27/// The identity tests sign with.
28pub(crate) fn ada() -> Identity {
29 Identity::new("Ada", "ada@example.org").unwrap()
30}
31
32/// A changeset on `base` setting each `(path, content)`, made durable.
33pub(crate) fn ada_change(repo: &Repo, base: Option<ObjectId>, sets: &[(&str, &str)]) -> ObjectId {
34 let id = braid_wc::create_change(
35 repo.store(),
36 &ChangeRequest {
37 base,
38 sets: sets
39 .iter()
40 .map(|(path, content)| (path.as_bytes().to_vec(), content.as_bytes().to_vec()))
41 .collect(),
42 deletes: Vec::new(),
43 expects: Vec::new(),
44 message: b"change\n".to_vec(),
45 author: ada(),
46 agent: "tester".to_owned(),
47 },
48 )
49 .unwrap();
50 repo.store().sync().unwrap();
51 id
52}
53
54/// Points `name` at `id`.
55pub(crate) fn set_ref(repo: &Repo, name: &str, id: ObjectId) {
56 repo.store()
57 .transact("tester", &format!("set {name}"), |refs| {
58 Ok::<_, Infallible>(vec![RefUpdate::new(name, refs.get(name), Some(id))])
59 })
60 .unwrap();
61}
62
63/// A repository in a temporary directory, and a link it may write.
64pub(crate) struct Fixture {
65 _dir: TempDir,
66 pub(crate) repo: Repo,
67 pub(crate) link: Link,
68}
69
70impl Fixture {
71 /// A new, empty repository.
72 pub(crate) fn new() -> Fixture {
73 let dir = tempfile::tempdir().unwrap();
74 let repo = Repo::init(dir.path()).unwrap();
75 Fixture {
76 _dir: dir,
77 repo,
78 link: Link {
79 url: "http://127.0.0.1:9".to_owned(),
80 repo: "ada/demo".parse().unwrap(),
81 paths: None,
82 },
83 }
84 }
85
86 /// A new, empty repository linked to the repository of `hub`.
87 pub(crate) fn linked(_hub: &FakeHub) -> Fixture {
88 let fixture = Fixture::new();
89 fixture.link.write(&fixture.repo).unwrap();
90 fixture
91 }
92}
93
94/// A hub in memory, holding one repository.
95pub(crate) struct FakeHub {
96 _dir: TempDir,
97 /// The repository: its store and refs are the hub's.
98 pub(crate) repo: Repo,
99 /// Claims to store everything, so that uploads send nothing and a
100 /// landing finds objects missing.
101 pub(crate) forgetful: Cell<bool>,
102 /// Answers every landing with `not_on_branch`.
103 pub(crate) off_branch: Cell<bool>,
104 /// The routes called, in order.
105 pub(crate) calls: RefCell<Vec<&'static str>>,
106}
107
108fn internal(err: impl std::fmt::Display) -> HubError {
109 HubError::api(500, "internal", err.to_string())
110}
111
112impl FakeHub {
113 pub(crate) fn new() -> FakeHub {
114 let dir = tempfile::tempdir().unwrap();
115 let repo = Repo::init(dir.path()).unwrap();
116 FakeHub {
117 _dir: dir,
118 repo,
119 forgetful: Cell::new(false),
120 off_branch: Cell::new(false),
121 calls: RefCell::new(Vec::new()),
122 }
123 }
124
125 /// How many times `route` was called.
126 pub(crate) fn called(&self, route: &str) -> usize {
127 self.calls.borrow().iter().filter(|c| **c == route).count()
128 }
129
130 fn call(&self, route: &'static str) {
131 self.calls.borrow_mut().push(route);
132 }
133
134 /// The objects landing `change` needs that the hub does not store.
135 fn needs(&self, change: ObjectId) -> Result<Vec<ObjectId>, HubError> {
136 let store = self.repo.store();
137 let reached = match reachable(
138 store,
139 &Reach {
140 want: &[change],
141 history: Some(0),
142 ..Reach::default()
143 },
144 ) {
145 Ok(reached) => reached,
146 Err(EngineError::Missing { id, .. }) => return Ok(vec![id]),
147 Err(err) => return Err(HubError::api(400, "invalid", err.to_string())),
148 };
149 let mut needed = Vec::new();
150 for object in &reached {
151 if !store.contains(&object.id).map_err(internal)? {
152 needed.push(object.id);
153 }
154 }
155 let changeset = braid_engine::read_changeset(store, change).map_err(internal)?;
156 for parent in changeset.parents.iter().take(1) {
157 if !store.contains(parent).map_err(internal)? {
158 needed.push(*parent);
159 }
160 }
161 Ok(needed)
162 }
163}
164
165/// A landing as the hub reports it.
166fn response(report: &LandReport) -> LandResponse {
167 let (outcome, change, conflicts) = match &report.landed {
168 Landed::Nothing => ("nothing", None, Vec::new()),
169 Landed::FastForward(_) => ("fast-forward", None, Vec::new()),
170 Landed::Rebased(_) => ("rebased", None, Vec::new()),
171 Landed::AlreadyApplied => ("already-applied", None, Vec::new()),
172 Landed::Conflicts { change, conflicts } => (
173 "conflicts",
174 Some(*change),
175 conflicts
176 .iter()
177 .map(braid_hubproto::json::conflict)
178 .collect(),
179 ),
180 Landed::Refused => ("refused", None, Vec::new()),
181 };
182 LandResponse {
183 reference: report.branch.clone(),
184 outcome: outcome.to_owned(),
185 head_before: report.head_before,
186 head: report.head(),
187 landed: report
188 .placed
189 .iter()
190 .map(|placed| Placed {
191 from: placed.from,
192 to: placed.to,
193 })
194 .collect(),
195 merged_paths: report
196 .merged_paths
197 .iter()
198 .map(|path| String::from_utf8_lossy(path).into_owned())
199 .collect(),
200 conflicts,
201 change,
202 git_commit: None,
203 operation: report.operation,
204 }
205}
206
207impl Remote for FakeHub {
208 fn refs(&self) -> Result<Refs, HubError> {
209 self.call("refs");
210 let refs = self.repo.store().refs().map_err(internal)?;
211 Ok(Refs {
212 seq: refs.seq(),
213 refs: refs.as_map().clone(),
214 })
215 }
216
217 fn info(&self) -> Result<RepoInfo, HubError> {
218 self.call("info");
219 Ok(RepoInfo {
220 owner: "ada".to_owned(),
221 name: "demo".to_owned(),
222 private: true,
223 description: String::new(),
224 default_branch: "main".to_owned(),
225 created: "2026-01-01T00:00:00Z".to_owned(),
226 mirror: None,
227 permission: "admin".to_owned(),
228 ..RepoInfo::default()
229 })
230 }
231
232 fn kind(&self, id: &ObjectId) -> Result<Option<Kind>, HubError> {
233 self.call("kind");
234 Ok(self
235 .repo
236 .store()
237 .stat(id)
238 .map_err(internal)?
239 .map(|(kind, _)| kind))
240 }
241
242 fn lacks(&self, ids: &[ObjectId]) -> Result<Vec<ObjectId>, HubError> {
243 self.call("lacks");
244 if ids.len() > LACKS_BATCH {
245 return Err(HubError::api(400, "invalid", "too many ids"));
246 }
247 if self.forgetful.get() {
248 return Ok(Vec::new());
249 }
250 let mut lacking = Vec::new();
251 for id in ids {
252 if !self.repo.store().contains(id).map_err(internal)? {
253 lacking.push(*id);
254 }
255 }
256 Ok(lacking)
257 }
258
259 fn send_objects(&self, body: &mut dyn Read, len: u64) -> Result<u64, HubError> {
260 self.call("objects");
261 let mut bytes = Vec::new();
262 body.read_to_end(&mut bytes)?;
263 if bytes.len() as u64 != len || len > MAX_BODY {
264 return Err(HubError::api(400, "invalid", "the body is not its length"));
265 }
266 let store = self.repo.store();
267 let mut stored = 0;
268 for record in stream::Reader::new(&bytes[..], MAX_BODY).map_err(internal)? {
269 let record = record.map_err(|err| HubError::api(400, "invalid", err.to_string()))?;
270 store.put(record.kind, &record.payload).map_err(internal)?;
271 stored += 1;
272 }
273 store.sync().map_err(internal)?;
274 Ok(stored)
275 }
276
277 fn missing(&self, request: &MissingRequest) -> Result<Box<dyn Read + '_>, HubError> {
278 self.call("missing");
279 let store = self.repo.store();
280 let paths: Option<Vec<Vec<u8>>> = request
281 .paths
282 .as_ref()
283 .map(|paths| paths.iter().map(|p| p.as_bytes().to_vec()).collect());
284 let reached = reachable(
285 store,
286 &Reach {
287 want: &request.want,
288 have: &request.have,
289 history: request.history,
290 paths: paths.as_deref(),
291 max_objects: None,
292 },
293 )
294 .map_err(|err| HubError::api(400, "invalid", err.to_string()))?;
295 let mut writer = stream::Writer::new(Vec::new())?;
296 for object in &reached {
297 let (kind, payload) = store
298 .get(&object.id)
299 .map_err(internal)?
300 .ok_or_else(|| internal(format!("{} is gone", object.id)))?;
301 writer.object(kind, &object.id, &payload)?;
302 }
303 Ok(Box::new(Cursor::new(writer.finish()?)))
304 }
305
306 fn land(&self, request: &LandRequest) -> Result<LandResponse, HubError> {
307 self.call("land");
308 if self.off_branch.get() {
309 return Err(HubError::api(
310 409,
311 "not_on_branch",
312 "the stack is not built on the ref",
313 ));
314 }
315 let mut needed = Vec::new();
316 for change in &request.changes {
317 needed.extend(self.needs(*change)?);
318 }
319 if !needed.is_empty() {
320 let mut err = HubError::api(409, "missing", "objects are missing");
321 if let HubError::Api { body, .. } = &mut err {
322 body.ids = needed;
323 }
324 return Err(err);
325 }
326 let mode = match request.mode {
327 LandMode::Rebase => StackMode::Rebase,
328 LandMode::FfOnly => StackMode::FastForwardOnly,
329 };
330 let committer = Identity::new("BraidHub", "hub@example.org").unwrap();
331 let agent = request.agent.as_deref().unwrap_or("hub");
332 match land_stack(
333 &self.repo,
334 &request.reference,
335 &request.changes,
336 mode,
337 agent,
338 &committer,
339 ) {
340 Ok(report) => Ok(response(&report)),
341 Err(braid_wc::Error::NotOnBranch { .. }) => Err(HubError::api(
342 409,
343 "not_on_branch",
344 "the stack is not built on the ref",
345 )),
346 Err(err @ (braid_wc::Error::EmptyStack | braid_wc::Error::NotAStack { .. })) => {
347 Err(HubError::api(400, "invalid", err.to_string()))
348 }
349 Err(err) => Err(internal(err)),
350 }
351 }
352}