summaryrefslogtreecommitdiff
path: root/include/erebos/storage.h
blob: 01aeadafef310868af3fd9c6e6cd39dabc8ebe13 (plain)
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
#pragma once

#include <erebos/frp.h>
#include <erebos/time.h>
#include <erebos/uuid.h>

#include <algorithm>
#include <array>
#include <cstring>
#include <filesystem>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <variant>
#include <vector>

namespace erebos {

class Storage;
class PartialStorage;
class Digest;
class Ref;
class PartialRef;

template<class S> class RecordT;
typedef RecordT<Storage> Record;
typedef RecordT<PartialStorage> PartialRecord;
template<class S> class ObjectT;
typedef ObjectT<Storage> Object;
typedef ObjectT<PartialStorage> PartialObject;
class Blob;

template<typename T> class Stored;
template<typename T> class Head;

using std::bind;
using std::call_once;
using std::make_unique;
using std::move;
using std::string;
using std::vector;

class PartialStorage
{
public:
	typedef erebos::PartialRef Ref;

	PartialStorage(const PartialStorage &) = default;
	PartialStorage & operator=(const PartialStorage &) = delete;
	virtual ~PartialStorage() = default;

	bool operator==(const PartialStorage &) const;
	bool operator!=(const PartialStorage &) const;

	PartialRef ref(const Digest &) const;

	std::optional<PartialObject> loadObject(const Digest &) const;
	PartialRef storeObject(const PartialObject &) const;
	PartialRef storeObject(const PartialRecord &) const;
	PartialRef storeObject(const Blob &) const;

protected:
	friend class Storage;
	friend erebos::Ref;
	friend erebos::PartialRef;
	struct Priv;
	const std::shared_ptr<const Priv> p;
	PartialStorage(const std::shared_ptr<const Priv> & p): p(p) {}

public:
	// For test usage
	const Priv & priv() const { return *p; }
};

class Storage : public PartialStorage
{
public:
	typedef erebos::Ref Ref;

	Storage(const std::filesystem::path &);
	Storage(const Storage &) = default;
	Storage & operator=(const Storage &) = delete;

	Storage deriveEphemeralStorage() const;
	PartialStorage derivePartialStorage() const;

	std::optional<Ref> ref(const Digest &) const;
	Ref zref() const;

	std::optional<Object> loadObject(const Digest &) const;
	Ref storeObject(const Object &) const;
	Ref storeObject(const Record &) const;
	Ref storeObject(const Blob &) const;

	std::variant<Ref, std::vector<Digest>> copy(const PartialRef &) const;
	std::variant<Ref, std::vector<Digest>> copy(const PartialObject &) const;
	Ref copy(const Ref &) const;
	Ref copy(const Object &) const;

	template<typename T> Stored<T> store(const T &) const;

	template<typename T> std::optional<Head<T>> head(UUID id) const;
	template<typename T> std::vector<Head<T>> heads() const;
	template<typename T> Head<T> storeHead(const T &) const;
	template<typename T> Head<T> storeHead(const Stored<T> &) const;

	void storeKey(Ref pubref, const std::vector<uint8_t> &) const;
	std::optional<std::vector<uint8_t>> loadKey(Ref pubref) const;

protected:
	template<typename T> friend class Head;
	template<typename T> friend class WatchedHead;

	Storage(const std::shared_ptr<const Priv> & p): PartialStorage(p) {}

	std::optional<Ref> headRef(UUID type, UUID id) const;
	std::vector<std::tuple<UUID, Ref>> headRefs(UUID type) const;
	static UUID storeHead(UUID type, const Ref & ref);
	static bool replaceHead(UUID type, UUID id, const Ref & old, const Ref & ref);
	static std::optional<Ref> updateHead(UUID type, UUID id, const Ref & old, const std::function<Ref(const Ref &)> &);
	int watchHead(UUID type, UUID id, const std::function<void(const Ref &)>) const;
	void unwatchHead(UUID type, UUID id, int watchId) const;
};

class Digest
{
public:
	static constexpr size_t size = 32;

