Skip to main content

tilo_resource/founding/
split.rs

1//! Bringing together a record whose root containers its devices each made of their own: what a
2//! record founded before every holder derived its founding ([`super::structure`]) needs
3//! once, and what a merge of such records leaves to do.
4
5use std::collections::BTreeMap;
6
7use automerge::transaction::Transactable;
8use automerge::{AutoCommit, ObjType, ROOT, ReadDoc, Value};
9use tilo_automerge::ApplyIncoming;
10
11/// Bring together a record whose root containers its devices each made of their own before its
12/// founding was the same everywhere: of every container `founding` names, the copies a merge left
13/// conflicting at the root, where it shows one and hides the rest with the items added to them.
14/// The items of each hidden copy are copied into the shown one, which every device picks alike: a
15/// map's entries it lacks by key (an item's id), and a list's elements it holds fewer of than the
16/// hidden copy does, an element naming an `id` held once by it.
17///
18/// The change is the same on every device that holds the same history: made at time zero by an
19/// actor derived from the record (`scope`: its workspace, kind and id), the containers it brings
20/// together and the heads it is made on, which are its only dependencies, and named as the app
21/// `app`'s own edit of its record, the same everywhere. Two devices doing it at once from one
22/// history make one change, which a merge keeps once; two doing it from different histories make
23/// two, of which a list keeps an element naming an `id` once all the same. Opened again, a record
24/// brought together is not changed. Whether this changed anything.
25///
26/// # Errors
27/// The record could not be written.
28pub fn merge_split_containers(
29    doc: &mut AutoCommit,
30    scope: super::Scope<'_>,
31    founding: &[(String, ObjType)],
32    app: &str,
33) -> Result<bool, automerge::AutomergeError> {
34    let mut split = Vec::new();
35    for (field, container) in founding {
36        let Some((Value::Object(_), shown)) = doc.get(ROOT, field.as_str())? else {
37            continue;
38        };
39        let hidden: Vec<automerge::ObjId> = doc
40            .get_all(ROOT, field.as_str())?
41            .into_iter()
42            .filter(|(value, held)| {
43                matches!(value, Value::Object(ty) if ty == container) && *held != shown
44            })
45            .map(|(_, held)| held)
46            .collect();
47        if !hidden.is_empty() {
48            split.push((*container, shown, hidden));
49        }
50    }
51    if split.is_empty() {
52        return Ok(false);
53    }
54    let heads = doc.get_heads();
55    let mut named: Vec<String> = split
56        .iter()
57        .flat_map(|(_, shown, hidden)| std::iter::once(shown).chain(hidden))
58        .map(ToString::to_string)
59        .collect();
60    named.sort();
61    let mut on: Vec<String> = heads.iter().map(ToString::to_string).collect();
62    on.sort();
63    let (named, on) = (named.join(","), on.join(","));
64    let salt = format!("merge {named} on {on} in {}", scope.workspace);
65    let mut merging = doc.fork();
66    merging.set_actor(crate::genesis::actor(scope.id, scope.kind, &salt));
67    for (container, shown, hidden) in &split {
68        for stray in hidden {
69            match container {
70                ObjType::Map | ObjType::Table => {
71                    for key in merging.keys(stray).collect::<Vec<_>>() {
72                        if merging.get(shown, key.as_str())?.is_none() {
73                            copy_value(
74                                &mut merging,
75                                stray,
76                                key.as_str().into(),
77                                shown,
78                                Place::Key(&key),
79                            )?;
80                        }
81                    }
82                }
83                ObjType::List => {
84                    let mut held: BTreeMap<String, usize> = BTreeMap::new();
85                    for at in 0..merging.length(shown) {
86                        let count = held
87                            .entry(fingerprint(&merging, shown, at.into())?)
88                            .or_default();
89                        *count = count.saturating_add(1);
90                    }
91                    for at in 0..merging.length(stray) {
92                        let print = fingerprint(&merging, stray, at.into())?;
93                        match held.get_mut(&print) {
94                            Some(count) if *count > 0 => *count = count.saturating_sub(1),
95                            _ => {
96                                let end = merging.length(shown);
97                                copy_value(
98                                    &mut merging,
99                                    stray,
100                                    at.into(),
101                                    shown,
102                                    Place::Index(end),
103                                )?;
104                            }
105                        }
106                    }
107                }
108                ObjType::Text => {}
109            }
110        }
111        if *container == ObjType::List {
112            once_by_id(&mut merging, shown)?;
113        }
114    }
115    if merging.pending_ops() == 0 {
116        return Ok(false);
117    }
118    merging.commit_with(
119        automerge::transaction::CommitOptions::default()
120            // The store derives it for the app whose record this is, on every device alike: the
121            // same bytes made apart merge as one change. Naming the app keeps that, and names
122            // who made it.
123            .with_message(tilo_actions::ActionContext::whole_edit_by(
124                &tilo_actions::Acting::by_app(app),
125            ))
126            .with_time(0),
127    );
128    let merged = merging
129        .get_last_local_change()
130        .ok_or(automerge::AutomergeError::Fail)?;
131    ApplyIncoming::apply_incoming(doc, vec![merged])?;
132    Ok(true)
133}
134
135/// The `id` the list element at `at` of `list` names, when it is a map naming one.
136pub fn element_id(doc: &AutoCommit, list: &automerge::ObjId, at: usize) -> Option<String> {
137    let Ok(Some((Value::Object(ObjType::Map), element))) = doc.get(list, at) else {
138        return None;
139    };
140    match doc.get(&element, "id") {
141        Ok(Some((Value::Scalar(id), _))) => Some(
142            id.as_str()
143                .map_or_else(|| format!("{:?}", id.as_ref()), str::to_owned),
144        ),
145        _ => None,
146    }
147}
148
149/// Keep each element of `list` that names an `id` once: the first holding it.
150fn once_by_id(
151    doc: &mut AutoCommit,
152    list: &automerge::ObjId,
153) -> Result<(), automerge::AutomergeError> {
154    let mut seen = std::collections::BTreeSet::new();
155    let mut at = 0;
156    while at < doc.length(list) {
157        match element_id(doc, list, at) {
158            Some(id) if seen.contains(&id) => doc.delete(list, at)?,
159            Some(id) => {
160                seen.insert(id);
161                at = at.saturating_add(1);
162            }
163            _ => at = at.saturating_add(1),
164        }
165    }
166    Ok(())
167}
168
169/// Where [`copy_value`] puts what it copies.
170enum Place<'a> {
171    Key(&'a str),
172    Index(usize),
173}
174
175/// What the value at `prop` of `obj` holds, the same wherever it is held: what tells one list
176/// element from another when two copies of a list are brought together.
177fn fingerprint(
178    doc: &AutoCommit,
179    obj: &automerge::ObjId,
180    prop: automerge::Prop,
181) -> Result<String, automerge::AutomergeError> {
182    Ok(match doc.get(obj, prop)? {
183        Some((Value::Scalar(value), _)) => format!("{:?}", value.as_ref()),
184        Some((Value::Object(ObjType::Text), id)) => format!("text:{:?}", doc.text(&id)?),
185        Some((Value::Object(ObjType::List), id)) => {
186            let items = (0..doc.length(&id))
187                .map(|at| fingerprint(doc, &id, at.into()))
188                .collect::<Result<Vec<String>, _>>()?;
189            format!("list:{items:?}")
190        }
191        Some((Value::Object(_), id)) => {
192            if let Some((Value::Scalar(named), _)) = doc.get(&id, "id")? {
193                return Ok(format!("id:{:?}", named.as_ref()));
194            }
195            let entries = doc
196                .keys(&id)
197                .map(|key| {
198                    let print = fingerprint(doc, &id, key.as_str().into())?;
199                    Ok((key, print))
200                })
201                .collect::<Result<Vec<(String, String)>, automerge::AutomergeError>>()?;
202            format!("map:{entries:?}")
203        }
204        None => String::new(),
205    })
206}
207
208/// Copy the value at `prop` of `from` to `place` in `to`, whole: a container is made anew with
209/// everything it holds.
210fn copy_value(
211    doc: &mut AutoCommit,
212    from: &automerge::ObjId,
213    prop: automerge::Prop,
214    to: &automerge::ObjId,
215    place: Place<'_>,
216) -> Result<(), automerge::AutomergeError> {
217    let Some((value, id)) = doc.get(from, prop)? else {
218        return Ok(());
219    };
220    let made = match (value, place) {
221        (Value::Scalar(value), Place::Key(key)) => {
222            doc.put(to, key, value.into_owned())?;
223            return Ok(());
224        }
225        (Value::Scalar(value), Place::Index(at)) => {
226            doc.insert(to, at, value.into_owned())?;
227            return Ok(());
228        }
229        (Value::Object(ty), Place::Key(key)) => doc.put_object(to, key, ty)?,
230        (Value::Object(ty), Place::Index(at)) => doc.insert_object(to, at, ty)?,
231    };
232    match doc.object_type(&id)? {
233        ObjType::Text => {
234            let text = doc.text(&id)?;
235            doc.splice_text(&made, 0, 0, &text)?;
236        }
237        ObjType::List => {
238            for at in 0..doc.length(&id) {
239                copy_value(doc, &id, at.into(), &made, Place::Index(at))?;
240            }
241        }
242        ObjType::Map | ObjType::Table => {
243            for key in doc.keys(&id).collect::<Vec<_>>() {
244                copy_value(doc, &id, key.as_str().into(), &made, Place::Key(&key))?;
245            }
246        }
247    }
248    Ok(())
249}
250
251/// Copy what the container `from` of `source` holds into the container `into` of `doc`, of the
252/// same type: a map's entries, a list's elements after those `into` holds, a text's characters.
253pub fn copy_across(
254    source: &AutoCommit,
255    from: &automerge::ObjId,
256    doc: &mut AutoCommit,
257    into: &automerge::ObjId,
258) -> Result<(), automerge::AutomergeError> {
259    let made = |doc: &mut AutoCommit, value: Value<'_>, place: Place<'_>| {
260        Ok::<_, automerge::AutomergeError>(match (value, place) {
261            (Value::Scalar(value), Place::Key(key)) => {
262                doc.put(into, key, value.into_owned())?;
263                None
264            }
265            (Value::Scalar(value), Place::Index(at)) => {
266                doc.insert(into, at, value.into_owned())?;
267                None
268            }
269            (Value::Object(ty), Place::Key(key)) => Some(doc.put_object(into, key, ty)?),
270            (Value::Object(ty), Place::Index(at)) => Some(doc.insert_object(into, at, ty)?),
271        })
272    };
273    match source.object_type(from)? {
274        ObjType::Text => {
275            let text = source.text(from)?;
276            let end = doc.length(into);
277            doc.splice_text(into, end, 0, &text)?;
278        }
279        ObjType::List => {
280            for at in 0..source.length(from) {
281                if let Some((value, held)) = source.get(from, at)? {
282                    let end = doc.length(into);
283                    if let Some(child) = made(doc, value, Place::Index(end))? {
284                        copy_across(source, &held, doc, &child)?;
285                    }
286                }
287            }
288        }
289        ObjType::Map | ObjType::Table => {
290            for key in source.keys(from).collect::<Vec<_>>() {
291                if let Some((value, held)) = source.get(from, key.as_str())?
292                    && let Some(child) = made(doc, value, Place::Key(&key))?
293                {
294                    copy_across(source, &held, doc, &child)?;
295                }
296            }
297        }
298    }
299    Ok(())
300}