interplane.Get Omega
Read in your language

synapse

A component of the AienOS ecosystem.

Brought by drakestapleton

branch main Branches Tags History

synapse / crates / synapse-coord / src / board / frame.rs

403 lines · 13050 bytes Raw Blame History
1//! On-disk codec of the board: CRC-32C, the journal frame, the fixed-width table entry, the
2//! compact one-line JSON printer, and the event body <-> [`J`] mapping.
3//!
4//! Journal frame: `u32 len (LE) | u32 crc32c(body) (LE) | body`, where `body` is one compact
5//! JSON object followed by `\n`. A frame whose length or checksum does not verify is never
6//! returned (see the torn-tail rule in `journal.rs`).
7
8use super::{BoardError, BoardId, Event, Kind, Ref, RefKind, PROTOCOL};
9use crate::json::{self, J};
10
11/// Bytes before the body: length and checksum.
12pub(crate) const FRAME_HEADER: u64 = 8;
13/// Largest frame body accepted on write or read (64 KiB). The field limits keep a real event
14/// far below this; the cap bounds what a hostile length field can make a reader allocate.
15pub const MAX_FRAME_BYTES: u32 = 64 * 1024;
16/// Fixed width of one `journal.idx` table entry.
17pub(crate) const ENTRY_BYTES: u64 = 64;
18/// Fixed width of one `topics/*.idx` / `inbox/*.idx` entry (a little-endian event id).
19pub(crate) const ID_BYTES: u64 = 8;
20
21const fn crc_table() -> [u32; 256] {
22 let mut t = [0u32; 256];
23 let mut i = 0;
24 while i < 256 {
25 let mut c = i as u32;
26 let mut k = 0;
27 while k < 8 {
28 c = if c & 1 != 0 {
29 (c >> 1) ^ 0x82F6_3B78
30 } else {
31 c >> 1
32 };
33 k += 1;
34 }
35 t[i] = c;
36 i += 1;
37 }
38 t
39}
40static CRC: [u32; 256] = crc_table();
41
42/// CRC-32C (Castagnoli), the checksum of every frame body and table entry.
43pub fn crc32c(data: &[u8]) -> u32 {
44 let mut c = !0u32;
45 for &b in data {
46 c = CRC[((c ^ b as u32) & 0xff) as usize] ^ (c >> 8);
47 }
48 !c
49}
50
51/// FNV-1a 64 over a domain byte and the key. Only a filter: every hit is verified against
52/// the real event, so a collision costs one extra frame read, never a wrong delivery.
53/// Never 0 (0 means "no key").
54pub(crate) fn key_hash(domain: u8, key: &[u8]) -> u64 {
55 let mut h: u64 = 0xcbf2_9ce4_8422_2325;
56 for &b in std::iter::once(&domain).chain(key) {
57 h ^= b as u64;
58 h = h.wrapping_mul(0x0000_0100_0000_01b3);
59 }
60 h.max(1)
61}
62pub(crate) const H_TOPIC: u8 = b't';
63pub(crate) const H_THREAD: u8 = b'h';
64pub(crate) const H_IDEM: u8 = b'i';
65
66/// `len | crc | body`.
67pub(crate) fn encode_frame(body: &[u8]) -> Vec<u8> {
68 let mut f = Vec::with_capacity(body.len() + FRAME_HEADER as usize);
69 f.extend_from_slice(&(body.len() as u32).to_le_bytes());
70 f.extend_from_slice(&crc32c(body).to_le_bytes());
71 f.extend_from_slice(body);
72 f
73}
74
75/// One `journal.idx` entry: where event `id` lives and the filter keys of its body.
76#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub(crate) struct Entry {
78 pub id: u64,
79 pub offset: u64,
80 pub len: u32,
81 pub crc: u32,
82 pub topic_h: u64,
83 pub thread_h: u64,
84 pub idem_h: u64,
85}
86
87impl Entry {
88 pub fn encode(&self) -> [u8; ENTRY_BYTES as usize] {
89 let mut b = [0u8; ENTRY_BYTES as usize];
90 b[0..8].copy_from_slice(&self.id.to_le_bytes());
91 b[8..16].copy_from_slice(&self.offset.to_le_bytes());
92 b[16..20].copy_from_slice(&self.len.to_le_bytes());
93 b[20..24].copy_from_slice(&self.crc.to_le_bytes());
94 b[24..32].copy_from_slice(&self.topic_h.to_le_bytes());
95 b[32..40].copy_from_slice(&self.thread_h.to_le_bytes());
96 b[40..48].copy_from_slice(&self.idem_h.to_le_bytes());
97 let c = crc32c(&b[..60]);
98 b[60..64].copy_from_slice(&c.to_le_bytes());
99 b
100 }
101 /// `None` when the entry checksum or the reserved bytes do not verify.
102 pub fn decode(b: &[u8]) -> Option<Entry> {
103 if b.len() != ENTRY_BYTES as usize || b[48..60].iter().any(|&x| x != 0) {
104 return None;
105 }
106 let u64_at = |i: usize| u64::from_le_bytes(b[i..i + 8].try_into().unwrap_or([0; 8]));
107 let u32_at = |i: usize| u32::from_le_bytes(b[i..i + 4].try_into().unwrap_or([0; 4]));
108 if u32_at(60) != crc32c(&b[..60]) {
109 return None;
110 }
111 Some(Entry {
112 id: u64_at(0),
113 offset: u64_at(8),
114 len: u32_at(16),
115 crc: u32_at(20),
116 topic_h: u64_at(24),
117 thread_h: u64_at(32),
118 idem_h: u64_at(40),
119 })
120 }
121 pub fn frame_end(&self) -> u64 {
122 self.offset + FRAME_HEADER + self.len as u64
123 }
124}
125
126/// JSON string escape for the one-line form (same escapes as `json::J::dump`).
127fn escape(b: &mut Vec<u8>, s: &[u8]) {
128 b.push(b'"');
129 for &c in s {
130 match c {
131 b'"' => b.extend_from_slice(b"\\\""),
132 b'\\' => b.extend_from_slice(b"\\\\"),
133 b'\n' => b.extend_from_slice(b"\\n"),
134 b'\r' => b.extend_from_slice(b"\\r"),
135 b'\t' => b.extend_from_slice(b"\\t"),
136 0x08 => b.extend_from_slice(b"\\b"),
137 0x0c => b.extend_from_slice(b"\\f"),
138 0x7f => b.extend_from_slice(b"\\u007f"),
139 c if c < 0x20 => b.extend_from_slice(format!("\\u{c:04x}").as_bytes()),
140 c => b.push(c),
141 }
142 }
143 b.push(b'"');
144}
145
146/// One-line JSON (no whitespace) of a [`J`] value, without a trailing newline. This is the
147/// frame body format and the CLI machine output format.
148pub fn compact(j: &J) -> Vec<u8> {
149 let mut b = Vec::new();
150 compact_into(j, &mut b);
151 b
152}
153
154fn compact_into(j: &J, b: &mut Vec<u8>) {
155 match j {
156 J::Null => b.extend_from_slice(b"null"),
157 J::True => b.extend_from_slice(b"true"),
158 J::False => b.extend_from_slice(b"false"),
159 J::Num(t) => b.extend_from_slice(t),
160 J::Str(s) => escape(b, s),
161 J::Arr(a) => {
162 b.push(b'[');
163 for (i, v) in a.iter().enumerate() {
164 if i > 0 {
165 b.push(b',');
166 }
167 compact_into(v, b);
168 }
169 b.push(b']');
170 }
171 J::Obj(m) => {
172 b.push(b'{');
173 for (i, (k, v)) in m.iter().enumerate() {
174 if i > 0 {
175 b.push(b',');
176 }
177 escape(b, k);
178 b.push(b':');
179 compact_into(v, b);
180 }
181 b.push(b'}');
182 }
183 }
184}
185
186pub(crate) fn num_u64(x: u64) -> J {
187 J::Num(x.to_string().into_bytes())
188}
189
190/// A JSON number that is a plain non-negative decimal integer fitting `u64`.
191pub(crate) fn as_u64(j: Option<&J>) -> Option<u64> {
192 match j {
193 Some(J::Num(t)) if !t.is_empty() && t.len() <= 20 && t.iter().all(u8::is_ascii_digit) => {
194 std::str::from_utf8(t).ok()?.parse().ok()
195 }
196 _ => None,
197 }
198}
199
200fn as_i64(j: Option<&J>) -> Option<i64> {
201 match j {
202 Some(J::Num(t)) => {
203 let s = std::str::from_utf8(t).ok()?;
204 let digits = s.strip_prefix('-').unwrap_or(s);
205 if digits.is_empty() || !digits.bytes().all(|c| c.is_ascii_digit()) {
206 return None;
207 }
208 s.parse().ok()
209 }
210 _ => None,
211 }
212}
213
214pub(crate) fn as_string(j: Option<&J>) -> Option<String> {
215 match j {
216 Some(J::Str(s)) => String::from_utf8(s.clone()).ok(),
217 _ => None,
218 }
219}
220
221pub(crate) fn str_list(j: Option<&J>) -> Option<Vec<String>> {
222 match j {
223 Some(J::Arr(a)) => a.iter().map(|v| as_string(Some(v))).collect(),
224 _ => None,
225 }
226}
227
228pub(crate) fn j_list(v: &[String]) -> J {
229 J::Arr(v.iter().map(|s| J::str(s)).collect())
230}
231
232impl Event {
233 /// The event body as a [`J`] object, fields in protocol order (`v`, `id`, `from_tag`,
234 /// `from`, ...).
235 pub fn to_json(&self) -> J {
236 let mut e = J::obj();
237 e.set("v", J::str(PROTOCOL));
238 e.set("id", num_u64(self.id));
239 e.set("from_tag", J::str(&self.from_tag));
240 e.set("from", J::str(&self.from));
241 e.set("mission", J::str(&self.mission.to_hex()));
242 e.set("thread", J::str(&self.thread));
243 e.set("topic", J::str(&self.topic));
244 e.set("to", j_list(&self.to));
245 e.set("kind", J::str(self.kind.as_str()));
246 e.set(
247 "parent",
248 match self.parent {
249 Some(p) => num_u64(p),
250 None => J::Null,
251 },
252 );
253 e.set("ts", J::num(self.ts));
254 e.set("text", J::str(&self.text));
255 e.set(
256 "refs",
257 J::Arr(
258 self.refs
259 .iter()
260 .map(|r| {
261 let mut o = J::obj();
262 o.set("repo", J::str(&r.repo));
263 o.set("kind", J::str(r.kind.as_str()));
264 o.set("value", J::str(&r.value));
265 o
266 })
267 .collect(),
268 ),
269 );
270 e.set(
271 "idem",
272 match &self.idem {
273 Some(k) => J::str(k),
274 None => J::Null,
275 },
276 );
277 e
278 }
279
280 /// Strict parse of an event body. Every field limit is checked again: a journal is a
281 /// store file, so a planted body is refused the same way a bad post is.
282 pub fn from_json(j: &J) -> Result<Event, String> {
283 if !j.is_obj() {
284 return Err("body is not an object".into());
285 }
286 let v = as_string(j.get("v")).ok_or("no protocol version")?;
287 if v != PROTOCOL {
288 return Err(format!("protocol {v:?} is not {PROTOCOL}"));
289 }
290 let s = |k: &str| as_string(j.get(k)).ok_or(format!("field {k} missing or not a string"));
291 let mission_hex = s("mission")?;
292 let mission =
293 BoardId::parse_hex(&mission_hex).ok_or(format!("bad mission {mission_hex:?}"))?;
294 let kind_s = s("kind")?;
295 let refs = match j.get("refs") {
296 Some(J::Arr(a)) => a
297 .iter()
298 .map(|r| {
299 let rk = as_string(r.get("kind")).ok_or("ref kind")?;
300 Ok(Ref {
301 repo: as_string(r.get("repo")).ok_or("ref repo")?,
302 kind: RefKind::parse(&rk).ok_or(format!("bad ref kind {rk:?}"))?,
303 value: as_string(r.get("value")).ok_or("ref value")?,
304 })
305 })
306 .collect::<Result<Vec<_>, String>>()?,
307 _ => return Err("refs missing".into()),
308 };
309 let e = Event {
310 id: as_u64(j.get("id")).ok_or("bad id")?,
311 from_tag: s("from_tag")?,
312 from: s("from")?,
313 mission,
314 thread: s("thread")?,
315 topic: s("topic")?,
316 to: str_list(j.get("to")).ok_or("bad to list")?,
317 kind: Kind::parse(&kind_s).ok_or(format!("bad kind {kind_s:?}"))?,
318 parent: match j.get("parent") {
319 Some(J::Null) => None,
320 p => Some(as_u64(p).ok_or("bad parent")?),
321 },
322 ts: as_i64(j.get("ts")).ok_or("bad ts")?,
323 text: s("text")?,
324 refs,
325 idem: match j.get("idem") {
326 Some(J::Null) => None,
327 Some(J::Str(_)) => Some(s("idem")?),
328 _ => return Err("bad idem".into()),
329 },
330 };
331 super::validate_event_fields(&e).map_err(|err| err.to_string())?;
332 Ok(e)
333 }
334
335 /// The frame body bytes: one-line JSON plus `\n`.
336 pub(crate) fn body(&self) -> Vec<u8> {
337 let mut b = compact(&self.to_json());
338 b.push(b'\n');
339 b
340 }
341
342 /// Parse a verified frame body.
343 pub(crate) fn from_body(body: &[u8]) -> Result<Event, String> {
344 if body.last() != Some(&b'\n') {
345 return Err("body does not end with a newline".into());
346 }
347 let j = json::parse(body).ok_or("body is not JSON")?;
348 Event::from_json(&j)
349 }
350}
351
352/// Error helper: a refusal about a board file.
353pub(crate) fn corrupt(
354 path: &std::path::Path,
355 offset: u64,
356 reason: impl Into<String>,
357) -> BoardError {
358 BoardError::Corrupt {
359 path: path.to_path_buf(),
360 offset,
361 reason: reason.into(),
362 }
363}
364
365#[cfg(test)]
366mod tests {
367 use super::*;
368
369 #[test]
370 fn crc32c_known_vector() {
371 assert_eq!(crc32c(b"123456789"), 0xE306_9283);
372 assert_eq!(crc32c(b""), 0);
373 }
374
375 #[test]
376 fn entry_round_trip_and_tamper() {
377 let e = Entry {
378 id: 7,
379 offset: 1234,
380 len: 99,
381 crc: 5,
382 topic_h: 11,
383 thread_h: 12,
384 idem_h: 0,
385 };
386 let mut b = e.encode();
387 assert_eq!(Entry::decode(&b), Some(e));
388 b[3] ^= 1;
389 assert_eq!(Entry::decode(&b), None);
390 }
391
392 #[test]
393 fn compact_is_one_line() {
394 let mut j = J::obj();
395 j.set("a", J::str("x\ny\"\u{7f}"));
396 j.set("b", J::Arr(vec![J::num(1), J::Null]));
397 assert_eq!(
398 compact(&j),
399 br#"{"a":"x\ny\"\u007f","b":[1,null]}"#.to_vec()
400 );
401 assert_eq!(json::parse(&compact(&j)), Some(j));
402 }
403}