	Digest(const Digest &) = default;
	Digest & operator=(const Digest &) = default;

	explicit Digest(std::array<uint8_t, size> value): value(value) {}
	explicit Digest(const std::string &);
	explicit operator std::string() const;
	bool isZero() const;

	static Digest of(const std::vector<uint8_t> & content);
	template<class S> static Digest of(const ObjectT<S> &);

	const std::array<uint8_t, size> & arr() const { return value; }

	bool operator==(const Digest & other) const { return value == other.value; }
	bool operator!=(const Digest & other) const { return value != other.value; }
	bool operator<(const Digest & other) const { return value < other.value; }
	bool operator<=(const Digest & other) const { return value <= other.value; }
	bool operator>(const Digest & other) const { return value > other.value; }
	bool operator>=(const Digest & other) const { return value >= other.value; }

private:
	std::array<uint8_t, size> value;
};

template<class S>
Digest Digest::of(const ObjectT<S> & obj)
{
	return Digest::of(obj.encode());
}

class PartialRef
{
public:
	PartialRef(const PartialRef &) = default;
	PartialRef(PartialRef &&) = default;
	PartialRef & operator=(const PartialRef &) = default;
	PartialRef & operator=(PartialRef &&) = default;

	static PartialRef create(const PartialStorage &, const Digest &);

	const Digest & digest() const;

	operator bool() const;
	const PartialObject operator*() const;
	std::unique_ptr<PartialObject> operator->() const;

	const PartialStorage & storage() const;

protected:
	friend class Storage;
	struct Priv;
	std::shared_ptr<const Priv> p;
	PartialRef(const std::shared_ptr<const Priv> p): p(p) {}
};

class Ref : public PartialRef
{
public:
	Ref(const Ref &) = default;
	Ref(Ref &&) = default;
	Ref & operator=(const Ref &) = default;
	Ref & operator=(Ref &&) = default;

	bool operator==(const Ref &) const;
	bool operator!=(const Ref &) const;

	static std::optional<Ref> create(const Storage &, const Digest &);
	static Ref zcreate(const Storage &);

	explicit constexpr operator bool() const { return true; }
	const Object operator*() const;
	std::unique_ptr<Object> operator->() const;

	const Storage & storage() const;

	vector<Ref> previous() const;
	class Generation generation() const;
	vector<Digest> roots() const;

private:
	class Generation generationLocked() const;
	class vector<Digest> rootsLocked() const;

protected:
	Ref(const std::shared_ptr<const Priv> p): PartialRef(p) {}
};

template<class S>
class RecordT
{
public:
	class Item {
	public:
		struct UnknownType
		{
			std::string type;
			std::string value;
		};

		typedef std::variant<
			std::monostate,
			int,
			std::string,
			std::vector<uint8_t>,
			ZonedTime,
			UUID,
			typename S::Ref,
			UnknownType> Variant;

		Item(const std::string & name):
			Item(name, std::monostate()) {}
		Item(const std::string & name, Variant value):
			name(name), value(value) {}
		template<typename T>
		Item(const std::string & name, const Stored<T> & value):
			Item(name, value.ref()) {}

		Item(const Item &) = default;
		Item & operator=(const Item &) = delete;

		operator bool() const;

		std::optional<int> asInteger() const;
		std::optional<std::string> asText() const;
		std::optional<std::vector<uint8_t>> asBinary() const;
		std::optional<ZonedTime> asDate() const;
		std::optional<UUID> asUUID() const;
		std::optional<typename S::Ref> asRef() const;
		std::optional<UnknownType> asUnknown() const;

		template<typename T> std::optional<Stored<T>> as() const;

		const std::string name;
		const Variant value;
	};

private:
	RecordT(const std::shared_ptr<std::vector<Item>> & ptr):
		ptr(ptr) {}

public:
	RecordT(const std::vector<Item> &);
	RecordT(std::vector<Item> &&);
	std::vector<uint8_t> encode() const;

