Skip to main content

tilo_resource/
batch.rs

1//! Writing a large amount of new content — a whole imported document, a
2//! pasted book — as a few changes instead of one operation at a time.
3//!
4//! Automerge applies every local operation to its op set on the spot, and
5//! each application pays for a seek plus an update of every column and index;
6//! an inline mark costs the most, because the mark index is rebuilt around
7//! each anchor. Ops a *change* makes on objects the document has not seen
8//! integrate as one run at the end of the op set, marks included. A
9//! [`ChangeWriter`] builds such changes directly, numbering ops exactly as
10//! Automerge will, on top of the document's own heads and actor, so the
11//! result is indistinguishable from the same writes made op by op — only
12//! several times faster to apply.
13
14use std::num::NonZeroU64;
15
16use automerge::{ActorId, ChangeHash, ObjId, ObjType, ReadDoc, ScalarValue, TextEncoding, legacy};
17
18use tilo_automerge::ApplyIncoming;
19
20use crate::model::Doc;
21
22/// Staged content bigger than this many ops is split over several changes,
23/// bounding the memory the expanded ops take before they are encoded.
24pub const OPS_PER_CHANGE: usize = 1 << 16;
25
26/// An object a [`ChangeWriter`] created, to write inside.
27#[derive(Clone, Debug, PartialEq, Eq)]
28pub struct Created(legacy::OpId);
29
30/// An inline mark over characters `start..end` of a text the writer creates.
31#[derive(Clone, Debug)]
32pub struct TextMark {
33    pub name: String,
34    pub value: ScalarValue,
35    pub start: usize,
36    pub end: usize,
37}
38
39fn legacy_obj(obj: &ObjId) -> legacy::ObjectId {
40    match obj {
41        ObjId::Root => legacy::ObjectId::Root,
42        ObjId::Id(counter, actor, _) => legacy::ObjectId::Id(legacy::OpId(*counter, actor.clone())),
43    }
44}
45
46/// Builds the changes that write new content into one document. See the
47/// module docs.
48pub struct ChangeWriter {
49    actor: ActorId,
50    seq: u64,
51    next: u64,
52    /// Counter of the first op of the change being built.
53    start: NonZeroU64,
54    deps: Vec<ChangeHash>,
55    ops: Vec<legacy::Op>,
56}
57
58impl ChangeWriter {
59    /// A writer continuing `doc`'s history as its actor: the open
60    /// transaction is committed first, and the changes this builds follow it.
61    /// `None` when the document can't take changes written this way (a text
62    /// encoding other than code points, an actor whose last change is
63    /// unreadable); write op by op instead.
64    pub fn continuing(doc: &mut Doc) -> Option<Self> {
65        if doc.text_encoding() != TextEncoding::UnicodeCodePoint {
66            return None;
67        }
68        let committed = doc.commit();
69        let actor = doc.get_actor().clone();
70        let last_seq = match committed {
71            Some(hash) => match doc.get_change_meta_by_hash(&hash) {
72                Some(meta) if meta.actor.as_ref() == &actor => meta.seq,
73                _ => return None,
74            },
75            None => doc
76                .get_changes_meta(&[])
77                .iter()
78                .filter(|meta| meta.actor.as_ref() == &actor)
79                .map(|meta| meta.seq)
80                .max()
81                .unwrap_or(0),
82        };
83        let heads = doc.get_heads();
84        let mut max_op = 0;
85        for head in &heads {
86            max_op = max_op.max(doc.get_change_meta_by_hash(head)?.max_op);
87        }
88        let start = NonZeroU64::new(max_op.saturating_add(1))?;
89        Some(Self {
90            actor,
91            seq: last_seq.saturating_add(1),
92            next: start.get(),
93            start,
94            deps: heads,
95            ops: Vec::new(),
96        })
97    }
98
99    /// Ops in the change being built.
100    pub fn pending(&self) -> usize {
101        self.ops.len()
102    }
103
104    fn push(
105        &mut self,
106        obj: legacy::ObjectId,
107        key: legacy::Key,
108        action: legacy::OpType,
109        insert: bool,
110    ) -> legacy::OpId {
111        let id = legacy::OpId(self.next, self.actor.clone());
112        self.next = self.next.saturating_add(1);
113        self.ops.push(legacy::Op {
114            action,
115            obj,
116            key,
117            pred: legacy::SortedVec::new(),
118            insert,
119        });
120        id
121    }
122
123    /// Create an object of `kind` under `key` of an object the document
124    /// already has.
125    pub fn make_in(&mut self, obj: &ObjId, key: &str, kind: ObjType) -> Created {
126        Created(self.push(
127            legacy_obj(obj),
128            legacy::Key::Map(key.into()),
129            legacy::OpType::Make(kind),
130            false,
131        ))
132    }
133
134    /// Create an object of `kind` under `key` of an object this writer
135    /// created.
136    pub fn make(&mut self, parent: &Created, key: &str, kind: ObjType) -> Created {
137        Created(self.put_op(parent, key, legacy::OpType::Make(kind)))
138    }
139
140    /// Put a scalar under `key` of an object this writer created.
141    pub fn put(&mut self, parent: &Created, key: &str, value: ScalarValue) {
142        self.put_op(parent, key, legacy::OpType::Put(value));
143    }
144
145    fn put_op(&mut self, parent: &Created, key: &str, action: legacy::OpType) -> legacy::OpId {
146        self.push(
147            legacy::ObjectId::Id(parent.0.clone()),
148            legacy::Key::Map(key.into()),
149            action,
150            false,
151        )
152    }
153
154    /// Create a text object under `key` of an object this writer created,
155    /// holding `text` with `marks` applied: per mark, a begin anchor after
156    /// the character before its start (not expanding) and an end anchor after
157    /// the character before its end (expanding), which is where a local
158    /// `ExpandMark::After` mark puts them. Marks must be non-empty and within
159    /// the text.
160    pub fn text(&mut self, parent: &Created, key: &str, text: &str, marks: &[TextMark]) {
161        let text_id = self.put_op(parent, key, legacy::OpType::Make(ObjType::Text));
162        let obj = legacy::ObjectId::Id(text_id);
163        let first = self.next;
164        let mut prev = legacy::ElementId::Head;
165        for ch in text.chars() {
166            let id = self.push(
167                obj.clone(),
168                legacy::Key::Seq(prev),
169                legacy::OpType::Put(ch.into()),
170                true,
171            );
172            prev = legacy::ElementId::Id(id);
173        }
174        for mark in marks {
175            let begin = self.anchor(first, mark.start);
176            let end = self.anchor(first, mark.end);
177            self.push(
178                obj.clone(),
179                legacy::Key::Seq(begin),
180                legacy::OpType::MarkBegin(legacy::MarkData {
181                    name: mark.name.as_str().into(),
182                    value: mark.value.clone(),
183                    expand: false,
184                }),
185                true,
186            );
187            self.push(
188                obj.clone(),
189                legacy::Key::Seq(end),
190                legacy::OpType::MarkEnd(true),
191                true,
192            );
193        }
194    }
195
196    /// The element a mark anchor at `pos` sits after, in a text whose
197    /// character 0 has op counter `first`: the character before `pos`, or
198    /// the head.
199    fn anchor(&self, first: u64, pos: usize) -> legacy::ElementId {
200        match pos.checked_sub(1).and_then(|p| u64::try_from(p).ok()) {
201            Some(p) => {
202                legacy::ElementId::Id(legacy::OpId(first.saturating_add(p), self.actor.clone()))
203            }
204            None => legacy::ElementId::Head,
205        }
206    }
207
208    /// Close the change being built; `None` if it has no ops.
209    fn seal(&mut self) -> Option<automerge::Change> {
210        if self.ops.is_empty() {
211            return None;
212        }
213        let change = automerge::Change::from(automerge::ExpandedChange {
214            operations: std::mem::take(&mut self.ops),
215            actor_id: self.actor.clone(),
216            hash: None,
217            seq: self.seq,
218            start_op: self.start,
219            time: 0,
220            message: None,
221            deps: std::mem::take(&mut self.deps),
222            extra_bytes: Vec::new(),
223            author: None,
224        });
225        self.deps = vec![change.hash()];
226        self.seq = self.seq.saturating_add(1);
227        // `next` only grows from `start`, which is at least one.
228        self.start = NonZeroU64::new(self.next).unwrap_or(self.start);
229        Some(change)
230    }
231
232    /// Seal the change being built and apply it to `doc`, the document this
233    /// writer continues. Apply as soon as a change is big enough
234    /// ([`OPS_PER_CHANGE`]): Automerge expands a change's ops in memory while
235    /// integrating it.
236    pub fn apply(&mut self, doc: &mut Doc) -> Result<(), automerge::AutomergeError> {
237        match self.seal() {
238            Some(change) => apply_change(doc, change),
239            None => Ok(()),
240        }
241    }
242}
243
244/// Apply one change, dropping the patch events Automerge logs for it unless
245/// a diff cursor will read them (see `tilo_automerge`).
246pub fn apply_change(
247    doc: &mut Doc,
248    change: automerge::Change,
249) -> Result<(), automerge::AutomergeError> {
250    doc.apply_incoming([change])
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256    use automerge::ROOT;
257    use automerge::marks::{ExpandMark, Mark};
258    use automerge::transaction::Transactable;
259
260    #[test]
261    fn changes_written_directly_read_like_the_same_writes_op_by_op() {
262        let mut direct = Doc::new().with_actor(ActorId::from(b"writer".as_slice()));
263        let items = direct.put_object(ROOT, "items", ObjType::Map).unwrap();
264        direct.commit();
265        let mut by_ops = direct
266            .fork()
267            .with_actor(ActorId::from(b"writer".as_slice()));
268
269        let mut writer = ChangeWriter::continuing(&mut direct).unwrap();
270        let item = writer.make_in(&items, "a", ObjType::Map);
271        writer.put(&item, "kind", "note".into());
272        let bold = TextMark {
273            name: "bold".into(),
274            value: true.into(),
275            start: 0,
276            end: 5,
277        };
278        writer.text(&item, "text", "hello world", &[bold]);
279        writer.apply(&mut direct).unwrap();
280
281        let item = by_ops.put_object(&items, "a", ObjType::Map).unwrap();
282        by_ops.put(&item, "kind", "note").unwrap();
283        let text = by_ops.put_object(&item, "text", ObjType::Text).unwrap();
284        by_ops.splice_text(&text, 0, 0, "hello world").unwrap();
285        by_ops
286            .mark(
287                &text,
288                Mark::new("bold".into(), true, 0, 5),
289                ExpandMark::After,
290            )
291            .unwrap();
292        by_ops.commit();
293
294        for doc in [&direct, &by_ops] {
295            let item = doc.get(&items, "a").unwrap().unwrap().1;
296            let text = doc.get(&item, "text").unwrap().unwrap().1;
297            assert_eq!(doc.text(&text).unwrap(), "hello world");
298            let marks = doc.marks(&text).unwrap();
299            assert_eq!(marks.len(), 1);
300            assert_eq!((marks[0].start, marks[0].end), (0, 5));
301        }
302        let item = direct.get(&items, "a").unwrap().unwrap().1;
303        direct.put(&item, "kind", "done").unwrap();
304        assert!(direct.commit().is_some());
305    }
306}