kmp_adapter_embedded/adapter/
replay.rs1use kmp_domain::{ContextUpdatedEvent, PortError, ProjectionMutation};
2
3use super::engine::Table;
4use super::projection_write::apply_mutations_in_transaction;
5use super::store::EmbeddedKernelStore;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub struct ProjectionRebuildReport {
10 pub events_replayed: u64,
11 pub mutations_applied: u64,
12}
13
14impl EmbeddedKernelStore {
15 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}