	const std::vector<Item> & items() const;
	Item item(const std::string & name) const;
	Item operator[](const std::string & name) const;
	std::vector<Item> items(const std::string & name) const;

private:
	friend ObjectT<S>;
	std::vector<uint8_t> encodeInner() const;
	static std::optional<RecordT<S>> decode(const S &,
			std::vector<uint8_t>::const_iterator,
			std::vector<uint8_t>::const_iterator);

	const std::shared_ptr<const std::vector<Item>> ptr;
};

extern template class RecordT<Storage>;
extern template class RecordT<PartialStorage>;

class Blob
{
public:
	Blob(const std::vector<uint8_t> &);

	const std::vector<uint8_t> & data() const { return *ptr; }
	std::vector<uint8_t> encode() const;

private:
	friend Object;
	friend PartialObject;
	std::vector<uint8_t> encodeInner() const;
	static Blob decode(
			std::vector<uint8_t>::const_iterator,
			std::vector<uint8_t>::const_iterator);

	Blob(std::shared_ptr<std::vector<uint8_t>> ptr): ptr(ptr) {}

	const std::shared_ptr<const std::vector<uint8_t>> ptr;
};

template<class S>
class ObjectT
{
public:
	typedef std::variant<
		RecordT<S>,
		Blob,
		std::monostate> Variants;

	ObjectT(const ObjectT<S> &) = default;
	ObjectT(Variants content): content(content) {}
	ObjectT<S> & operator=(const ObjectT<S> &) = default;

	static std::optional<std::tuple<ObjectT<S>, std::vector<uint8_t>::const_iterator>>
		decodePrefix(const S &,
				std::vector<uint8_t>::const_iterator,
				std::vector<uint8_t>::const_iterator);

	static std::optional<ObjectT<S>> decode(const S &, const std::vector<uint8_t> &);
	static std::optional<ObjectT<S>> decode(const S &,
			std::vector<uint8_t>::const_iterator,
			std::vector<uint8_t>::const_iterator);
	static std::vector<ObjectT<S>> decodeMany(const S &, const std::vector<uint8_t> &);
	std::vector<uint8_t> encode() const;
	static ObjectT<S> load(const typename S::Ref &);

	std::optional<RecordT<S>> asRecord() const;
	std::optional<Blob> asBlob() const;

private:
	friend RecordT<S>;
	friend Blob;

	Variants content;
};

extern template class ObjectT<Storage>;
extern template class ObjectT<PartialStorage>;

template<class S>
template<typename T>
std::optional<Stored<T>> RecordT<S>::Item::as() const
{
	if (auto ref = asRef())
		return Stored<T>::load(ref.value());
	return std::nullopt;
}

class Generation
{
public:
	Generation();
	static Generation next(const vector<Generation> &);

	explicit operator string() const;

private:
	Generation(size_t);
	size_t gen;
};

template<typename T>
class Stored
{
	Stored(Ref ref, T x);
	friend class Storage;
	friend class Head<T>;
public:
	Stored(const Stored &) = default;
	Stored(Stored &&) = default;
	Stored & operator=(const Stored &) = default;
	Stored & operator=(Stored &&) = default;

	Stored(Ref);
	static Stored<T> load(const Ref &);
	Ref store(const Storage &) const;

	bool operator==(const Stored<T> & other) const
	{ return p->ref.digest() == other.p->ref.digest(); }
	bool operator!=(const Stored<T> & other) const
	{ return p->ref.digest() != other.p->ref.digest(); }
	bool operator<(const Stored<T> & other) const
	{ return p->ref.digest() < other.p->ref.digest(); }
	bool operator<=(const Stored<T> & other) const
	{ return p->ref.digest() <= other.p->ref.digest(); }
	bool operator>(const Stored<T> & other) const
	{ return p->ref.digest() > other.p->ref.digest(); }
	bool operator>=(const Stored<T> & other) const
	{ return p->ref.digest() >= other.p->ref.digest(); }

