Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/synapse/blob/main/crates/synapse-api/src/derivation.rs # synapse A component of the AienOS ecosystem. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `synapse / crates / synapse-api / src / derivation.rs` 327 lines ยท 12398 bytes Raw Blame History 1 //! Server-derived revisions through the service (ADR 0003 step B5): the C1 tree store as the 2 //! [`DerivationTrees`] every rule is recomputed on, derivation by the server, admission, and 3 //! replica verification of the revision log. See `docs/B5_DERIVATION_ATTESTATION.md`. 4 5 use crate::tree::{TreeEdit, TreeFile, TreeStore}; 6 use crate::SynapseService; 7 use `ed25519`_dalek::SigningKey; 8 use std::collections::BTreeMap; 9 use synapse_core::{ 10 BlobDigest, ChangesetId, DerivationInput, DerivationRule, DerivationTrees, DerivedRevision, 11 FileMode, GitOid, MergeTier, MutationOp, PathMutation, RefusalCode, RevisionContent, 12 ServerKeyRegistry, SynapseError, SynapseResult, TreeDigest, 13 }; 14 use synapse_store::{AdmissionAuthority, RevisionOutcome, WalRecord}; 15 16 /// The tree store seen as [`DerivationTrees`]. `git_oids` carries the Git blob OID of every 17 /// blob a rule may upsert: a bridge attribute of tree files that never affects a `TreeDigest`. 18 /// 19 /// `blobs` holds the bytes a tier T1 merge reads (the input revisions' upserted blobs and 20 /// the base files at their paths, loaded before the rule runs) and `produced` the merged 21 /// files a rule wrote through [`DerivationTrees::put_blob`]. 22 pub struct ServiceDerivationTrees<'a> { 23 trees: &'a mut TreeStore, 24 git_oids: BTreeMap, 25 blobs: BTreeMap>, 26 produced: BTreeMap>, 27 } 28 29 impl DerivationTrees for ServiceDerivationTrees<'_> { 30 fn holds_tree(&mut self, tree: TreeDigest) -> bool { 31 self.trees.contains(tree) 32 } 33 34 fn apply_mutations( 35 &mut self, 36 base: TreeDigest, 37 mutations: &[PathMutation], 38 ) -> SynapseResult { 39 let mut edit = TreeEdit::new(self.trees, base)?; 40 for m in mutations { 41 match &m.op { 42 MutationOp::Upsert { 43 mode, 44 blob_digest, 45 size_bytes, 46 } => { 47 let git_blob_oid = *self.git_oids.get(blob_digest).ok_or_else(|| { 48 SynapseError::new( 49 RefusalCode::BlobNotFound, 50 format!("blob {blob_digest} of path {} is not readable", m.path), 51 ) 52 })?; 53 let file = TreeFile { 54 mode: *mode, 55 blob_digest: *blob_digest, 56 size_bytes: *size_bytes, 57 git_blob_oid, 58 }; 59 edit.upsert(self.trees, &m.path, file)?; 60 } 61 MutationOp::Delete => edit.delete(self.trees, &m.path)?, 62 } 63 } 64 edit.finish(self.trees) 65 } 66 67 fn changed_paths(&mut self, from: TreeDigest, to: TreeDigest) -> SynapseResult> { 68 Ok(self 69 .trees 70 .diff(from, to)? 71 .into_iter() 72 .map(|e| e.path) 73 .collect()) 74 } 75 76 fn file_at( 77 &mut self, 78 tree: TreeDigest, 79 path: &str, 80 ) -> SynapseResult> { 81 Ok(self 82 .trees 83 .lookup(tree, path)? 84 .map(|f| (f.mode, f.blob_digest))) 85 } 86 87 fn blob_bytes(&mut self, digest: BlobDigest) -> SynapseResult> { 88 self.produced 89 .get(&digest) 90 .or_else(|| self.blobs.get(&digest)) 91 .cloned() 92 .ok_or_else(|| { 93 SynapseError::new( 94 RefusalCode::BlobNotFound, 95 format!("blob {digest} is not readable by this derivation"), 96 ) 97 }) 98 } 99 100 fn put_blob(&mut self, bytes: Vec) -> SynapseResult { 101 let digest = BlobDigest::compute(&bytes); 102 self.git_oids 103 .entry(digest) 104 .or_insert_with(|| GitOid::compute_blob(&bytes)); 105 self.produced.insert(digest, bytes); 106 Ok(digest) 107 } 108 109 fn produced_blob(&self, digest: BlobDigest) -> Option<&[u8]> { 110 self.produced.get(&digest).map(Vec::as_slice) 111 } 112 } 113 114 impl SynapseService { 115 /// Git blob OIDs of every readable upserted blob of `contents` (unreadable blobs are left 116 /// out; a rule that needs one then fails with `BlobNotFound`). 117 fn git_oids_of<'c>( 118 &self, 119 contents: impl IntoIterator, 120 ) -> BTreeMap { 121 let mut out = BTreeMap::new(); 122 for c in contents { 123 for m in &c.mutations { 124 if let MutationOp::Upsert { blob_digest, .. } = &m.op { 125 if out.contains_key(blob_digest) { 126 continue; 127 } 128 if let Ok(raw) = self.read_blob_bytes(*blob_digest, None) { 129 out.insert(*blob_digest, GitOid::compute_blob(&raw)); 130 } 131 } 132 } 133 } 134 out 135 } 136 137 /// The bytes a tier T1 merge of `contents` reads: every upserted blob, and the file at each 138 /// mutated path of each content's base tree. Empty unless `rule` is a tier T1 merge (other 139 /// rules never read file bytes). Blobs this replica cannot read are left out; the rule then 140 /// refuses with `BlobNotFound` if it needs them. 141 fn merge_blobs( 142 &mut self, 143 rule: DerivationRule, 144 contents: &[RevisionContent], 145 ) -> BTreeMap> { 146 let mut out = BTreeMap::new(); 147 if rule 148 != (DerivationRule::Merge { 149 tier: MergeTier::T1Region, 150 }) 151 { 152 return out; 153 } 154 let mut wanted = Vec::new(); 155 for c in contents { 156 for m in &c.mutations { 157 if let MutationOp::Upsert { blob_digest, .. } = &m.op { 158 wanted.push(*blob_digest); 159 } 160 if let Ok(Some(f)) = self.trees.lookup(c.base_tree, &m.path) { 161 wanted.push(f.blob_digest); 162 } 163 } 164 } 165 for d in wanted { 166 if let std::collections::btree_map::Entry::Vacant(slot) = out.entry(d) { 167 if let Ok(bytes) = self.read_blob_bytes(d, None) { 168 slot.insert(bytes); 169 } 170 } 171 } 172 out 173 } 174 175 /// Contents of the input revisions `inputs` names that this repository has admitted. 176 fn input_contents(&self, inputs: &[DerivationInput]) -> Vec { 177 inputs 178 .iter() 179 .filter_map(|i| match i { 180 DerivationInput::Revision(id) => self 181 .store 182 .get_revision(&self.repo_id, *id) 183 .ok() 184 .map(|r| r.content), 185 DerivationInput::Tree(_) => None, 186 }) 187 .collect() 188 } 189 190 /// Derive a revision as the server: recompute `rule` on `inputs` over the tree store and 191 /// sign the attestation with the server's machine key `server`. Nothing is admitted. 192 pub fn derive_revision( 193 &mut self, 194 server: &SigningKey, 195 rule: DerivationRule, 196 inputs: Vec, 197 ) -> SynapseResult { 198 let sources = self.input_contents(&inputs); 199 let git_oids = self.git_oids_of(&sources); 200 let blobs = self.merge_blobs(rule, &sources); 201 let store = &self.store; 202 let repo = self.repo_id.clone(); 203 let lookup = |id: ChangesetId| store.get_revision(&repo, id).ok().map(|r| r.content); 204 let mut trees = ServiceDerivationTrees { 205 trees: &mut self.trees, 206 git_oids, 207 blobs, 208 produced: BTreeMap::new(), 209 }; 210 DerivedRevision::derive( 211 server, 212 self.repo_id.clone(), 213 rule, 214 inputs, 215 &lookup, 216 &mut trees, 217 ) 218 } 219 220 /// Admit a server-derived revision (ADR 0003 B5) under `authority` (the chain that asked 221 /// for it or proposed it, already authorized by the caller). `keys` is the repository 222 /// identity log (`synapse_radicle::IdentityLog`). The attestation must name this service's 223 /// repository (`AuthCrossRepoDenied`); the store then checks the derivation and recomputes 224 /// it over the tree store. 225 pub fn admit_derived_revision( 226 &mut self, 227 derived: DerivedRevision, 228 authority: AdmissionAuthority, 229 keys: &dyn ServerKeyRegistry, 230 now_ms: u64, 231 ) -> SynapseResult { 232 if derived.attestation.repo_id != self.repo_id { 233 return Err(SynapseError::new( 234 RefusalCode::AuthCrossRepoDenied, 235 "derivation attestation repo_id does not match service repo_id", 236 )); 237 } 238 let mut sources = self.input_contents(&derived.attestation.inputs); 239 let blobs = self.merge_blobs(derived.attestation.rule, &sources); 240 sources.push(derived.content.clone()); 241 let git_oids = self.git_oids_of(&sources); 242 let mut trees = ServiceDerivationTrees { 243 trees: &mut self.trees, 244 git_oids, 245 blobs, 246 produced: BTreeMap::new(), 247 }; 248 self.store 249 .admit_derived_revision(derived, authority, keys, &mut trees, now_ms) 250 } 251 252 /// Verify `records` as a replica (see `synapse_store::verify_revision_log`), recomputing 253 /// every derived revision over this service's tree store. Returns the number of records 254 /// verified. 255 pub fn verify_revision_records( 256 &mut self, 257 records: &[(synapse_core::WalSeq, WalRecord)], 258 keys: &dyn ServerKeyRegistry, 259 ) -> SynapseResult { 260 let contents = records.iter().filter_map(|(_, r)| match r { 261 WalRecord::RevisionAdmitted { envelope, .. } => Some(&envelope.content), 262 WalRecord::DerivedRevisionAdmitted { derived, .. } => Some(&derived.content), 263 _ => None, 264 }); 265 let git_oids = self.git_oids_of(contents); 266 let mut t1_inputs = Vec::new(); 267 for (_, r) in records { 268 if let WalRecord::DerivedRevisionAdmitted { derived, .. } = r { 269 if derived.attestation.rule 270 == (DerivationRule::Merge { 271 tier: MergeTier::T1Region, 272 }) 273 { 274 t1_inputs 275 .extend(self.record_input_contents(records, &derived.attestation.inputs)); 276 } 277 } 278 } 279 let blobs = self.merge_blobs( 280 DerivationRule::Merge { 281 tier: MergeTier::T1Region, 282 }, 283 &t1_inputs, 284 ); 285 let mut trees = ServiceDerivationTrees { 286 trees: &mut self.trees, 287 git_oids, 288 blobs, 289 produced: BTreeMap::new(), 290 }; 291 synapse_store::verify_revision_log(records, keys, &mut trees) 292 } 293 294 /// Contents of the revisions `inputs` names, from `records` (a replica verifies records it 295 /// may not have admitted itself). 296 fn record_input_contents( 297 &self, 298 records: &[(synapse_core::WalSeq, WalRecord)], 299 inputs: &[DerivationInput], 300 ) -> Vec { 301 inputs 302 .iter() 303 .filter_map(|i| match i { 304 DerivationInput::Revision(id) => records.iter().find_map(|(_, r)| match r { 305 WalRecord::RevisionAdmitted { envelope, .. } 306 if envelope.attestation.changeset_id == *id => 307 { 308 Some(envelope.content.clone()) 309 } 310 WalRecord::DerivedRevisionAdmitted { derived, .. } 311 if derived.attestation.output_changeset == *id => 312 { 313 Some(derived.content.clone()) 314 } 315 _ => None, 316 }), 317 DerivationInput::Tree(_) => None, 318 }) 319 .collect() 320 } 321 322 /// Verify this service's own revision log as a replica would after replay. 323 pub fn verify_revision_log(&mut self, keys: &dyn ServerKeyRegistry) -> SynapseResult { 324 let records = self.store.revision_records().to_vec(); 325 self.verify_revision_records(&records, keys) 326 } 327 }