-
Notifications
You must be signed in to change notification settings - Fork 0
/
crdt.h
525 lines (427 loc) · 13.4 KB
/
crdt.h
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
// Copyright (C) 2020 Felipe O. Carvalho
#pragma once
#include <cstdint>
#include <cstdio>
#include <optional>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <vector>
#include "lib.h"
// Primitives {{{
struct VersionVec {
using Repr = std::unordered_map<std::string, uint64_t>;
uint64_t max() const {
uint64_t sum = 0;
for (auto & [ _, v ] : data) {
sum += v;
}
return sum;
}
void increment(const std::string &replica_name, uint64_t delta) { data[replica_name] += delta; }
uint64_t localVersionForReplica(const std::string &replica_name) const {
if (auto *value = lookup(data, replica_name)) {
return *value;
}
return 0;
}
// Two version vectors v, w can be:
//
// (1) v < w : For all i, v[i] <= w[i] and there is at least one i such that v[i] < w[i];
// (2) v > w : For all i, v[i] >= w[i] and there is at least one i such that v[i] > w[i];
// (3) v = w : For all i, v[i] = w[i]; and
// (4) v || w : otherwise -- concurrent version vectors -- not(v < w) and not(v >= w).
bool operator<=(const VersionVec &other) const {
std::vector<const std::string *> replica_names;
for (auto & [ replica_name, _ ] : data) {
replica_names.push_back(&replica_name);
}
for (auto & [ replica_name, _ ] : other.data) {
replica_names.push_back(&replica_name);
}
for (auto *replica_name : replica_names) {
const bool leq =
localVersionForReplica(*replica_name) <= other.localVersionForReplica(*replica_name);
if (!leq) {
return false;
}
}
return true;
}
// When v < w, we say that v is dominated by w. [Marc Shapiro et al 2011]
// expresses the converse -- v is not dominated by w -- as (v || w) or (v >= w).
//
// My proof of equivalence:
//
// not(v < w) <=> (v || w) or (v >= w)
// <=> (not(v < w) and not(v >= w)) or (v >= w) (4)
// <=> (not(v < w) or (v >= w)) and (not(v >= w)) or (v >= w)) (Distribut.)
// <=> (not(v < w) or (v >= w)) and true (Complement)
// <=> not(v < w) or (v >= w) (Identity)
// <=> not(v < w) (v >= w implies not(v < w)
// so it can be dropped).
bool operator<(const VersionVec &other) const {
std::vector<const std::string *> replica_names;
for (auto & [ replica_name, _ ] : data) {
replica_names.push_back(&replica_name);
}
for (auto & [ replica_name, _ ] : other.data) {
replica_names.push_back(&replica_name);
}
bool at_least_one_strict_lt = false;
for (auto *replica_name : replica_names) {
const auto v = localVersionForReplica(*replica_name);
const auto w = other.localVersionForReplica(*replica_name);
if (v < w) {
at_least_one_strict_lt = true;
} else if (v > w) {
return false;
}
}
return at_least_one_strict_lt;
}
bool dominatedBy(const VersionVec &other) const { return *this < other; }
bool operator==(const VersionVec &other) const { return data == other.data; }
uint64_t mergeVersionForReplica(const std::string &replica_name, uint64_t other_version) {
if (other_version == 0) {
auto *version = lookup(data, replica_name);
return version ? *version : 0;
}
auto &max_version = data[replica_name];
max_version = std::max(max_version, other_version);
return max_version;
}
void merge(const VersionVec &other) {
std::vector<const std::string *> replica_names;
for (auto & [ replica_name, _ ] : data) {
replica_names.push_back(&replica_name);
}
for (auto & [ replica_name, _ ] : other.data) {
replica_names.push_back(&replica_name);
}
for (auto *replica_name : replica_names) {
mergeVersionForReplica(*replica_name, other.localVersionForReplica(*replica_name));
}
}
Repr::const_iterator begin() const { return data.begin(); }
Repr::const_iterator end() const { return data.end(); }
private:
Repr data;
};
namespace std {
template <>
struct hash<VersionVec> {
size_t operator()(const VersionVec &v) const {
size_t ret = 0;
for (const auto & [ key, value ] : v) {
if (value != 0) {
size_t h = 0;
hash_combine(h, key);
hash_combine(h, value);
ret ^= h;
}
}
return ret;
}
};
} // namespace std
// }}}
// Counters {{{
class GCounter {
public:
using ValueType = uint64_t;
using Payload = VersionVec;
// GCounter definition {{{
explicit GCounter(std::string name) : _name(std::move(name)) {}
unsigned int query() const { return _payload.max(); }
void increment(uint64_t delta = 1) {
printf("Incrementing by %llu at replica '%s'.\n", delta, _name.c_str());
_payload.increment(_name, delta);
}
void merge(const Payload &other) { _payload.merge(other); }
// }}}
const std::string &name() const { return _name; }
const Payload &payload() const { return _payload; }
void dump() { printf("GCounter('%s', %d)\n", _name.c_str(), query()); }
private:
const std::string _name;
Payload _payload;
};
class PNCounter {
public:
using ValueType = int64_t;
struct Payload {
VersionVec positive;
VersionVec negative;
};
// PNCounter definition {{{
explicit PNCounter(std::string name) : _name(std::move(name)) {}
int64_t query() const {
return (int64_t)_payload.positive.max() - (int64_t)_payload.negative.max();
}
void increment(int64_t delta) {
if (delta >= 0) {
printf("Incrementing by %lld at replica '%s'.\n", delta, _name.c_str());
_payload.positive.increment(_name, (uint64_t)delta);
} else {
printf("Decrementing by %lld at replica '%s'.\n", -delta, _name.c_str());
_payload.negative.increment(_name, (uint64_t)-delta);
}
}
void merge(const Payload &other) {
_payload.positive.merge(other.positive);
_payload.negative.merge(other.negative);
}
// }}}
const std::string &name() const { return _name; }
const Payload &payload() const { return _payload; }
void dump() { printf("PNCounter('%s', %lld)\n", _name.c_str(), query()); }
private:
const std::string _name;
Payload _payload;
};
// }}}
// Registers {{{
template <typename T>
class LWWRegister {
public:
using ValueType = std::optional<T>;
class Payload {
public:
Payload() : _value{}, _timestamp(0, 0), _empty(true) {}
void assign(const T *value, uint64_t now, const std::string &replica_name) {
if (value) {
_value = *value;
}
_timestamp = std::make_pair(now, hashedReplicaName(replica_name));
_empty = !value;
}
const T *query() const { return _empty ? nullptr : &_value; }
bool operator<=(const Payload &other) const { return _timestamp <= other._timestamp; }
void merge(const Payload &other) {
if (*this <= other) {
*this = other;
}
}
private:
static size_t hashedReplicaName(const std::string &name) {
// In the real and distributed world this would be a well-defined and
// stable hash function like SipHash-2-4, BLAKE, SHA1 etc.
return std::hash<std::string>{}(name);
}
T _value;
std::pair<uint64_t, size_t> _timestamp;
bool _empty;
};
// LWWRegister definition {{{
explicit LWWRegister(std::string name) : _name(std::move(name)) {}
void assign(const T &value) {
_now += 1;
_payload.assign(&value, _now, _name);
}
void clear() {
_now += 1;
_payload.assign(nullptr, _now, _name);
}
const ValueType query() const {
const auto *value = _payload.query();
return value ? std::optional(*value) : std::nullopt;
}
void merge(const Payload &other) { _payload.merge(other); }
// }}}
const std::string &name() const { return _name; }
const Payload &payload() const { return _payload; }
void dump() {
printf("LWWRegister('%s', ", _name.c_str());
ValuePrinter<ValueType> printer;
printer.print(query());
puts(")");
}
private:
const std::string _name;
uint64_t _now = 0;
Payload _payload;
};
template <typename T>
struct MVRegisterSetNode {
MVRegisterSetNode() : _empty(true) {}
MVRegisterSetNode(VersionVec version_vec)
: _empty(true), _version_vector(std::move(version_vec)) {}
MVRegisterSetNode(const T &value, VersionVec version_vec)
: _value(value), _empty(false), _version_vector(std::move(version_vec)) {}
bool operator==(const MVRegisterSetNode &other) const {
if (_empty != other._empty) {
return false;
}
if (_empty) {
return _version_vector == other._version_vector;
}
return _value == other._value && _version_vector == other._version_vector;
}
const T *value() const { return _empty ? nullptr : &_value; }
const VersionVec &versionVector() const { return _version_vector; }
private:
T _value;
bool _empty = true;
VersionVec _version_vector;
};
namespace std {
template <typename T>
struct hash<MVRegisterSetNode<T>> {
size_t operator()(const MVRegisterSetNode<T> &key) const {
size_t h = 0;
auto *value = key.value();
hash_combine(h, !!value);
if (value) {
hash_combine(h, *value);
}
hash_combine(h, key.versionVector());
return h;
}
};
} // namespace std
// MV-Register does not behave like a set, contrary to what one might expect
// since its payload is a set.
template <typename T>
class MVRegister {
public:
using ValueType = std::unordered_set<T>;
class Payload {
public:
void assign(ValueType value, const std::string &replica_name) {
_set.clear();
const auto version_vec = bumpVersionVector(replica_name);
if (value.empty()) {
_set.emplace(version_vec);
} else {
for (const auto &i : value) {
_set.emplace(i, version_vec);
}
}
}
ValueType query() const {
ValueType ret;
for (auto &node : _set) {
auto *value = node.value();
if (value) {
ret.insert(*value);
}
}
return ret;
}
void merge(const Payload &other) {
std::unordered_set<MVRegisterSetNode<T>> merged;
for (const MVRegisterSetNode<T> &i : _set) {
for (const MVRegisterSetNode<T> &j : other._set) {
if (!i.versionVector().dominatedBy(j.versionVector())) {
merged.insert(i);
}
if (!j.versionVector().dominatedBy(i.versionVector())) {
merged.insert(j);
}
}
}
_set = merged;
}
private:
VersionVec bumpVersionVector(const std::string &replica_name) {
VersionVec inc_version_vec;
for (auto &i : _set) {
inc_version_vec.merge(i.versionVector());
}
inc_version_vec.increment(replica_name, 1);
return inc_version_vec;
}
std::unordered_set<MVRegisterSetNode<T>> _set;
};
// MVRegister definition {{{
explicit MVRegister(std::string name) : _name(std::move(name)) {}
void assign(ValueType value) { _payload.assign(std::move(value), _name); }
const ValueType query() const { return _payload.query(); }
void merge(const Payload &other) { _payload.merge(other); }
// }}}
void clear() { assign({}); }
const std::string &name() const { return _name; }
const Payload &payload() const { return _payload; }
void dump() {
printf("MVRegister('%s', ", _name.c_str());
ValuePrinter<ValueType> printer;
printer.print(query());
puts(")");
}
private:
std::string _name;
Payload _payload;
};
// }}}
// Sets {{{
// NOTE(philix): Grow-Only Sets (GSets) are really simple so I didn't bother
// implementind them.
template <typename T>
class _2PSet {
public:
using ValueType = std::unordered_set<T>;
class Payload {
public:
ValueType query() const {
ValueType ret;
for (const auto &value : _add) {
if (!::contains(_rem, value)) {
ret.insert(value);
}
}
return ret;
}
bool contains(const T &value) const {
return ::contains(_add, value) && !::contains(_rem, value);
}
void add(const T &value) { _add.insert(value); }
[[nodiscard]] bool remove(const T &value) {
if (::contains(_add, value)) {
_rem.insert(value);
return true;
}
return false;
}
void merge(const Payload &other) {
_add.insert(other._add.begin(), other._add.end());
_rem.insert(other._rem.begin(), other._rem.end());
}
private:
std::unordered_set<T> _add;
std::unordered_set<T> _rem;
};
// 2PSet Definition {{{
explicit _2PSet(std::string name) : _name(std::move(name)) {}
bool contains(const T &value) const { return _payload.contains(value); }
void add(const T &value) { _payload.add(value); }
[[nodiscard]] bool remove(const T &value) { return _payload.remove(value); }
void merge(const Payload &other) { _payload.merge(other); }
// }}}
void addMany() {}
template <typename... Args>
void addMany(const T &value, Args... args) {
add(value);
addMany(args...);
}
bool removeMany() { return true; }
template <typename... Args>
[[nodiscard]] bool removeMany(const T &value, Args... args) {
const bool removed = remove(value);
return removeMany(args...) && removed;
}
ValueType query() const { return _payload.query(); }
const std::string &name() const { return _name; }
const Payload &payload() const { return _payload; }
void dump() {
printf("2PSet('%s', ", _name.c_str());
ValuePrinter<ValueType> printer;
printer.print(query());
puts(")");
}
private:
std::string _name;
Payload _payload;
};
// }}}