	void init() const;
	const T & operator*() const { init(); return *p->val; }
	const T * operator->() const { init(); return p->val.get(); }

	Generation generation() const { return p->ref.generation(); }

	std::vector<Stored<T>> previous() const;
	bool precedes(const Stored<T> &) const;

	std::vector<Digest> roots() const { return p->ref.roots(); }

	const Ref & ref() const { return p->ref; }

private:
	struct Priv {
		const Ref ref;
		mutable std::once_flag once {};
		mutable std::unique_ptr<T> val {};
		mutable std::function<T()> init {};
	};
	std::shared_ptr<Priv> p;
};

template<typename T>
void Stored<T>::init() const
{
	call_once(p->once, [this]() {
		p->val = std::make_unique<T>(p->init());
		p->init = decltype(p->init)();
	});
}

template<typename T>
Stored<T> Storage::store(const T & val) const
{
	return Stored(val.store(*this), val);
}

template<typename T>
Stored<T>::Stored(Ref ref, T x):
	p(new Priv {
		.ref = move(ref),
		.val = make_unique<T>(move(x)),
	})
{
	call_once(p->once, [](){});
}

template<typename T>
Stored<T>::Stored(Ref ref):
	p(new Priv {
		.ref = move(ref),
	})
{
	p->init = [p = p.get()]() { return T::load(p->ref); };
}

template<typename T>
Stored<T> Stored<T>::load(const Ref & ref)
{
	return Stored(ref);
}

template<typename T>
Ref Stored<T>::store(const Storage & st) const
{
	if (st == p->ref.storage())
		return p->ref;
	return st.storeObject(*p->ref);
}

template<typename T>
std::vector<Stored<T>> Stored<T>::previous() const
{
	auto refs = p->ref.previous();
	vector<Stored<T>> res;
	res.reserve(refs.size());
	for (const auto & r : refs)
		res.push_back(Stored<T>::load(r));
	return res;
}

template<typename T>
bool Stored<T>::precedes(const Stored<T> & other) const
{
	for (const auto & x : other.previous()) {
		if (*this == x || precedes(x))
			return true;
	}
	return false;
}

template<typename T>
void filterAncestors(std::vector<Stored<T>> & xs)
{
	if (xs.size() < 2)
		return;

	std::sort(xs.begin(), xs.end());
	xs.erase(std::unique(xs.begin(), xs.end()), xs.end());

	std::vector<Stored<T>> old;
	old.swap(xs);

	for (auto i = old.begin(); i != old.end(); i++) {
		bool add = true;
		for (const auto & x : xs)
			if (i->precedes(x)) {
				add = false;
				break;
			}
		if (add)
			for (auto j = i + 1; j != old.end(); j++)
				if (i->precedes(*j)) {
					add = false;
					break;
				}
		if (add)
			xs.push_back(std::move(*i));
	}
}

template<class T> class WatchedHead;

template<class T>
class Head
{
	Head(UUID id, Stored<T> stored):
		mid(id), mstored(move(stored)) {}
	Head(UUID id, Ref ref, T val):
		mid(id), mstored(move(ref), move(val)) {}
	friend class Storage;
public:
	Head(UUID id, Ref ref): mid(id), mstored(ref) {}

	const T & operator*() const { return *mstored; }
	const T * operator->() const { return &(*mstored); }

	UUID id() const { return mid; }
	const Stored<T> & stored() const { return mstored; }
	const Ref & ref() const { return mstored.ref(); }

	optional<Head<T>> reload() const;
	std::optional<Head<T>> update(const std::function<Stored<T>(const Stored<T> &)> &) const;
	WatchedHead<T> watch(const std::function<void(const Head<T> &)> &) const;

