gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit875353c1875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre875353c1/plugins/mpackdb/engine.zig

143.6 KB

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

Only the first lines are shown.

Branches

Latest commits

  • 875353c1calendar mission 009: re-vendor Hybriel master 022a3ac1 (int 6 6b396322 hl:time browser side, int 7 65e8ec21; bin sha256 6e0f77d7, plugins whole)mre
  • ce16a4efdeploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • f490bc8cdeploy: Web Push gate tests/push.mjs (PUSH_GATE_PORT)mre
  • 3af29fc8calendar mission 008 (A8): report, README, LOG, push-shots.mjsmre
  • f91f3663calendar mission 008 (A8): push only asked of the browser when the app has the VAPID settings (pushAvailable); real-FCM E2E scripts (push-real-app.mjs, push-real.mjs)mre
  • bf571badcalendar mission 008 (A8): Turn off on this device (unsubscribes the browser, server drops the device, choice kept), subscribe/refresh when the app is shown again; push gate part 3mre
  • 50985708calendar mission 008 (A7): Web Push report, README, mission, LOGmre
  • ee318774calendar mission 008 (A7): push-real.mjs, push sent log linemre
  • ebda0fd1calendar mission 008 (A7): server-side reminder plan on hl:time (push-plan.hl; hl:time fromLocal in a browser static is refused: repro .scratch/hltime-client), push gate 9/9mre
  • d063dad3calendar mission 008 (A7): Web Push (WIP): lib/push.hl subscriptions + sender clock, faces calPushSave/calPushOff, button subscribes, VAPID tool, tests/push.mjs; instantOf on hl:timemre
  • cf175c80calendar mission 008 (A7): re-vendor Hybriel master 0e3c9830 (bin 9d957fed, plugins whole: hl:crypto Web Push primitives, hl:web sendPush)mre
  • 9bf3c38bcalendar mission 008: re-vendor Hybriel f9833544 (gates old = new); Web Push stopped: hl:crypto half missing on mastermre
  • 186f969bcalendar mission 007: signed-in gate for the first-pointer race (fails on 3c5604f), README theme section, reportmre
  • ba9b4955calendar mission 006: first pointer event no longer re-runs the month (stale overwrite race), gate check, e2e settings cleanup, reportmre
  • bd730759calendar mission 006: theme move (WIP): brief, report, LOG, STATUSmre
  • b117b153calendar mission 006 WIP: reminder row fields keep 44 px; e2e script flagsmre
  • 53e3b0debrowser gate: Log out through the user menu, theme colour rgb(15, 20, 25)mre
  • 90bf9e2ecalendar mission 006 WIP: theme dbe3de7, theme shell (AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst), styles cut to the app's own rules, check-theme gate, e2e toolsmre
  • 3c5604f9identkit: refuse a taken ident port, cold-start deadline, abort on dead ident, clear no-code error (as notes)mre
  • 4996bbe7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre