use std::sync::{Arc, Mutex};
use codicil::{Codicil, LogId, Provenance, Seq};
use muniment::{Backend, Codec, SlotStore, StoreError};
use rkyv::{Archive, Deserialize, Serialize};
use super::Graph;
use super::capture::{CapturedDelta, replay_captured_deltas, replay_captured_deltas_onto};
use super::source_time::{SourceExtent, SourceTime};
pub const USER_AUTHOR: &str = "user";
#[derive(
Debug, Clone, PartialEq, Archive, Serialize, Deserialize, serde::Serialize, serde::Deserialize,
)]
pub struct AttributedDelta {
pub author: String,
pub delta: CapturedDelta,
}
#[derive(Clone, Debug)]
pub struct GraphJournal {
log: Codicil<AttributedDelta>,
author: String,
}
impl Default for GraphJournal {
fn default() -> Self {
Self {
log: Codicil::default(),
author: USER_AUTHOR.to_string(),
}
}
}
impl GraphJournal {
pub fn new() -> Self {
Self::default()
}
pub fn with_id(id: LogId) -> Self {
Self {
log: Codicil::with_id(id),
author: USER_AUTHOR.to_string(),
}
}
pub fn from_log(log: Codicil<AttributedDelta>) -> Self {
Self {
log,
author: USER_AUTHOR.to_string(),
}
}
pub fn author(&self) -> &str {
&self.author
}
pub fn set_author(&mut self, author: impl Into<String>) {
self.author = author.into();
}
pub fn record(&mut self, delta: CapturedDelta) -> Seq {
let author = self.author.clone();
self.record_as(author, delta)
}
pub fn record_as(&mut self, author: impl Into<String>, delta: CapturedDelta) -> Seq {
self.log.append(AttributedDelta {
author: author.into(),
delta,
})
}
pub fn log(&self) -> &Codicil<AttributedDelta> {
&self.log
}
pub fn entries(&self) -> &[AttributedDelta] {
self.log.entries()
}
pub fn len(&self) -> usize {
self.log.len()
}
pub fn is_empty(&self) -> bool {
self.log.is_empty()
}
pub fn next_seq(&self) -> Seq {
self.log.next_seq()
}
pub const fn earliest_cursor(&self) -> Seq {
Seq(0)
}
pub fn live_cursor(&self) -> Seq {
self.next_seq()
}
pub fn snapshot_at(&self, cursor: Seq) -> Option<Graph> {
let end = cursor.index();
(end <= self.log.len()).then(|| {
replay_captured_deltas(
self.log.entries()[..end]
.iter()
.map(|entry| entry.delta.clone()),
)
})
}
pub fn sequence_ticks(&self, max_points: usize) -> Vec<Seq> {
let live = self.live_cursor();
if max_points == 0 {
return Vec::new();
}
if max_points == 1 || live.0 == 0 {
return vec![live];
}
let points = max_points.min(live.0 as usize + 1);
let denominator = (points - 1) as u64;
(0..points)
.map(|index| Seq((index as u64 * live.0) / denominator))
.collect()
}
pub fn id(&self) -> Option<&LogId> {
self.log.id()
}
pub fn provenance(&self) -> Option<&Provenance> {
self.log.provenance()
}
pub fn replay(&self) -> Graph {
replay_captured_deltas(self.log.entries().iter().map(|e| e.delta.clone()))
}
pub fn replay_from(&self, since: Seq, graph: &mut Graph) {
replay_captured_deltas_onto(graph, self.log.from(since).iter().map(|e| e.delta.clone()));
}
pub fn fork(&self, new_id: LogId) -> Self {
Self {
log: self.log.fork(new_id),
author: self.author.clone(),
}
}
pub async fn save<B: Backend, C: Codec>(
&self,
slots: &SlotStore<B, C>,
key: &str,
) -> Result<(), StoreError> {
self.log.save(slots, key).await
}
pub async fn load<B: Backend, C: Codec>(
slots: &SlotStore<B, C>,
key: &str,
) -> Result<Self, StoreError> {
Ok(Self::from_log(Codicil::load(slots, key).await?))
}
pub fn migrate_bare_log(log: Codicil<CapturedDelta>) -> Self {
let mut journal = GraphJournal::new();
for delta in log.entries() {
journal.record_as("pre-gate", delta.clone());
}
journal
}
}
impl SourceTime for GraphJournal {
type Cursor = Seq;
type Snapshot = Graph;
fn source_extent(&self) -> SourceExtent<Self::Cursor> {
SourceExtent {
earliest: self.earliest_cursor(),
current: self.live_cursor(),
}
}
fn source_ticks(&self, max_points: usize) -> Vec<Self::Cursor> {
self.sequence_ticks(max_points)
}
fn source_snapshot(&self, cursor: &Self::Cursor) -> Option<Self::Snapshot> {
self.snapshot_at(*cursor)
}
}
pub fn journal_capture_hook() -> (
Arc<Mutex<GraphJournal>>,
Arc<dyn Fn(&CapturedDelta) + Send + Sync + 'static>,
) {
let journal = Arc::new(Mutex::new(GraphJournal::new()));
let sink = Arc::clone(&journal);
let hook: Arc<dyn Fn(&CapturedDelta) + Send + Sync + 'static> = Arc::new(move |delta| {
if let Ok(mut journal) = sink.lock() {
journal.record(delta.clone());
}
});
(journal, hook)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graph::apply::{GraphDelta, GraphDeltaResult, apply_graph_delta};
use crate::graph::set_captured_delta_hook;
use crate::graph::{EdgeAssertion, SemanticSubKind, SourceExtent, SourceTime};
use euclid::default::Point2D;
use uuid::Uuid;
fn add(id: u128, url: &str) -> CapturedDelta {
CapturedDelta::ReplayAddNodeWithIdIfMissing {
id: Uuid::from_u128(id).to_string(),
url: url.to_string(),
position: [0.0, 0.0],
}
}
fn fingerprint(graph: &Graph) -> (Vec<String>, Vec<(String, String, String)>) {
let mut nodes: Vec<String> = graph.nodes().map(|(_, n)| n.id.to_string()).collect();
nodes.sort();
let mut edges: Vec<(String, String, String)> = graph
.relations()
.map(|rel| {
let from = graph
.get_node(rel.from)
.map(|n| n.id.to_string())
.unwrap_or_default();
let to = graph
.get_node(rel.to)
.map(|n| n.id.to_string())
.unwrap_or_default();
(from, to, format!("{:?}", rel.kind))
})
.collect();
edges.sort();
(nodes, edges)
}
#[test]
fn entries_are_attributed_and_author_scoping_works() {
let mut journal = GraphJournal::new();
journal.record(add(1, "https://a.test/"));
journal.set_author("aa11");
journal.record(add(2, "https://b.test/"));
journal.set_author(USER_AUTHOR);
journal.record_as("gate", add(3, "https://c.test/"));
let authors: Vec<&str> = journal
.entries()
.iter()
.map(|e| e.author.as_str())
.collect();
assert_eq!(authors, ["user", "aa11", "gate"]);
assert_eq!(journal.author(), USER_AUTHOR, "scoping restored");
assert_eq!(
journal.replay().node_count(),
3,
"replay strips the envelope"
);
}
#[test]
fn source_time_contract_selects_immutable_journal_prefixes() {
let mut journal = GraphJournal::new();
journal.record(add(1, "https://one.test/"));
journal.record(add(2, "https://two.test/"));
assert_eq!(
journal.source_extent(),
SourceExtent {
earliest: Seq(0),
current: Seq(2),
}
);
assert_eq!(journal.source_ticks(3), [Seq(0), Seq(1), Seq(2)]);
assert_eq!(
journal
.source_snapshot(&Seq(1))
.expect("known source cursor")
.node_count(),
1
);
assert!(journal.source_snapshot(&Seq(3)).is_none());
assert_eq!(
journal.replay().node_count(),
2,
"scrubbing leaves live truth intact"
);
}
#[test]
fn a_bare_log_migrates_as_pre_gate() {
let mut bare = Codicil::<CapturedDelta>::default();
bare.append(add(1, "https://a.test/"));
bare.append(add(2, "https://b.test/"));
let journal = GraphJournal::migrate_bare_log(bare);
assert!(journal.entries().iter().all(|e| e.author == "pre-gate"));
assert_eq!(journal.replay().node_count(), 2);
}
#[test]
fn records_and_replays_reconstruct_the_graph() {
let mut journal = GraphJournal::new();
journal.record(add(1, "https://a.test/"));
journal.record(add(2, "https://b.test/"));
journal.record(CapturedDelta::ReplayAssertRelationByIds {
from_id: Uuid::from_u128(1).to_string(),
to_id: Uuid::from_u128(2).to_string(),
assertion: EdgeAssertion::Semantic {
sub_kind: SemanticSubKind::Cites,
label: None,
decay_progress: None,
},
});
journal.record(CapturedDelta::ReplaySetNodeTitleById {
node_id: Uuid::from_u128(1).to_string(),
title: "Paper A".to_string(),
});
let graph = journal.replay();
assert_eq!(graph.node_count(), 2);
assert_eq!(graph.relations().count(), 1, "the cites relation replayed");
let (_, node) = graph
.get_node_by_id(Uuid::from_u128(1))
.expect("node a present");
assert_eq!(node.title, "Paper A", "the content edit replayed too");
}
#[test]
fn prefix_cursors_replay_historical_graphs_without_touching_live_history() {
let mut journal = GraphJournal::new();
journal.record(add(1, "https://a.test/"));
journal.record(add(2, "https://b.test/"));
journal.record(CapturedDelta::ReplayAssertRelationByIds {
from_id: Uuid::from_u128(1).to_string(),
to_id: Uuid::from_u128(2).to_string(),
assertion: EdgeAssertion::Semantic {
sub_kind: SemanticSubKind::Cites,
label: None,
decay_progress: None,
},
});
assert_eq!(journal.earliest_cursor(), Seq(0));
assert_eq!(journal.live_cursor(), Seq(3));
assert_eq!(journal.snapshot_at(Seq(0)).unwrap().node_count(), 0);
assert_eq!(journal.snapshot_at(Seq(1)).unwrap().node_count(), 1);
let historical = journal.snapshot_at(Seq(2)).expect("known prefix");
assert_eq!(historical.node_count(), 2);
assert_eq!(historical.relations().count(), 0);
assert_eq!(journal.snapshot_at(Seq(3)).unwrap().relations().count(), 1);
assert!(
journal.snapshot_at(Seq(4)).is_none(),
"stale cursors refuse"
);
assert_eq!(
journal.replay().relations().count(),
1,
"live history remains live"
);
assert_eq!(journal.sequence_ticks(3), vec![Seq(0), Seq(1), Seq(3)]);
}
#[test]
fn fork_carries_history_then_diverges() {
let mut source = GraphJournal::with_id(LogId::new("source"));
source.record(add(1, "https://a.test/"));
source.record(add(2, "https://b.test/"));
let mut fork = source.fork(LogId::new("fork"));
assert_eq!(
fork.entries(),
source.entries(),
"the fork copies the history"
);
let provenance = fork.provenance().expect("a fork has provenance");
assert_eq!(provenance.source, Some(LogId::new("source")));
assert_eq!(provenance.at, Seq(source.len() as u64));
fork.record(add(3, "https://c.test/"));
assert_eq!(source.replay().node_count(), 2, "source unchanged");
assert_eq!(fork.replay().node_count(), 3);
}
#[test]
fn journal_round_trips_through_a_muniment_slot() {
use muniment::{JsonSlots, MemoryBackend};
pollster::block_on(async {
let slots = JsonSlots::new(MemoryBackend::new());
let mut journal = GraphJournal::new();
journal.record(add(1, "https://a.test/"));
journal.record(add(2, "https://b.test/"));
journal.save(&slots, "journal").await.unwrap();
let reloaded = GraphJournal::load(&slots, "journal").await.unwrap();
assert_eq!(reloaded.len(), 2, "the log survived the round trip");
assert_eq!(
fingerprint(&reloaded.replay()),
fingerprint(&journal.replay()),
"the reloaded journal replays to the same graph"
);
});
}
#[test]
fn the_capture_hook_feeds_the_journal_and_replay_matches_live() {
let (journal, hook) = journal_capture_hook();
set_captured_delta_hook(Some(hook));
let mut live = Graph::new();
let a = match apply_graph_delta(
&mut live,
GraphDelta::AddNode {
id: Some(Uuid::from_u128(1)),
url: "https://a.test/".to_string(),
position: Point2D::new(0.0, 0.0),
},
) {
GraphDeltaResult::NodeAdded(key) => key,
other => panic!("expected NodeAdded, got {other:?}"),
};
let b = match apply_graph_delta(
&mut live,
GraphDelta::AddNode {
id: Some(Uuid::from_u128(2)),
url: "https://b.test/".to_string(),
position: Point2D::new(1.0, 0.0),
},
) {
GraphDeltaResult::NodeAdded(key) => key,
other => panic!("expected NodeAdded, got {other:?}"),
};
apply_graph_delta(
&mut live,
GraphDelta::AssertRelation {
from: a,
to: b,
assertion: EdgeAssertion::Semantic {
sub_kind: SemanticSubKind::Cites,
label: None,
decay_progress: None,
},
},
);
apply_graph_delta(
&mut live,
GraphDelta::SetNodeTitle {
key: a,
title: "Paper A".to_string(),
},
);
set_captured_delta_hook(None);
let replayed = journal.lock().unwrap().replay();
assert_eq!(
fingerprint(&replayed),
fingerprint(&live),
"replay of the captured journal reconstructs the live graph"
);
let (_, node) = replayed.get_node_by_id(Uuid::from_u128(1)).expect("node a");
assert_eq!(node.title, "Paper A");
}
}