synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-git / src / bridge.rs
| 1 | //! ADR 0003 step H1 cut 2: the native side of the Git bridge (section 5.10). See |
| 2 | //! `docs/H1_GIT_BRIDGE.md`. |
| 3 | //! |
| 4 | //! * [`import_repository`] / [`import_history`]: a repository's full history into the store as |
| 5 | //! WAL kind 10 records (`synapse_store::git_bridge`). Blobs become stored blobs, trees become |
| 6 | //! canonical `TreeDigest` nodes (C1), commits become imported revisions that keep every byte |
| 7 | //! after their `tree` and `parent` lines, annotated tags keep every byte after their `object` |
| 8 | //! line, and the references are recorded last. Every object is converted and checked before |
| 9 | //! the first record is written, so a refused repository leaves the store unchanged. |
| 10 | //! * [`export_store`]: a new bare repository from the store alone. Imported objects are rebuilt |
| 11 | //! from their native form and the stored bytes, and each must hash to the Git ID it was |
| 12 | //! imported under. Native revisions (envelope v2) are written with generated, deterministic |
| 13 | //! commit fields. |
| 14 | |
| 15 | use crate::object::{parse_commit_links, parse_tag_target, parse_tree, GitTreeEntry}; |
| 16 | use crate::repo::{export_repository, ExportReceipt, GitHistory, GitRepository, ReadLimits}; |
| 17 | use crate::{GitObject, ObjectKind}; |
| 18 | use std::collections::{BTreeMap, HashMap, HashSet}; |
| 19 | use std::path::Path; |
| 20 | use synapse_core::{ |
| 21 | decode_tree_node, git_tree_payload_of_node, tree_entry_order, validate_tree_entry_name, |
| 22 | BlobDigest, ChangesetId, FileMode, GitOid, MutationOp, RefusalCode, RepoId, SynapseError, |
| 23 | SynapseResult, TreeDigest, TreeNodeEncoder, TreeNodeEntryKind, |
| 24 | }; |
| 25 | use synapse_store::git_bridge::{ |
| 26 | check_git_ref_names, GitBlobMapping, GitBridgeEntry, GitBridgeRepo, GitBridgeTarget, |
| 27 | GitImportRecord, GitImportedCommit, GitImportedRefs, GitImportedTag, GitTreeMapping, |
| 28 | }; |
| 29 | use synapse_store::SynapseStore; |
| 30 | |
| 31 | /// Most object mappings in one `Objects` record. |
| 32 | pub const MAX_MAPPINGS_PER_RECORD: usize = 4096; |
| 33 | |
| 34 | /// Author email of an exported native revision (its name is the first author's DID). |
| 35 | pub const NATIVE_AUTHOR_EMAIL: &str = "agent@synapse.aienos.local"; |
| 36 | |
| 37 | /// Committer line identity of an exported native revision. |
| 38 | pub const NATIVE_COMMITTER: &str = "Synapse Engine <synapse@aienos.local>"; |
| 39 | |
| 40 | fn not_representable(msg: impl Into<String>) -> SynapseError { |
| 41 | SynapseError::new(RefusalCode::GitObjectNotRepresentable, msg) |
| 42 | } |
| 43 | |
| 44 | fn corrupt(msg: impl Into<String>) -> SynapseError { |
| 45 | SynapseError::new(RefusalCode::GitObjectCorrupt, msg) |
| 46 | } |
| 47 | |
| 48 | /// What an import wrote. |
| 49 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 50 | pub struct ImportReceipt { |
| 51 | pub blobs: usize, |
| 52 | pub trees: usize, |
| 53 | pub commits: usize, |
| 54 | pub tags: usize, |
| 55 | pub refs: usize, |
| 56 | /// Kind 10 records written. |
| 57 | pub records_written: usize, |
| 58 | /// Records skipped because the store already held them (a repeated import). |
| 59 | pub records_skipped: usize, |
| 60 | } |
| 61 | |
| 62 | /// Read `git_dir`'s full history under `limits` and import it as `repo_id`. |
| 63 | pub fn import_repository( |
| 64 | store: &mut SynapseStore, |
| 65 | repo_id: &RepoId, |
| 66 | git_dir: &Path, |
| 67 | limits: ReadLimits, |
| 68 | ) -> SynapseResult<ImportReceipt> { |
| 69 | let history = GitRepository::open_with_limits(git_dir, limits)?.full_history()?; |
| 70 | import_history(store, repo_id, &history) |
| 71 | } |
| 72 | |
| 73 | /// A Git tree entry mode as a native entry: a file mode, or `None` for a subtree. Only the |
| 74 | /// modes Git writes today are representable (`100644`, `100755`, `120000`, `40000`). |
| 75 | fn native_mode(mode: &[u8]) -> SynapseResult<Option<FileMode>> { |
| 76 | match mode { |
| 77 | b"100644" => Ok(Some(FileMode::Regular644)), |
| 78 | b"100755" => Ok(Some(FileMode::Executable755)), |
| 79 | b"120000" => Ok(Some(FileMode::Symlink120000)), |
| 80 | b"40000" => Ok(None), |
| 81 | other => Err(not_representable(format!( |
| 82 | "tree entry mode {:?} has no native form (gitlinks and legacy modes are not imported)", |
| 83 | String::from_utf8_lossy(other) |
| 84 | ))), |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// The Git tree a canonical node stands for. Entries keep the node's order, which is Git's |
| 89 | /// tree order; `blob_oid` and `tree_oid` give the Git ID of each entry. |
| 90 | fn git_tree_of_node( |
| 91 | node: &[u8], |
| 92 | blob_oid: &dyn Fn(BlobDigest) -> SynapseResult<GitOid>, |
| 93 | tree_oid: &dyn Fn(TreeDigest) -> SynapseResult<GitOid>, |
| 94 | ) -> SynapseResult<GitObject> { |
| 95 | let payload = git_tree_payload_of_node(node, &mut |b| blob_oid(b), &mut |t| tree_oid(t))?; |
| 96 | Ok(GitObject::new(ObjectKind::Tree, payload)) |
| 97 | } |
| 98 | |
| 99 | /// `tree <hex>\n` then `parent <hex>\n` for each parent: the part of a commit the native |
| 100 | /// form stores as links. |
| 101 | fn commit_link_lines(tree: GitOid, parents: &[GitOid]) -> Vec<u8> { |
| 102 | let mut out = format!("tree {}\n", tree.to_hex()).into_bytes(); |
| 103 | for p in parents { |
| 104 | out.extend_from_slice(format!("parent {}\n", p.to_hex()).as_bytes()); |
| 105 | } |
| 106 | out |
| 107 | } |
| 108 | |
| 109 | /// Order `oids` so every object comes after the objects `links` names (iterative depth first, |
| 110 | /// so a long history cannot overflow the stack). A link to an object outside `oids` is |
| 111 | /// ignored here (the caller resolves it). |
| 112 | fn links_first( |
| 113 | oids: &[GitOid], |
| 114 | links: &dyn Fn(GitOid) -> SynapseResult<Vec<GitOid>>, |
| 115 | ) -> SynapseResult<Vec<GitOid>> { |
| 116 | let members: std::collections::HashSet<GitOid> = oids.iter().copied().collect(); |
| 117 | let mut done: std::collections::HashSet<GitOid> = std::collections::HashSet::new(); |
| 118 | let mut order = Vec::with_capacity(oids.len()); |
| 119 | for &root in oids { |
| 120 | let mut stack = vec![(root, false)]; |
| 121 | while let Some((oid, expanded)) = stack.pop() { |
| 122 | if done.contains(&oid) { |
| 123 | continue; |
| 124 | } |
| 125 | if expanded { |
| 126 | done.insert(oid); |
| 127 | order.push(oid); |
| 128 | continue; |
| 129 | } |
| 130 | stack.push((oid, true)); |
| 131 | for l in links(oid)? { |
| 132 | if members.contains(&l) && !done.contains(&l) { |
| 133 | stack.push((l, false)); |
| 134 | } |
| 135 | } |
| 136 | } |
| 137 | } |
| 138 | Ok(order) |
| 139 | } |
| 140 | |
| 141 | /// Import `history` as `repo_id`. Every object is converted first; a refusal (unrepresentable |
| 142 | /// tree, non-canonical commit or tag layout, invalid reference name, a blob over the store's |
| 143 | /// blob cap) happens before anything is written. Records then go in dependency order: objects |
| 144 | /// (blobs, then trees, children first), commits (parents first), tags, and one `Refs` record. |
| 145 | /// Importing the same history again writes nothing. |
| 146 | pub fn import_history( |
| 147 | store: &mut SynapseStore, |
| 148 | repo_id: &RepoId, |
| 149 | history: &GitHistory, |
| 150 | ) -> SynapseResult<ImportReceipt> { |
| 151 | let limits = store.limits().clone(); |
| 152 | let of_kind = |k: ObjectKind| -> Vec<GitOid> { |
| 153 | history |
| 154 | .objects |
| 155 | .iter() |
| 156 | .filter(|(_, o)| o.kind == k) |
| 157 | .map(|(oid, _)| *oid) |
| 158 | .collect() |
| 159 | }; |
| 160 | let object = |oid: GitOid| -> SynapseResult<&GitObject> { |
| 161 | history |
| 162 | .objects |
| 163 | .get(&oid) |
| 164 | .ok_or_else(|| corrupt(format!("object {oid} is not in the history"))) |
| 165 | }; |
| 166 | |
| 167 | // Blobs. |
| 168 | let mut blobs: HashMap<GitOid, (BlobDigest, u64)> = HashMap::new(); |
| 169 | let mut blob_oids: HashMap<BlobDigest, GitOid> = HashMap::new(); |
| 170 | let blob_list = of_kind(ObjectKind::Blob); |
| 171 | for &oid in &blob_list { |
| 172 | let payload = &object(oid)?.payload; |
| 173 | let size = payload.len() as u64; |
| 174 | if size > limits.max_blob_bytes { |
| 175 | return Err(SynapseError::new( |
| 176 | RefusalCode::QuotaPayloadTooLarge, |
| 177 | format!( |
| 178 | "Git blob {oid} holds {size} bytes, over the store's max_blob_bytes {}", |
| 179 | limits.max_blob_bytes |
| 180 | ), |
| 181 | )); |
| 182 | } |
| 183 | let digest = BlobDigest::compute(payload); |
| 184 | blobs.insert(oid, (digest, size)); |
| 185 | blob_oids.insert(digest, oid); |
| 186 | } |
| 187 | |
| 188 | // Trees, children first. |
| 189 | let tree_list = of_kind(ObjectKind::Tree); |
| 190 | let tree_order = links_first(&tree_list, &|oid| { |
| 191 | Ok(parse_tree(&object(oid)?.payload)? |
| 192 | .into_iter() |
| 193 | .filter(|e| e.mode == b"40000" || e.mode == b"040000") |
| 194 | .map(|e| e.oid) |
| 195 | .collect()) |
| 196 | })?; |
| 197 | let mut trees: HashMap<GitOid, (TreeDigest, Vec<u8>)> = HashMap::new(); |
| 198 | let mut tree_oids: HashMap<TreeDigest, GitOid> = HashMap::new(); |
| 199 | for &oid in &tree_order { |
| 200 | let entries = parse_tree(&object(oid)?.payload)?; |
| 201 | let count = u32::try_from(entries.len()) |
| 202 | .map_err(|_| not_representable(format!("tree {oid} has too many entries")))?; |
| 203 | let mut enc = TreeNodeEncoder::new(count); |
| 204 | for e in &entries { |
| 205 | let name = std::str::from_utf8(&e.name).map_err(|_| { |
| 206 | not_representable(format!("tree {oid} has an entry name that is not UTF-8")) |
| 207 | })?; |
| 208 | validate_tree_entry_name(name) |
| 209 | .map_err(|err| not_representable(format!("tree {oid}: {}", err.message)))?; |
| 210 | let pushed = match native_mode(&e.mode)? { |
| 211 | Some(mode) => { |
| 212 | let (blob, size) = *blobs.get(&e.oid).ok_or_else(|| { |
| 213 | corrupt(format!("tree {oid} names {} which is not a blob", e.oid)) |
| 214 | })?; |
| 215 | enc.file(name, mode, &blob, size) |
| 216 | } |
| 217 | None => { |
| 218 | let (child, _) = trees.get(&e.oid).ok_or_else(|| { |
| 219 | corrupt(format!("tree {oid} names {} which is not a tree", e.oid)) |
| 220 | })?; |
| 221 | if *child == TreeDigest::empty() { |
| 222 | return Err(not_representable(format!( |
| 223 | "tree {oid} holds an empty subtree {name:?}" |
| 224 | ))); |
| 225 | } |
| 226 | enc.dir(name, child) |
| 227 | } |
| 228 | }; |
| 229 | pushed.map_err(|err| not_representable(format!("tree {oid}: {}", err.message)))?; |
| 230 | } |
| 231 | let (digest, node) = enc |
| 232 | .finish() |
| 233 | .map_err(|err| not_representable(format!("tree {oid}: {}", err.message)))?; |
| 234 | // The node must give back exactly this tree (mode spelling, order, names). |
| 235 | let rebuilt = git_tree_of_node( |
| 236 | &node, |
| 237 | &|b| { |
| 238 | blob_oids |
| 239 | .get(&b) |
| 240 | .copied() |
| 241 | .ok_or_else(|| corrupt(format!("blob {b} has no Git ID"))) |
| 242 | }, |
| 243 | &|t| { |
| 244 | tree_oids |
| 245 | .get(&t) |
| 246 | .copied() |
| 247 | .ok_or_else(|| corrupt(format!("tree {t} has no Git ID"))) |
| 248 | }, |
| 249 | )?; |
| 250 | if rebuilt.oid() != oid { |
| 251 | return Err(not_representable(format!( |
| 252 | "tree {oid} is not in Git's canonical layout (its native form rebuilds as {})", |
| 253 | rebuilt.oid() |
| 254 | ))); |
| 255 | } |
| 256 | tree_oids.insert(digest, oid); |
| 257 | trees.insert(oid, (digest, node)); |
| 258 | } |
| 259 | |
| 260 | // Commits, parents first. |
| 261 | let commit_list = of_kind(ObjectKind::Commit); |
| 262 | let commit_order = links_first(&commit_list, &|oid| { |
| 263 | Ok(parse_commit_links(&object(oid)?.payload)?.parents) |
| 264 | })?; |
| 265 | let mut commits: HashMap<GitOid, ChangesetId> = HashMap::new(); |
| 266 | let mut commit_entries = Vec::with_capacity(commit_order.len()); |
| 267 | for &oid in &commit_order { |
| 268 | let payload = &object(oid)?.payload; |
| 269 | let links = parse_commit_links(payload)?; |
| 270 | let prefix = commit_link_lines(links.tree, &links.parents); |
| 271 | if !payload.starts_with(&prefix) { |
| 272 | return Err(not_representable(format!( |
| 273 | "commit {oid} does not start with its tree and parent lines in canonical form" |
| 274 | ))); |
| 275 | } |
| 276 | let (tree, _) = trees |
| 277 | .get(&links.tree) |
| 278 | .ok_or_else(|| corrupt(format!("commit {oid} names tree {} not read", links.tree)))?; |
| 279 | let parents = links |
| 280 | .parents |
| 281 | .iter() |
| 282 | .map(|p| { |
| 283 | commits |
| 284 | .get(p) |
| 285 | .copied() |
| 286 | .ok_or_else(|| corrupt(format!("commit {oid} names parent {p} not read"))) |
| 287 | }) |
| 288 | .collect::<SynapseResult<Vec<_>>>()?; |
| 289 | let c = GitImportedCommit { |
| 290 | git_oid: oid, |
| 291 | tree: *tree, |
| 292 | parents, |
| 293 | headers: payload[prefix.len()..].to_vec(), |
| 294 | }; |
| 295 | commits.insert(oid, c.changeset_id()); |
| 296 | commit_entries.push(c); |
| 297 | } |
| 298 | |
| 299 | // Annotated tags, inner tags first. |
| 300 | let target_of = |oid: GitOid, tags: &HashMap<GitOid, ()>| -> SynapseResult<GitBridgeTarget> { |
| 301 | let kind = object(oid)?.kind; |
| 302 | let missing = || corrupt(format!("{} {oid} was not imported", kind.name())); |
| 303 | Ok(match kind { |
| 304 | ObjectKind::Commit => GitBridgeTarget::Commit(*commits.get(&oid).ok_or_else(missing)?), |
| 305 | ObjectKind::Tree => GitBridgeTarget::Tree(trees.get(&oid).ok_or_else(missing)?.0), |
| 306 | ObjectKind::Blob => GitBridgeTarget::Blob(blobs.get(&oid).ok_or_else(missing)?.0), |
| 307 | ObjectKind::Tag => { |
| 308 | tags.get(&oid).ok_or_else(missing)?; |
| 309 | GitBridgeTarget::Tag(oid) |
| 310 | } |
| 311 | }) |
| 312 | }; |
| 313 | let tag_list = of_kind(ObjectKind::Tag); |
| 314 | let tag_order = links_first(&tag_list, &|oid| { |
| 315 | Ok(vec![parse_tag_target(&object(oid)?.payload)?.0]) |
| 316 | })?; |
| 317 | let mut tags: HashMap<GitOid, ()> = HashMap::new(); |
| 318 | let mut tag_entries = Vec::with_capacity(tag_order.len()); |
| 319 | for &oid in &tag_order { |
| 320 | let payload = &object(oid)?.payload; |
| 321 | let (target, _) = parse_tag_target(payload)?; |
| 322 | let prefix = format!("object {}\n", target.to_hex()); |
| 323 | if !payload.starts_with(prefix.as_bytes()) { |
| 324 | return Err(not_representable(format!( |
| 325 | "tag {oid} does not start with its object line in canonical form" |
| 326 | ))); |
| 327 | } |
| 328 | tag_entries.push(GitImportedTag { |
| 329 | git_oid: oid, |
| 330 | target: target_of(target, &tags)?, |
| 331 | rest: payload[prefix.len()..].to_vec(), |
| 332 | }); |
| 333 | tags.insert(oid, ()); |
| 334 | } |
| 335 | |
| 336 | // References (checked now, written last). |
| 337 | check_git_ref_names( |
| 338 | history.refs.keys().map(String::as_str), |
| 339 | history.head.as_deref(), |
| 340 | )?; |
| 341 | let refs = GitImportedRefs { |
| 342 | refs: history |
| 343 | .refs |
| 344 | .iter() |
| 345 | .map(|(name, oid)| Ok((name.clone(), target_of(*oid, &tags)?))) |
| 346 | .collect::<SynapseResult<Vec<_>>>()?, |
| 347 | head: history.head.clone(), |
| 348 | }; |
| 349 | |
| 350 | // Build every record, then hand them to the store as one batch: it checks them all |
| 351 | // (limits, frame size, every Git ID) before the first write, so a refusal writes nothing. |
| 352 | let mut receipt = ImportReceipt { |
| 353 | blobs: blob_list.len(), |
| 354 | trees: tree_order.len(), |
| 355 | commits: commit_entries.len(), |
| 356 | tags: tag_entries.len(), |
| 357 | refs: refs.refs.len(), |
| 358 | ..ImportReceipt::default() |
| 359 | }; |
| 360 | let mut records: Vec<GitImportRecord> = Vec::new(); |
| 361 | // Objects records: at most MAX_MAPPINGS_PER_RECORD mappings, inline blob bytes within |
| 362 | // max_total_changeset_bytes, and an upper bound of the WAL frame (metadata per mapping |
| 363 | // plus inline blobs) within max_wal_record_bytes. A single object over either limit |
| 364 | // goes alone into a record the store then refuses. |
| 365 | let budget = limits.max_total_changeset_bytes; |
| 366 | let frame_cap = limits.max_wal_record_bytes; |
| 367 | let frame_base = 64 + repo_id.as_str().len() as u64; |
| 368 | let mut batch_blobs: Vec<GitBlobMapping> = Vec::new(); |
| 369 | let mut batch_bytes: Vec<(BlobDigest, &[u8])> = Vec::new(); |
| 370 | let mut batch_trees: Vec<GitTreeMapping> = Vec::new(); |
| 371 | let mut used = 0u64; |
| 372 | let mut frame = frame_base; |
| 373 | #[allow(clippy::too_many_arguments)] |
| 374 | fn flush<'a>( |
| 375 | records: &mut Vec<GitImportRecord<'a>>, |
| 376 | batch_blobs: &mut Vec<GitBlobMapping>, |
| 377 | batch_bytes: &mut Vec<(BlobDigest, &'a [u8])>, |
| 378 | batch_trees: &mut Vec<GitTreeMapping>, |
| 379 | used: &mut u64, |
| 380 | frame: &mut u64, |
| 381 | frame_base: u64, |
| 382 | ) { |
| 383 | if batch_blobs.is_empty() && batch_trees.is_empty() { |
| 384 | return; |
| 385 | } |
| 386 | let entry = GitBridgeEntry::Objects { |
| 387 | blobs: std::mem::take(batch_blobs), |
| 388 | trees: std::mem::take(batch_trees), |
| 389 | }; |
| 390 | records.push((entry, std::mem::take(batch_bytes))); |
| 391 | *used = 0; |
| 392 | *frame = frame_base; |
| 393 | } |
| 394 | for &oid in &blob_list { |
| 395 | let payload = object(oid)?.payload.as_slice(); |
| 396 | let (digest, size) = blobs[&oid]; |
| 397 | // Mapping (20 + 32 + 8) plus inline blob (32 + 4 + bytes). |
| 398 | let grows = 96 + size; |
| 399 | if batch_blobs.len() == MAX_MAPPINGS_PER_RECORD |
| 400 | || used + size > budget |
| 401 | || frame + grows > frame_cap |
| 402 | { |
| 403 | flush( |
| 404 | &mut records, |
| 405 | &mut batch_blobs, |
| 406 | &mut batch_bytes, |
| 407 | &mut batch_trees, |
| 408 | &mut used, |
| 409 | &mut frame, |
| 410 | frame_base, |
| 411 | ); |
| 412 | } |
| 413 | batch_blobs.push(GitBlobMapping { |
| 414 | git_oid: oid, |
| 415 | blob: digest, |
| 416 | size_bytes: size, |
| 417 | }); |
| 418 | batch_bytes.push((digest, payload)); |
| 419 | used += size; |
| 420 | frame += grows; |
| 421 | } |
| 422 | for &oid in &tree_order { |
| 423 | let (_, node) = &trees[&oid]; |
| 424 | let size = node.len() as u64; |
| 425 | // Git ID (20) plus length (4) plus node. |
| 426 | let grows = 24 + size; |
| 427 | if batch_blobs.len() + batch_trees.len() >= MAX_MAPPINGS_PER_RECORD |
| 428 | || used + size > budget |
| 429 | || frame + grows > frame_cap |
| 430 | { |
| 431 | flush( |
| 432 | &mut records, |
| 433 | &mut batch_blobs, |
| 434 | &mut batch_bytes, |
| 435 | &mut batch_trees, |
| 436 | &mut used, |
| 437 | &mut frame, |
| 438 | frame_base, |
| 439 | ); |
| 440 | } |
| 441 | batch_trees.push(GitTreeMapping { |
| 442 | git_oid: oid, |
| 443 | node: node.clone(), |
| 444 | }); |
| 445 | used += size; |
| 446 | frame += grows; |
| 447 | } |
| 448 | flush( |
| 449 | &mut records, |
| 450 | &mut batch_blobs, |
| 451 | &mut batch_bytes, |
| 452 | &mut batch_trees, |
| 453 | &mut used, |
| 454 | &mut frame, |
| 455 | frame_base, |
| 456 | ); |
| 457 | for c in commit_entries { |
| 458 | records.push((GitBridgeEntry::Commit(c), Vec::new())); |
| 459 | } |
| 460 | for t in tag_entries { |
| 461 | records.push((GitBridgeEntry::Tag(t), Vec::new())); |
| 462 | } |
| 463 | records.push((GitBridgeEntry::Refs(refs), Vec::new())); |
| 464 | for seq in store.record_git_imports(repo_id, records)? { |
| 465 | match seq { |
| 466 | Some(_) => receipt.records_written += 1, |
| 467 | None => receipt.records_skipped += 1, |
| 468 | } |
| 469 | } |
| 470 | Ok(receipt) |
| 471 | } |
| 472 | |
| 473 | /// Git IDs of the imported objects of one repository, by native identity. |
| 474 | struct ImportedIds { |
| 475 | blobs: HashMap<BlobDigest, GitOid>, |
| 476 | trees: HashMap<TreeDigest, GitOid>, |
| 477 | commits: HashMap<ChangesetId, GitOid>, |
| 478 | tags: HashSet<GitOid>, |
| 479 | } |
| 480 | |
| 481 | impl ImportedIds { |
| 482 | fn of(repo: Option<&GitBridgeRepo>) -> Self { |
| 483 | let mut ids = Self { |
| 484 | blobs: HashMap::new(), |
| 485 | trees: HashMap::new(), |
| 486 | commits: HashMap::new(), |
| 487 | tags: HashSet::new(), |
| 488 | }; |
| 489 | if let Some(r) = repo { |
| 490 | ids.blobs = r.blobs().iter().map(|(oid, (d, _))| (*d, *oid)).collect(); |
| 491 | ids.trees = r.trees().iter().map(|(oid, d)| (*d, *oid)).collect(); |
| 492 | ids.commits = r.commits().map(|(oid, (id, _))| (*id, *oid)).collect(); |
| 493 | ids.tags = r.tags().keys().copied().collect(); |
| 494 | } |
| 495 | ids |
| 496 | } |
| 497 | |
| 498 | fn target(&self, t: &GitBridgeTarget) -> SynapseResult<GitOid> { |
| 499 | let missing = || corrupt(format!("bridge target {t:?} has no Git ID")); |
| 500 | Ok(match t { |
| 501 | GitBridgeTarget::Commit(id) => *self.commits.get(id).ok_or_else(missing)?, |
| 502 | GitBridgeTarget::Tree(d) => *self.trees.get(d).ok_or_else(missing)?, |
| 503 | GitBridgeTarget::Blob(b) => *self.blobs.get(b).ok_or_else(missing)?, |
| 504 | GitBridgeTarget::Tag(oid) => *self.tags.get(oid).ok_or_else(missing)?, |
| 505 | }) |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | /// One file of a flattened native tree. |
| 510 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 511 | struct FlatFile { |
| 512 | mode: FileMode, |
| 513 | blob: BlobDigest, |
| 514 | size: u64, |
| 515 | } |
| 516 | |
| 517 | /// Export state: every object written so far, by Git ID. |
| 518 | struct Exporter<'a> { |
| 519 | store: &'a SynapseStore, |
| 520 | repo_id: &'a RepoId, |
| 521 | objects: BTreeMap<GitOid, GitObject>, |
| 522 | /// Git blob IDs of blobs read for native trees. |
| 523 | native_blobs: HashMap<BlobDigest, GitOid>, |
| 524 | /// Result trees of the native revisions exported so far (a native child names its |
| 525 | /// parent's result as its `base_tree`). |
| 526 | native_trees: HashMap<TreeDigest, BTreeMap<String, FlatFile>>, |
| 527 | ids: ImportedIds, |
| 528 | } |
| 529 | |
| 530 | impl Exporter<'_> { |
| 531 | fn add(&mut self, object: GitObject) -> GitOid { |
| 532 | let oid = object.oid(); |
| 533 | self.objects.entry(oid).or_insert(object); |
| 534 | oid |
| 535 | } |
| 536 | |
| 537 | /// Add `object`, which must hash to the Git ID it was imported under. |
| 538 | fn add_checked(&mut self, object: GitObject, expected: GitOid) -> SynapseResult<()> { |
| 539 | let oid = object.oid(); |
| 540 | if oid != expected { |
| 541 | return Err(corrupt(format!( |
| 542 | "stored {} rebuilds as {oid}, not its imported Git ID {expected}", |
| 543 | object.kind.name() |
| 544 | ))); |
| 545 | } |
| 546 | self.objects.entry(oid).or_insert(object); |
| 547 | Ok(()) |
| 548 | } |
| 549 | |
| 550 | fn blob_oid(&mut self, blob: BlobDigest) -> SynapseResult<GitOid> { |
| 551 | if let Some(oid) = self.ids.blobs.get(&blob).or(self.native_blobs.get(&blob)) { |
| 552 | return Ok(*oid); |
| 553 | } |
| 554 | let bytes = self.store.get_blob_visible(blob, None, None)?; |
| 555 | let oid = self.add(GitObject::new(ObjectKind::Blob, bytes)); |
| 556 | self.native_blobs.insert(blob, oid); |
| 557 | Ok(oid) |
| 558 | } |
| 559 | |
| 560 | fn export_imported(&mut self, repo: &GitBridgeRepo) -> SynapseResult<()> { |
| 561 | for (oid, (digest, size)) in repo.blobs() { |
| 562 | let bytes = self.store.get_blob_visible(*digest, None, None)?; |
| 563 | if bytes.len() as u64 != *size { |
| 564 | return Err(corrupt(format!( |
| 565 | "stored blob of Git blob {oid} holds {} bytes, not {size}", |
| 566 | bytes.len() |
| 567 | ))); |
| 568 | } |
| 569 | self.add_checked(GitObject::new(ObjectKind::Blob, bytes), *oid)?; |
| 570 | } |
| 571 | for (oid, digest) in repo.trees() { |
| 572 | let node = self.store.git_bridge_tree_node(*digest).ok_or_else(|| { |
| 573 | SynapseError::new( |
| 574 | RefusalCode::TreeNodeNotFound, |
| 575 | format!("tree node {digest} of Git tree {oid} is not stored"), |
| 576 | ) |
| 577 | })?; |
| 578 | let ids = &self.ids; |
| 579 | let tree = git_tree_of_node(node, &|b| ids.target(&GitBridgeTarget::Blob(b)), &|t| { |
| 580 | ids.target(&GitBridgeTarget::Tree(t)) |
| 581 | })?; |
| 582 | self.add_checked(tree, *oid)?; |
| 583 | } |
| 584 | for (oid, (_, c)) in repo.commits() { |
| 585 | let tree = self.ids.target(&GitBridgeTarget::Tree(c.tree))?; |
| 586 | let parents = c |
| 587 | .parents |
| 588 | .iter() |
| 589 | .map(|p| self.ids.target(&GitBridgeTarget::Commit(*p))) |
| 590 | .collect::<SynapseResult<Vec<_>>>()?; |
| 591 | let mut payload = commit_link_lines(tree, &parents); |
| 592 | payload.extend_from_slice(&c.headers); |
| 593 | self.add_checked(GitObject::new(ObjectKind::Commit, payload), *oid)?; |
| 594 | } |
| 595 | for (oid, t) in repo.tags() { |
| 596 | let target = self.ids.target(&t.target)?; |
| 597 | let mut payload = format!("object {}\n", target.to_hex()).into_bytes(); |
| 598 | payload.extend_from_slice(&t.rest); |
| 599 | self.add_checked(GitObject::new(ObjectKind::Tag, payload), *oid)?; |
| 600 | } |
| 601 | Ok(()) |
| 602 | } |
| 603 | |
| 604 | /// Flatten the tree `root` (an imported tree, a native revision's result tree exported |
| 605 | /// before, or the empty tree) into path to file. |
| 606 | fn flatten(&self, root: TreeDigest) -> SynapseResult<BTreeMap<String, FlatFile>> { |
| 607 | if let Some(files) = self.native_trees.get(&root) { |
| 608 | return Ok(files.clone()); |
| 609 | } |
| 610 | let mut files = BTreeMap::new(); |
| 611 | let mut stack = vec![(String::new(), root)]; |
| 612 | while let Some((prefix, digest)) = stack.pop() { |
| 613 | if digest == TreeDigest::empty() { |
| 614 | continue; |
| 615 | } |
| 616 | let node = self.store.git_bridge_tree_node(digest).ok_or_else(|| { |
| 617 | SynapseError::new( |
| 618 | RefusalCode::TreeNodeNotFound, |
| 619 | format!("base tree node {digest} is not stored in the bridge"), |
| 620 | ) |
| 621 | })?; |
| 622 | for e in decode_tree_node(node)? { |
| 623 | let path = format!("{prefix}{}", e.name); |
| 624 | match e.kind { |
| 625 | TreeNodeEntryKind::File { |
| 626 | mode, |
| 627 | blob, |
| 628 | size_bytes, |
| 629 | } => { |
| 630 | files.insert( |
| 631 | path, |
| 632 | FlatFile { |
| 633 | mode, |
| 634 | blob, |
| 635 | size: size_bytes, |
| 636 | }, |
| 637 | ); |
| 638 | } |
| 639 | TreeNodeEntryKind::Dir(child) => stack.push((format!("{path}/"), child)), |
| 640 | } |
| 641 | } |
| 642 | } |
| 643 | Ok(files) |
| 644 | } |
| 645 | |
| 646 | /// Write the Git trees of `files` (a flat path map); returns the root tree's Git ID and |
| 647 | /// its C1 `TreeDigest` (the same canonical nodes the tree store builds). |
| 648 | fn write_tree( |
| 649 | &mut self, |
| 650 | files: &BTreeMap<String, FlatFile>, |
| 651 | ) -> SynapseResult<(GitOid, TreeDigest)> { |
| 652 | enum Node { |
| 653 | File(FlatFile), |
| 654 | Dir(BTreeMap<String, Node>), |
| 655 | } |
| 656 | enum Node2 { |
| 657 | File(FlatFile), |
| 658 | Dir(TreeDigest), |
| 659 | } |
| 660 | let mut root: BTreeMap<String, Node> = BTreeMap::new(); |
| 661 | for (path, f) in files { |
| 662 | let mut dir = &mut root; |
| 663 | let mut segs: Vec<&str> = path.split('/').collect(); |
| 664 | let name = segs.pop().unwrap_or_default(); |
| 665 | for s in segs { |
| 666 | let slot = dir |
| 667 | .entry(s.to_string()) |
| 668 | .or_insert_with(|| Node::Dir(BTreeMap::new())); |
| 669 | dir = match slot { |
| 670 | Node::Dir(d) => d, |
| 671 | Node::File(_) => { |
| 672 | return Err(corrupt(format!("path {path} lies below a file"))); |
| 673 | } |
| 674 | }; |
| 675 | } |
| 676 | dir.insert(name.to_string(), Node::File(*f)); |
| 677 | } |
| 678 | fn emit( |
| 679 | ex: &mut Exporter<'_>, |
| 680 | dir: &BTreeMap<String, Node>, |
| 681 | ) -> SynapseResult<(GitOid, TreeDigest)> { |
| 682 | let mut entries: Vec<(bool, &str, GitTreeEntry, Node2)> = Vec::new(); |
| 683 | for (name, node) in dir { |
| 684 | let (is_dir, mode, oid, native) = match node { |
| 685 | Node::File(f) => ( |
| 686 | false, |
| 687 | f.mode.git_octal_str().as_bytes().to_vec(), |
| 688 | ex.blob_oid(f.blob)?, |
| 689 | Node2::File(*f), |
| 690 | ), |
| 691 | Node::Dir(d) => { |
| 692 | let (oid, digest) = emit(ex, d)?; |
| 693 | (true, b"40000".to_vec(), oid, Node2::Dir(digest)) |
| 694 | } |
| 695 | }; |
| 696 | entries.push(( |
| 697 | is_dir, |
| 698 | name, |
| 699 | GitTreeEntry { |
| 700 | mode, |
| 701 | name: name.as_bytes().to_vec(), |
| 702 | oid, |
| 703 | }, |
| 704 | native, |
| 705 | )); |
| 706 | } |
| 707 | entries.sort_by(|a, b| tree_entry_order(a.1, a.0, b.1, b.0)); |
| 708 | let count = u32::try_from(entries.len()) |
| 709 | .map_err(|_| not_representable("a native tree has too many entries"))?; |
| 710 | let mut enc = TreeNodeEncoder::new(count); |
| 711 | for (_, name, _, native) in &entries { |
| 712 | match native { |
| 713 | Node2::File(f) => enc.file(name, f.mode, &f.blob, f.size)?, |
| 714 | Node2::Dir(d) => enc.dir(name, d)?, |
| 715 | } |
| 716 | } |
| 717 | let (digest, _) = enc.finish()?; |
| 718 | let list: Vec<GitTreeEntry> = entries.into_iter().map(|e| e.2).collect(); |
| 719 | let oid = ex.add(GitObject::new( |
| 720 | ObjectKind::Tree, |
| 721 | crate::object::encode_tree(&list), |
| 722 | )); |
| 723 | Ok((oid, digest)) |
| 724 | } |
| 725 | emit(self, &root) |
| 726 | } |
| 727 | |
| 728 | /// The Git commit of native revision `id` (and of its native ancestors), deterministic: |
| 729 | /// tree = `base_tree` (the empty tree, an imported tree, or the result tree of a native |
| 730 | /// revision exported before it) with the revision's mutations applied (an upsert replaces a file at |
| 731 | /// an ancestor path and everything below its own path; a delete removes only a file); |
| 732 | /// parents in the revision's order (imported commits by their Git ID); author the first |
| 733 | /// attestation's DID with `NATIVE_AUTHOR_EMAIL`, committer `NATIVE_COMMITTER`, both at |
| 734 | /// time 0 +0000; message the intent summary, a blank line, and `Synapse-Changeset-Id` and |
| 735 | /// `Synapse-Change-Id` trailers. |
| 736 | fn native_commit( |
| 737 | &mut self, |
| 738 | id: ChangesetId, |
| 739 | done: &mut HashMap<ChangesetId, GitOid>, |
| 740 | ) -> SynapseResult<GitOid> { |
| 741 | let mut stack = vec![(id, false)]; |
| 742 | while let Some((cs, expanded)) = stack.pop() { |
| 743 | if done.contains_key(&cs) || self.ids.commits.contains_key(&cs) { |
| 744 | continue; |
| 745 | } |
| 746 | let rev = self.store.get_revision(self.repo_id, cs)?; |
| 747 | if !expanded { |
| 748 | stack.push((cs, true)); |
| 749 | for p in &rev.content.parents { |
| 750 | if !done.contains_key(p) && !self.ids.commits.contains_key(p) { |
| 751 | stack.push((*p, false)); |
| 752 | } |
| 753 | } |
| 754 | continue; |
| 755 | } |
| 756 | let mut files = self.flatten(rev.content.base_tree)?; |
| 757 | for m in &rev.content.mutations { |
| 758 | match &m.op { |
| 759 | MutationOp::Upsert { |
| 760 | mode, |
| 761 | blob_digest, |
| 762 | size_bytes, |
| 763 | } => { |
| 764 | for (i, _) in m.path.match_indices('/') { |
| 765 | files.remove(&m.path[..i]); |
| 766 | } |
| 767 | let below = format!("{}/", m.path); |
| 768 | let doomed: Vec<String> = files |
| 769 | .range(below.clone()..) |
| 770 | .take_while(|(p, _)| p.starts_with(&below)) |
| 771 | .map(|(p, _)| p.clone()) |
| 772 | .collect(); |
| 773 | for p in doomed { |
| 774 | files.remove(&p); |
| 775 | } |
| 776 | files.insert( |
| 777 | m.path.clone(), |
| 778 | FlatFile { |
| 779 | mode: *mode, |
| 780 | blob: *blob_digest, |
| 781 | size: *size_bytes, |
| 782 | }, |
| 783 | ); |
| 784 | } |
| 785 | MutationOp::Delete => { |
| 786 | files.remove(&m.path); |
| 787 | } |
| 788 | } |
| 789 | } |
| 790 | let (tree, digest) = self.write_tree(&files)?; |
| 791 | self.native_trees.insert(digest, files); |
| 792 | let parents = rev |
| 793 | .content |
| 794 | .parents |
| 795 | .iter() |
| 796 | .map(|p| { |
| 797 | done.get(p) |
| 798 | .or(self.ids.commits.get(p)) |
| 799 | .copied() |
| 800 | .ok_or_else(|| corrupt(format!("parent {p} has no Git commit"))) |
| 801 | }) |
| 802 | .collect::<SynapseResult<Vec<_>>>()?; |
| 803 | let author = rev |
| 804 | .attestations |
| 805 | .first() |
| 806 | .map(|a| a.author_did()) |
| 807 | .ok_or_else(|| corrupt(format!("revision {cs} has no attestation")))?; |
| 808 | let mut payload = commit_link_lines(tree, &parents); |
| 809 | payload.extend_from_slice( |
| 810 | format!( |
| 811 | "author {author} <{NATIVE_AUTHOR_EMAIL}> 0 +0000\ncommitter {NATIVE_COMMITTER} 0 +0000\n\n{}\n\nSynapse-Changeset-Id: {}\nSynapse-Change-Id: {}\n", |
| 812 | rev.content.intent_summary, |
| 813 | cs.to_hex(), |
| 814 | rev.content.change_id.to_hex() |
| 815 | ) |
| 816 | .as_bytes(), |
| 817 | ); |
| 818 | let oid = self.add(GitObject::new(ObjectKind::Commit, payload)); |
| 819 | done.insert(cs, oid); |
| 820 | } |
| 821 | done.get(&id) |
| 822 | .or(self.ids.commits.get(&id)) |
| 823 | .copied() |
| 824 | .ok_or_else(|| corrupt(format!("revision {id} was not exported"))) |
| 825 | } |
| 826 | } |
| 827 | |
| 828 | /// Export `repo_id` from `store` alone as the new bare repository `dest` (one pack). Imported |
| 829 | /// objects and references are rebuilt from the bridge records and stored blobs; each object |
| 830 | /// must hash to its imported Git ID (`GitObjectCorrupt` otherwise). `native_refs` adds a |
| 831 | /// reference for each native revision named (written with its native ancestors, see the |
| 832 | /// native commit rule in `docs/H1_GIT_BRIDGE.md`); a name already imported is `PathInvalid`. |
| 833 | /// `HEAD` is the imported `HEAD` (default `refs/heads/main`). The same store state always gives |
| 834 | /// the same pack bytes. |
| 835 | pub fn export_store( |
| 836 | store: &SynapseStore, |
| 837 | repo_id: &RepoId, |
| 838 | native_refs: &BTreeMap<String, ChangesetId>, |
| 839 | dest: &Path, |
| 840 | ) -> SynapseResult<ExportReceipt> { |
| 841 | let repo = store.git_bridge_repo(repo_id); |
| 842 | let mut ex = Exporter { |
| 843 | store, |
| 844 | repo_id, |
| 845 | objects: BTreeMap::new(), |
| 846 | native_blobs: HashMap::new(), |
| 847 | native_trees: HashMap::new(), |
| 848 | ids: ImportedIds::of(repo), |
| 849 | }; |
| 850 | let mut refs: BTreeMap<String, GitOid> = BTreeMap::new(); |
| 851 | let mut head = None; |
| 852 | if let Some(r) = repo { |
| 853 | ex.export_imported(r)?; |
| 854 | if let Some(imported) = r.refs() { |
| 855 | for (name, target) in &imported.refs { |
| 856 | refs.insert(name.clone(), ex.ids.target(target)?); |
| 857 | } |
| 858 | head = imported.head.clone(); |
| 859 | } |
| 860 | } |
| 861 | let mut done = HashMap::new(); |
| 862 | for (name, id) in native_refs { |
| 863 | if refs.contains_key(name) { |
| 864 | return Err(SynapseError::new( |
| 865 | RefusalCode::PathInvalid, |
| 866 | format!("native reference {name} is already an imported reference"), |
| 867 | )); |
| 868 | } |
| 869 | let oid = ex.native_commit(*id, &mut done)?; |
| 870 | refs.insert(name.clone(), oid); |
| 871 | } |
| 872 | check_git_ref_names(refs.keys().map(String::as_str), head.as_deref())?; |
| 873 | let objects: Vec<GitObject> = ex.objects.into_values().collect(); |
| 874 | export_repository(dest, &objects, &refs, head.as_deref()) |
| 875 | } |
| 876 | |
| 877 | #[cfg(test)] |
| 878 | mod tests { |
| 879 | use super::*; |
| 880 | |
| 881 | /// Export resolves a reference or tag that names a tag only when that tag is imported |
| 882 | /// (review of #96: it used to pass any tag Git ID through). |
| 883 | #[test] |
| 884 | fn export_refuses_a_tag_target_that_is_not_imported() { |
| 885 | let ids = ImportedIds::of(None); |
| 886 | let oid = GitOid::compute_git_object("tag", b"never imported"); |
| 887 | let err = ids.target(&GitBridgeTarget::Tag(oid)).unwrap_err(); |
| 888 | assert_eq!(err.code, RefusalCode::GitObjectCorrupt, "{err}"); |
| 889 | } |
| 890 | } |