use automerge::transaction::{CommitOptions, Transactable as _};
use automerge::{AutoCommit, ObjType, ROOT};
use tilo_actions::surface::{FieldType, Surface};
use tilo_automerge::ApplyIncoming as _;
pub mod split;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Scope<'a> {
pub workspace: &'a str,
pub kind: &'a str,
pub id: &'a str,
}
impl Scope<'_> {
#[must_use]
pub fn founding_actor(self) -> automerge::ActorId {
crate::genesis::actor(
self.id,
self.kind,
&format!("founding in {}", self.workspace),
)
}
}
#[must_use]
pub fn containers(surface: &Surface) -> Vec<(String, ObjType)> {
let mut containers: Vec<(String, ObjType)> = surface
.fields
.iter()
.filter(|field| !field.path.contains('.'))
.filter_map(|field| {
let container = match &field.ty {
FieldType::Collection(_)
| FieldType::Map(_)
| FieldType::Set(_)
| FieldType::Outbox(_) => ObjType::Map,
FieldType::List(_) => ObjType::List,
FieldType::Named(_) if field.stored == "record" => ObjType::Map,
_ => return None,
};
Some((field.path.clone(), container))
})
.collect();
containers.sort_by(|a, b| a.0.cmp(&b.0));
containers.dedup_by(|a, b| a.0 == b.0);
containers
}
#[must_use]
pub fn of_kind(surface: &Surface) -> Vec<(String, ObjType)> {
let named = |name: &str| surface.types.iter().find(|ty| ty.name == name);
let own = match named(&surface.kind) {
Some(ty) => !ty.is_enum(),
None => named(&surface.label).is_none(),
};
if own { containers(surface) } else { Vec::new() }
}
pub fn structure(
scope: Scope<'_>,
containers: &[(String, ObjType)],
) -> Result<automerge::Change, automerge::AutomergeError> {
let mut doc = AutoCommit::new().with_actor(scope.founding_actor());
for (field, container) in containers {
doc.put_object(ROOT, field.as_str(), *container)?;
}
let options = || {
CommitOptions::default()
.with_message(tilo_actions::FrameworkChange::Genesis.change_message())
.with_time(0)
};
let hash = match doc.commit_with(options()) {
Some(hash) => hash,
None => doc.empty_change(options()),
};
doc.get_change_by_hash(&hash)
.ok_or(automerge::AutomergeError::MissingHash(hash))
}
pub fn chain(
scope: Scope<'_>,
version: u32,
containers: &[(String, ObjType)],
) -> Result<Vec<automerge::Change>, automerge::AutomergeError> {
let founding = structure(scope, containers)?;
let mut doc = AutoCommit::new();
doc.apply_incoming([founding.clone()])?;
let mut chain = vec![founding];
for version in 1..=version {
let step = crate::evolution::step(scope, version, &doc)?;
doc.apply_incoming([step.clone()])?;
chain.push(step);
}
Ok(chain)
}
pub fn migrate(
scope: Scope<'_>,
version: u32,
containers: &[(String, ObjType)],
) -> Result<automerge::Change, automerge::AutomergeError> {
chain(scope, version, containers)?
.pop()
.filter(|_| version > 0)
.ok_or(automerge::AutomergeError::Fail)
}
pub fn bring_up(
(scope, app): (Scope<'_>, &str),
version: u32,
containers: &[(String, ObjType)],
rewrite: &dyn Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError>,
doc: &mut AutoCommit,
) -> Result<bool, crate::ModelError> {
let from = crate::evolution::stored_version(doc);
let mut changed = found((scope, app), containers, doc)?;
let chain = chain(scope, version, containers)?;
let missing: Vec<automerge::Change> = chain
.into_iter()
.filter(|link| doc.get_change_by_hash(&link.hash()).is_none())
.collect();
changed |= !missing.is_empty();
doc.apply_incoming(missing)?;
if from < version || crate::evolution::stored_version(doc) < version {
changed |= crate::evolution::rewrite((scope, version), from, rewrite, doc)?;
}
Ok(changed)
}
pub fn found(
(scope, app): (Scope<'_>, &str),
containers: &[(String, ObjType)],
doc: &mut AutoCommit,
) -> Result<bool, automerge::AutomergeError> {
let founding = structure(scope, containers)?;
if doc.get_change_by_hash(&founding.hash()).is_some() {
return Ok(false);
}
doc.apply_incoming([founding])?;
split::merge_split_containers(doc, scope, containers, app)?;
Ok(true)
}
pub fn bring_up_resource<R: crate::Resource>(
workspace: &str,
id: &str,
doc: &mut AutoCommit,
) -> Result<bool, crate::ModelError> {
let scope = Scope {
workspace,
kind: R::KIND,
id,
};
bring_up(
(scope, R::APP_ID),
R::VERSION,
&of_kind(&crate::surface::surface_of::<R>()),
&|doc: &mut AutoCommit, from: u32| R::migrate(doc, from),
doc,
)
}
pub fn new_record<R: crate::Resource>(
workspace: &str,
id: &str,
) -> Result<AutoCommit, crate::ModelError> {
let mut doc = AutoCommit::new();
let containers = of_kind(&crate::surface::surface_of::<R>());
let scope = Scope {
workspace,
kind: R::KIND,
id,
};
doc.apply_incoming(chain(scope, R::VERSION, &containers)?)?;
R::initialize(&mut doc)?;
Ok(doc)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, reason = "tests")]
use crate::evolution::{VERSION_KEY, stored_version};
use automerge::transaction::Transactable as _;
use automerge::{AutoCommit, ObjType, ROOT, ReadDoc as _};
use tilo_automerge::ApplyIncoming as _;
const KIND: &str = "test.founding.chain";
const ID: &str = "groceries";
const APP: &str = "test.app";
const SCOPE: super::Scope<'static> = super::Scope {
workspace: "6f1c1b62-4f5e-4b8a-9b52-1f8a3f0f3a11",
kind: KIND,
id: ID,
};
fn containers() -> Vec<(String, ObjType)> {
vec![("items".to_owned(), ObjType::Map)]
}
fn device(version: u32, actor: u8, key: &str, wrote: &str) -> AutoCommit {
let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
doc.apply_incoming(super::chain(SCOPE, version, &containers()).unwrap())
.unwrap();
let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
doc.put(&items, key, wrote).unwrap();
doc.commit();
doc
}
fn unchanged() -> impl Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError> {
|_, _| Ok(())
}
fn items(doc: &AutoCommit) -> Vec<String> {
let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
doc.keys(&items).collect()
}
#[test]
fn a_kinds_queue_is_founded_with_its_containers() {
let surface: crate::Surface = serde_json::from_value(serde_json::json!({
"kind": "terminal.session",
"label": "Terminal",
"version": 1,
"fields": [
{
"path": "requests",
"type": {"outbox": {"named": "CommandRequest"}},
"readonly": true,
"unit": true
}
],
"verbs": [],
"types": []
}))
.unwrap();
assert_eq!(
super::containers(&surface),
vec![("requests".to_owned(), ObjType::Map)],
"the outbox is founded like a map the kind keeps its items in"
);
let founding = super::structure(SCOPE, &super::containers(&surface)).unwrap();
let mut doc = AutoCommit::new();
doc.apply_incoming([founding]).unwrap();
assert_eq!(
doc.get(ROOT, "requests").unwrap().map(|(value, _)| value),
Some(automerge::Value::Object(ObjType::Map)),
"founded, and empty"
);
}
#[test]
fn two_devices_with_their_own_writes_step_a_record_up_byte_for_byte_alike() {
let mut here = device(1, 1, "milk", "2 l");
let mut there = device(1, 2, "eggs", "6");
let (own_heads, peer_heads) = (here.get_heads(), there.get_heads());
assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut there).unwrap());
let bytes = |changes: Vec<automerge::Change>| -> Vec<Vec<u8>> {
changes
.into_iter()
.map(|change| change.raw_bytes().to_vec())
.collect()
};
let ours = bytes(here.get_changes(&own_heads));
let theirs = bytes(there.get_changes(&peer_heads));
assert_eq!(ours, theirs);
assert_eq!(
ours,
bytes(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2))
);
for (to, step) in (2..=3).zip(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2)) {
assert_eq!(
super::migrate(SCOPE, to, &containers()).unwrap().hash(),
step.hash()
);
}
tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
assert_eq!(stored_version(&here), 3);
assert_eq!(items(&here), ["eggs", "milk"]);
assert!(!super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
}
#[test]
fn a_rewrite_two_devices_make_apart_keeps_one_default() {
let mut here = device(1, 1, "milk", "2 l");
let mut there = here.fork().with_actor(automerge::ActorId::from([2; 16]));
let (_, kept) = there.get(ROOT, "items").unwrap().unwrap();
there.put(&kept, "eggs", "6").unwrap();
there.commit();
let add_tags = |doc: &mut AutoCommit, from: u32| {
assert_eq!(from, 1);
let tags = doc.put_object(ROOT, "tags", ObjType::Map)?;
doc.put(&tags, "default", "kept")?;
Ok(())
};
super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut here).unwrap();
super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut there).unwrap();
tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
let (_, tags) = here.get(ROOT, "tags").unwrap().unwrap();
assert_eq!(here.keys(&tags).collect::<Vec<_>>(), ["default"]);
assert_eq!(items(&here), ["eggs", "milk"]);
assert_eq!(stored_version(&here), 2);
}
#[test]
fn a_record_made_before_its_founding_was_derived_is_founded_once_and_brought_together() {
let made = |actor: u8, key: &str| {
let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
let items = doc.put_object(ROOT, "items", ObjType::Map).unwrap();
doc.put(&items, key, "kept").unwrap();
doc.commit();
doc
};
let mut here = made(1, "milk");
let mut there = made(2, "eggs");
tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
let mut again = here.fork();
assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut again).unwrap());
assert_eq!(here.get_heads(), again.get_heads());
let founding = super::structure(SCOPE, &containers()).unwrap();
assert!(here.get_change_by_hash(&founding.hash()).is_some());
let mut held = items(&here);
held.sort();
assert_eq!(held, ["eggs", "milk"]);
assert_eq!(stored_version(&here), 2);
assert!(here.get(ROOT, VERSION_KEY).unwrap().is_some());
assert!(!super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
}
#[test]
fn the_same_record_in_two_workspaces_shares_no_change() {
let other = super::Scope {
workspace: "0b9d7a3e-2c41-4f6b-8e15-7a9c3d2e1f40",
..SCOPE
};
let hashes = |scope| -> Vec<automerge::ChangeHash> {
super::chain(scope, 3, &containers())
.unwrap()
.iter()
.map(automerge::Change::hash)
.collect()
};
let (here, there) = (hashes(SCOPE), hashes(other));
assert_eq!(here.len(), 4);
assert!(here.iter().all(|hash| !there.contains(hash)));
assert_ne!(
super::structure(SCOPE, &containers()).unwrap().hash(),
super::structure(other, &containers()).unwrap().hash()
);
assert_ne!(
SCOPE.founding_actor(),
crate::genesis::actor(ID, KIND, SCOPE.workspace)
);
let mut here_doc = device(1, 1, "milk", "2 l");
let mut there_doc = AutoCommit::new().with_actor(automerge::ActorId::from([1; 16]));
there_doc
.apply_incoming(super::chain(other, 1, &containers()).unwrap())
.unwrap();
super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here_doc).unwrap();
super::bring_up((other, APP), 3, &containers(), &unchanged(), &mut there_doc).unwrap();
let held = |doc: &mut AutoCommit| -> Vec<automerge::ChangeHash> {
doc.get_changes(&[])
.iter()
.map(automerge::Change::hash)
.collect()
};
let there_held = held(&mut there_doc);
assert!(
held(&mut here_doc)
.iter()
.all(|hash| !there_held.contains(hash))
);
}
}