gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchf15-navigate3b3e451f|||PR ident#36 navigate to the app instead of location.assignmref15-navigate/plugins/mpackdb/engine.zig

208.0 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, fields: {field: coveredBytes}, idxFmt: 2, dataIno?, dataFp? }
  8. // <base>.lock lock file containing the holder's pid (O_EXCL protocol,
  9. // dead-pid takeover or 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. // Held until unlink on release; also serializes stale-file inspection/removal.
  556. lock_fd: i32 = -1,
  557. // schema
  558. pk: ?[]const u8 = null,
  559. pk_type: PkType = .string,
  560. index_fields: std.ArrayList([]const u8) = .empty, // pk first (when set), like JS
  561. unique_fields: std.ArrayList([]const u8) = .empty,
  562. idx: std.StringArrayHashMapUnmanaged(FieldIndex) = .empty,
  563. // meta
  564. next_id: f64 = FIRST_ID,
  565. deleted: std.ArrayList(u64) = .empty,
  566. /// lazily built set of `deleted` (mission 393); null = not built / invalidated
  567. del_cache: ?*DelSet = null,
  568. /// an index entry named a place that is no frame of its size (a stale persisted index):
  569. /// the next refresh() rebuilds every index from the data file (mission 393)
  570. index_bad: bool = false,
  571. index_retry: bool = false,
  572. version: u64 = 0,
  573. // THE META NAMES ITS DATA FILE (ticket #176): `dataFile` in .meta.json is the
  574. // inode and size of the data file it was written for, the compaction
  575. // generation, and a checksum of its own `deleted` list. A meta whose data file
  576. // was replaced under it (a crash between the rename and the meta write) has
  577. // tombstones that point into the WRONG file — they are dropped, not applied.
  578. // The checksum tells our dataFile from one another writer carried along: the
  579. // JS mpackdb rewrites the meta as `{...meta}` and keeps fields it does not
  580. // know, so a `deleted` list it changed no longer matches the sum, and such a
  581. // meta is taken as it is (as before #176).
  582. bind_known: bool = false, // the meta on disk carries a dataFile that is ours and true
  583. bind_ino: u64 = 0,
  584. bind_size: u64 = 0,
  585. bind_fp: [16]u8 = undefined, // content fingerprint of the data file's first `bind_size` bytes
  586. bind_fp_len: u8 = 0, // 0 = none known (an old meta whose data file was not read)
  587. data_gen: u64 = 0,
  588. meta_stale: bool = false, // the loaded meta belonged to another data file
  589. idx_bind_known: bool = false, // the idxstate on disk names the data file's inode
  590. // the data file this handle's offsets are into (ticket #176): its inode and
  591. // the compaction generation; refresh() compares them on every operation
  592. seen_ino: u64 = 0,
  593. // THE FILE THE OFFSETS ARE INTO, held open (ticket #176): every read and scan
  594. // goes through it, never through the path — a rewrite renamed in between a
  595. // lookup and its read (the tracker parsed 1.4 MB of meta between the two)
  596. // then still reads the file the offsets belong to, and the next refresh()
  597. // moves the handle to the new one.
  598. data_fd: i32 = -1,
  599. // fd403: the refcounted holder of data_fd. A streaming cursor takes a reference to the
  600. // generation it started on instead of dup()ing the fd (a dup per query held thousands of
  601. // fds until the GC finalized abandoned cursors: > 1024 at the tracker's boot). The fd is
  602. // closed when the Db has moved on (compaction, close) AND the last cursor is gone.
  603. fd_gen: ?*DataGen = null,
  604. // The meta file as THIS handle last read or wrote it (ticket #188): it is only ever
  605. // replaced by tmp + rename, so a write changes its inode; refresh() stats it and
  606. // skips the read + parse of a (1.4 MB on the tracker) meta that is unchanged.
  607. meta_seen: ?fio.Stat = null,
  608. meta_reads: u64 = 0, // reads of the meta file by loadMeta/refresh (the test counts them)
  609. bulk_index: bool = false, // indexInsertEntry appends (a sorted pass follows): rebuild / long catch-up
  610. /// keys of a rebuild live here until the sort has put the entries in order; then they are
  611. /// copied side by side in that order (a rebuilt index is read in sorted order, again and
  612. /// again: written, compared, searched) and this arena is freed (mission 436)
  613. bulk_keys: ?*std.heap.ArenaAllocator = null,
  614. covered_bytes: u64 = 0,
  615. compact_on_open: bool = true,
  616. stale_lock_timeout_ms: i64 = 30000,
  617. debug: bool = false,
  618. // last DuplicateKey detail for the plugin surface
  619. last_error_buf: [256]u8 = undefined,
  620. last_error: []const u8 = "",
  621. pub fn open(gpa: std.mem.Allocator, db_file: []const u8, opts: OpenOptions) Error!*Db {
  622. if (db_file.len == 0) return Error.NoDbFile;
  623. const self = gpa.create(Db) catch return Error.OutOfMemory;
  624. self.* = .{
  625. .arena_state = std.heap.ArenaAllocator.init(gpa),
  626. .alloc = undefined,
  627. .tmp = gpa,
  628. .data_path = undefined,
  629. .meta_path = undefined,
  630. .lock_path = undefined,
  631. .idxstate_path = undefined,
  632. };
  633. self.alloc = self.arena_state.allocator();
  634. errdefer {
  635. self.arena_state.deinit();
  636. gpa.destroy(self);
  637. }
  638. const a = self.alloc;
  639. self.compact_on_open = opts.compact;
  640. self.stale_lock_timeout_ms = opts.stale_lock_timeout_ms;
  641. self.debug = opts.debug;
  642. // dirname / basename (extension stripped, like JS basename(f, extname(f)))
  643. const dir = std.fs.path.dirname(db_file) orelse ".";
  644. var base = std.fs.path.basename(db_file);
  645. if (std.mem.lastIndexOfScalar(u8, base, '.')) |dot| {
  646. if (dot > 0) base = base[0..dot];
  647. }
  648. fio.mkdirAll(a, dir);
  649. self.data_path = std.fmt.allocPrint(a, "{s}/{s}.mpack", .{ dir, base }) catch return Error.OutOfMemory;
  650. self.meta_path = std.fmt.allocPrint(a, "{s}/{s}.meta.json", .{ dir, base }) catch return Error.OutOfMemory;
  651. self.lock_path = std.fmt.allocPrint(a, "{s}/{s}.lock", .{ dir, base }) catch return Error.OutOfMemory;
  652. self.idxstate_path = std.fmt.allocPrint(a, "{s}/{s}.idxstate.json", .{ dir, base }) catch return Error.OutOfMemory;
  653. self.flock_path = std.fmt.allocPrint(a, "{s}/{s}.flock", .{ dir, base }) catch return Error.OutOfMemory;
  654. try self.openStoreLock();
  655. errdefer self.closeStoreLock();
  656. // ---- parse primary key ----
  657. if (opts.primary_key) |pk_raw| {
  658. if (pk_raw.len > 0) {
  659. if (pk_raw[0] == '*') {
  660. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  661. self.pk_type = .number;
  662. } else if (pk_raw[0] == '@') {
  663. self.pk = a.dupe(u8, pk_raw[1..]) catch return Error.OutOfMemory;
  664. self.pk_type = .uuid;
  665. } else {
  666. self.pk = a.dupe(u8, pk_raw) catch return Error.OutOfMemory;
  667. self.pk_type = .string;
  668. }
  669. }
  670. }
  671. if (self.pk) |p| self.unique_fields.append(a, p) catch return Error.OutOfMemory;
  672. // ---- parse indexes (pk first, then configured; dedupe) ----
  673. if (self.pk) |p| {
  674. self.index_fields.append(a, p) catch return Error.OutOfMemory;
  675. const t: IdxType = if (self.pk_type == .number) .numeric else .lexical;
  676. self.idx.put(a, p, .{ .typ = t }) catch return Error.OutOfMemory;
  677. }
  678. for (opts.indexes) |raw| {
  679. var clean = raw;
  680. var is_unique = false;
  681. if (clean.len > 0 and clean[0] == '!') {
  682. is_unique = true;
  683. clean = clean[1..];
  684. }
  685. var typ: IdxType = .lexical;
  686. if (clean.len > 0 and clean[0] == '*') {
  687. typ = .numeric;
  688. clean = clean[1..];
  689. } else if (clean.len > 0 and clean[0] == '@') {
  690. clean = clean[1..];
  691. }
  692. if (self.idx.contains(clean)) continue;
  693. const owned = a.dupe(u8, clean) catch return Error.OutOfMemory;
  694. self.index_fields.append(a, owned) catch return Error.OutOfMemory;
  695. self.idx.put(a, owned, .{ .typ = typ }) catch return Error.OutOfMemory;
  696. if (is_unique) self.unique_fields.append(a, owned) catch return Error.OutOfMemory;
  697. }
  698. // ---- load meta ----
  699. self.loadMeta();
  700. // ---- compact on init (JS default; also creates an empty data file) ----
  701. // AN OPEN WITH NOTHING TO CHANGE WRITES NOTHING (ticket #21): a store
  702. // with no tombstones has nothing to compact, and rewriting it anyway
  703. // made opening a backup change it.
  704. var did_compact = false;
  705. const nothing_to_compact = self.deleted.items.len == 0 and
  706. fio.fileSize(self.tmp, self.data_path) != null;
  707. if (self.compact_on_open and !nothing_to_compact) {
  708. try self.acquireLock();
  709. const cr = if (self.tryExclusive()) blk: {
  710. defer self.backToShared();
  711. break :blk self.compactLocked();
  712. } else self.skipCompaction();
  713. self.releaseLock();
  714. // A REFUSED compaction does not fail the open (ticket #176): nothing
  715. // was rewritten, the store is as it was, and it stays readable; the
  716. // refusal is on stderr and in last_error.
  717. if (cr) |ran| {
  718. did_compact = ran;
  719. } else |e| {
  720. if (e != Error.CompactRefused) return e;
  721. }
  722. }
  723. self.adoptDataFile();
  724. errdefer self.dropDataFile();
  725. // ---- persist schema into meta (JS: init-schema under lock).
  726. // compactLocked already wrote meta (with schema); skip the extra bump.
  727. // A meta found to belong to another data file is replaced at once, so a
  728. // stale one never outlives the open that saw it (ticket #176).
  729. if (!did_compact and (self.meta_stale or ((self.pk != null or self.index_fields.items.len > 0) and
  730. !self.metaOnDiskIsCurrent())))
  731. {
  732. try self.acquireLock();
  733. // Opening read metadata before taking the mutation lock. Another
  734. // writer may have replaced rows since then: never publish our old
  735. // tombstones/version over its committed state. Indexes initialize below,
  736. // so reload metadata alone rather than catching up empty indexes.
  737. self.loadMeta();
  738. const mr = if (self.meta_stale or !self.metaOnDiskIsCurrent()) self.persistMetaLocked() else {};
  739. self.releaseLock();
  740. try mr;
  741. }
  742. // ---- indexes (JS: (re)build under the lock; force after compaction) ----
  743. if (self.index_fields.items.len > 0) {
  744. try self.acquireLock();
  745. const ir = self.initIndexes(did_compact);
  746. self.releaseLock();
  747. try ir;
  748. }
  749. return self;
  750. }
  751. pub fn close(self: *Db) void {
  752. // persist indexes + idxstate (JS: IndexManager.close → persist under lock)
  753. if (self.index_fields.items.len > 0) {
  754. if (self.acquireLock()) {
  755. // MISSION 395 (#203): the index in memory is of the data file this handle holds. Another
  756. // process (the JS mpackdb, a build before #176: none takes the store lock) may have
  757. // rewritten it since; persisting before looking wrote that old generation's offsets
  758. // as the index files — beside an idxstate that named the NEW file.
  759. self.refresh();
  760. self.persistIndexesLocked() catch {};
  761. self.releaseLock();
  762. } else |_| {}
  763. }
  764. self.dropDataFile();
  765. self.delCacheDrop();
  766. self.closeStoreLock();
  767. const gpa = self.arena_state.child_allocator;
  768. self.arena_state.deinit();
  769. gpa.destroy(self);
  770. }
  771. fn dbg(self: *Db, comptime fmt: []const u8, args: anytype) void {
  772. if (self.debug) std.debug.print("[mpackdb] " ++ fmt ++ "\n", args);
  773. }
  774. // =====================================================================
  775. // Locking (JS _acquireFileLock protocol)
  776. // =====================================================================
  777. /// Inspect only while holding this inode's flock. Recheck the path after
  778. /// taking it: a competing restarter may already have replaced the file.
  779. fn removeStaleLock(self: *Db) bool {
  780. const fd = fio.openz(self.tmp, self.lock_path, .{ .CLOEXEC = true }, 0) orelse return false;
  781. defer fio.close(fd);
  782. if (!fio.flock(fd, fio.LOCK_EX | fio.LOCK_NB)) return false;
  783. const held = fio.fdStat(fd) orelse return false;
  784. const at_path = fio.stat(self.tmp, self.lock_path) orelse return false;
  785. if (held.ino != at_path.ino) return false;
  786. var buf: [32]u8 = undefined;
  787. const n = fio.pread(fd, &buf, 0) orelse 0;
  788. const pid = std.fmt.parseInt(i32, std.mem.trim(u8, buf[0..n], " \t\r\n"), 10) catch 0;
  789. // Positive local PIDs only. EPERM means alive; errors other than ESRCH
  790. // cannot establish death. The legacy age rule remains the fallback.
  791. const dead = pid > 0 and (pid == linux.getpid() or
  792. linux.errno(linux.kill(pid, @enumFromInt(0))) == .SRCH);
  793. const old = self.stale_lock_timeout_ms > 0 and
  794. fio.nowMs() - @divTrunc(held.mtime_ns, 1_000_000) > self.stale_lock_timeout_ms;
  795. return (dead or old) and fio.unlink(self.tmp, self.lock_path);
  796. }
  797. fn acquireLock(self: *Db) Error!void {
  798. var retries: u32 = 0;
  799. while (true) {
  800. if (fio.openz(self.tmp, self.lock_path, .{
  801. .ACCMODE = .WRONLY,
  802. .CREAT = true,
  803. .EXCL = true,
  804. .CLOEXEC = true,
  805. }, 0o644)) |fd| {
  806. // Empty fresh files are not reclaimed while we publish the pid.
  807. // A taker can briefly flock this inode first; verify its path too.
  808. if (!fio.flock(fd, fio.LOCK_EX)) {
  809. fio.close(fd);
  810. return Error.IoError;
  811. }
  812. const held = fio.fdIno(fd);
  813. const at_path = fio.stat(self.tmp, self.lock_path);
  814. if (held == null or at_path == null or held.? != at_path.?.ino) {
  815. fio.close(fd);
  816. continue;
  817. }
  818. var pid_buf: [16]u8 = undefined;
  819. const pid_s = std.fmt.bufPrint(&pid_buf, "{d}", .{linux.getpid()}) catch unreachable;
  820. if (!fio.writeAll(fd, pid_s)) {
  821. _ = fio.unlink(self.tmp, self.lock_path);
  822. fio.close(fd);
  823. return Error.IoError;
  824. }
  825. self.lock_fd = fd;
  826. return;
  827. }
  828. if (self.removeStaleLock()) continue;
  829. if (retries > 480) return Error.LockTimeout; // ~12s at 25ms
  830. fio.sleepMs(25);
  831. retries += 1;
  832. }
  833. }
  834. fn releaseLock(self: *Db) void {
  835. if (self.lock_fd < 0) return;
  836. _ = fio.unlink(self.tmp, self.lock_path);
  837. fio.close(self.lock_fd);
  838. self.lock_fd = -1;
  839. }
  840. /// Take the shared store lock. The lock file is unlinked by the last handle
  841. /// to close (under the exclusive lock), so a lock taken on a file that is no
  842. /// longer the one at the path is let go and taken anew.
  843. fn openStoreLock(self: *Db) Error!void {
  844. var tries: usize = 0;
  845. while (tries < 1000) : (tries += 1) {
  846. const fd = fio.openz(self.tmp, self.flock_path, .{ .ACCMODE = .RDWR, .CREAT = true, .CLOEXEC = true }, 0o644) orelse return Error.IoError;
  847. if (!fio.flock(fd, fio.LOCK_SH)) {
  848. fio.close(fd);
  849. return Error.IoError;
  850. }
  851. const held = fio.fdIno(fd);
  852. const at_path = fio.stat(self.tmp, self.flock_path);
  853. if (held != null and at_path != null and held.? == at_path.?.ino) {
  854. self.store_fd = fd;
  855. return;
  856. }
  857. fio.close(fd);
  858. }
  859. return Error.LockTimeout;
  860. }
  861. fn closeStoreLock(self: *Db) void {
  862. if (self.store_fd < 0) return;
  863. // the last one out removes the lock file — only while no one else holds it
  864. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) _ = fio.unlink(self.tmp, self.flock_path);
  865. fio.close(self.store_fd);
  866. self.store_fd = -1;
  867. }
  868. /// Exclusive, without waiting: true when no other handle (in any process)
  869. /// holds the store.
  870. fn tryExclusive(self: *Db) bool {
  871. if (self.store_fd < 0) return false;
  872. if (fio.flock(self.store_fd, fio.LOCK_EX | fio.LOCK_NB)) return true;
  873. // a failed conversion may have given up the shared lock: take it again
  874. _ = fio.flock(self.store_fd, fio.LOCK_SH);
  875. return false;
  876. }
  877. fn backToShared(self: *Db) void {
  878. if (self.store_fd >= 0) _ = fio.flock(self.store_fd, fio.LOCK_SH);
  879. }
  880. fn skipCompaction(self: *Db) Error!bool {
  881. self.last_error = "compaction skipped: the store is open in another process";
  882. self.dbg("{s}: {s}", .{ self.data_path, self.last_error });
  883. return false;
  884. }
  885. // =====================================================================
  886. // Meta (.meta.json)
  887. // =====================================================================
  888. fn appendFmt(self: *Db, list: *std.ArrayList(u8), comptime fmt: []const u8, args: anytype) Error!void {
  889. // a short piece is formatted on the stack (mission 436: one heap allocation per
  890. // tombstone / index line made rendering a 3 MB meta cost more than parsing it)
  891. var sbuf: [256]u8 = undefined;
  892. if (std.fmt.bufPrint(&sbuf, fmt, args)) |piece| {
  893. list.appendSlice(self.tmp, piece) catch return Error.OutOfMemory;
  894. return;
  895. } else |_| {}
  896. const s = std.fmt.allocPrint(self.tmp, fmt, args) catch return Error.OutOfMemory;
  897. defer self.tmp.free(s);
  898. list.appendSlice(self.tmp, s) catch return Error.OutOfMemory;
  899. }
  900. fn loadMeta(self: *Db) void {
  901. // stat BEFORE the read: a write racing in between then shows as a change next time
  902. self.meta_seen = fio.stat(self.tmp, self.meta_path);
  903. self.meta_reads += 1;
  904. const content = fio.readAll(self.tmp, self.meta_path) orelse return;
  905. defer self.tmp.free(content);
  906. self.applyMetaJson(content);
  907. }
  908. /// What applyMetaJson needs of the meta's `dataFile` object.
  909. const DataFileMeta = struct {
  910. ino: ?u64 = null,
  911. size: ?u64 = null,
  912. gen: ?u64 = null,
  913. sum: ?[]const u8 = null, // deletedSum when it is a string
  914. fp_present: bool = false,
  915. fp: ?[]const u8 = null, // fp when it is a string
  916. };
  917. /// A JSON number token the way std.json.Value would hold it: an integer, or a float.
  918. const JNum = union(enum) { int: i64, float: f64 };
  919. fn jnum(text: []const u8) ?JNum {
  920. if (std.mem.indexOfAny(u8, text, ".eE") == null) {
  921. return .{ .int = std.fmt.parseInt(i64, text, 10) catch return null };
  922. }
  923. return .{ .float = std.fmt.parseFloat(f64, text) catch return null };
  924. }
  925. /// MISSION 436: the meta of a big table is megabytes (the tracker's shows: 308 K tombstones);
  926. /// std.json.Value built a tagged value per offset, then freed them again. This walks the
  927. /// tokens and keeps only what applyMetaJson reads. It returns false — having changed
  928. /// nothing — for anything it does not recognise or any malformed text, and the Value
  929. /// path below then decides, exactly as before.
  930. fn applyMetaFast(self: *Db, content: []const u8) bool {
  931. var sc = std.json.Scanner.initCompleteInput(self.tmp, content);
  932. defer sc.deinit();
  933. var del: std.ArrayList(u64) = .empty;
  934. defer del.deinit(self.tmp);
  935. var next_id: f64 = FIRST_ID;
  936. var version: u64 = 0;
  937. var df: ?DataFileMeta = null;
  938. const t0 = sc.next() catch return false;
  939. if (t0 != .object_begin) return false;
  940. while (true) {
  941. const kt = sc.next() catch return false;
  942. const key = switch (kt) {
  943. .object_end => break,
  944. .string => |k| k,
  945. else => return false,
  946. };
  947. if (std.mem.eql(u8, key, "nextId")) {
  948. const t = sc.next() catch return false;
  949. next_id = switch (t) {
  950. .number => |n| switch (jnum(n) orelse return false) {
  951. .int => |i| @floatFromInt(i),
  952. .float => |f| f,
  953. },
  954. .string, .true, .false, .null => FIRST_ID,
  955. else => return false,
  956. };
  957. } else if (std.mem.eql(u8, key, "version")) {
  958. const t = sc.next() catch return false;
  959. version = switch (t) {
  960. .number => |n| switch (jnum(n) orelse return false) {
  961. .int => |i| @intCast(@max(i, 0)),
  962. .float => 0,
  963. },
  964. .string, .true, .false, .null => 0,
  965. else => return false,
  966. };
  967. } else if (std.mem.eql(u8, key, "deleted")) {
  968. del.clearRetainingCapacity();
  969. const t = sc.next() catch return false;
  970. switch (t) {
  971. .array_begin => while (true) {
  972. const e = sc.next() catch return false;
  973. switch (e) {
  974. .array_end => break,
  975. .number => |n| {
  976. const off: u64 = switch (jnum(n) orelse return false) {
  977. .int => |i| @intCast(@max(i, 0)),
  978. .float => |f| @intFromFloat(@max(f, 0)),
  979. };
  980. del.append(self.tmp, off) catch return false;
  981. },
  982. .string, .true, .false, .null => {},
  983. else => return false,
  984. }
  985. },
  986. .string, .number, .true, .false, .null => {},
  987. else => return false,
  988. }
  989. } else if (std.mem.eql(u8, key, "dataFile")) {
  990. df = null;
  991. const t = sc.next() catch return false;
  992. switch (t) {
  993. .object_begin => {
  994. var d = DataFileMeta{};
  995. while (true) {
  996. const ik = sc.next() catch return false;
  997. const k2 = switch (ik) {
  998. .object_end => break,
  999. .string => |k| k,
  1000. else => return false,
  1001. };
  1002. const v = sc.next() catch return false;
  1003. const is_u64: ?u64 = switch (v) {
  1004. .number => |n| switch (jnum(n) orelse return false) {
  1005. .int => |i| if (i < 0) null else @intCast(i),
  1006. .float => null,
  1007. },
  1008. .string, .true, .false, .null => null,
  1009. else => return false,
  1010. };
  1011. const str: ?[]const u8 = if (v == .string) v.string else null;
  1012. if (std.mem.eql(u8, k2, "ino")) {
  1013. d.ino = is_u64;
  1014. } else if (std.mem.eql(u8, k2, "size")) {
  1015. d.size = is_u64;
  1016. } else if (std.mem.eql(u8, k2, "gen")) {
  1017. d.gen = is_u64;
  1018. } else if (std.mem.eql(u8, k2, "deletedSum")) {
  1019. d.sum = str;
  1020. } else if (std.mem.eql(u8, k2, "fp")) {
  1021. d.fp_present = true;
  1022. d.fp = str;
  1023. }
  1024. }
  1025. df = d;
  1026. },
  1027. .string, .number, .true, .false, .null => {},
  1028. else => return false,
  1029. }
  1030. } else {
  1031. sc.skipValue() catch return false;
  1032. }
  1033. }
  1034. const te = sc.next() catch return false;
  1035. if (te != .end_of_document) return false;
  1036. // parsed whole: apply
  1037. self.next_id = next_id;
  1038. self.deleted.clearRetainingCapacity();
  1039. self.delCacheDrop();
  1040. self.version = version;
  1041. self.deleted.appendSlice(self.alloc, del.items) catch {};
  1042. self.bind_known = false;
  1043. self.meta_stale = false;
  1044. if (df) |d| self.applyBinding(d);
  1045. return true;
  1046. }
  1047. fn applyMetaJson(self: *Db, content: []const u8) void {
  1048. if (self.applyMetaFast(content)) return;
  1049. self.applyMetaSlow(content);
  1050. }
  1051. /// The meta through std.json.Value (the reading before mission 436; also the fallback).
  1052. fn applyMetaSlow(self: *Db, content: []const u8) void {
  1053. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  1054. defer parsed.deinit();
  1055. if (parsed.value != .object) return;
  1056. const obj = parsed.value.object;
  1057. self.next_id = FIRST_ID;
  1058. self.deleted.clearRetainingCapacity();
  1059. self.delCacheDrop();
  1060. self.version = 0;
  1061. if (obj.get("nextId")) |v| {
  1062. self.next_id = switch (v) {
  1063. .integer => |i| @floatFromInt(i),
  1064. .float => |f| f,
  1065. else => FIRST_ID,
  1066. };
  1067. }
  1068. if (obj.get("version")) |v| {
  1069. if (v == .integer) self.version = @intCast(@max(v.integer, 0));
  1070. }
  1071. if (obj.get("deleted")) |v| {
  1072. if (v == .array) {
  1073. for (v.array.items) |it| {
  1074. const off: u64 = switch (it) {
  1075. .integer => |i| @intCast(@max(i, 0)),
  1076. .float => |f| @intFromFloat(@max(f, 0)),
  1077. else => continue,
  1078. };
  1079. self.deleted.append(self.alloc, off) catch {};
  1080. }
  1081. }
  1082. }
  1083. self.bind_known = false;
  1084. self.meta_stale = false;
  1085. const df_v = obj.get("dataFile") orelse return;
  1086. if (df_v != .object) return;
  1087. const df = df_v.object;
  1088. var d = DataFileMeta{ .ino = jsonU64(df.get("ino")), .size = jsonU64(df.get("size")), .gen = jsonU64(df.get("gen")) };
  1089. if (df.get("deletedSum")) |sv| {
  1090. if (sv == .string) d.sum = sv.string;
  1091. }
  1092. if (df.get("fp")) |fv| {
  1093. d.fp_present = true;
  1094. if (fv == .string) d.fp = fv.string;
  1095. }
  1096. self.applyBinding(d);
  1097. }
  1098. /// The tail of applyMetaJson: does the meta's `dataFile` bind it to the data file at the path?
  1099. fn applyBinding(self: *Db, df: DataFileMeta) void {
  1100. const ino = df.ino orelse return;
  1101. const size = df.size orelse return;
  1102. if (df.gen) |g| self.data_gen = @max(self.data_gen, g);
  1103. const sum = df.sum orelse return;
  1104. var sum_buf: [16]u8 = undefined;
  1105. if (!std.mem.eql(u8, sum, self.deletedSum(&sum_buf))) return; // another writer's
  1106. const cur = fio.stat(self.tmp, self.data_path);
  1107. // THE BINDING RULE (ticket 387, after #176): the inode is the fast path, the
  1108. // content is the proof. A byte COPY of an open store (a hot tar, a deploy
  1109. // backup, a restore) has a new inode but the same bytes, and its meta must
  1110. // still apply — its tombstones and newer versions are the store's truth.
  1111. // - same inode, file at least `size` bytes: bound (as in #176).
  1112. // - file shorter than `size`, or gone: stale (a different file).
  1113. // - another inode, meta carries `fp` (fingerprint of the first and last
  1114. // 4 KB of the first `size` bytes): bound if the file's fingerprint over
  1115. // that range equals it (the same content, copied or restored); a data
  1116. // file a compaction replaced differs in content, so it stays stale.
  1117. // - another inode, an OLD meta without `fp`: bound only if every tombstone
  1118. // offset is a plausible frame start in the file (size > 4, fits, and the
  1119. // next frame's header is plausible or EOF). Else stale.
  1120. var bound = false;
  1121. var fp_buf: [16]u8 = undefined;
  1122. var have_fp: ?[]const u8 = null;
  1123. if (cur) |c| {
  1124. if (c.size >= size) {
  1125. if (c.ino == ino) {
  1126. bound = true;
  1127. } else if (df.fp_present) {
  1128. if (df.fp) |fv| {
  1129. have_fp = self.dataFingerprint(size, &fp_buf);
  1130. bound = have_fp != null and std.mem.eql(u8, have_fp.?, fv);
  1131. }
  1132. } else {
  1133. bound = self.tombstonesAreFrameStarts(c.size);
  1134. }
  1135. }
  1136. } else bound = size == 0;
  1137. if (!bound) {
  1138. if (self.deleted.items.len > 0) {
  1139. 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 });
  1140. }
  1141. self.deleted.clearRetainingCapacity();
  1142. self.delCacheDrop();
  1143. self.meta_stale = true;
  1144. return;
  1145. }
  1146. self.bind_known = true;
  1147. self.bind_ino = if (cur) |c| c.ino else ino; // a copy: this file's inode from now on
  1148. self.bind_size = size;
  1149. self.bind_fp_len = 0;
  1150. if (have_fp == null) have_fp = self.dataFingerprint(size, &fp_buf);
  1151. if (have_fp) |f| {
  1152. @memcpy(self.bind_fp[0..f.len], f);
  1153. self.bind_fp_len = @intCast(f.len);
  1154. }
  1155. }
  1156. /// Fingerprint (16 hex chars) of the first `n` bytes of the data file: a hash of
  1157. /// its first 4 KB and one of the 4 KB before `n`. Appends past `n` do not change
  1158. /// it; a replaced (compacted) file, with other records at those places, does.
  1159. fn dataFingerprint(self: *Db, n: u64, buf: *[16]u8) ?[]const u8 {
  1160. const fd = fio.openRead(self.tmp, self.data_path) orelse return null;
  1161. defer fio.close(fd);
  1162. return fingerprintFd(fd, n, buf);
  1163. }
  1164. fn fingerprintFd(fd: i32, n: u64, buf: *[16]u8) ?[]const u8 {
  1165. var h = std.hash.Wyhash.init(387);
  1166. var blk: [4096]u8 = undefined;
  1167. const head: usize = @intCast(@min(n, 4096));
  1168. const got = fio.pread(fd, blk[0..head], 0) orelse return null;
  1169. if (got != head) return null;
  1170. h.update(blk[0..head]);
  1171. const tail_off = n - head;
  1172. const got2 = fio.pread(fd, blk[0..head], tail_off) orelse return null;
  1173. if (got2 != head) return null;
  1174. h.update(blk[0..head]);
  1175. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch null;
  1176. }
  1177. /// An old meta (no fingerprint) beside a file of another inode: are its tombstones
  1178. /// frame starts of this file? A frame start has a size > 4 that fits in the file,
  1179. /// and is followed by EOF or another plausible frame header.
  1180. fn tombstonesAreFrameStarts(self: *Db, file_size: u64) bool {
  1181. const fd = fio.openRead(self.tmp, self.data_path) orelse return self.deleted.items.len == 0;
  1182. defer fio.close(fd);
  1183. for (self.deleted.items) |off| {
  1184. if (!frameHeaderOk(fd, off, file_size)) return false;
  1185. var hdr: [4]u8 = undefined;
  1186. _ = fio.pread(fd, &hdr, off);
  1187. const next = off + std.mem.readInt(u32, &hdr, .little);
  1188. if (next != file_size and !frameHeaderOk(fd, next, file_size)) return false;
  1189. }
  1190. return true;
  1191. }
  1192. fn frameHeaderOk(fd: i32, off: u64, file_size: u64) bool {
  1193. if (off + 4 > file_size) return false;
  1194. var hdr: [4]u8 = undefined;
  1195. const got = fio.pread(fd, &hdr, off) orelse return false;
  1196. if (got < 4) return false;
  1197. const sz: u64 = std.mem.readInt(u32, &hdr, .little);
  1198. return sz > 4 and off + sz <= file_size;
  1199. }
  1200. fn jsonU64(v: ?std.json.Value) ?u64 {
  1201. const x = v orelse return null;
  1202. return switch (x) {
  1203. .integer => |i| if (i < 0) null else @intCast(i),
  1204. else => null,
  1205. };
  1206. }
  1207. /// The checksum of the deleted list (hex), as dataFile.deletedSum carries it.
  1208. fn deletedSum(self: *Db, buf: *[16]u8) []const u8 {
  1209. var h = std.hash.Wyhash.init(176);
  1210. // the stream of little-endian u64s, fed in blocks (the hash does not depend on the split)
  1211. var blk: [512]u64 = undefined;
  1212. var i: usize = 0;
  1213. while (i < self.deleted.items.len) {
  1214. const n = @min(blk.len, self.deleted.items.len - i);
  1215. for (0..n) |j| blk[j] = std.mem.nativeToLittle(u64, self.deleted.items[i + j]);
  1216. h.update(std.mem.sliceAsBytes(blk[0..n]));
  1217. i += n;
  1218. }
  1219. return std.fmt.bufPrint(buf, "{x:0>16}", .{h.final()}) catch buf[0..0];
  1220. }
  1221. /// Pick up other processes' persisted state (JS refresh()): adopt disk meta
  1222. /// when its version is newer; index appended tail records.
  1223. ///
  1224. /// A HANDLE NOTICES A REWRITE (ticket #176). Another process's compaction
  1225. /// replaces the data file and moves every record after its first tombstone;
  1226. /// this handle's offsets are then into a file that no longer exists, and
  1227. /// reading them read the middle of other records — a bare Number where a
  1228. /// record was (the tracker, 2026-10-20). The data file's inode, a size below
  1229. /// what was indexed, or a newer compaction generation in the meta says it
  1230. /// happened; the handle then re-reads the meta (dropping a deleted list that
  1231. /// belongs to the old file) and re-indexes the new file before it answers.
  1232. pub fn refresh(self: *Db) void {
  1233. if (self.data_fd < 0) self.adoptDataFile(); // a file created since the open
  1234. if (self.index_bad) self.rebuildIndexesFromData();
  1235. const cur = fio.stat(self.tmp, self.data_path);
  1236. var rewritten = false;
  1237. if (cur) |c| {
  1238. if (self.seen_ino != 0 and c.ino != self.seen_ino) rewritten = true;
  1239. if (self.index_fields.items.len > 0 and c.size < self.covered_bytes) rewritten = true;
  1240. }
  1241. const meta_now = fio.stat(self.tmp, self.meta_path);
  1242. 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;
  1243. // an unchanged meta says nothing new: its version and generation were taken when read
  1244. // (a rewritten data file still re-reads it, to drop a deleted list of the old file)
  1245. if (meta_same and !rewritten) {
  1246. // nothing to read
  1247. } else if (blk: {
  1248. self.meta_seen = meta_now;
  1249. self.meta_reads += 1;
  1250. break :blk fio.readAll(self.tmp, self.meta_path);
  1251. }) |content| {
  1252. defer self.tmp.free(content);
  1253. const parsed = std.json.parseFromSlice(std.json.Value, self.tmp, content, .{}) catch return;
  1254. defer parsed.deinit();
  1255. if (parsed.value == .object) {
  1256. var disk_version: u64 = 0;
  1257. if (parsed.value.object.get("version")) |v| {
  1258. if (v == .integer) disk_version = @intCast(@max(v.integer, 0));
  1259. }
  1260. if (parsed.value.object.get("dataFile")) |df| {
  1261. if (df == .object) {
  1262. if (jsonU64(df.object.get("gen"))) |g| {
  1263. if (g > self.data_gen) rewritten = true;
  1264. }
  1265. }
  1266. }
  1267. if (rewritten or disk_version > self.version) self.applyMetaJson(content);
  1268. }
  1269. }
  1270. if (rewritten) {
  1271. self.reindexRewritten();
  1272. return;
  1273. }
  1274. // catchUp: index records another process appended
  1275. if (self.index_fields.items.len > 0) {
  1276. const size = if (cur) |c| c.size else 0;
  1277. if (size > self.covered_bytes) self.catchUp(size);
  1278. }
  1279. }
  1280. /// THE INDEX NAMED A PLACE THAT IS NO RECORD (mission 393): the tracker's persons.id.txt
  1281. /// carried ~2100 entries with offsets past the end of the data file or into the middle of a
  1282. /// frame (entries of an older generation of the file), so range('id', …) answered a Number
  1283. /// where a record was ("reading 'id': the value is Number"). A hit is checked against its
  1284. /// frame header before it is returned; a bad one is dropped and the indexes are rebuilt from
  1285. /// the data file at the next refresh.
  1286. fn hitOk(self: *Db, h: Entry) bool {
  1287. if (self.data_fd < 0) return true;
  1288. var hdr: [4]u8 = undefined;
  1289. const got = fio.pread(self.data_fd, &hdr, h.off) orelse 0;
  1290. if (got == 4 and std.mem.readInt(u32, &hdr, .little) == h.len) return true;
  1291. self.index_bad = true;
  1292. return false;
  1293. }
  1294. fn rebuildIndexesFromData(self: *Db) void {
  1295. self.index_bad = false;
  1296. self.covered_bytes = 0;
  1297. var it0 = self.idx.iterator();
  1298. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1299. if (self.index_fields.items.len > 0) {
  1300. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  1301. self.catchUp(size);
  1302. }
  1303. std.debug.print("mpackdb: {s}: an index named a place that is no record; indexes rebuilt from the data file\n", .{self.data_path});
  1304. }
  1305. /// The data file was replaced under this handle: index it anew, in memory —
  1306. /// the index files are written when the handle persists or closes.
  1307. fn reindexRewritten(self: *Db) void {
  1308. const old_ino = self.seen_ino;
  1309. self.adoptDataFile();
  1310. 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 });
  1311. self.covered_bytes = 0;
  1312. var it0 = self.idx.iterator();
  1313. while (it0.next()) |kv| kv.value_ptr.entries.clearRetainingCapacity();
  1314. if (self.index_fields.items.len > 0) {
  1315. const size: u64 = if (self.data_fd >= 0) (if (fio.fdStat(self.data_fd)) |st| st.size else 0) else 0;
  1316. self.catchUp(size);
  1317. }
  1318. }
  1319. /// Hold the data file now at the path; its inode is what the offsets are into.
  1320. fn adoptDataFile(self: *Db) void {
  1321. self.dropDataFile();
  1322. self.data_fd = fio.openz(self.tmp, self.data_path, .{ .CLOEXEC = true }, 0) orelse -1;
  1323. if (self.data_fd >= 0) self.fd_gen = DataGen.create(self.tmp, self.data_fd);
  1324. self.seen_ino = if (self.data_fd >= 0) (fio.fdIno(self.data_fd) orelse 0) else 0;
  1325. }
  1326. fn dropDataFile(self: *Db) void {
  1327. if (self.fd_gen) |g| g.release() else if (self.data_fd >= 0) fio.close(self.data_fd);
  1328. self.fd_gen = null;
  1329. self.data_fd = -1;
  1330. }
  1331. fn persistMetaLocked(self: *Db) Error!void {
  1332. self.version += 1;
  1333. const cur = fio.stat(self.tmp, self.data_path);
  1334. self.bind_ino = if (cur) |c| c.ino else 0;
  1335. self.bind_size = if (cur) |c| c.size else 0;
  1336. self.bind_fp_len = 0;
  1337. var fpb: [16]u8 = undefined;
  1338. if (self.dataFingerprint(self.bind_size, &fpb)) |f| {
  1339. @memcpy(self.bind_fp[0..f.len], f);
  1340. self.bind_fp_len = @intCast(f.len);
  1341. }
  1342. self.bind_known = true;
  1343. self.meta_stale = false;
  1344. var out: std.ArrayList(u8) = .empty;
  1345. defer out.deinit(self.tmp);
  1346. try self.renderMeta(&out);
  1347. // atomic tmp + rename (JS: `${metaPath}.${pid}.tmp`)
  1348. var tmp_buf: [512]u8 = undefined;
  1349. const tmp_path = std.fmt.bufPrint(&tmp_buf, "{s}.{d}.tmp", .{ self.meta_path, linux.getpid() }) catch return Error.IoError;
  1350. const fd = fio.openTrunc(self.tmp, tmp_path) orelse return Error.IoError;
  1351. const ok = fio.writeAll(fd, out.items);
  1352. // the tmp file's own stat: rename keeps the inode, and no other writer can slip in
  1353. // between a stat of the path and our remembering it (ticket #188)
  1354. const written = fio.fdStat(fd);
  1355. fio.close(fd);
  1356. if (!ok) return Error.IoError;
  1357. if (!fio.rename(self.tmp, tmp_path, self.meta_path)) return Error.IoError;
  1358. self.meta_seen = written;
  1359. }
  1360. /// Does .meta.json already say, byte for byte, what this handle would write
  1361. /// at its current version? Then an open has nothing to persist (ticket #21).
  1362. fn metaOnDiskIsCurrent(self: *Db) bool {
  1363. const disk = fio.readAll(self.tmp, self.meta_path) orelse return false;
  1364. defer self.tmp.free(disk);
  1365. var out: std.ArrayList(u8) = .empty;
  1366. defer out.deinit(self.tmp);
  1367. self.renderMeta(&out) catch return false;
  1368. return std.mem.eql(u8, disk, out.items);
  1369. }
  1370. fn renderMeta(self: *Db, out: *std.ArrayList(u8)) Error!void {
  1371. try self.appendFmt(out, "{{", .{});
  1372. if (self.pk != null and self.pk_type == .number) {
  1373. var nbuf: [32]u8 = undefined;
  1374. try self.appendFmt(out, "\"nextId\":{s},", .{jsNumFmt(&nbuf, self.next_id)});
  1375. }
  1376. try self.appendFmt(out, "\"deleted\":[", .{});
  1377. out.ensureUnusedCapacity(self.tmp, self.deleted.items.len * 9 + 64) catch return Error.OutOfMemory;
  1378. for (self.deleted.items, 0..) |off, i| {
  1379. out.ensureUnusedCapacity(self.tmp, 24) catch return Error.OutOfMemory;
  1380. if (i > 0) out.appendAssumeCapacity(',');
  1381. const spare = out.unusedCapacitySlice();
  1382. const w = std.fmt.bufPrint(spare, "{d}", .{off}) catch return Error.OutOfMemory;
  1383. out.items.len += w.len;
  1384. }
  1385. try self.appendFmt(out, "],\"version\":{d}", .{self.version});
  1386. if (self.pk != null or self.index_fields.items.len > 0) {
  1387. try self.appendFmt(out, ",\"schema\":{{", .{});
  1388. var first = true;
  1389. if (self.pk) |p| {
  1390. const prefix: []const u8 = switch (self.pk_type) {
  1391. .number => "*",
  1392. .uuid => "@",
  1393. .string => "",
  1394. };
  1395. try self.appendFmt(out, "\"primaryKey\":\"{s}{s}\"", .{ prefix, p });
  1396. first = false;
  1397. }
  1398. if (!first) try self.appendFmt(out, ",", .{});
  1399. try self.appendFmt(out, "\"indexes\":[", .{});
  1400. var n: usize = 0;
  1401. for (self.index_fields.items) |field| {
  1402. if (self.pk != null and std.mem.eql(u8, field, self.pk.?)) continue;
  1403. if (n > 0) try self.appendFmt(out, ",", .{});
  1404. const uni = for (self.unique_fields.items) |u| {
  1405. if (std.mem.eql(u8, u, field)) break true;
  1406. } else false;
  1407. const numeric = (self.idx.get(field) orelse FieldIndex{ .typ = .lexical }).typ == .numeric;
  1408. try self.appendFmt(out, "\"{s}{s}{s}\"", .{
  1409. if (uni) "!" else "",
  1410. if (numeric) "*" else "",
  1411. field,
  1412. });
  1413. n += 1;
  1414. }
  1415. try self.appendFmt(out, "]}}", .{});
  1416. }
  1417. if (self.bind_known) {
  1418. var sum_buf: [16]u8 = undefined;
  1419. 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) });
  1420. if (self.bind_fp_len > 0) try self.appendFmt(out, ",\"fp\":\"{s}\"", .{self.bind_fp[0..self.bind_fp_len]});
  1421. try self.appendFmt(out, "}}", .{});
  1422. }
  1423. try self.appendFmt(out, "}}", .{});
  1424. }
  1425. // =====================================================================
  1426. // Data file scanning
  1427. // =====================================================================
  1428. fn deletedSet(self: *Db, alloc: std.mem.Allocator) std.AutoHashMapUnmanaged(u64, void) {
  1429. var set: std.AutoHashMapUnmanaged(u64, void) = .empty;
  1430. for (self.deleted.items) |off| set.put(alloc, off, {}) catch {};
  1431. return set;
  1432. }
  1433. /// The cached tombstone set, built on first use (borrowed: valid until the next
  1434. /// delete / meta adoption / compaction; hold it with delSetAcquire to keep it).
  1435. fn delSetCached(self: *Db) *DelSet {
  1436. if (self.del_cache) |c| return c;
  1437. const c = self.tmp.create(DelSet) catch unreachable;
  1438. c.* = .{ .alloc = self.tmp };
  1439. c.map.ensureTotalCapacity(self.tmp, @intCast(self.deleted.items.len)) catch {};
  1440. for (self.deleted.items) |off| c.map.put(self.tmp, off, {}) catch {};
  1441. self.del_cache = c;
  1442. return c;
  1443. }
  1444. /// A reference the caller must release() — a frozen view of the tombstones.
  1445. pub fn delSetAcquire(self: *Db) *DelSet {
  1446. const c = self.delSetCached();
  1447. c.refs += 1;
  1448. return c;
  1449. }
  1450. fn delCacheDrop(self: *Db) void {
  1451. if (self.del_cache) |c| c.release();
  1452. self.del_cache = null;
  1453. }
  1454. fn delCacheAdd(self: *Db, off: u64) void {
  1455. const c = self.del_cache orelse return;
  1456. if (c.refs > 1) {
  1457. // a cursor holds this set: it keeps it unchanged, the Db goes on with a copy
  1458. const n = self.tmp.create(DelSet) catch {
  1459. self.delCacheDrop();
  1460. return;
  1461. };
  1462. n.* = .{ .alloc = self.tmp };
  1463. n.map = c.map.clone(self.tmp) catch {
  1464. self.tmp.destroy(n);
  1465. self.delCacheDrop();
  1466. return;
  1467. };
  1468. c.release();
  1469. self.del_cache = n;
  1470. }
  1471. self.del_cache.?.map.put(self.tmp, off, {}) catch self.delCacheDrop();
  1472. }
  1473. /// Sequential scan yielding all live records. Caller supplies an arena for
  1474. /// decoded values. Used for rebuilds, compaction and unindexed finds.
  1475. pub const Scanner = struct {
  1476. db: *Db,
  1477. fd: i32 = -1,
  1478. offset: u64 = 0,
  1479. size: u64 = 0,
  1480. skip_deleted: bool = true,
  1481. owns_fd: bool = true,
  1482. /// a detached scanner's reference to the data file generation (instead of a dup)
  1483. gen: ?*DataGen = null,
  1484. /// a frozen view of the tombstones (null when !skip_deleted); released by deinit
  1485. deleted_set: ?*DelSet = null,
  1486. scratch: std.mem.Allocator,
  1487. pub fn init(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool) Scanner {
  1488. return initOpt(db, scratch, skip_deleted, false);
  1489. }
  1490. /// `detached` (a streaming cursor): the scanner holds a reference to the data file generation (no dup), so a compaction
  1491. /// or a foreign rewrite that makes the Db move to a new file leaves the scan reading
  1492. /// the file it started on; it also freezes the size and the tombstones (mission 393).
  1493. pub fn initOpt(db: *Db, scratch: std.mem.Allocator, skip_deleted: bool, detached: bool) Scanner {
  1494. var s = Scanner{ .db = db, .scratch = scratch, .skip_deleted = skip_deleted };
  1495. if (db.data_fd >= 0) {
  1496. // the file the handle's offsets are into (#176), not whatever is at the path
  1497. if (detached) {
  1498. if (db.fd_gen) |g| {
  1499. s.gen = g.retain();
  1500. s.fd = g.fd;
  1501. s.owns_fd = false;
  1502. } else {
  1503. s.fd = db.data_fd;
  1504. s.owns_fd = false;
  1505. }
  1506. } else {
  1507. s.fd = db.data_fd;
  1508. s.owns_fd = false;
  1509. }
  1510. s.size = if (fio.fdStat(s.fd)) |st| st.size else 0;
  1511. } else {
  1512. s.size = fio.fileSize(scratch, db.data_path) orelse 0;
  1513. if (s.size > 0) {
  1514. s.fd = fio.openRead(scratch, db.data_path) orelse -1;
  1515. }
  1516. }
  1517. if (skip_deleted) s.deleted_set = db.delSetAcquire();
  1518. return s;
  1519. }
  1520. pub fn deinit(self: *Scanner) void {
  1521. if (self.gen) |g| g.release();
  1522. self.gen = null;
  1523. if (self.fd >= 0 and self.owns_fd) fio.close(self.fd);
  1524. self.fd = -1;
  1525. if (self.deleted_set) |d| d.release();
  1526. self.deleted_set = null;
  1527. }
  1528. /// Returns the next record (decoded into `arena`) or null at EOF.
  1529. pub fn next(self: *Scanner, arena: std.mem.Allocator) Error!?Record {
  1530. return self.nextProjected(arena, null);
  1531. }
  1532. pub fn nextProjected(self: *Scanner, arena: std.mem.Allocator, fields: ?[]const []const u8) Error!?Record {
  1533. while (true) {
  1534. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1535. var hdr: [4]u8 = undefined;
  1536. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1537. if (got < 4) return null;
  1538. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1539. if (rec_size <= 4) return Error.CorruptRecord;
  1540. if (self.offset + rec_size > self.size) return null; // incomplete tail
  1541. const off = self.offset;
  1542. self.offset += rec_size;
  1543. if (self.deleted_set) |d| {
  1544. if (d.map.contains(off)) continue;
  1545. }
  1546. const buf = arena.alloc(u8, rec_size - 4) catch return Error.OutOfMemory;
  1547. const got2 = fio.pread(self.fd, buf, off + 4) orelse return Error.IoError;
  1548. if (got2 < rec_size - 4) return Error.Truncated;
  1549. const value = msgpack.decodeRecord(arena, buf, fields) catch return Error.CorruptRecord;
  1550. return Record{ .value = value, .off = off, .len = rec_size };
  1551. }
  1552. }
  1553. /// The number of live records from here on, reading only the 4-byte frame headers:
  1554. /// nothing is decoded or kept (count() decoded the whole table into an arena, 2 GB
  1555. /// for the tracker's two big tables).
  1556. pub fn countLive(self: *Scanner) Error!usize {
  1557. var n: usize = 0;
  1558. while (true) {
  1559. if (self.fd < 0 or self.offset + 4 > self.size) return n;
  1560. var hdr: [4]u8 = undefined;
  1561. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1562. if (got < 4) return n;
  1563. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1564. if (rec_size <= 4) return Error.CorruptRecord;
  1565. if (self.offset + rec_size > self.size) return n;
  1566. const off = self.offset;
  1567. self.offset += rec_size;
  1568. if (self.deleted_set) |d| {
  1569. if (d.map.contains(off)) continue;
  1570. }
  1571. n += 1;
  1572. }
  1573. }
  1574. /// Like next() but without decoding — yields the raw framed bytes.
  1575. pub fn nextRaw(self: *Scanner, arena: std.mem.Allocator) Error!?struct { bytes: []u8, off: u64 } {
  1576. while (true) {
  1577. if (self.fd < 0 or self.offset + 4 > self.size) return null;
  1578. var hdr: [4]u8 = undefined;
  1579. const got = fio.pread(self.fd, &hdr, self.offset) orelse return Error.IoError;
  1580. if (got < 4) return null;
  1581. const rec_size = std.mem.readInt(u32, &hdr, .little);
  1582. if (rec_size <= 4) return Error.CorruptRecord;
  1583. if (self.offset + rec_size > self.size) return null;
  1584. const off = self.offset;
  1585. self.offset += rec_size;
  1586. if (self.deleted_set) |d| {
  1587. if (d.map.contains(off)) continue;
  1588. }
  1589. const buf = arena.alloc(u8, rec_size) catch return Error.OutOfMemory;
  1590. const got2 = fio.pread(self.fd, buf, off) orelse return Error.IoError;
  1591. if (got2 < rec_size) return Error.Truncated;
  1592. return .{ .bytes = buf, .off = off };
  1593. }
  1594. }
  1595. };
  1596. /// A reference to the data file the offsets are into, for a streaming cursor (null: none).
  1597. /// Release it with `DataGen.release`; the fd (`.fd`) stays valid until then.
  1598. pub fn retainDataGen(self: *Db) ?*DataGen {
  1599. const g = self.fd_gen orelse return null;
  1600. return g.retain();
  1601. }
  1602. /// Read + decode one record by location from `fd` (a dupDataFd of the file the loc is into).
  1603. pub fn readAtFd(fd: i32, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1604. return readAtFdProjected(fd, arena, loc, null);
  1605. }
  1606. pub fn readAtFdProjected(fd: i32, arena: std.mem.Allocator, loc: Loc, fields: ?[]const []const u8) Error!msgpack.Value {
  1607. if (loc.len <= 4) return Error.CorruptRecord;
  1608. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1609. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1610. if (got < buf.len) return Error.Truncated;
  1611. return msgpack.decodeRecord(arena, buf, fields) catch return Error.CorruptRecord;
  1612. }
  1613. /// Read + decode one record by location.
  1614. pub fn readAt(self: *Db, arena: std.mem.Allocator, loc: Loc) Error!msgpack.Value {
  1615. return self.readAtProjected(arena, loc, null);
  1616. }
  1617. pub fn readAtProjected(self: *Db, arena: std.mem.Allocator, loc: Loc, fields: ?[]const []const u8) Error!msgpack.Value {
  1618. const own = self.data_fd < 0;
  1619. const fd = if (own) (fio.openRead(self.tmp, self.data_path) orelse return Error.IoError) else self.data_fd;
  1620. defer if (own) fio.close(fd);
  1621. if (loc.len <= 4) return Error.CorruptRecord;
  1622. const buf = arena.alloc(u8, loc.len - 4) catch return Error.OutOfMemory;
  1623. const got = fio.pread(fd, buf, loc.off + 4) orelse return Error.IoError;
  1624. if (got < buf.len) return Error.Truncated;
  1625. return msgpack.decodeRecord(arena, buf, fields) catch return Error.CorruptRecord;
  1626. }
  1627. // =====================================================================
  1628. // Index management
  1629. // =====================================================================
  1630. fn keyFromValue(v: msgpack.Value) ?Key {
  1631. return switch (v) {
  1632. .number => |n| Key{ .num = n },
  1633. .str => |s| Key{ .str = s },
  1634. else => null, // null/bool/objects are not indexed (see header note)
  1635. };
  1636. }
  1637. /// Duplicate a key's string into the db arena so it outlives the op arena.
  1638. fn ownKey(self: *Db, k: Key) Error!Key {
  1639. return switch (k) {
  1640. .num => k,
  1641. .str => |s| Key{ .str = (if (self.bulk_keys) |ka| ka.allocator() else self.alloc).dupe(u8, s) catch return Error.OutOfMemory },
  1642. };
  1643. }
  1644. /// Copy every string key of every index into one run of memory, in the lists' order.
  1645. fn packKeys(self: *Db) void {
  1646. for (self.idx.values()) |*fi| {
  1647. var total: usize = 0;
  1648. for (fi.entries.items) |e| {
  1649. if (e.key == .str) total += e.key.str.len;
  1650. }
  1651. if (total == 0) continue;
  1652. const slab = self.alloc.alloc(u8, total) catch continue;
  1653. var pos: usize = 0;
  1654. for (fi.entries.items) |*e| {
  1655. if (e.key == .str) {
  1656. const k = e.key.str;
  1657. @memcpy(slab[pos..][0..k.len], k);
  1658. e.key = .{ .str = slab[pos..][0..k.len] };
  1659. pos += k.len;
  1660. }
  1661. }
  1662. }
  1663. }
  1664. fn lowerBound(entries: []const Entry, key: Key) usize {
  1665. var lo: usize = 0;
  1666. var hi: usize = entries.len;
  1667. while (lo < hi) {
  1668. const mid = lo + (hi - lo) / 2;
  1669. if (cmpKeys(entries[mid].key, key) < 0) {
  1670. lo = mid + 1;
  1671. } else {
  1672. hi = mid;
  1673. }
  1674. }
  1675. return lo;
  1676. }
  1677. /// Binary search: all entries whose key equals `key` (appended to `out`).
  1678. pub fn indexGet(self: *Db, field: []const u8, key: Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1679. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1680. const parsed = self.parseKeyForField(field, key);
  1681. const entries = fi.entries.items;
  1682. var i = lowerBound(entries, parsed);
  1683. while (i < entries.len and cmpKeys(entries[i].key, parsed) == 0) : (i += 1) {
  1684. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1685. }
  1686. }
  1687. /// Range scan [from, to] (either side optional), ascending.
  1688. pub fn indexRange(self: *Db, field: []const u8, from: ?Key, to: ?Key, alloc: std.mem.Allocator, out: *std.ArrayList(Entry)) Error!void {
  1689. const fi = self.idx.getPtr(field) orelse return Error.NoSuchIndex;
  1690. const entries = fi.entries.items;
  1691. var i: usize = if (from) |f| lowerBound(entries, self.parseKeyForField(field, f)) else 0;
  1692. const to_key: ?Key = if (to) |t| self.parseKeyForField(field, t) else null;
  1693. while (i < entries.len) : (i += 1) {
  1694. if (to_key) |t| {
  1695. if (cmpKeys(entries[i].key, t) > 0) break;
  1696. }
  1697. out.append(alloc, entries[i]) catch return Error.OutOfMemory;
  1698. }
  1699. }
  1700. /// _parseKey semantics: numeric index fields parse string keys via
  1701. /// parseInt; on NaN the key stays a string.
  1702. fn parseKeyForField(self: *Db, field: []const u8, key: Key) Key {
  1703. const fi = self.idx.get(field) orelse return key;
  1704. if (fi.typ == .numeric and key == .str) {
  1705. if (jsParseInt(key.str)) |n| return Key{ .num = n };
  1706. }
  1707. return key;
  1708. }
  1709. fn indexInsertEntry(self: *Db, field: []const u8, key: Key, loc: Loc) Error!void {
  1710. const fi = self.idx.getPtr(field) orelse return;
  1711. const owned = try self.ownKey(key);
  1712. const e = Entry{ .key = owned, .off = loc.off, .len = loc.len };
  1713. // a bulk scan (rebuild / big catch-up) appends and sorts once at the end: a sorted
  1714. // insert per record is a memmove of the whole list each time — quadratic (#376)
  1715. if (self.bulk_index) {
  1716. fi.entries.append(self.alloc, e) catch return Error.OutOfMemory;
  1717. return;
  1718. }
  1719. // insert at sorted position
  1720. const pos = blk: {
  1721. var lo: usize = 0;
  1722. var hi: usize = fi.entries.items.len;
  1723. while (lo < hi) {
  1724. const mid = lo + (hi - lo) / 2;
  1725. if (entryLess({}, fi.entries.items[mid], e)) {
  1726. lo = mid + 1;
  1727. } else {
  1728. hi = mid;
  1729. }
  1730. }
  1731. break :blk lo;
  1732. };
  1733. fi.entries.insert(self.alloc, pos, e) catch return Error.OutOfMemory;
  1734. }
  1735. /// Index a record's fields at loc.
  1736. fn indexInsertRecord(self: *Db, rec: msgpack.Value, loc: Loc) Error!void {
  1737. for (self.index_fields.items) |field| {
  1738. const v = rec.get(field) orelse continue;
  1739. const key = keyFromValue(v) orelse continue;
  1740. try self.indexInsertEntry(field, key, loc);
  1741. }
  1742. self.covered_bytes = @max(self.covered_bytes, loc.off + loc.len);
  1743. }
  1744. /// Remove all entries pointing at offset `off` (all fields).
  1745. fn indexRemoveOffset(self: *Db, off: u64) void {
  1746. var it = self.idx.iterator();
  1747. while (it.next()) |kv| {
  1748. const list = &kv.value_ptr.entries;
  1749. var i: usize = 0;
  1750. while (i < list.items.len) {
  1751. if (list.items[i].off == off) {
  1752. _ = list.orderedRemove(i);
  1753. } else {
  1754. i += 1;
  1755. }
  1756. }
  1757. }
  1758. }
  1759. fn indexPath(self: *Db, buf: []u8, field: []const u8) []const u8 {
  1760. // <dir>/<base>.<field>.txt — derive from idxstate path (…/base.idxstate.json)
  1761. const prefix = self.idxstate_path[0 .. self.idxstate_path.len - "idxstate.json".len];
  1762. return std.fmt.bufPrint(buf, "{s}{s}.txt", .{ prefix, field }) catch buf[0..0];
  1763. }
  1764. fn initIndexes(self: *Db, force_rebuild: bool) Error!void {
  1765. var need_rebuild = force_rebuild;
  1766. const data_size = fio.fileSize(self.tmp, self.data_path) orelse 0;
  1767. if (!need_rebuild) {
  1768. for (self.index_fields.items) |field| {
  1769. var pbuf: [512]u8 = undefined;
  1770. const p = self.indexPath(&pbuf, field);
  1771. const isize_ = fio.fileSize(self.tmp, p);
  1772. if (isize_ == null or isize_.? == 0) {
  1773. if (data_size > 0) {
  1774. need_rebuild = true;
  1775. break;
  1776. }
  1777. }
  1778. }
  1779. }
  1780. if (!need_rebuild) {
  1781. // coveredBytes from idxstate — no state file means rebuild (JS). An
  1782. // idxstate of another data file (its inode, or more bytes covered
  1783. // than there are) means the index files are another file's too:
  1784. // a crash between a compaction's rename and its rebuild (#176).
  1785. if (self.readIdxState()) |st| {
  1786. self.covered_bytes = st.covered;
  1787. const cur = fio.stat(self.tmp, self.data_path);
  1788. const cur_ino: u64 = if (cur) |c| c.ino else 0;
  1789. if (st.covered > data_size) need_rebuild = true;
  1790. if (st.fmt < idx_format) need_rebuild = true;
  1791. if (!st.fields_current) need_rebuild = true;
  1792. if (st.ino) |i| {
  1793. self.idx_bind_known = true;
  1794. // another inode: a byte COPY of the store (ticket 387) has the same
  1795. // content over the covered bytes, so its index files are right
  1796. if (i != cur_ino) {
  1797. var fpb: [16]u8 = undefined;
  1798. const same = st.has_fp and st.covered <= data_size and
  1799. if (self.dataFingerprint(st.covered, &fpb)) |f| std.mem.eql(u8, f, &st.fp) else false;
  1800. if (!same) need_rebuild = true;
  1801. }
  1802. }
  1803. } else {
  1804. need_rebuild = true;
  1805. }
  1806. }
  1807. if (need_rebuild) {
  1808. try self.rebuildIndexes();
  1809. return;
  1810. }
  1811. // Load index files into memory
  1812. for (self.index_fields.items) |field| {
  1813. var pbuf: [512]u8 = undefined;
  1814. const p = self.indexPath(&pbuf, field);
  1815. // the keys point INTO the file's bytes (mission 436: one allocation + copy per key
  1816. // was most of the load); a numeric index keeps no key text, so its buffer goes back
  1817. const numeric = (self.idx.get(field) orelse continue).typ == .numeric;
  1818. const content = fio.readAll(if (numeric) self.tmp else self.alloc, p) orelse continue;
  1819. var keep = false;
  1820. self.loadIndexLines(field, content, &keep);
  1821. if (numeric and !keep) self.tmp.free(content);
  1822. }
  1823. // sort (files are sorted by JS localeCompare; re-sort under our order). A file we wrote
  1824. // is in our order already: checking is a pass, pdq with a key compare per step is more.
  1825. var it = self.idx.iterator();
  1826. while (it.next()) |kv| {
  1827. const items = kv.value_ptr.entries.items;
  1828. if (!std.sort.isSorted(Entry, items, {}, entryLess)) sortEntries(self.tmp, items);
  1829. }
  1830. if (data_size > self.covered_bytes) self.catchUp(data_size);
  1831. }
  1832. /// parseInt(u64, s, 10) with a loop for the plain all-digits case.
  1833. fn parseU64(s: []const u8) ?u64 {
  1834. if (s.len == 0 or s.len > 19) return std.fmt.parseInt(u64, s, 10) catch null;
  1835. var v: u64 = 0;
  1836. for (s) |c| {
  1837. if (c < '0' or c > '9') return std.fmt.parseInt(u64, s, 10) catch null;
  1838. v = v * 10 + (c - '0');
  1839. }
  1840. return v;
  1841. }
  1842. /// `content` must outlive the entries when `keep` is set: string keys are slices of it.
  1843. fn loadIndexLines(self: *Db, field: []const u8, content: []const u8, keep: *bool) void {
  1844. const fi = self.idx.getPtr(field) orelse return;
  1845. // sizing: the first line's length says how many lines to expect
  1846. const nl_first = std.mem.indexOfScalar(u8, content, '\n') orelse content.len;
  1847. fi.entries.ensureUnusedCapacity(self.alloc, content.len / @max(nl_first + 1, 8) + 16) catch {};
  1848. const numeric = fi.typ == .numeric;
  1849. const c = content;

Only the first lines are shown.

Branches

Latest commits

  • 3b3e451f|||PR ident#36 navigate to the app instead of location.assignmre
  • e36f4516Merge branch 'f14-online' into mainIdent
  • 2c5eac91|||PR ident#38 online state without probe timermre
  • bf1980f2Merge branch 'v56-day56' into mainIdent
  • 62ae0adf|||PR ident: vendor Hybriel day56mre
  • 0d18abc4Merge branch 'f13-avatar' into mainIdent
  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre
  • 675493b1ident#42: editing an identity upserts the one edited row (face editIdentity answers { identity, row }); a create or delete keeps the whole list because the rows' position-dependent parts (default, Delete, Identity n) changemre
  • 45e55303ident#42: an app write patches one row: upsert on create, edit and new secret, one-argument remove on delete; the faces answer the changed app (or the deleted id), not the whole listmre
  • 991641d4Merge branch 'f10-access' into mainIdent
  • e56d8273|||PR ident#34 part 4: access and inbox fixed classesmre
  • df7696dbident#34: tests: access ticks selector quoting fixmre
  • 7215903eident#34: access: the unstyled classes all, app, tick, apptick, plus are dropped; the gate finds the app ticks by input[name=app]mre
  • 69b0a0ceident#34: access: the pick buttons use Style.pickCard instead of class pickmre
  • dc702419Merge branch 'f9-choose' into mainIdent
  • 8caec771|||PR ident#34 restore .choose hookmre
  • 0dbff960Merge branch 'f8-shared' into mainIdent
  • d69665f6|||PR ident#34 part 3: shared look classes (wide, avatar, chip/used, conn, choose, who, inboxlink) moved to statics or droppedmre