gitoria

layouts

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit137303c5137303c5MainMenu marks the current page from the route (hybriel#197, server-rendered); current prop/item.current stay as fallback; tracker demo drops current; gate: SSR marker; docsmre137303c5/plugins/mpackdb/engine.zig

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

Only the first lines are shown.

Branches

Latest commits

  • 137303c5MainMenu marks the current page from the route (hybriel#197, server-rendered); current prop/item.current stay as fallback; tracker demo drops current; gate: SSR marker; docsmre
  • 9325b403Re-vendor Hybriel to master 7f13a82f (hl:web batch 2: #190 #193 #197 #194 named regions); plugins whole, bin/hybriel static build (git-ignored)mre
  • b31dc74dusage: calendar (theme 76f99f6-era ContentFirst, user menu, ☰ menu) and tracker (theme 76f99f6, modal + pagination current, own current marker until hybriel#197) rowsmre
  • 8a3d5d40Mission 010: brief, report, LOG, STATUSmre
  • a56abf1fSync components to components.hybriel 3794c59 (MdEditor real-key fixes); showcase real-key check on the md-editor pagemre
  • 76f99f64E2E in lisbeth's Chrome for the menu's current page (mission 009): tests/e2e-menu-current.mjs, reportmre
  • 159b1d53MainMenu/Sidebar: current page marked beyond colour, count badge, item current flag; gate 300/0 (mission 009)mre
  • 0573eed3usage: notes + tickets on MdEditor (md-editor.js retired), gitoria on theme dbe3de7, tracker theme oldermre
  • 78478f6eSync showcase to components.hybriel 1442e58: pick-mode page, comments attach, md-editor rows/files off; gates 285/0mre
  • dbe3de79Display bugs from a real Chrome walk (mission 007): Settings page and in-shell doc reader instead of raw .md links, closed phone search hidden whatever a page says, /elements form rules scoped, three-pane danger contrast; display audit gate (132 -> 244 checks), walk + Settings e2e toolsmre
  • 1875a051Theme: 44 px tap targets mobile first (layoutTap), 16 px fields, desktop denser only in @media 60rem; 390 px tap audit + gate checks (mission 006)mre
  • 3d4f8e19Sync showcase to components.hybriel 9db927d: comments and files-upload pages, pagination onPage, md-editor readonly, gate 99 checksmre
  • 64d635acmission brief 005mre
  • 0d0fef25paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 2dbe0df5Re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ is git-ignored), compose cache volume + tmpfs /tmp, gate wait 120 s, report 004mre
  • 0adc551emission brief 004mre
  • 1376e905deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • c0fdbf6cdocker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • ecf70665usage: layouts on components a567b57mre
  • 315731efcomponents re-synced to components.hybriel a567b57 (md-editor tables)mre