gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/mpackdb/engine.zig

223.5 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre