Skip to main content

forgedb_wal/
entry.rs

1//! WAL Entry types and serialization
2
3/// WAL operation types.
4///
5/// Only the `Raw` variant remains. The WAL stores opaque bytes and never
6/// interprets their content. The (generated) caller owns the encoding; the WAL
7/// provides framing, CRC integrity, and torn-tail crash safety.
8#[derive(Debug, Clone, PartialEq)]
9pub enum WalOperation {
10    /// Opaque, schema-agnostic payload. The WAL stores and returns these bytes
11    /// verbatim and never interprets them — the (generated) caller owns the
12    /// encoding. This is the identity-preserving write path.
13    Raw { payload: Vec<u8> },
14}
15
16impl WalOperation {
17    /// Get the operation type byte used in the on-disk framing.
18    pub fn type_byte(&self) -> u8 {
19        match self {
20            WalOperation::Raw { .. } => 0x20,
21        }
22    }
23
24    /// Serialize the operation payload to bytes (excluding the type byte and
25    /// model-name framing, which are written by [`WalEntry::to_bytes`]).
26    pub fn to_bytes(&self) -> Vec<u8> {
27        match self {
28            WalOperation::Raw { payload } => {
29                // 4-byte little-endian length prefix so `from_bytes` can
30                // reconstruct the exact slice even if the entry data section
31                // grows in a future format revision.
32                let mut bytes = Vec::with_capacity(4 + payload.len());
33                bytes.extend_from_slice(&(payload.len() as u32).to_le_bytes());
34                bytes.extend_from_slice(payload);
35                bytes
36            }
37        }
38    }
39
40    /// Deserialize an operation from `(type_byte, payload_bytes)`.
41    pub fn from_bytes(type_byte: u8, bytes: &[u8]) -> std::io::Result<Self> {
42        use std::io::{Error, ErrorKind};
43
44        match type_byte {
45            0x20 => {
46                if bytes.len() < 4 {
47                    return Err(Error::new(
48                        ErrorKind::UnexpectedEof,
49                        "Incomplete Raw payload length",
50                    ));
51                }
52                let payload_len =
53                    u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
54                if bytes.len() < 4 + payload_len {
55                    return Err(Error::new(
56                        ErrorKind::UnexpectedEof,
57                        "Incomplete Raw payload data",
58                    ));
59                }
60                let payload = bytes[4..4 + payload_len].to_vec();
61                Ok(WalOperation::Raw { payload })
62            }
63            _ => Err(Error::new(
64                ErrorKind::InvalidData,
65                format!("Unknown operation type: 0x{:02x}", type_byte),
66            )),
67        }
68    }
69}
70
71/// A complete WAL entry: a model-name routing tag plus an operation.
72///
73/// The `model_name` field is an opaque string stored verbatim in the entry
74/// header. The WAL never interprets it. Generated code uses it to route
75/// replayed entries back to the correct model; ForgeDB itself never branches
76/// on it.
77#[derive(Debug, Clone, PartialEq)]
78pub struct WalEntry {
79    pub model_name: String,
80    pub operation: WalOperation,
81}
82
83impl WalEntry {
84    /// Create a raw opaque-bytes entry.
85    ///
86    /// `model_name` is an opaque routing/debug tag stored verbatim in the
87    /// entry header. The WAL never interprets it. The generated caller uses it
88    /// to identify which model a replayed entry belongs to.
89    ///
90    /// `payload` is stored verbatim and returned byte-identical on replay. The
91    /// WAL neither inspects nor encodes the payload — the caller owns the
92    /// encoding entirely.
93    pub fn raw(model_name: impl Into<String>, payload: Vec<u8>) -> Self {
94        WalEntry {
95            model_name: model_name.into(),
96            operation: WalOperation::Raw { payload },
97        }
98    }
99
100    /// Serialize the entry to bytes including the CRC32 checksum.
101    ///
102    /// Wire format (see `lib.rs` for the full layout comment):
103    /// `[4: total_length][1: op_type][2: model_name_len][N: model_name][M: op_data][4: crc32]`
104    pub fn to_bytes(&self) -> Vec<u8> {
105        let mut bytes = Vec::new();
106
107        // Operation type byte
108        bytes.push(self.operation.type_byte());
109
110        // Model name
111        let model_bytes = self.model_name.as_bytes();
112        bytes.extend_from_slice(&(model_bytes.len() as u16).to_le_bytes());
113        bytes.extend_from_slice(model_bytes);
114
115        // Operation data
116        bytes.extend_from_slice(&self.operation.to_bytes());
117
118        // CRC32 over everything so far
119        let checksum = crc32fast::hash(&bytes);
120
121        // Prepend total length (everything after this 4-byte field)
122        let total_length = bytes.len() + 4; // +4 for checksum
123        let mut result = Vec::with_capacity(4 + total_length);
124        result.extend_from_slice(&(total_length as u32).to_le_bytes());
125        result.extend_from_slice(&bytes);
126        result.extend_from_slice(&checksum.to_le_bytes());
127
128        result
129    }
130
131    /// Deserialize an entry from a byte slice.
132    ///
133    /// Returns `(entry, bytes_consumed)` on success. Returns an error on
134    /// truncation (torn tail) or CRC mismatch.
135    pub fn from_bytes(bytes: &[u8]) -> std::io::Result<(Self, usize)> {
136        use std::io::{Error, ErrorKind};
137
138        if bytes.len() < 4 {
139            return Err(Error::new(
140                ErrorKind::UnexpectedEof,
141                "Incomplete entry length",
142            ));
143        }
144
145        let total_length = u32::from_le_bytes(bytes[0..4].try_into().unwrap()) as usize;
146
147        // A valid entry always carries at least a 4-byte trailing checksum. A
148        // corrupt length prefix reporting fewer than 4 bytes would otherwise
149        // underflow `entry_bytes.len() - 4` below and panic.
150        if total_length < 4 {
151            return Err(Error::new(
152                ErrorKind::InvalidData,
153                "Entry length too short to contain a checksum",
154            ));
155        }
156
157        if bytes.len() < 4 + total_length {
158            return Err(Error::new(ErrorKind::UnexpectedEof, "Incomplete entry"));
159        }
160
161        let entry_bytes = &bytes[4..4 + total_length];
162
163        // Verify CRC32
164        let data_bytes = &entry_bytes[..entry_bytes.len() - 4];
165        let stored_checksum =
166            u32::from_le_bytes(entry_bytes[entry_bytes.len() - 4..].try_into().unwrap());
167        let calculated_checksum = crc32fast::hash(data_bytes);
168
169        if stored_checksum != calculated_checksum {
170            return Err(Error::new(
171                ErrorKind::InvalidData,
172                "Checksum mismatch - entry corrupted",
173            ));
174        }
175
176        // Parse inner fields
177        let mut offset = 0;
178
179        let op_type = data_bytes[offset];
180        offset += 1;
181
182        if data_bytes.len() < offset + 2 {
183            return Err(Error::new(
184                ErrorKind::UnexpectedEof,
185                "Incomplete model name length",
186            ));
187        }
188
189        let model_name_len =
190            u16::from_le_bytes(data_bytes[offset..offset + 2].try_into().unwrap()) as usize;
191        offset += 2;
192
193        if data_bytes.len() < offset + model_name_len {
194            return Err(Error::new(
195                ErrorKind::UnexpectedEof,
196                "Incomplete model name",
197            ));
198        }
199
200        let model_name = String::from_utf8(data_bytes[offset..offset + model_name_len].to_vec())
201            .map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
202        offset += model_name_len;
203
204        let operation = WalOperation::from_bytes(op_type, &data_bytes[offset..])?;
205
206        Ok((WalEntry { model_name, operation }, 4 + total_length))
207    }
208}