Skip to main content

spanfold/
changelog.rs

1use std::collections::BTreeMap;
2
3use serde::{Deserialize, Serialize};
4
5use crate::{ComparisonFinality, ComparisonRowFinality};
6
7/// Kind of state transition represented by a changelog entry.
8#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
9pub enum ComparisonChangeKind {
10    /// A row was added to the snapshot.
11    Added,
12    /// A row remained present but its metadata changed.
13    Updated,
14    /// A row was removed from the snapshot.
15    Retracted,
16}
17
18/// Deterministic changelog entry between row-finality snapshots.
19#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
20pub struct ComparisonChangelogEntry {
21    /// Row family.
22    #[serde(rename = "rowType")]
23    pub row_type: String,
24    /// Row identifier.
25    #[serde(rename = "rowId")]
26    pub row_id: String,
27    /// Metadata version.
28    pub version: u32,
29    /// Kind of change represented by this entry.
30    #[serde(rename = "changeKind")]
31    pub change_kind: ComparisonChangeKind,
32    /// Resulting row finality. `None` is used for retractions.
33    pub finality: Option<ComparisonFinality>,
34    /// Prior row identifier superseded by this entry, when any.
35    #[serde(rename = "supersedesRowId")]
36    pub supersedes_row_id: Option<String>,
37    /// Human-readable reason.
38    pub reason: String,
39}
40
41/// Creates a changelog between row-finality snapshots.
42#[must_use]
43pub fn create_changelog(
44    previous: &[ComparisonRowFinality],
45    current: &[ComparisonRowFinality],
46) -> Vec<ComparisonChangelogEntry> {
47    let previous_by_key = previous
48        .iter()
49        .map(|row| ((row.row_type.clone(), row.row_id.clone()), row))
50        .collect::<BTreeMap<_, _>>();
51    let current_by_key = current
52        .iter()
53        .map(|row| ((row.row_type.clone(), row.row_id.clone()), row))
54        .collect::<BTreeMap<_, _>>();
55    let mut entries = Vec::new();
56
57    for ((row_type, row_id), current_row) in &current_by_key {
58        if let Some(previous_row) = previous_by_key.get(&(row_type.clone(), row_id.clone())) {
59            if previous_row.finality == current_row.finality
60                && previous_row.reason == current_row.reason
61            {
62                continue;
63            }
64            entries.push(ComparisonChangelogEntry {
65                row_type: row_type.clone(),
66                row_id: row_id.clone(),
67                version: previous_row.version + 1,
68                change_kind: ComparisonChangeKind::Updated,
69                finality: Some(current_row.finality.clone()),
70                supersedes_row_id: current_row
71                    .supersedes_row_id
72                    .clone()
73                    .or_else(|| Some(previous_row.row_id.clone())),
74                reason: current_row.reason.clone(),
75            });
76            continue;
77        }
78
79        entries.push(ComparisonChangelogEntry {
80            row_type: row_type.clone(),
81            row_id: row_id.clone(),
82            version: current_row.version,
83            change_kind: ComparisonChangeKind::Added,
84            finality: Some(current_row.finality.clone()),
85            supersedes_row_id: current_row.supersedes_row_id.clone(),
86            reason: current_row.reason.clone(),
87        });
88    }
89
90    for ((row_type, row_id), previous_row) in &previous_by_key {
91        if current_by_key.contains_key(&(row_type.clone(), row_id.clone())) {
92            continue;
93        }
94        entries.push(ComparisonChangelogEntry {
95            row_type: row_type.clone(),
96            row_id: row_id.clone(),
97            version: previous_row.version + 1,
98            change_kind: ComparisonChangeKind::Retracted,
99            finality: None,
100            supersedes_row_id: Some(previous_row.row_id.clone()),
101            reason: "Row was not emitted by the current snapshot.".to_owned(),
102        });
103    }
104
105    entries
106}
107
108/// Replays a changelog over a previous row-finality snapshot.
109#[must_use]
110pub fn replay_changelog(
111    previous: &[ComparisonRowFinality],
112    entries: &[ComparisonChangelogEntry],
113) -> Vec<ComparisonRowFinality> {
114    let mut active = previous
115        .iter()
116        .map(|row| ((row.row_type.clone(), row.row_id.clone()), row.clone()))
117        .collect::<BTreeMap<_, _>>();
118
119    for entry in entries {
120        let key = (entry.row_type.clone(), entry.row_id.clone());
121        match entry.change_kind {
122            ComparisonChangeKind::Retracted => {
123                active.remove(&key);
124            }
125            ComparisonChangeKind::Added | ComparisonChangeKind::Updated => {
126                let Some(finality) = entry.finality.clone() else {
127                    continue;
128                };
129                active.insert(
130                    key,
131                    ComparisonRowFinality {
132                        row_type: entry.row_type.clone(),
133                        row_id: entry.row_id.clone(),
134                        finality,
135                        reason: entry.reason.clone(),
136                        version: entry.version,
137                        supersedes_row_id: entry.supersedes_row_id.clone(),
138                    },
139                );
140            }
141        }
142    }
143
144    active.into_values().collect()
145}
146
147#[cfg(test)]
148mod tests {
149    use super::*;
150
151    #[test]
152    fn changelog_replays_revisions_and_retractions() {
153        let previous = vec![ComparisonRowFinality {
154            row_type: "residual".to_owned(),
155            row_id: "residual[0]".to_owned(),
156            finality: ComparisonFinality::Provisional,
157            reason: "depends on an open window clipped to the evaluation horizon".to_owned(),
158            version: 1,
159            supersedes_row_id: None,
160        }];
161        let current = vec![ComparisonRowFinality {
162            row_type: "residual".to_owned(),
163            row_id: "residual[0]".to_owned(),
164            finality: ComparisonFinality::Final,
165            reason: "derived from closed windows".to_owned(),
166            version: 1,
167            supersedes_row_id: None,
168        }];
169
170        let entries = create_changelog(&previous, &current);
171        assert_eq!(entries.len(), 1);
172        assert_eq!(entries[0].change_kind, ComparisonChangeKind::Updated);
173        assert_eq!(entries[0].finality, Some(ComparisonFinality::Final));
174
175        let replayed = replay_changelog(&previous, &entries);
176        assert_eq!(replayed.len(), 1);
177        assert_eq!(replayed[0].finality, ComparisonFinality::Final);
178        assert_eq!(replayed[0].version, 2);
179    }
180
181    #[test]
182    fn changelog_preserves_resulting_finality_for_every_update() {
183        let previous = vec![ComparisonRowFinality {
184            row_type: "overlap".to_owned(),
185            row_id: "overlap[0]".to_owned(),
186            finality: ComparisonFinality::Final,
187            reason: "closed".to_owned(),
188            version: 3,
189            supersedes_row_id: None,
190        }];
191        let current = vec![ComparisonRowFinality {
192            row_type: "overlap".to_owned(),
193            row_id: "overlap[0]".to_owned(),
194            finality: ComparisonFinality::Provisional,
195            reason: "reopened by a live horizon".to_owned(),
196            version: 3,
197            supersedes_row_id: None,
198        }];
199
200        let entries = create_changelog(&previous, &current);
201        assert_eq!(entries[0].change_kind, ComparisonChangeKind::Updated);
202        assert_eq!(entries[0].finality, Some(ComparisonFinality::Provisional));
203        let replayed = replay_changelog(&previous, &entries);
204        assert_eq!(replayed[0].finality, ComparisonFinality::Provisional);
205        assert_eq!(replayed[0].reason, current[0].reason);
206        assert_eq!(replayed[0].version, 4);
207    }
208}