	Bhv<T> behavior() const;

private:
	UUID mid;
	Stored<T> mstored;
};

template<class T>
class WatchedHead : public Head<T>
{
	friend class Head<T>;
	WatchedHead(const Head<T> & h, int watcherId):
		Head<T>(h), watcherId(watcherId) {}
	int watcherId;

public:
	WatchedHead(WatchedHead<T> && h):
		Head<T>(h), watcherId(h.watcherId)
	{ h.watcherId = -1; }

	WatchedHead<T> & operator=(WatchedHead<T> && h)
	{ watcherId = h.watcherId; h.watcherId = -1; return *this; }

	WatchedHead<T> & operator=(const Head<T> & h) {
		if (Head<T>::id() != h.id())
			throw std::runtime_error("WatchedHead ID mismatch");
		static_cast<Head<T> &>(*this) = h;
		return *this;
	}
	~WatchedHead();
};

template<class T>
class HeadBhv : public BhvSource<T>
{
public:
	HeadBhv(const Head<T> & head):
		whead(head.watch([this] (const Head<T> & cur) {
			BhvCurTime ctime;
			whead = cur;
			BhvImplBase::updated(ctime);
		})) {}

	T get(const BhvCurTime &, const std::monostate &) const { return *whead; }

private:
	WatchedHead<T> whead;
};

template<typename T>
std::optional<Head<T>> Storage::head(UUID id) const
{
	if (auto ref = headRef(T::headTypeId, id))
		return Head<T>(id, *ref);
	return std::nullopt;
}

template<typename T>
std::vector<Head<T>> Storage::heads() const
{
	std::vector<Head<T>> res;
	for (const auto & x : headRefs(T::headTypeId))
		res.emplace_back(std::get<UUID>(x), std::get<Ref>(x));
	return res;
}

template<typename T>
Head<T> Storage::storeHead(const T & val) const
{
	auto ref = val.store(*this);
	auto id = storeHead(T::headTypeId, ref);
	return Head(id, ref, val);
}

template<typename T>
Head<T> Storage::storeHead(const Stored<T> & val) const
{
	auto id = storeHead(T::headTypeId, val.ref());
	return Head(id, val);
}

template<typename T>
optional<Head<T>> Head<T>::reload() const
{
	return ref().storage().template head<T>(id());
}

template<typename T>
std::optional<Head<T>> Head<T>::update(const std::function<Stored<T>(const Stored<T> &)> & f) const
{
	auto res = Storage::updateHead(T::headTypeId, mid, ref(), [&f, this](const Ref & r) {
		return f(r.digest() == ref().digest() ? stored() : Stored<T>::load(r)).ref();
	});

	if (!res)
		return std::nullopt;
	if (res->digest() == ref().digest())
		return *this;
	return Head<T>(mid, *res);
}

template<typename T>
WatchedHead<T> Head<T>::watch(const std::function<void(const Head<T> &)> & watcher) const
{
	int wid = stored().ref().storage().watchHead(T::headTypeId, id(), [id = id(), watcher] (const Ref & ref) {
		watcher(Head<T>(id, ref));
	});
	return WatchedHead<T>(*this, wid);
}

template<typename T>
Bhv<T> Head<T>::behavior() const
{
	auto cur = reload();
	return make_shared<HeadBhv<T>>(cur ? *cur : *this);
}

template<class T>
WatchedHead<T>::~WatchedHead()
{
	if (watcherId >= 0)
		Head<T>::stored().ref().storage().unwatchHead(
				T::headTypeId, Head<T>::id(), watcherId);
}

template<class T>
vector<Ref> storedRefs(const vector<Stored<T>> & v)
{
	vector<Ref> res;
	res.reserve(v.size());
	for (const auto & x : v)
		res.push_back(x.ref());
	return res;
}

}

namespace std
{
	template<> struct hash<erebos::Digest>
	{
		std::size_t operator()(const erebos::Digest & dgst) const noexcept
		{
			std::size_t res;
			std::memcpy(&res, dgst.arr().data(), sizeof res);
			return res;
		}
	};
}