Skip to main content

link_cli/transactions/
migration_state.rs

1//! Migration state shares the row transaction's durable commit decision.
2
3use super::*;
4
5const PREFIX: &str = "__transactions:migrations:";
6const CHECKPOINT: &str = "checkpoint";
7
8impl<T, S, L> GenericTransactionsDecorator<T, S, L>
9where
10    T: LinkReference,
11    S: LinksStorage<T>,
12    L: TransitionLogStore,
13{
14    /// The latest committed migration state, independent of row retention.
15    pub fn migration_state(&mut self) -> Result<Option<String>, LinkError> {
16        let mut state = None;
17        for entry in self.log_store.read_log_entries()? {
18            let Some((owner, payload)) = entry
19                .strip_prefix(PREFIX)
20                .and_then(|entry| entry.split_once(':'))
21            else {
22                continue;
23            };
24            if owner == CHECKPOINT
25                || u128::from_str_radix(owner, 16).is_ok_and(|id| self.committed.contains(&id))
26            {
27                state = Some(payload.to_owned());
28            }
29        }
30        Ok(state)
31    }
32
33    /// Attaches a serialized state to the currently open transaction.
34    pub fn stage_migration_state(&mut self, state: &str) -> Result<(), LinkError> {
35        self.ensure_write_allowed()?;
36        let owner = self.current.as_ref().ok_or_else(|| {
37            LinkError::Transaction("Migration state requires an open transaction.".into())
38        })?;
39        if state.contains(['\n', '\r', '\0']) {
40            return Err(LinkError::InvalidFormat(
41                "Invalid migration state line.".into(),
42            ));
43        }
44        self.append_journal_entry(&format!("{PREFIX}{:032x}:{state}", owner.id))
45    }
46
47    pub(super) fn compact_migration_state(&mut self) -> Result<Option<String>, LinkError> {
48        Ok(self
49            .migration_state()?
50            .map(|state| format!("{PREFIX}{CHECKPOINT}:{state}")))
51    }
52}