gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7276a0087276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre7276a008/plugins/mpackdb/engine.zig

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

Only the first lines are shown.

Branches

Latest commits

  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre
  • b7a61546ident mission 013: e2e — in-place main-menu mark kept as a known gapmre
  • 59b43d81ident mission 013: sign out everywhere keeps this browser's own (signed-out) session so the page goes on in placemre
  • 716e14ffident mission 013: browser gate — Bob signs out everywhere (no second code request)mre
  • 5885f1c9ident mission 013 step 2: stopgap reload removed (in-place sign-in/out reach the shell via emit, notices back, route-marked main menu), gates updatedmre
  • 734ac0a9ident mission 013 step 1: re-vendor Hybriel ce6f2e0a (plugins whole; bin/ is git-ignored)mre
  • b37875ccident mission 012 part 3: real-Chrome fixes (brand 44 px, identity form width), e2e walk, report, logmre
  • f989c2ebident mission 012: stopgap reload after in-place sign-in/sign-out (until hybriel#193), gates wait for cold start, welcome end reloadsmre
  • 443291d4ident mission 012: /start on its own shell (no account), browser gate 152/0, reportmre
  • 021dd0fcident mission 012: browser gate waits cold start (IDENT_COLD_MS), header selectors, e2e checks; shell events from a page do not reach it (probe), current not marked, account-bar link 44 pxmre
  • 97f77b07ident mission 012 (WIP): onto the layouts theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ContentFirst, styles cut, check-theme gatemre
  • 8e4f435bpaths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • fa288f63ident mission 011: report wording (Intl zone names)mre
  • 961fae01ident mission 011: report, LOG, STATUSmre
  • 65348039ident#7: delivery gate — console check split at the gate's own server restart (49 checks)mre
  • dfa7b783ident#7: README (Delivery, env, gate, files, data), deploy.sh runs tests/delivery.mjsmre
  • ab6331f4ident#7: tests/delivery.mjs — fake clock gate: Vienna/New York/Tokyo/UTC 17:00, urgent, mail off, restart, DST days, zone changemre
  • 7869f57bident#7: delivery — the daily mail at 17:00 in the user's zone (digests table, once per local day, test clock IDENT_TEST_CLOCK), urgent mailed at once, push hookmre