| 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, and |
| 7 | //! the routes of verification ([`VerifyApi`]) the way section 25 says. No |
| 8 | //! HTTP is involved. |
| 9 | |
| 10 | use std::cell::{Cell, RefCell}; |
| 11 | use std::collections::HashMap; |
| 12 | use std::convert::Infallible; |
| 13 | use std::io::{Cursor, Read}; |
| 14 | |
| 15 | use braid_engine::{Error as EngineError, Reach, reachable}; |
| 16 | use braid_format::{Kind, ObjectId, Objects}; |
| 17 | use braid_hubproto::api::{ |
| 18 | LandMode, LandRequest, LandResponse, MissingRequest, Placed, Refs, RepoInfo, |
| 19 | }; |
| 20 | use braid_hubproto::stream; |
| 21 | use braid_hubproto::verify::{ |
| 22 | self as verify, LandVerify, ReportPolicy, VerifyEvent, VerifyPolicy, VerifyReport, VerifyReset, |
| 23 | VerifyStatus, |
| 24 | }; |
| 25 | use braid_repo::Repo; |
| 26 | use braid_store::RefUpdate; |
| 27 | use braid_wc::{ChangeRequest, Identity, LandReport, Landed, StackMode, land_stack}; |
| 28 | use serde_json::{Value, json}; |
| 29 | use tempfile::TempDir; |
| 30 | |
| 31 | use super::link::Link; |
| 32 | use super::remote::{HubError, LACKS_BATCH, MAX_BODY, Remote}; |
| 33 | use super::verify::VerifyApi; |
| 34 | |
| 35 | /// The identity tests sign with. |
| 36 | pub(crate) fn ada() -> Identity { |
| 37 | Identity::new("Ada", "ada@example.org").unwrap() |
| 38 | } |
| 39 | |
| 40 | /// A changeset on `base` setting each `(path, content)`, made durable. |
| 41 | pub(crate) fn ada_change(repo: &Repo, base: Option<ObjectId>, sets: &[(&str, &str)]) -> ObjectId { |
| 42 | let id = braid_wc::create_change( |
| 43 | repo.store(), |
| 44 | &ChangeRequest { |
| 45 | base, |
| 46 | sets: sets |
| 47 | .iter() |
| 48 | .map(|(path, content)| (path.as_bytes().to_vec(), content.as_bytes().to_vec())) |
| 49 | .collect(), |
| 50 | deletes: Vec::new(), |
| 51 | expects: Vec::new(), |
| 52 | message: b"change\n".to_vec(), |
| 53 | author: ada(), |
| 54 | agent: "tester".to_owned(), |
| 55 | }, |
| 56 | ) |
| 57 | .unwrap(); |
| 58 | repo.store().sync().unwrap(); |
| 59 | id |
| 60 | } |
| 61 | |
| 62 | /// Points `name` at `id`. |
| 63 | pub(crate) fn set_ref(repo: &Repo, name: &str, id: ObjectId) { |
| 64 | repo.store() |
| 65 | .transact("tester", &format!("set {name}"), |refs| { |
| 66 | Ok::<_, Infallible>(vec![RefUpdate::new(name, refs.get(name), Some(id))]) |
| 67 | }) |
| 68 | .unwrap(); |
| 69 | } |
| 70 | |
| 71 | /// A repository in a temporary directory, and a link it may write. |
| 72 | pub(crate) struct Fixture { |
| 73 | _dir: TempDir, |
| 74 | pub(crate) repo: Repo, |
| 75 | pub(crate) link: Link, |
| 76 | } |
| 77 | |
| 78 | impl Fixture { |
| 79 | /// A new, empty repository. |
| 80 | pub(crate) fn new() -> Fixture { |
| 81 | let dir = tempfile::tempdir().unwrap(); |
| 82 | let repo = Repo::init(dir.path()).unwrap(); |
| 83 | Fixture { |
| 84 | _dir: dir, |
| 85 | repo, |
| 86 | link: Link { |
| 87 | url: "http://127.0.0.1:9".to_owned(), |
| 88 | repo: "ada/demo".parse().unwrap(), |
| 89 | paths: None, |
| 90 | }, |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | /// A new, empty repository linked to the repository of `hub`. |
| 95 | pub(crate) fn linked(_hub: &FakeHub) -> Fixture { |
| 96 | let fixture = Fixture::new(); |
| 97 | fixture.link.write(&fixture.repo).unwrap(); |
| 98 | fixture |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | /// A hub in memory, holding one repository. |
| 103 | pub(crate) struct FakeHub { |
| 104 | _dir: TempDir, |
| 105 | /// The repository: its store and refs are the hub's. |
| 106 | pub(crate) repo: Repo, |
| 107 | /// Claims to store everything, so that uploads send nothing and a |
| 108 | /// landing finds objects missing. |
| 109 | pub(crate) forgetful: Cell<bool>, |
| 110 | /// Answers every landing with `not_on_branch`. |
| 111 | pub(crate) off_branch: Cell<bool>, |
| 112 | /// The routes called, in order. |
| 113 | pub(crate) calls: RefCell<Vec<&'static str>>, |
| 114 | /// The verification of its repository's `main`. |
| 115 | pub(crate) verify: RefCell<FakeVerify>, |
| 116 | } |
| 117 | |
| 118 | fn internal(err: impl std::fmt::Display) -> HubError { |
| 119 | HubError::api(500, "internal", err.to_string()) |
| 120 | } |
| 121 | |
| 122 | impl FakeHub { |
| 123 | pub(crate) fn new() -> FakeHub { |
| 124 | let dir = tempfile::tempdir().unwrap(); |
| 125 | let repo = Repo::init(dir.path()).unwrap(); |
| 126 | FakeHub { |
| 127 | _dir: dir, |
| 128 | repo, |
| 129 | forgetful: Cell::new(false), |
| 130 | off_branch: Cell::new(false), |
| 131 | calls: RefCell::new(Vec::new()), |
| 132 | verify: RefCell::new(FakeVerify::new()), |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// How many times `route` was called. |
| 137 | pub(crate) fn called(&self, route: &str) -> usize { |
| 138 | self.calls.borrow().iter().filter(|c| **c == route).count() |
| 139 | } |
| 140 | |
| 141 | fn call(&self, route: &'static str) { |
| 142 | self.calls.borrow_mut().push(route); |
| 143 | } |
| 144 | |
| 145 | /// The objects landing `change` needs that the hub does not store. |
| 146 | fn needs(&self, change: ObjectId) -> Result<Vec<ObjectId>, HubError> { |
| 147 | let store = self.repo.store(); |
| 148 | let reached = match reachable( |
| 149 | store, |
| 150 | &Reach { |
| 151 | want: &[change], |
| 152 | history: Some(0), |
| 153 | ..Reach::default() |
| 154 | }, |
| 155 | ) { |
| 156 | Ok(reached) => reached, |
| 157 | Err(EngineError::Missing { id, .. }) => return Ok(vec![id]), |
| 158 | Err(err) => return Err(HubError::api(400, "invalid", err.to_string())), |
| 159 | }; |
| 160 | let mut needed = Vec::new(); |
| 161 | for object in &reached { |
| 162 | if !store.contains(&object.id).map_err(internal)? { |
| 163 | needed.push(object.id); |
| 164 | } |
| 165 | } |
| 166 | let changeset = braid_engine::read_changeset(store, change).map_err(internal)?; |
| 167 | for parent in changeset.parents.iter().take(1) { |
| 168 | if !store.contains(parent).map_err(internal)? { |
| 169 | needed.push(*parent); |
| 170 | } |
| 171 | } |
| 172 | Ok(needed) |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | /// A landing as the hub reports it. |
| 177 | fn response(report: &LandReport) -> LandResponse { |
| 178 | let (outcome, change, conflicts) = match &report.landed { |
| 179 | Landed::Nothing => ("nothing", None, Vec::new()), |
| 180 | Landed::FastForward(_) => ("fast-forward", None, Vec::new()), |
| 181 | Landed::Rebased(_) => ("rebased", None, Vec::new()), |
| 182 | Landed::AlreadyApplied => ("already-applied", None, Vec::new()), |
| 183 | Landed::Conflicts { change, conflicts } => ( |
| 184 | "conflicts", |
| 185 | Some(*change), |
| 186 | conflicts |
| 187 | .iter() |
| 188 | .map(braid_hubproto::json::conflict) |
| 189 | .collect(), |
| 190 | ), |
| 191 | Landed::Refused => ("refused", None, Vec::new()), |
| 192 | }; |
| 193 | LandResponse { |
| 194 | reference: report.branch.clone(), |
| 195 | outcome: outcome.to_owned(), |
| 196 | head_before: report.head_before, |
| 197 | head: report.head(), |
| 198 | landed: report |
| 199 | .placed |
| 200 | .iter() |
| 201 | .map(|placed| Placed { |
| 202 | from: placed.from, |
| 203 | to: placed.to, |
| 204 | }) |
| 205 | .collect(), |
| 206 | merged_paths: report |
| 207 | .merged_paths |
| 208 | .iter() |
| 209 | .map(|path| String::from_utf8_lossy(path).into_owned()) |
| 210 | .collect(), |
| 211 | conflicts, |
| 212 | change, |
| 213 | git_commit: None, |
| 214 | operation: report.operation, |
| 215 | verify: None, |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | impl Remote for FakeHub { |
| 220 | fn refs(&self) -> Result<Refs, HubError> { |
| 221 | self.call("refs"); |
| 222 | let refs = self.repo.store().refs().map_err(internal)?; |
| 223 | Ok(Refs { |
| 224 | seq: refs.seq(), |
| 225 | refs: refs.as_map().clone(), |
| 226 | }) |
| 227 | } |
| 228 | |
| 229 | fn info(&self) -> Result<RepoInfo, HubError> { |
| 230 | self.call("info"); |
| 231 | Ok(RepoInfo { |
| 232 | owner: "ada".to_owned(), |
| 233 | name: "demo".to_owned(), |
| 234 | private: true, |
| 235 | description: String::new(), |
| 236 | default_branch: "main".to_owned(), |
| 237 | created: "2026-01-01T00:00:00Z".to_owned(), |
| 238 | mirror: None, |
| 239 | permission: "admin".to_owned(), |
| 240 | ..RepoInfo::default() |
| 241 | }) |
| 242 | } |
| 243 | |
| 244 | fn kind(&self, id: &ObjectId) -> Result<Option<Kind>, HubError> { |
| 245 | self.call("kind"); |
| 246 | Ok(self |
| 247 | .repo |
| 248 | .store() |
| 249 | .stat(id) |
| 250 | .map_err(internal)? |
| 251 | .map(|(kind, _)| kind)) |
| 252 | } |
| 253 | |
| 254 | fn lacks(&self, ids: &[ObjectId]) -> Result<Vec<ObjectId>, HubError> { |
| 255 | self.call("lacks"); |
| 256 | if ids.len() > LACKS_BATCH { |
| 257 | return Err(HubError::api(400, "invalid", "too many ids")); |
| 258 | } |
| 259 | if self.forgetful.get() { |
| 260 | return Ok(Vec::new()); |
| 261 | } |
| 262 | let mut lacking = Vec::new(); |
| 263 | for id in ids { |
| 264 | if !self.repo.store().contains(id).map_err(internal)? { |
| 265 | lacking.push(*id); |
| 266 | } |
| 267 | } |
| 268 | Ok(lacking) |
| 269 | } |
| 270 | |
| 271 | fn send_objects(&self, body: &mut dyn Read, len: u64) -> Result<u64, HubError> { |
| 272 | self.call("objects"); |
| 273 | let mut bytes = Vec::new(); |
| 274 | body.read_to_end(&mut bytes)?; |
| 275 | if bytes.len() as u64 != len || len > MAX_BODY { |
| 276 | return Err(HubError::api(400, "invalid", "the body is not its length")); |
| 277 | } |
| 278 | let store = self.repo.store(); |
| 279 | let mut stored = 0; |
| 280 | for record in stream::Reader::new(&bytes[..], MAX_BODY).map_err(internal)? { |
| 281 | let record = record.map_err(|err| HubError::api(400, "invalid", err.to_string()))?; |
| 282 | store.put(record.kind, &record.payload).map_err(internal)?; |
| 283 | stored += 1; |
| 284 | } |
| 285 | store.sync().map_err(internal)?; |
| 286 | Ok(stored) |
| 287 | } |
| 288 | |
| 289 | fn missing(&self, request: &MissingRequest) -> Result<Box<dyn Read + '_>, HubError> { |
| 290 | self.call("missing"); |
| 291 | let store = self.repo.store(); |
| 292 | let paths: Option<Vec<Vec<u8>>> = request |
| 293 | .paths |
| 294 | .as_ref() |
| 295 | .map(|paths| paths.iter().map(|p| p.as_bytes().to_vec()).collect()); |
| 296 | let reached = reachable( |
| 297 | store, |
| 298 | &Reach { |
| 299 | want: &request.want, |
| 300 | have: &request.have, |
| 301 | history: request.history, |
| 302 | paths: paths.as_deref(), |
| 303 | max_objects: None, |
| 304 | }, |
| 305 | ) |
| 306 | .map_err(|err| HubError::api(400, "invalid", err.to_string()))?; |
| 307 | let mut writer = stream::Writer::new(Vec::new())?; |
| 308 | for object in &reached { |
| 309 | let (kind, payload) = store |
| 310 | .get(&object.id) |
| 311 | .map_err(internal)? |
| 312 | .ok_or_else(|| internal(format!("{} is gone", object.id)))?; |
| 313 | writer.object(kind, &object.id, &payload)?; |
| 314 | } |
| 315 | Ok(Box::new(Cursor::new(writer.finish()?))) |
| 316 | } |
| 317 | |
| 318 | fn land(&self, request: &LandRequest) -> Result<LandResponse, HubError> { |
| 319 | self.call("land"); |
| 320 | if self.off_branch.get() { |
| 321 | return Err(HubError::api( |
| 322 | 409, |
| 323 | "not_on_branch", |
| 324 | "the stack is not built on the ref", |
| 325 | )); |
| 326 | } |
| 327 | let mut needed = Vec::new(); |
| 328 | for change in &request.changes { |
| 329 | needed.extend(self.needs(*change)?); |
| 330 | } |
| 331 | if !needed.is_empty() { |
| 332 | let mut err = HubError::api(409, "missing", "objects are missing"); |
| 333 | if let HubError::Api { body, .. } = &mut err { |
| 334 | body.ids = needed; |
| 335 | } |
| 336 | return Err(err); |
| 337 | } |
| 338 | let mode = match request.mode { |
| 339 | LandMode::Rebase => StackMode::Rebase, |
| 340 | LandMode::FfOnly => StackMode::FastForwardOnly, |
| 341 | }; |
| 342 | let committer = Identity::new("BraidHub", "hub@example.org").unwrap(); |
| 343 | let agent = request.agent.as_deref().unwrap_or("hub"); |
| 344 | match land_stack( |
| 345 | &self.repo, |
| 346 | &request.reference, |
| 347 | &request.changes, |
| 348 | mode, |
| 349 | agent, |
| 350 | &committer, |
| 351 | ) { |
| 352 | Ok(report) => Ok(LandResponse { |
| 353 | verify: self.verify.borrow().landing.clone(), |
| 354 | ..response(&report) |
| 355 | }), |
| 356 | Err(braid_wc::Error::NotOnBranch { .. }) => Err(HubError::api( |
| 357 | 409, |
| 358 | "not_on_branch", |
| 359 | "the stack is not built on the ref", |
| 360 | )), |
| 361 | Err(err @ (braid_wc::Error::EmptyStack | braid_wc::Error::NotAStack { .. })) => { |
| 362 | Err(HubError::api(400, "invalid", err.to_string())) |
| 363 | } |
| 364 | Err(err) => Err(internal(err)), |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | /// How the fake hub's routes of verification answer while a test says so. |
| 370 | #[derive(Clone, Copy, Debug)] |
| 371 | pub(crate) enum Refusal { |
| 372 | /// An error answer: its status and its code. |
| 373 | Api(u16, &'static str), |
| 374 | /// The hub cannot be reached. |
| 375 | Unreachable, |
| 376 | } |
| 377 | |
| 378 | impl Refusal { |
| 379 | fn error(self) -> HubError { |
| 380 | match self { |
| 381 | Refusal::Api(status, code) => HubError::api(status, code, "as the test says"), |
| 382 | Refusal::Unreachable => HubError::Transport { |
| 383 | hub: "http://127.0.0.1:9".to_owned(), |
| 384 | detail: "connection refused".to_owned(), |
| 385 | }, |
| 386 | } |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | /// The verification of the fake hub's repository, whose default branch is |
| 391 | /// `main` (section 25): what a test sets, and what the calls of |
| 392 | /// [`VerifyApi`] leave. It keeps the refs in its status rather than in the |
| 393 | /// store, and names a culprit as the hub does when one changeset separates |
| 394 | /// green from a fail. |
| 395 | pub(crate) struct FakeVerify { |
| 396 | /// Whether `GET /v1` lists the feature. |
| 397 | pub(crate) served: bool, |
| 398 | /// The policy, as it was last put, kept whole. |
| 399 | pub(crate) policy: Value, |
| 400 | /// How `main` stands. |
| 401 | pub(crate) status: VerifyStatus, |
| 402 | /// Fields a newer hub adds to the status it answers. |
| 403 | pub(crate) extra: Option<Value>, |
| 404 | /// The log, oldest first. |
| 405 | pub(crate) events: Vec<VerifyEvent>, |
| 406 | /// The git commits the hub knows, and their changesets. |
| 407 | pub(crate) commits: HashMap<String, ObjectId>, |
| 408 | /// Each request that carried an `Idempotency-Key`: the key, and the |
| 409 | /// body. |
| 410 | pub(crate) keyed: Vec<(String, Value)>, |
| 411 | /// The verdicts recorded, oldest first. |
| 412 | pub(crate) verdicts: Vec<(ObjectId, String)>, |
| 413 | /// How many of the next answers of reports and resets are lost on |
| 414 | /// their way back, once they took effect. |
| 415 | pub(crate) lose: usize, |
| 416 | /// What every call answers instead, while it is set. |
| 417 | pub(crate) refuse: Option<Refusal>, |
| 418 | /// What the answers of landings say of the branch, as `verify`. |
| 419 | pub(crate) landing: Option<LandVerify>, |
| 420 | /// The answers given, by key: the same key gets the same answer. |
| 421 | answers: HashMap<String, Value>, |
| 422 | } |
| 423 | |
| 424 | impl FakeVerify { |
| 425 | fn new() -> FakeVerify { |
| 426 | FakeVerify { |
| 427 | served: false, |
| 428 | policy: serde_json::to_value(VerifyPolicy::default()).unwrap(), |
| 429 | status: VerifyStatus::default(), |
| 430 | extra: None, |
| 431 | events: Vec::new(), |
| 432 | commits: HashMap::new(), |
| 433 | keyed: Vec::new(), |
| 434 | verdicts: Vec::new(), |
| 435 | lose: 0, |
| 436 | refuse: None, |
| 437 | landing: None, |
| 438 | answers: HashMap::new(), |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | /// Verification on, as an admin turns it on: the hub lists the |
| 443 | /// feature, and takes the reports of ci-bot on the suite `ci`. |
| 444 | pub(crate) fn turn_on(&mut self) { |
| 445 | self.served = true; |
| 446 | self.policy = serde_json::to_value(VerifyPolicy { |
| 447 | mode: verify::MODE_REPORT.to_owned(), |
| 448 | green_from: vec![verify::SOURCE_REPORT.to_owned()], |
| 449 | flaky_moves_green: false, |
| 450 | report: Some(ReportPolicy { |
| 451 | suite: "ci".to_owned(), |
| 452 | reporters: vec!["ci-bot".to_owned()], |
| 453 | }), |
| 454 | }) |
| 455 | .unwrap(); |
| 456 | self.status = VerifyStatus { |
| 457 | mode: verify::MODE_REPORT.to_owned(), |
| 458 | branch: Some("main".to_owned()), |
| 459 | state: verify::STATE_UNKNOWN.to_owned(), |
| 460 | ..VerifyStatus::default() |
| 461 | }; |
| 462 | } |
| 463 | |
| 464 | fn refused(&self) -> Result<(), HubError> { |
| 465 | self.refuse.map_or(Ok(()), |refusal| Err(refusal.error())) |
| 466 | } |
| 467 | |
| 468 | /// Records an event of the log. |
| 469 | fn event(&mut self, code: &str, changeset: Option<ObjectId>, actor: Option<&str>) { |
| 470 | let id = self.events.len() as u64 + 1; |
| 471 | self.events.push(VerifyEvent { |
| 472 | id, |
| 473 | at: format!("2026-10-22T12:{:02}:00Z", id % 60), |
| 474 | code: code.to_owned(), |
| 475 | changeset, |
| 476 | other: None, |
| 477 | actor: actor.map(str::to_owned), |
| 478 | }); |
| 479 | } |
| 480 | |
| 481 | /// Keeps `answer` for `key`, and gives it, unless it is to be lost. |
| 482 | fn answer(&mut self, key: &str, answer: Value) -> Result<Value, HubError> { |
| 483 | let answer = self.answers.entry(key.to_owned()).or_insert(answer).clone(); |
| 484 | if self.lose > 0 { |
| 485 | self.lose -= 1; |
| 486 | return Err(HubError::Transport { |
| 487 | hub: "http://127.0.0.1:9".to_owned(), |
| 488 | detail: "the connection closed before the answer".to_owned(), |
| 489 | }); |
| 490 | } |
| 491 | Ok(answer) |
| 492 | } |
| 493 | |
| 494 | /// The state the refs make, with `head` the head of `main`. |
| 495 | fn settle(&mut self, head: Option<ObjectId>) { |
| 496 | self.status.head = head; |
| 497 | self.status.state = if self.status.red.is_some() { |
| 498 | verify::STATE_RED |
| 499 | } else if self.status.green.is_some() && self.status.green == head { |
| 500 | verify::STATE_GREEN |
| 501 | } else { |
| 502 | verify::STATE_PENDING |
| 503 | } |
| 504 | .to_owned(); |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | impl FakeHub { |
| 509 | /// The head of `main`. |
| 510 | fn main_head(&self) -> Option<ObjectId> { |
| 511 | self.repo.store().refs().ok()?.get("main") |
| 512 | } |
| 513 | |
| 514 | /// Whether `id` is `head`, or on its first-parent chain. |
| 515 | fn on_chain(&self, head: ObjectId, id: ObjectId) -> bool { |
| 516 | braid_engine::first_parent_chain_contains(self.repo.store(), head, id, usize::MAX) |
| 517 | .unwrap_or(false) |
| 518 | } |
| 519 | |
| 520 | /// The first parent of `id`. |
| 521 | fn parent(&self, id: ObjectId) -> Option<ObjectId> { |
| 522 | braid_engine::read_changeset(self.repo.store(), id) |
| 523 | .ok()? |
| 524 | .parents |
| 525 | .first() |
| 526 | .copied() |
| 527 | } |
| 528 | } |
| 529 | |
| 530 | impl VerifyApi for FakeHub { |
| 531 | fn features(&self) -> Result<Vec<String>, HubError> { |
| 532 | self.call("features"); |
| 533 | let verify = self.verify.borrow(); |
| 534 | verify.refused()?; |
| 535 | Ok(if verify.served { |
| 536 | vec![verify::FEATURE.to_owned()] |
| 537 | } else { |
| 538 | Vec::new() |
| 539 | }) |
| 540 | } |
| 541 | |
| 542 | fn status(&self) -> Result<Value, HubError> { |
| 543 | self.call("verify"); |
| 544 | let verify = self.verify.borrow(); |
| 545 | verify.refused()?; |
| 546 | let mut answer = serde_json::to_value(&verify.status).map_err(internal)?; |
| 547 | if let (Some(Value::Object(extra)), Value::Object(fields)) = (&verify.extra, &mut answer) { |
| 548 | fields.extend(extra.clone()); |
| 549 | } |
| 550 | Ok(answer) |
| 551 | } |
| 552 | |
| 553 | fn report(&self, report: &VerifyReport, key: &str) -> Result<Value, HubError> { |
| 554 | self.call("verify/report"); |
| 555 | let head = self.main_head(); |
| 556 | let mut verify = self.verify.borrow_mut(); |
| 557 | verify.refused()?; |
| 558 | let body = serde_json::to_value(report).map_err(internal)?; |
| 559 | verify.keyed.push((key.to_owned(), body)); |
| 560 | if let Some(answer) = verify.answers.get(key).cloned() { |
| 561 | return verify.answer(key, answer); |
| 562 | } |
| 563 | let policy: VerifyPolicy = |
| 564 | serde_json::from_value(verify.policy.clone()).map_err(internal)?; |
| 565 | let Some(reporting) = policy.report.filter(|_| policy.mode != verify::MODE_OFF) else { |
| 566 | return Err(HubError::api(403, "forbidden", "verification is off")); |
| 567 | }; |
| 568 | if report.suite != reporting.suite { |
| 569 | return Err(HubError::api(400, "invalid", "not the policy's suite")); |
| 570 | } |
| 571 | let changeset = match (&report.changeset, &report.git_commit) { |
| 572 | (Some(id), None) => *id, |
| 573 | (None, Some(sha)) => *verify |
| 574 | .commits |
| 575 | .get(sha) |
| 576 | .ok_or_else(|| HubError::api(404, "not_found", "no such commit"))?, |
| 577 | _ => return Err(HubError::api(400, "invalid", "give one of the two")), |
| 578 | }; |
| 579 | if !head.is_some_and(|head| self.on_chain(head, changeset)) { |
| 580 | let mut err = HubError::api(409, "not_on_branch", "not on main"); |
| 581 | if let HubError::Api { body, .. } = &mut err { |
| 582 | body.head = head.map(|head| head.to_hex()); |
| 583 | } |
| 584 | return Err(err); |
| 585 | } |
| 586 | let outcome = report.outcome.as_str(); |
| 587 | let effect = if verify |
| 588 | .status |
| 589 | .green |
| 590 | .is_some_and(|green| self.on_chain(green, changeset)) |
| 591 | { |
| 592 | verify::EFFECT_STALE |
| 593 | } else if verify.verdicts.contains(&(changeset, outcome.to_owned())) { |
| 594 | verify::EFFECT_DUPLICATE |
| 595 | } else { |
| 596 | verify.verdicts.push((changeset, outcome.to_owned())); |
| 597 | match outcome { |
| 598 | verify::PASS => { |
| 599 | verify.status.green = Some(changeset); |
| 600 | verify.event(verify::EVENT_GREEN, Some(changeset), None); |
| 601 | let cleared = verify |
| 602 | .status |
| 603 | .red |
| 604 | .is_some_and(|red| self.on_chain(changeset, red)); |
| 605 | if cleared { |
| 606 | let status = &mut verify.status; |
| 607 | (status.red, status.culprit, status.decided_by) = (None, None, None); |
| 608 | (status.code, status.since, status.window) = (None, None, None); |
| 609 | verify.event(verify::EVENT_FIXED, None, None); |
| 610 | verify::EFFECT_RED_CLEARED |
| 611 | } else { |
| 612 | verify::EFFECT_GREEN_MOVED |
| 613 | } |
| 614 | } |
| 615 | verify::FAIL if verify.status.red.is_none() => { |
| 616 | let single = verify.status.green.is_some() |
| 617 | && self.parent(changeset) == verify.status.green; |
| 618 | let status = &mut verify.status; |
| 619 | status.red = Some(changeset); |
| 620 | status.since = Some("2026-10-22T12:03:00Z".to_owned()); |
| 621 | if single { |
| 622 | status.culprit = Some(changeset); |
| 623 | status.decided_by = Some(verify::DECIDED_SINGLE.to_owned()); |
| 624 | } else { |
| 625 | status.code = Some( |
| 626 | if status.green.is_some() { |
| 627 | verify::CODE_CULPRIT_UNKNOWN |
| 628 | } else { |
| 629 | verify::CODE_NO_GREEN |
| 630 | } |
| 631 | .to_owned(), |
| 632 | ); |
| 633 | } |
| 634 | verify.event(verify::EVENT_RED, Some(changeset), None); |
| 635 | verify::EFFECT_RED_SET |
| 636 | } |
| 637 | verify::FLAKY => { |
| 638 | verify.status.code = Some(verify::CODE_FLAKY.to_owned()); |
| 639 | verify.event(verify::EVENT_FLAKY, Some(changeset), None); |
| 640 | verify::EFFECT_RECORDED |
| 641 | } |
| 642 | _ => verify::EFFECT_RECORDED, |
| 643 | } |
| 644 | }; |
| 645 | verify.settle(head); |
| 646 | let answer = json!({"effect": effect, "status": verify.status}); |
| 647 | verify.answer(key, answer) |
| 648 | } |
| 649 | |
| 650 | fn policy(&self) -> Result<Value, HubError> { |
| 651 | self.call("verify/policy"); |
| 652 | let verify = self.verify.borrow(); |
| 653 | verify.refused()?; |
| 654 | Ok(verify.policy.clone()) |
| 655 | } |
| 656 | |
| 657 | fn put_policy(&self, policy: &Value) -> Result<Value, HubError> { |
| 658 | self.call("verify/policy put"); |
| 659 | let mut verify = self.verify.borrow_mut(); |
| 660 | verify.refused()?; |
| 661 | let mode = policy["mode"].as_str().unwrap_or_default().to_owned(); |
| 662 | if !verify::MODES.contains(&mode.as_str()) { |
| 663 | return Err(HubError::api(400, "invalid", "no such mode")); |
| 664 | } |
| 665 | verify.policy = policy.clone(); |
| 666 | if mode == verify::MODE_OFF { |
| 667 | verify.status = VerifyStatus::default(); |
| 668 | } else { |
| 669 | verify.status.mode = mode; |
| 670 | verify.status.branch = Some("main".to_owned()); |
| 671 | } |
| 672 | verify.event(verify::EVENT_POLICY, None, Some("ada")); |
| 673 | Ok(policy.clone()) |
| 674 | } |
| 675 | |
| 676 | fn log(&self, after: Option<u64>, limit: Option<u32>) -> Result<Value, HubError> { |
| 677 | self.call("verify/log"); |
| 678 | let verify = self.verify.borrow(); |
| 679 | verify.refused()?; |
| 680 | let limit = limit.unwrap_or(30) as usize; |
| 681 | let older: Vec<&VerifyEvent> = verify |
| 682 | .events |
| 683 | .iter() |
| 684 | .rev() |
| 685 | .filter(|event| after.is_none_or(|after| event.id < after)) |
| 686 | .collect(); |
| 687 | let page: Vec<&VerifyEvent> = older.iter().take(limit).copied().collect(); |
| 688 | let next = (older.len() > limit).then(|| page.last().map(|event| event.id)); |
| 689 | Ok(json!({"events": page, "next": next.flatten()})) |
| 690 | } |
| 691 | |
| 692 | fn reset(&self, reset: &VerifyReset, key: &str) -> Result<Value, HubError> { |
| 693 | self.call("verify/reset"); |
| 694 | let head = self.main_head(); |
| 695 | let mut verify = self.verify.borrow_mut(); |
| 696 | verify.refused()?; |
| 697 | let body = serde_json::to_value(reset).map_err(internal)?; |
| 698 | verify.keyed.push((key.to_owned(), body)); |
| 699 | if let Some(answer) = verify.answers.get(key).cloned() { |
| 700 | return verify.answer(key, answer); |
| 701 | } |
| 702 | if let Some(expect) = &reset.expect |
| 703 | && (expect.green != verify.status.green || expect.red != verify.status.red) |
| 704 | { |
| 705 | return Err(HubError::api(409, "moved", "the refs moved")); |
| 706 | } |
| 707 | if let Some(green) = reset.green { |
| 708 | if !head.is_some_and(|head| self.on_chain(head, green)) { |
| 709 | return Err(HubError::api(400, "invalid", "not on main")); |
| 710 | } |
| 711 | verify.status.green = Some(green); |
| 712 | } |
| 713 | let status = &mut verify.status; |
| 714 | (status.red, status.culprit, status.decided_by) = (None, None, None); |
| 715 | (status.code, status.since, status.window) = (None, None, None); |
| 716 | verify.event(verify::EVENT_RESET, reset.green, Some("ada")); |
| 717 | verify.settle(head); |
| 718 | let answer = serde_json::to_value(&verify.status).map_err(internal)?; |
| 719 | verify.answer(key, answer) |
| 720 | } |
| 721 | } |