gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita80da7bda80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmrea80da7bd/plugins/mpackdb/engine.zig

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

Only the first lines are shown.

Branches

Latest commits

  • a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
  • 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
  • a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre