synapse
A component of the AienOS ecosystem.
Brought by drakestapleton
synapse / crates / synapse-store / src / segment.rs
| 1 | //! Segment store (ADR 0003 step A2, section 5.9): WAL records and blob content in |
| 2 | //! append-only segment files instead of one file per blob. |
| 3 | //! |
| 4 | //! * Segment `1` is `wal.v2.log`; segment `n >= 2` is `wal.v2.<n, at least 6 digits>.log`, |
| 5 | //! all in the store root. Every segment has the WAL v2 layout ([`super::wal2`]): 4 KiB |
| 6 | //! aligned batches, frames with inline blobs, zero-filled and synced space ahead of the |
| 7 | //! write position. A batch is one positioned write plus one `fdatasync` of the active |
| 8 | //! segment. |
| 9 | //! * Rotation: when the active segment holds data and the next batch would end past |
| 10 | //! `StoreLimits::segment_bytes`, a new segment file is created, zero-filled, synced |
| 11 | //! (`sync_all`), and the store directory is flushed before any batch is written into it. |
| 12 | //! The active segment is synced and the directory flushed again on every open, so a |
| 13 | //! file left by a process that died before its directory flush is made durable before |
| 14 | //! it receives a batch. |
| 15 | //! * Index: in memory, blob digest to `(segment, offset, length)`. Recovery rebuilds it |
| 16 | //! from the segment index file bound to the checkpoint plus the batches replayed after |
| 17 | //! it. Checkpoints never move blobs out of the segments and never empty a segment |
| 18 | //! (no garbage collection of segment data before ADR 0003 step K1). |
| 19 | //! * Segment index file `wal.v2.index.<16 hex>`: written (temp, sync, rename, directory |
| 20 | //! sync) before the checkpoint it is bound to. Layout, little-endian: |
| 21 | //! `magic "SSX1" | u16 version = 1 | u16 reserved = 0 | binding[32] | |
| 22 | //! u64 replay_segment | u64 replay_offset | u64 count | |
| 23 | //! count x (digest[32] | u64 segment | u64 offset | u32 len) | sha256[32]`, entries in |
| 24 | //! strictly increasing digest order, the trailing digest over |
| 25 | //! `"SYNAPSE_SEGMENT_INDEX_V1\0" || every preceding byte`. `binding` is the digest of the |
| 26 | //! checkpoint file the index belongs to ([`checkpoint_binding`]), so an index written |
| 27 | //! just before a crash that kept the older checkpoint is never used with it. |
| 28 | //! * Chunks (ADR 0003 G2): an index whose checkpoint retains chunked blobs has version 2: |
| 29 | //! the version 1 layout up to the blob entries, then `u64 chunk_count | chunk_count x |
| 30 | //! (chunk_digest[32] | u64 segment | u64 offset | u32 len) | u64 manifest_count | |
| 31 | //! manifest_count x (blob_digest[32] | u64 len | u32 n | n x (chunk_digest[32] | u32 len))` |
| 32 | //! before the trailing digest; chunks and manifests in strictly increasing digest order, |
| 33 | //! every chunk named by a manifest and before the replay position, every manifest length |
| 34 | //! the sum of its chunks. An index without chunks stays version 1, so a store that never |
| 35 | //! chunked stays readable by builds before G2; builds before G2 refuse one that did |
| 36 | //! (`CheckpointCorrupt` for the index, `WalFlagsNonZero` for its chunked frames). |
| 37 | |
| 38 | use super::*; |
| 39 | use std::os::unix::fs::FileExt; |
| 40 | use std::sync::Arc; |
| 41 | |
| 42 | /// Marker frame version in `wal.log` for the segment layout (version 2 is the WAL v2 |
| 43 | /// marker of the single-file layout). Binaries that predate A2 refuse version 3 |
| 44 | /// (`WalVersionUnsupported`) instead of missing segments 2 and up. |
| 45 | pub const WAL_SEGMENT_MARKER_VERSION: u16 = 3; |
| 46 | /// File name prefix of segment index files. |
| 47 | pub const SEGMENT_INDEX_PREFIX: &str = "wal.v2.index."; |
| 48 | /// Segment index magic. |
| 49 | pub const SEGMENT_INDEX_MAGIC: [u8; 4] = *b"SSX1"; |
| 50 | /// Segment index format version. |
| 51 | pub const SEGMENT_INDEX_VERSION: u16 = 1; |
| 52 | /// Segment index format version with chunks and manifests (ADR 0003 G2). |
| 53 | pub const SEGMENT_INDEX_VERSION_CHUNKS: u16 = 2; |
| 54 | /// Domain tag of the segment index trailer digest. |
| 55 | pub const DOMAIN_SEGMENT_INDEX: &[u8] = b"SYNAPSE_SEGMENT_INDEX_V1\0"; |
| 56 | /// Domain tag of the checkpoint binding digest. |
| 57 | pub const DOMAIN_SEGMENT_BINDING: &[u8] = b"SYNAPSE_SEGMENT_CHECKPOINT_BINDING_V1\0"; |
| 58 | |
| 59 | const INDEX_HEADER_LEN: usize = 64; |
| 60 | const INDEX_ENTRY_LEN: usize = 52; |
| 61 | |
| 62 | /// File name of segment `id` (`id >= 1`). |
| 63 | pub fn segment_file_name(id: u64) -> String { |
| 64 | if id == 1 { |
| 65 | wal2::WAL_V2_FILE.to_string() |
| 66 | } else { |
| 67 | format!("wal.v2.{id:06}.log") |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// Segment id of a file name, if it is one in canonical form. |
| 72 | pub fn parse_segment_file_name(name: &str) -> Option<u64> { |
| 73 | if name == wal2::WAL_V2_FILE { |
| 74 | return Some(1); |
| 75 | } |
| 76 | let digits = name.strip_prefix("wal.v2.")?.strip_suffix(".log")?; |
| 77 | if digits.len() < 6 || !digits.bytes().all(|b| b.is_ascii_digit()) { |
| 78 | return None; |
| 79 | } |
| 80 | let id: u64 = digits.parse().ok()?; |
| 81 | (id >= 2 && segment_file_name(id) == name).then_some(id) |
| 82 | } |
| 83 | |
| 84 | /// Ids of the segment files present in `root`, ascending. |
| 85 | pub(crate) fn list_segments(root: &Path) -> SynapseResult<Vec<u64>> { |
| 86 | let mut ids = Vec::new(); |
| 87 | for entry in fs::read_dir(root).map_err(io_err)? { |
| 88 | let entry = entry.map_err(io_err)?; |
| 89 | if let Some(id) = entry.file_name().to_str().and_then(parse_segment_file_name) { |
| 90 | ids.push(id); |
| 91 | } |
| 92 | } |
| 93 | ids.sort_unstable(); |
| 94 | Ok(ids) |
| 95 | } |
| 96 | |
| 97 | /// Location of one blob inside a segment. |
| 98 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 99 | pub(crate) struct BlobLoc { |
| 100 | pub segment: u64, |
| 101 | pub offset: u64, |
| 102 | pub len: u32, |
| 103 | } |
| 104 | |
| 105 | /// Digest that binds a segment index to one checkpoint file's exact bytes. |
| 106 | pub(crate) fn binding_of(checkpoint: Option<(&str, &[u8])>) -> [u8; 32] { |
| 107 | let mut h = Sha256::new(); |
| 108 | h.update(DOMAIN_SEGMENT_BINDING); |
| 109 | match checkpoint { |
| 110 | Some((name, bytes)) => { |
| 111 | h.update([1u8]); |
| 112 | h.update((name.len() as u32).to_le_bytes()); |
| 113 | h.update(name.as_bytes()); |
| 114 | h.update(bytes); |
| 115 | } |
| 116 | None => h.update([0u8]), |
| 117 | } |
| 118 | h.finalize().into() |
| 119 | } |
| 120 | |
| 121 | /// Binding of the checkpoint in a store directory (see [`checkpoint_binding_on`]). |
| 122 | #[cfg(test)] |
| 123 | pub(crate) fn checkpoint_binding(root: &Path) -> SynapseResult<[u8; 32]> { |
| 124 | checkpoint_binding_on(&Medium::Dir(root.to_path_buf())) |
| 125 | } |
| 126 | |
| 127 | /// Binding of the checkpoint on the medium: `checkpoint.v2` when present, else a |
| 128 | /// `checkpoint.v1` that is not the tombstone, else none. |
| 129 | pub(crate) fn checkpoint_binding_on(m: &Medium) -> SynapseResult<[u8; 32]> { |
| 130 | if m.exists(codec::CHECKPOINT_V2_FILE) { |
| 131 | let bytes = m.read(codec::CHECKPOINT_V2_FILE).map_err(io_err)?; |
| 132 | return Ok(binding_of(Some((codec::CHECKPOINT_V2_FILE, &bytes)))); |
| 133 | } |
| 134 | if m.exists("checkpoint.v1") { |
| 135 | let bytes = m.read("checkpoint.v1").map_err(io_err)?; |
| 136 | if bytes != codec::v1_tombstone_bytes() { |
| 137 | return Ok(binding_of(Some(("checkpoint.v1", &bytes)))); |
| 138 | } |
| 139 | } |
| 140 | Ok(binding_of(None)) |
| 141 | } |
| 142 | |
| 143 | /// The segment index persisted next to a checkpoint. |
| 144 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 145 | pub(crate) struct SegmentIndex { |
| 146 | /// [`binding_of`] the checkpoint this index belongs to. |
| 147 | pub binding: [u8; 32], |
| 148 | /// Replay starts at this segment and byte offset: everything before it is covered |
| 149 | /// by the checkpoint. |
| 150 | pub replay_segment: u64, |
| 151 | pub replay_offset: u64, |
| 152 | /// Locations of the blobs the checkpoint retains that live in segment bytes before |
| 153 | /// the replay position. |
| 154 | pub entries: BTreeMap<BlobDigest, BlobLoc>, |
| 155 | /// Locations of the chunks the retained chunked blobs name (ADR 0003 G2; version 2). |
| 156 | pub chunks: BTreeMap<ChunkDigest, BlobLoc>, |
| 157 | /// Manifests of the retained chunked blobs (version 2). |
| 158 | pub manifests: BTreeMap<BlobDigest, ChunkManifest>, |
| 159 | } |
| 160 | |
| 161 | fn index_corrupt(what: &str) -> SynapseError { |
| 162 | SynapseError::new( |
| 163 | RefusalCode::CheckpointCorrupt, |
| 164 | format!("segment index: {what}"), |
| 165 | ) |
| 166 | } |
| 167 | |
| 168 | fn index_digest(bytes: &[u8]) -> [u8; 32] { |
| 169 | let mut h = Sha256::new(); |
| 170 | h.update(DOMAIN_SEGMENT_INDEX); |
| 171 | h.update(bytes); |
| 172 | h.finalize().into() |
| 173 | } |
| 174 | |
| 175 | impl SegmentIndex { |
| 176 | /// File name of the index bound to `binding`. |
| 177 | pub fn file_name(binding: &[u8; 32]) -> String { |
| 178 | format!("{SEGMENT_INDEX_PREFIX}{}", hex::encode(&binding[..8])) |
| 179 | } |
| 180 | |
| 181 | /// Encoded index: version 1 when it holds no chunks (readable by pre-G2 builds), |
| 182 | /// version 2 otherwise. |
| 183 | pub fn encode(&self) -> Vec<u8> { |
| 184 | let v2 = !self.chunks.is_empty() || !self.manifests.is_empty(); |
| 185 | let mut b = |
| 186 | Vec::with_capacity(INDEX_HEADER_LEN + self.entries.len() * INDEX_ENTRY_LEN + 32); |
| 187 | b.extend_from_slice(&SEGMENT_INDEX_MAGIC); |
| 188 | let version = if v2 { |
| 189 | SEGMENT_INDEX_VERSION_CHUNKS |
| 190 | } else { |
| 191 | SEGMENT_INDEX_VERSION |
| 192 | }; |
| 193 | b.extend_from_slice(&version.to_le_bytes()); |
| 194 | b.extend_from_slice(&0u16.to_le_bytes()); |
| 195 | b.extend_from_slice(&self.binding); |
| 196 | b.extend_from_slice(&self.replay_segment.to_le_bytes()); |
| 197 | b.extend_from_slice(&self.replay_offset.to_le_bytes()); |
| 198 | b.extend_from_slice(&(self.entries.len() as u64).to_le_bytes()); |
| 199 | let put_loc = |b: &mut Vec<u8>, d: &[u8; 32], loc: &BlobLoc| { |
| 200 | b.extend_from_slice(d); |
| 201 | b.extend_from_slice(&loc.segment.to_le_bytes()); |
| 202 | b.extend_from_slice(&loc.offset.to_le_bytes()); |
| 203 | b.extend_from_slice(&loc.len.to_le_bytes()); |
| 204 | }; |
| 205 | for (d, loc) in &self.entries { |
| 206 | put_loc(&mut b, &d.0, loc); |
| 207 | } |
| 208 | if v2 { |
| 209 | b.extend_from_slice(&(self.chunks.len() as u64).to_le_bytes()); |
| 210 | for (d, loc) in &self.chunks { |
| 211 | put_loc(&mut b, &d.0, loc); |
| 212 | } |
| 213 | b.extend_from_slice(&(self.manifests.len() as u64).to_le_bytes()); |
| 214 | for m in self.manifests.values() { |
| 215 | b.extend_from_slice(&m.blob.0); |
| 216 | b.extend_from_slice(&m.len.to_le_bytes()); |
| 217 | b.extend_from_slice(&(m.chunks.len() as u32).to_le_bytes()); |
| 218 | for (d, l) in &m.chunks { |
| 219 | b.extend_from_slice(&d.0); |
| 220 | b.extend_from_slice(&l.to_le_bytes()); |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | let sha = index_digest(&b); |
| 225 | b.extend_from_slice(&sha); |
| 226 | b |
| 227 | } |
| 228 | |
| 229 | /// Strict decoder: one encoding per index; every failure is `CheckpointCorrupt`. |
| 230 | pub fn decode(bytes: &[u8]) -> SynapseResult<Self> { |
| 231 | if bytes.len() < INDEX_HEADER_LEN + 32 { |
| 232 | return Err(index_corrupt("shorter than its header")); |
| 233 | } |
| 234 | let (body, trailer) = bytes.split_at(bytes.len() - 32); |
| 235 | if index_digest(body) != trailer { |
| 236 | return Err(index_corrupt("digest mismatch")); |
| 237 | } |
| 238 | if body[0..4] != SEGMENT_INDEX_MAGIC { |
| 239 | return Err(index_corrupt("bad magic")); |
| 240 | } |
| 241 | let version = u16::from_le_bytes([body[4], body[5]]); |
| 242 | let v2 = match version { |
| 243 | SEGMENT_INDEX_VERSION => false, |
| 244 | SEGMENT_INDEX_VERSION_CHUNKS => true, |
| 245 | _ => return Err(index_corrupt("unsupported version or reserved bytes")), |
| 246 | }; |
| 247 | if body[6..8] != [0, 0] { |
| 248 | return Err(index_corrupt("unsupported version or reserved bytes")); |
| 249 | } |
| 250 | let u64_at = |at: usize| u64::from_le_bytes(body[at..at + 8].try_into().expect("8")); |
| 251 | let binding: [u8; 32] = body[8..40].try_into().expect("32"); |
| 252 | let replay_segment = u64_at(40); |
| 253 | let replay_offset = u64_at(48); |
| 254 | let count = u64_at(56); |
| 255 | if replay_segment == 0 || replay_offset % wal2::WAL_V2_ALIGN != 0 { |
| 256 | return Err(index_corrupt("invalid replay position")); |
| 257 | } |
| 258 | let mut at = INDEX_HEADER_LEN; |
| 259 | let take = |at: &mut usize, n: u128| -> SynapseResult<&[u8]> { |
| 260 | if n > (body.len() - *at) as u128 { |
| 261 | return Err(index_corrupt("entry count does not match the length")); |
| 262 | } |
| 263 | let s = &body[*at..*at + n as usize]; |
| 264 | *at += n as usize; |
| 265 | Ok(s) |
| 266 | }; |
| 267 | let check_loc = |e: &[u8]| -> SynapseResult<BlobLoc> { |
| 268 | let loc = BlobLoc { |
| 269 | segment: u64::from_le_bytes(e[32..40].try_into().expect("8")), |
| 270 | offset: u64::from_le_bytes(e[40..48].try_into().expect("8")), |
| 271 | len: u32::from_le_bytes(e[48..52].try_into().expect("4")), |
| 272 | }; |
| 273 | let end = loc.offset.checked_add(u64::from(loc.len)); |
| 274 | let before_replay = |
| 275 | (loc.segment, end.unwrap_or(u64::MAX)) <= (replay_segment, replay_offset); |
| 276 | if loc.segment == 0 || end.is_none() || !before_replay { |
| 277 | return Err(index_corrupt("entry outside the covered segment bytes")); |
| 278 | } |
| 279 | Ok(loc) |
| 280 | }; |
| 281 | let region = take(&mut at, count as u128 * INDEX_ENTRY_LEN as u128)?; |
| 282 | let mut entries = BTreeMap::new(); |
| 283 | let mut prev: Option<BlobDigest> = None; |
| 284 | for e in region.as_chunks::<INDEX_ENTRY_LEN>().0 { |
| 285 | let d = BlobDigest(e[0..32].try_into().expect("32")); |
| 286 | if prev.is_some_and(|p| p >= d) { |
| 287 | return Err(index_corrupt("entries not in strictly increasing order")); |
| 288 | } |
| 289 | prev = Some(d); |
| 290 | entries.insert(d, check_loc(e)?); |
| 291 | } |
| 292 | let mut chunks = BTreeMap::new(); |
| 293 | let mut manifests = BTreeMap::new(); |
| 294 | if v2 { |
| 295 | let n = u64::from_le_bytes(take(&mut at, 8)?.try_into().expect("8")); |
| 296 | let region = take(&mut at, n as u128 * INDEX_ENTRY_LEN as u128)?; |
| 297 | let mut prev: Option<ChunkDigest> = None; |
| 298 | for e in region.as_chunks::<INDEX_ENTRY_LEN>().0 { |
| 299 | let d = ChunkDigest(e[0..32].try_into().expect("32")); |
| 300 | if prev.is_some_and(|p| p >= d) { |
| 301 | return Err(index_corrupt("chunks not in strictly increasing order")); |
| 302 | } |
| 303 | prev = Some(d); |
| 304 | chunks.insert(d, check_loc(e)?); |
| 305 | } |
| 306 | let n = u64::from_le_bytes(take(&mut at, 8)?.try_into().expect("8")); |
| 307 | let mut prev: Option<BlobDigest> = None; |
| 308 | let mut referenced = BTreeSet::new(); |
| 309 | for _ in 0..n { |
| 310 | let h = take(&mut at, 44)?; |
| 311 | let blob = BlobDigest(h[0..32].try_into().expect("32")); |
| 312 | let len = u64::from_le_bytes(h[32..40].try_into().expect("8")); |
| 313 | let k = u32::from_le_bytes(h[40..44].try_into().expect("4")); |
| 314 | if prev.is_some_and(|p| p >= blob) { |
| 315 | return Err(index_corrupt("manifests not in strictly increasing order")); |
| 316 | } |
| 317 | prev = Some(blob); |
| 318 | let region = take(&mut at, k as u128 * 36)?; |
| 319 | let mut list = Vec::with_capacity(k as usize); |
| 320 | let mut sum = 0u64; |
| 321 | for e in region.as_chunks::<36>().0 { |
| 322 | let d = ChunkDigest(e[0..32].try_into().expect("32")); |
| 323 | let l = u32::from_le_bytes(e[32..36].try_into().expect("4")); |
| 324 | if chunks.get(&d).is_none_or(|loc: &BlobLoc| loc.len != l) || l == 0 { |
| 325 | return Err(index_corrupt("manifest names a chunk the index lacks")); |
| 326 | } |
| 327 | referenced.insert(d); |
| 328 | sum += u64::from(l); |
| 329 | list.push((d, l)); |
| 330 | } |
| 331 | if k == 0 || sum != len { |
| 332 | return Err(index_corrupt("manifest length does not match its chunks")); |
| 333 | } |
| 334 | manifests.insert( |
| 335 | blob, |
| 336 | ChunkManifest { |
| 337 | blob, |
| 338 | len, |
| 339 | chunks: list, |
| 340 | }, |
| 341 | ); |
| 342 | } |
| 343 | if referenced.len() != chunks.len() { |
| 344 | return Err(index_corrupt("chunk named by no manifest")); |
| 345 | } |
| 346 | if chunks.is_empty() { |
| 347 | return Err(index_corrupt("version 2 index without chunks")); |
| 348 | } |
| 349 | } |
| 350 | if at != body.len() { |
| 351 | return Err(index_corrupt("entry count does not match the length")); |
| 352 | } |
| 353 | Ok(Self { |
| 354 | binding, |
| 355 | replay_segment, |
| 356 | replay_offset, |
| 357 | entries, |
| 358 | chunks, |
| 359 | manifests, |
| 360 | }) |
| 361 | } |
| 362 | |
| 363 | /// Write atomically (A2: temp file, sync, rename, directory sync; R1: one metadata |
| 364 | /// commit); returns the file name. |
| 365 | pub fn write(&self, m: &Medium) -> SynapseResult<String> { |
| 366 | let name = Self::file_name(&self.binding); |
| 367 | m.write_atomic(&name, &self.encode())?; |
| 368 | Ok(name) |
| 369 | } |
| 370 | |
| 371 | /// Load the index bound to `binding` from a store directory. |
| 372 | #[cfg(test)] |
| 373 | pub fn load(root: &Path, binding: &[u8; 32]) -> SynapseResult<Self> { |
| 374 | Self::load_from(&Medium::Dir(root.to_path_buf()), binding) |
| 375 | } |
| 376 | |
| 377 | /// Load the index bound to `binding` (`CheckpointCorrupt` when missing or invalid). |
| 378 | pub fn load_from(m: &Medium, binding: &[u8; 32]) -> SynapseResult<Self> { |
| 379 | let name = Self::file_name(binding); |
| 380 | let bytes = m.read(&name).map_err(|e| { |
| 381 | index_corrupt(&format!( |
| 382 | "{name} for the checkpoint on disk cannot be read: {e}" |
| 383 | )) |
| 384 | })?; |
| 385 | let index = Self::decode(&bytes)?; |
| 386 | if &index.binding != binding { |
| 387 | return Err(index_corrupt(&format!( |
| 388 | "{name} is bound to a different checkpoint" |
| 389 | ))); |
| 390 | } |
| 391 | Ok(index) |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | /// Remove every segment index file (and leftover temp file) except `keep`. Index files |
| 396 | /// are metadata: this never touches segment data. |
| 397 | pub(crate) fn remove_other_indexes(m: &Medium, keep: &str) -> SynapseResult<()> { |
| 398 | let root = match m { |
| 399 | Medium::Dir(root) => root, |
| 400 | Medium::Block(dev) => { |
| 401 | dev.remove_named_where(|n| n.starts_with(SEGMENT_INDEX_PREFIX) && n != keep) |
| 402 | .map_err(io_err)?; |
| 403 | return Ok(()); |
| 404 | } |
| 405 | }; |
| 406 | let mut removed = false; |
| 407 | for entry in fs::read_dir(root).map_err(io_err)? { |
| 408 | let entry = entry.map_err(io_err)?; |
| 409 | let name = entry.file_name(); |
| 410 | let Some(name) = name.to_str() else { continue }; |
| 411 | if name.starts_with(SEGMENT_INDEX_PREFIX) && name != keep { |
| 412 | fs::remove_file(entry.path()).map_err(io_err)?; |
| 413 | removed = true; |
| 414 | } |
| 415 | } |
| 416 | if removed { |
| 417 | sync_dir(root)?; |
| 418 | } |
| 419 | Ok(()) |
| 420 | } |
| 421 | |
| 422 | /// Faults injected into the next segment rotation (test hooks). |
| 423 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 424 | pub(crate) enum RotationFault { |
| 425 | None, |
| 426 | /// Create and pre-write the new segment, then exit the process with `code` before |
| 427 | /// the directory flush. |
| 428 | CrashBeforeDirSync { |
| 429 | code: i32, |
| 430 | }, |
| 431 | /// The directory flush after creating the new segment fails. |
| 432 | FailDirSync, |
| 433 | } |
| 434 | |
| 435 | /// Durability events of the segment writer, in order (test camera). |
| 436 | #[cfg(test)] |
| 437 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 438 | pub(crate) enum SegEvent { |
| 439 | /// A new segment file was created. |
| 440 | Created(u64), |
| 441 | /// The segment file's data and size were synced (`sync_all`). |
| 442 | FileSynced(u64), |
| 443 | /// The store directory was flushed after this segment was created or opened. |
| 444 | DirSynced(u64), |
| 445 | /// A batch write into this segment started. |
| 446 | BatchWrite(u64), |
| 447 | /// A batch in this segment was written and `fdatasync` returned success. |
| 448 | BatchDurable(u64), |
| 449 | } |
| 450 | |
| 451 | /// Writer of the active segment, rotating to new segments (files in A2, device slots in |
| 452 | /// R1). |
| 453 | #[derive(Debug)] |
| 454 | pub(crate) struct SegmentLog { |
| 455 | medium: Medium, |
| 456 | active: u64, |
| 457 | writer: wal2::WalV2Writer, |
| 458 | segment_bytes: u64, |
| 459 | chunk: u64, |
| 460 | #[cfg(test)] |
| 461 | pub trace: Vec<SegEvent>, |
| 462 | } |
| 463 | |
| 464 | impl SegmentLog { |
| 465 | /// Open the active segment `active` with the log ending at `write_offset`. The file |
| 466 | /// is synced and the directory flushed before anything is written into it (R1: the |
| 467 | /// device is flushed, and a slot past the committed count is created first). |
| 468 | pub fn open( |
| 469 | medium: &Medium, |
| 470 | active: u64, |
| 471 | write_offset: u64, |
| 472 | segment_bytes: u64, |
| 473 | chunk: u64, |
| 474 | ) -> SynapseResult<Self> { |
| 475 | let root = match medium { |
| 476 | Medium::Dir(root) => root, |
| 477 | Medium::Block(dev) => return Self::open_block(medium, dev, active, write_offset), |
| 478 | }; |
| 479 | let segment_bytes = segment_bytes.max(wal2::WAL_V2_ALIGN); |
| 480 | let chunk = chunk.min(segment_bytes); |
| 481 | let path = root.join(segment_file_name(active)); |
| 482 | let mut writer = wal2::WalV2Writer::open(&path, write_offset, chunk)?; |
| 483 | writer.set_prewrite_cap(segment_bytes); |
| 484 | // The file may come from a process that died before flushing the directory |
| 485 | // entry: make both durable before the first batch lands in it. |
| 486 | writer.sync_all()?; |
| 487 | sync_dir(root)?; |
| 488 | Ok(Self { |
| 489 | medium: medium.clone(), |
| 490 | active, |
| 491 | writer, |
| 492 | segment_bytes, |
| 493 | chunk, |
| 494 | #[cfg(test)] |
| 495 | trace: vec![SegEvent::FileSynced(active), SegEvent::DirSynced(active)], |
| 496 | }) |
| 497 | } |
| 498 | |
| 499 | fn open_block( |
| 500 | medium: &Medium, |
| 501 | dev: &Arc<blockdev::BlockDevice>, |
| 502 | active: u64, |
| 503 | write_offset: u64, |
| 504 | ) -> SynapseResult<Self> { |
| 505 | let segment_bytes = dev.geometry().segment_bytes; |
| 506 | let mut log = Self { |
| 507 | medium: medium.clone(), |
| 508 | active, |
| 509 | writer: wal2::WalV2Writer::on_block(dev.clone(), active, write_offset, segment_bytes), |
| 510 | segment_bytes, |
| 511 | chunk: segment_bytes, |
| 512 | #[cfg(test)] |
| 513 | trace: Vec::new(), |
| 514 | }; |
| 515 | if active > dev.segment_count() { |
| 516 | // A new store, or a slot a rotation created but never committed. |
| 517 | log.create_block_slot(dev, active, RotationFault::None) |
| 518 | .map_err(io_err)?; |
| 519 | } else { |
| 520 | dev.flush().map_err(io_err)?; |
| 521 | #[cfg(test)] |
| 522 | log.trace |
| 523 | .extend([SegEvent::FileSynced(active), SegEvent::DirSynced(active)]); |
| 524 | } |
| 525 | Ok(log) |
| 526 | } |
| 527 | |
| 528 | /// R1 rotation: header, zero the slot and `fdatasync`, then commit the segment count |
| 529 | /// in the superblock (`fdatasync`). |
| 530 | fn create_block_slot( |
| 531 | &mut self, |
| 532 | dev: &blockdev::BlockDevice, |
| 533 | id: u64, |
| 534 | fault: RotationFault, |
| 535 | ) -> std::io::Result<()> { |
| 536 | // Zero and flush before the header goes in: a valid header then always sits on a |
| 537 | // zeroed slot, so data under a valid header past the committed count can only |
| 538 | // be acknowledged batches (`BlockDevice::refuse_data_past_segment_count`). |
| 539 | dev.zero_segment(id)?; |
| 540 | dev.write_segment_header(id)?; |
| 541 | #[cfg(test)] |
| 542 | self.trace.push(SegEvent::Created(id)); |
| 543 | dev.flush()?; |
| 544 | #[cfg(test)] |
| 545 | self.trace.push(SegEvent::FileSynced(id)); |
| 546 | match fault { |
| 547 | RotationFault::None => {} |
| 548 | RotationFault::CrashBeforeDirSync { code } => std::process::exit(code), |
| 549 | RotationFault::FailDirSync => { |
| 550 | return Err(std::io::Error::other( |
| 551 | "injected fault: directory flush failed", |
| 552 | )) |
| 553 | } |
| 554 | } |
| 555 | dev.commit_segment(id)?; |
| 556 | #[cfg(test)] |
| 557 | self.trace.push(SegEvent::DirSynced(id)); |
| 558 | Ok(()) |
| 559 | } |
| 560 | |
| 561 | pub fn active(&self) -> u64 { |
| 562 | self.active |
| 563 | } |
| 564 | |
| 565 | pub fn write_offset(&self) -> u64 { |
| 566 | self.writer.write_offset |
| 567 | } |
| 568 | |
| 569 | /// Make room for a batch of `len` bytes and return `(segment, offset)` where it |
| 570 | /// goes. Rotates when the active segment holds data and the batch would end past |
| 571 | /// the segment size: the new file is created, zero-filled, synced, and the |
| 572 | /// directory flushed before this returns. On failure nothing was written into any |
| 573 | /// log extent and the active segment is unchanged. |
| 574 | pub fn reserve( |
| 575 | &mut self, |
| 576 | len: u64, |
| 577 | fault: RotationFault, |
| 578 | ) -> Result<(u64, u64), wal2::BatchFailure> { |
| 579 | let at = self.writer.write_offset; |
| 580 | if at == 0 || at.saturating_add(len) <= self.segment_bytes { |
| 581 | return Ok((self.active, at)); |
| 582 | } |
| 583 | let id = self.active + 1; |
| 584 | let fail = |e: std::io::Error| { |
| 585 | wal2::BatchFailure::RolledBack(SynapseError::new( |
| 586 | RefusalCode::IoFailure, |
| 587 | format!("create segment {id}: {e}"), |
| 588 | )) |
| 589 | }; |
| 590 | let root = match &self.medium { |
| 591 | Medium::Dir(root) => root.clone(), |
| 592 | Medium::Block(dev) => { |
| 593 | let dev = dev.clone(); |
| 594 | // A slot with this id past the committed count was never data: it is |
| 595 | // given a header and zeroed again. |
| 596 | self.create_block_slot(&dev, id, fault).map_err(fail)?; |
| 597 | self.writer = wal2::WalV2Writer::on_block(dev, id, 0, self.segment_bytes); |
| 598 | self.active = id; |
| 599 | return Ok((id, 0)); |
| 600 | } |
| 601 | }; |
| 602 | // A file with this id can only be one an earlier failed rotation of this |
| 603 | // process created (or an all-zero one recovery verified): never acknowledged |
| 604 | // data, so it is truncated and pre-written again. |
| 605 | let file = OpenOptions::new() |
| 606 | .create(true) |
| 607 | .truncate(true) |
| 608 | .read(true) |
| 609 | .write(true) |
| 610 | .open(root.join(segment_file_name(id))) |
| 611 | .map_err(fail)?; |
| 612 | #[cfg(test)] |
| 613 | self.trace.push(SegEvent::Created(id)); |
| 614 | let mut writer = wal2::WalV2Writer::new_empty(file, self.chunk, self.segment_bytes); |
| 615 | writer.ensure_space(len).map_err(fail)?; |
| 616 | #[cfg(test)] |
| 617 | self.trace.push(SegEvent::FileSynced(id)); |
| 618 | match fault { |
| 619 | RotationFault::None => {} |
| 620 | RotationFault::CrashBeforeDirSync { code } => std::process::exit(code), |
| 621 | RotationFault::FailDirSync => { |
| 622 | return Err(fail(std::io::Error::other( |
| 623 | "injected fault: directory flush failed", |
| 624 | ))) |
| 625 | } |
| 626 | } |
| 627 | File::open(&root).and_then(|d| d.sync_all()).map_err(fail)?; |
| 628 | #[cfg(test)] |
| 629 | self.trace.push(SegEvent::DirSynced(id)); |
| 630 | self.writer = writer; |
| 631 | self.active = id; |
| 632 | Ok((id, 0)) |
| 633 | } |
| 634 | |
| 635 | /// Write one batch at the reserved position: one write, one `fdatasync`. |
| 636 | pub fn write_batch( |
| 637 | &mut self, |
| 638 | buf: &[u8], |
| 639 | fault: wal2::BatchIoFault, |
| 640 | ) -> Result<(), wal2::BatchFailure> { |
| 641 | #[cfg(test)] |
| 642 | self.trace.push(SegEvent::BatchWrite(self.active)); |
| 643 | self.writer.write_batch(buf, fault)?; |
| 644 | #[cfg(test)] |
| 645 | self.trace.push(SegEvent::BatchDurable(self.active)); |
| 646 | Ok(()) |
| 647 | } |
| 648 | |
| 649 | pub fn sync(&self) -> SynapseResult<()> { |
| 650 | self.writer.sync() |
| 651 | } |
| 652 | } |
| 653 | |
| 654 | /// A read handle on one segment, for inline blob reads. |
| 655 | #[derive(Debug)] |
| 656 | pub(crate) enum SegReader { |
| 657 | File(File), |
| 658 | Block(Arc<blockdev::BlockDevice>, u64), |
| 659 | } |
| 660 | |
| 661 | impl SegReader { |
| 662 | /// Read `len` bytes at `offset` of the segment. |
| 663 | pub fn read_at(&self, offset: u64, len: u32) -> std::io::Result<Vec<u8>> { |
| 664 | match self { |
| 665 | SegReader::File(f) => { |
| 666 | let mut bytes = vec![0u8; len as usize]; |
| 667 | f.read_exact_at(&mut bytes, offset)?; |
| 668 | Ok(bytes) |
| 669 | } |
| 670 | SegReader::Block(dev, id) => dev.read_segment_at(*id, offset, len), |
| 671 | } |
| 672 | } |
| 673 | |
| 674 | /// Fill `buf` from `offset` of the segment (ADR 0003 G2 chunk runs). |
| 675 | pub fn read_into(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> { |
| 676 | match self { |
| 677 | SegReader::File(f) => f.read_exact_at(buf, offset), |
| 678 | SegReader::Block(dev, id) => { |
| 679 | let len = u32::try_from(buf.len()).map_err(|_| { |
| 680 | std::io::Error::new(std::io::ErrorKind::InvalidInput, "chunk run too large") |
| 681 | })?; |
| 682 | buf.copy_from_slice(&dev.read_segment_at(*id, offset, len)?); |
| 683 | Ok(()) |
| 684 | } |
| 685 | } |
| 686 | } |
| 687 | } |