1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
use super::change_collector::ChangeCollector;
use std::collections::{BTreeSet, HashMap};
use tracing::instrument;
use crate::{
change::Change,
columnar::Key as DocOpKey,
op_tree::OpSetMetadata,
storage::{DocOp, Document},
types::{ChangeHash, ElemId, Key, ObjId, ObjType, Op, OpId, OpIds, OpType},
ScalarValue,
};
#[derive(Debug, thiserror::Error)]
pub(crate) enum Error {
#[error("the document contained ops which were out of order")]
OpsOutOfOrder,
#[error("error reading operation: {0:?}")]
ReadOp(Box<dyn std::error::Error + Send + Sync + 'static>),
#[error("an operation contained an invalid action")]
InvalidAction,
#[error("an operation referenced a missing actor id")]
MissingActor,
#[error("invalid changes: {0}")]
InvalidChanges(#[from] super::change_collector::Error),
#[error("mismatching heads")]
MismatchingHeads,
#[error("missing operations")]
MissingOps,
#[error("succ out of order")]
SuccOutOfOrder,
}
pub(crate) struct LoadedObject {
pub(crate) id: ObjId,
pub(crate) parent: Option<ObjId>,
pub(crate) ops: Vec<crate::types::Op>,
pub(crate) obj_type: ObjType,
}
pub(crate) trait DocObserver {
type Output;
fn object_loaded(&mut self, object: LoadedObject);
fn finish(self, metadata: OpSetMetadata) -> Self::Output;
}
pub(crate) struct Reconstructed<Output> {
pub(crate) max_op: u64,
pub(crate) changes: Vec<Change>,
pub(crate) result: Output,
pub(crate) heads: BTreeSet<ChangeHash>,
}
#[instrument(skip(doc, observer))]
pub(crate) fn reconstruct_document<'a, O: DocObserver>(
doc: &'a Document<'a>,
mut observer: O,
) -> Result<Reconstructed<O::Output>, Error> {
let mut metadata = OpSetMetadata::from_actors(doc.actors().to_vec());
let mut current_object = LoadingObject::root();
let mut collector = ChangeCollector::new(doc.iter_changes())?;
let mut create_ops = HashMap::new();
let mut max_op = 0;
let mut objs_loaded = BTreeSet::new();
for op_res in doc.iter_ops() {
let doc_op = op_res.map_err(|e| Error::ReadOp(Box::new(e)))?;
max_op = std::cmp::max(max_op, doc_op.id.counter());
for succ in &doc_op.succ {
max_op = std::cmp::max(max_op, succ.counter());
}
let obj = doc_op.object;
check_opid(&metadata, *obj.opid())?;
let op = import_op(&mut metadata, doc_op)?;
tracing::trace!(?op, ?obj, "loading document op");
if let OpType::Make(obj_type) = op.action {
create_ops.insert(
ObjId::from(op.id),
CreateOp {
obj_type,
parent_id: obj,
},
);
};
if obj == current_object.id {
current_object.append_op(op.clone())?;
} else {
let create_op = match create_ops.get(&obj) {
Some(t) => Ok(t),
None => {
tracing::error!(
?op,
"operation referenced an object which we haven't seen a create op for yet"
);
Err(Error::OpsOutOfOrder)
}
}?;
if obj < current_object.id {
tracing::error!(?op, previous_obj=?current_object.id, "op referenced an object ID which was smaller than the previous object ID");
return Err(Error::OpsOutOfOrder);
} else {
let loaded = current_object.finish(&mut collector, &metadata)?;
objs_loaded.insert(loaded.id);
observer.object_loaded(loaded);
current_object =
LoadingObject::new(obj, Some(create_op.parent_id), create_op.obj_type);
current_object.append_op(op.clone())?;
}
}
}
let loaded = current_object.finish(&mut collector, &metadata)?;
objs_loaded.insert(loaded.id);
observer.object_loaded(loaded);
for (
obj_id,
CreateOp {
parent_id,
obj_type,
},
) in create_ops.into_iter()
{
if !objs_loaded.contains(&obj_id) {
observer.object_loaded(LoadedObject {
parent: Some(parent_id),
id: obj_id,
ops: Vec::new(),
obj_type,
})
}
}
let super::change_collector::CollectedChanges { history, heads } =
collector.finish(&metadata)?;
let expected_heads: BTreeSet<_> = doc.heads().iter().cloned().collect();
if expected_heads != heads {
tracing::error!(?expected_heads, ?heads, "mismatching heads");
return Err(Error::MismatchingHeads);
}
let result = observer.finish(metadata);
Ok(Reconstructed {
result,
changes: history.into_iter().map(Change::new).collect(),
heads,
max_op,
})
}
struct CreateOp {
parent_id: ObjId,
obj_type: ObjType,
}
struct LoadingObject {
id: ObjId,
parent_id: Option<ObjId>,
ops: Vec<Op>,
obj_type: ObjType,
preds: HashMap<OpId, Vec<OpId>>,
set_ops: HashMap<OpId, Key>,
inc_ops: HashMap<OpId, i64>,
}
impl LoadingObject {
fn root() -> Self {
Self::new(ObjId::root(), None, ObjType::Map)
}
fn new(id: ObjId, parent_id: Option<ObjId>, obj_type: ObjType) -> Self {
LoadingObject {
id,
parent_id,
ops: Vec::new(),
obj_type,
preds: HashMap::new(),
set_ops: HashMap::new(),
inc_ops: HashMap::new(),
}
}
fn append_op(&mut self, op: Op) -> Result<(), Error> {
if matches!(op.action, OpType::Put(_) | OpType::Make(_)) {
match op.key {
Key::Map(_) => {
self.set_ops.insert(op.id, op.key);
}
Key::Seq(ElemId(o)) => {
let elem_opid = if op.insert { op.id } else { o };
self.set_ops.insert(op.id, Key::Seq(ElemId(elem_opid)));
}
};
}
if let OpType::Increment(inc) = op.action {
self.inc_ops.insert(op.id, inc);
}
for succ in &op.succ {
self.preds.entry(*succ).or_default().push(op.id);
}
self.ops.push(op);
Ok(())
}
fn finish(
mut self,
collector: &mut ChangeCollector<'_>,
meta: &OpSetMetadata,
) -> Result<LoadedObject, Error> {
let mut ops = Vec::new();
for mut op in self.ops.into_iter() {
if let Some(preds) = self.preds.remove(&op.id) {
op.pred = meta.sorted_opids(preds.into_iter());
}
if let OpType::Put(ScalarValue::Counter(c)) = &mut op.action {
let inc_ops = op.succ.iter().filter_map(|s| self.inc_ops.get(s).copied());
c.increment(inc_ops);
}
collector.collect(self.id, op.clone())?;
ops.push(op)
}
for (opid, preds) in self.preds.into_iter() {
let key = self.set_ops.get(&preds[0]).ok_or_else(|| {
tracing::error!(?opid, ?preds, "no delete operation found");
Error::MissingOps
})?;
collector.collect(
self.id,
Op {
id: opid,
pred: meta.sorted_opids(preds.into_iter()),
insert: false,
succ: OpIds::empty(),
key: *key,
action: OpType::Delete,
},
)?;
}
Ok(LoadedObject {
id: self.id,
parent: self.parent_id,
ops,
obj_type: self.obj_type,
})
}
}
fn import_op(m: &mut OpSetMetadata, op: DocOp) -> Result<Op, Error> {
let key = match op.key {
DocOpKey::Prop(s) => Key::Map(m.import_prop(s)),
DocOpKey::Elem(ElemId(op)) => Key::Seq(ElemId(check_opid(m, op)?)),
};
for opid in &op.succ {
if m.actors.safe_get(opid.actor()).is_none() {
tracing::error!(?opid, "missing actor");
return Err(Error::MissingActor);
}
}
Ok(Op {
id: check_opid(m, op.id)?,
action: parse_optype(op.action, op.value)?,
key,
succ: m.try_sorted_opids(op.succ).ok_or(Error::SuccOutOfOrder)?,
pred: OpIds::empty(),
insert: op.insert,
})
}
fn check_opid(m: &OpSetMetadata, opid: OpId) -> Result<OpId, Error> {
match m.actors.safe_get(opid.actor()) {
Some(_) => Ok(opid),
None => {
tracing::error!("missing actor");
Err(Error::MissingActor)
}
}
}
fn parse_optype(action_index: usize, value: ScalarValue) -> Result<OpType, Error> {
match action_index {
0 => Ok(OpType::Make(ObjType::Map)),
1 => Ok(OpType::Put(value)),
2 => Ok(OpType::Make(ObjType::List)),
3 => Ok(OpType::Delete),
4 => Ok(OpType::Make(ObjType::Text)),
5 => match value {
ScalarValue::Int(i) => Ok(OpType::Increment(i)),
_ => {
tracing::error!(?value, "invalid value for counter op");
Err(Error::InvalidAction)
}
},
6 => Ok(OpType::Make(ObjType::Table)),
other => {
tracing::error!(action = other, "unknown action type");
Err(Error::InvalidAction)
}
}
}