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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
|
//! 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 tear the last (its root
//! header on disk, its bytes not), and the file is then opened at the commit
//! before it (`mend`): the dumps outlive it.
//!
//! A file there that is no database of pardes's (another program's, one
//! with no commit left whole) 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), one a
/// power loss tore is opened at its last whole commit (`mend`), 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.Io.Dir.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| {
switch (err) {
error.InvalidDatabase, error.InvalidVersion, error.InvalidHashSize, error.TruncatedDatabase, error.InvalidEnumTag, error.EndOfStream => {},
else => {
file.close(io);
return err;
},
}
if (!fresh) if (mend(io, file, &o.buffer)) |d| {
o.where = .{ .disk = .{ .db = d, .file = file, .path = own } };
return o;
};
file.close(io);
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);
}
}
}
// xitdb's layout, which a mend reads (zig-pkg's xitdb src/lib.zig): the
// database header (its file id the last 8 of its 20 bytes, big endian),
// the root header (the root slot's 9 bytes, then the committed size's 8),
// and the trailer ending every commit (the root slot's 9 bytes, the commit
// id's 8, and their CRC-64/XZ's 8, with the file id and its own position).
const db_header_len = 20;
const root_header_end = db_header_len + 17;
const trailer_len = 25;
const hash_map_tag = 4;
/// A file xitdb refused, a power loss having torn its last commit (its
/// root header written, the commit's bytes not all): opened at the last
/// commit before it whose trailer verifies and whose maps read whole,
/// scanned back from the file's end, its root header put back at it (what
/// came after, a Recent's change or two, is lost; the dumps before it are
/// not). Null, the file as it was, when none does: it is no database of
/// pardes's, or none of its commits outlived the tear.
fn mend(io: std.Io, file: std.Io.File, buffer: *std.Io.Writer.Allocating) ?Disk {
file.lock(io, .exclusive) catch return null;
defer file.unlock(io);
// Another session mended it first.
if (Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false, .hash_id = hash_id })) |d| return d else |_| {}
var head: [root_header_end]u8 = undefined;
if ((file.readPositionalAll(io, &head, 0) catch return null) != head.len or !std.mem.eql(u8, head[0..3], "xit")) return null;
const file_id = std.mem.readInt(u64, head[db_header_len - 8 .. db_header_len], .big);
var chunk: [64 << 10]u8 = undefined;
var end = file.length(io) catch return null;
while (end >= root_header_end + trailer_len) {
const start = @max(root_header_end, end - @min(end, chunk.len));
const got = file.readPositionalAll(io, chunk[0 .. end - start], start) catch return null;
if (got != end - start) return null;
var i = got;
while (i >= trailer_len) : (i -= 1) {
const t = chunk[i - trailer_len ..][0..trailer_len];
const at = start + i - trailer_len;
// A pardes root is a map, at a slot written before its trailer.
if (t[0] & 0x7f != hash_map_tag or std.mem.readInt(u64, t[1..9], .big) >= at) continue;
var sum: [33]u8 = undefined;
std.mem.writeInt(u64, sum[0..8], file_id, .big);
std.mem.writeInt(u64, sum[8..16], at, .big);
@memcpy(sum[16..33], t[0..17]);
if (std.hash.crc.@"CRC-64/XZ".hash(&sum) != std.mem.readInt(u64, t[17..25], .big)) continue;
var root: [17]u8 = undefined;
@memcpy(root[0..9], t[0..9]);
std.mem.writeInt(u64, root[9..17], at + trailer_len, .big);
file.writePositionalAll(io, &root, db_header_len) catch return null;
var d = Disk.init(io, .{ .file = file, .buffer = buffer, .fsync = false, .hash_id = hash_id }) catch continue;
_ = liveSize(&d) catch continue;
file.sync(io) catch {};
return d;
}
if (start == root_header_end) break;
end = start + trailer_len - 1;
}
file.writePositionalAll(io, head[db_header_len..], db_header_len) catch {};
return null;
}
/// 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;
const first = !db.loaded;
db.loaded = true;
const held = db.mergeRecent(p, o);
// A state file that holds no Recent yet: the files before it, once.
if (first and held != null and !held.?) if (p.opts.recent_import) |dir| importRecent(p, dir);
}
/// Whether the database holds Recent; null when nothing was read (nothing
/// committed since the last read, or it could not be).
fn mergeRecent(db: *Db, p: *Pardes, o: *Open) ?bool {
const size = committed(o) catch return null;
if (size == db.seen) return null;
const gpa = p.recentGpa();
const text = recentText(o, gpa) catch return null;
defer if (text) |t| gpa.free(t);
p.recent.merge(gpa, text orelse "");
db.seen = size;
return text != null;
}
/// Recent as the files before the state file kept it, in `dir`: 0.24's
/// `recent` (200 lines, the newest first), else the `store` before it (a
/// log whose `@r` records are such lines, the oldest first). Both are left
/// where they are. ponytail: for a release or two, while those files are
/// about.
fn importRecent(p: *Pardes, dir: []const u8) void {
const gpa = p.recentGpa();
const io = ioOf();
var path_buf: [4200]u8 = undefined;
if (dir.len + "/recent".len >= std.Io.Dir.max_path_bytes) {
var said: [160]u8 = undefined;
return p.setMessage(p.view().active, std.fmt.bufPrint(&said, "Recent: the files before the state file were not read: their directory's path is {d} bytes, too long", .{dir.len}) catch unreachable); // a number fits 160
}
pardes.turn.yield();
const listed = std.Io.Dir.cwd().readFileAlloc(io, std.fmt.bufPrint(&path_buf, "{s}/recent", .{dir}) catch "", gpa, .limited(recent_max)) catch null;
const logged = if (listed == null) std.Io.Dir.cwd().readFileAlloc(io, std.fmt.bufPrint(&path_buf, "{s}/store", .{dir}) catch "", gpa, .limited(128 << 20)) catch null else null;
pardes.turn.back();
if (listed) |text| {
defer gpa.free(text);
p.recent.merge(gpa, text);
// Written to the state file at the next step: read once.
for (p.recent.entries.items) |*e| e.changed = true;
p.recent.dirty = p.recent.entries.items.len > 0;
} else if (logged) |text| {
defer gpa.free(text);
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
const e = recent.List.parseLine(line) orelse continue;
const open = if (p.recent.get(e.path)) |here| here.open else false;
p.recent.opened(gpa, e.path);
p.recent.closed(gpa, e.path, e.nums[0], e.nums[1], e.nums[2], e.nums[3]);
// Open here, it stays open: the cap never drops it.
if (open) p.recent.opened(gpa, e.path);
}
}
}
/// 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;
}
// ---- a far client's blob cache ----
/// A far replica client's blob cache (replica.zig `Have`): `cache.xitdb` in
/// $XDG_CACHE_HOME/pardes (else ~/.cache/pardes), the texts a join was
/// sent, by their BLAKE3 hash, so a client started again or a second one on
/// this machine is not sent them again. Expendable, and up to a gigabyte, so
/// a file of its own, never the state file's:
///
/// blobs/<hash> the text
/// seqs/<hash> its number in `seen`
/// seen a sorted map, a number (big endian) to its blob's hash:
/// the least recently used first (a hit takes a new number)
/// size, next the texts' bytes, the next number
///
/// Past the cap (PARDES_BLOB_CACHE_MB, else 1 GiB) the most recently used
/// that fit stay and the rest go, and the file is compacted into
/// `cache.xitdb.new` and renamed over it: one transaction and one
/// compaction, at a far client's end (`trim`), never on a frame. A text read back is hashed again: one torn or changed is a miss
/// and goes, never wrong content; a file that is no database is started
/// afresh (it holds nothing a join cannot send again). Each use opens the
/// file for itself: a client's reader, its storing thread and its end each
/// have a database of their own, as xitdb asks.
pub const Cache = struct {
path_buf: [4096]u8 = undefined,
path_len: usize = 0,
/// Bytes it keeps at most.
cap: u64,
pub const name = "cache.xitdb";
/// The cache's place, its directory made: null with no home for it.
pub fn open(io: std.Io) ?Cache {
var c: Cache = .{ .cap = (if (std.c.getenv("PARDES_BLOB_CACHE_MB")) |v| std.fmt.parseInt(u64, std.mem.span(v), 10) catch 1024 else 1024) << 20 };
const base = if (std.c.getenv("XDG_CACHE_HOME")) |x| std.mem.span(x) else "";
const where = (if (base.len > 0 and base[0] == '/')
std.fmt.bufPrint(&c.path_buf, "{s}/pardes/" ++ name, .{base})
else if (std.c.getenv("HOME")) |home|
std.fmt.bufPrint(&c.path_buf, "{s}/.cache/pardes/" ++ name, .{std.mem.span(home)})
else
return null) catch return null;
std.Io.Dir.cwd().createDirPath(io, std.Io.Dir.path.dirname(where).?) catch return null;
c.path_len = where.len;
return c;
}
/// The cache at `where` (a test's).
pub fn of(where: []const u8, cap: u64) Cache {
var c: Cache = .{ .cap = cap, .path_len = where.len };
@memcpy(c.path_buf[0..where.len], where);
return c;
}
pub fn path(c: *const Cache) []const u8 {
return c.path_buf[0..c.path_len];
}
/// The cache open for one use.
const Use = struct {
file: std.Io.File,
buffer: std.Io.Writer.Allocating,
db: Disk,
};
fn use(c: *const Cache, io: std.Io, u: *Use) !void {
const cwd = std.Io.Dir.cwd();
u.buffer = .init(std.heap.c_allocator);
errdefer u.buffer.deinit();
for (0..2) |_| {
u.file = try cwd.createFile(io, c.path(), .{ .read = true, .truncate = false });
u.db = Disk.init(io, .{ .file = u.file, .buffer = &u.buffer, .fsync = false, .hash_id = hash_id }) catch |err| {
u.file.close(io);
// No database: started afresh, as nothing in it is precious.
cwd.deleteFile(io, c.path()) catch return err;
continue;
};
return;
}
return error.InvalidDatabase;
}
fn done(u: *Use, io: std.Io) void {
u.file.close(io);
u.buffer.deinit();
}
fn mapAt(root: Disk.HashMap(.read_only), field: []const u8) !?Disk.HashMap(.read_only) {
const c = (try root.getCursor(key(field))) orelse return null;
return try Disk.HashMap(.read_only).init(c);
}
/// The text of `hash` read into `out` (its length) and hashed again.
/// One of another length or content is a miss, and goes.
pub fn get(c: *const Cache, io: std.Io, hash: *const [32]u8, out: []u8) bool {
var u: Use = undefined;
c.use(io, &u) catch return false;
defer done(&u, io);
const ok = ok: {
const root = Disk.HashMap(.read_only).init(u.db.rootCursor().readOnly()) catch break :ok false;
const blobs = (mapAt(root, "blobs") catch break :ok false) orelse return false;
const at = (blobs.getCursor(blobKey(hash)) catch break :ok false) orelse return false;
if ((at.count() catch break :ok false) != out.len) break :ok false;
_ = at.readBytes(out) catch break :ok false;
var d: [32]u8 = undefined;
std.crypto.hash.Blake3.hash(out, &d, .{});
break :ok std.mem.eql(u8, &d, hash);
};
if (!ok) drop(&u, io, hash);
return ok;
}
/// Whether a text of `len` bytes is there under `hash` (not read).
pub fn has(c: *const Cache, io: std.Io, hash: *const [32]u8, len: usize) bool {
var u: Use = undefined;
c.use(io, &u) catch return false;
defer done(&u, io);
const root = Disk.HashMap(.read_only).init(u.db.rootCursor().readOnly()) catch return false;
const blobs = (mapAt(root, "blobs") catch return false) orelse return false;
const at = (blobs.getCursor(blobKey(hash)) catch return false) orelse return false;
return (at.count() catch return false) == len;
}
/// The text of `hash`, gone (one read back wrong).
fn drop(u: *Use, io: std.Io, hash: *const [32]u8) void {
u.file.lock(io, .exclusive) catch return;
defer u.file.unlock(io);
u.db.runContext(struct {
hash: *const [32]u8,
pub fn run(ctx: @This(), cursor: *Disk.Cursor(.read_write)) !void {
const root = try Disk.HashMap(.read_write).init(cursor.*);
const blobs = try Disk.HashMap(.read_write).init(try root.putCursor(key("blobs")));
const at = (try blobs.getCursor(blobKey(ctx.hash))) orelse return;
const len = try at.count();
_ = try blobs.remove(blobKey(ctx.hash));
const size = if (try root.getCursor(key("size"))) |s| try s.readUint() else 0;
try root.put(key("size"), .{ .uint = size -| len });
const seqs = try Disk.HashMap(.read_write).init(try root.putCursor(key("seqs")));
if (try seqs.getCursor(blobKey(ctx.hash))) |s| {
const was = try s.readUint();
_ = try seqs.remove(blobKey(ctx.hash));
const seen = try Disk.SortedMap(.read_write).init(try root.putCursor(key("seen")));
_ = try seen.remove(&seqKey(was));
}
}
}{ .hash = hash }) catch {};
}
fn seqKey(seq: u64) [8]u8 {
var k: [8]u8 = undefined;
std.mem.writeInt(u64, &k, seq, .big);
return k;
}
/// `blobs` kept (each text not there yet, under its hash) and `hits`,
/// texts read from here, made the most recently used: one transaction,
/// the file's lock waited for (a storing thread's, a client's end's).
pub fn put(c: *const Cache, io: std.Io, blobs: []const pardes.walk.Blob, hits: []const [32]u8) void {
if (blobs.len == 0 and hits.len == 0) return;
var u: Use = undefined;
c.use(io, &u) catch return;
defer done(&u, io);
u.file.lock(io, .exclusive) catch return;
defer u.file.unlock(io);
u.db.runContext(struct {
blobs: []const pardes.walk.Blob,
hits: []const [32]u8,
pub fn run(ctx: @This(), cursor: *Disk.Cursor(.read_write)) !void {
const root = try Disk.HashMap(.read_write).init(cursor.*);
const texts = try Disk.HashMap(.read_write).init(try root.putCursor(key("blobs")));
const seqs = try Disk.HashMap(.read_write).init(try root.putCursor(key("seqs")));
const seen = try Disk.SortedMap(.read_write).init(try root.putCursor(key("seen")));
var next = if (try root.getCursor(key("next"))) |n| try n.readUint() else 0;
var size = if (try root.getCursor(key("size"))) |s| try s.readUint() else 0;
for (ctx.blobs) |*b| {
if (try texts.getCursor(blobKey(&b.hash)) != null) continue;
try texts.put(blobKey(&b.hash), .{ .bytes = b.bytes });
try seqs.put(blobKey(&b.hash), .{ .uint = next });
try seen.put(&seqKey(next), .{ .bytes = &b.hash });
next += 1;
size += b.bytes.len;
}
for (ctx.hits) |*h| {
const at = (try seqs.getCursor(blobKey(h))) orelse continue;
_ = try seen.remove(&seqKey(try at.readUint()));
try seqs.put(blobKey(h), .{ .uint = next });
try seen.put(&seqKey(next), .{ .bytes = h });
next += 1;
}
try root.put(key("next"), .{ .uint = next });
try root.put(key("size"), .{ .uint = size });
}
}{ .blobs = blobs, .hits = hits }) catch {};
}
/// Under the cap: the most recently used texts kept while they fit, the
/// newest first, and the rest gone, in one transaction (one past the cap
/// alone goes without taking the older ones with it); then the file
/// compacted into `<path>.new` and renamed over it once any went (what
/// no moment holds is the file's growth).
pub fn trim(c: *const Cache, io: std.Io) void {
var u: Use = undefined;
c.use(io, &u) catch return;
defer done(&u, io);
u.file.lock(io, .exclusive) catch return;
defer u.file.unlock(io);
var went = false;
u.db.runContext(struct {
cap: u64,
went: *bool,
pub fn run(ctx: @This(), cursor: *Disk.Cursor(.read_write)) !void {
const root = try Disk.HashMap(.read_write).init(cursor.*);
const size = if (try root.getCursor(key("size"))) |s| try s.readUint() else 0;
if (size <= ctx.cap) return;
const texts = try Disk.HashMap(.read_write).init(try root.putCursor(key("blobs")));
const seqs = try Disk.HashMap(.read_write).init(try root.putCursor(key("seqs")));
const seen = try Disk.SortedMap(.read_write).init(try root.putCursor(key("seen")));
// Every text, the least recently used first, read before any goes.
const Text = struct { seq: [8]u8, hash: [32]u8, len: ?u64, kept: bool = false };
var all: std.ArrayList(Text) = .empty;
defer all.deinit(std.heap.c_allocator);
var it = try seen.iterator();
while (try it.next()) |kv_at| {
const kv = try kv_at.readKeyValuePair();
var t: Text = .{ .seq = undefined, .hash = undefined, .len = null };
if ((try kv.key_cursor.readBytes(&t.seq)).len != 8 or (try kv.value_cursor.readBytes(&t.hash)).len != 32) continue;
t.len = if (try texts.getCursor(blobKey(&t.hash))) |at| try at.count() else null;
try all.append(std.heap.c_allocator, t);
}
var room = ctx.cap;
var i = all.items.len;
while (i > 0) {
i -= 1;
const t = &all.items[i];
t.kept = if (t.len) |len| len <= room else false;
if (t.kept) room -= t.len.?;
}
for (all.items) |*t| if (!t.kept) {
_ = try texts.remove(blobKey(&t.hash));
_ = try seqs.remove(blobKey(&t.hash));
_ = try seen.remove(&t.seq);
ctx.went.* = true;
};
try root.put(key("size"), .{ .uint = ctx.cap - room });
}
}{ .cap = c.cap, .went = &went }) catch return;
if (!went) return;
var new_buf: [c.path_buf.len + ".new".len]u8 = undefined;
const new = std.fmt.bufPrint(&new_buf, "{s}.new", .{c.path()}) catch unreachable; // path_buf's [4096]u8 and ".new" fit
const cwd = std.Io.Dir.cwd();
const file = cwd.createFile(io, new, .{ .read = true, .truncate = true }) catch return;
var buffer: std.Io.Writer.Allocating = .init(std.heap.c_allocator);
defer buffer.deinit();
var offsets: std.AutoHashMap(u64, u64) = .init(std.heap.c_allocator);
defer offsets.deinit();
_ = u.db.compact(.buffered_file, .{ .file = file, .buffer = &buffer, .fsync = false, .hash_id = hash_id }, &offsets) catch {
file.close(io);
cwd.deleteFile(io, new) catch {};
return;
};
file.close(io);
cwd.rename(new, cwd, c.path(), io) catch cwd.deleteFile(io, new) catch {};
}
};
// ---- 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.Io.Dir.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.Io.Dir.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.Io.Dir.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.Io.Dir.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: one a power loss tore is opened at its last whole commit, the dumps before it kept; it is set aside only when none is whole" {
if (std.c.getenv("PARDES_DUMP") != null) return error.SkipZigTest;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
const dir = try testDir(&tmp, &dir_buf);
var label_buf: [64]u8 = undefined;
var label: []const u8 = undefined;
var dumped: u64 = undefined;
{
// A Dump, then a Recent's change committed after it.
const a = try testWindow(dir);
defer a.deinit();
_ = try a.setTestFile("kept through a tear\n");
try pardes.dump.dumpState(a);
pardes.host_io.writeDump(a, a.dump_out.?);
label = try std.fmt.bufPrint(&label_buf, "{s}", .{a.last_dump.?});
dumped = fileSize(dir);
a.recent.opened(a.recentGpa(), "/w/after.zig");
a.saveRecent();
}
const whole = try tmp.dir.readFileAlloc(testing.io, file_name, testing.allocator, .limited(64 << 20));
defer testing.allocator.free(whole);
try testing.expect(whole.len > dumped);
const torn = try testing.allocator.alloc(u8, whole.len + 4096);
defer testing.allocator.free(torn);
const cases = [_]struct { what: []const u8, len: usize, after: ?bool }{
// Its last commit cut short: the file ends before its root header says.
.{ .what = "cut short", .len = whole.len - 10, .after = null },
// A commit after the last whole one, its root header written, its
// bytes garbage: the last whole one's Recent is there.
.{ .what = "garbage after", .len = whole.len + 4096, .after = true },
// Recent's commit after the Dump never reached the disk (zeros where
// it would be) but its root header did: the Dump is there, the
// change gone.
.{ .what = "Recent's commit torn", .len = whole.len, .after = false },
};
for (cases) |case| {
@memcpy(torn[0..whole.len], whole);
@memset(torn[whole.len..], 0x5a);
if (std.mem.eql(u8, case.what, "garbage after")) std.mem.writeInt(u64, torn[root_header_end - 8 .. root_header_end], torn.len, .big);
if (std.mem.eql(u8, case.what, "Recent's commit torn")) @memset(torn[dumped..whole.len], 0);
try tmp.dir.writeFile(testing.io, .{ .sub_path = file_name, .data = torn[0..case.len] });
const b = try testWindow(dir);
defer b.deinit();
errdefer std.debug.print("case: {s}\n", .{case.what});
try testing.expectError(error.FileNotFound, tmp.dir.statFile(testing.io, file_name ++ ".broken", .{}));
var buf: [64]u8 = undefined;
try testing.expect(b.db.labelled(b, label, &buf) != null);
if (case.after) |after| try testing.expectEqual(after, b.recent.get("/w/after.zig") != null);
// The Dump read back whole, its text with it.
const img = (try b.db.getDump(b, testing.allocator, label)).?;
defer testing.allocator.free(img);
const q = try pardes.dump.initFromDump(testing.allocator, .{ .tty_only = true }, img);
defer q.deinit();
const text = for (q.panes) |slot| {
if (slot) |pane| if (pane.file) |f| if (f.output == null) break f.content;
} else return error.FileLost;
try testing.expectEqualStrings("kept through a tear\n", text);
}
// No commit whole: set aside, the bytes as they were, and a new one started.
@memcpy(torn[0..whole.len], whole);
@memset(torn[root_header_end..whole.len], 0);
try tmp.dir.writeFile(testing.io, .{ .sub_path = file_name, .data = torn[0..whole.len] });
const c = try testWindow(dir);
defer c.deinit();
var buf: [64]u8 = undefined;
try testing.expect(c.db.labelled(c, label, &buf) == null);
const aside = try tmp.dir.readFileAlloc(testing.io, file_name ++ ".broken", testing.allocator, .limited(64 << 20));
defer testing.allocator.free(aside);
try testing.expectEqualSlices(u8, torn[0..whole.len], aside);
}
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.Io.Dir.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);
}
test "state file: Recent is read once from the file it replaced, else from the store before that, both left where they are" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
const dir = try testDir(&tmp, &dir_buf);
try tmp.dir.createDirPath(testing.io, "old");
try tmp.dir.createDirPath(testing.io, "older");
try tmp.dir.createDirPath(testing.io, "a");
try tmp.dir.createDirPath(testing.io, "b");
// 0.24's Recent: 200 lines, the newest first.
try tmp.dir.writeFile(testing.io, .{ .sub_path = "old/recent", .data = "7 3 0 0 /w/newest.zig\n1 1 0 0 /w/older.zig\n" });
// Before it, the store: its `@r` records' bodies the same lines, oldest
// first, a closed pane's record between them.
try tmp.dir.writeFile(testing.io, .{ .sub_path = "older/store", .data = "@h 31 3c6ce28a\npardes-store 1 ca2a9583be7d1ba3\n@r 20 0\n1 1 0 0 /w/old.zig\n@c 12 0\n0 1 7 0 0 0 0 9\t/w/x\n.{}\n@r 21 0\n2 2 0 0 /w/both.zig\n@r 20 0\n9 9 0 0 /w/old.zig\n" });
var buf: [3][4200]u8 = undefined;
const old = try std.fmt.bufPrint(&buf[0], "{s}/old", .{dir});
const older = try std.fmt.bufPrint(&buf[1], "{s}/older", .{dir});
const window = struct {
fn of(state: []const u8, import: []const u8) !*Pardes {
var config: [4200]u8 = undefined;
return Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48, .state = .disk, .recent_import = import, .startup_config = try std.fmt.bufPrint(&config, "DumpDir {s}\n", .{state}) });
}
}.of;
{
const a = try window(try std.fmt.bufPrint(&buf[2], "{s}/a", .{dir}), old);
defer a.deinit();
try testing.expectEqual(@as(usize, 2), a.recent.entries.items.len);
try testing.expectEqualStrings("/w/newest.zig", a.recent.entries.items[0].path);
try testing.expectEqual(@as(u32, 7), a.recent.get("/w/newest.zig").?.line);
a.saveRecent();
}
// Read once: what the old file says after is not the state file's.
try tmp.dir.writeFile(testing.io, .{ .sub_path = "old/recent", .data = "5 5 0 0 /w/later.zig\n" });
{
const a = try window(try std.fmt.bufPrint(&buf[2], "{s}/a", .{dir}), old);
defer a.deinit();
try testing.expectEqual(@as(usize, 2), a.recent.entries.items.len);
try testing.expect(a.recent.get("/w/later.zig") == null);
}
// No `recent` there: the store's, its newest records first.
{
const b = try window(try std.fmt.bufPrint(&buf[2], "{s}/b", .{dir}), older);
defer b.deinit();
try testing.expectEqual(@as(usize, 2), b.recent.entries.items.len);
try testing.expectEqualStrings("/w/old.zig", b.recent.entries.items[0].path);
try testing.expectEqual(@as(u32, 9), b.recent.entries.items[0].line);
try testing.expectEqualStrings("/w/both.zig", b.recent.entries.items[1].path);
}
// A directory whose path is past the room for its files' names: none
// read, and said so.
{
try tmp.dir.createDirPath(testing.io, "c");
var long: [4200]u8 = undefined;
@memset(&long, 'd');
long[0] = '/';
const c = try window(try std.fmt.bufPrint(&buf[2], "{s}/c", .{dir}), &long);
defer c.deinit();
try testing.expectEqual(@as(usize, 0), c.recent.entries.items.len);
const pane = c.panes[c.view().active].?;
try testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "Recent: the files before the state file were not read") != null);
}
// Both left where they were.
_ = try tmp.dir.statFile(testing.io, "old/recent", .{});
_ = try tmp.dir.statFile(testing.io, "older/store", .{});
}
|