use std::collections::{BTreeSet, HashMap};
use automerge::{ChangeHash, ObjId, Prop, ReadDoc};
use crate::model::Doc;
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Touched {
written: BTreeSet<String>,
below: BTreeSet<String>,
all: bool,
}
impl Touched {
fn everything() -> Self {
Self {
all: true,
..Self::default()
}
}
pub fn is_empty(&self) -> bool {
!self.all && self.written.is_empty() && self.below.is_empty()
}
pub fn is_all(&self) -> bool {
self.all
}
pub fn key(&self, key: &str) -> Touch {
if self.all || self.written.contains(key) {
Touch::Written
} else if self.below.contains(key) {
Touch::Below
} else {
Touch::Untouched
}
}
pub fn keys(&self) -> impl Iterator<Item = &str> {
let mut keys: BTreeSet<&str> = self.written.iter().map(String::as_str).collect();
keys.extend(self.below.iter().map(String::as_str));
keys.into_iter()
}
pub fn written(&self) -> impl Iterator<Item = &str> {
self.written.iter().map(String::as_str)
}
fn merge(&mut self, other: Self) {
self.written.extend(other.written);
self.below.extend(other.below);
self.all |= other.all;
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Touch {
Untouched,
Written,
Below,
}
#[derive(Clone, Debug, Default)]
enum Kind {
#[default]
Nothing,
Everything,
Indexed(HashMap<ObjId, Touched>),
}
#[derive(Clone, Debug, Default)]
pub struct Delta {
kind: Kind,
}
impl Delta {
#[must_use]
pub fn nothing() -> Self {
Self::default()
}
#[must_use]
pub fn everything() -> Self {
Self {
kind: Kind::Everything,
}
}
pub fn merge(&mut self, other: Self) {
self.kind = match (std::mem::take(&mut self.kind), other.kind) {
(Kind::Everything, _) | (_, Kind::Everything) => Kind::Everything,
(Kind::Nothing, other) | (other, Kind::Nothing) => other,
(Kind::Indexed(mut index), Kind::Indexed(more)) => {
for (obj, touched) in more {
index.entry(obj).or_default().merge(touched);
}
Kind::Indexed(index)
}
};
}
pub fn is_empty(&self) -> bool {
matches!(self.kind, Kind::Nothing)
}
pub fn is_everything(&self) -> bool {
matches!(self.kind, Kind::Everything)
}
pub fn under(&self, obj: &ObjId) -> Touched {
match &self.kind {
Kind::Nothing => Touched::default(),
Kind::Everything => Touched::everything(),
Kind::Indexed(index) => index.get(obj).cloned().unwrap_or_default(),
}
}
pub fn touches(&self, obj: &ObjId) -> bool {
match &self.kind {
Kind::Nothing => false,
Kind::Everything => true,
Kind::Indexed(index) => index.get(obj).is_some_and(|touched| !touched.is_empty()),
}
}
pub fn key(&self, obj: &ObjId, key: &str) -> Touch {
match &self.kind {
Kind::Nothing => Touch::Untouched,
Kind::Everything => Touch::Written,
Kind::Indexed(index) => index
.get(obj)
.map_or(Touch::Untouched, |touched| touched.key(key)),
}
}
}
pub type ObjPath = Vec<(ObjId, Prop)>;
const MAX_CHANGES: usize = 4_096;
const MAX_OPS: u64 = 200_000;
type Read = (Vec<ChangeHash>, Vec<ChangeHash>, Delta);
thread_local! {
static LAST: std::cell::RefCell<Option<Read>> = const { std::cell::RefCell::new(None) };
}
impl Delta {
pub fn from_changes(
doc: &Doc,
changes: &[automerge::Change],
locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
) -> Self {
let mut at = doc.committed_heads();
at.sort_unstable();
let mut read: Vec<ChangeHash> = changes.iter().map(automerge::Change::hash).collect();
read.sort_unstable();
let known = LAST.with_borrow(|last| {
last.as_ref()
.filter(|(heads, hashes, _)| *heads == at && *hashes == read)
.map(|(_, _, delta)| delta.clone())
});
if let Some(delta) = known {
return delta;
}
let delta = Self::read_from(doc, changes, locate);
LAST.with_borrow_mut(|last| *last = Some((at, read, delta.clone())));
delta
}
fn read_from(
doc: &Doc,
changes: &[automerge::Change],
locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
) -> Self {
let committed = doc.committed_document();
let mut index: HashMap<ObjId, Touched> = HashMap::new();
let mut created: HashMap<ObjId, (ObjId, Option<String>)> = HashMap::new();
let mut located: std::collections::HashSet<ObjId> = std::collections::HashSet::new();
let mut touched = Vec::new();
for change in changes {
let Some(writes) = committed.change_touches(change) else {
return Self::everything();
};
for (made, obj, key) in writes.made {
created.insert(made, (obj, key));
}
for (obj, key) in writes.writes {
let entry = match index.entry(obj) {
std::collections::hash_map::Entry::Occupied(entry) => entry.into_mut(),
std::collections::hash_map::Entry::Vacant(entry) => {
touched.push(entry.key().clone());
entry.insert(Touched::default())
}
};
match key {
Some(key) => {
entry.written.insert(key);
}
None => entry.all = true,
}
}
}
for obj in touched {
mark_path(doc, &obj, &created, locate, &mut located, &mut index);
}
Self {
kind: Kind::Indexed(index),
}
}
}
fn mark_path(
doc: &Doc,
obj: &ObjId,
created: &HashMap<ObjId, (ObjId, Option<String>)>,
locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
located: &mut std::collections::HashSet<ObjId>,
index: &mut HashMap<ObjId, Touched>,
) {
let mut current = obj.clone();
loop {
if current == automerge::ROOT || !located.insert(current.clone()) {
return;
}
if let Some((parent, key)) = created.get(¤t) {
let entry = index.entry(parent.clone()).or_default();
match key {
Some(key) => {
entry.below.insert(key.clone());
}
None => entry.all = true,
}
current = parent.clone();
continue;
}
let path: Option<ObjPath> = locate(¤t).or_else(|| {
let parents: Vec<automerge::Parent> = doc.parents(¤t).ok()?.collect();
if parents.iter().any(|parent| !parent.visible) {
return None;
}
Some(
parents
.into_iter()
.rev()
.map(|parent| (parent.obj, parent.prop))
.collect(),
)
});
for (parent, prop) in path.unwrap_or_default() {
let entry = index.entry(parent.clone()).or_default();
match prop {
Prop::Map(key) => {
entry.below.insert(key);
}
Prop::Seq(_) => entry.all = true,
}
located.insert(parent);
}
return;
}
}
#[derive(Debug, Default)]
pub struct Tracker {
heads: Option<Vec<ChangeHash>>,
}
impl Tracker {
#[must_use]
pub fn new() -> Self {
Self::default()
}
pub fn start(&mut self, doc: &mut Doc) {
self.heads = Some(doc.get_heads());
}
#[must_use]
pub fn at(heads: Vec<ChangeHash>) -> Self {
Self { heads: Some(heads) }
}
pub fn heads(&self) -> Option<&[ChangeHash]> {
self.heads.as_deref()
}
pub fn leads_to(&self, doc: &Doc) -> bool {
let committed = doc.committed_document();
self.heads.as_ref().is_some_and(|heads| {
heads
.iter()
.all(|hash| committed.get_change_meta_by_hash(hash).is_some())
})
}
pub fn delta(&mut self, doc: &mut Doc) -> Delta {
self.delta_located(doc, &|_| None)
}
pub fn delta_located(
&mut self,
doc: &mut Doc,
locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
) -> Delta {
doc.get_heads();
self.committed_delta_located(doc, locate)
}
pub fn committed_delta_located(
&mut self,
doc: &Doc,
locate: &dyn Fn(&ObjId) -> Option<ObjPath>,
) -> Delta {
let heads = doc.committed_heads();
if self.heads.as_ref() == Some(&heads) {
return Delta::nothing();
}
let committed = doc.committed_document();
let moved_on = self.leads_to(doc);
let Some(previous) = self.heads.replace(heads.clone()) else {
return Delta::everything();
};
if previous == heads {
return Delta::nothing();
}
if !moved_on {
return Delta::everything();
}
let metas = committed.get_changes_meta(&previous);
let ops: u64 = match metas.as_slice() {
[meta] if crate::apply_cache::stored_by(meta).is_some() => 0,
metas => metas
.iter()
.map(|meta| meta.max_op.saturating_add(1).saturating_sub(meta.start_op))
.sum(),
};
if metas.len() > MAX_CHANGES || ops > MAX_OPS {
return Delta::everything();
}
let mut changes = Vec::with_capacity(metas.len());
for meta in &metas {
match committed.get_change_by_hash(&meta.hash) {
Some(change) => changes.push(change),
None => return Delta::everything(),
}
}
Delta::from_changes(doc, &changes, locate)
}
}
#[cfg(test)]
mod tests {
use super::*;
use automerge::transaction::Transactable;
use automerge::{ObjType, ROOT};
tilo_test_env::scenario! {
fn a_delta_names_what_changes_touched;
phase a_splice_touches_the_path_to_its_text_and_nothing_else;
{
let mut doc = Doc::new();
let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
let mut texts = Vec::new();
for id in ["a", "b", "c"] {
let block = doc.put_object(&blocks, id, ObjType::Map).unwrap();
texts.push(doc.put_object(&block, "text", ObjType::Text).unwrap());
}
doc.commit();
let mut tracker = Tracker::new();
tracker.start(&mut doc);
doc.splice_text(&texts[1], 0, 0, "hello").unwrap();
let delta = tracker.delta(&mut doc);
assert_eq!(delta.key(&ROOT, "blocks"), Touch::Below);
let under = delta.under(&blocks);
assert_eq!(under.keys().collect::<Vec<_>>(), ["b"]);
assert_eq!(under.key("b"), Touch::Below);
assert_eq!(under.key("a"), Touch::Untouched);
assert!(delta.under(&texts[1]).is_all());
assert!(!delta.touches(&texts[0]));
assert!(tracker.delta(&mut doc).is_empty());
doc.delete(&blocks, "c").unwrap();
let delta = tracker.delta(&mut doc);
assert_eq!(delta.under(&blocks).key("c"), Touch::Written);
assert_eq!(doc.text(&texts[1]).unwrap(), "hello");
}
phase a_replaced_document_reads_as_everything_and_new_objects_locate_themselves;
{
let mut doc = Doc::new();
doc.put(ROOT, "x", 1).unwrap();
doc.commit();
let mut tracker = Tracker::new();
tracker.start(&mut doc);
let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
let block = doc.put_object(&blocks, "new", ObjType::Map).unwrap();
let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
doc.splice_text(&text, 0, 0, "fresh").unwrap();
doc.commit();
let delta = tracker.delta_located(&mut doc, &|_| panic!("created objects need no lookup"));
assert_eq!(delta.key(&ROOT, "blocks"), Touch::Written);
assert_eq!(delta.under(&blocks).key("new"), Touch::Written);
assert!(delta.under(&text).is_all());
let mut other = Doc::new();
other.put(ROOT, "x", 9).unwrap();
other.commit();
let delta = tracker.delta(&mut other);
assert!(delta.is_everything());
}
phase an_edit_located_by_the_state_asks_the_document_nothing;
{
let mut doc = Doc::new();
let blocks = doc.put_object(ROOT, "blocks", ObjType::Map).unwrap();
let block = doc.put_object(&blocks, "b", ObjType::Map).unwrap();
let text = doc.put_object(&block, "text", ObjType::Text).unwrap();
doc.commit();
let mut tracker = Tracker::new();
tracker.start(&mut doc);
doc.splice_text(&text, 0, 0, "k").unwrap();
doc.commit();
let path = vec![
(ROOT, Prop::Map("blocks".into())),
(blocks.clone(), Prop::Map("b".into())),
(block.clone(), Prop::Map("text".into())),
];
let asked = std::cell::Cell::new(0);
let delta = tracker.delta_located(&mut doc, &|obj| {
asked.set(asked.get() + 1);
(*obj == text).then(|| path.clone())
});
assert_eq!(asked.get(), 1);
assert_eq!(delta.under(&blocks).key("b"), Touch::Below);
assert_eq!(delta.under(&block).key("text"), Touch::Below);
}
phase merged_deltas_read_as_one;
{
let mut doc = Doc::new();
doc.put(ROOT, "a", 1).unwrap();
doc.put(ROOT, "b", 1).unwrap();
doc.commit();
let mut tracker = Tracker::new();
tracker.start(&mut doc);
doc.put(ROOT, "a", 2).unwrap();
doc.commit();
let mut merged = tracker.delta(&mut doc);
doc.put(ROOT, "b", 2).unwrap();
doc.commit();
merged.merge(tracker.delta(&mut doc));
assert_eq!(merged.key(&ROOT, "a"), Touch::Written);
assert_eq!(merged.key(&ROOT, "b"), Touch::Written);
let mut nothing = Delta::nothing();
nothing.merge(merged.clone());
assert_eq!(nothing.key(&ROOT, "b"), Touch::Written);
merged.merge(Delta::everything());
assert!(merged.is_everything());
}
}
}