use std::collections::HashSet;
use doublets::data::LinkReference;
use super::types::{
LogRetentionPolicy, APPLIED_MARKER_PREFIX, COMMIT_MARKER_PREFIX, ROLLBACK_MARKER_PREFIX,
SEQUENCE_MARKER_PREFIX, TRANSITION_NAME_PREFIX,
};
use super::{GenericTransactionsDecorator, LinkError, LinksStorage, TransitionLogStore};
const COMPACTION_SLACK: usize = 256;
impl<T, S, L> GenericTransactionsDecorator<T, S, L>
where
T: LinkReference,
S: LinksStorage<T>,
L: TransitionLogStore,
{
pub(super) fn append_journal_entry(&mut self, entry: &str) -> Result<(), LinkError> {
self.journal_entries = self.journal_entries.saturating_add(1);
self.log_store.append_log_entry(entry)
}
pub fn journal_entry_count(&self) -> usize {
self.journal_entries
}
pub(super) fn compact_journal_if_needed(&mut self) -> Result<(), LinkError> {
if matches!(self.retention_policy, LogRetentionPolicy::Infinite)
|| !self.log_store.supports_compaction()
|| self.has_open_transaction()
{
return Ok(());
}
let live = self.log.len().saturating_mul(3).saturating_add(3);
if self.journal_entries <= live.saturating_mul(2).saturating_add(COMPACTION_SLACK) {
return Ok(());
}
let Some(entries) = self.compacted_journal() else {
return Ok(());
};
self.log_store.flush_log()?;
let before = self.journal_entries;
self.log_store.compact_log_entries(&entries)?;
self.journal_entries = entries.len();
if self.trace {
crate::diagnostics::stderr!(
"[Transactions] Compacted journal from {before} to {} entries.",
entries.len()
);
}
Ok(())
}
fn compacted_journal(&self) -> Option<Vec<String>> {
let mut owners = Vec::new();
let mut seen = HashSet::new();
for record in &self.log {
if seen.insert(record.transaction_id) {
owners.push(record.transaction_id);
}
}
let mut decisions = Vec::with_capacity(owners.len() + 1);
for owner in owners {
let prefix = if self.committed.contains(&owner) {
COMMIT_MARKER_PREFIX
} else if self.rolled_back.contains(&owner) {
ROLLBACK_MARKER_PREFIX
} else {
return None;
};
decisions.push(format!("{prefix}{owner:032x}"));
}
if let Some(last) = &self.last_decision {
if !decisions.contains(last) {
decisions.push(last.clone());
}
}
let mut entries = Vec::with_capacity(self.log.len() * 2 + decisions.len() + 2);
if self.sequence_counter > 0 {
entries.push(format!("{SEQUENCE_MARKER_PREFIX}{}", self.sequence_counter));
}
let applied_retained = self
.log
.iter()
.any(|record| record.sequence == self.applied_sequence);
if self.applied_sequence > 0 && !applied_retained {
entries.push(format!("{APPLIED_MARKER_PREFIX}{}", self.applied_sequence));
}
for record in &self.log {
entries.push(format!("{TRANSITION_NAME_PREFIX}{}", record.serialize()));
}
entries.extend(decisions);
for record in &self.log {
if self.applied.contains(&record.sequence) {
entries.push(format!("{APPLIED_MARKER_PREFIX}{}", record.sequence));
}
}
Some(entries)
}
}