1use automerge::transaction::{CommitOptions, Transactable as _};
17use automerge::{AutoCommit, Change, ChangeHash, ChangeMetadata, ObjType, ROOT};
18use tilo_actions::surface::{FieldType, Surface};
19use tilo_automerge::ApplyIncoming as _;
20
21pub mod split;
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct Scope<'a> {
29 pub workspace: &'a str,
30 pub kind: &'a str,
31 pub id: &'a str,
32}
33
34impl Scope<'_> {
35 #[must_use]
39 pub fn founding_actor(self) -> automerge::ActorId {
40 crate::genesis::actor(
41 self.id,
42 self.kind,
43 &format!("founding in {}", self.workspace),
44 )
45 }
46}
47
48#[must_use]
56pub fn containers(surface: &Surface) -> Vec<(String, ObjType)> {
57 let mut containers: Vec<(String, ObjType)> = surface
58 .fields
59 .iter()
60 .filter(|field| !field.path.contains('.'))
61 .filter_map(|field| {
62 let container = match &field.ty {
63 FieldType::Collection(_)
65 | FieldType::Map(_)
66 | FieldType::Set(_)
67 | FieldType::Outbox(_) => ObjType::Map,
68 FieldType::List(_) => ObjType::List,
69 FieldType::Named(_) if field.stored == "record" => ObjType::Map,
70 _ => return None,
71 };
72 Some((field.path.clone(), container))
73 })
74 .collect();
75 containers.sort_by(|a, b| a.0.cmp(&b.0));
76 containers.dedup_by(|a, b| a.0 == b.0);
77 containers
78}
79
80#[must_use]
84pub fn of_kind(surface: &Surface) -> Vec<(String, ObjType)> {
85 let named = |name: &str| surface.types.iter().find(|ty| ty.name == name);
86 let own = match named(&surface.kind) {
87 Some(ty) => !ty.is_enum(),
88 None => named(&surface.label).is_none(),
89 };
90 if own { containers(surface) } else { Vec::new() }
91}
92
93pub fn structure(
101 scope: Scope<'_>,
102 containers: &[(String, ObjType)],
103) -> Result<automerge::Change, automerge::AutomergeError> {
104 let mut doc = AutoCommit::new().with_actor(scope.founding_actor());
105 for (field, container) in containers {
106 doc.put_object(ROOT, field.as_str(), *container)?;
107 }
108 let options = || {
109 CommitOptions::default()
110 .with_message(tilo_actions::FrameworkChange::Genesis.change_message())
111 .with_time(0)
112 };
113 let hash = match doc.commit_with(options()) {
115 Some(hash) => hash,
116 None => doc.empty_change(options()),
117 };
118 doc.get_change_by_hash(&hash)
119 .ok_or(automerge::AutomergeError::MissingHash(hash))
120}
121
122pub fn chain(
131 scope: Scope<'_>,
132 version: u32,
133 containers: &[(String, ObjType)],
134) -> Result<Vec<automerge::Change>, automerge::AutomergeError> {
135 let founding = structure(scope, containers)?;
136 chain_on(&founding, scope, version)
137}
138
139pub fn chain_on(
147 founding: &automerge::Change,
148 scope: Scope<'_>,
149 version: u32,
150) -> Result<Vec<automerge::Change>, automerge::AutomergeError> {
151 let mut doc = AutoCommit::new();
152 doc.apply_incoming([founding.clone()])?;
153 let mut chain = vec![founding.clone()];
154 for version in 1..=version {
155 let step = crate::evolution::step(scope, version, &doc)?;
156 doc.apply_incoming([step.clone()])?;
157 chain.push(step);
158 }
159 Ok(chain)
160}
161
162pub trait FoundingDoc {
165 fn change_metas(&mut self) -> Vec<ChangeMetadata<'_>>;
167
168 fn change_by_hash(&mut self, hash: &ChangeHash) -> Option<Change>;
170}
171
172impl FoundingDoc for AutoCommit {
173 fn change_metas(&mut self) -> Vec<ChangeMetadata<'_>> {
174 self.get_changes_meta(&[])
175 }
176
177 fn change_by_hash(&mut self, hash: &ChangeHash) -> Option<Change> {
178 self.get_change_by_hash(hash)
179 }
180}
181
182impl FoundingDoc for automerge::Automerge {
183 fn change_metas(&mut self) -> Vec<ChangeMetadata<'_>> {
184 self.get_changes_meta(&[])
185 }
186
187 fn change_by_hash(&mut self, hash: &ChangeHash) -> Option<Change> {
188 automerge::ReadDoc::get_change_by_hash(self, hash)
189 }
190}
191
192#[must_use]
196pub fn founding_of(doc: &mut impl FoundingDoc, scope: Scope<'_>) -> Option<automerge::Change> {
197 let actor = scope.founding_actor();
198 let hash = doc
199 .change_metas()
200 .into_iter()
201 .find(|change| change.actor.as_ref() == &actor && change.seq == 1)?
202 .hash;
203 doc.change_by_hash(&hash)
204}
205
206pub fn migrate_on(
213 doc: &mut impl FoundingDoc,
214 scope: Scope<'_>,
215 version: u32,
216 containers: &[(String, ObjType)],
217) -> Result<automerge::Change, automerge::AutomergeError> {
218 let founding = match founding_of(doc, scope) {
219 Some(founding) => founding,
220 None => structure(scope, containers)?,
221 };
222 chain_on(&founding, scope, version)?
223 .pop()
224 .filter(|_| version > 0)
225 .ok_or(automerge::AutomergeError::Fail)
226}
227
228pub fn migrate(
235 scope: Scope<'_>,
236 version: u32,
237 containers: &[(String, ObjType)],
238) -> Result<automerge::Change, automerge::AutomergeError> {
239 chain(scope, version, containers)?
240 .pop()
241 .filter(|_| version > 0)
242 .ok_or(automerge::AutomergeError::Fail)
243}
244
245pub fn bring_up(
257 (scope, app): (Scope<'_>, &str),
258 version: u32,
259 containers: &[(String, ObjType)],
260 rewrite: &dyn Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError>,
261 doc: &mut AutoCommit,
262) -> Result<bool, crate::ModelError> {
263 let from = crate::evolution::stored_version(doc);
264 let (found_changed, held) = found_holding((scope, app), containers, doc)?;
265 let mut changed = found_changed;
266 let current = structure(scope, containers)?;
268 let chain = if held == current.hash() {
269 chain_on(¤t, scope, version)?
270 } else {
271 let founding = doc
272 .get_change_by_hash(&held)
273 .ok_or(automerge::AutomergeError::Fail)?;
274 chain_on(&founding, scope, version)?
275 };
276 let missing: Vec<automerge::Change> = chain
277 .into_iter()
278 .filter(|link| doc.get_change_by_hash(&link.hash()).is_none())
279 .collect();
280 changed |= !missing.is_empty();
281 doc.apply_incoming(missing)?;
282 if from < version || crate::evolution::stored_version(doc) < version {
283 changed |= crate::evolution::rewrite((scope, version), from, rewrite, doc)?;
284 }
285 Ok(changed)
286}
287
288pub fn found_holding(
299 (scope, app): (Scope<'_>, &str),
300 containers: &[(String, ObjType)],
301 doc: &mut AutoCommit,
302) -> Result<(bool, ChangeHash), automerge::AutomergeError> {
303 let founding = structure(scope, containers)?;
304 let current = founding.hash();
305 if doc.get_change_by_hash(¤t).is_some() {
306 return Ok((false, current));
307 }
308 if let Some(held) = founding_of(doc, scope) {
309 return Ok((false, held.hash()));
310 }
311 doc.apply_incoming([founding])?;
312 split::merge_split_containers(doc, scope, containers, app)?;
313 Ok((true, current))
314}
315
316pub fn bring_up_resource<R: crate::Resource>(
322 workspace: &str,
323 id: &str,
324 doc: &mut AutoCommit,
325) -> Result<bool, crate::ModelError> {
326 let scope = Scope {
327 workspace,
328 kind: R::KIND,
329 id,
330 };
331 bring_up(
332 (scope, R::APP_ID),
333 R::VERSION,
334 &of_kind(&crate::surface::surface_of::<R>()),
335 &|doc: &mut AutoCommit, from: u32| R::migrate(doc, from),
336 doc,
337 )
338}
339
340pub fn new_record<R: crate::Resource>(
347 workspace: &str,
348 id: &str,
349) -> Result<AutoCommit, crate::ModelError> {
350 let mut doc = AutoCommit::new();
351 let containers = of_kind(&crate::surface::surface_of::<R>());
352 let scope = Scope {
353 workspace,
354 kind: R::KIND,
355 id,
356 };
357 doc.apply_incoming(chain(scope, R::VERSION, &containers)?)?;
358 R::initialize(&mut doc)?;
359 Ok(doc)
360}
361
362#[cfg(test)]
363mod tests {
364 #![allow(clippy::unwrap_used, reason = "tests")]
365
366 use crate::evolution::{VERSION_KEY, stored_version};
367 use automerge::transaction::Transactable as _;
368 use automerge::{AutoCommit, ObjType, ROOT, ReadDoc as _};
369 use tilo_automerge::ApplyIncoming as _;
370
371 const KIND: &str = "test.founding.chain";
372 const ID: &str = "groceries";
373 const APP: &str = "test.app";
374 const SCOPE: super::Scope<'static> = super::Scope {
375 workspace: "6f1c1b62-4f5e-4b8a-9b52-1f8a3f0f3a11",
376 kind: KIND,
377 id: ID,
378 };
379
380 fn containers() -> Vec<(String, ObjType)> {
381 vec![("items".to_owned(), ObjType::Map)]
382 }
383
384 fn device(version: u32, actor: u8, key: &str, wrote: &str) -> AutoCommit {
387 let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
388 doc.apply_incoming(super::chain(SCOPE, version, &containers()).unwrap())
389 .unwrap();
390 let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
391 doc.put(&items, key, wrote).unwrap();
392 doc.commit();
393 doc
394 }
395
396 fn unchanged() -> impl Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError> {
398 |_, _| Ok(())
399 }
400
401 fn items(doc: &AutoCommit) -> Vec<String> {
402 let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
403 doc.keys(&items).collect()
404 }
405
406 #[test]
409 fn a_kinds_queue_is_founded_with_its_containers() {
410 let surface: crate::Surface = serde_json::from_value(serde_json::json!({
411 "kind": "terminal.session",
412 "label": "Terminal",
413 "version": 1,
414 "fields": [
415 {
416 "path": "requests",
417 "type": {"outbox": {"named": "CommandRequest"}},
418 "readonly": true,
419 "unit": true
420 }
421 ],
422 "verbs": [],
423 "types": []
424 }))
425 .unwrap();
426 assert_eq!(
427 super::containers(&surface),
428 vec![("requests".to_owned(), ObjType::Map)],
429 "the outbox is founded like a map the kind keeps its items in"
430 );
431 let founding = super::structure(SCOPE, &super::containers(&surface)).unwrap();
432 let mut doc = AutoCommit::new();
433 doc.apply_incoming([founding]).unwrap();
434 assert_eq!(
435 doc.get(ROOT, "requests").unwrap().map(|(value, _)| value),
436 Some(automerge::Value::Object(ObjType::Map)),
437 "founded, and empty"
438 );
439 }
440
441 #[test]
442 fn two_devices_with_their_own_writes_step_a_record_up_byte_for_byte_alike() {
443 let mut here = device(1, 1, "milk", "2 l");
444 let mut there = device(1, 2, "eggs", "6");
445 let (own_heads, peer_heads) = (here.get_heads(), there.get_heads());
446 assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
447 assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut there).unwrap());
448 let bytes = |changes: Vec<automerge::Change>| -> Vec<Vec<u8>> {
449 changes
450 .into_iter()
451 .map(|change| change.raw_bytes().to_vec())
452 .collect()
453 };
454 let ours = bytes(here.get_changes(&own_heads));
455 let theirs = bytes(there.get_changes(&peer_heads));
456 assert_eq!(ours, theirs);
459 assert_eq!(
460 ours,
461 bytes(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2))
462 );
463 for (to, step) in (2..=3).zip(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2)) {
464 assert_eq!(
465 super::migrate(SCOPE, to, &containers()).unwrap().hash(),
466 step.hash()
467 );
468 }
469 tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
470 assert_eq!(stored_version(&here), 3);
471 assert_eq!(items(&here), ["eggs", "milk"]);
472 assert!(!super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
474 }
475
476 #[test]
477 fn a_rewrite_two_devices_make_apart_keeps_one_default() {
478 let mut here = device(1, 1, "milk", "2 l");
481 let mut there = here.fork().with_actor(automerge::ActorId::from([2; 16]));
482 let (_, kept) = there.get(ROOT, "items").unwrap().unwrap();
483 there.put(&kept, "eggs", "6").unwrap();
484 there.commit();
485 let add_tags = |doc: &mut AutoCommit, from: u32| {
486 assert_eq!(from, 1);
487 let tags = doc.put_object(ROOT, "tags", ObjType::Map)?;
488 doc.put(&tags, "default", "kept")?;
489 Ok(())
490 };
491 super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut here).unwrap();
492 super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut there).unwrap();
493 tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
494 let (_, tags) = here.get(ROOT, "tags").unwrap().unwrap();
495 assert_eq!(here.keys(&tags).collect::<Vec<_>>(), ["default"]);
496 assert_eq!(items(&here), ["eggs", "milk"]);
497 assert_eq!(stored_version(&here), 2);
498 }
499
500 #[test]
501 fn a_record_made_before_its_founding_was_derived_is_founded_once_and_brought_together() {
502 let made = |actor: u8, key: &str| {
504 let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
505 let items = doc.put_object(ROOT, "items", ObjType::Map).unwrap();
506 doc.put(&items, key, "kept").unwrap();
507 doc.commit();
508 doc
509 };
510 let mut here = made(1, "milk");
511 let mut there = made(2, "eggs");
512 tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
513 let mut again = here.fork();
514 assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
515 assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut again).unwrap());
516 assert_eq!(here.get_heads(), again.get_heads());
518 let founding = super::structure(SCOPE, &containers()).unwrap();
519 assert!(here.get_change_by_hash(&founding.hash()).is_some());
520 let mut held = items(&here);
521 held.sort();
522 assert_eq!(held, ["eggs", "milk"]);
523 assert_eq!(stored_version(&here), 2);
524 assert!(here.get(ROOT, VERSION_KEY).unwrap().is_some());
525 assert!(!super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
526 }
527
528 #[test]
529 fn the_same_record_in_two_workspaces_shares_no_change() {
530 let other = super::Scope {
534 workspace: "0b9d7a3e-2c41-4f6b-8e15-7a9c3d2e1f40",
535 ..SCOPE
536 };
537 let hashes = |scope| -> Vec<automerge::ChangeHash> {
538 super::chain(scope, 3, &containers())
539 .unwrap()
540 .iter()
541 .map(automerge::Change::hash)
542 .collect()
543 };
544 let (here, there) = (hashes(SCOPE), hashes(other));
545 assert_eq!(here.len(), 4);
546 assert!(here.iter().all(|hash| !there.contains(hash)));
547 assert_ne!(
548 super::structure(SCOPE, &containers()).unwrap().hash(),
549 super::structure(other, &containers()).unwrap().hash()
550 );
551 assert_ne!(
554 SCOPE.founding_actor(),
555 crate::genesis::actor(ID, KIND, SCOPE.workspace)
556 );
557 let mut here_doc = device(1, 1, "milk", "2 l");
560 let mut there_doc = AutoCommit::new().with_actor(automerge::ActorId::from([1; 16]));
561 there_doc
562 .apply_incoming(super::chain(other, 1, &containers()).unwrap())
563 .unwrap();
564 super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here_doc).unwrap();
565 super::bring_up((other, APP), 3, &containers(), &unchanged(), &mut there_doc).unwrap();
566 let held = |doc: &mut AutoCommit| -> Vec<automerge::ChangeHash> {
567 doc.get_changes(&[])
568 .iter()
569 .map(automerge::Change::hash)
570 .collect()
571 };
572 let there_held = held(&mut there_doc);
573 assert!(
574 held(&mut here_doc)
575 .iter()
576 .all(|hash| !there_held.contains(hash))
577 );
578 }
579}