synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-api / src / lib.rs
| 1 | //! Bounded paginated read/proposal API, checkout-free tree inspection over a shared Merkle tree |
| 2 | //! store with a bounded cache (`tree`, ADR 0003 step C1), exact `PathIndex` invalidation, and |
| 3 | //! durable subscription cursors (`synapse-api`, Gate 2b). |
| 4 | |
| 5 | use ed25519_dalek::SigningKey; |
| 6 | use serde::{Deserialize, Serialize}; |
| 7 | use std::collections::{BTreeMap, BTreeSet}; |
| 8 | use std::fs::{self, File}; |
| 9 | use std::io::Write; |
| 10 | use std::path::{Path, PathBuf}; |
| 11 | use std::process::Command; |
| 12 | use synapse_auth::{ |
| 13 | AuditEntry, AuthenticatedRequest, BoundaryKind, Capability, CapabilityChain, ChainedRequest, |
| 14 | PolicyEnforcer, SignedStateMove, |
| 15 | }; |
| 16 | use synapse_core::{ |
| 17 | validate_repo_relative_path, BlobDigest, ChangesetEnvelope, ChangesetId, EvidenceAttachment, |
| 18 | FileMode, GitHubPullRequestProjection, GitOid, IdempotencyKey, MutationOp, |
| 19 | RadicleCanonicalHead, RefusalCode, RepoId, SynapseError, SynapseResult, TreeDigest, WalSeq, |
| 20 | }; |
| 21 | use synapse_core::{ChainPath, ChangeId, ChangesetEnvelopeV2, ObsolescenceMarker, RevisionState}; |
| 22 | use synapse_store::{ |
| 23 | AdmissionAuthority, CompactionReport, FsyncPolicy, IngestOutcome, RecoveryPolicy, ReviewRecord, |
| 24 | RevisionOutcome, RevisionSealKey, StoreLimits, StoredChangeset, StoredRevision, SynapseStore, |
| 25 | }; |
| 26 | |
| 27 | mod advisory; |
| 28 | mod crumb; |
| 29 | mod derivation; |
| 30 | pub use derivation::ServiceDerivationTrees; |
| 31 | mod evidence; |
| 32 | pub mod secret_scan; |
| 33 | pub mod tree; |
| 34 | pub use advisory::{ |
| 35 | ChangesetAdvisory, ChangesetAdvisoryPayload, CoordinationStatus, GuidanceNote, |
| 36 | OverlappingProposal, PathAdvisory, Staleness, MAX_ADVISORY_PATHS, |
| 37 | }; |
| 38 | pub use crumb::CrumbContextQueryPayload; |
| 39 | pub use evidence::{ |
| 40 | EvidenceBase, EvidenceBaseQueryPayload, ReceiptMismatch, ReceiptVerification, StaleContext, |
| 41 | StaleReason, VerifyEvidenceReceiptPayload, |
| 42 | }; |
| 43 | pub use tree::{ |
| 44 | TreeCacheConfig, TreeDiffEntry, TreeEdit, TreeEntry, TreeEntryKind, TreeFile, TreeNode, |
| 45 | TreeStore, TreeStoreStats, DEFAULT_TREE_CACHE_BYTES, MIN_TREE_CACHE_BYTES, |
| 46 | }; |
| 47 | |
| 48 | /// Default maximum page size for bounded API queries. |
| 49 | pub const DEFAULT_MAX_PAGE_SIZE: usize = 256; |
| 50 | |
| 51 | /// Bounded pagination parameters accepted by read/query APIs. |
| 52 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 53 | pub struct PageRequest { |
| 54 | pub cursor: Option<String>, |
| 55 | pub limit: usize, |
| 56 | pub min_visible_seq: Option<WalSeq>, |
| 57 | pub snapshot_seq: Option<WalSeq>, |
| 58 | } |
| 59 | |
| 60 | impl Default for PageRequest { |
| 61 | fn default() -> Self { |
| 62 | Self { |
| 63 | cursor: None, |
| 64 | limit: 64, |
| 65 | min_visible_seq: None, |
| 66 | snapshot_seq: None, |
| 67 | } |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// Paginated response envelope returned by read/query APIs. |
| 72 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 73 | pub struct PageResponse<T> { |
| 74 | pub items: Vec<T>, |
| 75 | pub next_cursor: Option<String>, |
| 76 | pub snapshot_seq: WalSeq, |
| 77 | pub total_matching: usize, |
| 78 | } |
| 79 | |
| 80 | /// Target selector for `tree` and `diff` inspection without a working-tree checkout. |
| 81 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] |
| 82 | pub enum TreeTarget { |
| 83 | BaseGitCommit(GitOid), |
| 84 | Changeset(ChangesetId), |
| 85 | } |
| 86 | |
| 87 | /// One file of a tree as returned by `tree`, `diff`, and `materialize_virtual_tree`. |
| 88 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 89 | pub struct VirtualTreeEntry { |
| 90 | pub path: String, |
| 91 | pub mode: FileMode, |
| 92 | pub blob_digest: BlobDigest, |
| 93 | pub git_blob_oid: GitOid, |
| 94 | pub size_bytes: u64, |
| 95 | } |
| 96 | |
| 97 | /// Kind of difference between two `VirtualTree` views. |
| 98 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] |
| 99 | pub enum DiffStatus { |
| 100 | Added, |
| 101 | Modified, |
| 102 | Deleted, |
| 103 | /// The entry changed between a symlink and a regular or executable file (Git status `T`). |
| 104 | TypeChanged, |
| 105 | } |
| 106 | |
| 107 | impl DiffStatus { |
| 108 | pub fn git_status_char(self) -> &'static str { |
| 109 | match self { |
| 110 | Self::Added => "A", |
| 111 | Self::Modified => "M", |
| 112 | Self::Deleted => "D", |
| 113 | Self::TypeChanged => "T", |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Single path difference entry returned by `diff`. |
| 119 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 120 | pub struct DiffEntry { |
| 121 | pub path: String, |
| 122 | pub status: DiffStatus, |
| 123 | pub old_entry: Option<VirtualTreeEntry>, |
| 124 | pub new_entry: Option<VirtualTreeEntry>, |
| 125 | } |
| 126 | |
| 127 | /// Entry returned by the paginated `history` API. |
| 128 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 129 | pub struct HistoryEntry { |
| 130 | pub changeset_id: ChangesetId, |
| 131 | pub committed_seq: WalSeq, |
| 132 | pub author_did: String, |
| 133 | pub created_at_ms: u64, |
| 134 | pub base_git_oid: GitOid, |
| 135 | pub parent_changesets: Vec<ChangesetId>, |
| 136 | pub intent_summary: String, |
| 137 | pub mutated_paths_count: usize, |
| 138 | } |
| 139 | |
| 140 | /// Comprehensive provenance receipt returned by `provenance`. |
| 141 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 142 | pub struct ProvenanceReport { |
| 143 | pub changeset_id: ChangesetId, |
| 144 | pub committed_seq: WalSeq, |
| 145 | pub repo_id: RepoId, |
| 146 | pub author_did: String, |
| 147 | pub idempotency_key: IdempotencyKey, |
| 148 | pub base_git_oid: GitOid, |
| 149 | pub parent_changesets: Vec<ChangesetId>, |
| 150 | pub evaluations: Vec<EvidenceAttachment>, |
| 151 | pub reviews: Vec<ReviewRecord>, |
| 152 | pub github_projection: Option<GitHubPullRequestProjection>, |
| 153 | pub canonical_promotion: Option<RadicleCanonicalHead>, |
| 154 | pub audit_trail: Vec<AuditEntry>, |
| 155 | } |
| 156 | |
| 157 | /// Path-level or directory/file hierarchy conflict between two concurrent changesets. |
| 158 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 159 | pub struct PathConflict { |
| 160 | pub path: String, |
| 161 | pub candidate_changeset: ChangesetId, |
| 162 | pub conflicting_changeset: ChangesetId, |
| 163 | pub reason: String, |
| 164 | } |
| 165 | |
| 166 | /// Repository service status returned by `status`. |
| 167 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 168 | pub struct ServiceStatus { |
| 169 | pub repo_id: RepoId, |
| 170 | pub committed_seq: WalSeq, |
| 171 | pub last_frame_sha256: [u8; 32], |
| 172 | pub state_root_digest: [u8; 32], |
| 173 | pub total_changesets: usize, |
| 174 | pub indexed_paths_count: usize, |
| 175 | pub cached_virtual_trees: usize, |
| 176 | pub canonical_head: Option<RadicleCanonicalHead>, |
| 177 | pub audit_chain_head: [u8; 32], |
| 178 | } |
| 179 | |
| 180 | /// Event item emitted on the `watch` subscription stream. |
| 181 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 182 | pub struct WatchEvent { |
| 183 | pub wal_seq: WalSeq, |
| 184 | pub changeset_id: ChangesetId, |
| 185 | pub author_did: String, |
| 186 | pub intent_summary: String, |
| 187 | pub touched_paths: Vec<String>, |
| 188 | } |
| 189 | |
| 190 | /// Durable subscriber cursor persisted on disk for crash-safe resumption. |
| 191 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 192 | pub struct WatchCursor { |
| 193 | pub subscriber_id: String, |
| 194 | pub repo_id: RepoId, |
| 195 | pub last_seen_seq: WalSeq, |
| 196 | pub last_frame_sha256: [u8; 32], |
| 197 | pub updated_at_ms: u64, |
| 198 | } |
| 199 | |
| 200 | /// Request payload for `submit`. |
| 201 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 202 | pub struct SubmitChangesetPayload { |
| 203 | pub envelope: ChangesetEnvelope, |
| 204 | pub blobs: Vec<(BlobDigest, Vec<u8>)>, |
| 205 | } |
| 206 | |
| 207 | /// Request payload for `tree`. |
| 208 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 209 | pub struct TreeQueryPayload { |
| 210 | pub target: TreeTarget, |
| 211 | pub path_prefix: Option<String>, |
| 212 | pub page: PageRequest, |
| 213 | } |
| 214 | |
| 215 | /// Request payload for `diff`. |
| 216 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 217 | pub struct DiffQueryPayload { |
| 218 | pub base: TreeTarget, |
| 219 | pub target: TreeTarget, |
| 220 | pub page: PageRequest, |
| 221 | } |
| 222 | |
| 223 | /// Request payload for `history`. |
| 224 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 225 | pub struct HistoryQueryPayload { |
| 226 | pub ancestor_of: Option<ChangesetId>, |
| 227 | pub path_filter: Option<String>, |
| 228 | pub page: PageRequest, |
| 229 | } |
| 230 | |
| 231 | /// Request payload for `conflicts`. |
| 232 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 233 | pub struct ConflictQueryPayload { |
| 234 | pub candidate: ChangesetId, |
| 235 | pub against: Option<Vec<ChangesetId>>, |
| 236 | pub page: PageRequest, |
| 237 | } |
| 238 | |
| 239 | /// Request payload for `watch`. |
| 240 | #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] |
| 241 | pub struct WatchQueryPayload { |
| 242 | pub subscriber_id: String, |
| 243 | pub after_seq: Option<WalSeq>, |
| 244 | pub page: PageRequest, |
| 245 | } |
| 246 | |
| 247 | /// Request payload for `advance_revision_state` (ADR 0003 B4, issue #89), in its one binary |
| 248 | /// encoding: `changeset_id [32] | state u8 | signed_at_ms u64 | signature [64]` (105 bytes). |
| 249 | /// `signature` is the request agent's Ed25519 signature over |
| 250 | /// [`SignedStateMove::statement_bytes`] for the service's repository, this revision and |
| 251 | /// state, the request's chain, and `signed_at_ms`; the store records it with the move. |
| 252 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 253 | pub struct RevisionStateMovePayload { |
| 254 | pub changeset_id: ChangesetId, |
| 255 | pub to: RevisionState, |
| 256 | pub signed_at_ms: u64, |
| 257 | pub signature: [u8; 64], |
| 258 | } |
| 259 | |
| 260 | impl RevisionStateMovePayload { |
| 261 | /// Encoded size. |
| 262 | pub const LEN: usize = 32 + 1 + 8 + 64; |
| 263 | |
| 264 | /// Sign a move of `changeset_id` of `repo_id` to `to` as `agent`, the leaf audience of |
| 265 | /// `chain`, at the agent's time `signed_at_ms`. |
| 266 | pub fn sign_new( |
| 267 | agent: &SigningKey, |
| 268 | repo_id: &RepoId, |
| 269 | chain: &CapabilityChain, |
| 270 | changeset_id: ChangesetId, |
| 271 | to: RevisionState, |
| 272 | signed_at_ms: u64, |
| 273 | ) -> SynapseResult<Self> { |
| 274 | let path = ChainPath::new(chain.link_digests().iter().map(|d| d.0).collect())?; |
| 275 | Ok(Self { |
| 276 | changeset_id, |
| 277 | to, |
| 278 | signed_at_ms, |
| 279 | signature: SignedStateMove::sign_statement( |
| 280 | agent, |
| 281 | repo_id, |
| 282 | changeset_id, |
| 283 | to, |
| 284 | &path, |
| 285 | signed_at_ms, |
| 286 | ), |
| 287 | }) |
| 288 | } |
| 289 | |
| 290 | pub fn encode(&self) -> Vec<u8> { |
| 291 | let mut buf = Vec::with_capacity(Self::LEN); |
| 292 | buf.extend_from_slice(&self.changeset_id.0); |
| 293 | buf.push(self.to.tag_byte()); |
| 294 | buf.extend_from_slice(&self.signed_at_ms.to_le_bytes()); |
| 295 | buf.extend_from_slice(&self.signature); |
| 296 | buf |
| 297 | } |
| 298 | |
| 299 | /// Exactly 105 bytes with a known state tag; anything else is `EnvelopeMalformed`. |
| 300 | pub fn decode(bytes: &[u8]) -> SynapseResult<Self> { |
| 301 | let malformed = || { |
| 302 | SynapseError::new( |
| 303 | RefusalCode::EnvelopeMalformed, |
| 304 | "state move payload must be changeset_id [32] | state u8 (1..=5) | signed_at_ms u64 | signature [64]", |
| 305 | ) |
| 306 | }; |
| 307 | if bytes.len() != Self::LEN { |
| 308 | return Err(malformed()); |
| 309 | } |
| 310 | let (id, rest) = bytes.split_at(32); |
| 311 | let (tag, rest) = rest.split_at(1); |
| 312 | let (at, sig) = rest.split_at(8); |
| 313 | Ok(Self { |
| 314 | changeset_id: ChangesetId(id.try_into().map_err(|_| malformed())?), |
| 315 | to: RevisionState::from_tag_byte(tag[0]).ok_or_else(malformed)?, |
| 316 | signed_at_ms: u64::from_le_bytes(at.try_into().map_err(|_| malformed())?), |
| 317 | signature: sig.try_into().map_err(|_| malformed())?, |
| 318 | }) |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// Exact path index mapping repository paths to touching `ChangesetId`s. Trees live in the |
| 323 | /// service's shared [`TreeStore`]. |
| 324 | #[derive(Debug, Default)] |
| 325 | pub struct PathIndex { |
| 326 | path_to_changesets: BTreeMap<String, BTreeSet<ChangesetId>>, |
| 327 | changeset_to_paths: BTreeMap<ChangesetId, Vec<String>>, |
| 328 | } |
| 329 | |
| 330 | impl PathIndex { |
| 331 | pub fn new() -> Self { |
| 332 | Self::default() |
| 333 | } |
| 334 | |
| 335 | pub fn index_changeset(&mut self, changeset_id: ChangesetId, envelope: &ChangesetEnvelope) { |
| 336 | let mut paths = Vec::with_capacity(envelope.mutations.len()); |
| 337 | for m in &envelope.mutations { |
| 338 | self.path_to_changesets |
| 339 | .entry(m.path.clone()) |
| 340 | .or_default() |
| 341 | .insert(changeset_id); |
| 342 | paths.push(m.path.clone()); |
| 343 | } |
| 344 | self.changeset_to_paths.insert(changeset_id, paths); |
| 345 | } |
| 346 | |
| 347 | /// Remove a `ChangesetId` from the path index. |
| 348 | pub fn invalidate_changeset(&mut self, changeset_id: ChangesetId) { |
| 349 | if let Some(paths) = self.changeset_to_paths.remove(&changeset_id) { |
| 350 | for p in paths { |
| 351 | if let Some(set) = self.path_to_changesets.get_mut(&p) { |
| 352 | set.remove(&changeset_id); |
| 353 | if set.is_empty() { |
| 354 | self.path_to_changesets.remove(&p); |
| 355 | } |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | pub fn changesets_for_path(&self, path: &str) -> Option<&BTreeSet<ChangesetId>> { |
| 362 | self.path_to_changesets.get(path) |
| 363 | } |
| 364 | |
| 365 | pub fn indexed_paths_count(&self) -> usize { |
| 366 | self.path_to_changesets.len() |
| 367 | } |
| 368 | } |
| 369 | |
| 370 | /// API-first changeset and virtual-tree inspection service (`Gate 2`). |
| 371 | pub struct SynapseService { |
| 372 | root_dir: PathBuf, |
| 373 | cursors_dir: PathBuf, |
| 374 | repo_id: RepoId, |
| 375 | store: SynapseStore, |
| 376 | auth: PolicyEnforcer, |
| 377 | path_index: PathIndex, |
| 378 | base_roots: BTreeMap<GitOid, TreeDigest>, |
| 379 | trees: TreeStore, |
| 380 | base_blobs: BTreeMap<BlobDigest, Vec<u8>>, |
| 381 | max_page_size: usize, |
| 382 | /// Materialized snapshots for advisory and Crumb reads, bounded by a share of the tree |
| 383 | /// cache bound (issue #94). Freed with the service. |
| 384 | snapshot_views: advisory::SnapshotViewCache, |
| 385 | } |
| 386 | |
| 387 | impl SynapseService { |
| 388 | /// Open or create a `SynapseService` at `root_dir` for `repo_id`. Revision records are |
| 389 | /// not sealed (see [`SynapseStore::open`]); [`Self::open_sealed`] seals them. |
| 390 | pub fn open( |
| 391 | root_dir: impl AsRef<Path>, |
| 392 | repo_id: RepoId, |
| 393 | fsync_policy: FsyncPolicy, |
| 394 | recovery_policy: RecoveryPolicy, |
| 395 | limits: StoreLimits, |
| 396 | ) -> SynapseResult<Self> { |
| 397 | Self::open_with( |
| 398 | root_dir, |
| 399 | repo_id, |
| 400 | fsync_policy, |
| 401 | recovery_policy, |
| 402 | limits, |
| 403 | None, |
| 404 | ) |
| 405 | } |
| 406 | |
| 407 | /// [`Self::open`] with the server's machine key sealing every revision record, so a |
| 408 | /// rewrite of the log without that key changes nothing on replay (issue #101; see |
| 409 | /// [`SynapseStore::open_sealed`]). |
| 410 | pub fn open_sealed( |
| 411 | root_dir: impl AsRef<Path>, |
| 412 | repo_id: RepoId, |
| 413 | fsync_policy: FsyncPolicy, |
| 414 | recovery_policy: RecoveryPolicy, |
| 415 | limits: StoreLimits, |
| 416 | seal: RevisionSealKey, |
| 417 | ) -> SynapseResult<Self> { |
| 418 | Self::open_with( |
| 419 | root_dir, |
| 420 | repo_id, |
| 421 | fsync_policy, |
| 422 | recovery_policy, |
| 423 | limits, |
| 424 | Some(seal), |
| 425 | ) |
| 426 | } |
| 427 | |
| 428 | fn open_with( |
| 429 | root_dir: impl AsRef<Path>, |
| 430 | repo_id: RepoId, |
| 431 | fsync_policy: FsyncPolicy, |
| 432 | recovery_policy: RecoveryPolicy, |
| 433 | limits: StoreLimits, |
| 434 | seal: Option<RevisionSealKey>, |
| 435 | ) -> SynapseResult<Self> { |
| 436 | let root_dir = root_dir.as_ref().to_path_buf(); |
| 437 | let cursors_dir = root_dir.join("cursors"); |
| 438 | fs::create_dir_all(&cursors_dir) |
| 439 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 440 | |
| 441 | let store = match seal { |
| 442 | Some(seal) => { |
| 443 | SynapseStore::open_sealed(&root_dir, fsync_policy, recovery_policy, limits, seal)? |
| 444 | } |
| 445 | None => SynapseStore::open(&root_dir, fsync_policy, recovery_policy, limits)?, |
| 446 | }; |
| 447 | let mut path_index = PathIndex::new(); |
| 448 | for cs in store.list_changesets(Some(&repo_id), None, None)? { |
| 449 | path_index.index_changeset(cs.changeset_id, &cs.envelope); |
| 450 | } |
| 451 | |
| 452 | Ok(Self { |
| 453 | root_dir, |
| 454 | cursors_dir, |
| 455 | repo_id, |
| 456 | store, |
| 457 | auth: PolicyEnforcer::new(), |
| 458 | path_index, |
| 459 | base_roots: BTreeMap::new(), |
| 460 | trees: TreeStore::new(TreeCacheConfig::default())?, |
| 461 | base_blobs: BTreeMap::new(), |
| 462 | max_page_size: DEFAULT_MAX_PAGE_SIZE, |
| 463 | snapshot_views: advisory::SnapshotViewCache::default(), |
| 464 | }) |
| 465 | } |
| 466 | |
| 467 | pub fn store(&self) -> &SynapseStore { |
| 468 | &self.store |
| 469 | } |
| 470 | |
| 471 | pub fn store_mut(&mut self) -> &mut SynapseStore { |
| 472 | &mut self.store |
| 473 | } |
| 474 | |
| 475 | pub fn auth(&self) -> &PolicyEnforcer { |
| 476 | &self.auth |
| 477 | } |
| 478 | |
| 479 | pub fn auth_mut(&mut self) -> &mut PolicyEnforcer { |
| 480 | &mut self.auth |
| 481 | } |
| 482 | |
| 483 | pub fn path_index(&self) -> &PathIndex { |
| 484 | &self.path_index |
| 485 | } |
| 486 | |
| 487 | /// Register a trusted repository authority `did:key:z6Mk...`. |
| 488 | pub fn register_authority(&mut self, authority_did: impl Into<String>) { |
| 489 | self.auth |
| 490 | .register_repo_authority(self.repo_id.clone(), authority_did); |
| 491 | } |
| 492 | |
| 493 | /// Register an in-memory base Git commit tree for checkout-free tree overlays. The tree is |
| 494 | /// built once as a native Merkle tree and pinned in the [`TreeStore`] (base trees are the |
| 495 | /// source every changeset tree is rebuilt from); a base that does not fit in the tree cache |
| 496 | /// bound is refused with `RefusalCode::BackpressureOverCapacity`. |
| 497 | pub fn register_base_tree( |
| 498 | &mut self, |
| 499 | base_git_oid: GitOid, |
| 500 | files: Vec<(String, FileMode, Vec<u8>)>, |
| 501 | ) -> SynapseResult<()> { |
| 502 | let mut edit = TreeEdit::new(&mut self.trees, TreeDigest::empty())?; |
| 503 | let mut blobs = Vec::with_capacity(files.len()); |
| 504 | for (path, mode, bytes) in files { |
| 505 | validate_repo_relative_path(&path)?; |
| 506 | let file = TreeFile { |
| 507 | mode, |
| 508 | blob_digest: BlobDigest::compute(&bytes), |
| 509 | size_bytes: bytes.len() as u64, |
| 510 | git_blob_oid: GitOid::compute_blob(&bytes), |
| 511 | }; |
| 512 | edit.upsert(&mut self.trees, &path, file)?; |
| 513 | blobs.push((file.blob_digest, bytes)); |
| 514 | } |
| 515 | let root = edit.finish(&mut self.trees)?; |
| 516 | if self.base_roots.get(&base_git_oid) != Some(&root) { |
| 517 | self.trees.pin(root)?; |
| 518 | if let Some(old) = self.base_roots.insert(base_git_oid, root) { |
| 519 | self.trees.unpin(old); |
| 520 | } |
| 521 | } |
| 522 | self.base_blobs.extend(blobs); |
| 523 | Ok(()) |
| 524 | } |
| 525 | |
| 526 | /// Import a real Git commit's tree from `git_repo_dir` without checking out a working tree, |
| 527 | /// using `git ls-tree -r -z` and `git cat-file blob`. |
| 528 | pub fn import_base_tree_from_git_repo( |
| 529 | &mut self, |
| 530 | git_repo_dir: &Path, |
| 531 | commit_rev: &str, |
| 532 | ) -> SynapseResult<GitOid> { |
| 533 | let rev_out = Command::new("git") |
| 534 | .arg("-C") |
| 535 | .arg(git_repo_dir) |
| 536 | .arg("rev-parse") |
| 537 | .arg(format!("{commit_rev}^{{commit}}")) |
| 538 | .output() |
| 539 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 540 | if !rev_out.status.success() { |
| 541 | return Err(SynapseError::new( |
| 542 | RefusalCode::BaseTreeNotFound, |
| 543 | format!("git rev-parse failed for {commit_rev}"), |
| 544 | )); |
| 545 | } |
| 546 | let commit_hex = String::from_utf8_lossy(&rev_out.stdout).trim().to_string(); |
| 547 | let commit_oid = GitOid::from_hex(&commit_hex)?; |
| 548 | |
| 549 | let ls_out = Command::new("git") |
| 550 | .arg("-C") |
| 551 | .arg(git_repo_dir) |
| 552 | .arg("ls-tree") |
| 553 | .arg("-r") |
| 554 | .arg("-z") |
| 555 | .arg(&commit_hex) |
| 556 | .output() |
| 557 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 558 | if !ls_out.status.success() { |
| 559 | return Err(SynapseError::new( |
| 560 | RefusalCode::BaseTreeNotFound, |
| 561 | "git ls-tree failed", |
| 562 | )); |
| 563 | } |
| 564 | |
| 565 | let mut files = Vec::new(); |
| 566 | for record in ls_out.stdout.split(|&b| b == 0) { |
| 567 | if record.is_empty() { |
| 568 | continue; |
| 569 | } |
| 570 | let rec_str = std::str::from_utf8(record) |
| 571 | .map_err(|e| SynapseError::new(RefusalCode::GitObjectCorrupt, e.to_string()))?; |
| 572 | let (meta, path) = rec_str.split_once('\t').ok_or_else(|| { |
| 573 | SynapseError::new(RefusalCode::GitObjectCorrupt, "malformed git ls-tree line") |
| 574 | })?; |
| 575 | let mut parts = meta.split_whitespace(); |
| 576 | let mode_str = parts.next().unwrap_or(""); |
| 577 | let _obj_type = parts.next().unwrap_or(""); |
| 578 | let oid_hex = parts.next().unwrap_or(""); |
| 579 | |
| 580 | let mode = match mode_str { |
| 581 | "100644" => FileMode::Regular644, |
| 582 | "100755" => FileMode::Executable755, |
| 583 | "120000" => FileMode::Symlink120000, |
| 584 | _ => continue, |
| 585 | }; |
| 586 | |
| 587 | let cat_out = Command::new("git") |
| 588 | .arg("-C") |
| 589 | .arg(git_repo_dir) |
| 590 | .arg("cat-file") |
| 591 | .arg("blob") |
| 592 | .arg(oid_hex) |
| 593 | .output() |
| 594 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 595 | if !cat_out.status.success() { |
| 596 | return Err(SynapseError::new( |
| 597 | RefusalCode::GitObjectCorrupt, |
| 598 | format!("git cat-file failed for {oid_hex}"), |
| 599 | )); |
| 600 | } |
| 601 | files.push((path.to_string(), mode, cat_out.stdout)); |
| 602 | } |
| 603 | |
| 604 | self.register_base_tree(commit_oid, files)?; |
| 605 | Ok(commit_oid) |
| 606 | } |
| 607 | |
| 608 | /// API 1: `submit` a signed changeset proposal (`Capability::Propose`). |
| 609 | /// Enforces capability and anti-replay at `BoundaryKind::Api` and store admission at `BoundaryKind::Store`. |
| 610 | pub fn submit( |
| 611 | &mut self, |
| 612 | req: &AuthenticatedRequest<SubmitChangesetPayload>, |
| 613 | now_ms: u64, |
| 614 | ) -> SynapseResult<IngestOutcome> { |
| 615 | self.admit_submit(req, now_ms)?; |
| 616 | let outcome = self |
| 617 | .store |
| 618 | .ingest_changeset(req.payload.envelope.clone(), &req.payload.blobs)?; |
| 619 | self.index_submitted(&outcome, &req.payload.envelope); |
| 620 | Ok(outcome) |
| 621 | } |
| 622 | |
| 623 | /// API-boundary half of [`Self::submit`]: capability, anti-replay, repository, author |
| 624 | /// and base-tree checks, without touching the store. A caller that commits through a |
| 625 | /// group-commit `SharedStore` runs this, then `SharedStore::submit`, then |
| 626 | /// [`Self::index_submitted`]. |
| 627 | pub fn admit_submit( |
| 628 | &mut self, |
| 629 | req: &AuthenticatedRequest<SubmitChangesetPayload>, |
| 630 | now_ms: u64, |
| 631 | ) -> SynapseResult<()> { |
| 632 | self.auth.authorize( |
| 633 | BoundaryKind::Api, |
| 634 | "submit", |
| 635 | &self.repo_id, |
| 636 | Capability::Propose, |
| 637 | req, |
| 638 | now_ms, |
| 639 | )?; |
| 640 | // Secret scanning (ADR 0003 section 5.13, step M1) runs here, before the store and the |
| 641 | // single writer, so a refused secret never reaches the WAL. |
| 642 | secret_scan::check_blobs(&req.payload.blobs)?; |
| 643 | |
| 644 | if req.payload.envelope.repo_id != self.repo_id { |
| 645 | return Err(SynapseError::new( |
| 646 | RefusalCode::AuthCrossRepoDenied, |
| 647 | "envelope repo_id does not match service repo_id", |
| 648 | )); |
| 649 | } |
| 650 | if req.payload.envelope.author_did != req.grant.agent_did { |
| 651 | return Err(SynapseError::new( |
| 652 | RefusalCode::AuthSignatureInvalid, |
| 653 | "envelope author_did does not match authenticated grant agent_did", |
| 654 | )); |
| 655 | } |
| 656 | if !self |
| 657 | .base_roots |
| 658 | .contains_key(&req.payload.envelope.base_git_oid) |
| 659 | { |
| 660 | return Err(SynapseError::new( |
| 661 | RefusalCode::BaseTreeNotFound, |
| 662 | format!( |
| 663 | "base_git_oid {} is not registered in service", |
| 664 | req.payload.envelope.base_git_oid |
| 665 | ), |
| 666 | )); |
| 667 | } |
| 668 | |
| 669 | Ok(()) |
| 670 | } |
| 671 | |
| 672 | /// Submit an envelope v2 revision (ADR 0003 B1) under an F1 delegation chain. |
| 673 | /// `req.payload` is the canonical envelope encoding; `req.scope` must name the |
| 674 | /// revision's `ChangeId` as `join_change` and exactly its mutation paths, so the chain's |
| 675 | /// change and path scopes are enforced (`AuthChangeOutOfScope`, `AuthPathOutOfScope`). |
| 676 | /// The chain must grant `Propose`; the attestation must be signed by the request's agent |
| 677 | /// for this repository; the base `TreeDigest` must be a registered base root or a tree |
| 678 | /// the tree store holds (`BaseTreeNotFound`). The store then applies the join rule |
| 679 | /// against the change's creating chain. |
| 680 | pub fn submit_revision( |
| 681 | &mut self, |
| 682 | req: &ChainedRequest, |
| 683 | blobs: &[(BlobDigest, Vec<u8>)], |
| 684 | now_ms: u64, |
| 685 | ) -> SynapseResult<RevisionOutcome> { |
| 686 | let envelope = ChangesetEnvelopeV2::decode(&req.payload)?; |
| 687 | let content = &envelope.content; |
| 688 | check_join_scope(req, content.change_id)?; |
| 689 | let paths: Vec<String> = content.mutations.iter().map(|m| m.path.clone()).collect(); |
| 690 | if req.scope.paths != paths { |
| 691 | return Err(SynapseError::new( |
| 692 | RefusalCode::AuthPathOutOfScope, |
| 693 | "request scope paths must be exactly the revision's mutation paths", |
| 694 | )); |
| 695 | } |
| 696 | self.auth.authorize_chain( |
| 697 | BoundaryKind::Api, |
| 698 | "submit_revision", |
| 699 | &self.repo_id, |
| 700 | Capability::Propose, |
| 701 | req, |
| 702 | self.store.committed_seq().next(), |
| 703 | now_ms, |
| 704 | )?; |
| 705 | if envelope.attestation.repo_id != self.repo_id { |
| 706 | return Err(SynapseError::new( |
| 707 | RefusalCode::AuthCrossRepoDenied, |
| 708 | "attestation repo_id does not match service repo_id", |
| 709 | )); |
| 710 | } |
| 711 | if envelope.attestation.author_key != req.agent_key { |
| 712 | return Err(SynapseError::new( |
| 713 | RefusalCode::AuthSignatureInvalid, |
| 714 | "attestation author is not the agent that presented the chain", |
| 715 | )); |
| 716 | } |
| 717 | let base = content.base_tree; |
| 718 | if !self.base_roots.values().any(|r| *r == base) && !self.tree_store().contains(base) { |
| 719 | return Err(SynapseError::new( |
| 720 | RefusalCode::BaseTreeNotFound, |
| 721 | format!("base tree {base} is not known to the service"), |
| 722 | )); |
| 723 | } |
| 724 | let authority = admission_authority(req)?; |
| 725 | secret_scan::check_blobs(blobs)?; |
| 726 | self.store |
| 727 | .admit_revision(envelope, blobs, authority, now_ms) |
| 728 | } |
| 729 | |
| 730 | /// Record an obsolescence marker (ADR 0003 B1) under an F1 delegation chain granting |
| 731 | /// `Propose`. `req.payload` is the canonical marker encoding and `req.scope.join_change` |
| 732 | /// must name its `ChangeId`; the marker must be signed by the request's agent. The store |
| 733 | /// applies the dominance rules (`AuthChainNotDominant`). |
| 734 | pub fn record_obsolescence( |
| 735 | &mut self, |
| 736 | req: &ChainedRequest, |
| 737 | now_ms: u64, |
| 738 | ) -> SynapseResult<WalSeq> { |
| 739 | let marker = ObsolescenceMarker::decode(&req.payload)?; |
| 740 | check_join_scope(req, marker.change_id)?; |
| 741 | self.auth.authorize_chain( |
| 742 | BoundaryKind::Api, |
| 743 | "record_obsolescence", |
| 744 | &self.repo_id, |
| 745 | Capability::Propose, |
| 746 | req, |
| 747 | self.store.committed_seq().next(), |
| 748 | now_ms, |
| 749 | )?; |
| 750 | if marker.repo_id != self.repo_id { |
| 751 | return Err(SynapseError::new( |
| 752 | RefusalCode::AuthCrossRepoDenied, |
| 753 | "marker repo_id does not match service repo_id", |
| 754 | )); |
| 755 | } |
| 756 | if marker.signer_key != req.agent_key { |
| 757 | return Err(SynapseError::new( |
| 758 | RefusalCode::AuthSignatureInvalid, |
| 759 | "marker signer is not the agent that presented the chain", |
| 760 | )); |
| 761 | } |
| 762 | let chain = admission_authority(req)?.chain; |
| 763 | self.store.record_obsolescence(marker, chain, now_ms) |
| 764 | } |
| 765 | |
| 766 | /// Move a revision's state (ADR 0003 B4) under an F1 delegation chain granting |
| 767 | /// `Propose`. `req.payload` is a [`RevisionStateMovePayload`]: the request agent (the |
| 768 | /// chain's leaf audience) must sign the move itself (issue #89), and the store records |
| 769 | /// that signature with the chain's leaf link, so replay can check the mover. A signature |
| 770 | /// that does not verify is `AuthSignatureInvalid`. The store applies the owner-chain and |
| 771 | /// state-machine rules: any move to `Canonical` is refused |
| 772 | /// (`CanonicalOutsidePromotionQueue`; canonical moves only through the promotion queue, |
| 773 | /// step E2), another owner's `Private` revision is `ChangesetNotFound`, a chain that does |
| 774 | /// not own the revision is `AuthChainNotDominant`, and a move to `Verified` or any move |
| 775 | /// that is backwards, in place, or skips a state is `RevisionStateMoveInvalid`. |
| 776 | pub fn advance_revision_state( |
| 777 | &mut self, |
| 778 | req: &ChainedRequest, |
| 779 | now_ms: u64, |
| 780 | ) -> SynapseResult<WalSeq> { |
| 781 | let mv = RevisionStateMovePayload::decode(&req.payload)?; |
| 782 | self.auth.authorize_chain( |
| 783 | BoundaryKind::Api, |
| 784 | "advance_revision_state", |
| 785 | &self.repo_id, |
| 786 | Capability::Propose, |
| 787 | req, |
| 788 | self.store.committed_seq().next(), |
| 789 | now_ms, |
| 790 | )?; |
| 791 | let leaf_link = req.chain.leaf().cloned().ok_or_else(|| { |
| 792 | SynapseError::new(RefusalCode::AuthChainBroken, "state move: empty chain") |
| 793 | })?; |
| 794 | let state_move = SignedStateMove { |
| 795 | repo_id: self.repo_id.clone(), |
| 796 | changeset_id: mv.changeset_id, |
| 797 | to: mv.to, |
| 798 | chain: admission_authority(req)?.chain, |
| 799 | signed_at_ms: mv.signed_at_ms, |
| 800 | leaf_link, |
| 801 | mover_key: req.agent_key, |
| 802 | signature: mv.signature, |
| 803 | }; |
| 804 | self.store.advance_revision_state(state_move, now_ms) |
| 805 | } |
| 806 | |
| 807 | /// Read an envelope v2 revision (ADR 0003 B4) under an F1 delegation chain granting |
| 808 | /// `Read`. `req.payload` is the 32-byte `ChangesetId`. A revision the chain may not see |
| 809 | /// is `ChangesetNotFound`, exactly like an unknown one: another owner's `Private` |
| 810 | /// revision, or a revision with a mutation path outside the chain's path scope. |
| 811 | pub fn read_revision( |
| 812 | &mut self, |
| 813 | req: &ChainedRequest, |
| 814 | now_ms: u64, |
| 815 | ) -> SynapseResult<StoredRevision> { |
| 816 | let id: [u8; 32] = req.payload.as_slice().try_into().map_err(|_| { |
| 817 | SynapseError::new( |
| 818 | RefusalCode::EnvelopeMalformed, |
| 819 | "read_revision payload must be exactly one 32-byte ChangesetId", |
| 820 | ) |
| 821 | })?; |
| 822 | let id = ChangesetId(id); |
| 823 | self.auth.authorize_chain( |
| 824 | BoundaryKind::Api, |
| 825 | "read_revision", |
| 826 | &self.repo_id, |
| 827 | Capability::Read, |
| 828 | req, |
| 829 | self.store.committed_seq().next(), |
| 830 | now_ms, |
| 831 | )?; |
| 832 | let viewer = admission_authority(req)?.chain; |
| 833 | let rev = self |
| 834 | .store |
| 835 | .get_revision_visible_to(&self.repo_id, id, &viewer)?; |
| 836 | let in_scope = req.chain.leaf().is_some_and(|leaf| { |
| 837 | rev.content |
| 838 | .mutations |
| 839 | .iter() |
| 840 | .all(|m| leaf.caveats.paths.covers_path(&m.path)) |
| 841 | }); |
| 842 | if !in_scope { |
| 843 | return Err(SynapseError::new( |
| 844 | RefusalCode::ChangesetNotFound, |
| 845 | format!("revision {id} not found"), |
| 846 | )); |
| 847 | } |
| 848 | Ok(rev) |
| 849 | } |
| 850 | |
| 851 | /// Index a committed (or duplicate) submission in the path index. |
| 852 | pub fn index_submitted(&mut self, outcome: &IngestOutcome, envelope: &ChangesetEnvelope) { |
| 853 | let cs_id = match outcome { |
| 854 | IngestOutcome::Committed { changeset_id, .. } |
| 855 | | IngestOutcome::IdempotentDuplicate { changeset_id, .. } => *changeset_id, |
| 856 | }; |
| 857 | self.path_index.index_changeset(cs_id, envelope); |
| 858 | } |
| 859 | |
| 860 | /// API 2: `get` a committed changeset (`Capability::Read`). |
| 861 | pub fn get( |
| 862 | &mut self, |
| 863 | req: &AuthenticatedRequest<(ChangesetId, Option<WalSeq>, Option<WalSeq>)>, |
| 864 | now_ms: u64, |
| 865 | ) -> SynapseResult<StoredChangeset> { |
| 866 | self.auth.authorize( |
| 867 | BoundaryKind::Api, |
| 868 | "get", |
| 869 | &self.repo_id, |
| 870 | Capability::Read, |
| 871 | req, |
| 872 | now_ms, |
| 873 | )?; |
| 874 | let (cs_id, min_seq, snap_seq) = req.payload; |
| 875 | self.store |
| 876 | .get_changeset_in_repo(&self.repo_id, cs_id, min_seq, snap_seq) |
| 877 | } |
| 878 | |
| 879 | /// Read a file's raw bytes at `TreeTarget` without cloning or checking out a working tree (`Capability::Read`). |
| 880 | pub fn read_file( |
| 881 | &mut self, |
| 882 | req: &AuthenticatedRequest<(TreeTarget, String, Option<WalSeq>)>, |
| 883 | now_ms: u64, |
| 884 | ) -> SynapseResult<Vec<u8>> { |
| 885 | self.auth.authorize( |
| 886 | BoundaryKind::Api, |
| 887 | "read_file", |
| 888 | &self.repo_id, |
| 889 | Capability::Read, |
| 890 | req, |
| 891 | now_ms, |
| 892 | )?; |
| 893 | let (target, ref path, snap_seq) = req.payload; |
| 894 | let file = self |
| 895 | .with_tree(target, snap_seq, |trees, root| trees.lookup(root, path))? |
| 896 | .ok_or_else(|| { |
| 897 | SynapseError::new( |
| 898 | RefusalCode::BlobNotFound, |
| 899 | format!("path {path} not found in tree"), |
| 900 | ) |
| 901 | })?; |
| 902 | self.read_blob_bytes(file.blob_digest, snap_seq) |
| 903 | } |
| 904 | |
| 905 | /// API 3: `tree` returns a bounded, cursor-paginated `VirtualTree` without checkout (`Capability::Read`). |
| 906 | pub fn tree( |
| 907 | &mut self, |
| 908 | req: &AuthenticatedRequest<TreeQueryPayload>, |
| 909 | now_ms: u64, |
| 910 | ) -> SynapseResult<PageResponse<VirtualTreeEntry>> { |
| 911 | self.auth.authorize( |
| 912 | BoundaryKind::Api, |
| 913 | "tree", |
| 914 | &self.repo_id, |
| 915 | Capability::Read, |
| 916 | req, |
| 917 | now_ms, |
| 918 | )?; |
| 919 | let snap_seq = self.validate_page_request(&req.payload.page)?; |
| 920 | let prefix = req.payload.path_prefix.as_deref().unwrap_or(""); |
| 921 | let offset = parse_offset_cursor(&req.payload.page)?; |
| 922 | let limit = req.payload.page.limit; |
| 923 | let (total, items) = |
| 924 | self.tree_page(req.payload.target, prefix, offset, limit, Some(snap_seq))?; |
| 925 | let end = offset + items.len() as u64; |
| 926 | Ok(PageResponse { |
| 927 | items, |
| 928 | next_cursor: (end < total).then(|| format!("offset:{end}")), |
| 929 | snapshot_seq: snap_seq, |
| 930 | total_matching: total as usize, |
| 931 | }) |
| 932 | } |
| 933 | |
| 934 | /// API 4: `diff` computes a bounded, cursor-paginated path diff between two `TreeTarget`s (`Capability::Read`). |
| 935 | pub fn diff( |
| 936 | &mut self, |
| 937 | req: &AuthenticatedRequest<DiffQueryPayload>, |
| 938 | now_ms: u64, |
| 939 | ) -> SynapseResult<PageResponse<DiffEntry>> { |
| 940 | self.auth.authorize( |
| 941 | BoundaryKind::Api, |
| 942 | "diff", |
| 943 | &self.repo_id, |
| 944 | Capability::Read, |
| 945 | req, |
| 946 | now_ms, |
| 947 | )?; |
| 948 | let snap_seq = self.validate_page_request(&req.payload.page)?; |
| 949 | let diffs: Vec<DiffEntry> = self |
| 950 | .diff_trees(req.payload.base, req.payload.target, Some(snap_seq))? |
| 951 | .into_iter() |
| 952 | .map(diff_entry) |
| 953 | .collect(); |
| 954 | paginate_slice(&diffs, &req.payload.page, snap_seq) |
| 955 | } |
| 956 | |
| 957 | /// API 5: `history` returns a bounded, cursor-paginated changeset history (`Capability::Read`). |
| 958 | pub fn history( |
| 959 | &mut self, |
| 960 | req: &AuthenticatedRequest<HistoryQueryPayload>, |
| 961 | now_ms: u64, |
| 962 | ) -> SynapseResult<PageResponse<HistoryEntry>> { |
| 963 | self.auth.authorize( |
| 964 | BoundaryKind::Api, |
| 965 | "history", |
| 966 | &self.repo_id, |
| 967 | Capability::Read, |
| 968 | req, |
| 969 | now_ms, |
| 970 | )?; |
| 971 | let snap_seq = self.validate_page_request(&req.payload.page)?; |
| 972 | |
| 973 | let allowed_by_ancestor: Option<BTreeSet<ChangesetId>> = |
| 974 | if let Some(head_id) = req.payload.ancestor_of { |
| 975 | let mut set = BTreeSet::new(); |
| 976 | let mut stack = vec![head_id]; |
| 977 | while let Some(curr) = stack.pop() { |
| 978 | if set.insert(curr) { |
| 979 | let stored = self.store.get_changeset_in_repo( |
| 980 | &self.repo_id, |
| 981 | curr, |
| 982 | None, |
| 983 | Some(snap_seq), |
| 984 | )?; |
| 985 | for p in &stored.envelope.parent_changesets { |
| 986 | stack.push(*p); |
| 987 | } |
| 988 | } |
| 989 | } |
| 990 | Some(set) |
| 991 | } else { |
| 992 | None |
| 993 | }; |
| 994 | |
| 995 | let allowed_by_path: Option<BTreeSet<ChangesetId>> = |
| 996 | req.payload.path_filter.as_ref().map(|p| { |
| 997 | self.path_index |
| 998 | .changesets_for_path(p) |
| 999 | .cloned() |
| 1000 | .unwrap_or_default() |
| 1001 | }); |
| 1002 | |
| 1003 | let all_visible = self.store.list_changesets( |
| 1004 | Some(&self.repo_id), |
| 1005 | req.payload.page.min_visible_seq, |
| 1006 | Some(snap_seq), |
| 1007 | )?; |
| 1008 | |
| 1009 | let mut entries: Vec<HistoryEntry> = all_visible |
| 1010 | .into_iter() |
| 1011 | .rev() // newest first |
| 1012 | .filter(|cs| { |
| 1013 | allowed_by_ancestor |
| 1014 | .as_ref() |
| 1015 | .is_none_or(|s| s.contains(&cs.changeset_id)) |
| 1016 | && allowed_by_path |
| 1017 | .as_ref() |
| 1018 | .is_none_or(|s| s.contains(&cs.changeset_id)) |
| 1019 | }) |
| 1020 | .map(|cs| HistoryEntry { |
| 1021 | changeset_id: cs.changeset_id, |
| 1022 | committed_seq: cs.committed_seq, |
| 1023 | author_did: cs.envelope.author_did.clone(), |
| 1024 | created_at_ms: cs.envelope.created_at_ms, |
| 1025 | base_git_oid: cs.envelope.base_git_oid, |
| 1026 | parent_changesets: cs.envelope.parent_changesets.clone(), |
| 1027 | intent_summary: cs.envelope.intent_summary.clone(), |
| 1028 | mutated_paths_count: cs.envelope.mutations.len(), |
| 1029 | }) |
| 1030 | .collect(); |
| 1031 | |
| 1032 | entries.sort_by_key(|a| std::cmp::Reverse(a.committed_seq)); |
| 1033 | paginate_slice(&entries, &req.payload.page, snap_seq) |
| 1034 | } |
| 1035 | |
| 1036 | /// API 6: `provenance` returns the full cryptographic and audit provenance for a `ChangesetId` (`Capability::Read`). |
| 1037 | pub fn provenance( |
| 1038 | &mut self, |
| 1039 | req: &AuthenticatedRequest<(ChangesetId, Option<WalSeq>)>, |
| 1040 | now_ms: u64, |
| 1041 | ) -> SynapseResult<ProvenanceReport> { |
| 1042 | self.auth.authorize( |
| 1043 | BoundaryKind::Api, |
| 1044 | "provenance", |
| 1045 | &self.repo_id, |
| 1046 | Capability::Read, |
| 1047 | req, |
| 1048 | now_ms, |
| 1049 | )?; |
| 1050 | let (cs_id, snap_seq) = req.payload; |
| 1051 | let stored = self |
| 1052 | .store |
| 1053 | .get_changeset_in_repo(&self.repo_id, cs_id, None, snap_seq)?; |
| 1054 | let github_projection = self |
| 1055 | .store |
| 1056 | .github_projections() |
| 1057 | .values() |
| 1058 | .find(|p| p.changeset_id == cs_id) |
| 1059 | .cloned(); |
| 1060 | let canonical_promotion = self |
| 1061 | .store |
| 1062 | .canonical_head(&self.repo_id) |
| 1063 | .filter(|c| c.promoted_changeset_id == Some(cs_id)) |
| 1064 | .cloned(); |
| 1065 | let audit_trail: Vec<AuditEntry> = self |
| 1066 | .auth |
| 1067 | .audit_log() |
| 1068 | .entries() |
| 1069 | .iter() |
| 1070 | .filter(|e| e.repo_id == self.repo_id) |
| 1071 | .cloned() |
| 1072 | .collect(); |
| 1073 | |
| 1074 | Ok(ProvenanceReport { |
| 1075 | changeset_id: cs_id, |
| 1076 | committed_seq: stored.committed_seq, |
| 1077 | repo_id: stored.envelope.repo_id, |
| 1078 | author_did: stored.envelope.author_did, |
| 1079 | idempotency_key: stored.envelope.idempotency_key, |
| 1080 | base_git_oid: stored.envelope.base_git_oid, |
| 1081 | parent_changesets: stored.envelope.parent_changesets, |
| 1082 | evaluations: stored.evaluations, |
| 1083 | reviews: stored.reviews, |
| 1084 | github_projection, |
| 1085 | canonical_promotion, |
| 1086 | audit_trail, |
| 1087 | }) |
| 1088 | } |
| 1089 | |
| 1090 | /// API 7: `conflicts` detects path-level and file/directory collisions across concurrent changesets (`Capability::Read`). |
| 1091 | pub fn conflicts( |
| 1092 | &mut self, |
| 1093 | req: &AuthenticatedRequest<ConflictQueryPayload>, |
| 1094 | now_ms: u64, |
| 1095 | ) -> SynapseResult<PageResponse<PathConflict>> { |
| 1096 | self.auth.authorize( |
| 1097 | BoundaryKind::Api, |
| 1098 | "conflicts", |
| 1099 | &self.repo_id, |
| 1100 | Capability::Read, |
| 1101 | req, |
| 1102 | now_ms, |
| 1103 | )?; |
| 1104 | let snap_seq = self.validate_page_request(&req.payload.page)?; |
| 1105 | let cand_stored = self.store.get_changeset_in_repo( |
| 1106 | &self.repo_id, |
| 1107 | req.payload.candidate, |
| 1108 | None, |
| 1109 | Some(snap_seq), |
| 1110 | )?; |
| 1111 | |
| 1112 | let peers: Vec<StoredChangeset> = if let Some(ref explicit) = req.payload.against { |
| 1113 | let mut list = Vec::with_capacity(explicit.len()); |
| 1114 | for &id in explicit { |
| 1115 | if id != req.payload.candidate { |
| 1116 | list.push(self.store.get_changeset_in_repo( |
| 1117 | &self.repo_id, |
| 1118 | id, |
| 1119 | None, |
| 1120 | Some(snap_seq), |
| 1121 | )?); |
| 1122 | } |
| 1123 | } |
| 1124 | list |
| 1125 | } else { |
| 1126 | self.store |
| 1127 | .list_changesets(Some(&self.repo_id), None, Some(snap_seq))? |
| 1128 | .into_iter() |
| 1129 | .filter(|cs| { |
| 1130 | cs.changeset_id != req.payload.candidate |
| 1131 | && cs.envelope.base_git_oid == cand_stored.envelope.base_git_oid |
| 1132 | && !cand_stored |
| 1133 | .envelope |
| 1134 | .parent_changesets |
| 1135 | .contains(&cs.changeset_id) |
| 1136 | && !cs |
| 1137 | .envelope |
| 1138 | .parent_changesets |
| 1139 | .contains(&req.payload.candidate) |
| 1140 | }) |
| 1141 | .collect() |
| 1142 | }; |
| 1143 | |
| 1144 | let mut conflicts = Vec::new(); |
| 1145 | for peer in &peers { |
| 1146 | for cm in &cand_stored.envelope.mutations { |
| 1147 | for pm in &peer.envelope.mutations { |
| 1148 | if cm.path == pm.path && cm.op != pm.op { |
| 1149 | conflicts.push(PathConflict { |
| 1150 | path: cm.path.clone(), |
| 1151 | candidate_changeset: cand_stored.changeset_id, |
| 1152 | conflicting_changeset: peer.changeset_id, |
| 1153 | reason: "concurrent incompatible mutations on same path".to_string(), |
| 1154 | }); |
| 1155 | } else if is_file_dir_prefix_collision(&cm.path, &pm.path) |
| 1156 | && !matches!(cm.op, MutationOp::Delete) |
| 1157 | && !matches!(pm.op, MutationOp::Delete) |
| 1158 | { |
| 1159 | conflicts.push(PathConflict { |
| 1160 | path: cm.path.clone(), |
| 1161 | candidate_changeset: cand_stored.changeset_id, |
| 1162 | conflicting_changeset: peer.changeset_id, |
| 1163 | reason: format!( |
| 1164 | "file/directory hierarchy collision between {} and {}", |
| 1165 | cm.path, pm.path |
| 1166 | ), |
| 1167 | }); |
| 1168 | } |
| 1169 | } |
| 1170 | } |
| 1171 | } |
| 1172 | |
| 1173 | paginate_slice(&conflicts, &req.payload.page, snap_seq) |
| 1174 | } |
| 1175 | |
| 1176 | /// API 8: `status` returns repository watermarks, index counts, and canonical state (`Capability::Read`). |
| 1177 | pub fn status( |
| 1178 | &mut self, |
| 1179 | req: &AuthenticatedRequest<Option<WalSeq>>, |
| 1180 | now_ms: u64, |
| 1181 | ) -> SynapseResult<ServiceStatus> { |
| 1182 | self.auth.authorize( |
| 1183 | BoundaryKind::Api, |
| 1184 | "status", |
| 1185 | &self.repo_id, |
| 1186 | Capability::Read, |
| 1187 | req, |
| 1188 | now_ms, |
| 1189 | )?; |
| 1190 | let snap_seq = req.payload.unwrap_or_else(|| self.store.committed_seq()); |
| 1191 | let state_root_digest = self.store.state_root_digest(Some(snap_seq))?; |
| 1192 | let visible_cs = self |
| 1193 | .store |
| 1194 | .list_changesets(Some(&self.repo_id), None, Some(snap_seq))?; |
| 1195 | let audit_chain_head = self.auth.audit_log().verify_chain()?; |
| 1196 | |
| 1197 | Ok(ServiceStatus { |
| 1198 | repo_id: self.repo_id.clone(), |
| 1199 | committed_seq: self.store.committed_seq(), |
| 1200 | last_frame_sha256: self.store.last_frame_sha256(), |
| 1201 | state_root_digest, |
| 1202 | total_changesets: visible_cs.len(), |
| 1203 | indexed_paths_count: self.path_index.indexed_paths_count(), |
| 1204 | cached_virtual_trees: self.trees.memoized_roots(), |
| 1205 | canonical_head: self.store.canonical_head(&self.repo_id).cloned(), |
| 1206 | audit_chain_head, |
| 1207 | }) |
| 1208 | } |
| 1209 | |
| 1210 | /// API 9: `watch` returns a bounded page of WAL events after `after_seq` (or the recovered |
| 1211 | /// durable subscriber cursor) and atomically persists the updated `WatchCursor` (`Capability::Read`). |
| 1212 | pub fn watch( |
| 1213 | &mut self, |
| 1214 | req: &AuthenticatedRequest<WatchQueryPayload>, |
| 1215 | now_ms: u64, |
| 1216 | ) -> SynapseResult<(PageResponse<WatchEvent>, WatchCursor)> { |
| 1217 | self.auth.authorize( |
| 1218 | BoundaryKind::Api, |
| 1219 | "watch", |
| 1220 | &self.repo_id, |
| 1221 | Capability::Read, |
| 1222 | req, |
| 1223 | now_ms, |
| 1224 | )?; |
| 1225 | let snap_seq = self.validate_page_request(&req.payload.page)?; |
| 1226 | |
| 1227 | let start_after = if let Some(explicit) = req.payload.after_seq { |
| 1228 | explicit |
| 1229 | } else if let Some(saved) = self.load_watch_cursor(&req.payload.subscriber_id)? { |
| 1230 | saved.last_seen_seq |
| 1231 | } else { |
| 1232 | WalSeq::ZERO |
| 1233 | }; |
| 1234 | |
| 1235 | let all_visible = self.store.list_changesets( |
| 1236 | Some(&self.repo_id), |
| 1237 | req.payload.page.min_visible_seq, |
| 1238 | Some(snap_seq), |
| 1239 | )?; |
| 1240 | |
| 1241 | let matching: Vec<WatchEvent> = all_visible |
| 1242 | .into_iter() |
| 1243 | .filter(|cs| cs.committed_seq > start_after) |
| 1244 | .map(|cs| WatchEvent { |
| 1245 | wal_seq: cs.committed_seq, |
| 1246 | changeset_id: cs.changeset_id, |
| 1247 | author_did: cs.envelope.author_did.clone(), |
| 1248 | intent_summary: cs.envelope.intent_summary.clone(), |
| 1249 | touched_paths: cs |
| 1250 | .envelope |
| 1251 | .mutations |
| 1252 | .iter() |
| 1253 | .map(|m| m.path.clone()) |
| 1254 | .collect(), |
| 1255 | }) |
| 1256 | .collect(); |
| 1257 | |
| 1258 | let page_resp = paginate_slice(&matching, &req.payload.page, snap_seq)?; |
| 1259 | let new_last_seen = page_resp |
| 1260 | .items |
| 1261 | .last() |
| 1262 | .map(|ev| ev.wal_seq) |
| 1263 | .unwrap_or(start_after); |
| 1264 | |
| 1265 | let cursor = WatchCursor { |
| 1266 | subscriber_id: req.payload.subscriber_id.clone(), |
| 1267 | repo_id: self.repo_id.clone(), |
| 1268 | last_seen_seq: new_last_seen, |
| 1269 | last_frame_sha256: self.store.last_frame_sha256(), |
| 1270 | updated_at_ms: now_ms, |
| 1271 | }; |
| 1272 | self.save_watch_cursor(&cursor)?; |
| 1273 | Ok((page_resp, cursor)) |
| 1274 | } |
| 1275 | |
| 1276 | /// Load a durable `WatchCursor` from disk if one exists for `subscriber_id`. |
| 1277 | pub fn load_watch_cursor(&self, subscriber_id: &str) -> SynapseResult<Option<WatchCursor>> { |
| 1278 | validate_subscriber_id(subscriber_id)?; |
| 1279 | let path = self.cursors_dir.join(format!("{subscriber_id}.json")); |
| 1280 | if !path.exists() { |
| 1281 | return Ok(None); |
| 1282 | } |
| 1283 | let raw = fs::read(&path) |
| 1284 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 1285 | let cursor: WatchCursor = serde_json::from_slice(&raw) |
| 1286 | .map_err(|e| SynapseError::new(RefusalCode::CursorInvalid, e.to_string()))?; |
| 1287 | Ok(Some(cursor)) |
| 1288 | } |
| 1289 | |
| 1290 | /// Atomically persist a durable `WatchCursor` to disk (`sync_all` + rename). |
| 1291 | pub fn save_watch_cursor(&self, cursor: &WatchCursor) -> SynapseResult<()> { |
| 1292 | validate_subscriber_id(&cursor.subscriber_id)?; |
| 1293 | let final_path = self |
| 1294 | .cursors_dir |
| 1295 | .join(format!("{}.json", cursor.subscriber_id)); |
| 1296 | let tmp_path = self |
| 1297 | .cursors_dir |
| 1298 | .join(format!("{}.json.tmp", cursor.subscriber_id)); |
| 1299 | let bytes = serde_json::to_vec(cursor) |
| 1300 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 1301 | { |
| 1302 | let mut f = File::create(&tmp_path) |
| 1303 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 1304 | f.write_all(&bytes) |
| 1305 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 1306 | f.sync_all() |
| 1307 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 1308 | } |
| 1309 | fs::rename(&tmp_path, &final_path) |
| 1310 | .map_err(|e| SynapseError::new(RefusalCode::IoFailure, e.to_string()))?; |
| 1311 | Ok(()) |
| 1312 | } |
| 1313 | |
| 1314 | /// Run store compaction and immediately perform exact path-index invalidation |
| 1315 | /// for all evicted speculative changesets. |
| 1316 | pub fn checkpoint_compact_and_invalidate_index( |
| 1317 | &mut self, |
| 1318 | now_ms: u64, |
| 1319 | ) -> SynapseResult<CompactionReport> { |
| 1320 | let before_ids: Vec<ChangesetId> = self |
| 1321 | .store |
| 1322 | .list_changesets(Some(&self.repo_id), None, None)? |
| 1323 | .into_iter() |
| 1324 | .map(|cs| cs.changeset_id) |
| 1325 | .collect(); |
| 1326 | |
| 1327 | let report = self.store.checkpoint_and_compact(now_ms)?; |
| 1328 | |
| 1329 | let retained_set: BTreeSet<ChangesetId> = self |
| 1330 | .store |
| 1331 | .list_changesets(Some(&self.repo_id), None, None)? |
| 1332 | .into_iter() |
| 1333 | .map(|cs| cs.changeset_id) |
| 1334 | .collect(); |
| 1335 | |
| 1336 | for id in before_ids { |
| 1337 | if !retained_set.contains(&id) { |
| 1338 | self.path_index.invalidate_changeset(id); |
| 1339 | self.trees.forget_root(id); |
| 1340 | } |
| 1341 | } |
| 1342 | Ok(report) |
| 1343 | } |
| 1344 | |
| 1345 | /// Materialize the complete sorted file list of `target` without a working-tree checkout. |
| 1346 | /// Prefer [`SynapseService::tree`] or [`SynapseService::tree_digest`] where a flat copy of |
| 1347 | /// the whole tree is not needed. |
| 1348 | pub fn materialize_virtual_tree( |
| 1349 | &mut self, |
| 1350 | target: TreeTarget, |
| 1351 | snapshot_seq: Option<WalSeq>, |
| 1352 | ) -> SynapseResult<BTreeMap<String, VirtualTreeEntry>> { |
| 1353 | let files = self.with_tree(target, snapshot_seq, |trees, root| trees.files(root))?; |
| 1354 | Ok(files |
| 1355 | .into_iter() |
| 1356 | .map(|(path, f)| (path.clone(), virtual_tree_entry(path, &f))) |
| 1357 | .collect()) |
| 1358 | } |
| 1359 | |
| 1360 | /// The native [`TreeDigest`] of `target`: the domain-separated Merkle root of the whole |
| 1361 | /// repository state (ADR 0003 section 5.1). Built on first use (the cold path) and then |
| 1362 | /// answered from the bounded root memo (the warm path). |
| 1363 | pub fn tree_digest( |
| 1364 | &mut self, |
| 1365 | target: TreeTarget, |
| 1366 | snapshot_seq: Option<WalSeq>, |
| 1367 | ) -> SynapseResult<TreeDigest> { |
| 1368 | self.with_tree(target, snapshot_seq, |_, root| Ok(root)) |
| 1369 | } |
| 1370 | |
| 1371 | /// One page of the files of `target` under `prefix` (path byte order) and the total count, |
| 1372 | /// paged straight from the Merkle tree by seeking with subtree file counts (no flat copy). |
| 1373 | /// This is the engine behind [`SynapseService::tree`] without the request authorization; |
| 1374 | /// an `offset` past the end is `CursorInvalid`. |
| 1375 | pub fn tree_page( |
| 1376 | &mut self, |
| 1377 | target: TreeTarget, |
| 1378 | prefix: &str, |
| 1379 | offset: u64, |
| 1380 | limit: usize, |
| 1381 | snapshot_seq: Option<WalSeq>, |
| 1382 | ) -> SynapseResult<(u64, Vec<VirtualTreeEntry>)> { |
| 1383 | let (total, files) = self.with_tree(target, snapshot_seq, |trees, root| { |
| 1384 | let total = trees.count_files(root, prefix)?; |
| 1385 | if offset > total { |
| 1386 | return Err(SynapseError::new( |
| 1387 | RefusalCode::CursorInvalid, |
| 1388 | format!("cursor offset {offset} out of bounds for {total} items"), |
| 1389 | )); |
| 1390 | } |
| 1391 | Ok((total, trees.page_files(root, prefix, offset, limit)?)) |
| 1392 | })?; |
| 1393 | Ok(( |
| 1394 | total, |
| 1395 | files |
| 1396 | .into_iter() |
| 1397 | .map(|(path, f)| virtual_tree_entry(path, &f)) |
| 1398 | .collect(), |
| 1399 | )) |
| 1400 | } |
| 1401 | |
| 1402 | /// Canonical encoded bytes and count of the distinct nodes of `target`'s tree: the bytes a |
| 1403 | /// full walk of the tree reads (the input of the warm paging bound). |
| 1404 | pub fn tree_encoded_bytes( |
| 1405 | &mut self, |
| 1406 | target: TreeTarget, |
| 1407 | snapshot_seq: Option<WalSeq>, |
| 1408 | ) -> SynapseResult<(u64, u64)> { |
| 1409 | self.with_tree(target, snapshot_seq, |trees, root| { |
| 1410 | trees.encoded_bytes(root) |
| 1411 | }) |
| 1412 | } |
| 1413 | |
| 1414 | /// Path-level differences from `base` to `target` in path byte order, computed by walking |
| 1415 | /// both Merkle trees and skipping every subtree whose digest is equal on both sides. |
| 1416 | pub fn diff_trees( |
| 1417 | &mut self, |
| 1418 | base: TreeTarget, |
| 1419 | target: TreeTarget, |
| 1420 | snapshot_seq: Option<WalSeq>, |
| 1421 | ) -> SynapseResult<Vec<TreeDiffEntry>> { |
| 1422 | let attempt = |svc: &mut Self, force: bool| -> SynapseResult<Vec<TreeDiffEntry>> { |
| 1423 | let a = svc.tree_root(base, snapshot_seq, force)?; |
| 1424 | let b = svc.tree_root(target, snapshot_seq, force)?; |
| 1425 | svc.trees.diff(a, b) |
| 1426 | }; |
| 1427 | match attempt(self, false) { |
| 1428 | Err(e) if e.code == RefusalCode::TreeNodeNotFound => { |
| 1429 | attempt(self, true).map_err(cache_bound_too_small) |
| 1430 | } |
| 1431 | other => other, |
| 1432 | } |
| 1433 | } |
| 1434 | |
| 1435 | /// The shared Merkle tree store (read-only view, for statistics and bounds). |
| 1436 | pub fn tree_store(&self) -> &TreeStore { |
| 1437 | &self.trees |
| 1438 | } |
| 1439 | |
| 1440 | /// Replace the tree store with one bounded by `config`, carrying the pinned base trees over. |
| 1441 | /// Memoized changeset roots and snapshot views are dropped and rebuilt on demand. |
| 1442 | pub fn set_tree_cache_config(&mut self, config: TreeCacheConfig) -> SynapseResult<()> { |
| 1443 | let mut next = TreeStore::new(config)?; |
| 1444 | for &root in self.base_roots.values() { |
| 1445 | copy_tree(&mut self.trees, &mut next, root)?; |
| 1446 | next.pin(root)?; |
| 1447 | } |
| 1448 | self.trees = next; |
| 1449 | self.snapshot_views.clear(); |
| 1450 | Ok(()) |
| 1451 | } |
| 1452 | |
| 1453 | /// Run `f` on the root of `target`. If `f` reaches a node evicted from the bounded store, |
| 1454 | /// the tree is rebuilt from its source once and `f` runs again; a tree that still cannot be |
| 1455 | /// walked means the bound is too small for one tree (`BackpressureOverCapacity`). |
| 1456 | fn with_tree<T>( |
| 1457 | &mut self, |
| 1458 | target: TreeTarget, |
| 1459 | snapshot_seq: Option<WalSeq>, |
| 1460 | mut f: impl FnMut(&mut TreeStore, TreeDigest) -> SynapseResult<T>, |
| 1461 | ) -> SynapseResult<T> { |
| 1462 | let first = self |
| 1463 | .tree_root(target, snapshot_seq, false) |
| 1464 | .and_then(|root| f(&mut self.trees, root)); |
| 1465 | match first { |
| 1466 | Err(e) if e.code == RefusalCode::TreeNodeNotFound => { |
| 1467 | let root = self |
| 1468 | .tree_root(target, snapshot_seq, true) |
| 1469 | .map_err(cache_bound_too_small)?; |
| 1470 | f(&mut self.trees, root).map_err(cache_bound_too_small) |
| 1471 | } |
| 1472 | other => other, |
| 1473 | } |
| 1474 | } |
| 1475 | |
| 1476 | /// Root digest of `target`. A changeset tree is its parents' tree (or its base tree) with |
| 1477 | /// its mutations applied; `force` rebuilds it and every ancestor instead of trusting memos. |
| 1478 | fn tree_root( |
| 1479 | &mut self, |
| 1480 | target: TreeTarget, |
| 1481 | snapshot_seq: Option<WalSeq>, |
| 1482 | force: bool, |
| 1483 | ) -> SynapseResult<TreeDigest> { |
| 1484 | let cs_id = match target { |
| 1485 | TreeTarget::BaseGitCommit(oid) => { |
| 1486 | return self.base_roots.get(&oid).copied().ok_or_else(|| { |
| 1487 | SynapseError::new( |
| 1488 | RefusalCode::BaseTreeNotFound, |
| 1489 | format!("base_git_oid {oid} not found"), |
| 1490 | ) |
| 1491 | }) |
| 1492 | } |
| 1493 | TreeTarget::Changeset(cs_id) => cs_id, |
| 1494 | }; |
| 1495 | // Visibility at `snapshot_seq` is checked on every lookup, memoized or not. |
| 1496 | let stored = self |
| 1497 | .store |
| 1498 | .get_changeset_in_repo(&self.repo_id, cs_id, None, snapshot_seq)?; |
| 1499 | if !force { |
| 1500 | if let Some(root) = self.trees.memo_root(cs_id) { |
| 1501 | return Ok(root); |
| 1502 | } |
| 1503 | } |
| 1504 | self.trees.count_root_build(); |
| 1505 | let base = self.changeset_base_root(&stored.envelope, snapshot_seq, force)?; |
| 1506 | let mut edit = TreeEdit::new(&mut self.trees, base)?; |
| 1507 | for m in &stored.envelope.mutations { |
| 1508 | match &m.op { |
| 1509 | MutationOp::Upsert { |
| 1510 | mode, |
| 1511 | blob_digest, |
| 1512 | size_bytes, |
| 1513 | } => { |
| 1514 | let raw = self.read_blob_bytes(*blob_digest, snapshot_seq)?; |
| 1515 | let file = TreeFile { |
| 1516 | mode: *mode, |
| 1517 | blob_digest: *blob_digest, |
| 1518 | size_bytes: *size_bytes, |
| 1519 | git_blob_oid: GitOid::compute_blob(&raw), |
| 1520 | }; |
| 1521 | edit.upsert(&mut self.trees, &m.path, file)?; |
| 1522 | } |
| 1523 | MutationOp::Delete => edit.delete(&mut self.trees, &m.path)?, |
| 1524 | } |
| 1525 | } |
| 1526 | let root = edit.finish(&mut self.trees)?; |
| 1527 | self.trees.remember_root(cs_id, root); |
| 1528 | Ok(root) |
| 1529 | } |
| 1530 | |
| 1531 | /// The tree a changeset was built on: its base tree when it has no parents, else its parent |
| 1532 | /// trees overlaid in order (later parents win, including at a file and directory collision, |
| 1533 | /// the same rule as an upsert). |
| 1534 | pub(crate) fn changeset_base_root( |
| 1535 | &mut self, |
| 1536 | envelope: &ChangesetEnvelope, |
| 1537 | snapshot_seq: Option<WalSeq>, |
| 1538 | force: bool, |
| 1539 | ) -> SynapseResult<TreeDigest> { |
| 1540 | let Some((&first, rest)) = envelope.parent_changesets.split_first() else { |
| 1541 | return self.tree_root( |
| 1542 | TreeTarget::BaseGitCommit(envelope.base_git_oid), |
| 1543 | snapshot_seq, |
| 1544 | force, |
| 1545 | ); |
| 1546 | }; |
| 1547 | let first_root = self.tree_root(TreeTarget::Changeset(first), snapshot_seq, force)?; |
| 1548 | if rest.is_empty() { |
| 1549 | return Ok(first_root); |
| 1550 | } |
| 1551 | let mut roots = Vec::with_capacity(rest.len()); |
| 1552 | for &parent in rest { |
| 1553 | roots.push(self.tree_root(TreeTarget::Changeset(parent), snapshot_seq, force)?); |
| 1554 | } |
| 1555 | let mut edit = TreeEdit::new(&mut self.trees, first_root)?; |
| 1556 | for root in roots { |
| 1557 | edit.overlay(&mut self.trees, root)?; |
| 1558 | } |
| 1559 | edit.finish(&mut self.trees) |
| 1560 | } |
| 1561 | |
| 1562 | /// Flat file list of the tree a changeset was built on (see `changeset_base_root`). |
| 1563 | pub(crate) fn changeset_base_files( |
| 1564 | &mut self, |
| 1565 | envelope: &ChangesetEnvelope, |
| 1566 | snapshot_seq: Option<WalSeq>, |
| 1567 | ) -> SynapseResult<BTreeMap<String, VirtualTreeEntry>> { |
| 1568 | let attempt = |svc: &mut Self, force: bool| { |
| 1569 | let root = svc.changeset_base_root(envelope, snapshot_seq, force)?; |
| 1570 | svc.trees.files(root) |
| 1571 | }; |
| 1572 | let files = match attempt(self, false) { |
| 1573 | Err(e) if e.code == RefusalCode::TreeNodeNotFound => { |
| 1574 | attempt(self, true).map_err(cache_bound_too_small)? |
| 1575 | } |
| 1576 | other => other?, |
| 1577 | }; |
| 1578 | Ok(files |
| 1579 | .into_iter() |
| 1580 | .map(|(path, f)| (path.clone(), virtual_tree_entry(path, &f))) |
| 1581 | .collect()) |
| 1582 | } |
| 1583 | |
| 1584 | /// Read raw blob bytes from either the committed `SynapseStore` or imported base blobs. |
| 1585 | pub fn read_blob_bytes( |
| 1586 | &self, |
| 1587 | digest: BlobDigest, |
| 1588 | snapshot_seq: Option<WalSeq>, |
| 1589 | ) -> SynapseResult<Vec<u8>> { |
| 1590 | if let Ok(bytes) = self.store.get_blob_visible(digest, None, snapshot_seq) { |
| 1591 | return Ok(bytes); |
| 1592 | } |
| 1593 | if let Some(bytes) = self.base_blobs.get(&digest) { |
| 1594 | return Ok(bytes.clone()); |
| 1595 | } |
| 1596 | Err(SynapseError::new( |
| 1597 | RefusalCode::BlobNotFound, |
| 1598 | format!("blob {digest} not found in store or base tree"), |
| 1599 | )) |
| 1600 | } |
| 1601 | |
| 1602 | pub fn root_dir(&self) -> &Path { |
| 1603 | &self.root_dir |
| 1604 | } |
| 1605 | |
| 1606 | pub fn repo_id(&self) -> &RepoId { |
| 1607 | &self.repo_id |
| 1608 | } |
| 1609 | |
| 1610 | /// Authorize an export/publication request (`Capability::Publish` at `BoundaryKind::Export`) |
| 1611 | /// against this service's repository authority and policy enforcer. |
| 1612 | pub fn authorize_export<T: Serialize>( |
| 1613 | &mut self, |
| 1614 | operation: &str, |
| 1615 | req: &AuthenticatedRequest<T>, |
| 1616 | now_ms: u64, |
| 1617 | ) -> SynapseResult<()> { |
| 1618 | self.auth.authorize( |
| 1619 | BoundaryKind::Export, |
| 1620 | operation, |
| 1621 | &self.repo_id, |
| 1622 | Capability::Publish, |
| 1623 | req, |
| 1624 | now_ms, |
| 1625 | ) |
| 1626 | } |
| 1627 | |
| 1628 | fn validate_page_request(&self, page: &PageRequest) -> SynapseResult<WalSeq> { |
| 1629 | if page.limit == 0 || page.limit > self.max_page_size { |
| 1630 | return Err(SynapseError::new( |
| 1631 | RefusalCode::PaginationLimitExceeded, |
| 1632 | format!( |
| 1633 | "page limit {} must be in 1..={}", |
| 1634 | page.limit, self.max_page_size |
| 1635 | ), |
| 1636 | )); |
| 1637 | } |
| 1638 | let committed = self.store.committed_seq(); |
| 1639 | if let Some(min_seq) = page.min_visible_seq { |
| 1640 | if min_seq > committed { |
| 1641 | return Err(SynapseError::new( |
| 1642 | RefusalCode::VisibilitySeqAhead, |
| 1643 | format!("min_visible_seq {min_seq} exceeds committed {committed}"), |
| 1644 | )); |
| 1645 | } |
| 1646 | } |
| 1647 | if let Some(snap) = page.snapshot_seq { |
| 1648 | if snap > committed { |
| 1649 | return Err(SynapseError::new( |
| 1650 | RefusalCode::VisibilitySeqAhead, |
| 1651 | format!("snapshot_seq {snap} exceeds committed {committed}"), |
| 1652 | )); |
| 1653 | } |
| 1654 | Ok(snap) |
| 1655 | } else { |
| 1656 | Ok(committed) |
| 1657 | } |
| 1658 | } |
| 1659 | } |
| 1660 | |
| 1661 | /// Parse an `offset:N` pagination cursor (absent cursor: offset 0). |
| 1662 | fn parse_offset_cursor(page: &PageRequest) -> SynapseResult<u64> { |
| 1663 | let Some(cur) = page.cursor.as_ref() else { |
| 1664 | return Ok(0); |
| 1665 | }; |
| 1666 | let stripped = cur.strip_prefix("offset:").ok_or_else(|| { |
| 1667 | SynapseError::new( |
| 1668 | RefusalCode::CursorInvalid, |
| 1669 | format!("invalid pagination cursor: {cur}"), |
| 1670 | ) |
| 1671 | })?; |
| 1672 | stripped.parse().map_err(|_| { |
| 1673 | SynapseError::new( |
| 1674 | RefusalCode::CursorInvalid, |
| 1675 | format!("non-numeric pagination cursor: {cur}"), |
| 1676 | ) |
| 1677 | }) |
| 1678 | } |
| 1679 | |
| 1680 | fn paginate_slice<T: Clone>( |
| 1681 | all: &[T], |
| 1682 | page: &PageRequest, |
| 1683 | snapshot_seq: WalSeq, |
| 1684 | ) -> SynapseResult<PageResponse<T>> { |
| 1685 | let start_idx = parse_offset_cursor(page)? as usize; |
| 1686 | if start_idx > all.len() { |
| 1687 | return Err(SynapseError::new( |
| 1688 | RefusalCode::CursorInvalid, |
| 1689 | format!( |
| 1690 | "cursor offset {start_idx} out of bounds for {} items", |
| 1691 | all.len() |
| 1692 | ), |
| 1693 | )); |
| 1694 | } |
| 1695 | |
| 1696 | let end_idx = (start_idx + page.limit).min(all.len()); |
| 1697 | let items = all[start_idx..end_idx].to_vec(); |
| 1698 | let next_cursor = if end_idx < all.len() { |
| 1699 | Some(format!("offset:{end_idx}")) |
| 1700 | } else { |
| 1701 | None |
| 1702 | }; |
| 1703 | |
| 1704 | Ok(PageResponse { |
| 1705 | items, |
| 1706 | next_cursor, |
| 1707 | snapshot_seq, |
| 1708 | total_matching: all.len(), |
| 1709 | }) |
| 1710 | } |
| 1711 | |
| 1712 | fn virtual_tree_entry(path: String, f: &TreeFile) -> VirtualTreeEntry { |
| 1713 | VirtualTreeEntry { |
| 1714 | path, |
| 1715 | mode: f.mode, |
| 1716 | blob_digest: f.blob_digest, |
| 1717 | git_blob_oid: f.git_blob_oid, |
| 1718 | size_bytes: f.size_bytes, |
| 1719 | } |
| 1720 | } |
| 1721 | |
| 1722 | /// Convert a tree diff entry into the API's `DiffEntry`, classifying it as Git does: a change |
| 1723 | /// between a symlink and a regular or executable file is a type change (`T`). |
| 1724 | fn diff_entry(d: TreeDiffEntry) -> DiffEntry { |
| 1725 | let status = match (&d.old, &d.new) { |
| 1726 | (None, _) => DiffStatus::Added, |
| 1727 | (_, None) => DiffStatus::Deleted, |
| 1728 | (Some(o), Some(n)) => { |
| 1729 | let link = |m: FileMode| m == FileMode::Symlink120000; |
| 1730 | if link(o.mode) != link(n.mode) { |
| 1731 | DiffStatus::TypeChanged |
| 1732 | } else { |
| 1733 | DiffStatus::Modified |
| 1734 | } |
| 1735 | } |
| 1736 | }; |
| 1737 | DiffEntry { |
| 1738 | old_entry: d.old.map(|f| virtual_tree_entry(d.path.clone(), &f)), |
| 1739 | new_entry: d.new.map(|f| virtual_tree_entry(d.path.clone(), &f)), |
| 1740 | path: d.path, |
| 1741 | status, |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | /// A tree that cannot be walked even right after a rebuild: the bound cannot hold one tree. |
| 1746 | fn cache_bound_too_small(e: SynapseError) -> SynapseError { |
| 1747 | if e.code == RefusalCode::TreeNodeNotFound { |
| 1748 | SynapseError::new( |
| 1749 | RefusalCode::BackpressureOverCapacity, |
| 1750 | format!("tree cache bound too small to hold one tree: {}", e.message), |
| 1751 | ) |
| 1752 | } else { |
| 1753 | e |
| 1754 | } |
| 1755 | } |
| 1756 | |
| 1757 | /// Copy every node reachable from `root` from one store into another. |
| 1758 | fn copy_tree(from: &mut TreeStore, to: &mut TreeStore, root: TreeDigest) -> SynapseResult<()> { |
| 1759 | let node = from.get(root)?; |
| 1760 | for e in node.entries() { |
| 1761 | if let TreeEntryKind::Dir { digest, .. } = e.kind { |
| 1762 | copy_tree(from, to, digest)?; |
| 1763 | } |
| 1764 | } |
| 1765 | to.insert(TreeNode::new(node.entries().to_vec())?); |
| 1766 | Ok(()) |
| 1767 | } |
| 1768 | |
| 1769 | fn is_file_dir_prefix_collision(a: &str, b: &str) -> bool { |
| 1770 | if a == b { |
| 1771 | return false; |
| 1772 | } |
| 1773 | if let Some(rest) = a.strip_prefix(b) { |
| 1774 | return rest.starts_with('/'); |
| 1775 | } |
| 1776 | if let Some(rest) = b.strip_prefix(a) { |
| 1777 | return rest.starts_with('/'); |
| 1778 | } |
| 1779 | false |
| 1780 | } |
| 1781 | |
| 1782 | fn validate_subscriber_id(id: &str) -> SynapseResult<()> { |
| 1783 | if id.is_empty() |
| 1784 | || id.len() > 64 |
| 1785 | || !id |
| 1786 | .bytes() |
| 1787 | .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')) |
| 1788 | { |
| 1789 | return Err(SynapseError::new( |
| 1790 | RefusalCode::CursorInvalid, |
| 1791 | format!("invalid subscriber_id: {id}"), |
| 1792 | )); |
| 1793 | } |
| 1794 | Ok(()) |
| 1795 | } |
| 1796 | |
| 1797 | /// The request must name `change_id` as the change it joins, so F1 checks it against the |
| 1798 | /// chain's change scope. |
| 1799 | fn check_join_scope(req: &ChainedRequest, change_id: ChangeId) -> SynapseResult<()> { |
| 1800 | if req.scope.join_change != Some(change_id) { |
| 1801 | return Err(SynapseError::new( |
| 1802 | RefusalCode::AuthChangeOutOfScope, |
| 1803 | format!("request scope must name change {change_id} as join_change"), |
| 1804 | )); |
| 1805 | } |
| 1806 | Ok(()) |
| 1807 | } |
| 1808 | |
| 1809 | /// The store-side authority of a verified chain: its link digests, and the `ChangeId`s its |
| 1810 | /// leaf grant names explicitly (a grant for any change names none). |
| 1811 | fn admission_authority(req: &ChainedRequest) -> SynapseResult<AdmissionAuthority> { |
| 1812 | let chain = ChainPath::new(req.chain.link_digests().iter().map(|d| d.0).collect())?; |
| 1813 | let change_scope = req |
| 1814 | .chain |
| 1815 | .leaf() |
| 1816 | .and_then(|l| l.caveats.changes.ids()) |
| 1817 | .map(<[ChangeId]>::to_vec) |
| 1818 | .unwrap_or_default(); |
| 1819 | Ok(AdmissionAuthority { |
| 1820 | chain, |
| 1821 | change_scope, |
| 1822 | }) |
| 1823 | } |
| 1824 | |
| 1825 | #[cfg(test)] |
| 1826 | mod tests { |
| 1827 | use super::*; |
| 1828 | use ed25519_dalek::SigningKey; |
| 1829 | use synapse_auth::AgentCapabilityGrant; |
| 1830 | use synapse_core::{encode_did_key_ed25519, PathMutation, SYNAPSE_ENVELOPE_VERSION}; |
| 1831 | |
| 1832 | fn temp_dir(label: &str) -> PathBuf { |
| 1833 | let dir = std::env::temp_dir().join(format!( |
| 1834 | "synapse-api-test-{}-{}-{}", |
| 1835 | label, |
| 1836 | std::process::id(), |
| 1837 | std::time::SystemTime::now() |
| 1838 | .duration_since(std::time::UNIX_EPOCH) |
| 1839 | .unwrap() |
| 1840 | .as_nanos() |
| 1841 | )); |
| 1842 | let _ = fs::remove_dir_all(&dir); |
| 1843 | fs::create_dir_all(&dir).unwrap(); |
| 1844 | dir |
| 1845 | } |
| 1846 | #[test] |
| 1847 | fn repository_grant_cannot_read_foreign_changesets_in_mixed_store() { |
| 1848 | let dir = temp_dir("mixed-repositories"); |
| 1849 | let a = RepoId::new("example/repo-a").unwrap(); |
| 1850 | let b = RepoId::new("example/repo-b").unwrap(); |
| 1851 | let mut svc = SynapseService::open( |
| 1852 | &dir, |
| 1853 | a.clone(), |
| 1854 | FsyncPolicy::EveryCommit, |
| 1855 | RecoveryPolicy::StrictFailClosed, |
| 1856 | StoreLimits::default(), |
| 1857 | ) |
| 1858 | .unwrap(); |
| 1859 | let authority = SigningKey::from_bytes(&[11; 32]); |
| 1860 | let agent = SigningKey::from_bytes(&[12; 32]); |
| 1861 | svc.register_authority(encode_did_key_ed25519( |
| 1862 | &authority.verifying_key().to_bytes(), |
| 1863 | )); |
| 1864 | let grant = AgentCapabilityGrant::issue( |
| 1865 | &authority, |
| 1866 | [1; 32], |
| 1867 | a.clone(), |
| 1868 | encode_did_key_ed25519(&agent.verifying_key().to_bytes()), |
| 1869 | vec![Capability::Read], |
| 1870 | 1_000_000, |
| 1871 | 100, |
| 1872 | 60_000, |
| 1873 | 0, |
| 1874 | 100_000, |
| 1875 | ); |
| 1876 | let base = GitOid([7; 20]); |
| 1877 | svc.register_base_tree(base, vec![]).unwrap(); |
| 1878 | let make = |repo_id: RepoId, tag: u8, parents: Vec<ChangesetId>| { |
| 1879 | let mut env = ChangesetEnvelope { |
| 1880 | version: SYNAPSE_ENVELOPE_VERSION, |
| 1881 | repo_id, |
| 1882 | base_git_oid: base, |
| 1883 | parent_changesets: parents, |
| 1884 | author_did: String::new(), |
| 1885 | idempotency_key: IdempotencyKey([tag; 32]), |
| 1886 | created_at_ms: 1_000, |
| 1887 | intent_summary: "security test".into(), |
| 1888 | mutations: vec![PathMutation { |
| 1889 | path: "private.txt".into(), |
| 1890 | op: MutationOp::Delete, |
| 1891 | }], |
| 1892 | evidence_receipts: vec![], |
| 1893 | signature: vec![], |
| 1894 | }; |
| 1895 | env.sign(&agent); |
| 1896 | env |
| 1897 | }; |
| 1898 | let own = match svc |
| 1899 | .store_mut() |
| 1900 | .ingest_changeset(make(a.clone(), 1, vec![]), &[]) |
| 1901 | .unwrap() |
| 1902 | { |
| 1903 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 1904 | _ => unreachable!(), |
| 1905 | }; |
| 1906 | let foreign = match svc |
| 1907 | .store_mut() |
| 1908 | .ingest_changeset(make(b, 2, vec![]), &[]) |
| 1909 | .unwrap() |
| 1910 | { |
| 1911 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 1912 | _ => unreachable!(), |
| 1913 | }; |
| 1914 | let foreign_child = match svc |
| 1915 | .store_mut() |
| 1916 | .ingest_changeset( |
| 1917 | make(RepoId::new("example/repo-b").unwrap(), 3, vec![foreign]), |
| 1918 | &[], |
| 1919 | ) |
| 1920 | .unwrap() |
| 1921 | { |
| 1922 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 1923 | _ => unreachable!(), |
| 1924 | }; |
| 1925 | let mut nonce = 0u8; |
| 1926 | macro_rules! request { |
| 1927 | ($payload:expr) => {{ |
| 1928 | nonce += 1; |
| 1929 | AuthenticatedRequest::sign_new( |
| 1930 | &agent, |
| 1931 | grant.clone(), |
| 1932 | a.clone(), |
| 1933 | Capability::Read, |
| 1934 | [nonce; 32], |
| 1935 | 2_000, |
| 1936 | 0, |
| 1937 | $payload, |
| 1938 | ) |
| 1939 | .unwrap() |
| 1940 | }}; |
| 1941 | } |
| 1942 | assert_eq!( |
| 1943 | svc.get(&request!((own, None, None)), 2_000) |
| 1944 | .unwrap() |
| 1945 | .changeset_id, |
| 1946 | own |
| 1947 | ); |
| 1948 | assert_eq!( |
| 1949 | svc.get(&request!((foreign, None, None)), 2_000) |
| 1950 | .unwrap_err() |
| 1951 | .code, |
| 1952 | RefusalCode::ChangesetNotFound |
| 1953 | ); |
| 1954 | assert_eq!( |
| 1955 | svc.get(&request!((ChangesetId([0xFF; 32]), None, None)), 2_000) |
| 1956 | .unwrap_err() |
| 1957 | .code, |
| 1958 | RefusalCode::ChangesetNotFound |
| 1959 | ); |
| 1960 | assert_eq!( |
| 1961 | svc.provenance(&request!((foreign, None)), 2_000) |
| 1962 | .unwrap_err() |
| 1963 | .code, |
| 1964 | RefusalCode::ChangesetNotFound |
| 1965 | ); |
| 1966 | assert_eq!( |
| 1967 | svc.tree( |
| 1968 | &request!(TreeQueryPayload { |
| 1969 | target: TreeTarget::Changeset(foreign), |
| 1970 | path_prefix: None, |
| 1971 | page: PageRequest::default(), |
| 1972 | }), |
| 1973 | 2_000 |
| 1974 | ) |
| 1975 | .unwrap_err() |
| 1976 | .code, |
| 1977 | RefusalCode::ChangesetNotFound |
| 1978 | ); |
| 1979 | assert_eq!( |
| 1980 | svc.tree( |
| 1981 | &request!(TreeQueryPayload { |
| 1982 | target: TreeTarget::Changeset(foreign_child), |
| 1983 | path_prefix: None, |
| 1984 | page: PageRequest::default(), |
| 1985 | }), |
| 1986 | 2_000 |
| 1987 | ) |
| 1988 | .unwrap_err() |
| 1989 | .code, |
| 1990 | RefusalCode::ChangesetNotFound |
| 1991 | ); |
| 1992 | assert_eq!( |
| 1993 | svc.evidence_base( |
| 1994 | &request!(EvidenceBaseQueryPayload { |
| 1995 | changeset_id: foreign, |
| 1996 | snapshot_seq: None, |
| 1997 | }), |
| 1998 | 2_000 |
| 1999 | ) |
| 2000 | .unwrap_err() |
| 2001 | .code, |
| 2002 | RefusalCode::ChangesetNotFound |
| 2003 | ); |
| 2004 | assert_eq!( |
| 2005 | svc.changeset_advisory( |
| 2006 | &request!(ChangesetAdvisoryPayload { |
| 2007 | base: TreeTarget::BaseGitCommit(base), |
| 2008 | latest: Some(TreeTarget::Changeset(foreign)), |
| 2009 | paths: vec!["private.txt".into()], |
| 2010 | agent: "reader".into(), |
| 2011 | snapshot_seq: None, |
| 2012 | }), |
| 2013 | None, |
| 2014 | 2_000 |
| 2015 | ) |
| 2016 | .unwrap_err() |
| 2017 | .code, |
| 2018 | RefusalCode::ChangesetNotFound |
| 2019 | ); |
| 2020 | assert_eq!( |
| 2021 | svc.history( |
| 2022 | &request!(HistoryQueryPayload { |
| 2023 | ancestor_of: Some(foreign), |
| 2024 | path_filter: None, |
| 2025 | page: PageRequest::default(), |
| 2026 | }), |
| 2027 | 2_000 |
| 2028 | ) |
| 2029 | .unwrap_err() |
| 2030 | .code, |
| 2031 | RefusalCode::ChangesetNotFound |
| 2032 | ); |
| 2033 | assert_eq!( |
| 2034 | svc.history( |
| 2035 | &request!(HistoryQueryPayload { |
| 2036 | ancestor_of: Some(foreign_child), |
| 2037 | path_filter: None, |
| 2038 | page: PageRequest::default(), |
| 2039 | }), |
| 2040 | 2_000 |
| 2041 | ) |
| 2042 | .unwrap_err() |
| 2043 | .code, |
| 2044 | RefusalCode::ChangesetNotFound |
| 2045 | ); |
| 2046 | for (candidate, against) in [(foreign, vec![own]), (own, vec![foreign])] { |
| 2047 | assert_eq!( |
| 2048 | svc.conflicts( |
| 2049 | &request!(ConflictQueryPayload { |
| 2050 | candidate, |
| 2051 | against: Some(against), |
| 2052 | page: PageRequest::default(), |
| 2053 | }), |
| 2054 | 2_000 |
| 2055 | ) |
| 2056 | .unwrap_err() |
| 2057 | .code, |
| 2058 | RefusalCode::ChangesetNotFound |
| 2059 | ); |
| 2060 | } |
| 2061 | assert!(svc.provenance(&request!((own, None)), 2_000).is_ok()); |
| 2062 | let _ = fs::remove_dir_all(dir); |
| 2063 | } |
| 2064 | |
| 2065 | #[test] |
| 2066 | fn test_virtual_tree_and_diff_parity_against_git_cli() { |
| 2067 | let work = temp_dir("git-parity"); |
| 2068 | let git_dir = work.join("git-repo"); |
| 2069 | let store_dir = work.join("synapse-service"); |
| 2070 | fs::create_dir_all(&git_dir).unwrap(); |
| 2071 | |
| 2072 | // 1. Initialize a real Git repository and create base commit with multiple files |
| 2073 | Command::new("git") |
| 2074 | .arg("init") |
| 2075 | .current_dir(&git_dir) |
| 2076 | .output() |
| 2077 | .unwrap(); |
| 2078 | Command::new("git") |
| 2079 | .args(["config", "user.name", "Synapse Test"]) |
| 2080 | .current_dir(&git_dir) |
| 2081 | .output() |
| 2082 | .unwrap(); |
| 2083 | Command::new("git") |
| 2084 | .args(["config", "user.email", "synapse@aienos.com"]) |
| 2085 | .current_dir(&git_dir) |
| 2086 | .output() |
| 2087 | .unwrap(); |
| 2088 | |
| 2089 | fs::create_dir_all(git_dir.join("src/net")).unwrap(); |
| 2090 | fs::write(git_dir.join("README.md"), b"# Base Repo\n").unwrap(); |
| 2091 | fs::write(git_dir.join("src/lib.rs"), b"pub mod net;\n").unwrap(); |
| 2092 | fs::write(git_dir.join("src/net/http.rs"), b"pub fn serve() {}\n").unwrap(); |
| 2093 | |
| 2094 | Command::new("git") |
| 2095 | .args(["add", "."]) |
| 2096 | .current_dir(&git_dir) |
| 2097 | .output() |
| 2098 | .unwrap(); |
| 2099 | Command::new("git") |
| 2100 | .args(["commit", "-m", "base commit"]) |
| 2101 | .current_dir(&git_dir) |
| 2102 | .output() |
| 2103 | .unwrap(); |
| 2104 | |
| 2105 | // 2. Open SynapseService and import base tree from the real Git repository |
| 2106 | let repo_id = RepoId::new("aien-spark/synapse").unwrap(); |
| 2107 | let mut svc = SynapseService::open( |
| 2108 | &store_dir, |
| 2109 | repo_id.clone(), |
| 2110 | FsyncPolicy::EveryCommit, |
| 2111 | RecoveryPolicy::StrictFailClosed, |
| 2112 | StoreLimits::default(), |
| 2113 | ) |
| 2114 | .unwrap(); |
| 2115 | |
| 2116 | let auth_key = SigningKey::from_bytes(&[10u8; 32]); |
| 2117 | let auth_did = encode_did_key_ed25519(&auth_key.verifying_key().to_bytes()); |
| 2118 | svc.register_authority(auth_did); |
| 2119 | |
| 2120 | let agent_key = SigningKey::from_bytes(&[20u8; 32]); |
| 2121 | let agent_did = encode_did_key_ed25519(&agent_key.verifying_key().to_bytes()); |
| 2122 | let grant = AgentCapabilityGrant::issue( |
| 2123 | &auth_key, |
| 2124 | [1u8; 32], |
| 2125 | repo_id.clone(), |
| 2126 | agent_did, |
| 2127 | vec![Capability::Read, Capability::Propose], |
| 2128 | 1024 * 1024, |
| 2129 | 100, |
| 2130 | 60_000, |
| 2131 | 100, |
| 2132 | 100_000, |
| 2133 | ); |
| 2134 | |
| 2135 | let base_oid = svc |
| 2136 | .import_base_tree_from_git_repo(&git_dir, "HEAD") |
| 2137 | .unwrap(); |
| 2138 | |
| 2139 | // 3. Submit Changeset 1 (modify src/lib.rs, add src/store.rs) and stacked Changeset 2 (delete src/net/http.rs, add scripts/run.sh) |
| 2140 | let lib_v2 = b"pub mod net;\npub mod store;\n"; |
| 2141 | let store_v1 = b"pub struct Wal;\n"; |
| 2142 | let lib_digest = BlobDigest::compute(lib_v2); |
| 2143 | let store_digest = BlobDigest::compute(store_v1); |
| 2144 | |
| 2145 | let mut env1 = ChangesetEnvelope { |
| 2146 | version: SYNAPSE_ENVELOPE_VERSION, |
| 2147 | repo_id: repo_id.clone(), |
| 2148 | base_git_oid: base_oid, |
| 2149 | parent_changesets: vec![], |
| 2150 | author_did: String::new(), |
| 2151 | idempotency_key: IdempotencyKey::from_label("cs1"), |
| 2152 | created_at_ms: 1_000, |
| 2153 | intent_summary: "Add store module".to_string(), |
| 2154 | mutations: vec![ |
| 2155 | PathMutation { |
| 2156 | path: "src/lib.rs".to_string(), |
| 2157 | op: MutationOp::Upsert { |
| 2158 | mode: FileMode::Regular644, |
| 2159 | blob_digest: lib_digest, |
| 2160 | size_bytes: lib_v2.len() as u64, |
| 2161 | }, |
| 2162 | }, |
| 2163 | PathMutation { |
| 2164 | path: "src/store.rs".to_string(), |
| 2165 | op: MutationOp::Upsert { |
| 2166 | mode: FileMode::Regular644, |
| 2167 | blob_digest: store_digest, |
| 2168 | size_bytes: store_v1.len() as u64, |
| 2169 | }, |
| 2170 | }, |
| 2171 | ], |
| 2172 | evidence_receipts: vec![], |
| 2173 | signature: vec![], |
| 2174 | }; |
| 2175 | env1.sign(&agent_key); |
| 2176 | |
| 2177 | let sub1 = AuthenticatedRequest::sign_new( |
| 2178 | &agent_key, |
| 2179 | grant.clone(), |
| 2180 | repo_id.clone(), |
| 2181 | Capability::Propose, |
| 2182 | [10u8; 32], |
| 2183 | 1_000, |
| 2184 | 0, |
| 2185 | SubmitChangesetPayload { |
| 2186 | envelope: env1, |
| 2187 | blobs: vec![ |
| 2188 | (lib_digest, lib_v2.to_vec()), |
| 2189 | (store_digest, store_v1.to_vec()), |
| 2190 | ], |
| 2191 | }, |
| 2192 | ) |
| 2193 | .unwrap(); |
| 2194 | let cs1_id = match svc.submit(&sub1, 1_000).unwrap() { |
| 2195 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 2196 | _ => unreachable!(), |
| 2197 | }; |
| 2198 | |
| 2199 | let run_sh = b"#!/usr/bin/env bash\necho ok\n"; |
| 2200 | let run_digest = BlobDigest::compute(run_sh); |
| 2201 | let mut env2 = ChangesetEnvelope { |
| 2202 | version: SYNAPSE_ENVELOPE_VERSION, |
| 2203 | repo_id: repo_id.clone(), |
| 2204 | base_git_oid: base_oid, |
| 2205 | parent_changesets: vec![cs1_id], |
| 2206 | author_did: String::new(), |
| 2207 | idempotency_key: IdempotencyKey::from_label("cs2"), |
| 2208 | created_at_ms: 2_000, |
| 2209 | intent_summary: "Remove http.rs and add run.sh".to_string(), |
| 2210 | mutations: vec![ |
| 2211 | PathMutation { |
| 2212 | path: "scripts/run.sh".to_string(), |
| 2213 | op: MutationOp::Upsert { |
| 2214 | mode: FileMode::Executable755, |
| 2215 | blob_digest: run_digest, |
| 2216 | size_bytes: run_sh.len() as u64, |
| 2217 | }, |
| 2218 | }, |
| 2219 | PathMutation { |
| 2220 | path: "src/net/http.rs".to_string(), |
| 2221 | op: MutationOp::Delete, |
| 2222 | }, |
| 2223 | ], |
| 2224 | evidence_receipts: vec![], |
| 2225 | signature: vec![], |
| 2226 | }; |
| 2227 | env2.sign(&agent_key); |
| 2228 | |
| 2229 | let sub2 = AuthenticatedRequest::sign_new( |
| 2230 | &agent_key, |
| 2231 | grant.clone(), |
| 2232 | repo_id.clone(), |
| 2233 | Capability::Propose, |
| 2234 | [11u8; 32], |
| 2235 | 2_000, |
| 2236 | 0, |
| 2237 | SubmitChangesetPayload { |
| 2238 | envelope: env2, |
| 2239 | blobs: vec![(run_digest, run_sh.to_vec())], |
| 2240 | }, |
| 2241 | ) |
| 2242 | .unwrap(); |
| 2243 | let cs2_id = match svc.submit(&sub2, 2_000).unwrap() { |
| 2244 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 2245 | _ => unreachable!(), |
| 2246 | }; |
| 2247 | |
| 2248 | // 4. Perform the exact same changes in Git to compare against Git's own ls-tree and diff! |
| 2249 | fs::write(git_dir.join("src/lib.rs"), lib_v2).unwrap(); |
| 2250 | fs::write(git_dir.join("src/store.rs"), store_v1).unwrap(); |
| 2251 | fs::remove_file(git_dir.join("src/net/http.rs")).unwrap(); |
| 2252 | fs::create_dir_all(git_dir.join("scripts")).unwrap(); |
| 2253 | fs::write(git_dir.join("scripts/run.sh"), run_sh).unwrap(); |
| 2254 | #[cfg(unix)] |
| 2255 | { |
| 2256 | use std::os::unix::fs::PermissionsExt; |
| 2257 | fs::set_permissions( |
| 2258 | git_dir.join("scripts/run.sh"), |
| 2259 | fs::Permissions::from_mode(0o755), |
| 2260 | ) |
| 2261 | .unwrap(); |
| 2262 | } |
| 2263 | Command::new("git") |
| 2264 | .args(["add", "-A"]) |
| 2265 | .current_dir(&git_dir) |
| 2266 | .output() |
| 2267 | .unwrap(); |
| 2268 | Command::new("git") |
| 2269 | .args(["commit", "-m", "target commit"]) |
| 2270 | .current_dir(&git_dir) |
| 2271 | .output() |
| 2272 | .unwrap(); |
| 2273 | |
| 2274 | // Compare `SynapseService::tree(cs2_id)` against `git ls-tree -r HEAD` |
| 2275 | let tree_req = AuthenticatedRequest::sign_new( |
| 2276 | &agent_key, |
| 2277 | grant.clone(), |
| 2278 | repo_id.clone(), |
| 2279 | Capability::Read, |
| 2280 | [12u8; 32], |
| 2281 | 2_100, |
| 2282 | 0, |
| 2283 | TreeQueryPayload { |
| 2284 | target: TreeTarget::Changeset(cs2_id), |
| 2285 | path_prefix: None, |
| 2286 | page: PageRequest { |
| 2287 | cursor: None, |
| 2288 | limit: 2, // Exercise pagination across 4 files! |
| 2289 | min_visible_seq: Some(WalSeq(2)), |
| 2290 | snapshot_seq: None, |
| 2291 | }, |
| 2292 | }, |
| 2293 | ) |
| 2294 | .unwrap(); |
| 2295 | let page1 = svc.tree(&tree_req, 2_100).unwrap(); |
| 2296 | assert_eq!(page1.items.len(), 2); |
| 2297 | assert_eq!(page1.total_matching, 4); |
| 2298 | assert!(page1.next_cursor.is_some()); |
| 2299 | |
| 2300 | let tree_req2 = AuthenticatedRequest::sign_new( |
| 2301 | &agent_key, |
| 2302 | grant.clone(), |
| 2303 | repo_id.clone(), |
| 2304 | Capability::Read, |
| 2305 | [13u8; 32], |
| 2306 | 2_101, |
| 2307 | 0, |
| 2308 | TreeQueryPayload { |
| 2309 | target: TreeTarget::Changeset(cs2_id), |
| 2310 | path_prefix: None, |
| 2311 | page: PageRequest { |
| 2312 | cursor: page1.next_cursor, |
| 2313 | limit: 2, |
| 2314 | min_visible_seq: Some(WalSeq(2)), |
| 2315 | snapshot_seq: None, |
| 2316 | }, |
| 2317 | }, |
| 2318 | ) |
| 2319 | .unwrap(); |
| 2320 | let page2 = svc.tree(&tree_req2, 2_101).unwrap(); |
| 2321 | assert_eq!(page2.items.len(), 2); |
| 2322 | assert!(page2.next_cursor.is_none()); |
| 2323 | |
| 2324 | let mut synapse_ls_tree = String::new(); |
| 2325 | for entry in page1.items.iter().chain(page2.items.iter()) { |
| 2326 | synapse_ls_tree.push_str(&format!( |
| 2327 | "{} blob {}\t{}\n", |
| 2328 | entry.mode.git_octal_str(), |
| 2329 | entry.git_blob_oid.to_hex(), |
| 2330 | entry.path |
| 2331 | )); |
| 2332 | } |
| 2333 | |
| 2334 | let git_ls_out = Command::new("git") |
| 2335 | .args(["ls-tree", "-r", "HEAD"]) |
| 2336 | .current_dir(&git_dir) |
| 2337 | .output() |
| 2338 | .unwrap(); |
| 2339 | let git_ls_tree = String::from_utf8(git_ls_out.stdout).unwrap(); |
| 2340 | assert_eq!(synapse_ls_tree, git_ls_tree); |
| 2341 | |
| 2342 | // Compare `SynapseService::diff(base_oid, cs2_id)` against `git diff --name-status HEAD~1 HEAD` |
| 2343 | let diff_req = AuthenticatedRequest::sign_new( |
| 2344 | &agent_key, |
| 2345 | grant, |
| 2346 | repo_id, |
| 2347 | Capability::Read, |
| 2348 | [14u8; 32], |
| 2349 | 2_102, |
| 2350 | 0, |
| 2351 | DiffQueryPayload { |
| 2352 | base: TreeTarget::BaseGitCommit(base_oid), |
| 2353 | target: TreeTarget::Changeset(cs2_id), |
| 2354 | page: PageRequest::default(), |
| 2355 | }, |
| 2356 | ) |
| 2357 | .unwrap(); |
| 2358 | let diff_resp = svc.diff(&diff_req, 2_102).unwrap(); |
| 2359 | let mut synapse_diff = String::new(); |
| 2360 | for d in &diff_resp.items { |
| 2361 | synapse_diff.push_str(&format!("{}\t{}\n", d.status.git_status_char(), d.path)); |
| 2362 | } |
| 2363 | |
| 2364 | let git_diff_out = Command::new("git") |
| 2365 | .args(["diff", "--name-status", "HEAD~1", "HEAD"]) |
| 2366 | .current_dir(&git_dir) |
| 2367 | .output() |
| 2368 | .unwrap(); |
| 2369 | let git_diff_str = String::from_utf8(git_diff_out.stdout).unwrap(); |
| 2370 | assert_eq!(synapse_diff, git_diff_str); |
| 2371 | |
| 2372 | let _ = fs::remove_dir_all(&work); |
| 2373 | } |
| 2374 | |
| 2375 | #[test] |
| 2376 | fn test_conflicts_history_provenance_status_path_invalidation_and_watch_cursor_recovery() { |
| 2377 | let dir = temp_dir("api-lifecycle"); |
| 2378 | let repo_id = RepoId::new("aien-spark/synapse").unwrap(); |
| 2379 | let limits = StoreLimits { |
| 2380 | default_retention_window_ms: 500, |
| 2381 | ..Default::default() |
| 2382 | }; |
| 2383 | |
| 2384 | let auth_key = SigningKey::from_bytes(&[30u8; 32]); |
| 2385 | let auth_did = encode_did_key_ed25519(&auth_key.verifying_key().to_bytes()); |
| 2386 | let agent_a = SigningKey::from_bytes(&[31u8; 32]); |
| 2387 | let agent_a_did = encode_did_key_ed25519(&agent_a.verifying_key().to_bytes()); |
| 2388 | let agent_b = SigningKey::from_bytes(&[32u8; 32]); |
| 2389 | let agent_b_did = encode_did_key_ed25519(&agent_b.verifying_key().to_bytes()); |
| 2390 | |
| 2391 | let base_oid = GitOid::compute_blob(b"base-tree"); |
| 2392 | |
| 2393 | let (cs_a_id, cs_b_id); |
| 2394 | { |
| 2395 | let mut svc = SynapseService::open( |
| 2396 | &dir, |
| 2397 | repo_id.clone(), |
| 2398 | FsyncPolicy::EveryCommit, |
| 2399 | RecoveryPolicy::StrictFailClosed, |
| 2400 | limits.clone(), |
| 2401 | ) |
| 2402 | .unwrap(); |
| 2403 | svc.register_authority(auth_did.clone()); |
| 2404 | svc.register_base_tree( |
| 2405 | base_oid, |
| 2406 | vec![( |
| 2407 | "src/shared.rs".to_string(), |
| 2408 | FileMode::Regular644, |
| 2409 | b"pub fn v0() {}\n".to_vec(), |
| 2410 | )], |
| 2411 | ) |
| 2412 | .unwrap(); |
| 2413 | |
| 2414 | let grant_a = AgentCapabilityGrant::issue( |
| 2415 | &auth_key, |
| 2416 | [1u8; 32], |
| 2417 | repo_id.clone(), |
| 2418 | agent_a_did.clone(), |
| 2419 | vec![Capability::Read, Capability::Propose], |
| 2420 | 1024 * 1024, |
| 2421 | 100, |
| 2422 | 60_000, |
| 2423 | 10, |
| 2424 | 100_000, |
| 2425 | ); |
| 2426 | let grant_b = AgentCapabilityGrant::issue( |
| 2427 | &auth_key, |
| 2428 | [2u8; 32], |
| 2429 | repo_id.clone(), |
| 2430 | agent_b_did, |
| 2431 | vec![Capability::Read, Capability::Propose], |
| 2432 | 1024 * 1024, |
| 2433 | 100, |
| 2434 | 60_000, |
| 2435 | 10, |
| 2436 | 100_000, |
| 2437 | ); |
| 2438 | |
| 2439 | // Agent A submits changeset at t=100 (will expire when compacting at t=2000) |
| 2440 | let bytes_a = b"pub fn v_agent_a() {}\n"; |
| 2441 | let dig_a = BlobDigest::compute(bytes_a); |
| 2442 | let mut env_a = ChangesetEnvelope { |
| 2443 | version: SYNAPSE_ENVELOPE_VERSION, |
| 2444 | repo_id: repo_id.clone(), |
| 2445 | base_git_oid: base_oid, |
| 2446 | parent_changesets: vec![], |
| 2447 | author_did: String::new(), |
| 2448 | idempotency_key: IdempotencyKey::from_label("a-1"), |
| 2449 | created_at_ms: 100, |
| 2450 | intent_summary: "Agent A edit shared.rs".to_string(), |
| 2451 | mutations: vec![PathMutation { |
| 2452 | path: "src/shared.rs".to_string(), |
| 2453 | op: MutationOp::Upsert { |
| 2454 | mode: FileMode::Regular644, |
| 2455 | blob_digest: dig_a, |
| 2456 | size_bytes: bytes_a.len() as u64, |
| 2457 | }, |
| 2458 | }], |
| 2459 | evidence_receipts: vec![], |
| 2460 | signature: vec![], |
| 2461 | }; |
| 2462 | env_a.sign(&agent_a); |
| 2463 | let req_a = AuthenticatedRequest::sign_new( |
| 2464 | &agent_a, |
| 2465 | grant_a.clone(), |
| 2466 | repo_id.clone(), |
| 2467 | Capability::Propose, |
| 2468 | [1u8; 32], |
| 2469 | 100, |
| 2470 | 0, |
| 2471 | SubmitChangesetPayload { |
| 2472 | envelope: env_a, |
| 2473 | blobs: vec![(dig_a, bytes_a.to_vec())], |
| 2474 | }, |
| 2475 | ) |
| 2476 | .unwrap(); |
| 2477 | cs_a_id = match svc.submit(&req_a, 100).unwrap() { |
| 2478 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 2479 | _ => unreachable!(), |
| 2480 | }; |
| 2481 | |
| 2482 | // Agent B submits conflicting changeset at t=1800 (within retention window at t=2000) |
| 2483 | let bytes_b = b"pub fn v_agent_b() {}\n"; |
| 2484 | let dig_b = BlobDigest::compute(bytes_b); |
| 2485 | let mut env_b = ChangesetEnvelope { |
| 2486 | version: SYNAPSE_ENVELOPE_VERSION, |
| 2487 | repo_id: repo_id.clone(), |
| 2488 | base_git_oid: base_oid, |
| 2489 | parent_changesets: vec![], |
| 2490 | author_did: String::new(), |
| 2491 | idempotency_key: IdempotencyKey::from_label("b-1"), |
| 2492 | created_at_ms: 1800, |
| 2493 | intent_summary: "Agent B edit shared.rs".to_string(), |
| 2494 | mutations: vec![PathMutation { |
| 2495 | path: "src/shared.rs".to_string(), |
| 2496 | op: MutationOp::Upsert { |
| 2497 | mode: FileMode::Regular644, |
| 2498 | blob_digest: dig_b, |
| 2499 | size_bytes: bytes_b.len() as u64, |
| 2500 | }, |
| 2501 | }], |
| 2502 | evidence_receipts: vec![], |
| 2503 | signature: vec![], |
| 2504 | }; |
| 2505 | env_b.sign(&agent_b); |
| 2506 | let req_b = AuthenticatedRequest::sign_new( |
| 2507 | &agent_b, |
| 2508 | grant_b, |
| 2509 | repo_id.clone(), |
| 2510 | Capability::Propose, |
| 2511 | [2u8; 32], |
| 2512 | 1800, |
| 2513 | 0, |
| 2514 | SubmitChangesetPayload { |
| 2515 | envelope: env_b, |
| 2516 | blobs: vec![(dig_b, bytes_b.to_vec())], |
| 2517 | }, |
| 2518 | ) |
| 2519 | .unwrap(); |
| 2520 | cs_b_id = match svc.submit(&req_b, 1800).unwrap() { |
| 2521 | IngestOutcome::Committed { changeset_id, .. } => changeset_id, |
| 2522 | _ => unreachable!(), |
| 2523 | }; |
| 2524 | |
| 2525 | // Detect conflict between cs_a and cs_b on src/shared.rs |
| 2526 | let conf_req = AuthenticatedRequest::sign_new( |
| 2527 | &agent_a, |
| 2528 | grant_a.clone(), |
| 2529 | repo_id.clone(), |
| 2530 | Capability::Read, |
| 2531 | [3u8; 32], |
| 2532 | 1850, |
| 2533 | 0, |
| 2534 | ConflictQueryPayload { |
| 2535 | candidate: cs_a_id, |
| 2536 | against: None, |
| 2537 | page: PageRequest::default(), |
| 2538 | }, |
| 2539 | ) |
| 2540 | .unwrap(); |
| 2541 | let conf_resp = svc.conflicts(&conf_req, 1850).unwrap(); |
| 2542 | assert_eq!(conf_resp.items.len(), 1); |
| 2543 | assert_eq!(conf_resp.items[0].path, "src/shared.rs"); |
| 2544 | assert_eq!(conf_resp.items[0].conflicting_changeset, cs_b_id); |
| 2545 | |
| 2546 | // Watch cursor reads 1st event (`limit: 1`) and persists durable cursor at WalSeq(1) |
| 2547 | let watch_req1 = AuthenticatedRequest::sign_new( |
| 2548 | &agent_a, |
| 2549 | grant_a.clone(), |
| 2550 | repo_id.clone(), |
| 2551 | Capability::Read, |
| 2552 | [4u8; 32], |
| 2553 | 1860, |
| 2554 | 0, |
| 2555 | WatchQueryPayload { |
| 2556 | subscriber_id: "worker-lane-1".to_string(), |
| 2557 | after_seq: None, |
| 2558 | page: PageRequest { |
| 2559 | cursor: None, |
| 2560 | limit: 1, |
| 2561 | min_visible_seq: None, |
| 2562 | snapshot_seq: None, |
| 2563 | }, |
| 2564 | }, |
| 2565 | ) |
| 2566 | .unwrap(); |
| 2567 | let (wpage1, wcur1) = svc.watch(&watch_req1, 1860).unwrap(); |
| 2568 | assert_eq!(wpage1.items.len(), 1); |
| 2569 | assert_eq!(wcur1.last_seen_seq, WalSeq(1)); |
| 2570 | |
| 2571 | // Materialize virtual tree for cs_a so it enters the cache before compaction |
| 2572 | let _ = svc |
| 2573 | .materialize_virtual_tree(TreeTarget::Changeset(cs_a_id), None) |
| 2574 | .unwrap(); |
| 2575 | assert_eq!(svc.tree_store().memoized_roots(), 1); |
| 2576 | assert_eq!( |
| 2577 | svc.path_index() |
| 2578 | .changesets_for_path("src/shared.rs") |
| 2579 | .unwrap() |
| 2580 | .len(), |
| 2581 | 2 |
| 2582 | ); |
| 2583 | |
| 2584 | // Compact at t=2000: cs_a (t=100) is evicted and invalidated from PathIndex! |
| 2585 | let report = svc.checkpoint_compact_and_invalidate_index(2000).unwrap(); |
| 2586 | assert_eq!(report.evicted_changesets, 1); |
| 2587 | assert_eq!(svc.tree_store().memoized_roots(), 0); |
| 2588 | let remaining_for_shared = svc |
| 2589 | .path_index() |
| 2590 | .changesets_for_path("src/shared.rs") |
| 2591 | .unwrap(); |
| 2592 | assert_eq!(remaining_for_shared.len(), 1); |
| 2593 | assert!(remaining_for_shared.contains(&cs_b_id)); |
| 2594 | assert!(!remaining_for_shared.contains(&cs_a_id)); |
| 2595 | } |
| 2596 | |
| 2597 | // Reopen service from disk and verify durable watch cursor resumes from WalSeq(1) -> WalSeq(2) |
| 2598 | let mut reopened = SynapseService::open( |
| 2599 | &dir, |
| 2600 | repo_id.clone(), |
| 2601 | FsyncPolicy::EveryCommit, |
| 2602 | RecoveryPolicy::StrictFailClosed, |
| 2603 | limits, |
| 2604 | ) |
| 2605 | .unwrap(); |
| 2606 | reopened.register_authority(auth_did); |
| 2607 | let grant_a = AgentCapabilityGrant::issue( |
| 2608 | &auth_key, |
| 2609 | [9u8; 32], |
| 2610 | repo_id.clone(), |
| 2611 | agent_a_did, |
| 2612 | vec![Capability::Read], |
| 2613 | 1024 * 1024, |
| 2614 | 100, |
| 2615 | 60_000, |
| 2616 | 10, |
| 2617 | 100_000, |
| 2618 | ); |
| 2619 | let watch_req2 = AuthenticatedRequest::sign_new( |
| 2620 | &agent_a, |
| 2621 | grant_a, |
| 2622 | repo_id, |
| 2623 | Capability::Read, |
| 2624 | [5u8; 32], |
| 2625 | 2100, |
| 2626 | 0, |
| 2627 | WatchQueryPayload { |
| 2628 | subscriber_id: "worker-lane-1".to_string(), |
| 2629 | after_seq: None, // Automatically resumes from durable cursor on disk! |
| 2630 | page: PageRequest::default(), |
| 2631 | }, |
| 2632 | ) |
| 2633 | .unwrap(); |
| 2634 | let (wpage2, wcur2) = reopened.watch(&watch_req2, 2100).unwrap(); |
| 2635 | assert_eq!(wpage2.items.len(), 1); |
| 2636 | assert_eq!(wpage2.items[0].changeset_id, cs_b_id); |
| 2637 | assert_eq!(wcur2.last_seen_seq, WalSeq(2)); |
| 2638 | |
| 2639 | let _ = fs::remove_dir_all(&dir); |
| 2640 | } |
| 2641 | } |