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
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
|
//! What pardes keeps on disk, through xitdb (docs/next-store.md): the
//! user's state file, `pardes.xitdb` in the DumpDir ($XDG_DATA_HOME/pardes,
//! else ~/.local/share/pardes), which every session of the user's shares.
//! Its root is a map:
//!
//! recent Recent's list (recent.zig), a line a file, the newest first
//!
//! A session reads Recent at its start, and again on use (Recent, /recent)
//! when the file's committed size says another session committed since. A
//! step that changed it writes it at its end in one transaction under the
//! file's lock, what another session committed since read and merged under
//! this session's changes first (`recent.List.merge`). Held by another
//! session, the lock is tried again at the next step: a frame never waits
//! for one. Recent's commits are not fsynced, as its file never was: a crash
//! keeps every one committed, a power loss may lose the last.
//!
//! A file there that is no database of pardes's (another program's, one a
//! power loss tore) is kept beside it as `pardes.xitdb.broken` and a new one
//! started: pardes always starts. The test host's is a `.memory` database,
//! the same code (`Kind.memory`).
const Db = @This();
const std = @import("std");
const xitdb = @import("xitdb");
const pardes = @import("pardes.zig");
const recent = @import("recent.zig");
const Pardes = pardes.Pardes;
pub const Disk = xitdb.Database(.buffered_file, u256);
pub const Memory = xitdb.Database(.memory, u256);
/// Where a session keeps what outlives it: nowhere (a unit test, a replica,
/// a replay), its user's state file, or memory (the test host's).
pub const Kind = enum { off, disk, memory };
pub const file_name = "pardes.xitdb";
/// The hash every key of these databases is: a field's or a label's name
/// hashed, a blob keyed by its content's.
const hash_id = xitdb.HashId.fromBytes("blk3");
/// Recent's lines are read this far at most (200 of the longest paths).
const recent_max = 1 << 20;
kind: Kind = .off,
open: ?*Open = null,
/// The state file's committed size when this session last read or wrote
/// Recent: another session's commit moves it.
seen: u64 = 0,
/// Recent was read (or there was none): only then is it written, so a
/// session never writes over a list it did not read.
loaded: bool = false,
/// The open database. Its own allocation: a database points at its buffer,
/// and a Restore's new core takes it over from the old one.
pub const Open = struct {
gpa: std.mem.Allocator,
buffer: std.Io.Writer.Allocating,
where: union(enum) {
disk: struct { db: Disk, file: std.Io.File, path: []u8 },
memory: struct { db: Memory },
},
};
fn ioOf() std.Io {
return std.Io.Threaded.global_single_threaded.io();
}
/// A name's key: its BLAKE3 hash.
pub fn key(name: []const u8) u256 {
var out: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(name, &out, .{});
return std.mem.readInt(u256, &out, .big);
}
pub fn deinit(db: *Db) void {
const o = db.open orelse return;
db.open = null;
switch (o.where) {
.disk => |*d| {
d.file.close(ioOf());
o.gpa.free(d.path);
},
.memory => {},
}
o.buffer.deinit();
o.gpa.destroy(o);
}
/// The state file's path for the DumpDir setting `dir_setting`, made in
/// `buf`; null with no home to keep it in.
pub fn statePath(buf: []u8, dir_setting: []const u8) ?[]const u8 {
var dir_buf: [4096]u8 = undefined;
const dir = pardes.dump.directory(&dir_buf, dir_setting) orelse return null;
return std.fmt.bufPrint(buf, "{s}/" ++ file_name, .{dir}) catch null;
}
/// The database, opened (made, when its file is not there) at its first use
/// and again once the DumpDir names another: null when this session keeps
/// none, or it cannot be had now (the next use tries again).
fn opened(db: *Db, p: *Pardes) ?*Open {
switch (db.kind) {
.off => return null,
.disk => {
var buf: [4200]u8 = undefined;
const path = statePath(&buf, p.settings.dump_dir.get()) orelse return null;
if (db.open) |o| {
// The same file still: another session's compaction renames
// a new one over it, which this one then opens.
if (std.mem.eql(u8, o.where.disk.path, path) and !replaced(o)) return o;
// The DumpDir moved: its own file, read afresh.
db.deinit();
db.seen = 0;
}
db.open = openDisk(p.recentGpa(), path) catch return null;
},
.memory => if (db.open == null) {
const gpa = p.recentGpa();
const o = gpa.create(Open) catch return null;
o.* = .{ .gpa = gpa, .buffer = .init(gpa), .where = undefined };
o.where = .{ .memory = .{ .db = Memory.init(ioOf(), .{ .buffer = &o.buffer, .hash_id = hash_id }) catch {
o.buffer.deinit();
gpa.destroy(o);
return null;
} } };
db.open = o;
},
}
return db.open;
}
/// The state file at `path`, its directory made: a new one is written under
/// the file's lock (two sessions starting at once write one header), and a
/// file that is no database of pardes's is put aside for a new one.
fn openDisk(gpa: std.mem.Allocator, path: []const u8) !*Open {
pardes.turn.yield();
defer pardes.turn.back();
const io = ioOf();
const cwd = std.Io.Dir.cwd();
if (std.fs.path.dirname(path)) |dir| try cwd.createDirPath(io, dir);
const o = try gpa.create(Open);
errdefer gpa.destroy(o);
o.* = .{ .gpa = gpa, .buffer = .init(gpa), .where = undefined };
errdefer o.buffer.deinit();
const own = try gpa.dupe(u8, path);
errdefer gpa.free(own);
var tried_aside = false;
while (true) {
const file = try cwd.createFile(io, path, .{ .read = true, .truncate = false });
const fresh = (file.length(io) catch 0) == 0;
// Another session making it now: it has its header in a moment.
if (fresh and !(file.tryLock(io, .exclusive) catch false)) {
file.close(io);
return error.WouldBlock;
}
const made = Disk.init(io, .{ .file = file, .buffer = &o.buffer, .fsync = false, .hash_id = hash_id });
if (fresh) file.unlock(io);
if (made) |d| {
o.where = .{ .disk = .{ .db = d, .file = file, .path = own } };
return o;
} else |err| {
file.close(io);
switch (err) {
error.InvalidDatabase, error.InvalidVersion, error.InvalidHashSize, error.TruncatedDatabase, error.InvalidEnumTag, error.EndOfStream => {},
else => return err,
}
if (tried_aside) return err;
tried_aside = true;
var aside_buf: [4300]u8 = undefined;
try cwd.rename(path, cwd, try std.fmt.bufPrint(&aside_buf, "{s}.broken", .{path}), io);
}
}
}
/// Whether the file at the open one's path is another now (a compaction's).
fn replaced(o: *Open) bool {
const d = o.where.disk;
pardes.turn.yield();
defer pardes.turn.back();
const io = ioOf();
const open_st = d.file.stat(io) catch return false;
const path_st = std.Io.Dir.cwd().statFile(io, d.path, .{}) catch return false;
return open_st.inode != path_st.inode;
}
fn committed(o: *Open) !u64 {
pardes.turn.yield();
defer pardes.turn.back();
return switch (o.where) {
inline else => |*w| w.db.committedSize(),
};
}
/// The file's lock, taken (`wait`: waited for): false when another session
/// holds it. A database in memory is this process's alone.
fn lock(o: *Open, wait: bool) bool {
const file = switch (o.where) {
.disk => |d| d.file,
.memory => return true,
};
pardes.turn.yield();
defer pardes.turn.back();
if (wait) {
file.lock(ioOf(), .exclusive) catch return false;
return true;
}
return file.tryLock(ioOf(), .exclusive) catch false;
}
/// The database, its file locked for a transaction (`wait`: waited for). A
/// file a compaction replaced while this waited is let go, and the new one
/// opened and locked.
fn locked(db: *Db, p: *Pardes, wait: bool) error{ NoStateFile, Busy }!*Open {
for (0..2) |_| {
const o = db.opened(p) orelse return error.NoStateFile;
if (!lock(o, wait)) return error.Busy;
if (o.where == .memory or !replaced(o)) return o;
unlock(o);
db.deinit();
db.seen = 0;
}
return error.Busy;
}
fn unlock(o: *Open) void {
switch (o.where) {
.disk => |d| d.file.unlock(ioOf()),
.memory => {},
}
}
// ---- Recent ----
/// Recent's lines, `gpa`'s; null when the database holds none.
fn recentText(o: *Open, gpa: std.mem.Allocator) !?[]const u8 {
pardes.turn.yield();
defer pardes.turn.back();
switch (o.where) {
inline else => |*w| {
const DB = @TypeOf(w.db);
const root = try DB.HashMap(.read_only).init(w.db.rootCursor().readOnly());
const c = (try root.getCursor(key("recent"))) orelse return null;
return try c.readBytesAlloc(gpa, recent_max);
},
}
}
fn putRecent(o: *Open, text: []const u8) !void {
pardes.turn.yield();
defer pardes.turn.back();
switch (o.where) {
inline else => |*w| {
const DB = @TypeOf(w.db);
try w.db.runContext(struct {
text: []const u8,
pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void {
const root = try DB.HashMap(.read_write).init(cursor.*);
try root.put(key("recent"), .{ .bytes = ctx.text });
}
}{ .text = text });
},
}
}
/// What other sessions committed to Recent since this one last read or
/// wrote it, read under this session's changes: at the start, and on use.
pub fn readRecent(db: *Db, p: *Pardes) void {
const o = db.opened(p) orelse return;
db.loaded = true;
db.mergeRecent(p, o);
}
fn mergeRecent(db: *Db, p: *Pardes, o: *Open) void {
const size = committed(o) catch return;
if (size == db.seen) return;
const gpa = p.recentGpa();
const text = recentText(o, gpa) catch return;
defer if (text) |t| gpa.free(t);
p.recent.merge(gpa, text orelse "");
db.seen = size;
}
/// Recent written when it changed, at the end of a step and at the end
/// (`wait`: the lock is waited for there, never in a step).
pub fn writeRecent(db: *Db, p: *Pardes, wait: bool) void {
if (!p.recent.dirty) return;
if (db.kind != .off) written: {
if (!db.loaded) return;
const o = db.locked(p, wait) catch |err| switch (err) {
// Another session's lock: the next step tries again.
error.Busy => return,
error.NoStateFile => break :written,
};
defer unlock(o);
db.mergeRecent(p, o);
p.recent.changedFirst();
const gpa = p.recentGpa();
var text: std.Io.Writer.Allocating = .init(gpa);
defer text.deinit();
const entries = p.recent.entries.items;
for (entries[0..@min(entries.len, recent.cap)]) |e| recent.List.writeEntry(e, &text.writer) catch break :written;
// The disk refused it: kept for no one, as before.
putRecent(o, text.written()) catch break :written;
db.seen = committed(o) catch 0;
}
for (p.recent.entries.items) |*e| e.changed = false;
p.recent.dirty = false;
}
// ---- the dumps ----
//
// Each Dump is a labelled entry of the state file's `dumps`, written in one
// transaction, fsynced (a dump is worth the wait; Recent's commits are not):
// a full disk or a kill in the middle leaves the dump before it whole, as
// xitdb writes its header last.
//
// dumps/<label> seq, date (seconds, UTC), panes, size, the session (a
// database of its own: walk.Put's maps, its bytes one
// value) and the hashes of the texts it keeps beside it
// blobs/<hash> each such text once, by its BLAKE3 hash: an unchanged
// text is written once, however many dumps keep it
// last the newest dump's label
// seq the next dump's number
//
// A Dump is labelled `pardes-<date>-<time>` (UTC; `-2` and on for another
// in the same second), an Upgrade's `upgrade-<pid>`. The newest `kept` are
// kept: one more drops the oldest, and the texts no kept dump names, in
// the same transaction. A dump travels as an image, a database in memory
// holding it alone in the same shape (`image`): what a Dump hands its host,
// what a Restore of a label is read into (`imageOf`), what `Dump export`
// and a handover write as a file, and what `-l` and `Restore <path>` read.
/// How many dumps the state file keeps, the newest.
pub const kept = 32;
/// The text of a dump's blob is its BLAKE3 hash's key.
fn blobKey(hash: *const [32]u8) u256 {
return std.mem.readInt(u256, hash, .big);
}
const session_tag = "db".*;
/// A dump's image: the one dump `label` (its session's bytes, the texts it
/// keeps beside it and its pane count) in a database in memory, `last`
/// naming it, `gpa`'s. Of the same session, the same bytes: its ids are
/// std.Io.failing's zeros, never random ones.
pub fn image(gpa: std.mem.Allocator, label: []const u8, session: []const u8, blobs: []const pardes.walk.Blob, panes: u64) ![]u8 {
var buf: std.Io.Writer.Allocating = .init(gpa);
errdefer buf.deinit();
var db = try Memory.init(std.Io.failing, .{ .buffer = &buf, .hash_id = hash_id, .file_id = 0 });
try db.runContext(struct {
label: []const u8,
session: []const u8,
blobs: []const pardes.walk.Blob,
panes: u64,
pub fn run(ctx: @This(), cursor: *Memory.Cursor(.read_write)) !void {
const root = try Memory.HashMap(.read_write).init(cursor.*);
try root.put(key("last"), .{ .bytes = ctx.label });
const dumps = try Memory.HashMap(.read_write).init(try root.putCursor(key("dumps")));
try dumps.putKey(key(ctx.label), .{ .bytes = ctx.label });
const entry = try Memory.HashMap(.read_write).init(try dumps.putCursor(key(ctx.label)));
try entry.put(key("session"), .{ .bytes_object = .{ .value = ctx.session, .format_tag = session_tag } });
try entry.put(key("panes"), .{ .uint = ctx.panes });
const hashes = try Memory.ArrayList(.read_write).init(try entry.putCursor(key("blobs")));
const texts = try Memory.HashMap(.read_write).init(try root.putCursor(key("blobs")));
for (ctx.blobs) |*b| {
try hashes.append(.{ .bytes = &b.hash });
try texts.put(blobKey(&b.hash), .{ .bytes = b.bytes });
}
}
}{ .label = label, .session = session, .blobs = blobs, .panes = panes });
return buf.toOwnedSlice();
}
/// Whether `bytes` are a database of xitdb's (an image, a state file):
/// what `-l` and `Restore <path>` tell from an old dump by.
pub fn isImage(bytes: []const u8) bool {
return std.mem.startsWith(u8, bytes, "xit");
}
/// A dump's image opened for a load: the session's database, and the
/// texts its blobs are. The image's bytes are the caller's while it is open.
pub const Read = struct {
gpa: std.mem.Allocator,
image_buf: std.Io.Writer.Allocating,
image: Memory,
session_buf: std.Io.Writer.Allocating,
session: Memory,
label: []u8,
panes: u64,
/// The image `bytes` at its dump `label`, else its last one.
pub fn open(gpa: std.mem.Allocator, bytes: []const u8, label: ?[]const u8) !*Read {
if (!isImage(bytes)) return error.NotADump;
const r = try gpa.create(Read);
errdefer gpa.destroy(r);
// Read, never written: the bytes are borrowed, never freed here.
var borrowed: std.ArrayList(u8) = .fromOwnedSlice(@constCast(bytes));
r.* = .{ .gpa = gpa, .image_buf = .fromArrayList(gpa, &borrowed), .image = undefined, .session_buf = undefined, .session = undefined, .label = &.{}, .panes = 0 };
r.image = Memory.init(std.Io.failing, .{ .buffer = &r.image_buf }) catch return error.NotADump;
const top = Memory.HashMap(.read_only).init(r.image.rootCursor().readOnly()) catch return error.NotADump;
r.label = if (label) |l| try gpa.dupe(u8, l) else last: {
const c = (top.getCursor(key("last")) catch return error.NotADump) orelse return error.NoDump;
break :last @constCast(c.readBytesAlloc(gpa, 4096) catch return error.NotADump);
};
errdefer gpa.free(r.label);
const entry = try entryOf(Memory, top, r.label) orelse return error.NoDump;
r.panes = if (entry.getCursor(key("panes")) catch null) |c| c.readUint() catch 0 else 0;
const at = (entry.getCursor(key("session")) catch return error.NotADump) orelse return error.NotADump;
const session: []u8 = @constCast(at.readBytesAlloc(gpa, null) catch |err| return if (err == error.OutOfMemory) error.OutOfMemory else error.NotADump);
var owned: std.ArrayList(u8) = .fromOwnedSlice(session);
r.session_buf = .fromArrayList(gpa, &owned);
errdefer r.session_buf.deinit();
r.session = Memory.init(std.Io.failing, .{ .buffer = &r.session_buf }) catch return error.NotADump;
return r;
}
pub fn close(r: *Read) void {
r.session_buf.deinit();
r.gpa.free(r.label);
r.gpa.destroy(r);
}
/// The session's roots.
pub fn root(r: *Read) Memory.Cursor(.read_only) {
return r.session.rootCursor().readOnly();
}
/// The texts the session's blobs are, by hash.
pub fn blobs(r: *Read) !Memory.HashMap(.read_only) {
const root_map = try Memory.HashMap(.read_only).init(r.image.rootCursor().readOnly());
return Memory.HashMap(.read_only).init((try root_map.getCursor(key("blobs"))) orelse return error.NotADump);
}
};
/// The entry of dump `label` in the root map `root`; null when there is none.
fn entryOf(comptime DB: type, root: DB.HashMap(.read_only), label: []const u8) !?DB.HashMap(.read_only) {
const dumps = (try root.getCursor(key("dumps"))) orelse return null;
const at = (try (try DB.HashMap(.read_only).init(dumps)).getCursor(key(label))) orelse return null;
return try DB.HashMap(.read_only).init(at);
}
/// The dump `label` of `o` as an image, `gpa`'s; null when it keeps none
/// of that label.
fn imageOf(o: *Open, gpa: std.mem.Allocator, label: []const u8) !?[]u8 {
pardes.turn.yield();
defer pardes.turn.back();
switch (o.where) {
inline else => |*w| {
const DB = @TypeOf(w.db);
const root = try DB.HashMap(.read_only).init(w.db.rootCursor().readOnly());
const entry = (try entryOf(DB, root, label)) orelse return null;
const session = try (try entry.getCursor(key("session")) orelse return error.NotADump).readBytesAlloc(gpa, null);
defer gpa.free(session);
const panes = if (try entry.getCursor(key("panes"))) |c| try c.readUint() else 0;
var blobs: std.ArrayList(pardes.walk.Blob) = .empty;
defer {
for (blobs.items) |b| gpa.free(b.bytes);
blobs.deinit(gpa);
}
const texts = try DB.HashMap(.read_only).init((try root.getCursor(key("blobs"))) orelse return error.NotADump);
if (try entry.getCursor(key("blobs"))) |list_at| {
var it = try (try DB.ArrayList(.read_only).init(list_at)).iterator();
while (try it.next()) |h| {
var hash: [32]u8 = undefined;
if ((try h.readBytes(&hash)).len != 32) return error.NotADump;
const text = try (try texts.getCursor(blobKey(&hash)) orelse return error.NotADump).readBytesAlloc(gpa, null);
errdefer gpa.free(text);
try blobs.append(gpa, .{ .hash = hash, .bytes = text });
}
}
return try image(gpa, label, session, blobs.items, panes);
},
}
}
/// The dump `label` (bare: the newest) of this session's state file, as
/// an image, `gpa`'s; null when it keeps none of that label.
pub fn getDump(db: *Db, p: *Pardes, gpa: std.mem.Allocator, label: ?[]const u8) !?[]u8 {
const o = db.opened(p) orelse return error.NoStateFile;
var last_buf: [4096]u8 = undefined;
const name = label orelse (try lastLabel(o, &last_buf)) orelse return null;
return imageOf(o, gpa, name);
}
/// The dump `label` of the state file at `path` as an image, `gpa`'s: an
/// upgraded process's (its record names both), read before it has a core.
pub fn readDumpAt(gpa: std.mem.Allocator, path: []const u8, label: []const u8) ![]u8 {
var db: Db = .{ .kind = .disk, .open = try openDisk(gpa, path) };
defer db.deinit();
return (try imageOf(db.open.?, gpa, label)) orelse error.NoDump;
}
/// The newest dump's label, in `buf`; null when there is none.
fn lastLabel(o: *Open, buf: []u8) !?[]const u8 {
pardes.turn.yield();
defer pardes.turn.back();
switch (o.where) {
inline else => |*w| {
const DB = @TypeOf(w.db);
const root = try DB.HashMap(.read_only).init(w.db.rootCursor().readOnly());
const c = (try root.getCursor(key("last"))) orelse return null;
return try c.readBytes(buf);
},
}
}
/// The label of the state file's dump `label` (bare: its newest), in `buf`;
/// null when it keeps none of that label. A step asks it of the authority
/// (tape.authority): a replica keeps no state file.
pub fn labelled(db: *Db, p: *Pardes, label: ?[]const u8, buf: []u8) ?[]const u8 {
const o = db.opened(p) orelse return null;
const name = if (label) |l| (std.fmt.bufPrint(buf, "{s}", .{l}) catch return null) else ((lastLabel(o, buf) catch return null) orelse return null);
pardes.turn.yield();
defer pardes.turn.back();
switch (o.where) {
inline else => |*w| {
const DB = @TypeOf(w.db);
const root = DB.HashMap(.read_only).init(w.db.rootCursor().readOnly()) catch return null;
return if ((entryOf(DB, root, name) catch return null) != null) name else null;
},
}
}
/// The dump in the image `bytes` put in this session's state file under a
/// label of its own (`label`, else with `-2` and on), in one fsynced
/// transaction that also drops the oldest past `kept` and the texts no kept
/// dump names; waits for another session's transaction. The label, `buf`'s.
pub fn putDump(db: *Db, p: *Pardes, bytes: []const u8, label: []const u8, buf: []u8) ![]const u8 {
const r = try Read.open(p.recentGpa(), bytes, null);
defer r.close();
const o = try db.locked(p, true);
defer unlock(o);
const before = committed(o) catch 0;
const name = try putLocked(o, r, label, buf);
if (db.seen == before) db.seen = committed(o) catch 0;
return name;
}
fn putLocked(o: *Open, r: *Read, label: []const u8, buf: []u8) ![]const u8 {
pardes.turn.yield();
defer pardes.turn.back();
var ts: std.c.timespec = undefined;
_ = std.c.clock_gettime(.REALTIME, &ts);
switch (o.where) {
inline else => |*w, kind| {
const DB = @TypeOf(w.db);
if (kind == .disk) w.db.core.file.fsync = true;
defer if (kind == .disk) {
w.db.core.file.fsync = false;
};
var name: []const u8 = label;
try w.db.runContext(struct {
r: *Read,
label: []const u8,
buf: []u8,
name: *[]const u8,
date: u64,
gpa: std.mem.Allocator,
pub fn run(ctx: @This(), cursor: *DB.Cursor(.read_write)) !void {
const root = try DB.HashMap(.read_write).init(cursor.*);
const seq = if (try root.getCursor(key("seq"))) |c| try c.readUint() else 0;
try root.put(key("seq"), .{ .uint = seq + 1 });
const dumps = try DB.HashMap(.read_write).init(try root.putCursor(key("dumps")));
// A label of its own: a second dump in a second is `-2`.
var n: usize = 1;
var label_now: []const u8 = ctx.label;
while (try dumps.getCursor(key(label_now)) != null) {
n += 1;
label_now = try std.fmt.bufPrint(ctx.buf, "{s}-{d}", .{ ctx.label, n });
}
if (n == 1) label_now = try std.fmt.bufPrint(ctx.buf, "{s}", .{ctx.label});
ctx.name.* = label_now;
// The image's one entry, copied: its session, its texts
// the state file does not have yet, the numbers.
const image_root = try Memory.HashMap(.read_only).init(ctx.r.image.rootCursor().readOnly());
const from = (try entryOf(Memory, image_root, ctx.r.label)) orelse return error.NoDump;
const image_texts = try ctx.r.blobs();
try dumps.putKey(key(label_now), .{ .bytes = label_now });
const entry = try DB.HashMap(.read_write).init(try dumps.putCursor(key(label_now)));
try entry.put(key("seq"), .{ .uint = seq });
try entry.put(key("date"), .{ .uint = ctx.date });
try entry.put(key("panes"), .{ .uint = ctx.r.panes });
var session_at = (try from.getCursor(key("session"))) orelse return error.NoDump;
var size = try session_at.count();
try copyBytes(DB, &session_at, try entry.putCursor(key("session")), session_tag);
const texts = try DB.HashMap(.read_write).init(try root.putCursor(key("blobs")));
const hashes = try DB.ArrayList(.read_write).init(try entry.putCursor(key("blobs")));
if (try from.getCursor(key("blobs"))) |list_at| {
var it = try (try Memory.ArrayList(.read_only).init(list_at)).iterator();
while (try it.next()) |h| {
var hash: [32]u8 = undefined;
if ((try h.readBytes(&hash)).len != 32) return error.NotADump;
try hashes.append(.{ .bytes = &hash });
var text_at = (try image_texts.getCursor(blobKey(&hash))) orelse return error.NotADump;
size += try text_at.count();
if (try texts.getCursor(blobKey(&hash)) == null) try copyBytes(DB, &text_at, try texts.putCursor(blobKey(&hash)), null);
}
}
try entry.put(key("size"), .{ .uint = size });
try root.put(key("last"), .{ .bytes = label_now });
try trim(DB, ctx.gpa, dumps, texts);
}
}{ .r = r, .label = label, .buf = buf, .name = &name, .date = @intCast(@max(0, ts.sec)), .gpa = r.gpa });
return name;
},
}
}
/// The bytes at `from` (an image's, read while it is open) written at `to`,
/// streamed.
fn copyBytes(comptime DB: type, from: *Memory.Cursor(.read_only), to: DB.Cursor(.read_write), tag: ?[2]u8) !void {
var at = to;
var in_buf: [64 << 10]u8 = undefined;
var reader = try from.reader(&in_buf);
var out_buf: [64 << 10]u8 = undefined;
var writer = try at.writer(&out_buf);
_ = try reader.interface.streamRemaining(&writer.interface);
writer.format_tag = tag;
try writer.finish();
}
/// The newest `kept` dumps kept, the older dropped, and every text no kept
/// dump names (one replaced or dropped) dropped with them.
fn trim(comptime DB: type, gpa: std.mem.Allocator, dumps: DB.HashMap(.read_write), texts: DB.HashMap(.read_write)) !void {
const Dumped = struct { seq: u64, hash: u256 };
var all: std.ArrayList(Dumped) = .empty;
defer all.deinit(gpa);
var it = try dumps.iterator();
while (try it.next()) |kv_at| {
const kv = try kv_at.readKeyValuePair();
const entry = try DB.HashMap(.read_only).init(kv.value_cursor);
const seq = if (try entry.getCursor(key("seq"))) |c| try c.readUint() else 0;
try all.append(gpa, .{ .seq = seq, .hash = kv.hash });
}
std.mem.sort(Dumped, all.items, {}, struct {
fn newer(_: void, a: Dumped, b: Dumped) bool {
return a.seq > b.seq;
}
}.newer);
if (all.items.len > kept) for (all.items[kept..]) |d| {
_ = try dumps.remove(d.hash);
};
// The texts the kept ones name; every other one goes.
var named: std.AutoHashMapUnmanaged(u256, void) = .empty;
defer named.deinit(gpa);
for (all.items[0..@min(all.items.len, kept)]) |d| {
const entry = try DB.HashMap(.read_only).init((try dumps.getCursor(d.hash)) orelse continue);
const list_at = (try entry.getCursor(key("blobs"))) orelse continue;
var hashes = try (try DB.ArrayList(.read_only).init(list_at)).iterator();
while (try hashes.next()) |h| {
var hash: [32]u8 = undefined;
if ((try h.readBytes(&hash)).len == 32) try named.put(gpa, blobKey(&hash), {});
}
}
var gone: std.ArrayList(u256) = .empty;
defer gone.deinit(gpa);
var texts_it = try texts.iterator();
while (try texts_it.next()) |kv_at| {
const kv = try kv_at.readKeyValuePair();
if (!named.contains(kv.hash)) try gone.append(gpa, kv.hash);
}
for (gone.items) |h| _ = try texts.remove(h);
}
/// The dumps the state file keeps, a line each, the newest first: its
/// label, its date (UTC), its size in bytes and its pane count.
pub fn listDumps(db: *Db, p: *Pardes, w: *std.Io.Writer) !void {
const o = db.opened(p) orelse return;
pardes.turn.yield();
defer pardes.turn.back();
const gpa = p.recentGpa();
const Row = struct { seq: u64, date: u64, size: u64, panes: u64, label: []u8 };
var rows: std.ArrayList(Row) = .empty;
defer {
for (rows.items) |r| gpa.free(r.label);
rows.deinit(gpa);
}
switch (o.where) {
inline else => |*d| {
const DB = @TypeOf(d.db);
const root = try DB.HashMap(.read_only).init(d.db.rootCursor().readOnly());
const dumps_at = (try root.getCursor(key("dumps"))) orelse return;
var it = try (try DB.HashMap(.read_only).init(dumps_at)).iterator();
while (try it.next()) |kv_at| {
const kv = try kv_at.readKeyValuePair();
const entry = try DB.HashMap(.read_only).init(kv.value_cursor);
var row: Row = .{ .seq = 0, .date = 0, .size = 0, .panes = 0, .label = @constCast(try kv.key_cursor.readBytesAlloc(gpa, 4096)) };
inline for (.{ "seq", "date", "size", "panes" }) |field| if (try entry.getCursor(key(field))) |c| {
@field(row, field) = c.readUint() catch 0;
};
rows.append(gpa, row) catch |err| {
gpa.free(row.label);
return err;
};
}
},
}
std.mem.sort(Row, rows.items, {}, struct {
fn newer(_: void, a: Row, b: Row) bool {
return a.seq > b.seq;
}
}.newer);
for (rows.items) |r| {
const es: std.time.epoch.EpochSeconds = .{ .secs = r.date };
const yd = es.getEpochDay().calculateYearDay();
const md = yd.calculateMonthDay();
const ds = es.getDaySeconds();
try w.print("{s} {d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z {d} {d}\n", .{
r.label, yd.year, md.month.numeric(), @as(u8, md.day_index) + 1,
ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), r.size,
r.panes,
});
}
}
/// At a session's end: the state file compacted (into `<path>.new`,
/// renamed over it) once it is past twice what its dumps and Recent hold,
/// plus 64 MiB. Under the file's lock: no session commits to the old file
/// meanwhile, and one that opened it reopens the new one (`opened`).
pub fn compact(db: *Db, p: *Pardes) void {
if (db.kind != .disk or db.open == null) return;
const size = db.open.?.where.disk.file.length(ioOf()) catch return;
if (size < 64 << 20) return;
const o = db.locked(p, true) catch return;
defer unlock(o);
const d = &o.where.disk;
const io = ioOf();
const live = liveSize(&d.db) catch return;
if (size <= 2 * live + (64 << 20)) return;
var buf: [4300]u8 = undefined;
const new = std.fmt.bufPrint(&buf, "{s}.new", .{d.path}) catch return;
const cwd = std.Io.Dir.cwd();
const file = cwd.createFile(io, new, .{ .read = true, .truncate = true }) catch return;
var new_buf: std.Io.Writer.Allocating = .init(p.recentGpa());
defer new_buf.deinit();
var offsets: std.AutoHashMap(u64, u64) = .init(p.recentGpa());
defer offsets.deinit();
_ = d.db.compact(.buffered_file, .{ .file = file, .buffer = &new_buf, .hash_id = hash_id }, &offsets) catch {
file.close(io);
cwd.deleteFile(io, new) catch {};
return;
};
file.close(io);
cwd.rename(new, cwd, d.path, io) catch cwd.deleteFile(io, new) catch {};
}
/// What the state file's latest moment holds: Recent, each dump's
/// session, each text once.
fn liveSize(db: *Disk) !u64 {
const root = try Disk.HashMap(.read_only).init(db.rootCursor().readOnly());
var live: u64 = 0;
if (try root.getCursor(key("recent"))) |c| live += try c.count();
if (try root.getCursor(key("dumps"))) |at| {
var it = try (try Disk.HashMap(.read_only).init(at)).iterator();
while (try it.next()) |kv_at| {
const entry = try Disk.HashMap(.read_only).init((try kv_at.readKeyValuePair()).value_cursor);
if (try entry.getCursor(key("session"))) |c| live += try c.count();
}
}
if (try root.getCursor(key("blobs"))) |at| {
var it = try (try Disk.HashMap(.read_only).init(at)).iterator();
while (try it.next()) |kv_at| live += try (try kv_at.readKeyValuePair()).value_cursor.count();
}
return live;
}
// ---- tests ----
const testing = std.testing;
/// A window keeping its state in `dir` (never the user's DumpDir).
fn testWindow(dir: []const u8) !*Pardes {
var config: [4200]u8 = undefined;
return Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48, .state = .disk, .startup_config = try std.fmt.bufPrint(&config, "DumpDir {s}\n", .{dir}) });
}
fn testDir(tmp: *std.testing.TmpDir, buf: *[std.fs.max_path_bytes]u8) ![]const u8 {
return buf[0..try tmp.dir.realPath(testing.io, buf)];
}
fn fileSize(dir: []const u8) u64 {
var buf: [4200]u8 = undefined;
const path = std.fmt.bufPrint(&buf, "{s}/" ++ file_name, .{dir}) catch return 0;
const st = std.Io.Dir.cwd().statFile(testing.io, path, .{}) catch return 0;
return st.size;
}
test "state file: two windows share Recent, each reading the other's commits on use; a busy lock delays, never loses" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const dir = try testDir(&tmp, &dir_buf);
const a = try testWindow(dir);
defer a.deinit();
const b = try testWindow(dir);
defer b.deinit();
a.recent.opened(a.recentGpa(), "/w/a.zig");
a.saveRecent();
b.recent.opened(b.recentGpa(), "/w/b.zig");
b.saveRecent();
a.recent.closed(a.recentGpa(), "/w/a.zig", 7, 3, 0, 0);
a.saveRecent();
// Each has both, in the order they were written: a closed last, then b.
a.db.readRecent(a);
b.db.readRecent(b);
for ([_]*Pardes{ a, b }) |w| {
try testing.expectEqual(@as(usize, 2), w.recent.entries.items.len);
try testing.expectEqualStrings("/w/a.zig", w.recent.entries.items[0].path);
try testing.expectEqualStrings("/w/b.zig", w.recent.entries.items[1].path);
try testing.expectEqual(@as(u32, 7), w.recent.get("/w/a.zig").?.line);
}
// Another window holding the file's lock: b's change waits in memory...
var path_buf: [4200]u8 = undefined;
const lock_file = try std.Io.Dir.cwd().openFile(testing.io, try std.fmt.bufPrint(&path_buf, "{s}/" ++ file_name, .{dir}), .{ .mode = .read_write });
try lock_file.lock(testing.io, .exclusive);
b.recent.opened(b.recentGpa(), "/w/c.zig");
const size = fileSize(dir);
b.saveRecent();
try testing.expectEqual(size, fileSize(dir));
try testing.expect(b.recent.dirty);
// ...and is written at the next step after it is let go.
lock_file.close(testing.io);
b.saveRecent();
try testing.expect(fileSize(dir) > size);
a.db.readRecent(a);
try testing.expectEqualStrings("/w/c.zig", a.recent.entries.items[0].path);
// A window started now reads the same list.
const c = try testWindow(dir);
defer c.deinit();
try testing.expectEqual(@as(usize, 3), c.recent.entries.items.len);
for (a.recent.entries.items, c.recent.entries.items) |x, y| try testing.expectEqualStrings(x.path, y.path);
}
test "state file: Recent holds the newest 200, the newest first, and a window started on it reads them so" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const dir = try testDir(&tmp, &dir_buf);
const a = try testWindow(dir);
defer a.deinit();
var name: [32]u8 = undefined;
for (0..recent.cap + 100) |i| {
const file = std.fmt.bufPrint(&name, "/w/file{d}.zig", .{i}) catch unreachable;
a.recent.opened(a.recentGpa(), file);
a.recent.closed(a.recentGpa(), file, 1, 1, 0, 0);
a.saveRecent();
}
try testing.expectEqual(@as(usize, recent.cap), a.recent.entries.items.len);
const text = (try recentText(a.db.open.?, testing.allocator)).?;
defer testing.allocator.free(text);
try testing.expectEqual(@as(usize, recent.cap), std.mem.count(u8, text, "\n"));
try testing.expect(std.mem.startsWith(u8, text, "1 1 0 0 /w/file299.zig\n"));
const b = try testWindow(dir);
defer b.deinit();
try testing.expectEqual(@as(usize, recent.cap), b.recent.entries.items.len);
try testing.expectEqualStrings("/w/file299.zig", b.recent.entries.items[0].path);
try testing.expectEqualStrings("/w/file100.zig", b.recent.entries.items[recent.cap - 1].path);
}
test "state file: one that is no database of pardes's never stops pardes: it is kept aside, and a new one started" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const dir = try testDir(&tmp, &dir_buf);
try tmp.dir.writeFile(testing.io, .{ .sub_path = file_name, .data = "\x00\xffnot a database at all\n7 3 0 0 /w/ok.zig\n" });
const a = try testWindow(dir);
defer a.deinit();
try testing.expectEqual(@as(usize, 0), a.recent.entries.items.len);
a.recent.opened(a.recentGpa(), "/w/a.zig");
a.saveRecent();
const aside = try tmp.dir.readFileAlloc(testing.io, file_name ++ ".broken", testing.allocator, .limited(1 << 20));
defer testing.allocator.free(aside);
try testing.expect(std.mem.startsWith(u8, aside, "\x00\xffnot a database"));
const b = try testWindow(dir);
defer b.deinit();
try testing.expectEqual(@as(usize, 1), b.recent.entries.items.len);
try testing.expectEqualStrings("/w/a.zig", b.recent.entries.items[0].path);
}
test "state file: two dumps with one label get labels of their own" {
const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .state = .memory });
defer p.deinit();
const bytes = try pardes.dump.dumpBytes(p);
defer testing.allocator.free(bytes);
var buf: [64]u8 = undefined;
try testing.expectEqualStrings("pardes-x", try p.db.putDump(p, bytes, "pardes-x", &buf));
try testing.expectEqualStrings("pardes-x-2", try p.db.putDump(p, bytes, "pardes-x", &buf));
try testing.expectEqualStrings("pardes-x-3", try p.db.putDump(p, bytes, "pardes-x", &buf));
var label_buf: [64]u8 = undefined;
try testing.expectEqualStrings("pardes-x-3", p.db.labelled(p, null, &label_buf).?);
}
test "state file: a Dump makes every directory missing on the way to its DumpDir, and the file there" {
if (std.c.getenv("PARDES_DUMP") != null) return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [std.fs.max_path_bytes]u8 = undefined;
const base = try testDir(&tmp, &dir_buf);
var setting: [4200]u8 = undefined;
const dir = try std.fmt.bufPrint(&setting, "{s}/fresh/.local/share/pardes", .{base});
const p = try testWindow(dir);
defer p.deinit();
try pardes.dump.dumpState(p);
pardes.host_io.writeDump(p, p.dump_out.?);
try testing.expect(std.mem.startsWith(u8, p.last_dump.?, "pardes-"));
try testing.expect(fileSize(dir) > 0);
var label_buf: [64]u8 = undefined;
try testing.expect(p.db.labelled(p, p.last_dump.?, &label_buf) != null);
}
|