gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf04afc43f04afc43tickets: MdEditor from components 59704ce (a file manager copy still attaches, pipe rows, tickets#49)mref04afc43/plugins/mpackdb/engine.zig

191.6 KB

  1. // mpackdb DB engine — Zig port of mpackdb v1.0.7 (MPackDB.js / IndexManager.js)
  2. // semantics. File-level compatible with the JS implementation (D12):
  3. //
  4. // <base>.mpack append-only records: [4-byte LE total size][msgpack map]
  5. // <base>.meta.json { nextId?, deleted:[offsets], version, schema? }
  6. // <base>.<field>.txt sorted index lines "key,offset,length\n" (a key with a newline, CR or leading quote is a JSON string; read from the right: mission 486)
  7. // <base>.idxstate.json { coveredBytes, idxFmt (2 since mission 486; absent means rebuild once) }
  8. // <base>.lock lock file containing the holder's pid (O_EXCL protocol,
  9. // stale takeover after staleLockTimeout ms)
  10. // <base>.flock (this engine only, ticket #176) the store lock: every open
  11. // handle holds a shared flock on it, compaction needs it
  12. // exclusive and is skipped without it; the last handle out
  13. // removes the file
  14. //
  15. // Ticket #176 additions the JS mpackdb ignores (it keeps unknown meta fields):
  16. // meta.json `dataFile` {ino, size, gen, deletedSum} and idxstate.json `dataIno`
  17. // name the data file they were written for, so tombstones and index offsets of
  18. // a replaced data file are never applied to the new one.
  19. //
  20. // Ticket 387 (a COPY of an open store must read back as the store): the inode alone
  21. // is not the identity of a data file, a hot tar or a restore gives the same bytes a
  22. // new inode. dataFile also carries `fp`, a fingerprint of the first `size` bytes
  23. // (hash of the first 4 KB + hash of the 4 KB before `size`), idxstate carries
  24. // `dataFp` for the first `coveredBytes`. Binding rule: same inode -> bound; another
  25. // inode and equal fingerprint -> bound (a copy); a file shorter than `size` or a
  26. // different fingerprint -> stale (another process's compaction); an old meta without
  27. // `fp` on another inode -> bound only if all its tombstones are plausible frame
  28. // starts. See applyMetaJson.
  29. //
  30. // Divergences from the JS implementation (documented in the 066 report):
  31. // - the in-memory index is the COMPLETE entry set (JS keeps on-disk + delta);
  32. // persist() writes the full set instead of read-merge-write. Sequential
  33. // cross-process use (close one side, open the other) behaves identically.
  34. // - string index keys sort bytewise (JS: String.localeCompare, ICU collation).
  35. // Equality lookups are unaffected; range ordering can differ for
  36. // mixed-case/accented keys.
  37. // - null field values are not indexed (JS indexes them under the key "null").
  38. // - a data file replaced while open (inode change, shrink, newer compaction
  39. // generation) is detected and re-indexed before the next read (#176).
  40. // - the JS mpackdb does not take the .flock store lock: its compaction can still
  41. // rewrite a file this engine has open (which then re-indexes), and this
  42. // engine's compaction cannot see a JS process that has the store open.
  43. // - a fresh `*id` table's first id is 1 (JS: 0) — ticket #4, see FIRST_ID.
  44. const std = @import("std");
  45. const linux = std.os.linux;
  46. const msgpack = @import("msgpack.zig");
  47. pub const PkType = enum(u8) { number = 0, uuid = 1, string = 2 };
  48. /// A `*id` table's first auto-increment id (ticket #4, the creator's ruling:
  49. /// "start at 1"). Only a table WITHOUT a stored counter starts here: a
  50. /// .meta.json that carries `nextId` — every existing table, including one the
  51. /// JS mpackdb wrote — keeps counting from it. The file format is unchanged;
  52. /// the JS mpackdb 1.0.7 starts a fresh table at 0, which is the one divergence.
  53. pub const FIRST_ID: f64 = 1;
  54. pub const IdxType = enum(u8) { lexical = 0, numeric = 1 };
  55. pub const Error = error{
  56. NoDbFile,
  57. NoPrimaryKey,
  58. /// mission 077 (074 GAP 10): a query named a field with no index. There is
  59. /// no index to binary-search and mpackdb does not silently full-scan, so
  60. /// the answer used to be an empty result — indistinguishable from "no such
  61. /// record". It is a mistake, and it says so now.
  62. NoSuchIndex,
  63. DuplicateKey,
  64. /// ticket #29: update()'s record must carry the primary key. Without it
  65. /// the old record was deleted, the new one written without a key, and the
  66. /// table left corrupt (fetch null, a unique index still finding it).
  67. RecordLacksPrimaryKey,
  68. LockTimeout,
  69. /// ticket #176: compaction found a frame it cannot vouch for (or a tombstone
  70. /// that names no frame) and rewrote nothing; last_error names the offset.
  71. CompactRefused,
  72. CorruptRecord,
  73. IoError,
  74. OutOfMemory,
  75. InvalidFormat,
  76. Truncated,
  77. MapTooLarge,
  78. };
  79. pub const Key = union(enum) {
  80. num: f64,
  81. str: []const u8,
  82. };
  83. pub const Entry = struct {
  84. key: Key,
  85. off: u64,
  86. len: u64,
  87. };
  88. const FieldIndex = struct {
  89. typ: IdxType,
  90. entries: std.ArrayList(Entry) = .empty, // sorted by (key, off)
  91. };
  92. pub const Loc = struct { off: u64, len: u64 };
  93. pub const Record = struct {
  94. value: msgpack.Value,
  95. off: u64,
  96. len: u64,
  97. };
  98. // =========================================================================
  99. // Low-level file IO (raw linux syscalls — plugins avoid std.Io plumbing)
  100. // =========================================================================
  101. const fio = struct {
  102. fn openz(alloc: std.mem.Allocator, path: []const u8, flags: linux.O, mode: u32) ?i32 {
  103. const path_z = alloc.dupeZ(u8, path) catch return null;
  104. defer alloc.free(path_z);
  105. const rc = linux.open(path_z, flags, mode);
  106. const fd: i32 = @bitCast(@as(u32, @truncate(rc)));
  107. if (fd < 0) return null;
  108. return fd;
  109. }
  110. fn openRead(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  111. return openz(alloc, path, .{}, 0);
  112. }
  113. fn openAppend(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  114. return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true }, 0o644);
  115. }
  116. fn openTrunc(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  117. return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, 0o644);
  118. }
  119. /// O_CREAT|O_EXCL — returns null when the file already exists.
  120. fn openExcl(alloc: std.mem.Allocator, path: []const u8) ?i32 {
  121. return openz(alloc, path, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true }, 0o644);
  122. }
  123. fn close(fd: i32) void {
  124. _ = linux.close(fd);
  125. }
  126. fn fsync(fd: i32) bool {
  127. return linux.fsync(fd) == 0;
  128. }
  129. /// fsync the directory holding `path`, so a rename in it is durable.
  130. fn fsyncDir(alloc: std.mem.Allocator, path: []const u8) void {
  131. const dir = std.fs.path.dirname(path) orelse ".";
  132. const fd = openz(alloc, dir, .{ .DIRECTORY = true }, 0) orelse return;
  133. _ = linux.fsync(fd);
  134. close(fd);
  135. }
  136. fn writeAll(fd: i32, bytes: []const u8) bool {
  137. var written: usize = 0;
  138. while (written < bytes.len) {
  139. const rc = linux.write(fd, bytes.ptr + written, bytes.len - written);
  140. if (@as(isize, @bitCast(rc)) <= 0) return false;
  141. written += rc;
  142. }
  143. return true;
  144. }
  145. fn pread(fd: i32, buf: []u8, offset: u64) ?usize {
  146. var got: usize = 0;
  147. while (got < buf.len) {
  148. const rc = linux.pread(fd, buf.ptr + got, buf.len - got, @intCast(offset + got));
  149. const n: isize = @bitCast(rc);
  150. if (n < 0) return null;
  151. if (n == 0) break;
  152. got += @intCast(n);
  153. }
  154. return got;
  155. }
  156. fn readAll(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {
  157. const fd = openRead(alloc, path) orelse return null;
  158. defer close(fd);
  159. // ONE read into a buffer of the file's size (mission 436): the 64 KB read + append
  160. // loop copied a 25 MB index file twice and regrew the list ~100 times
  161. var content: std.ArrayList(u8) = .empty;
  162. errdefer content.deinit(alloc);
  163. const hint: usize = if (fdStat(fd)) |st| @intCast(st.size) else 0;
  164. content.ensureTotalCapacityPrecise(alloc, hint + 1) catch return null;
  165. while (true) {
  166. if (content.capacity - content.items.len < 4096) content.ensureUnusedCapacity(alloc, 65536) catch return null;
  167. const spare = content.unusedCapacitySlice();
  168. const rc = linux.read(fd, spare.ptr, spare.len);
  169. if (@as(isize, @bitCast(rc)) <= 0) break;
  170. content.items.len += rc;
  171. }
  172. return content.toOwnedSlice(alloc) catch null;
  173. }
  174. fn fileSize(alloc: std.mem.Allocator, path: []const u8) ?u64 {
  175. const path_z = alloc.dupeZ(u8, path) catch return null;
  176. defer alloc.free(path_z);
  177. var stx: linux.Statx = undefined;
  178. const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);
  179. if (rc != 0) return null;
  180. return stx.size;
  181. }
  182. const Stat = struct { ino: u64, size: u64, mtime_ns: i128 = 0 };
  183. // flock(2) operations
  184. const LOCK_SH: i32 = 1;
  185. const LOCK_EX: i32 = 2;
  186. const LOCK_NB: i32 = 4;
  187. fn flock(fd: i32, op: i32) bool {
  188. return linux.flock(fd, op) == 0;
  189. }
  190. fn fdStat(fd: i32) ?Stat {
  191. var stx: linux.Statx = undefined;
  192. const rc = linux.statx(fd, "", 0x1000, linux.STATX.BASIC_STATS, &stx); // AT_EMPTY_PATH
  193. if (rc != 0) return null;
  194. return .{ .ino = stx.ino, .size = stx.size, .mtime_ns = @as(i128, stx.mtime.sec) * 1_000_000_000 + stx.mtime.nsec };
  195. }
  196. fn fdIno(fd: i32) ?u64 {
  197. return if (fdStat(fd)) |st| st.ino else null;
  198. }
  199. fn stat(alloc: std.mem.Allocator, path: []const u8) ?Stat {
  200. const path_z = alloc.dupeZ(u8, path) catch return null;
  201. defer alloc.free(path_z);
  202. var stx: linux.Statx = undefined;
  203. const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);
  204. if (rc != 0) return null;
  205. return .{ .ino = stx.ino, .size = stx.size, .mtime_ns = @as(i128, stx.mtime.sec) * 1_000_000_000 + stx.mtime.nsec };
  206. }
  207. fn mtimeMs(alloc: std.mem.Allocator, path: []const u8) ?i64 {
  208. const path_z = alloc.dupeZ(u8, path) catch return null;
  209. defer alloc.free(path_z);
  210. var stx: linux.Statx = undefined;
  211. const rc = linux.statx(linux.AT.FDCWD, path_z, 0, linux.STATX.BASIC_STATS, &stx);
  212. if (rc != 0) return null;
  213. return @as(i64, stx.mtime.sec) * 1000 + @divTrunc(@as(i64, stx.mtime.nsec), 1_000_000);
  214. }
  215. fn rename(alloc: std.mem.Allocator, old_path: []const u8, new_path: []const u8) bool {
  216. const old_z = alloc.dupeZ(u8, old_path) catch return false;
  217. defer alloc.free(old_z);
  218. const new_z = alloc.dupeZ(u8, new_path) catch return false;
  219. defer alloc.free(new_z);
  220. return linux.renameat(linux.AT.FDCWD, old_z, linux.AT.FDCWD, new_z) == 0;
  221. }
  222. fn unlink(alloc: std.mem.Allocator, path: []const u8) bool {
  223. const path_z = alloc.dupeZ(u8, path) catch return false;
  224. defer alloc.free(path_z);
  225. return linux.unlinkat(linux.AT.FDCWD, path_z, 0) == 0;
  226. }
  227. fn mkdirAll(alloc: std.mem.Allocator, dir_path: []const u8) void {
  228. if (dir_path.len == 0 or std.mem.eql(u8, dir_path, ".")) return;
  229. var i: usize = 1;
  230. while (i <= dir_path.len) : (i += 1) {
  231. if (i == dir_path.len or dir_path[i] == '/') {
  232. const part = alloc.dupeZ(u8, dir_path[0..i]) catch return;
  233. defer alloc.free(part);
  234. _ = linux.mkdirat(linux.AT.FDCWD, part, 0o755);
  235. }
  236. }
  237. }
  238. fn sleepMs(ms: u64) void {
  239. var req: linux.timespec = .{ .sec = @intCast(ms / 1000), .nsec = @intCast((ms % 1000) * 1_000_000) };
  240. var rem: linux.timespec = undefined;
  241. _ = linux.nanosleep(&req, &rem);
  242. }
  243. fn nowMs() i64 {
  244. var ts: linux.timespec = undefined;
  245. _ = linux.clock_gettime(linux.CLOCK.REALTIME, &ts);
  246. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  247. }
  248. };
  249. // =========================================================================
  250. // JS-compatible helpers
  251. // =========================================================================
  252. /// Format an f64 the way JS String(n) does for the values mpackdb produces:
  253. /// integral values print without a decimal point. (Exotic floats may diverge
  254. /// from V8's shortest-round-trip formatting; index keys are ints/strings in
  255. /// practice.)
  256. pub fn jsNumFmt(buf: []u8, v: f64) []const u8 {
  257. if (v == @floor(v) and @abs(v) <= 9007199254740992.0) {
  258. const i: i64 = @intFromFloat(v);
  259. return std.fmt.bufPrint(buf, "{d}", .{i}) catch buf[0..0];
  260. }
  261. return std.fmt.bufPrint(buf, "{d}", .{v}) catch buf[0..0];
  262. }
  263. /// Index line key text (mission 486). A key is written raw, as it always was, unless it holds
  264. /// a newline or a carriage return (it would split the line) or starts with a double quote (it
  265. /// would look like the quoted form); only then it is written as a JSON string.
  266. fn keyNeedsQuote(ks: []const u8) bool {
  267. if (ks.len > 0 and ks[0] == '"') return true;
  268. return std.mem.indexOfAny(u8, ks, "\n\r") != null;
  269. }
  270. /// Append `ks` as a JSON string (the escapes of JSON.stringify).
  271. fn appendQuotedKey(out: *std.ArrayList(u8), a: std.mem.Allocator, ks: []const u8) !void {
  272. try out.append(a, '"');
  273. for (ks) |c| {
  274. switch (c) {
  275. '"' => try out.appendSlice(a, "\\\""),
  276. '\\' => try out.appendSlice(a, "\\\\"),
  277. '\n' => try out.appendSlice(a, "\\n"),
  278. '\r' => try out.appendSlice(a, "\\r"),
  279. '\t' => try out.appendSlice(a, "\\t"),
  280. 8 => try out.appendSlice(a, "\\b"),
  281. 12 => try out.appendSlice(a, "\\f"),
  282. 0...7, 11, 14...31 => {
  283. var b: [6]u8 = undefined;
  284. try out.appendSlice(a, std.fmt.bufPrint(&b, "\\u{x:0>4}", .{c}) catch unreachable);
  285. },
  286. else => try out.append(a, c),
  287. }
  288. }
  289. try out.append(a, '"');
  290. }
  291. /// The key text of an index line: raw, or quoted when it has to be.
  292. fn appendKeyText(out: *std.ArrayList(u8), a: std.mem.Allocator, ks: []const u8) !void {
  293. if (keyNeedsQuote(ks)) try appendQuotedKey(out, a, ks) else try out.appendSlice(a, ks);
  294. }
  295. /// Decode the JSON string that starts at line[0] (a double quote). Returns the key and the
  296. /// index just after the closing quote, or null when it is no valid JSON string.
  297. fn decodeQuotedKey(a: std.mem.Allocator, line: []const u8) ?struct { key: []const u8, end: usize } {
  298. var i: usize = 1;
  299. var plain = true;
  300. while (i < line.len and line[i] != '"') : (i += 1) {
  301. if (line[i] == '\\') {
  302. plain = false;
  303. i += 1; // the escaped character is skipped here, decoded below
  304. }
  305. }
  306. if (i >= line.len) return null;
  307. if (plain) return .{ .key = line[1..i], .end = i + 1 };
  308. var out: std.ArrayList(u8) = .empty;
  309. var j: usize = 1;
  310. while (j < i) {
  311. const c = line[j];
  312. if (c != '\\') {
  313. out.append(a, c) catch return null;
  314. j += 1;
  315. continue;
  316. }
  317. j += 1;
  318. if (j >= i) return null;
  319. const e = line[j];
  320. j += 1;
  321. switch (e) {
  322. '"', '\\', '/' => out.append(a, e) catch return null,
  323. 'n' => out.append(a, '\n') catch return null,
  324. 'r' => out.append(a, '\r') catch return null,
  325. 't' => out.append(a, '\t') catch return null,
  326. 'b' => out.append(a, 8) catch return null,
  327. 'f' => out.append(a, 12) catch return null,
  328. 'u' => {
  329. if (j + 4 > i) return null;
  330. var cp: u21 = std.fmt.parseInt(u16, line[j .. j + 4], 16) catch return null;
  331. j += 4;
  332. if (cp >= 0xD800 and cp < 0xDC00 and j + 6 <= i and line[j] == '\\' and line[j + 1] == 'u') {
  333. const lo = std.fmt.parseInt(u16, line[j + 2 .. j + 6], 16) catch return null;
  334. if (lo >= 0xDC00 and lo < 0xE000) {
  335. cp = 0x10000 + ((cp - 0xD800) << 10) + (lo - 0xDC00);
  336. j += 6;
  337. }
  338. }
  339. var ub: [4]u8 = undefined;
  340. const n = std.unicode.utf8Encode(cp, &ub) catch blk: {
  341. // a lone surrogate has no UTF-8 form: the replacement character
  342. break :blk std.unicode.utf8Encode(0xFFFD, &ub) catch return null;
  343. };
  344. out.appendSlice(a, ub[0..n]) catch return null;
  345. },
  346. else => return null,
  347. }
  348. }
  349. return .{ .key = out.items, .end = i + 1 };
  350. }
  351. /// JS parseInt(s, 10) semantics: optional sign, leading digits, ignore rest.
  352. /// Returns null for NaN.
  353. fn jsParseInt(s: []const u8) ?f64 {
  354. var i: usize = 0;
  355. while (i < s.len and (s[i] == ' ' or s[i] == '\t')) i += 1;
  356. var sign: f64 = 1;
  357. if (i < s.len and (s[i] == '+' or s[i] == '-')) {
  358. if (s[i] == '-') sign = -1;
  359. i += 1;
  360. }
  361. var got = false;
  362. var v: f64 = 0;
  363. while (i < s.len and s[i] >= '0' and s[i] <= '9') : (i += 1) {
  364. v = v * 10 + @as(f64, @floatFromInt(s[i] - '0'));
  365. got = true;
  366. }
  367. if (!got) return null;
  368. return sign * v;
  369. }
  370. /// _compareKeys: numbers numerically; otherwise stringified byte compare
  371. /// (JS uses localeCompare — see divergence note in the header).
  372. pub fn cmpKeys(a: Key, b: Key) i32 {
  373. if (a == .num and b == .num) {
  374. if (a.num < b.num) return -1;
  375. if (a.num > b.num) return 1;
  376. return 0;
  377. }
  378. var buf_a: [32]u8 = undefined;
  379. var buf_b: [32]u8 = undefined;
  380. const sa = if (a == .str) a.str else jsNumFmt(&buf_a, a.num);
  381. const sb = if (b == .str) b.str else jsNumFmt(&buf_b, b.num);
  382. return switch (std.mem.order(u8, sa, sb)) {
  383. .lt => -1,
  384. .eq => 0,
  385. .gt => 1,
  386. };
  387. }
  388. fn entryLess(_: void, a: Entry, b: Entry) bool {
  389. const c = cmpKeys(a.key, b.key);
  390. if (c != 0) return c < 0;
  391. return a.off < b.off;
  392. }
  393. /// Sorts `items` by entryLess. Comparing two string keys follows two pointers into memory the
  394. /// sort has long left (a cache miss each, ~20 per entry): for a list of string keys the sort
  395. /// runs over (first 16 key bytes, index) records instead and compares the whole keys only for
  396. /// equal prefixes; the entries are then moved once (mission 436: 1 M ids, 3.4 s -> see report).
  397. fn sortEntries(alloc: std.mem.Allocator, items: []Entry) void {
  398. const plain = items.len < 512;
  399. var all_str = !plain;
  400. if (all_str) {
  401. for (items) |e| {
  402. if (e.key != .str) {
  403. all_str = false;
  404. break;
  405. }
  406. }
  407. }
  408. if (!all_str) return std.sort.pdq(Entry, items, {}, entryLess);
  409. const P = struct {
  410. p0: u64,
  411. p1: u64,
  412. i: u32,
  413. };
  414. if (items.len >= std.math.maxInt(u32)) return std.sort.pdq(Entry, items, {}, entryLess);
  415. const ps = alloc.alloc(P, items.len) catch return std.sort.pdq(Entry, items, {}, entryLess);
  416. defer alloc.free(ps);
  417. const copy = alloc.dupe(Entry, items) catch return std.sort.pdq(Entry, items, {}, entryLess);
  418. defer alloc.free(copy);
  419. for (copy, 0..) |e, i| {
  420. var b: [16]u8 = @splat(0);
  421. const k = e.key.str;
  422. @memcpy(b[0..@min(k.len, 16)], k[0..@min(k.len, 16)]);
  423. ps[i] = .{ .p0 = std.mem.readInt(u64, b[0..8], .big), .p1 = std.mem.readInt(u64, b[8..16], .big), .i = @intCast(i) };
  424. }
  425. const Ctx = struct {
  426. es: []const Entry,
  427. fn less(c: @This(), a: P, b: P) bool {
  428. if (a.p0 != b.p0) return a.p0 < b.p0;
  429. if (a.p1 != b.p1) return a.p1 < b.p1;
  430. const ea = c.es[a.i];
  431. const eb = c.es[b.i];
  432. return switch (std.mem.order(u8, ea.key.str, eb.key.str)) {
  433. .lt => true,
  434. .gt => false,
  435. .eq => ea.off < eb.off,
  436. };
  437. }
  438. };
  439. std.sort.pdq(P, ps, Ctx{ .es = copy }, Ctx.less);
  440. for (ps, 0..) |p, k| items[k] = copy[p.i];
  441. }
  442. /// mpack.js uuid(): 9-char base36 ms timestamp (padStart '0') + 3 base36 chars.
  443. pub fn genUuid(buf: *[12]u8) []const u8 {
  444. const digits = "0123456789abcdefghijklmnopqrstuvwxyz";
  445. const t: u64 = @intCast(fio.nowMs());
  446. var tmp: [16]u8 = undefined;
  447. var n: usize = 0;
  448. var v = t;
  449. while (v > 0) : (v /= 36) {
  450. tmp[n] = digits[@intCast(v % 36)];
  451. n += 1;
  452. }
  453. var i: usize = 0;
  454. while (i < 9) : (i += 1) {
  455. buf[8 - i] = if (i < n) tmp[i] else '0';
  456. }
  457. if (!rng_init) {
  458. var ts: linux.timespec = undefined;
  459. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  460. rng = std.Random.DefaultPrng.init(@bitCast(@as(i64, ts.sec) *% 1_000_000_000 +% ts.nsec));
  461. rng_init = true;
  462. }
  463. var r = rng.random();
  464. for (0..3) |j| {
  465. buf[9 + j] = digits[r.uintLessThan(u8, 36)];
  466. }
  467. return buf[0..12];
  468. }
  469. var rng: std.Random.DefaultPrng = .{ .s = undefined };
  470. var rng_init: bool = false;
  471. // =========================================================================
  472. // The database
  473. // =========================================================================
  474. pub const OpenOptions = struct {
  475. primary_key: ?[]const u8 = null, // with */@/! prefixes, like the JS API
  476. indexes: []const []const u8 = &.{}, // with prefixes
  477. compact: bool = true,
  478. stale_lock_timeout_ms: i64 = 30000,
  479. debug: bool = false,
  480. };
  481. /// The identity of a table on disk (ticket #110): dirname + basename with any
  482. /// extension stripped, exactly the computation `Db.open` uses to turn a given
  483. /// path into `<base>.mpack` — so two spellings of the same file (`x.db`, `x`)
  484. /// share one key. The plugin ABI layer (mpackdb.zig) keys its process-wide
  485. /// handle registry on this, so a table opened twice in one process — from any
  486. /// module instance or realm — shares the one live `Db` instead of each open
  487. /// racing the other's file state.
  488. pub fn tableKey(alloc: std.mem.Allocator, db_file: []const u8) Error![]u8 {
  489. const dir = std.fs.path.dirname(db_file) orelse ".";
  490. var base = std.fs.path.basename(db_file);
  491. if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {
  492. if (dot > 0) base = base[0..dot];
  493. }
  494. return std.fmt.allocPrint(alloc, "{s}/{s}", .{ dir, base }) catch Error.OutOfMemory;
  495. }
  496. /// The set of tombstoned offsets, shared and reference-counted (mission 393). The Db
  497. /// keeps ONE of it, built lazily from `deleted` and kept in step with every delete,
  498. /// so a lookup / range / scan no longer rebuilds an N-entry hash set per call. A scan
  499. /// that streams (a cursor) holds a reference to the set it started with: a later
  500. /// delete copies the set first (copy on write) and a compaction / foreign meta
  501. /// drops the Db's reference, so the cursor's view of the tombstones never changes.
  502. pub const DelSet = struct {
  503. map: std.AutoHashMapUnmanaged(u64, void) = .empty,
  504. refs: u32 = 1,
  505. alloc: std.mem.Allocator,
  506. pub fn release(self: *DelSet) void {
  507. self.refs -= 1;
  508. if (self.refs == 0) {
  509. const a = self.alloc;
  510. self.map.deinit(a);
  511. a.destroy(self);
  512. }
  513. }
  514. };
  515. /// One open data file, shared by the Db and the cursors that started on it (fd403).
  516. pub const DataGen = struct {
  517. fd: i32,
  518. refs: std.atomic.Value(u32),
  519. gpa: std.mem.Allocator,
  520. fn create(gpa: std.mem.Allocator, fd: i32) ?*DataGen {
  521. const g = gpa.create(DataGen) catch return null;
  522. g.* = .{ .fd = fd, .refs = std.atomic.Value(u32).init(1), .gpa = gpa };
  523. return g;
  524. }
  525. pub fn retain(self: *DataGen) *DataGen {
  526. _ = self.refs.fetchAdd(1, .monotonic);
  527. return self;
  528. }
  529. pub fn release(self: *DataGen) void {
  530. if (self.refs.fetchSub(1, .acq_rel) == 1) {
  531. fio.close(self.fd);
  532. self.gpa.destroy(self);
  533. }
  534. }
  535. };
  536. pub const Db = struct {
  537. arena_state: std.heap.ArenaAllocator,
  538. alloc: std.mem.Allocator, // arena — freed wholesale on close
  539. // THE BUFFERS OF ONE OPERATION ARE NOT THE HANDLE'S (hybriel#126): the meta read
  540. // back and rendered anew, the index files, the paths. On the arena they stayed for
  541. // the handle's life, and the meta grows with every tombstone, so each update leaked
  542. // more than the last (notes: 2000 updates of one note, +100 MB). They are freed now.
  543. tmp: std.mem.Allocator,
  544. // paths
  545. data_path: []const u8,
  546. meta_path: []const u8,
  547. lock_path: []const u8,
  548. idxstate_path: []const u8,
  549. flock_path: []const u8 = "",
  550. /// THE STORE LOCK (ticket #176): every open handle holds a shared flock on
  551. /// `<base>.flock` for its whole life; a compaction needs it exclusive and
  552. /// skips when it cannot have it at once — another process has the store open,
  553. /// and rewriting the file under it is what lost the tracker its reads.
  554. store_fd: i32 = -1,
  555. // schema
  556. pk: ?[]const u8 = null,
  557. pk_type: PkType = .string,
  558. index_fields: std.ArrayList([]const u8) = .empty, // pk first (when set), like JS
  559. unique_fields: std.ArrayList([]const u8) = .empty,
  560. idx: std.StringArrayHashMapUnmanaged(FieldIndex) = .empty,
  561. // meta
  562. next_id: f64 = FIRST_ID,
  563. deleted: std.ArrayList(u64) = .empty,
  564. /// lazily built set of `deleted` (mission 393); null = not built / invalidated
  565. del_cache: ?*DelSet = null,
  566. /// an index entry named a place that is no frame of its size (a stale persisted index):
  567. /// the next refresh() rebuilds every index from the data file (mission 393)
  568. index_bad: bool = false,
  569. index_retry: bool = false,
  570. version: u64 = 0,
  571. // THE META NAMES ITS DATA FILE (ticket #176): `dataFile` in .meta.json is the
  572. // inode and size of the data file it was written for, the compaction
  573. // generation, and a checksum of its own `deleted` list. A meta whose data file
  574. // was replaced under it (a crash between the rename and the meta write) has
  575. // tombstones that point into the WRONG file — they are dropped, not applied.
  576. // The checksum tells our dataFile from one another writer carried along: the
  577. // JS mpackdb rewrites the meta as `{...meta}` and keeps fields it does not
  578. // know, so a `deleted` list it changed no longer matches the sum, and such a
  579. // meta is taken as it is (as before #176).
  580. bind_known: bool = false, // the meta on disk carries a dataFile that is ours and true
  581. bind_ino: u64 = 0,
  582. bind_size: u64 = 0,
  583. bind_fp: [16]u8 = undefined, // content fingerprint of the data file's first `bind_size` bytes
  584. bind_fp_len: u8 = 0, // 0 = none known (an old meta whose data file was not read)
  585. data_gen: u64 = 0,
  586. meta_stale: bool = false, // the loaded meta belonged to another data file
  587. idx_bind_known: bool = false, // the idxstate on disk names the data file's inode
  588. // the data file this handle's offsets are into (ticket #176): its inode and
  589. // the compaction generation; refresh() compares them on every operation
  590. seen_ino: u64 = 0,
  591. // THE FILE THE OFFSETS ARE INTO, held open (ticket #176): every read and scan
  592. // goes through it, never through the path — a rewrite renamed in between a
  593. // lookup and its read (the tracker parsed 1.4 MB of meta between the two)
  594. // then still reads the file the offsets belong to, and the next refresh()
  595. // moves the handle to the new one.
  596. data_fd: i32 = -1,
  597. // fd403: the refcounted holder of data_fd. A streaming cursor takes a reference to the
  598. // generation it started on instead of dup()ing the fd (a dup per query held thousands of
  599. // fds until the GC finalized abandoned cursors: > 1024 at the tracker's boot). The fd is
  600. // closed when the Db has moved on (compaction, close) AND the last cursor is gone.
  601. fd_gen: ?*DataGen = null,
  602. // The meta file as THIS handle last read or wrote it (ticket #188): it is only ever
  603. // replaced by tmp + rename, so a write changes its inode; refresh() stats it and
  604. // skips the read + parse of a (1.4 MB on the tracker) meta that is unchanged.
  605. meta_seen: ?fio.Stat = null,
  606. meta_reads: u64 = 0, // reads of the meta file by loadMeta/refresh (the test counts them)
  607. bulk_index: bool = false, // indexInsertEntry appends (a sorted pass follows): rebuild / long catch-up
  608. /// keys of a rebuild live here until the sort has put the entries in order; then they are
  609. /// copied side by side in that order (a rebuilt index is read in sorted order, again and
  610. /// again: written, compared, searched) and this arena is freed (mission 436)
  611. bulk_keys: ?*std.heap.ArenaAllocator = null,
  612. covered_bytes: u64 = 0,
  613. compact_on_open: bool = true,
  614. stale_lock_timeout_ms: i64 = 30000,
  615. debug: bool = false,
  616. // last DuplicateKey detail for the plugin surface
  617. last_error_buf: [256]u8 = undefined,
  618. last_error: []const u8 = "",
  619. pub fn open(gpa: std.mem.Allocator, db_file: []const u8, opts: OpenOptions) Error!*Db {
  620. if (db_file.len == 0) return Error.NoDbFile;
  621. const self = gpa.create(Db) catch return Error.OutOfMemory;
  622. self.* = .{
  623. .arena_state = std.heap.ArenaAllocator.init(gpa),
  624. .alloc = undefined,
  625. .tmp = gpa,
  626. .data_path = undefined,
  627. .meta_path = undefined,
  628. .lock_path = undefined,
  629. .idxstate_path = undefined,
  630. };
  631. self.alloc = self.arena_state.allocator();
  632. errdefer {
  633. self.arena_state.deinit();
  634. gpa.destroy(self);
  635. }
  636. const a = self.alloc;
  637. self.compact_on_open = opts.compact;
  638. self.stale_lock_timeout_ms = opts.stale_lock_timeout_ms;
  639. self.debug = opts.debug;
  640. // dirname / basename (extension stripped, like JS basename(f, extname(f)))
  641. const dir = std.fs.path.dirname(db_file) orelse ".";
  642. var base = std.fs.path.basename(db_file);
  643. if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {
  644. if (dot > 0) base = base[0..dot];
  645. }
  646. fio.mkdirAll(a, dir);
  647. self.data_path = std.fmt.allocPrint(a, "{s}/{s}.mpack", .{ dir, base }) catch return Error.OutOfMemory;
  648. self.meta_path = std.fmt.allocPrint(a, "{s}/{s}.meta.json", .{ dir, base }) catch return Error.OutOfMemory;
  649. self.lock_path = std.fmt.allocPrint(a, "{s}/{s}.lock", .{ dir, base }) catch return Error.OutOfMemory;
  650. self.idxstate_path = std.fmt.allocPrint(a, "{s}/{s}.idxstate.json", .{ dir, base }) catch return Error.OutOfMemory;
  651. self.flock_path = std.fmt.allocPrint(a, "{s}/{s}.flock", .{ dir, base }) catch return Error.OutOfMemory;
  652. try self.openStoreLock();
  653. errdefer self.closeStoreLock();
  654. // ---- parse primary key ----
  655. if (opts.primary_key) |pk_raw| {
  656. if (pk_raw.len > 0) {
  657. if (pk_raw[0] == '*') {
  658. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  659. self.pk_type = .number;
  660. } else if (pk_raw[0] == '@') {
  661. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  662. self.pk_type = .uuid;
  663. } else {
  664. self.pk = a.dupe(u8, pk_raw) catch return Error.OutOfMemory;
  665. self.pk_type = .string;
  666. }
  667. }
  668. }
  669. if (self.pk) |p| self.unique_fields.append(a, p) catch return Error.OutOfMemory;
  670. // ---- parse indexes (pk first, then configured; dedupe) ----
  671. if (self.pk) |p| {
  672. self.index_fields.append(a, p) catch return Error.OutOfMemory;
  673. const t: IdxType = if (self.pk_type == .number) .numeric else .lexical;
  674. self.idx.put(a, p, .{ .typ = t }) catch return Error.OutOfMemory;
  675. }
  676. for (opts.indexes) |raw| {
  677. var clean = raw;
  678. var is_unique = false;
  679. if (clean.len > 0 and clean[0] == '!') {
  680. is_unique = true;
  681. clean = clean[1..];
  682. }
  683. var typ: IdxType = .lexical;
  684. if (clean.len > 0 and clean[0] == '*') {
  685. typ = .numeric;
  686. clean = clean[1..];
  687. } else if (clean.len > 0 and clean[0] == '@') {
  688. clean = clean[1..];
  689. }
  690. if (self.idx.contains(clean)) continue;
  691. const owned = a.dupe(u8, clean) catch return Error.OutOfMemory;
  692. self.index_fields.append(a, owned) catch return Error.OutOfMemory;
  693. self.idx.put(a, owned, .{ .typ = typ }) catch return Error.OutOfMemory;
  694. if (is_unique) self.unique_fields.append(a, owned) catch return Error.OutOfMemory;
  695. }
  696. // ---- load meta ----
  697. self.loadMeta();
  698. // ---- compact on init (JS default; also creates an empty data file) ----
  699. // AN OPEN WITH NOTHING TO CHANGE WRITES NOTHING (ticket #21): a store
  700. // with no tombstones has nothing to compact, and rewriting it anyway
  701. // made opening a backup change it.
  702. var did_compact = false;
  703. const nothing_to_compact = self.deleted.items.len == 0 and
  704. fio.fileSize(self.tmp, self.data_path) != null;
  705. if (self.compact_on_open and !nothing_to_compact) {
  706. try self.acquireLock();
  707. const cr = if (self.tryExclusive()) blk: {
  708. defer self.backToShared();
  709. break :blk self.compactLocked();
  710. } else self.skipCompaction();
  711. self.releaseLock();
  712. // A REFUSED compaction does not fail the open (ticket #176): nothing
  713. // was rewritten, the store is as it was, and it stays readable; the
  714. // refusal is on stderr and in last_error.
  715. if (cr) |ran| {
  716. did_compact = ran;
  717. } else |e| {
  718. if (e != Error.CompactRefused) return e;
  719. }
  720. }
  721. self.adoptDataFile();
  722. errdefer self.dropDataFile();
  723. // ---- persist schema into meta (JS: init-schema under lock).
  724. // compactLocked already wrote meta (with schema); skip the extra bump.
  725. // A meta found to belong to another data file is replaced at once, so a
  726. // stale one never outlives the open that saw it (ticket #176).
  727. if (!did_compact and (self.meta_stale or ((self.pk != null or self.index_fields.items.len > 0) and
  728. !self.metaOnDiskIsCurrent())))
  729. {
  730. try self.acquireLock();
  731. const mr = self.persistMetaLocked();
  732. self.releaseLock();
  733. try mr;
  734. }
  735. // ---- indexes (JS: (re)build under the lock; force after compaction) ----
  736. if (self.index_fields.items.len > 0) {
  737. try self.acquireLock();
  738. const ir = self.initIndexes(did_compact);
  739. self.releaseLock();
  740. try ir;
  741. }
  742. return self;
  743. }
  744. pub fn close(self: *Db) void {
  745. // persist indexes + idxstate (JS: IndexManager.close → persist under lock)
  746. if (self.index_fields.items.len > 0) {
  747. if (self.acquireLock()) {
  748. // MISSION 395 (#203): the index in memory is of the data file this handle holds. Another
  749. // process (the JS mpackdb, a build before #176: none takes the store lock) may have
  750. // rewritten it since; persisting before looking wrote that old generation's offsets
  751. // as the index files — beside an idxstate that named the NEW file.
  752. self.refresh();
  753. self.persistIndexesLocked() catch {};
  754. self.releaseLock();
  755. } else |_| {}
  756. }
  757. self.dropDataFile();
  758. self.delCacheDrop();
  759. self.closeStoreLock();
  760. const gpa = self.arena_state.child_allocator;
  761. self.arena_state.deinit();
  762. gpa.destroy(self);
  763. }
  764. fn dbg(self: *Db, comptime fmt: []const u8, args: anytype) void {
  765. if (self.debug) std.debug.print("[mpackdb] " ++ fmt ++ "\n", args);
  766. }
  767. // =====================================================================
  768. // Locking (JS _acquireFileLock protocol)
  769. // =====================================================================
  770. fn acquireLock(self: *Db) Error!void {
  771. var retries: u32 = 0;
  772. while (true) {
  773. if (fio.openExcl(self.tmp, self.lock_path)) |fd| {
  774. var pid_buf: [16]u8 = undefined;
  775. const pid_s = std.fmt.bufPrint(&pid_buf, "{d}", .{linux.getpid()}) catch "0";
  776. _ = fio.writeAll(fd, pid_s);
  777. fio.close(fd);
  778. return;
  779. }
  780. // stale lock takeover
  781. if (self.stale_lock_timeout_ms > 0) {
  782. if (fio.mtimeMs(self.tmp, self.lock_path)) |mt| {
  783. if (fio.nowMs() - mt > self.stale_lock_timeout_ms) {
  784. _ = fio.unlink(self.tmp, self.lock_path);
  785. continue;
  786. }
  787. }
  788. }
  789. if (retries > 480) return Error.LockTimeout; // ~12s at 25ms
  790. fio.sleepMs(25);
  791. retries += 1;
  792. }
  793. }
  794. fn releaseLock(self: *Db) void {
  795. _ = fio.unlink(self.tmp, self.lock_path);
  796. }
  797. /// Take the shared store lock. The lock file is unlinked by the last handle
  798. /// to close (under the exclusive lock), so a lock taken on a file that is no
  799. /// longer the one at the path is let go and taken anew.
  800. fn openStoreLock(self: *Db) Error!void {
  801. var tries: usize = 0;
  802. while (tries < 1000) : (tries += 1) {
  803. const fd = fio.openz(self.tmp, self.flock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, 0o644) orelse return Error.IoError;
  804. if (!fio.flock(fd, fio.LOCK_SH)) {
  805. fio.close(fd);
  806. return Error.IoError;
  807. }
  808. const held = fio.fdIno(fd);
  809. const at_path = fio.stat(self.tmp, self.flock_path);
  810. if (held != null and at_path != null and held.? == at_path.?.ino) {
  811. self.store_fd = fd;
  812. return;
  813. }
  814. fio.close(fd);
  815. }
  816. return Error.LockTimeout;
  817. }
  818. fn closeStoreLock(self: *Db) void {
  819. if (self.store_fd < 0) return;
  820. // the last one out removes the lock file — only while no one else holds it
  821. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) _ = fio.unlink(self.tmp, self.flock_path);
  822. fio.close(self.store_fd);
  823. self.store_fd = -1;
  824. }
  825. /// Exclusive, without waiting: true when no other handle (in any process)
  826. /// holds the store.
  827. fn tryExclusive(self: *Db) bool {
  828. if (self.store_fd < 0) return false;
  829. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) return true;
  830. // a failed conversion may have given up the shared lock: take it again
  831. _ = fio.flock(self.store_fd, fio.LOCK_SH);
  832. return false;
  833. }
  834. fn backToShared(self: *Db) void {
  835. if (self.store_fd >= 0) _ = fio.flock(self.store_fd, fio.LOCK_SH);
  836. }
  837. fn skipCompaction(self: *Db) Error!bool {
  838. self.last_error = "compaction skipped: the store is open in another process";
  839. self.dbg("{s}: {s}", .{ self.data_path, self.last_error });
  840. return false;
  841. }
  842. // =====================================================================
  843. // Meta (.meta.json)
  844. // =====================================================================
  845. fn appendFmt(self: *Db, list: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) Error!void {
  846. // a short piece is formatted on the stack (mission 436: one heap allocation per
  847. // tombstone / index line made rendering a 3 MB meta cost more than parsing it)
  848. var sbuf: [256]u8 = undefined;
  849. if (std.fmt.bufPrint(&sbuf, fmt, args)) |piece| {
  850. list.appendSlice(self.tmp, piece) catch return Error.OutOfMemory;
  851. return;
  852. } else |_| {}
  853. const s = std.fmt.allocPrint(self.tmp, fmt, args) catch return Error.OutOfMemory;
  854. defer self.tmp.free(s);
  855. list.appendSlice(self.tmp, s) catch return Error.OutOfMemory;
  856. }
  857. fn loadMeta(self: *Db) void {
  858. // stat BEFORE the read: a write racing in between then shows as a change next time
  859. self.meta_seen = fio.stat(self.tmp, self.meta_path);
  860. self.meta_reads += 1;
  861. const content = fio.readAll(self.tmp, self.meta_path) orelse return;
  862. defer self.tmp.free(content);
  863. self.applyMetaJson(content);
  864. }
  865. /// What applyMetaJson needs of the meta's `dataFile` object.
  866. const DataFileMeta = struct {
  867. ino: ?u64 = null,
  868. size: ?u64 = null,
  869. gen: ?u64 = null,
  870. sum: ?[]const u8 = null, // deletedSum when it is a string
  871. fp_present: bool = false,
  872. fp: ?[]const u8 = null, // fp when it is a string
  873. };
  874. /// A JSON number token the way std.json.Value would hold it: an integer, or a float.
  875. const JNum = union(enum) { int: i64, float: f64 };
  876. fn jnum(text: []const u8) ?JNum {
  877. if (std.mem.indexOfAny(u8, text, ".eE") == null) {
  878. return .{ .int = std.fmt.parseInt(i64, text, 10) catch return null };
  879. }
  880. return .{ .float = std.fmt.parseFloat(f64, text) catch return null };
  881. }
  882. /// MISSION 436: the meta of a big table is megabytes (the tracker's shows: 308 K tombstones);
  883. /// std.json.Value built a tagged value per offset, then freed them again. This walks the
  884. /// tokens and keeps only what applyMetaJson reads. It returns false — having changed
  885. /// nothing — for anything it does not recognise or any malformed text, and the Value
  886. /// path below then decides, exactly as before.
  887. fn applyMetaFast(self: *Db, content: []const u8) bool {
  888. var sc = std.json.Scanner.initCompleteInput(self.tmp, content);
  889. defer sc.deinit();
  890. var del: std.ArrayList(u64) = .empty;
  891. defer del.deinit(self.tmp);
  892. var next_id: f64 = FIRST_ID;
  893. var version: u64 = 0;
  894. var df: ?DataFileMeta = null;
  895. const t0 = sc.next() catch return false;
  896. if (t0 != .object_begin) return false;
  897. while (true) {
  898. const kt = sc.next() catch return false;
  899. const key = switch (kt) {
  900. .object_end => break,
  901. .string => |k| k,
  902. else => return false,
  903. };
  904. if (std.mem.eql(u8, key, "nextId")) {
  905. const t = sc.next() catch return false;
  906. next_id = switch (t) {
  907. .number => |n| switch (jnum(n) orelse return false) {
  908. .int => |i| @floatFromInt(i),
  909. .float => |f| f,
  910. },
  911. .string, .true, .false, .null => FIRST_ID,
  912. else => return false,
  913. };
  914. } else if (std.mem.eql(u8, key, "version")) {
  915. const t = sc.next() catch return false;
  916. version = switch (t) {
  917. .number => |n| switch (jnum(n) orelse return false) {
  918. .int => |i| @intCast(@max(i, 0)),
  919. .float => 0,
  920. },
  921. .string, .true, .false, .null => 0,
  922. else => return false,
  923. };
  924. } else if (std.mem.eql(u8, key, "deleted")) {
  925. del.clearRetainingCapacity();
  926. const t = sc.next() catch return false;
  927. switch (t) {
  928. .array_begin => while (true) {
  929. const e = sc.next() catch return false;
  930. switch (e) {
  931. .array_end => break,
  932. .number => |n| {
  933. const off: u64 = switch (jnum(n) orelse return false) {
  934. .int => |i| @intCast(@max(i, 0)),
  935. .float => |f| @intFromFloat(@max(f, 0)),
  936. };
  937. del.append(self.tmp, off) catch return false;
  938. },
  939. .string, .true, .false, .null => {},
  940. else => return false,
  941. }
  942. },
  943. .string, .number, .true, .false, .null => {},
  944. else => return false,
  945. }
  946. } else if (std.mem.eql(u8, key, "dataFile")) {
  947. df = null;
  948. const t = sc.next() catch return false;
  949. switch (t) {
  950. .object_begin => {
  951. var d = DataFileMeta{};
  952. while (true) {
  953. const ik = sc.next() catch return false;
  954. const k2 = switch (ik) {
  955. .object_end => break,
  956. .string => |k| k,
  957. else => return false,
  958. };
  959. const v = sc.next() catch return false;
  960. const is_u64: ?u64 = switch (v) {
  961. .number => |n| switch (jnum(n) orelse return false) {
  962. .int => |i| if (i < 0) null else @intCast(i),
  963. .float => null,
  964. },
  965. .string, .true, .false, .null => null,
  966. else => return false,
  967. };
  968. const str: ?[]const u8 = if (v == .string) v.string else null;
  969. if (std.mem.eql(u8, k2, "ino")) {
  970. d.ino = is_u64;
  971. } else if (std.mem.eql(u8, k2, "size")) {
  972. d.size = is_u64;
  973. } else if (std.mem.eql(u8, k2, "gen")) {
  974. d.gen = is_u64;
  975. } else if (std.mem.eql(u8, k2, "deletedSum")) {
  976. d.sum = str;
  977. } else if (std.mem.eql(u8, k2, "fp")) {
  978. d.fp_present = true;
  979. d.fp = str;
  980. }
  981. }
  982. df = d;
  983. },
  984. .string, .number, .true, .false, .null => {},
  985. else => return false,
  986. }
  987. } else {
  988. sc.skipValue() catch return false;
  989. }
  990. }
  991. const te = sc.next() catch return false;
  992. if (te != .end_of_document) return false;
  993. // parsed whole: apply
  994. self.next_id = next_id;
  995. self.deleted.clearRetainingCapacity();
  996. self.delCacheDrop();
  997. self.version = version;
  998. self.deleted.appendSlice(self.alloc, del.items) catch {};
  999. self.bind_known = false;
  1000. self.meta_stale = false;
  1001. if (df) |d| self.applyBinding(d);
  1002. return true;
  1003. }
  1004. fn applyMetaJson(self: *Db, content: []const u8) void {
  1005. if (self.applyMetaFast(content)) return;
  1006. self.applyMetaSlow(content);
  1007. }
  1008. /// The meta through std.json.Value (the reading before mission 436; also the fallback).
  1009. fn applyMetaSlow(self: *Db, content: []const u8) void {
  1010. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  1011. defer parsed.deinit();
  1012. if (parsed.value != .object) return;
  1013. const obj = parsed.value.object;
  1014. self.next_id = FIRST_ID;
  1015. self.deleted.clearRetainingCapacity();
  1016. self.delCacheDrop();
  1017. self.version = 0;
  1018. if (obj.get("nextId")) |v| {
  1019. self.next_id = switch (v) {
  1020. .integer => |i| @floatFromInt(i),
  1021. .float => |f| f,
  1022. else => FIRST_ID,
  1023. };
  1024. }
  1025. if (obj.get("version")) |v| {
  1026. if (v == .integer) self.version = @intCast(@max(v.integer, 0));
  1027. }
  1028. if (obj.get("deleted")) |v| {
  1029. if (v == .array) {
  1030. for (v.array.items) |it| {
  1031. const off: u64 = switch (it) {
  1032. .integer => |i| @intCast(@max(i, 0)),
  1033. .float => |f| @intFromFloat(@max(f, 0)),
  1034. else => continue,
  1035. };
  1036. self.deleted.append(self.alloc, off) catch {};
  1037. }
  1038. }
  1039. }
  1040. self.bind_known = false;
  1041. self.meta_stale = false;
  1042. const df_v = obj.get("dataFile") orelse return;
  1043. if (df_v != .object) return;
  1044. const df = df_v.object;
  1045. var d = DataFileMeta{ .ino = jsonU64(df.get("ino")), .size = jsonU64(df.get("size")), .gen = jsonU64(df.get("gen")) };
  1046. if (df.get("deletedSum")) |sv| {
  1047. if (sv == .string) d.sum = sv.string;
  1048. }
  1049. if (df.get("fp")) |fv| {
  1050. d.fp_present = true;
  1051. if (fv == .string) d.fp = fv.string;
  1052. }
  1053. self.applyBinding(d);
  1054. }
  1055. /// The tail of applyMetaJson: does the meta's `dataFile` bind it to the data file at the path?
  1056. fn applyBinding(self: *Db, df: DataFileMeta) void {
  1057. const ino = df.ino orelse return;
  1058. const size = df.size orelse return;
  1059. if (df.gen) |g| self.data_gen = @max(self.data_gen, g);
  1060. const sum = df.sum orelse return;
  1061. var sum_buf: [16]u8 = undefined;
  1062. if (!std.mem.eql(u8, sum, self.deletedSum(&sum_buf))) return; // another writer's
  1063. const cur = fio.stat(self.tmp, self.data_path);
  1064. // THE BINDING RULE (ticket 387, after #176): the inode is the fast path, the
  1065. // content is the proof. A byte COPY of an open store (a hot tar, a deploy
  1066. // backup, a restore) has a new inode but the same bytes, and its meta must
  1067. // still apply — its tombstones and newer versions are the store's truth.
  1068. // - same inode, file at least `size` bytes: bound (as in #176).
  1069. // - file shorter than `size`, or gone: stale (a different file).
  1070. // - another inode, meta carries `fp` (fingerprint of the first and last
  1071. // 4 KB of the first `size` bytes): bound if the file's fingerprint over
  1072. // that range equals it (the same content, copied or restored); a data
  1073. // file a compaction replaced differs in content, so it stays stale.
  1074. // - another inode, an OLD meta without `fp`: bound only if every tombstone
  1075. // offset is a plausible frame start in the file (size > 4, fits, and the
  1076. // next frame's header is plausible or EOF). Else stale.
  1077. var bound = false;
  1078. var fp_buf: [16]u8 = undefined;
  1079. var have_fp: ?[]const u8 = null;
  1080. if (cur) |c| {
  1081. if (c.size >= size) {
  1082. if (c.ino == ino) {
  1083. bound = true;
  1084. } else if (df.fp_present) {
  1085. if (df.fp) |fv| {
  1086. have_fp = self.dataFingerprint(size, &fp_buf);
  1087. bound = have_fp != null and std.mem.eql(u8, have_fp.?, fv);
  1088. }
  1089. } else {
  1090. bound = self.tombstonesAreFrameStarts(c.size);
  1091. }
  1092. }
  1093. } else bound = size == 0;
  1094. if (!bound) {
  1095. if (self.deleted.items.len > 0) {
  1096. std.debug.print("mpackdb: {s}: the meta belongs to another data file (inode {d}, {d} bytes); its {d} tombstones are not applied\n", .{ self.data_path, ino, size, self.deleted.items.len });
  1097. }
  1098. self.deleted.clearRetainingCapacity();
  1099. self.delCacheDrop();
  1100. self.meta_stale = true;
  1101. return;
  1102. }
  1103. self.bind_known = true;
  1104. self.bind_ino = if (cur) |c| c.ino else ino; // a copy: this file's inode from now on
  1105. self.bind_size = size;
  1106. self.bind_fp_len = 0;
  1107. if (have_fp == null) have_fp = self.dataFingerprint(size, &fp_buf);
  1108. if (have_fp) |f| {
  1109. @memcpy(self.bind_fp[0..f.len], f);
  1110. self.bind_fp_len = @intCast(f.len);
  1111. }
  1112. }
  1113. /// Fingerprint (16 hex chars) of the first `n` bytes of the data file: a hash of
  1114. /// its first 4 KB and one of the 4 KB before `n`. Appends past `n` do not change
  1115. /// it; a replaced (compacted) file, with other records at those places, does.
  1116. fn dataFingerprint(self: *Db, n: u64, buf: *[16]u8) ?[]const u8 {
  1117. const fd = fio.openRead(self.tmp, self.data_path) orelse return null;
  1118. defer fio.close(fd);
  1119. return fingerprintFd(fd, n, buf);
  1120. }
  1121. fn fingerprintFd(fd: i32, n: u64, buf: *[16]u8) ?[]const u8 {
  1122. var h = std.hash.Wyhash.init(387);
  1123. var blk: [4096]u8 = undefined;
  1124. const head: usize = @intCast(@min(n, 4096));
  1125. const got = fio.pread(fd, blk[0..head], 0) orelse return null;
  1126. if (got != head) return null;
  1127. h.update(blk[0..head]);
  1128. const tail_off = n - head;
  1129. const got2 = fio.pread(fd, blk[0..head], tail_off) orelse return null;
  1130. if (got2 != head) return null;
  1131. h.update(blk[0..head]);
  1132. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch null;
  1133. }
  1134. /// An old meta (no fingerprint) beside a file of another inode: are its tombstones
  1135. /// frame starts of this file? A frame start has a size > 4 that fits in the file,
  1136. /// and is followed by EOF or another plausible frame header.
  1137. fn tombstonesAreFrameStarts(self: *Db, file_size: u64) bool {
  1138. const fd = fio.openRead(self.tmp, self.data_path) orelse return self.deleted.items.len == 0;
  1139. defer fio.close(fd);
  1140. for (self.deleted.items) |off| {
  1141. if (!frameHeaderOk(fd, off, file_size)) return false;
  1142. var hdr: [4]u8 = undefined;
  1143. _ = fio.pread(fd, &hdr, off);
  1144. const next = off + std.mem.readInt(u32, &hdr, .little);
  1145. if (next != file_size and !frameHeaderOk(fd, next, file_size)) return false;
  1146. }
  1147. return true;
  1148. }
  1149. fn frameHeaderOk(fd: i32, off: u64, file_size: u64) bool {
  1150. if (off + 4 > file_size) return false;
  1151. var hdr: [4]u8 = undefined;
  1152. const got = fio.pread(fd, &hdr, off) orelse return false;
  1153. if (got < 4) return false;
  1154. const sz: u64 = std.mem.readInt(u32, &hdr, .little);
  1155. return sz > 4 and off + sz <= file_size;
  1156. }
  1157. fn jsonU64(v: ?std.json.Value) ?u64 {
  1158. const x = v orelse return null;
  1159. return switch (x) {
  1160. .integer => |i| if (i < 0) null else @intCast(i),
  1161. else => null,
  1162. };
  1163. }
  1164. /// The checksum of the deleted list (hex), as dataFile.deletedSum carries it.
  1165. fn deletedSum(self: *Db, buf: *[16]u8) []const u8 {
  1166. var h = std.hash.Wyhash.init(176);
  1167. // the stream of little-endian u64s, fed in blocks (the hash does not depend on the split)
  1168. var blk: [512]u64 = undefined;
  1169. var i: usize = 0;
  1170. while (i < self.deleted.items.len) {
  1171. const n = @min(blk.len, self.deleted.items.len - i);
  1172. for (0..n) |j| blk[j] = std.mem.nativeToLittle(u64, self.deleted.items[i + j]);
  1173. h.update(std.mem.sliceAsBytes(blk[0..n]));
  1174. i += n;
  1175. }
  1176. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch buf[0..0];
  1177. }
  1178. /// Pick up other processes' persisted state (JS refresh()): adopt disk meta
  1179. /// when its version is newer; index appended tail records.
  1180. ///
  1181. /// A HANDLE NOTICES A REWRITE (ticket #176). Another process's compaction
  1182. /// replaces the data file and moves every record after its first tombstone;
  1183. /// this handle's offsets are then into a file that no longer exists, and
  1184. /// reading them read the middle of other records — a bare Number where a
  1185. /// record was (the tracker, 2026-10-20). The data file's inode, a size below
  1186. /// what was indexed, or a newer compaction generation in the meta says it
  1187. /// happened; the handle then re-reads the meta (dropping a deleted list that
  1188. /// belongs to the old file) and re-indexes the new file before it answers.
  1189. pub fn refresh(self: *Db) void {
  1190. if (self.data_fd < 0) self.adoptDataFile(); // a file created since the open
  1191. if (self.index_bad) self.rebuildIndexesFromData();
  1192. const cur = fio.stat(self.tmp, self.data_path);
  1193. var rewritten = false;
  1194. if (cur) |c| {
  1195. if (self.seen_ino != 0 and c.ino != self.seen_ino) rewritten = true;
  1196. if (self.index_fields.items.len > 0 and c.size < self.covered_bytes) rewritten = true;
  1197. }
  1198. const meta_now = fio.stat(self.tmp, self.meta_path);
  1199. const meta_same = if (meta_now) |m| (if (self.meta_seen) |o| (m.ino == o.ino and m.size == o.size and m.mtime_ns == o.mtime_ns) else false) else true;
  1200. // an unchanged meta says nothing new: its version and generation were taken when read
  1201. // (a rewritten data file still re-reads it, to drop a deleted list of the old file)
  1202. if (meta_same and !rewritten) {
  1203. // nothing to read
  1204. } else if (blk: {
  1205. self.meta_seen = meta_now;
  1206. self.meta_reads += 1;
  1207. break :blk fio.readAll(self.tmp, self.meta_path);
  1208. }) |content| {
  1209. defer self.tmp.free(content);
  1210. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  1211. defer parsed.deinit();
  1212. if (parsed.value == .object) {
  1213. var disk_version: u64 = 0;
  1214. if (parsed.value.object.get("version")) |v| {
  1215. if (v == .integer) disk_version = @intCast(@max(v.integer, 0));
  1216. }
  1217. if (parsed.value.object.get("dataFile")) |df| {
  1218. if (df == .object) {
  1219. if (jsonU64(df.object.get("gen"))) |g| {
  1220. if (g > self.data_gen) rewritten = true;
  1221. }
  1222. }
  1223. }
  1224. if (rewritten or disk_version > self.version) self.applyMetaJson(content);
  1225. }
  1226. }
  1227. if (rewritten) {
  1228. self.reindexRewritten();
  1229. return;
  1230. }
  1231. // catchUp: index records another process appended
  1232. if (self.index_fields.items.len > 0) {
  1233. const size = if (cur) |c| c.size else 0;
  1234. if (size > self.covered_bytes) self.catchUp(size);
  1235. }
  1236. }
  1237. /// THE INDEX NAMED A PLACE THAT IS NO RECORD (mission 393): the tracker's persons.id.txt
  1238. /// carried ~2100 entries with offsets past the end of the data file or into the middle of a
  1239. /// frame (entries of an older generation of the file), so range('id', …) answered a Number
  1240. /// where a record was ("reading 'id': the value is Number"). A hit is checked against its
  1241. /// frame header before it is returned; a bad one is dropped and the indexes are rebuilt from
  1242. /// the data file at the next refresh.
  1243. fn hitOk(self: *Db, h: Entry) bool {
  1244. if (self.data_fd < 0) return true;
  1245. var hdr: [4]u8 = undefined;
  1246. const got = fio.pread(self.data_fd, &hdr, h.off) orelse 0;
  1247. if (got == 4 and std.mem.readInt(u32, &hdr, .little) == h.len) return true;
  1248. self.index_bad = true;
  1249. return false;
  1250. }
  1251. fn rebuildIndexesFromData(self: *Db) void {
  1252. self.index_bad = false;
  1253. self.covered_bytes = 0;
  1254. var it0 = self.idx.iterator();
  1255. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1256. if (self.index_fields.items.len > 0) {
  1257. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  1258. self.catchUp(size);
  1259. }
  1260. std.debug.print("mpackdb: {s}: an index named a place that is no record; indexes rebuilt from the data file\n", .{self.data_path});
  1261. }
  1262. /// The data file was replaced under this handle: index it anew, in memory —
  1263. /// the index files are written when the handle persists or closes.
  1264. fn reindexRewritten(self: *Db) void {
  1265. const old_ino = self.seen_ino;
  1266. self.adoptDataFile();
  1267. std.debug.print("mpackdb: {s}: the data file was rewritten by another process (inode {d} -> {d}); re-indexing before reading\n", .{ self.data_path, old_ino, self.seen_ino });
  1268. self.covered_bytes = 0;
  1269. var it0 = self.idx.iterator();
  1270. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1271. if (self.index_fields.items.len > 0) {
  1272. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  1273. self.catchUp(size);
  1274. }
  1275. }
  1276. /// Hold the data file now at the path; its inode is what the offsets are into.
  1277. fn adoptDataFile(self: *Db) void {
  1278. self.dropDataFile();
  1279. self.data_fd = fio.openz(self.tmp, self.data_path, .{ .CLOEXEC = true }, 0) orelse -1;
  1280. if (self.data_fd >= 0) self.fd_gen = DataGen.create(self.tmp, self.data_fd);
  1281. self.seen_ino = if (self.data_fd >= 0) (fio.fdIno(self.data_fd) orelse 0) else 0;
  1282. }
  1283. fn dropDataFile(self: *Db) void {
  1284. if (self.fd_gen) |g| g.release() else if (self.data_fd >= 0) fio.close(self.data_fd);
  1285. self.fd_gen = null;
  1286. self.data_fd = -1;
  1287. }
  1288. fn persistMetaLocked(self: *Db) Error!void {
  1289. self.version += 1;
  1290. const cur = fio.stat(self.tmp, self.data_path);
  1291. self.bind_ino = if (cur) |c| c.ino else 0;
  1292. self.bind_size = if (cur) |c| c.size else 0;
  1293. self.bind_fp_len = 0;
  1294. var fpb: [16]u8 = undefined;
  1295. if (self.dataFingerprint(self.bind_size, &fpb)) |f| {
  1296. @memcpy(self.bind_fp[0..f.len], f);
  1297. self.bind_fp_len = @intCast(f.len);
  1298. }
  1299. self.bind_known = true;
  1300. self.meta_stale = false;
  1301. var out: std.ArrayList(u8) = .empty;
  1302. defer out.deinit(self.tmp);
  1303. try self.renderMeta(&out);
  1304. // atomic tmp + rename (JS: `${metaPath}.${pid}.tmp`)
  1305. var tmp_buf: [512]u8 = undefined;
  1306. const tmp_path = std.fmt.bufPrint(&tmp_buf, "{s}.{d}.tmp", .{ self.meta_path, linux.getpid() }) catch return Error.IoError;
  1307. const fd = fio.openTrunc(self.tmp, tmp_path) orelse return Error.IoError;
  1308. const ok = fio.writeAll(fd, out.items);
  1309. // the tmp file's own stat: rename keeps the inode, and no other writer can slip in
  1310. // between a stat of the path and our remembering it (ticket #188)
  1311. const written = fio.fdStat(fd);
  1312. fio.close(fd);
  1313. if (!ok) return Error.IoError;
  1314. if (!fio.rename(self.tmp, tmp_path, self.meta_path)) return Error.IoError;
  1315. self.meta_seen = written;
  1316. }
  1317. /// Does .meta.json already say, byte for byte, what this handle would write
  1318. /// at its current version? Then an open has nothing to persist (ticket #21).
  1319. fn metaOnDiskIsCurrent(self: *Db) bool {
  1320. const disk = fio.readAll(self.tmp, self.meta_path) orelse return false;
  1321. defer self.tmp.free(disk);
  1322. var out: std.ArrayList(u8) = .empty;
  1323. defer out.deinit(self.tmp);
  1324. self.renderMeta(&out) catch return false;
  1325. return std.mem.eql(u8, disk, out.items);
  1326. }
  1327. fn renderMeta(self: *Db, out: *std.ArrayList(u8)) Error!void {
  1328. try self.appendFmt(out, "{{", .{});
  1329. if (self.pk != null and self.pk_type == .number) {
  1330. var nbuf: [32]u8 = undefined;
  1331. try self.appendFmt(out, "\"nextId\":{s},", .{jsNumFmt(&nbuf, self.next_id)});
  1332. }
  1333. try self.appendFmt(out, "\"deleted\":[", .{});
  1334. out.ensureUnusedCapacity(self.tmp, self.deleted.items.len * 9 + 64) catch return Error.OutOfMemory;
  1335. for (self.deleted.items, 0..) |off, i| {
  1336. out.ensureUnusedCapacity(self.tmp, 24) catch return Error.OutOfMemory;
  1337. if (i > 0) out.appendAssumeCapacity(',');
  1338. const spare = out.unusedCapacitySlice();
  1339. const w = std.fmt.bufPrint(spare, "{d}", .{off}) catch return Error.OutOfMemory;
  1340. out.items.len += w.len;
  1341. }
  1342. try self.appendFmt(out, "],\"version\":{d}", .{self.version});
  1343. if (self.pk != null or self.index_fields.items.len > 0) {
  1344. try self.appendFmt(out, ",\"schema\":{{", .{});
  1345. var first = true;
  1346. if (self.pk) |p| {
  1347. const prefix: []const u8 = switch (self.pk_type) {
  1348. .number => "*",
  1349. .uuid => "@",
  1350. .string => "",
  1351. };
  1352. try self.appendFmt(out, "\"primaryKey\":\"{s}{s}\"", .{ prefix, p });
  1353. first = false;
  1354. }
  1355. if (!first) try self.appendFmt(out, ",", .{});
  1356. try self.appendFmt(out, "\"indexes\":[", .{});
  1357. var n: usize = 0;
  1358. for (self.index_fields.items) |field| {
  1359. if (self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;
  1360. if (n > 0) try self.appendFmt(out, ",", .{});
  1361. const uni = for (self.unique_fields.items) |u| {
  1362. if (std.mem.eql(u8, u, field)) break true;
  1363. } else false;
  1364. const numeric = (self.idx.get(field) orelse FieldIndex{ .typ = .lexical }).typ == .numeric;
  1365. try self.appendFmt(out, "\"{s}{s}{s}\"", .{
  1366. if (uni) "!" else "",
  1367. if (numeric) "*" else "",
  1368. field,
  1369. });
  1370. n += 1;
  1371. }
  1372. try self.appendFmt(out, "]}}", .{});
  1373. }
  1374. if (self.bind_known) {
  1375. var sum_buf: [16]u8 = undefined;
  1376. try self.appendFmt(out, ",\"dataFile\":{{\"ino\":{d},\"size\":{d},\"gen\":{d},\"deletedSum\":\"{s}\"", .{ self.bind_ino, self.bind_size, self.data_gen, self.deletedSum(&sum_buf) });
  1377. if (self.bind_fp_len > 0) try self.appendFmt(out, ",\"fp\":\"{s}\"", .{self.bind_fp[0..self.bind_fp_len]});
  1378. try self.appendFmt(out, "}}", .{});
  1379. }
  1380. try self.appendFmt(out, "}}", .{});
  1381. }
  1382. // =====================================================================
  1383. // Data file scanning
  1384. // =====================================================================
  1385. fn deletedSet(self: *Db, alloc: std.mem.Allocator) std.AutoHashMapUnmanaged(u64, void) {
  1386. var set: std.AutoHashMapUnmanaged(u64, void) = .empty;
  1387. for (self.deleted.items) |off| set.put(alloc, off, {}) catch {};
  1388. return set;
  1389. }
  1390. /// The cached tombstone set, built on first use (borrowed: valid until the next
  1391. /// delete / meta adoption / compaction; hold it with delSetAcquire to keep it).
  1392. fn delSetCached(self: *Db) *DelSet {
  1393. if (self.del_cache) |c| return c;
  1394. const c = self.tmp.create(DelSet) catch unreachable;
  1395. c.* = .{ .alloc = self.tmp };
  1396. c.map.ensureTotalCapacity(self.tmp, @intCast(self.deleted.items.len)) catch {};
  1397. for (self.deleted.items) |off| c.map.put(self.tmp, off, {}) catch {};
  1398. self.del_cache = c;
  1399. return c;
  1400. }
  1401. /// A reference the caller must release() — a frozen view of the tombstones.
  1402. pub fn delSetAcquire(self: *Db) *DelSet {
  1403. const c = self.delSetCached();
  1404. c.refs += 1;
  1405. return c;
  1406. }
  1407. fn delCacheDrop(self: *Db) void {
  1408. if (self.del_cache) |c| c.release();
  1409. self.del_cache = null;
  1410. }
  1411. fn delCacheAdd(self: *Db, off: u64) void {
  1412. const c = self.del_cache orelse return;
  1413. if (c.refs > 1) {
  1414. // a cursor holds this set: it keeps it unchanged, the Db goes on with a copy
  1415. const n = self.tmp.create(DelSet) catch {
  1416. self.delCacheDrop();
  1417. return;
  1418. };
  1419. n.* = .{ .alloc = self.tmp };
  1420. n.map = c.map.clone(self.tmp) catch {
  1421. self.tmp.destroy(n);
  1422. self.delCacheDrop();
  1423. return;
  1424. };
  1425. c.release();
  1426. self.del_cache = n;
  1427. }
  1428. self.del_cache.?.map.put(self.tmp, off, {}) catch self.delCacheDrop();
  1429. }
  1430. /// Sequential scan yielding all live records. Caller supplies an arena for
  1431. /// decoded values. Used for rebuilds, compaction and unindexed finds.
  1432. pub const Scanner = struct {
  1433. db: *Db,
  1434. fd: i32 = -1,
  1435. offset: u64 = 0,
  1436. size: u64 = 0,
  1437. skip_deleted: bool = true,
  1438. owns_fd: bool = true,
  1439. /// a detached scanner's reference to the data file generation (instead of a dup)
  1440. gen: ?*DataGen = null,
  1441. /// a frozen view of the tombstones (null when !skip_deleted); released by deinit
  1442. deleted_set: ?*DelSet = null,
  1443. scratch: std.mem.Allocator,
  1444. pub fn init(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool) Scanner {
  1445. return initOpt(db, scratch, skip_deleted, false);
  1446. }
  1447. /// `detached` (a streaming cursor): the scanner holds a reference to the data file generation (no dup), so a compaction
  1448. /// or a foreign rewrite that makes the Db move to a new file leaves the scan reading
  1449. /// the file it started on; it also freezes the size and the tombstones (mission 393).
  1450. pub fn initOpt(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool, detached: bool) Scanner {
  1451. var s = Scanner{ .db = db, .scratch = scratch, .skip_deleted = skip_deleted };
  1452. if (db.data_fd >= 0) {
  1453. // the file the handle's offsets are into (#176), not whatever is at the path
  1454. if (detached) {
  1455. if (db.fd_gen) |g| {
  1456. s.gen = g.retain();
  1457. s.fd = g.fd;
  1458. s.owns_fd = false;
  1459. } else {
  1460. s.fd = db.data_fd;
  1461. s.owns_fd = false;
  1462. }
  1463. } else {
  1464. s.fd = db.data_fd;
  1465. s.owns_fd = false;
  1466. }
  1467. s.size = if (fio.fdStat(s.fd)) |st| st.size else 0;
  1468. } else {
  1469. s.size = fio.fileSize(scratch, db.data_path) orelse 0;
  1470. if (s.size > 0) {
  1471. s.fd = fio.openRead(scratch, db.data_path) orelse -1;
  1472. }
  1473. }
  1474. if (skip_deleted) s.deleted_set = db.delSetAcquire();
  1475. return s;
  1476. }
  1477. pub fn deinit(self: *Scanner) void {
  1478. if (self.gen) |g| g.release();
  1479. self.gen = null;
  1480. if (self.fd >= 0 and self.owns_fd) fio.close(self.fd);
  1481. self.fd = -1;
  1482. if (self.deleted_set) |d| d.release();
  1483. self.deleted_set = null;
  1484. }
  1485. /// Returns the next record (decoded into `arena`) or null at EOF.
  1486. pub fn next(self: *Scanner, arena: std.mem.Allocator) Error!?Record {
  1487. while (true) {
  1488. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1489. var hdr: [4]u8 = undefined;
  1490. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1491. if (got < 4) return null;
  1492. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1493. if (rec_size <= 4) return Error.CorruptRecord;
  1494. if (self.offset + rec_size > self.size) return null; // incomplete tail
  1495. const off = self.offset;
  1496. self.offset += rec_size;
  1497. if (self.deleted_set) |d| {
  1498. if (d.map.contains(off)) continue;
  1499. }
  1500. const buf = arena.alloc(u8, rec_size - 4) catch return Error.OutOfMemory;
  1501. const got2 = fio.pread(self.fd, buf, off + 4) orelse return Error.IoError;
  1502. if (got2 < rec_size - 4) return Error.Truncated;
  1503. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1504. return Record{ .value = d.value, .off = off, .len = rec_size };
  1505. }
  1506. }
  1507. /// The number of live records from here on, reading only the 4-byte frame headers:
  1508. /// nothing is decoded or kept (count() decoded the whole table into an arena, 2 GB
  1509. /// for the tracker's two big tables).
  1510. pub fn countLive(self: *Scanner) Error!usize {
  1511. var n: usize = 0;
  1512. while (true) {
  1513. if (self.fd < 0 or self.offset + 4 > self.size) return n;
  1514. var hdr: [4]u8 = undefined;
  1515. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1516. if (got < 4) return n;
  1517. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1518. if (rec_size <= 4) return Error.CorruptRecord;
  1519. if (self.offset + rec_size > self.size) return n;
  1520. const off = self.offset;
  1521. self.offset += rec_size;
  1522. if (self.deleted_set) |d| {
  1523. if (d.map.contains(off)) continue;
  1524. }
  1525. n += 1;
  1526. }
  1527. }
  1528. /// Like next() but without decoding — yields the raw framed bytes.
  1529. pub fn nextRaw(self: *Scanner, arena: std.mem.Allocator) Error!?struct { bytes: []u8, off: u64 } {
  1530. while (true) {
  1531. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1532. var hdr: [4]u8 = undefined;
  1533. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1534. if (got < 4) return null;
  1535. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1536. if (rec_size <= 4) return Error.CorruptRecord;
  1537. if (self.offset + rec_size > self.size) return null;
  1538. const off = self.offset;
  1539. self.offset += rec_size;
  1540. if (self.deleted_set) |d| {
  1541. if (d.map.contains(off)) continue;
  1542. }
  1543. const buf = arena.alloc(u8, rec_size) catch return Error.OutOfMemory;
  1544. const got2 = fio.pread(self.fd, buf, off) orelse return Error.IoError;
  1545. if (got2 < rec_size) return Error.Truncated;
  1546. return .{ .bytes = buf, .off = off };
  1547. }
  1548. }
  1549. };
  1550. /// A reference to the data file the offsets are into, for a streaming cursor (null: none).
  1551. /// Release it with `DataGen.release`; the fd (`.fd`) stays valid until then.
  1552. pub fn retainDataGen(self: *Db) ?*DataGen {
  1553. const g = self.fd_gen orelse return null;
  1554. return g.retain();
  1555. }
  1556. /// Read + decode one record by location from `fd` (a dupDataFd of the file the loc is into).
  1557. pub fn readAtFd(fd: i32, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1558. if (loc.len <= 4) return Error.CorruptRecord;
  1559. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1560. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1561. if (got < buf.len) return Error.Truncated;
  1562. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1563. return d.value;
  1564. }
  1565. /// Read + decode one record by location.
  1566. pub fn readAt(self: *Db, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1567. const own = self.data_fd < 0;
  1568. const fd = if (own) (fio.openRead(self.tmp, self.data_path) orelse return Error.IoError) else self.data_fd;
  1569. defer if (own) fio.close(fd);
  1570. if (loc.len <= 4) return Error.CorruptRecord;
  1571. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1572. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1573. if (got < buf.len) return Error.Truncated;
  1574. const d = msgpack.decode(arena, buf) catch return Error.CorruptRecord;
  1575. return d.value;
  1576. }
  1577. // =====================================================================
  1578. // Index management
  1579. // =====================================================================
  1580. fn keyFromValue(v: msgpack.Value) ?Key {
  1581. return switch (v) {
  1582. .number => |n| Key{ .num = n },
  1583. .str => |s| Key{ .str = s },
  1584. else => null, // null/bool/objects are not indexed (see header note)
  1585. };
  1586. }
  1587. /// Duplicate a key's string into the db arena so it outlives the op arena.
  1588. fn ownKey(self: *Db, k: Key) Error!Key {
  1589. return switch (k) {
  1590. .num => k,
  1591. .str => |s| Key{ .str = (if (self.bulk_keys) |ka| ka.allocator() else self.alloc).dupe(u8, s) catch return Error.OutOfMemory },
  1592. };
  1593. }
  1594. /// Copy every string key of every index into one run of memory, in the lists' order.
  1595. fn packKeys(self: *Db) void {
  1596. for (self.idx.values()) |*fi| {
  1597. var total: usize = 0;
  1598. for (fi.entries.items) |e| {
  1599. if (e.key == .str) total += e.key.str.len;
  1600. }
  1601. if (total == 0) continue;
  1602. const slab = self.alloc.alloc(u8, total) catch continue;
  1603. var pos: usize = 0;
  1604. for (fi.entries.items) |*e| {
  1605. if (e.key == .str) {
  1606. const k = e.key.str;
  1607. @memcpy(slab[pos..][0..k.len], k);
  1608. e.key = .{ .str = slab[pos..][0..k.len] };
  1609. pos += k.len;
  1610. }
  1611. }
  1612. }
  1613. }
  1614. fn lowerBound(entries: []const Entry, key: Key) usize {
  1615. var lo: usize = 0;
  1616. var hi: usize = entries.len;
  1617. while (lo < hi) {
  1618. const mid = lo + (hi - lo) / 2;
  1619. if (cmpKeys(entries[mid].key, key) < 0) {
  1620. lo = mid + 1;
  1621. } else {
  1622. hi = mid;
  1623. }
  1624. }
  1625. return lo;
  1626. }
  1627. /// Binary search: all entries whose key equals `key` (appended to `out`).
  1628. pub fn indexGet(self: *Db, field: []const u8, key: Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1629. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1630. const parsed = self.parseKeyForField(field, key);
  1631. const entries = fi.entries.items;
  1632. var i = lowerBound(entries, parsed);
  1633. while (i < entries.len and cmpKeys(entries[i].key, parsed) == 0) : (i += 1) {
  1634. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1635. }
  1636. }
  1637. /// Range scan [from, to] (either side optional), ascending.
  1638. pub fn indexRange(self: *Db, field: []const u8, from: ?Key, to: ?Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1639. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1640. const entries = fi.entries.items;
  1641. var i: usize = if (from) |f| lowerBound(entries, self.parseKeyForField(field, f)) else 0;
  1642. const to_key: ?Key = if (to) |t| self.parseKeyForField(field, t) else null;
  1643. while (i < entries.len) : (i += 1) {
  1644. if (to_key) |t| {
  1645. if (cmpKeys(entries[i].key, t) > 0) break;
  1646. }
  1647. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1648. }
  1649. }
  1650. /// _parseKey semantics: numeric index fields parse string keys via
  1651. /// parseInt; on NaN the key stays a string.
  1652. fn parseKeyForField(self: *Db, field: []const u8, key: Key) Key {
  1653. const fi = self.idx.get(field) orelse return key;
  1654. if (fi.typ == .numeric and key == .str) {
  1655. if (jsParseInt(key.str)) |n| return Key{ .num = n };
  1656. }
  1657. return key;
  1658. }
  1659. fn indexInsertEntry(self: *Db, field: []const u8, key: Key, loc: Loc) Error!void {
  1660. const fi = self.idx.getPtr(field) orelse return;
  1661. const owned = try self.ownKey(key);
  1662. const e = Entry{ .key = owned, .off = loc.off, .len = loc.len };
  1663. // a bulk scan (rebuild / big catch-up) appends and sorts once at the end: a sorted
  1664. // insert per record is a memmove of the whole list each time — quadratic (#376)
  1665. if (self.bulk_index) {
  1666. fi.entries.append(self.alloc, e) catch return Error.OutOfMemory;
  1667. return;
  1668. }
  1669. // insert at sorted position
  1670. const pos = blk: {
  1671. var lo: usize = 0;
  1672. var hi: usize = fi.entries.items.len;
  1673. while (lo < hi) {
  1674. const mid = lo + (hi - lo) / 2;
  1675. if (entryLess({}, fi.entries.items[mid], e)) {
  1676. lo = mid + 1;
  1677. } else {
  1678. hi = mid;
  1679. }
  1680. }
  1681. break :blk lo;
  1682. };
  1683. fi.entries.insert(self.alloc, pos, e) catch return Error.OutOfMemory;
  1684. }
  1685. /// Index a record's fields at loc.
  1686. fn indexInsertRecord(self: *Db, rec: msgpack.Value, loc: Loc) Error!void {
  1687. for (self.index_fields.items) |field| {
  1688. const v = rec.get(field) orelse continue;
  1689. const key = keyFromValue(v) orelse continue;
  1690. try self.indexInsertEntry(field, key, loc);
  1691. }
  1692. self.covered_bytes = @max(self.covered_bytes, loc.off + loc.len);
  1693. }
  1694. /// Remove all entries pointing at offset `off` (all fields).
  1695. fn indexRemoveOffset(self: *Db, off: u64) void {
  1696. var it = self.idx.iterator();
  1697. while (it.next()) |kv| {
  1698. const list = &kv.value_ptr.entries;
  1699. var i: usize = 0;
  1700. while (i < list.items.len) {
  1701. if (list.items[i].off == off) {
  1702. _ = list.orderedRemove(i);
  1703. } else {
  1704. i += 1;
  1705. }
  1706. }
  1707. }
  1708. }
  1709. fn indexPath(self: *Db, buf: []u8, field: []const u8) []const u8 {
  1710. // <dir>/<base>.<field>.txt — derive from idxstate path (…/base.idxstate.json)
  1711. const prefix = self.idxstate_path[0 .. self.idxstate_path.len - "idxstate.json".len];
  1712. return std.fmt.bufPrint(buf, "{s}{s}.txt", .{ prefix, field }) catch buf[0..0];
  1713. }
  1714. fn initIndexes(self: *Db, force_rebuild: bool) Error!void {
  1715. var need_rebuild = force_rebuild;
  1716. const data_size = fio.fileSize(self.tmp, self.data_path) orelse 0;
  1717. if (!need_rebuild) {
  1718. for (self.index_fields.items) |field| {
  1719. var pbuf: [512]u8 = undefined;
  1720. const p = self.indexPath(&pbuf, field);
  1721. const isize_ = fio.fileSize(self.tmp, p);
  1722. if (isize_ == null or isize_.? == 0) {
  1723. if (data_size > 0) {
  1724. need_rebuild = true;
  1725. break;
  1726. }
  1727. }
  1728. }
  1729. }
  1730. if (!need_rebuild) {
  1731. // coveredBytes from idxstate — no state file means rebuild (JS). An
  1732. // idxstate of another data file (its inode, or more bytes covered
  1733. // than there are) means the index files are another file's too:
  1734. // a crash between a compaction's rename and its rebuild (#176).
  1735. if (self.readIdxState()) |st| {
  1736. self.covered_bytes = st.covered;
  1737. const cur = fio.stat(self.tmp, self.data_path);
  1738. const cur_ino: u64 = if (cur) |c| c.ino else 0;
  1739. if (st.covered > data_size) need_rebuild = true;
  1740. if (st.fmt < idx_format) need_rebuild = true;
  1741. if (st.ino) |i| {
  1742. self.idx_bind_known = true;
  1743. // another inode: a byte COPY of the store (ticket 387) has the same
  1744. // content over the covered bytes, so its index files are right
  1745. if (i != cur_ino) {
  1746. var fpb: [16]u8 = undefined;
  1747. const same = st.has_fp and st.covered <= data_size and
  1748. if (self.dataFingerprint(st.covered, &fpb)) |f| std.mem.eql(u8, f, &st.fp) else false;
  1749. if (!same) need_rebuild = true;
  1750. }
  1751. }
  1752. } else {
  1753. need_rebuild = true;
  1754. }
  1755. }
  1756. if (need_rebuild) {
  1757. try self.rebuildIndexes();
  1758. return;
  1759. }
  1760. // Load index files into memory
  1761. for (self.index_fields.items) |field| {
  1762. var pbuf: [512]u8 = undefined;
  1763. const p = self.indexPath(&pbuf, field);
  1764. // the keys point INTO the file's bytes (mission 436: one allocation + copy per key
  1765. // was most of the load); a numeric index keeps no key text, so its buffer goes back
  1766. const numeric = (self.idx.get(field) orelse continue).typ == .numeric;
  1767. const content = fio.readAll(if (numeric) self.tmp else self.alloc, p) orelse continue;
  1768. var keep = false;
  1769. self.loadIndexLines(field, content, &keep);
  1770. if (numeric and !keep) self.tmp.free(content);
  1771. }
  1772. // sort (files are sorted by JS localeCompare; re-sort under our order). A file we wrote
  1773. // is in our order already: checking is a pass, pdq with a key compare per step is more.
  1774. var it = self.idx.iterator();
  1775. while (it.next()) |kv| {
  1776. const items = kv.value_ptr.entries.items;
  1777. if (!std.sort.isSorted(Entry, items, {}, entryLess)) sortEntries(self.tmp, items);
  1778. }
  1779. if (data_size > self.covered_bytes) self.catchUp(data_size);
  1780. }
  1781. /// parseInt(u64, s, 10) with a loop for the plain all-digits case.
  1782. fn parseU64(s: []const u8) ?u64 {
  1783. if (s.len == 0 or s.len > 19) return std.fmt.parseInt(u64, s, 10) catch null;
  1784. var v: u64 = 0;
  1785. for (s) |c| {
  1786. if (c < '0' or c > '9') return std.fmt.parseInt(u64, s, 10) catch null;
  1787. v = v * 10 + (c - '0');
  1788. }
  1789. return v;
  1790. }
  1791. /// `content` must outlive the entries when `keep` is set: string keys are slices of it.
  1792. fn loadIndexLines(self: *Db, field: []const u8, content: []const u8, keep: *bool) void {
  1793. const fi = self.idx.getPtr(field) orelse return;
  1794. // sizing: the first line's length says how many lines to expect
  1795. const nl_first = std.mem.indexOfScalar(u8, content, '\n') orelse content.len;
  1796. fi.entries.ensureUnusedCapacity(self.alloc, content.len / @max(nl_first + 1, 8) + 16) catch {};
  1797. const numeric = fi.typ == .numeric;
  1798. const c = content;
  1799. var pos: usize = 0;
  1800. while (pos < c.len) {
  1801. // one pass over the line: key up to the first comma, then two runs of digits
  1802. const start = pos;
  1803. var i = pos;
  1804. while (i < c.len and c[i] != ',' and c[i] != '\n') i += 1;
  1805. if (i >= c.len or c[i] == '\n') { // no comma: nothing to read (an empty line included)
  1806. pos = i + 1;
  1807. continue;
  1808. }
  1809. const key_end = i;
  1810. i += 1;
  1811. var off: u64 = 0;
  1812. var nd: usize = 0;
  1813. while (i < c.len and c[i] >= '0' and c[i] <= '9') : (i += 1) {
  1814. off = off *% 10 +% (c[i] - '0');
  1815. nd += 1;
  1816. }
  1817. var fast = nd >= 1 and nd <= 19 and i < c.len and c[i] == ',';
  1818. var len: u64 = 0;
  1819. if (fast) {
  1820. i += 1;
  1821. nd = 0;
  1822. while (i < c.len and c[i] >= '0' and c[i] <= '9') : (i += 1) {
  1823. len = len *% 10 +% (c[i] - '0');
  1824. nd += 1;
  1825. }
  1826. fast = nd >= 1 and nd <= 19 and (i >= c.len or c[i] == '\n');
  1827. }
  1828. if (c[start] == '"') fast = false; // a quoted key: the careful reading
  1829. if (!fast) {
  1830. // anything unusual: the careful reading of the whole line
  1831. const end = std.mem.indexOfScalarPos(u8, c, start, '\n') orelse c.len;
  1832. self.loadIndexLineSlow(fi, c[start..end], numeric, keep);
  1833. pos = end + 1;
  1834. continue;
  1835. }
  1836. pos = i + 1;
  1837. if (len == 0) continue;
  1838. const key_s = c[start..key_end];
  1839. var key: Key = undefined;
  1840. if (numeric) {
  1841. key = if (jsParseInt(key_s)) |n| Key{ .num = n } else Key{ .str = key_s };
  1842. if (key == .str) keep.* = true;
  1843. } else {
  1844. key = Key{ .str = key_s };
  1845. keep.* = true;
  1846. }
  1847. fi.entries.append(self.alloc, .{ .key = key, .off = off, .len = len }) catch return;
  1848. }
  1849. }
  1850. /// The reading of one index line (odd digits, signs, a long number, a comma in the key, a
  1851. /// quoted key). A line that starts with a double quote holds a JSON string, then ",off,len".
  1852. /// Any other line is split from the RIGHT: the last two parts are offset and length, all
  1853. /// before them is the key (mission 486).
  1854. fn loadIndexLineSlow(self: *Db, fi: *FieldIndex, line: []const u8, numeric: bool, keep: *bool) void {

Only the first lines are shown.

Branches

Latest commits

  • f04afc43tickets: MdEditor from components 59704ce (a file manager copy still attaches, pipe rows, tickets#49)mre
  • 06599fa0tickets: MdEditor from components b0f1ec2 (a clipboard with text always pastes the text, tickets#49); real Ctrl+V gatemre
  • 2e1b116ftickets: re-vendor Hybriel master acaceaf3 (framework ec8d6c1d): plugins/web patch queue while a page is built, anonymous session cookies refresh; gate waits for the comment editors to draw (W174) and clicks the form editor when it stands still; security gate: main's code runs on its own binary, lazy-session cookie checksmre
  • 361bc0fetickets: re-vendor Hybriel 7a684920 (WIP, not deployed); on Error exits 1 at startup; migrate passes its log by reference; gate checks follow lazy sessions and the 413 refusalmre
  • 8a69999cident#28: /login/callback never signs out the session it finds; a valid code puts the user on the same sessionmre
  • 337e9b21tickets#37: a comment's files are open to everyone who can read the commentmre
  • 1800600ftickets: write the standby service out in full so the boot gate can read the main servicemre
  • 8179d287tickets: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
  • 0398145ctickets: the table grid rule is marked functional for check-thememre
  • 40fddc20tickets takes components e54f83a: tables get thin grey lines from the theme, desktop toolbar stays one row with the Table button, F4 check counts 11 buttonsmre
  • c1b77d61tickets#35: text typed before the editor is built is taken in once by the build (the input handler no longer writes it to the field first, which doubled the first letters); the gate failure shows the surfacemre
  • 32bf1873tickets#35: the gate types right after the load with the CPU slowed, no waitingmre
  • 64ea9ca2tickets#35: text typed into the reply editor before the page has finished starting is kept; the gate types right after loadmre
  • ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmre
  • 4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • 66ef3005Merge branch 'iw-ident-widget'mre
  • bc0ad663tickets: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 2f818d46UX2: report, LOG line, e2e fixes, gate pause after loadmre
  • af3ef7c4gate: the legacy state line says progressmre
  • 62480a00tickets#33: a state change with a note is a comment card in the feed (same framework rendering, can be liked, edited, deleted), its state line stands alone; gate checks for a new comment with and without a state change, at once and after a reloadmre