1use crate::error::{Result, WalError};
15
16pub const WAL_MAGIC: u32 = 0x5359_4E57; pub const WAL_FORMAT_VERSION: u16 = 1;
21
22pub const MAX_WAL_PAYLOAD_SIZE: usize = 64 * 1024 * 1024;
24
25pub const HEADER_SIZE: usize = 30;
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct RecordHeader {
31 pub magic: u32,
33
34 pub format_version: u16,
36
37 pub record_type: u16,
39
40 pub lsn: u64,
42
43 pub tenant_id: u32,
45
46 pub vshard_id: u16,
48
49 pub payload_len: u32,
51
52 pub crc32c: u32,
54}
55
56impl RecordHeader {
57 pub fn to_bytes(&self) -> [u8; HEADER_SIZE] {
59 let mut buf = [0u8; HEADER_SIZE];
60 buf[0..4].copy_from_slice(&self.magic.to_le_bytes());
61 buf[4..6].copy_from_slice(&self.format_version.to_le_bytes());
62 buf[6..8].copy_from_slice(&self.record_type.to_le_bytes());
63 buf[8..16].copy_from_slice(&self.lsn.to_le_bytes());
64 buf[16..20].copy_from_slice(&self.tenant_id.to_le_bytes());
65 buf[20..22].copy_from_slice(&self.vshard_id.to_le_bytes());
66 buf[22..26].copy_from_slice(&self.payload_len.to_le_bytes());
67 buf[26..30].copy_from_slice(&self.crc32c.to_le_bytes());
68 buf
69 }
70
71 pub fn from_bytes(buf: &[u8; HEADER_SIZE]) -> Self {
73 Self {
74 magic: u32::from_le_bytes([buf[0], buf[1], buf[2], buf[3]]),
75 format_version: u16::from_le_bytes([buf[4], buf[5]]),
76 record_type: u16::from_le_bytes([buf[6], buf[7]]),
77 lsn: u64::from_le_bytes([
78 buf[8], buf[9], buf[10], buf[11], buf[12], buf[13], buf[14], buf[15],
79 ]),
80 tenant_id: u32::from_le_bytes([buf[16], buf[17], buf[18], buf[19]]),
81 vshard_id: u16::from_le_bytes([buf[20], buf[21]]),
82 payload_len: u32::from_le_bytes([buf[22], buf[23], buf[24], buf[25]]),
83 crc32c: u32::from_le_bytes([buf[26], buf[27], buf[28], buf[29]]),
84 }
85 }
86
87 pub fn compute_checksum(&self, payload: &[u8]) -> u32 {
89 let header_bytes = self.to_bytes();
90 let mut digest = crc32c::crc32c(&header_bytes[..HEADER_SIZE - 4]);
92 digest = crc32c::crc32c_append(digest, payload);
93 digest
94 }
95
96 pub fn logical_record_type(&self) -> u16 {
98 self.record_type & !ENCRYPTED_FLAG
99 }
100
101 pub fn validate(&self, offset: u64) -> Result<()> {
103 if self.magic != WAL_MAGIC {
104 return Err(WalError::InvalidMagic {
105 offset,
106 expected: WAL_MAGIC,
107 actual: self.magic,
108 });
109 }
110 if self.format_version > WAL_FORMAT_VERSION {
111 return Err(WalError::UnsupportedVersion {
112 version: self.format_version,
113 supported: WAL_FORMAT_VERSION,
114 });
115 }
116 Ok(())
117 }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128#[repr(u16)]
129pub enum RecordType {
130 Noop = 0,
132
133 Put = 1 | 0x8000,
135
136 Delete = 2 | 0x8000,
138
139 VectorPut = 10 | 0x8000,
141
142 VectorDelete = 11 | 0x8000,
144
145 VectorParams = 12 | 0x8000,
147
148 CrdtDelta = 20 | 0x8000,
150
151 TimeseriesBatch = 30,
153
154 LogBatch = 31,
156
157 Transaction = 50 | 0x8000,
161
162 Checkpoint = 100 | 0x8000,
164}
165
166impl RecordType {
167 pub fn is_required(raw: u16) -> bool {
169 raw & 0x8000 != 0
170 }
171
172 pub fn from_raw(raw: u16) -> Option<Self> {
174 match raw {
175 0 => Some(Self::Noop),
176 x if x == 1 | 0x8000 => Some(Self::Put),
177 x if x == 2 | 0x8000 => Some(Self::Delete),
178 x if x == 10 | 0x8000 => Some(Self::VectorPut),
179 x if x == 11 | 0x8000 => Some(Self::VectorDelete),
180 x if x == 12 | 0x8000 => Some(Self::VectorParams),
181 x if x == 20 | 0x8000 => Some(Self::CrdtDelta),
182 x if x == 50 | 0x8000 => Some(Self::Transaction),
183 30 => Some(Self::TimeseriesBatch),
184 31 => Some(Self::LogBatch),
185 x if x == 100 | 0x8000 => Some(Self::Checkpoint),
186 _ => None,
187 }
188 }
189}
190
191#[derive(Debug, Clone)]
193pub struct WalRecord {
194 pub header: RecordHeader,
195 pub payload: Vec<u8>,
196}
197
198impl WalRecord {
199 pub fn new(
204 record_type: u16,
205 lsn: u64,
206 tenant_id: u32,
207 vshard_id: u16,
208 payload: Vec<u8>,
209 encryption_key: Option<&crate::crypto::WalEncryptionKey>,
210 ) -> Result<Self> {
211 if payload.len() > MAX_WAL_PAYLOAD_SIZE {
212 return Err(WalError::PayloadTooLarge {
213 size: payload.len(),
214 max: MAX_WAL_PAYLOAD_SIZE,
215 });
216 }
217
218 let (final_payload, encrypted) = if let Some(key) = encryption_key {
220 let temp_header = RecordHeader {
222 magic: WAL_MAGIC,
223 format_version: WAL_FORMAT_VERSION,
224 record_type,
225 lsn,
226 tenant_id,
227 vshard_id,
228 payload_len: 0, crc32c: 0,
230 };
231 let header_bytes = temp_header.to_bytes();
232 let ciphertext = key.encrypt(lsn, &header_bytes, &payload)?;
233 (ciphertext, true)
234 } else {
235 (payload, false)
236 };
237
238 let record_type = if encrypted {
240 record_type | ENCRYPTED_FLAG
241 } else {
242 record_type
243 };
244
245 let mut header = RecordHeader {
246 magic: WAL_MAGIC,
247 format_version: WAL_FORMAT_VERSION,
248 record_type,
249 lsn,
250 tenant_id,
251 vshard_id,
252 payload_len: final_payload.len() as u32,
253 crc32c: 0,
254 };
255
256 header.crc32c = header.compute_checksum(&final_payload);
257
258 Ok(Self {
259 header,
260 payload: final_payload,
261 })
262 }
263
264 pub fn decrypt_payload(
268 &self,
269 encryption_key: Option<&crate::crypto::WalEncryptionKey>,
270 ) -> Result<Vec<u8>> {
271 if !self.is_encrypted() {
272 return Ok(self.payload.clone());
273 }
274
275 let key = encryption_key.ok_or_else(|| WalError::EncryptionError {
276 detail: "record is encrypted but no decryption key provided".into(),
277 })?;
278
279 let mut aad_header = self.header;
282 aad_header.record_type &= !ENCRYPTED_FLAG;
283 aad_header.payload_len = 0;
284 aad_header.crc32c = 0;
285 let header_bytes = aad_header.to_bytes();
286
287 key.decrypt(self.header.lsn, &header_bytes, &self.payload)
288 }
289
290 pub fn decrypt_payload_ring(&self, ring: Option<&crate::crypto::KeyRing>) -> Result<Vec<u8>> {
295 if !self.is_encrypted() {
296 return Ok(self.payload.clone());
297 }
298
299 let ring = ring.ok_or_else(|| WalError::EncryptionError {
300 detail: "record is encrypted but no decryption key ring provided".into(),
301 })?;
302
303 let mut aad_header = self.header;
304 aad_header.record_type &= !ENCRYPTED_FLAG;
305 aad_header.payload_len = 0;
306 aad_header.crc32c = 0;
307 let header_bytes = aad_header.to_bytes();
308
309 ring.decrypt(self.header.lsn, &header_bytes, &self.payload)
310 }
311
312 pub fn is_encrypted(&self) -> bool {
314 self.header.record_type & ENCRYPTED_FLAG != 0
315 }
316
317 pub fn logical_record_type(&self) -> u16 {
319 self.header.record_type & !ENCRYPTED_FLAG
320 }
321
322 pub fn verify_checksum(&self) -> Result<()> {
324 let expected = self.header.crc32c;
325 let actual = self.header.compute_checksum(&self.payload);
326 if expected != actual {
327 return Err(WalError::ChecksumMismatch {
328 lsn: self.header.lsn,
329 expected,
330 actual,
331 });
332 }
333 Ok(())
334 }
335
336 pub fn wire_size(&self) -> usize {
338 HEADER_SIZE + self.payload.len()
339 }
340}
341
342pub const ENCRYPTED_FLAG: u16 = 0x4000;
345
346#[cfg(test)]
347mod tests {
348 use super::*;
349
350 #[test]
351 fn header_roundtrip() {
352 let header = RecordHeader {
353 magic: WAL_MAGIC,
354 format_version: WAL_FORMAT_VERSION,
355 record_type: RecordType::Put as u16,
356 lsn: 42,
357 tenant_id: 7,
358 vshard_id: 3,
359 payload_len: 100,
360 crc32c: 0xDEAD_BEEF,
361 };
362
363 let bytes = header.to_bytes();
364 let decoded = RecordHeader::from_bytes(&bytes);
365 assert_eq!(header, decoded);
366 }
367
368 #[test]
369 fn checksum_roundtrip() {
370 let payload = b"hello nodedb";
371 let record =
372 WalRecord::new(RecordType::Put as u16, 1, 0, 0, payload.to_vec(), None).unwrap();
373
374 record.verify_checksum().unwrap();
375 }
376
377 #[test]
378 fn checksum_detects_corruption() {
379 let payload = b"hello nodedb";
380 let mut record =
381 WalRecord::new(RecordType::Put as u16, 1, 0, 0, payload.to_vec(), None).unwrap();
382
383 record.payload[0] ^= 0xFF;
385
386 assert!(matches!(
387 record.verify_checksum(),
388 Err(WalError::ChecksumMismatch { .. })
389 ));
390 }
391
392 #[test]
393 fn invalid_magic_detected() {
394 let header = RecordHeader {
395 magic: 0xBAD0_F00D,
396 format_version: WAL_FORMAT_VERSION,
397 record_type: 0,
398 lsn: 0,
399 tenant_id: 0,
400 vshard_id: 0,
401 payload_len: 0,
402 crc32c: 0,
403 };
404
405 assert!(matches!(
406 header.validate(0),
407 Err(WalError::InvalidMagic { .. })
408 ));
409 }
410
411 #[test]
412 fn payload_too_large_rejected() {
413 let big_payload = vec![0u8; MAX_WAL_PAYLOAD_SIZE + 1];
414 assert!(matches!(
415 WalRecord::new(RecordType::Put as u16, 1, 0, 0, big_payload, None),
416 Err(WalError::PayloadTooLarge { .. })
417 ));
418 }
419
420 #[test]
421 fn record_type_required_flag() {
422 assert!(RecordType::is_required(RecordType::Put as u16));
423 assert!(RecordType::is_required(RecordType::Delete as u16));
424 assert!(RecordType::is_required(RecordType::Checkpoint as u16));
425 assert!(!RecordType::is_required(RecordType::Noop as u16));
426 assert!(!RecordType::is_required(RecordType::TimeseriesBatch as u16));
427 assert!(!RecordType::is_required(RecordType::LogBatch as u16));
428 }
429}