Skip to main content

kmp_adapter_embedded/adapter/
replay.rs

1use kmp_domain::{ContextUpdatedEvent, PortError, ProjectionMutation};
2
3use super::engine::Table;
4use super::projection_write::apply_mutations_in_transaction;
5use super::store::EmbeddedKernelStore;
6
7/// Outcome of a projection rebuild from the append-only event log.
8#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct ProjectionRebuildReport {
10    pub events_replayed: u64,
11    pub mutations_applied: u64,
12}
13
14impl EmbeddedKernelStore {
15    /// Drops every projection table and rebuilds them by replaying the event
16    /// log in sequence order — the recovery and migration story in one.
17    ///
18    /// The mutation derivation is injected so this adapter stays free of
19    /// application-layer dependencies; the composition root passes
20    /// `kmp_application::projection_mutations_for_context_event`.
21    /// The whole rebuild is one transaction: a crash mid-rebuild leaves the
22    /// previous projections intact.
23    pub async fn rebuild_projections<F>(
24        &self,
25        derive: F,
26    ) -> Result<ProjectionRebuildReport, PortError>
27    where
28        F: Fn(&ContextUpdatedEvent) -> Result<Vec<ProjectionMutation>, PortError> + Send + 'static,
29    {
30        let events = self.run(EmbeddedKernelStore::read_event_log).await?;
31
32        let mut mutations = Vec::new();
33        for event in &events {
34            mutations.extend(derive(event)?);
35        }
36        let events_replayed = events.len() as u64;
37
38        self.run(move |store| {
39            let mut tx = store.begin_write()?;
40            tx.clear(Table::Nodes)?;
41            tx.clear(Table::Relations)?;
42            tx.clear(Table::RelationsByTarget)?;
43            tx.clear(Table::Details)?;
44            tx.clear(Table::Anchors)?;
45
46            let mutations_applied = apply_mutations_in_transaction(tx.as_mut(), mutations)?;
47            tx.commit()?;
48
49            Ok(ProjectionRebuildReport {
50                events_replayed,
51                mutations_applied,
52            })
53        })
54        .await
55    }
56}