1use automerge::transaction::{CommitOptions, Transactable as _};
17use automerge::{AutoCommit, 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 let mut doc = AutoCommit::new();
137 doc.apply_incoming([founding.clone()])?;
138 let mut chain = vec![founding];
139 for version in 1..=version {
140 let step = crate::evolution::step(scope, version, &doc)?;
141 doc.apply_incoming([step.clone()])?;
142 chain.push(step);
143 }
144 Ok(chain)
145}
146
147pub fn migrate(
154 scope: Scope<'_>,
155 version: u32,
156 containers: &[(String, ObjType)],
157) -> Result<automerge::Change, automerge::AutomergeError> {
158 chain(scope, version, containers)?
159 .pop()
160 .filter(|_| version > 0)
161 .ok_or(automerge::AutomergeError::Fail)
162}
163
164pub fn bring_up(
176 (scope, app): (Scope<'_>, &str),
177 version: u32,
178 containers: &[(String, ObjType)],
179 rewrite: &dyn Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError>,
180 doc: &mut AutoCommit,
181) -> Result<bool, crate::ModelError> {
182 let from = crate::evolution::stored_version(doc);
183 let mut changed = found((scope, app), containers, doc)?;
184 let chain = chain(scope, version, containers)?;
185 let missing: Vec<automerge::Change> = chain
186 .into_iter()
187 .filter(|link| doc.get_change_by_hash(&link.hash()).is_none())
188 .collect();
189 changed |= !missing.is_empty();
190 doc.apply_incoming(missing)?;
191 if from < version || crate::evolution::stored_version(doc) < version {
192 changed |= crate::evolution::rewrite((scope, version), from, rewrite, doc)?;
193 }
194 Ok(changed)
195}
196
197pub fn found(
206 (scope, app): (Scope<'_>, &str),
207 containers: &[(String, ObjType)],
208 doc: &mut AutoCommit,
209) -> Result<bool, automerge::AutomergeError> {
210 let founding = structure(scope, containers)?;
211 if doc.get_change_by_hash(&founding.hash()).is_some() {
212 return Ok(false);
213 }
214 doc.apply_incoming([founding])?;
215 split::merge_split_containers(doc, scope, containers, app)?;
216 Ok(true)
217}
218
219pub fn bring_up_resource<R: crate::Resource>(
225 workspace: &str,
226 id: &str,
227 doc: &mut AutoCommit,
228) -> Result<bool, crate::ModelError> {
229 let scope = Scope {
230 workspace,
231 kind: R::KIND,
232 id,
233 };
234 bring_up(
235 (scope, R::APP_ID),
236 R::VERSION,
237 &of_kind(&crate::surface::surface_of::<R>()),
238 &|doc: &mut AutoCommit, from: u32| R::migrate(doc, from),
239 doc,
240 )
241}
242
243pub fn new_record<R: crate::Resource>(
250 workspace: &str,
251 id: &str,
252) -> Result<AutoCommit, crate::ModelError> {
253 let mut doc = AutoCommit::new();
254 let containers = of_kind(&crate::surface::surface_of::<R>());
255 let scope = Scope {
256 workspace,
257 kind: R::KIND,
258 id,
259 };
260 doc.apply_incoming(chain(scope, R::VERSION, &containers)?)?;
261 R::initialize(&mut doc)?;
262 Ok(doc)
263}
264
265#[cfg(test)]
266mod tests {
267 #![allow(clippy::unwrap_used, reason = "tests")]
268
269 use crate::evolution::{VERSION_KEY, stored_version};
270 use automerge::transaction::Transactable as _;
271 use automerge::{AutoCommit, ObjType, ROOT, ReadDoc as _};
272 use tilo_automerge::ApplyIncoming as _;
273
274 const KIND: &str = "test.founding.chain";
275 const ID: &str = "groceries";
276 const APP: &str = "test.app";
277 const SCOPE: super::Scope<'static> = super::Scope {
278 workspace: "6f1c1b62-4f5e-4b8a-9b52-1f8a3f0f3a11",
279 kind: KIND,
280 id: ID,
281 };
282
283 fn containers() -> Vec<(String, ObjType)> {
284 vec![("items".to_owned(), ObjType::Map)]
285 }
286
287 fn device(version: u32, actor: u8, key: &str, wrote: &str) -> AutoCommit {
290 let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
291 doc.apply_incoming(super::chain(SCOPE, version, &containers()).unwrap())
292 .unwrap();
293 let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
294 doc.put(&items, key, wrote).unwrap();
295 doc.commit();
296 doc
297 }
298
299 fn unchanged() -> impl Fn(&mut AutoCommit, u32) -> Result<(), crate::ModelError> {
301 |_, _| Ok(())
302 }
303
304 fn items(doc: &AutoCommit) -> Vec<String> {
305 let (_, items) = doc.get(ROOT, "items").unwrap().unwrap();
306 doc.keys(&items).collect()
307 }
308
309 #[test]
312 fn a_kinds_queue_is_founded_with_its_containers() {
313 let surface: crate::Surface = serde_json::from_value(serde_json::json!({
314 "kind": "terminal.session",
315 "label": "Terminal",
316 "version": 1,
317 "fields": [
318 {
319 "path": "requests",
320 "type": {"outbox": {"named": "CommandRequest"}},
321 "readonly": true,
322 "unit": true
323 }
324 ],
325 "verbs": [],
326 "types": []
327 }))
328 .unwrap();
329 assert_eq!(
330 super::containers(&surface),
331 vec![("requests".to_owned(), ObjType::Map)],
332 "the outbox is founded like a map the kind keeps its items in"
333 );
334 let founding = super::structure(SCOPE, &super::containers(&surface)).unwrap();
335 let mut doc = AutoCommit::new();
336 doc.apply_incoming([founding]).unwrap();
337 assert_eq!(
338 doc.get(ROOT, "requests").unwrap().map(|(value, _)| value),
339 Some(automerge::Value::Object(ObjType::Map)),
340 "founded, and empty"
341 );
342 }
343
344 #[test]
345 fn two_devices_with_their_own_writes_step_a_record_up_byte_for_byte_alike() {
346 let mut here = device(1, 1, "milk", "2 l");
347 let mut there = device(1, 2, "eggs", "6");
348 let (own_heads, peer_heads) = (here.get_heads(), there.get_heads());
349 assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
350 assert!(super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut there).unwrap());
351 let bytes = |changes: Vec<automerge::Change>| -> Vec<Vec<u8>> {
352 changes
353 .into_iter()
354 .map(|change| change.raw_bytes().to_vec())
355 .collect()
356 };
357 let ours = bytes(here.get_changes(&own_heads));
358 let theirs = bytes(there.get_changes(&peer_heads));
359 assert_eq!(ours, theirs);
362 assert_eq!(
363 ours,
364 bytes(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2))
365 );
366 for (to, step) in (2..=3).zip(super::chain(SCOPE, 3, &containers()).unwrap().split_off(2)) {
367 assert_eq!(
368 super::migrate(SCOPE, to, &containers()).unwrap().hash(),
369 step.hash()
370 );
371 }
372 tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
373 assert_eq!(stored_version(&here), 3);
374 assert_eq!(items(&here), ["eggs", "milk"]);
375 assert!(!super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here).unwrap());
377 }
378
379 #[test]
380 fn a_rewrite_two_devices_make_apart_keeps_one_default() {
381 let mut here = device(1, 1, "milk", "2 l");
384 let mut there = here.fork().with_actor(automerge::ActorId::from([2; 16]));
385 let (_, kept) = there.get(ROOT, "items").unwrap().unwrap();
386 there.put(&kept, "eggs", "6").unwrap();
387 there.commit();
388 let add_tags = |doc: &mut AutoCommit, from: u32| {
389 assert_eq!(from, 1);
390 let tags = doc.put_object(ROOT, "tags", ObjType::Map)?;
391 doc.put(&tags, "default", "kept")?;
392 Ok(())
393 };
394 super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut here).unwrap();
395 super::bring_up((SCOPE, APP), 2, &containers(), &add_tags, &mut there).unwrap();
396 tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
397 let (_, tags) = here.get(ROOT, "tags").unwrap().unwrap();
398 assert_eq!(here.keys(&tags).collect::<Vec<_>>(), ["default"]);
399 assert_eq!(items(&here), ["eggs", "milk"]);
400 assert_eq!(stored_version(&here), 2);
401 }
402
403 #[test]
404 fn a_record_made_before_its_founding_was_derived_is_founded_once_and_brought_together() {
405 let made = |actor: u8, key: &str| {
407 let mut doc = AutoCommit::new().with_actor(automerge::ActorId::from([actor; 16]));
408 let items = doc.put_object(ROOT, "items", ObjType::Map).unwrap();
409 doc.put(&items, key, "kept").unwrap();
410 doc.commit();
411 doc
412 };
413 let mut here = made(1, "milk");
414 let mut there = made(2, "eggs");
415 tilo_automerge::ApplyIncoming::merge_incoming(&mut here, &mut there).unwrap();
416 let mut again = here.fork();
417 assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
418 assert!(super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut again).unwrap());
419 assert_eq!(here.get_heads(), again.get_heads());
421 let founding = super::structure(SCOPE, &containers()).unwrap();
422 assert!(here.get_change_by_hash(&founding.hash()).is_some());
423 let mut held = items(&here);
424 held.sort();
425 assert_eq!(held, ["eggs", "milk"]);
426 assert_eq!(stored_version(&here), 2);
427 assert!(here.get(ROOT, VERSION_KEY).unwrap().is_some());
428 assert!(!super::bring_up((SCOPE, APP), 2, &containers(), &unchanged(), &mut here).unwrap());
429 }
430
431 #[test]
432 fn the_same_record_in_two_workspaces_shares_no_change() {
433 let other = super::Scope {
437 workspace: "0b9d7a3e-2c41-4f6b-8e15-7a9c3d2e1f40",
438 ..SCOPE
439 };
440 let hashes = |scope| -> Vec<automerge::ChangeHash> {
441 super::chain(scope, 3, &containers())
442 .unwrap()
443 .iter()
444 .map(automerge::Change::hash)
445 .collect()
446 };
447 let (here, there) = (hashes(SCOPE), hashes(other));
448 assert_eq!(here.len(), 4);
449 assert!(here.iter().all(|hash| !there.contains(hash)));
450 assert_ne!(
451 super::structure(SCOPE, &containers()).unwrap().hash(),
452 super::structure(other, &containers()).unwrap().hash()
453 );
454 assert_ne!(
457 SCOPE.founding_actor(),
458 crate::genesis::actor(ID, KIND, SCOPE.workspace)
459 );
460 let mut here_doc = device(1, 1, "milk", "2 l");
463 let mut there_doc = AutoCommit::new().with_actor(automerge::ActorId::from([1; 16]));
464 there_doc
465 .apply_incoming(super::chain(other, 1, &containers()).unwrap())
466 .unwrap();
467 super::bring_up((SCOPE, APP), 3, &containers(), &unchanged(), &mut here_doc).unwrap();
468 super::bring_up((other, APP), 3, &containers(), &unchanged(), &mut there_doc).unwrap();
469 let held = |doc: &mut AutoCommit| -> Vec<automerge::ChangeHash> {
470 doc.get_changes(&[])
471 .iter()
472 .map(automerge::Change::hash)
473 .collect()
474 };
475 let there_held = held(&mut there_doc);
476 assert!(
477 held(&mut here_doc)
478 .iter()
479 .all(|hash| !there_held.contains(hash))
480 );
481 }
482}