Skip to main content

relate_engine_api/
commit.rs

1//! One durable commit. The JSON field names match the historical log record,
2//! so a file written before this type moved still decodes.
3
4use serde::{Deserialize, Serialize};
5
6use crate::redo::RedoOp;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct CommitRecord {
10    pub lsn: u64,
11    pub commit_ts: u64,
12    pub ops: Vec<RedoOp>,
13}
14
15/// The record's serialized shape, spelled once beside the type whose field
16/// names it mirrors. The WAL's encode-once path (ADR-0558) writes the header
17/// by hand around an already-serialized `ops` array; these are the
18/// spellings it consults, and the test below pins them to what serde emits.
19impl CommitRecord {
20    /// The opening brace and the `lsn` key.
21    pub const LSN_KEY: &'static str = "{\"lsn\":";
22    /// The separator and the `commit_ts` key.
23    pub const COMMIT_TS_KEY: &'static str = ",\"commit_ts\":";
24    /// The separator and the `ops` key; the array follows.
25    pub const OPS_KEY: &'static str = ",\"ops\":";
26    /// Decimal digits of `u64::MAX`: the widest `lsn` or `commit_ts`.
27    pub const U64_DECIMAL_MAX: usize = 20;
28    /// The widest header the record can carry: the three key spellings and
29    /// two maximum-width unsigned decimals.
30    pub const HEADER_MAX: usize = Self::LSN_KEY.len()
31        + Self::COMMIT_TS_KEY.len()
32        + Self::OPS_KEY.len()
33        + 2 * Self::U64_DECIMAL_MAX;
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn the_header_spellings_match_the_serialized_field_names() {
42        let record = CommitRecord {
43            lsn: u64::MAX,
44            commit_ts: u64::MAX,
45            ops: Vec::new(),
46        };
47        let json = serde_json::to_string(&record).unwrap();
48        let header = format!(
49            "{}{}{}{}{}",
50            CommitRecord::LSN_KEY,
51            u64::MAX,
52            CommitRecord::COMMIT_TS_KEY,
53            u64::MAX,
54            CommitRecord::OPS_KEY
55        );
56        assert_eq!(json, format!("{header}[]}}"));
57        assert_eq!(header.len(), CommitRecord::HEADER_MAX);
58        assert_eq!(u64::MAX.to_string().len(), CommitRecord::U64_DECIMAL_MAX);
59    }
60}