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
363
364
365
366
367
368
369
use crate::storage::TaskMap;
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::cmp::{Ord, Ordering};
use uuid::Uuid;
/// An Operation defines a single change to the task database, as stored locally in the replica.
///
/// Operations are the means by which changes are made to the database, typically batched together
/// into [`Operations`] and committed to the replica.
#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub enum Operation {
/// Create a new task.
///
/// On undo, the task is deleted.
Create { uuid: Uuid },
/// Delete an existing task.
///
/// On undo, the task's data is restored from old_task.
Delete { uuid: Uuid, old_task: TaskMap },
/// Update an existing task, setting the given property to the given value. If the value is
/// None, then the corresponding property is deleted.
///
/// On undo, the property is set back to its previous value.
Update {
uuid: Uuid,
property: String,
old_value: Option<String>,
value: Option<String>,
timestamp: DateTime<Utc>,
},
/// Mark a point in the operations history to which the user might like to undo. Users
/// typically want to undo more than one operation at a time (for example, most changes update
/// both the `modified` property and some other task property -- the user would like to "undo"
/// both updates at the same time). Applying an UndoPoint does nothing.
UndoPoint,
}
impl Operation {
/// Determine whether this is an undo point.
pub fn is_undo_point(&self) -> bool {
self == &Self::UndoPoint
}
/// Get the UUID for this function, if it has one.
pub fn get_uuid(&self) -> Option<Uuid> {
match self {
Operation::Create { uuid: u } => Some(*u),
Operation::Delete { uuid: u, .. } => Some(*u),
Operation::Update { uuid: u, .. } => Some(*u),
Operation::UndoPoint => None,
}
}
}
impl PartialOrd for Operation {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for Operation {
/// Define an order for operations.
///
/// First, orders by Uuid, with all UndoPoints first. Then, by type, with Creates, then Updates,
/// then Deletes. Updates are ordered by timestamp and, where that is equal, by the remaining
/// fields. This ordering is intended to be "human-readable", even in confusing situations like
/// multiple creations of the same task.
fn cmp(&self, other: &Self) -> Ordering {
use Operation::*;
use Ordering::*;
fn type_idx(op: &Operation) -> u8 {
match op {
UndoPoint => 0,
Create { .. } => 1,
Update { .. } => 2,
Delete { .. } => 3,
}
}
Equal
// First sort by UUID. UndoPoint's have `None` as uuid, and are thus sorted first.
.then(self.get_uuid().cmp(&other.get_uuid()))
// Then sort by type.
.then(type_idx(self).cmp(&type_idx(other)))
// Then sort within the same type. Only match arms with `self` and `other` the same
// type are possible, as we have already sorted by type.
.then_with(|| {
match (self, other) {
(Create { uuid: uuid1 }, Create { uuid: uuid2 }) => uuid1.cmp(uuid2),
(
Delete {
uuid: uuid1,
old_task: old_task1,
},
Delete {
uuid: uuid2,
old_task: old_task2,
},
) => uuid1.cmp(uuid2).then_with(|| {
let mut old_task1 = old_task1.iter().collect::<Vec<_>>();
old_task1.sort();
let mut old_task2 = old_task2.iter().collect::<Vec<_>>();
old_task2.sort();
old_task1.cmp(&old_task2)
}),
(
Update {
uuid: uuid1,
property: property1,
value: value1,
old_value: old_value1,
timestamp: timestamp1,
},
Update {
uuid: uuid2,
property: property2,
value: value2,
old_value: old_value2,
timestamp: timestamp2,
},
) => Equal
// Sort Updates principally by timestamp.
.then(uuid1.cmp(uuid2))
.then(timestamp1.cmp(timestamp2))
.then(property1.cmp(property2))
.then(value1.cmp(value2))
.then(old_value1.cmp(old_value2)),
(UndoPoint, UndoPoint) => Equal,
_ => unreachable!(),
}
})
}
}
/// Operations are a sequence of [`Operation`] values, which can be committed in a single
/// transaction with [`Replica::commit_operations`](crate::Replica::commit_operations).
pub type Operations = Vec<Operation>;
#[cfg(test)]
mod test {
use super::*;
use crate::errors::Result;
use chrono::Utc;
use pretty_assertions::assert_eq;
use Operation::*;
#[test]
fn test_json_create() -> Result<()> {
let uuid = Uuid::new_v4();
let op = Create { uuid };
let json = serde_json::to_string(&op)?;
assert_eq!(json, format!(r#"{{"Create":{{"uuid":"{}"}}}}"#, uuid));
let deser: Operation = serde_json::from_str(&json)?;
assert_eq!(deser, op);
Ok(())
}
#[test]
fn test_json_delete() -> Result<()> {
let uuid = Uuid::new_v4();
let old_task = vec![("foo".into(), "bar".into())].drain(..).collect();
let op = Delete { uuid, old_task };
let json = serde_json::to_string(&op)?;
assert_eq!(
json,
format!(
r#"{{"Delete":{{"uuid":"{}","old_task":{{"foo":"bar"}}}}}}"#,
uuid
)
);
let deser: Operation = serde_json::from_str(&json)?;
assert_eq!(deser, op);
Ok(())
}
#[test]
fn test_json_update() -> Result<()> {
let uuid = Uuid::new_v4();
let timestamp = Utc::now();
let op = Update {
uuid,
property: "abc".into(),
old_value: Some("true".into()),
value: Some("false".into()),
timestamp,
};
let json = serde_json::to_string(&op)?;
assert_eq!(
json,
format!(
r#"{{"Update":{{"uuid":"{}","property":"abc","old_value":"true","value":"false","timestamp":"{:?}"}}}}"#,
uuid, timestamp,
)
);
let deser: Operation = serde_json::from_str(&json)?;
assert_eq!(deser, op);
Ok(())
}
#[test]
fn test_json_update_none() -> Result<()> {
let uuid = Uuid::new_v4();
let timestamp = Utc::now();
let op = Update {
uuid,
property: "abc".into(),
old_value: None,
value: None,
timestamp,
};
let json = serde_json::to_string(&op)?;
assert_eq!(
json,
format!(
r#"{{"Update":{{"uuid":"{}","property":"abc","old_value":null,"value":null,"timestamp":"{:?}"}}}}"#,
uuid, timestamp,
)
);
let deser: Operation = serde_json::from_str(&json)?;
assert_eq!(deser, op);
Ok(())
}
#[test]
fn op_order() {
let mut uuid1 = Uuid::new_v4();
let mut uuid2 = Uuid::new_v4();
if uuid2 < uuid1 {
(uuid1, uuid2) = (uuid2, uuid1);
}
let now1 = Utc::now();
let now2 = now1 + chrono::Duration::seconds(1);
let create1 = Operation::Create { uuid: uuid1 };
let create2 = Operation::Create { uuid: uuid2 };
let update1 = Operation::Update {
uuid: uuid1,
property: "prop1".into(),
old_value: None,
value: None,
timestamp: now1,
};
let update2_now1_prop1_val1 = Operation::Update {
uuid: uuid2,
property: "prop1".into(),
old_value: None,
value: None,
timestamp: now1,
};
let update2_now1_prop1_val2 = Operation::Update {
uuid: uuid2,
property: "prop1".into(),
old_value: None,
value: Some("v".into()),
timestamp: now1,
};
let update2_now1_prop2_val1 = Operation::Update {
uuid: uuid2,
property: "prop2".into(),
old_value: None,
value: None,
timestamp: now1,
};
let update2_now1_prop2_val2 = Operation::Update {
uuid: uuid2,
property: "prop2".into(),
old_value: None,
value: Some("v".into()),
timestamp: now1,
};
let update2_now2_prop1_val1 = Operation::Update {
uuid: uuid2,
property: "prop1".into(),
old_value: None,
value: None,
timestamp: now2,
};
let update2_now2_prop1_val2 = Operation::Update {
uuid: uuid2,
property: "prop1".into(),
old_value: None,
value: Some("v".into()),
timestamp: now2,
};
let update2_now2_prop2_val1 = Operation::Update {
uuid: uuid2,
property: "prop2".into(),
old_value: None,
value: None,
timestamp: now2,
};
let update2_now2_prop2_val2_oldval1 = Operation::Update {
uuid: uuid2,
property: "prop2".into(),
old_value: None,
value: Some("v".into()),
timestamp: now2,
};
let update2_now2_prop2_val2_oldval2 = Operation::Update {
uuid: uuid2,
property: "prop2".into(),
old_value: Some("v2".into()),
value: Some("v".into()),
timestamp: now2,
};
let update2_now2_prop2_val2_oldval3 = Operation::Update {
uuid: uuid2,
property: "prop2".into(),
old_value: Some("v3".into()),
value: Some("v".into()),
timestamp: now2,
};
let delete1 = Operation::Delete {
uuid: uuid1,
old_task: TaskMap::from([("a".to_string(), "a".to_string())]),
};
let delete1b = Operation::Delete {
uuid: uuid1,
old_task: TaskMap::from([("b".to_string(), "b".to_string())]),
};
let delete2 = Operation::Delete {
uuid: uuid2,
old_task: TaskMap::from([("a".to_string(), "a".to_string())]),
};
let undo_point = Operation::UndoPoint;
// Specify order all of these operations should be in.
let total_order = vec![
undo_point,
create1,
update1,
delete1,
delete1b,
create2,
update2_now1_prop1_val1,
update2_now1_prop1_val2,
update2_now1_prop2_val1,
update2_now1_prop2_val2,
update2_now2_prop1_val1,
update2_now2_prop1_val2,
update2_now2_prop2_val1,
update2_now2_prop2_val2_oldval1,
update2_now2_prop2_val2_oldval2,
update2_now2_prop2_val2_oldval3,
delete2,
];
// Check that each operation compares the same as the comparison of its index. This is more
// thorough than just sorting a list, which would not perform every pairwise comparison.
for i in 0..total_order.len() {
for j in 0..total_order.len() {
let a = &total_order[i];
let b = &total_order[j];
assert_eq!(a.cmp(b), i.cmp(&j), "{a:?} <??> {b:?} ([{i}] <??> [{j}])");
}
}
}
}