synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / git_bridge.rs
| 1 | //! Git bridge records and the persistent `GitOid` map (ADR 0003 section 5.10, step H1 cut 2). |
| 2 | //! See `docs/H1_GIT_BRIDGE.md`. |
| 3 | //! |
| 4 | //! An import is a sequence of WAL kind 10 records ([`crate::WalRecord::GitBridgeImported`]), |
| 5 | //! one [`GitBridgeEntry`] each: |
| 6 | //! |
| 7 | //! * `Objects`: Git blobs mapped to `BlobDigest`s (their bytes stored as ordinary blobs) and Git |
| 8 | //! trees mapped to canonical `TreeDigest` nodes (C1). A Git tree ID is never stored as native |
| 9 | //! identity: at export it is recomputed from the node. |
| 10 | //! * `Commit`: an imported revision. Its native form is the commit's `TreeDigest`, its parents |
| 11 | //! as imported revision IDs in Git's written order, and the rest of the commit (author, |
| 12 | //! committer, extra headers such as `gpgsig` and `mergetag`, message) as opaque bytes. Its |
| 13 | //! `ChangesetId` is [`GitImportedCommit::changeset_id`]. |
| 14 | //! * `Tag`: an annotated tag, its target as a native identity and every byte after the |
| 15 | //! `object` line opaque. |
| 16 | //! * `Refs`: the repository's references and `HEAD` at import. |
| 17 | //! |
| 18 | //! The ledger is a pure function of the kind 10 records that took effect, in `WalSeq` order: |
| 19 | //! replay, a checkpoint (which keeps the records) and a live store rebuild the same map. In a |
| 20 | //! store opened with a seal key, kind 10 is a revision record like kinds 7, 8, 9 and 11: it is |
| 21 | //! written sealed and applied only when its seal verifies against the chain so far (issue |
| 22 | //! #101). Every check runs before the write ([`crate::SynapseStore::record_git_import`]); |
| 23 | //! apply itself is total. |
| 24 | |
| 25 | use crate::WalRecord; |
| 26 | use sha2::{Digest, Sha256}; |
| 27 | use std::collections::{BTreeMap, BTreeSet}; |
| 28 | use synapse_core::{ |
| 29 | decode_tree_node, git_tree_payload_of_node, BlobDigest, ChangesetId, GitOid, RefusalCode, |
| 30 | RepoId, SynapseError, SynapseResult, TreeDigest, TreeNodeEntryKind, WalSeq, |
| 31 | }; |
| 32 | |
| 33 | /// Domain tag of an imported revision's `ChangesetId`. Distinct from the v1 and v2 domains, so |
| 34 | /// an imported revision never shares an identity with an agent revision. |
| 35 | pub const DOMAIN_GIT_IMPORTED_REVISION_V1: &[u8] = b"SYNAPSE_GIT_IMPORTED_REVISION_V1\0"; |
| 36 | |
| 37 | /// Version of the imported revision encoding hashed into its `ChangesetId`. |
| 38 | pub const GIT_IMPORTED_REVISION_VERSION: u16 = 1; |
| 39 | |
| 40 | /// Longest reference name the bridge stores. |
| 41 | pub const MAX_GIT_REF_NAME_BYTES: usize = 1024; |
| 42 | |
| 43 | /// One Git blob and the native blob holding its bytes. |
| 44 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 45 | pub struct GitBlobMapping { |
| 46 | pub git_oid: GitOid, |
| 47 | pub blob: BlobDigest, |
| 48 | pub size_bytes: u64, |
| 49 | } |
| 50 | |
| 51 | /// One Git tree and its canonical native node (C1 version 1 encoding). The `TreeDigest` is |
| 52 | /// derived from the node bytes. |
| 53 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 54 | pub struct GitTreeMapping { |
| 55 | pub git_oid: GitOid, |
| 56 | pub node: Vec<u8>, |
| 57 | } |
| 58 | |
| 59 | impl GitTreeMapping { |
| 60 | pub fn digest(&self) -> TreeDigest { |
| 61 | TreeDigest::of_encoded_node(&self.node) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | /// An imported Git commit: tree, parents in written order, and the opaque remainder of the |
| 66 | /// commit object (every byte after the `tree` and `parent` lines). |
| 67 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 68 | pub struct GitImportedCommit { |
| 69 | /// The original Git commit ID (the map key; checked again at every export). |
| 70 | pub git_oid: GitOid, |
| 71 | pub tree: TreeDigest, |
| 72 | /// Imported revision IDs of the parents, in the commit's written order. |
| 73 | pub parents: Vec<ChangesetId>, |
| 74 | /// Author, committer, extra headers and message, byte for byte. |
| 75 | pub headers: Vec<u8>, |
| 76 | } |
| 77 | |
| 78 | impl GitImportedCommit { |
| 79 | /// `version u16 (1) | tree [32] | u32 n | parent [32]*n | u32 len | headers`. |
| 80 | pub fn encode_content(&self) -> Vec<u8> { |
| 81 | let mut buf = Vec::with_capacity(46 + 32 * self.parents.len() + self.headers.len()); |
| 82 | buf.extend_from_slice(&GIT_IMPORTED_REVISION_VERSION.to_le_bytes()); |
| 83 | buf.extend_from_slice(&self.tree.0); |
| 84 | buf.extend_from_slice(&(self.parents.len() as u32).to_le_bytes()); |
| 85 | for p in &self.parents { |
| 86 | buf.extend_from_slice(&p.0); |
| 87 | } |
| 88 | buf.extend_from_slice(&(self.headers.len() as u32).to_le_bytes()); |
| 89 | buf.extend_from_slice(&self.headers); |
| 90 | buf |
| 91 | } |
| 92 | |
| 93 | /// `SHA-256(DOMAIN_GIT_IMPORTED_REVISION_V1 || u64 len || encode_content())`. It covers the |
| 94 | /// tree, the parents in order and the opaque headers, so two Git commits are one imported |
| 95 | /// revision exactly when their objects are identical; the Git ID itself is not hashed in. |
| 96 | pub fn changeset_id(&self) -> ChangesetId { |
| 97 | let bytes = self.encode_content(); |
| 98 | let mut h = Sha256::new(); |
| 99 | h.update(DOMAIN_GIT_IMPORTED_REVISION_V1); |
| 100 | h.update((bytes.len() as u64).to_le_bytes()); |
| 101 | h.update(&bytes); |
| 102 | ChangesetId(h.finalize().into()) |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | /// A native identity a tag or reference points at. |
| 107 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] |
| 108 | pub enum GitBridgeTarget { |
| 109 | /// An imported revision. |
| 110 | Commit(ChangesetId), |
| 111 | Tree(TreeDigest), |
| 112 | Blob(BlobDigest), |
| 113 | /// Another imported tag, by its Git ID (tags have no native identity). |
| 114 | Tag(GitOid), |
| 115 | } |
| 116 | |
| 117 | /// An imported annotated tag: its target and every byte after its `object` line. |
| 118 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 119 | pub struct GitImportedTag { |
| 120 | pub git_oid: GitOid, |
| 121 | pub target: GitBridgeTarget, |
| 122 | /// From the `type` line to the end of the object, byte for byte. |
| 123 | pub rest: Vec<u8>, |
| 124 | } |
| 125 | |
| 126 | /// The references of an imported repository: names strictly ascending, and the branch `HEAD` |
| 127 | /// names. |
| 128 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 129 | pub struct GitImportedRefs { |
| 130 | pub refs: Vec<(String, GitBridgeTarget)>, |
| 131 | pub head: Option<String>, |
| 132 | } |
| 133 | |
| 134 | /// The body of one kind 10 record. |
| 135 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 136 | pub enum GitBridgeEntry { |
| 137 | Objects { |
| 138 | blobs: Vec<GitBlobMapping>, |
| 139 | trees: Vec<GitTreeMapping>, |
| 140 | }, |
| 141 | Commit(GitImportedCommit), |
| 142 | Tag(GitImportedTag), |
| 143 | Refs(GitImportedRefs), |
| 144 | } |
| 145 | |
| 146 | impl GitBridgeEntry { |
| 147 | /// Entry tag in the record encoding. |
| 148 | pub fn tag(&self) -> u8 { |
| 149 | match self { |
| 150 | Self::Objects { .. } => 1, |
| 151 | Self::Commit(_) => 2, |
| 152 | Self::Tag(_) => 3, |
| 153 | Self::Refs(_) => 4, |
| 154 | } |
| 155 | } |
| 156 | |
| 157 | /// Blob digests an `Objects` entry maps (all must be visible once the record commits). |
| 158 | pub fn blobs(&self) -> Vec<BlobDigest> { |
| 159 | match self { |
| 160 | Self::Objects { blobs, .. } => blobs.iter().map(|b| b.blob).collect(), |
| 161 | _ => Vec::new(), |
| 162 | } |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | /// Is `name` a reference name the bridge accepts: under `refs/`, no empty, `.`-leading or |
| 167 | /// `..` components, no `.lock` suffix, no control or `" ~^:?*[\"` bytes, at most |
| 168 | /// [`MAX_GIT_REF_NAME_BYTES`]. Export writes each reference as a file below the new |
| 169 | /// repository, so this rule also keeps every write inside it. |
| 170 | pub fn valid_git_ref_name(name: &str) -> bool { |
| 171 | name.len() <= MAX_GIT_REF_NAME_BYTES |
| 172 | && name.starts_with("refs/") |
| 173 | && !name.ends_with('/') |
| 174 | && !name.ends_with(".lock") |
| 175 | && !name.contains("@{") |
| 176 | && name.split('/').all(|c| { |
| 177 | !c.is_empty() && !c.starts_with('.') && !c.ends_with(".lock") && !c.contains("..") |
| 178 | }) |
| 179 | && !name |
| 180 | .bytes() |
| 181 | .any(|b| b < 0x20 || b == 0x7f || b" ~^:?*[\\".contains(&b)) |
| 182 | } |
| 183 | |
| 184 | /// Blobs that come with one kind 10 record: digest and bytes. |
| 185 | pub type GitImportBlobs<'a> = Vec<(BlobDigest, &'a [u8])>; |
| 186 | |
| 187 | /// One record of a Git import batch: the entry and the blobs it brings. |
| 188 | pub type GitImportRecord<'a> = (GitBridgeEntry, GitImportBlobs<'a>); |
| 189 | |
| 190 | fn refused(code: RefusalCode, msg: impl Into<String>) -> SynapseError { |
| 191 | SynapseError::new(code, msg) |
| 192 | } |
| 193 | |
| 194 | /// The persistent map of one repository. |
| 195 | #[derive(Debug, Clone, Default)] |
| 196 | pub struct GitBridgeRepo { |
| 197 | blobs: BTreeMap<GitOid, (BlobDigest, u64)>, |
| 198 | trees: BTreeMap<GitOid, TreeDigest>, |
| 199 | commits: BTreeMap<GitOid, (ChangesetId, GitImportedCommit)>, |
| 200 | by_changeset: BTreeMap<ChangesetId, GitOid>, |
| 201 | tags: BTreeMap<GitOid, GitImportedTag>, |
| 202 | refs: Option<GitImportedRefs>, |
| 203 | /// Reverse maps (native identity to Git ID), so a tree, commit or tag can be re-hashed. |
| 204 | blob_oids: BTreeMap<BlobDigest, GitOid>, |
| 205 | tree_oids: BTreeMap<TreeDigest, GitOid>, |
| 206 | } |
| 207 | |
| 208 | impl GitBridgeRepo { |
| 209 | /// The map: an imported commit's (`ChangesetId`, `TreeDigest`). |
| 210 | pub fn commit(&self, git_oid: GitOid) -> Option<(ChangesetId, TreeDigest)> { |
| 211 | self.commits.get(&git_oid).map(|(id, c)| (*id, c.tree)) |
| 212 | } |
| 213 | |
| 214 | /// The imported commit behind an imported revision ID. |
| 215 | pub fn commit_by_changeset(&self, id: ChangesetId) -> Option<&GitImportedCommit> { |
| 216 | self.by_changeset |
| 217 | .get(&id) |
| 218 | .and_then(|oid| self.commits.get(oid)) |
| 219 | .map(|(_, c)| c) |
| 220 | } |
| 221 | |
| 222 | pub fn blob(&self, git_oid: GitOid) -> Option<(BlobDigest, u64)> { |
| 223 | self.blobs.get(&git_oid).copied() |
| 224 | } |
| 225 | |
| 226 | pub fn tree(&self, git_oid: GitOid) -> Option<TreeDigest> { |
| 227 | self.trees.get(&git_oid).copied() |
| 228 | } |
| 229 | |
| 230 | pub fn tag(&self, git_oid: GitOid) -> Option<&GitImportedTag> { |
| 231 | self.tags.get(&git_oid) |
| 232 | } |
| 233 | |
| 234 | /// Every mapped blob: Git ID to (`BlobDigest`, size). |
| 235 | pub fn blobs(&self) -> &BTreeMap<GitOid, (BlobDigest, u64)> { |
| 236 | &self.blobs |
| 237 | } |
| 238 | |
| 239 | /// Every mapped tree: Git ID to `TreeDigest`. |
| 240 | pub fn trees(&self) -> &BTreeMap<GitOid, TreeDigest> { |
| 241 | &self.trees |
| 242 | } |
| 243 | |
| 244 | /// Every imported commit by Git ID, with its imported revision ID. |
| 245 | pub fn commits(&self) -> impl Iterator<Item = (&GitOid, &(ChangesetId, GitImportedCommit))> { |
| 246 | self.commits.iter() |
| 247 | } |
| 248 | |
| 249 | pub fn tags(&self) -> &BTreeMap<GitOid, GitImportedTag> { |
| 250 | &self.tags |
| 251 | } |
| 252 | |
| 253 | /// The references of the latest `Refs` record. |
| 254 | pub fn refs(&self) -> Option<&GitImportedRefs> { |
| 255 | self.refs.as_ref() |
| 256 | } |
| 257 | |
| 258 | /// Commits, trees, blobs and tags held. |
| 259 | pub fn object_count(&self) -> usize { |
| 260 | self.blobs.len() + self.trees.len() + self.commits.len() + self.tags.len() |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | /// In-memory bridge state, rebuilt from kind 10 records. |
| 265 | #[derive(Debug, Clone, Default)] |
| 266 | pub(crate) struct GitBridgeLedger { |
| 267 | repos: BTreeMap<RepoId, GitBridgeRepo>, |
| 268 | /// Canonical tree nodes by digest (content addressed, shared by every repository). |
| 269 | nodes: BTreeMap<TreeDigest, Vec<u8>>, |
| 270 | /// Size of every blob a Git blob maps to (content addressed, shared). |
| 271 | blob_sizes: BTreeMap<BlobDigest, u64>, |
| 272 | } |
| 273 | |
| 274 | impl GitBridgeLedger { |
| 275 | pub(crate) fn from_log<'a>(log: impl IntoIterator<Item = &'a (WalSeq, WalRecord)>) -> Self { |
| 276 | let mut l = Self::default(); |
| 277 | for (_, record) in log { |
| 278 | l.apply(record); |
| 279 | } |
| 280 | l |
| 281 | } |
| 282 | |
| 283 | pub(crate) fn repo(&self, repo: &RepoId) -> Option<&GitBridgeRepo> { |
| 284 | self.repos.get(repo) |
| 285 | } |
| 286 | |
| 287 | pub(crate) fn node(&self, digest: TreeDigest) -> Option<&[u8]> { |
| 288 | self.nodes.get(&digest).map(Vec::as_slice) |
| 289 | } |
| 290 | |
| 291 | /// Every blob any repository maps (compaction keeps them). |
| 292 | pub(crate) fn blob_digests(&self) -> impl Iterator<Item = BlobDigest> + '_ { |
| 293 | self.blob_sizes.keys().copied() |
| 294 | } |
| 295 | |
| 296 | /// Apply one kind 10 record (other records are ignored). Total: replay applies every |
| 297 | /// record the same way on every replica. |
| 298 | pub(crate) fn apply(&mut self, record: &WalRecord) { |
| 299 | let WalRecord::GitBridgeImported { repo_id, entry, .. } = record else { |
| 300 | return; |
| 301 | }; |
| 302 | let repo = self.repos.entry(repo_id.clone()).or_default(); |
| 303 | match entry { |
| 304 | GitBridgeEntry::Objects { blobs, trees } => { |
| 305 | for b in blobs { |
| 306 | repo.blobs.insert(b.git_oid, (b.blob, b.size_bytes)); |
| 307 | repo.blob_oids.insert(b.blob, b.git_oid); |
| 308 | self.blob_sizes.entry(b.blob).or_insert(b.size_bytes); |
| 309 | } |
| 310 | for t in trees { |
| 311 | let d = t.digest(); |
| 312 | repo.trees.insert(t.git_oid, d); |
| 313 | repo.tree_oids.insert(d, t.git_oid); |
| 314 | self.nodes.entry(d).or_insert_with(|| t.node.clone()); |
| 315 | } |
| 316 | } |
| 317 | GitBridgeEntry::Commit(c) => { |
| 318 | let id = c.changeset_id(); |
| 319 | repo.by_changeset.insert(id, c.git_oid); |
| 320 | repo.commits.insert(c.git_oid, (id, c.clone())); |
| 321 | } |
| 322 | GitBridgeEntry::Tag(t) => { |
| 323 | repo.tags.insert(t.git_oid, t.clone()); |
| 324 | } |
| 325 | GitBridgeEntry::Refs(r) => repo.refs = Some(r.clone()), |
| 326 | } |
| 327 | } |
| 328 | |
| 329 | /// Check one entry against the map before it is written. Returns `false` when the entry |
| 330 | /// is already fully recorded (nothing to write). `provided` holds the blobs whose bytes |
| 331 | /// come with the record; `blob_visible` says whether a blob is already committed and |
| 332 | /// `read_blob` reads one that is. |
| 333 | /// |
| 334 | /// Beyond structure (sizes, visibility, subtrees, parents and targets imported in this |
| 335 | /// repository, no Git ID remapped), every Git ID the entry newly maps is re-hashed from |
| 336 | /// the content it maps to (blob bytes; tree, commit and tag payloads rebuilt from the |
| 337 | /// stored form and the Git IDs already mapped), and a Git ID may appear only once in an |
| 338 | /// entry. So a record cannot map a Git ID to anything export would not give back. |
| 339 | pub(crate) fn check( |
| 340 | &self, |
| 341 | repo_id: &RepoId, |
| 342 | entry: &GitBridgeEntry, |
| 343 | provided: &BTreeMap<BlobDigest, &[u8]>, |
| 344 | blob_visible: &dyn Fn(&BlobDigest) -> bool, |
| 345 | read_blob: &dyn Fn(&BlobDigest) -> SynapseResult<Vec<u8>>, |
| 346 | ) -> SynapseResult<bool> { |
| 347 | let repo = self.repos.get(repo_id); |
| 348 | let conflict = |what: &str, oid: GitOid| { |
| 349 | refused( |
| 350 | RefusalCode::GitObjectCorrupt, |
| 351 | format!("{what} {oid} is already mapped to a different native object"), |
| 352 | ) |
| 353 | }; |
| 354 | match entry { |
| 355 | GitBridgeEntry::Objects { blobs, trees } => { |
| 356 | if blobs.is_empty() && trees.is_empty() { |
| 357 | return Err(refused( |
| 358 | RefusalCode::GitObjectCorrupt, |
| 359 | "an objects entry maps no object", |
| 360 | )); |
| 361 | } |
| 362 | let mut ids: BTreeSet<GitOid> = BTreeSet::new(); |
| 363 | for oid in blobs |
| 364 | .iter() |
| 365 | .map(|b| b.git_oid) |
| 366 | .chain(trees.iter().map(|t| t.git_oid)) |
| 367 | { |
| 368 | if !ids.insert(oid) { |
| 369 | return Err(refused( |
| 370 | RefusalCode::GitObjectCorrupt, |
| 371 | format!("Git ID {oid} appears more than once in one objects entry"), |
| 372 | )); |
| 373 | } |
| 374 | } |
| 375 | let mut fresh = false; |
| 376 | // Blobs this entry maps: digest to (Git ID, size). |
| 377 | let mut entry_blobs: BTreeMap<BlobDigest, (GitOid, u64)> = BTreeMap::new(); |
| 378 | for b in blobs { |
| 379 | let known = match repo.and_then(|r| r.blobs.get(&b.git_oid)) { |
| 380 | Some(&(d, s)) if d == b.blob && s == b.size_bytes => true, |
| 381 | Some(_) => return Err(conflict("Git blob", b.git_oid)), |
| 382 | None => false, |
| 383 | }; |
| 384 | match provided.get(&b.blob) { |
| 385 | Some(bytes) if bytes.len() as u64 != b.size_bytes => { |
| 386 | return Err(refused( |
| 387 | RefusalCode::BlobDigestMismatch, |
| 388 | format!( |
| 389 | "Git blob {} declares {} bytes but its blob holds {}", |
| 390 | b.git_oid, |
| 391 | b.size_bytes, |
| 392 | bytes.len() |
| 393 | ), |
| 394 | )) |
| 395 | } |
| 396 | Some(_) => {} |
| 397 | None if blob_visible(&b.blob) => {} |
| 398 | None => { |
| 399 | return Err(refused( |
| 400 | RefusalCode::BlobNotFound, |
| 401 | format!("Git blob {} maps to missing blob {}", b.git_oid, b.blob), |
| 402 | )) |
| 403 | } |
| 404 | } |
| 405 | if !known { |
| 406 | fresh = true; |
| 407 | let read; |
| 408 | let content: &[u8] = match provided.get(&b.blob) { |
| 409 | Some(bytes) => bytes, |
| 410 | None => { |
| 411 | read = read_blob(&b.blob)?; |
| 412 | &read |
| 413 | } |
| 414 | }; |
| 415 | if content.len() as u64 != b.size_bytes { |
| 416 | return Err(refused( |
| 417 | RefusalCode::BlobDigestMismatch, |
| 418 | format!( |
| 419 | "Git blob {} declares {} bytes but its blob holds {}", |
| 420 | b.git_oid, |
| 421 | b.size_bytes, |
| 422 | content.len() |
| 423 | ), |
| 424 | )); |
| 425 | } |
| 426 | verify_git_id("blob", b.git_oid, content)?; |
| 427 | } |
| 428 | entry_blobs.insert(b.blob, (b.git_oid, b.size_bytes)); |
| 429 | } |
| 430 | let mapped_blob = |blob: &BlobDigest| -> Option<(GitOid, u64)> { |
| 431 | entry_blobs.get(blob).copied().or_else(|| { |
| 432 | let r = repo?; |
| 433 | let oid = *r.blob_oids.get(blob)?; |
| 434 | r.blobs.get(&oid).map(|&(_, s)| (oid, s)) |
| 435 | }) |
| 436 | }; |
| 437 | // Trees this entry maps: digest to Git ID. |
| 438 | let mut entry_trees: BTreeMap<TreeDigest, GitOid> = BTreeMap::new(); |
| 439 | for t in trees { |
| 440 | let digest = t.digest(); |
| 441 | let known = match repo.and_then(|r| r.trees.get(&t.git_oid)) { |
| 442 | Some(&d) if d == digest => true, |
| 443 | Some(_) => return Err(conflict("Git tree", t.git_oid)), |
| 444 | None => false, |
| 445 | }; |
| 446 | let mapped_tree = |child: &TreeDigest| -> Option<GitOid> { |
| 447 | entry_trees |
| 448 | .get(child) |
| 449 | .or_else(|| repo.and_then(|r| r.tree_oids.get(child))) |
| 450 | .copied() |
| 451 | }; |
| 452 | for e in decode_tree_node(&t.node)? { |
| 453 | match e.kind { |
| 454 | TreeNodeEntryKind::File { |
| 455 | blob, size_bytes, .. |
| 456 | } => match mapped_blob(&blob) { |
| 457 | None => { |
| 458 | return Err(refused( |
| 459 | RefusalCode::BlobNotFound, |
| 460 | format!( |
| 461 | "tree {} names blob {blob} that no Git blob of this repository maps", |
| 462 | t.git_oid |
| 463 | ), |
| 464 | )) |
| 465 | } |
| 466 | Some((_, s)) if s != size_bytes => { |
| 467 | return Err(refused( |
| 468 | RefusalCode::BlobDigestMismatch, |
| 469 | format!( |
| 470 | "tree {} gives {} the size {size_bytes} but its blob holds {s}", |
| 471 | t.git_oid, e.name |
| 472 | ), |
| 473 | )) |
| 474 | } |
| 475 | Some(_) => {} |
| 476 | }, |
| 477 | TreeNodeEntryKind::Dir(child) => { |
| 478 | if child == TreeDigest::empty() || mapped_tree(&child).is_none() { |
| 479 | return Err(refused( |
| 480 | RefusalCode::TreeNodeNotFound, |
| 481 | format!( |
| 482 | "tree {} names subtree {child} that is empty or not imported", |
| 483 | t.git_oid |
| 484 | ), |
| 485 | )); |
| 486 | } |
| 487 | } |
| 488 | } |
| 489 | } |
| 490 | if !known { |
| 491 | fresh = true; |
| 492 | let unmapped = || refused(RefusalCode::GitObjectCorrupt, "unmapped entry"); |
| 493 | let payload = git_tree_payload_of_node( |
| 494 | &t.node, |
| 495 | &mut |b| mapped_blob(&b).map(|(o, _)| o).ok_or_else(unmapped), |
| 496 | &mut |c| mapped_tree(&c).ok_or_else(unmapped), |
| 497 | )?; |
| 498 | verify_git_id("tree", t.git_oid, &payload)?; |
| 499 | } |
| 500 | entry_trees.insert(digest, t.git_oid); |
| 501 | } |
| 502 | Ok(fresh) |
| 503 | } |
| 504 | GitBridgeEntry::Commit(c) => { |
| 505 | let id = c.changeset_id(); |
| 506 | if let Some((existing, _)) = repo.and_then(|r| r.commits.get(&c.git_oid)) { |
| 507 | return if *existing == id { |
| 508 | Ok(false) |
| 509 | } else { |
| 510 | Err(conflict("Git commit", c.git_oid)) |
| 511 | }; |
| 512 | } |
| 513 | if let Some(other) = repo.and_then(|r| r.by_changeset.get(&id)) { |
| 514 | return Err(refused( |
| 515 | RefusalCode::GitObjectCorrupt, |
| 516 | format!( |
| 517 | "commit {} has the same content as the imported commit {other}", |
| 518 | c.git_oid |
| 519 | ), |
| 520 | )); |
| 521 | } |
| 522 | let tree = target_oid(repo, &GitBridgeTarget::Tree(c.tree)).map_err(|_| { |
| 523 | refused( |
| 524 | RefusalCode::TreeNodeNotFound, |
| 525 | format!( |
| 526 | "commit {} names tree {} that is not imported", |
| 527 | c.git_oid, c.tree |
| 528 | ), |
| 529 | ) |
| 530 | })?; |
| 531 | let mut payload = format!("tree {}\n", tree.to_hex()).into_bytes(); |
| 532 | for p in &c.parents { |
| 533 | let Some(parent) = repo.and_then(|r| r.by_changeset.get(p)) else { |
| 534 | return Err(refused( |
| 535 | RefusalCode::ParentChangesetNotFound, |
| 536 | format!("commit {} names parent {p} that is not imported", c.git_oid), |
| 537 | )); |
| 538 | }; |
| 539 | payload.extend_from_slice(format!("parent {}\n", parent.to_hex()).as_bytes()); |
| 540 | } |
| 541 | payload.extend_from_slice(&c.headers); |
| 542 | verify_git_id("commit", c.git_oid, &payload)?; |
| 543 | Ok(true) |
| 544 | } |
| 545 | GitBridgeEntry::Tag(t) => { |
| 546 | if let Some(existing) = repo.and_then(|r| r.tags.get(&t.git_oid)) { |
| 547 | return if existing == t { |
| 548 | Ok(false) |
| 549 | } else { |
| 550 | Err(conflict("Git tag", t.git_oid)) |
| 551 | }; |
| 552 | } |
| 553 | let target = target_oid(repo, &t.target)?; |
| 554 | let mut payload = format!("object {}\n", target.to_hex()).into_bytes(); |
| 555 | payload.extend_from_slice(&t.rest); |
| 556 | verify_git_id("tag", t.git_oid, &payload)?; |
| 557 | Ok(true) |
| 558 | } |
| 559 | GitBridgeEntry::Refs(r) => { |
| 560 | check_git_ref_names(r.refs.iter().map(|(n, _)| n.as_str()), r.head.as_deref())?; |
| 561 | for (_, target) in &r.refs { |
| 562 | target_oid(repo, target)?; |
| 563 | } |
| 564 | Ok(repo.and_then(|x| x.refs.as_ref()) != Some(r)) |
| 565 | } |
| 566 | } |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | /// The Git ID a bridge target names in `repo`, refused unless it is imported there (the |
| 571 | /// empty tree is always known: its Git ID is that of the empty Git tree). |
| 572 | fn target_oid(repo: Option<&GitBridgeRepo>, target: &GitBridgeTarget) -> SynapseResult<GitOid> { |
| 573 | let oid = match target { |
| 574 | GitBridgeTarget::Commit(id) => repo.and_then(|r| r.by_changeset.get(id).copied()), |
| 575 | GitBridgeTarget::Tree(d) if *d == TreeDigest::empty() => { |
| 576 | Some(GitOid::compute_git_object("tree", b"")) |
| 577 | } |
| 578 | GitBridgeTarget::Tree(d) => repo.and_then(|r| r.tree_oids.get(d).copied()), |
| 579 | GitBridgeTarget::Blob(b) => repo.and_then(|r| r.blob_oids.get(b).copied()), |
| 580 | GitBridgeTarget::Tag(oid) => repo.filter(|r| r.tags.contains_key(oid)).map(|_| *oid), |
| 581 | }; |
| 582 | oid.ok_or_else(|| { |
| 583 | refused( |
| 584 | RefusalCode::GitObjectCorrupt, |
| 585 | format!("bridge target {target:?} is not imported"), |
| 586 | ) |
| 587 | }) |
| 588 | } |
| 589 | |
| 590 | /// Refuse a Git ID that is not the SHA-1 of its object (`{kind} {len}\0{payload}`). |
| 591 | fn verify_git_id(kind: &str, claimed: GitOid, payload: &[u8]) -> SynapseResult<()> { |
| 592 | let actual = GitOid::compute_git_object(kind, payload); |
| 593 | if actual == claimed { |
| 594 | Ok(()) |
| 595 | } else { |
| 596 | Err(refused( |
| 597 | RefusalCode::GitObjectCorrupt, |
| 598 | format!("Git {kind} {claimed} does not match its content (which hashes to {actual})"), |
| 599 | )) |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | /// Check reference names as a `Refs` record must hold them: each [`valid_git_ref_name`], |
| 604 | /// strictly ascending, no name a directory prefix of another (`refs/a` beside `refs/a/b`: |
| 605 | /// one would be a file and the other a directory), and a valid `HEAD` target. |
| 606 | pub fn check_git_ref_names<'a>( |
| 607 | names: impl IntoIterator<Item = &'a str>, |
| 608 | head: Option<&str>, |
| 609 | ) -> SynapseResult<()> { |
| 610 | let mut seen: BTreeSet<&str> = BTreeSet::new(); |
| 611 | for name in names { |
| 612 | if !valid_git_ref_name(name) { |
| 613 | return Err(refused( |
| 614 | RefusalCode::PathInvalid, |
| 615 | format!("invalid reference name {name:?}"), |
| 616 | )); |
| 617 | } |
| 618 | if seen.last().is_some_and(|p| *p >= name) { |
| 619 | return Err(refused( |
| 620 | RefusalCode::PathInvalid, |
| 621 | "reference names must be strictly ascending", |
| 622 | )); |
| 623 | } |
| 624 | // A prefix sorts first, so it is already in `seen`. |
| 625 | for (i, _) in name.match_indices('/') { |
| 626 | if seen.contains(&name[..i]) { |
| 627 | return Err(refused( |
| 628 | RefusalCode::PathInvalid, |
| 629 | format!("reference {} is a prefix directory of {name}", &name[..i]), |
| 630 | )); |
| 631 | } |
| 632 | } |
| 633 | seen.insert(name); |
| 634 | } |
| 635 | if let Some(head) = head { |
| 636 | if !valid_git_ref_name(head) { |
| 637 | return Err(refused( |
| 638 | RefusalCode::PathInvalid, |
| 639 | format!("invalid HEAD target {head:?}"), |
| 640 | )); |
| 641 | } |
| 642 | } |
| 643 | Ok(()) |
| 644 | } |
| 645 | |
| 646 | /// Digest input of one kind 10 record for the state root and the seal chain: its body |
| 647 | /// (`repo_id | entry`) without the seal trailer, length first. |
| 648 | pub(crate) fn record_digest_input(repo_id: &RepoId, entry: &GitBridgeEntry, h: &mut Sha256) { |
| 649 | if let Ok(bytes) = crate::codec::git_bridge_body(repo_id, entry) { |
| 650 | h.update((bytes.len() as u64).to_le_bytes()); |
| 651 | h.update(&bytes); |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | impl crate::SynapseStore { |
| 656 | /// Write one Git bridge record (WAL kind 10) for `repo_id`: a batch of one, see |
| 657 | /// [`Self::record_git_imports`]. Returns `None` when the entry is already recorded. |
| 658 | pub fn record_git_import( |
| 659 | &mut self, |
| 660 | repo_id: &RepoId, |
| 661 | entry: GitBridgeEntry, |
| 662 | blobs: &[(BlobDigest, &[u8])], |
| 663 | ) -> SynapseResult<Option<WalSeq>> { |
| 664 | let mut out = self.record_git_imports(repo_id, vec![(entry, blobs.to_vec())])?; |
| 665 | Ok(out.pop().flatten()) |
| 666 | } |
| 667 | |
| 668 | /// Write a whole Git import (WAL kind 10 records, in order) for `repo_id`, checked as one |
| 669 | /// unit before the first write. Every record of a batch of more than one is first run |
| 670 | /// against a copy of the map in which the earlier records of the batch are already applied: binary codec, blob caps, |
| 671 | /// each provided blob's digest and that the entry maps it, [`GitBridgeLedger::check`] |
| 672 | /// (structure and every new Git ID re-hashed from its content) and the exact size of its |
| 673 | /// WAL frame against `max_wal_record_bytes`. Only when every record passes are they |
| 674 | /// written, each checked again against the live map. So any refusal the checks can give |
| 675 | /// leaves the store untouched; a failure while writing (an I/O error) can still stop a |
| 676 | /// batch part way, and a re-import then finishes it. Blobs not yet visible go inline. |
| 677 | /// Returns, per record, its sequence number or `None` when it was already recorded. |
| 678 | pub fn record_git_imports( |
| 679 | &mut self, |
| 680 | repo_id: &RepoId, |
| 681 | records: Vec<GitImportRecord<'_>>, |
| 682 | ) -> SynapseResult<Vec<Option<WalSeq>>> { |
| 683 | self.check_writable()?; |
| 684 | self.check_binary_codec()?; |
| 685 | // Dry run on a copy of the map. A single record needs none: its write checks every |
| 686 | // limit, the frame size included, before anything is written. |
| 687 | let mut sim = (records.len() > 1).then(|| self.git_bridge.clone()); |
| 688 | let mut sim_visible: BTreeSet<BlobDigest> = BTreeSet::new(); |
| 689 | let mut prepared = Vec::with_capacity(records.len()); |
| 690 | for (entry, blobs) in records { |
| 691 | let record = WalRecord::GitBridgeImported { |
| 692 | repo_id: repo_id.clone(), |
| 693 | entry, |
| 694 | seal: None, |
| 695 | }; |
| 696 | if let Some(sim) = sim.as_mut() { |
| 697 | let visible = |d: &BlobDigest| { |
| 698 | self.blob_first_visible_seq.contains_key(d) || sim_visible.contains(d) |
| 699 | }; |
| 700 | if let Some(inline) = self.prepare_git_import(sim, &record, &blobs, &visible)? { |
| 701 | self.check_frame_cap(self.git_import_frame_len(&record, &inline)?)?; |
| 702 | sim_visible.extend(inline.iter().map(|(d, _)| *d)); |
| 703 | sim.apply(&record); |
| 704 | } |
| 705 | } |
| 706 | prepared.push((record, blobs)); |
| 707 | } |
| 708 | drop(sim); |
| 709 | let mut out = Vec::with_capacity(prepared.len()); |
| 710 | for (record, blobs) in prepared { |
| 711 | let visible = |d: &BlobDigest| self.blob_first_visible_seq.contains_key(d); |
| 712 | let seq = match self.prepare_git_import(&self.git_bridge, &record, &blobs, &visible)? { |
| 713 | None => None, |
| 714 | Some(inline) => Some(self.append_revision_record(record, &inline, None)?), |
| 715 | }; |
| 716 | out.push(seq); |
| 717 | } |
| 718 | Ok(out) |
| 719 | } |
| 720 | |
| 721 | /// Every check of one kind 10 record against `ledger`. Returns the blobs to put inline, |
| 722 | /// or `None` when the entry is already recorded. |
| 723 | fn prepare_git_import<'b>( |
| 724 | &self, |
| 725 | ledger: &GitBridgeLedger, |
| 726 | record: &WalRecord, |
| 727 | blobs: &[(BlobDigest, &'b [u8])], |
| 728 | visible: &dyn Fn(&BlobDigest) -> bool, |
| 729 | ) -> SynapseResult<Option<GitImportBlobs<'b>>> { |
| 730 | let WalRecord::GitBridgeImported { repo_id, entry, .. } = record else { |
| 731 | return Err(refused( |
| 732 | RefusalCode::GitObjectCorrupt, |
| 733 | "not a Git bridge record", |
| 734 | )); |
| 735 | }; |
| 736 | let mapped: BTreeSet<BlobDigest> = entry.blobs().into_iter().collect(); |
| 737 | let mut provided: BTreeMap<BlobDigest, &[u8]> = BTreeMap::new(); |
| 738 | let mut total = 0u64; |
| 739 | for (declared, bytes) in blobs { |
| 740 | let len = bytes.len() as u64; |
| 741 | total = total.saturating_add(len); |
| 742 | if len > self.limits.max_blob_bytes || total > self.limits.max_total_changeset_bytes { |
| 743 | return Err(refused( |
| 744 | RefusalCode::QuotaPayloadTooLarge, |
| 745 | "Git bridge blobs exceed max_blob_bytes or max_total_changeset_bytes", |
| 746 | )); |
| 747 | } |
| 748 | let actual = BlobDigest::compute(bytes); |
| 749 | if actual != *declared { |
| 750 | return Err(refused( |
| 751 | RefusalCode::BlobDigestMismatch, |
| 752 | format!("declared blob digest {declared} does not match computed {actual}"), |
| 753 | )); |
| 754 | } |
| 755 | if !mapped.contains(declared) { |
| 756 | return Err(refused( |
| 757 | RefusalCode::GitObjectCorrupt, |
| 758 | format!("blob {declared} is provided but no Git blob maps to it"), |
| 759 | )); |
| 760 | } |
| 761 | provided.insert(*declared, bytes); |
| 762 | } |
| 763 | let read_blob = |d: &BlobDigest| self.get_blob_visible(*d, None, None); |
| 764 | if !ledger.check(repo_id, entry, &provided, visible, &read_blob)? { |
| 765 | return Ok(None); |
| 766 | } |
| 767 | let mut inline: GitImportBlobs<'b> = Vec::new(); |
| 768 | for (digest, bytes) in blobs { |
| 769 | if !visible(digest) && !inline.iter().any(|(d, _)| d == digest) { |
| 770 | inline.push((*digest, *bytes)); |
| 771 | } |
| 772 | } |
| 773 | Ok(Some(inline)) |
| 774 | } |
| 775 | |
| 776 | /// The exact WAL payload length `append_revision_record` gives `record` with `inline` |
| 777 | /// blobs (v2: `u32 meta_len | meta | u32 count | (digest | u32 len | bytes)*`; v1: the |
| 778 | /// metadata, blobs go to files). A sealed store adds the seal trailer `tag | server key | |
| 779 | /// signature` (1 + 32 + 64 bytes) that the write seals `record` with. |
| 780 | fn git_import_frame_len( |
| 781 | &self, |
| 782 | record: &WalRecord, |
| 783 | inline: &[(BlobDigest, &[u8])], |
| 784 | ) -> SynapseResult<usize> { |
| 785 | let trailer = if self.revision_seal.is_some() && record.seal().is_none() { |
| 786 | 1 + 32 + 64 |
| 787 | } else { |
| 788 | 0 |
| 789 | }; |
| 790 | let meta = crate::codec::encode_record_with(record, self.codec)?.len() + trailer; |
| 791 | Ok(if self.v2_mode { |
| 792 | inline |
| 793 | .iter() |
| 794 | .fold(8 + meta, |n, (_, b)| n.saturating_add(36 + b.len())) |
| 795 | } else { |
| 796 | meta |
| 797 | }) |
| 798 | } |
| 799 | |
| 800 | /// The Git bridge map of `repo_id`, if anything was imported into it. |
| 801 | pub fn git_bridge_repo(&self, repo_id: &RepoId) -> Option<&GitBridgeRepo> { |
| 802 | self.git_bridge.repo(repo_id) |
| 803 | } |
| 804 | |
| 805 | /// The canonical node bytes of an imported tree (`TreeDigest` to C1 version 1 encoding). |
| 806 | pub fn git_bridge_tree_node(&self, digest: TreeDigest) -> Option<&[u8]> { |
| 807 | self.git_bridge.node(digest) |
| 808 | } |
| 809 | } |
| 810 | |
| 811 | #[cfg(test)] |
| 812 | mod tests { |
| 813 | use super::*; |
| 814 | use crate::codec::{decode_record, encode_record, encode_record_with, RecordCodec}; |
| 815 | use synapse_core::{FileMode, TreeNodeEncoder}; |
| 816 | |
| 817 | const CAP: u64 = 1 << 20; |
| 818 | |
| 819 | fn records() -> Vec<WalRecord> { |
| 820 | let repo = RepoId::new("aien-dev/h1-codec").unwrap(); |
| 821 | let body = b"hello\n"; |
| 822 | let blob = BlobDigest::compute(body); |
| 823 | let mut enc = TreeNodeEncoder::new(1); |
| 824 | enc.file("a.txt", FileMode::Regular644, &blob, body.len() as u64) |
| 825 | .unwrap(); |
| 826 | let (tree, node) = enc.finish().unwrap(); |
| 827 | let commit = GitImportedCommit { |
| 828 | git_oid: GitOid::compute_git_object("commit", b"c"), |
| 829 | tree, |
| 830 | parents: vec![ChangesetId(Sha256::digest(b"parent").into())], |
| 831 | headers: b"author a <a@b> 0 +0000\ncommitter a <a@b> 0 +0000\n\nm\n".to_vec(), |
| 832 | }; |
| 833 | let entries = vec![ |
| 834 | GitBridgeEntry::Objects { |
| 835 | blobs: vec![GitBlobMapping { |
| 836 | git_oid: GitOid::compute_blob(body), |
| 837 | blob, |
| 838 | size_bytes: body.len() as u64, |
| 839 | }], |
| 840 | trees: vec![GitTreeMapping { |
| 841 | git_oid: GitOid::compute_git_object("tree", b"t"), |
| 842 | node, |
| 843 | }], |
| 844 | }, |
| 845 | GitBridgeEntry::Commit(commit.clone()), |
| 846 | GitBridgeEntry::Tag(GitImportedTag { |
| 847 | git_oid: GitOid::compute_git_object("tag", b"t"), |
| 848 | target: GitBridgeTarget::Commit(commit.changeset_id()), |
| 849 | rest: b"type commit\ntag v1\n\nm\n".to_vec(), |
| 850 | }), |
| 851 | GitBridgeEntry::Refs(GitImportedRefs { |
| 852 | refs: vec![ |
| 853 | ("refs/heads/main".into(), GitBridgeTarget::Tree(tree)), |
| 854 | ("refs/tags/b".into(), GitBridgeTarget::Blob(blob)), |
| 855 | ( |
| 856 | "refs/tags/t".into(), |
| 857 | GitBridgeTarget::Tag(GitOid::compute_git_object("tag", b"t")), |
| 858 | ), |
| 859 | ], |
| 860 | head: Some("refs/heads/main".into()), |
| 861 | }), |
| 862 | GitBridgeEntry::Refs(GitImportedRefs { |
| 863 | refs: Vec::new(), |
| 864 | head: None, |
| 865 | }), |
| 866 | ]; |
| 867 | entries |
| 868 | .into_iter() |
| 869 | .map(|entry| WalRecord::GitBridgeImported { |
| 870 | repo_id: repo.clone(), |
| 871 | entry, |
| 872 | seal: None, |
| 873 | }) |
| 874 | .collect() |
| 875 | } |
| 876 | |
| 877 | #[test] |
| 878 | fn kind_10_round_trips_and_every_truncation_is_refused() { |
| 879 | for record in records() { |
| 880 | let bytes = encode_record(&record).unwrap(); |
| 881 | assert_eq!(bytes[1], 10, "record kind 10"); |
| 882 | assert_eq!(decode_record(&bytes, CAP).unwrap(), record); |
| 883 | for cut in 0..bytes.len() { |
| 884 | assert!( |
| 885 | decode_record(&bytes[..cut], CAP).is_err(), |
| 886 | "a record cut at {cut} of {} bytes decoded", |
| 887 | bytes.len() |
| 888 | ); |
| 889 | } |
| 890 | let mut trailing = bytes.clone(); |
| 891 | trailing.push(0); |
| 892 | assert!(decode_record(&trailing, CAP).is_err(), "trailing byte"); |
| 893 | assert!( |
| 894 | encode_record_with(&record, RecordCodec::JsonV1).is_err(), |
| 895 | "kind 10 has no JSON form" |
| 896 | ); |
| 897 | } |
| 898 | } |
| 899 | |
| 900 | #[test] |
| 901 | fn kind_10_is_a_sealed_revision_record_and_its_digest_excludes_the_seal() { |
| 902 | for mut record in records() { |
| 903 | assert!( |
| 904 | record.is_revision_record(), |
| 905 | "kind 10 is sealed (issue #101)" |
| 906 | ); |
| 907 | let unsealed = encode_record(&record).unwrap(); |
| 908 | let digest = crate::revision::record_digest(&record); |
| 909 | record.set_seal(crate::RevisionSeal { |
| 910 | server_key: [7; 32], |
| 911 | signature: [9; 64], |
| 912 | }); |
| 913 | let sealed = encode_record(&record).unwrap(); |
| 914 | assert_eq!(sealed.len(), unsealed.len() + 1 + 32 + 64, "seal trailer"); |
| 915 | assert_eq!(&sealed[..unsealed.len()], &unsealed[..]); |
| 916 | assert_eq!(decode_record(&sealed, CAP).unwrap(), record); |
| 917 | assert_eq!( |
| 918 | crate::revision::record_digest(&record), |
| 919 | digest, |
| 920 | "the seal covers the digest, so the digest leaves the seal out" |
| 921 | ); |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | #[test] |
| 926 | fn imported_revision_id_covers_tree_parents_and_headers() { |
| 927 | let base = match &records()[1] { |
| 928 | WalRecord::GitBridgeImported { |
| 929 | entry: GitBridgeEntry::Commit(c), |
| 930 | .. |
| 931 | } => c.clone(), |
| 932 | _ => unreachable!(), |
| 933 | }; |
| 934 | let id = base.changeset_id(); |
| 935 | let mut other_oid = base.clone(); |
| 936 | other_oid.git_oid = GitOid::compute_git_object("commit", b"other"); |
| 937 | assert_eq!(other_oid.changeset_id(), id, "the Git ID is not hashed in"); |
| 938 | let mut changed = base.clone(); |
| 939 | changed.headers.push(b'x'); |
| 940 | assert_ne!(changed.changeset_id(), id); |
| 941 | let mut changed = base.clone(); |
| 942 | changed.parents.push(changed.parents[0]); |
| 943 | assert_ne!(changed.changeset_id(), id); |
| 944 | let mut changed = base; |
| 945 | changed.tree = TreeDigest::empty(); |
| 946 | assert_ne!(changed.changeset_id(), id); |
| 947 | } |
| 948 | |
| 949 | /// Issue #101 for kind 10: on a sealed store, a Git bridge record without a valid seal |
| 950 | /// maps nothing. Strict replay refuses the store; torn-tail replay opens it with the |
| 951 | /// record reported unsealed and the repository absent from the bridge map, and the |
| 952 | /// record is left out by compaction. |
| 953 | #[test] |
| 954 | fn kind_10_without_a_seal_maps_nothing_on_sealed_replay() { |
| 955 | use crate::{FsyncPolicy, RecoveryPolicy, RevisionSealKey, StoreLimits, SynapseStore}; |
| 956 | let nanos = std::time::SystemTime::now() |
| 957 | .duration_since(std::time::UNIX_EPOCH) |
| 958 | .unwrap() |
| 959 | .as_nanos(); |
| 960 | let dir = std::env::temp_dir().join(format!( |
| 961 | "synapse-h1-unsealed-{}-{nanos}", |
| 962 | std::process::id() |
| 963 | )); |
| 964 | std::fs::create_dir_all(&dir).unwrap(); |
| 965 | let limits = || StoreLimits { |
| 966 | wal_prealloc_bytes: 64 * 1024, |
| 967 | ..Default::default() |
| 968 | }; |
| 969 | let key = || RevisionSealKey::new(ed25519_dalek::SigningKey::from_bytes(&[3; 32])); |
| 970 | let repo = RepoId::new("aien-dev/h1-unsealed").unwrap(); |
| 971 | let body = b"unsealed\n"; |
| 972 | let blob = BlobDigest::compute(body); |
| 973 | let git_oid = GitOid::compute_blob(body); |
| 974 | let entry = GitBridgeEntry::Objects { |
| 975 | blobs: vec![GitBlobMapping { |
| 976 | git_oid, |
| 977 | blob, |
| 978 | size_bytes: body.len() as u64, |
| 979 | }], |
| 980 | trees: Vec::new(), |
| 981 | }; |
| 982 | let mut w = SynapseStore::open( |
| 983 | &dir, |
| 984 | FsyncPolicy::EveryCommit, |
| 985 | RecoveryPolicy::StrictFailClosed, |
| 986 | limits(), |
| 987 | ) |
| 988 | .unwrap(); |
| 989 | assert!(w |
| 990 | .record_git_import(&repo, entry, &[(blob, &body[..])]) |
| 991 | .unwrap() |
| 992 | .is_some()); |
| 993 | assert_eq!( |
| 994 | w.git_bridge_repo(&repo).and_then(|r| r.blob(git_oid)), |
| 995 | Some((blob, body.len() as u64)), |
| 996 | "an unsealed store maps it" |
| 997 | ); |
| 998 | drop(w); |
| 999 | |
| 1000 | let sealed = |policy| { |
| 1001 | SynapseStore::open_sealed(&dir, FsyncPolicy::EveryCommit, policy, limits(), key()) |
| 1002 | }; |
| 1003 | assert_eq!( |
| 1004 | sealed(RecoveryPolicy::StrictFailClosed).err().unwrap().code, |
| 1005 | RefusalCode::RevisionRecordUnsealed |
| 1006 | ); |
| 1007 | let mut s = sealed(RecoveryPolicy::TruncateTornTail).unwrap(); |
| 1008 | assert_eq!(s.seal_replay_report().unsealed, 1); |
| 1009 | assert!( |
| 1010 | s.git_bridge_repo(&repo).is_none(), |
| 1011 | "an unsealed kind 10 record mapped a Git ID on sealed replay" |
| 1012 | ); |
| 1013 | s.checkpoint_and_compact(1_000).unwrap(); |
| 1014 | drop(s); |
| 1015 | let s = |
| 1016 | sealed(RecoveryPolicy::StrictFailClosed).expect("strict accepts the compacted store"); |
| 1017 | assert!(s.git_bridge_repo(&repo).is_none()); |
| 1018 | let _ = std::fs::remove_dir_all(&dir); |
| 1019 | } |
| 1020 | } |