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
|
mod vector_clock;
use std::fmt::Display;
use uuid::Uuid;
use crate::vector_clock::VectorClock;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum Error {
#[error("object with ID {0} not found")]
NotFound(DerivedId),
}
#[derive(Default)]
pub struct Doc {
ops: Vec<Op>,
}
impl Doc {
pub fn append_op(&mut self, actor_id: &Uuid, payload: OpPayload) {
// Increment the last clock for the provided actor
let clock = self
.ops
.last()
.map(|Op { clock, .. }| clock.inc(actor_id))
// For an empty document, initialize a new clock
.unwrap_or_else(|| VectorClock::default().inc(actor_id));
self.ops.push(Op {
id: Uuid::now_v7(),
clock,
payload,
});
}
pub fn realize(&self) -> Result<RealizedDoc, Error> {
let mut realized = RealizedDoc::default();
for op in &self.ops {
op.apply(&mut realized)?;
}
Ok(realized)
}
}
#[derive(Debug)]
pub struct Op {
id: Uuid,
payload: OpPayload,
clock: VectorClock,
}
impl Op {
fn apply(&self, realized: &mut RealizedDoc) -> Result<(), Error> {
match &self.payload {
OpPayload::CreateGrid {
rows,
base_cells_per_row,
} => {
let rows = (0..*rows)
.map(|row_idx| {
let cells = (0..*base_cells_per_row)
.map(|cell_idx| Cell {
id: self.id.derive_id("cell", cell_idx),
})
.collect();
Row {
id: self.id.derive_id("row", row_idx),
cells,
}
})
.collect();
realized.grids.push(Grid {
id: self.id.derive_id("grid", 0),
rows,
});
}
OpPayload::ChangeSubdivisions {
grid_id,
row_id,
start_cell_id,
end_cell_id,
subdivisions,
} => {
let grid = realized
.grids
.iter_mut()
.find(|g| g.id == *grid_id)
.ok_or(Error::NotFound(grid_id.clone()))?;
let row = grid
.rows
.iter_mut()
.find(|r| r.id == *row_id)
.ok_or(Error::NotFound(row_id.clone()))?;
let start_cell_idx = row
.cells
.iter()
.position(|c| c.id == *start_cell_id)
.ok_or(Error::NotFound(start_cell_id.clone()))?;
let end_cell_idx = row
.cells
.iter()
.position(|c| c.id == *end_cell_id)
.ok_or(Error::NotFound(end_cell_id.clone()))?;
let (i, j) = if start_cell_idx <= end_cell_idx {
(start_cell_idx, end_cell_idx)
} else {
(end_cell_idx, start_cell_idx)
};
row.cells.splice(
i..(j + 1),
(0..*subdivisions).map(|subdivision_idx| Cell {
id: self.id.derive_id("cell", subdivision_idx),
}),
);
}
}
Ok(())
}
}
#[derive(Debug)]
pub enum OpPayload {
CreateGrid {
rows: usize,
base_cells_per_row: usize,
},
ChangeSubdivisions {
grid_id: DerivedId,
row_id: DerivedId,
start_cell_id: DerivedId,
end_cell_id: DerivedId,
subdivisions: usize,
},
}
#[derive(Default, Debug)]
pub struct RealizedDoc {
grids: Vec<Grid>,
}
#[derive(Debug)]
pub struct Grid {
id: DerivedId,
rows: Vec<Row>,
}
#[derive(Debug)]
pub struct Row {
id: DerivedId,
cells: Vec<Cell>,
}
#[derive(Debug)]
pub struct Cell {
id: DerivedId,
}
#[derive(PartialEq, Eq, Debug, Clone)]
pub struct DerivedId {
// TODO These IDs can be interned on the Doc
id: Uuid,
tag: &'static str,
index: usize,
}
impl Display for DerivedId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}:{}:{}", self.id, self.tag, self.index)
}
}
trait DerivableId {
fn derive_id(&self, tag: &'static str, index: usize) -> DerivedId;
}
impl DerivableId for Uuid {
fn derive_id(&self, tag: &'static str, index: usize) -> DerivedId {
DerivedId {
id: self.clone(),
tag,
index,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn realize_doc() {
let actor_id = Uuid::now_v7();
let mut doc = Doc::default();
doc.append_op(
&actor_id,
OpPayload::CreateGrid {
rows: 4,
base_cells_per_row: 16,
},
);
{
let realized = doc.realize().unwrap();
assert!(realized.grids.len() == 1);
let grid = realized.grids.first().unwrap();
assert!(grid.rows.len() == 4);
let row = grid.rows.first().unwrap();
assert!(row.cells.len() == 16);
doc.append_op(
&actor_id,
OpPayload::ChangeSubdivisions {
grid_id: grid.id.clone(),
row_id: row.id.clone(),
start_cell_id: row.cells[0].id.clone(),
end_cell_id: row.cells[3].id.clone(),
subdivisions: 3,
},
);
}
{
let realized = doc.realize().unwrap();
assert_eq!(realized.grids[0].rows[0].cells.len(), 15);
assert_eq!(realized.grids[0].rows[1].cells.len(), 16);
let grid = &realized.grids[0];
let row = &grid.rows[0];
doc.append_op(
&actor_id,
OpPayload::ChangeSubdivisions {
grid_id: grid.id.clone(),
row_id: row.id.clone(),
start_cell_id: row.cells[0].id.clone(),
end_cell_id: row.cells.last().unwrap().id.clone(),
subdivisions: 12,
},
);
}
{
let realized = doc.realize().unwrap();
assert_eq!(realized.grids[0].rows[0].cells.len(), 12);
assert_eq!(realized.grids[0].rows[1].cells.len(), 16);
}
}
}
|