gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitd25bd14ad25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemred25bd14a/plugins/mpackdb/mpackdb.zig

28.0 KB

  1. // hl:mpackdb plugin — native shared library (mission 066)
  2. // Zig port of mpackdb v1.0.7 (MessagePack DB with binary-search indexes).
  3. //
  4. // Layout:
  5. // msgpack.zig — MessagePack codec (msgpackr-compatible, see D12)
  6. // engine.zig — DB engine (MPackDB/IndexManager semantics)
  7. // mpackdb.zig — this file: plugin ABI surface
  8. //
  9. // Exports:
  10. // hl_mpackdb_open(path, primaryKey, indexes, compact) → handle
  11. // handle ops: insert(record) / find_all() / find_pk(v) /
  12. // find_index(field, v) / find_range(field, from, to) /
  13. // delete_pk(v) / update_pk(v, record) / count() /
  14. // compact() / persist() / last_error() / pk_name()
  15. //
  16. // The `hl:mpackdb` .hl surface (MPackDB.hl, cursor.hl, server.hl) is the public
  17. // API; these ops are its transport.
  18. //
  19. // Cursors materialize matches eagerly into a per-iterator arena; the runtime
  20. // deep-copies each record on next(), and the arena is freed at iterator deinit.
  21. const std = @import("std");
  22. const api = @import("plugin_api");
  23. pub const msgpack = @import("msgpack.zig");
  24. pub const engine = @import("engine.zig");
  25. const HlValue = api.HlValue;
  26. const HlObject = api.HlObject;
  27. const HlField = api.HlField;
  28. const HlIterator = api.HlIterator;
  29. const HlHandle = api.HlHandle;
  30. const HlString = api.HlString;
  31. // the plugins' allocator (plugin_api.zig): a DebugAllocator here mapped and unmapped every
  32. // buffer of a page or more, which the per-operation buffers made a syscall pair per call
  33. const gpa = api.allocator;
  34. fn hlStr(comptime s: []const u8) HlString {
  35. return .{ .ptr = s.ptr, .len = s.len };
  36. }
  37. // =========================================================================
  38. // Path resolution (mission 077, 074 GAP 9)
  39. //
  40. // CONTRACT — the same one hl:fs got in mission 068: a relative db path resolves
  41. // against the MAIN SCRIPT's directory, not the process CWD. `cd /tmp && hybriel
  42. // /srv/app/main.hl` must find /srv/app's database, not create a second one in
  43. // /tmp. Absolute paths are used as-is. The runtime injects the directory through
  44. // the optional plugin hook hl_mpackdb_set_script_dir right after dlopen.
  45. // =========================================================================
  46. var script_dir: ?[]u8 = null;
  47. export fn hl_mpackdb_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  48. if (script_dir) |old| gpa.free(old);
  49. script_dir = gpa.dupe(u8, ptr[0..len]) catch null;
  50. }
  51. /// Resolve a (possibly relative) db path against the script dir. The returned
  52. /// slice is gpa-allocated; caller frees.
  53. fn resolvePath(path: []const u8) ?[]u8 {
  54. if (path.len == 0 or path[0] == '/') return gpa.dupe(u8, path) catch null;
  55. if (script_dir) |sd| return std.fmt.allocPrint(gpa, "{s}/{s}", .{ sd, path }) catch null;
  56. return gpa.dupe(u8, path) catch null;
  57. }
  58. // =========================================================================
  59. // HlValue ⇄ msgpack.Value conversion
  60. // =========================================================================
  61. /// AN EMPTY LIST is marked by its `fields` address (ticket #58) — the runtime's
  62. /// contract, stated in native/src/plugin_loader.zig beside the same constant. Zero
  63. /// fields alone read back as an empty hybrid, and `tags = []` was stored as a map.
  64. const EMPTY_LIST_FIELDS: [*]HlField = @ptrFromInt(0x4C49_5354_0000_0008);
  65. fn isEmptyList(obj: *const HlObject) bool {
  66. return obj.field_count == 0 and obj.fields == EMPTY_LIST_FIELDS;
  67. }
  68. /// Hybriel value (as HlObject tree) → msgpack value, allocated in `arena`.
  69. /// An HlObject whose keys are exactly the sequence "0".."n-1" (in order)
  70. /// becomes a msgpack array; everything else becomes a map. Hybriel null and
  71. /// undefined both arrive as hl_null → msgpack nil.
  72. fn hlToMsgpack(arena: std.mem.Allocator, v: HlValue) msgpack.Value {
  73. switch (v.type) {
  74. .hl_null => return .nil,
  75. .hl_bool => return .{ .boolean = v.data.boolean },
  76. .hl_number => return .{ .number = v.data.number },
  77. .hl_string => {
  78. const s = v.data.string.ptr[0..v.data.string.len];
  79. const copy = arena.dupe(u8, s) catch return .nil;
  80. return .{ .str = copy };
  81. },
  82. .hl_object => {
  83. const obj = v.data.object;
  84. const fields = obj.fields[0..obj.field_count];
  85. // strict numeric sequence "0".."n-1" → array; an empty list carries its
  86. // mark (ticket #58), or `tags = []` was stored as an empty map
  87. var is_array = fields.len > 0 or isEmptyList(obj);
  88. for (fields, 0..) |f, i| {
  89. const k = f.key.ptr[0..f.key.len];
  90. var buf: [20]u8 = undefined;
  91. const expect = std.fmt.bufPrint(&buf, "{d}", .{i}) catch "";
  92. if (!std.mem.eql(u8, k, expect)) {
  93. is_array = false;
  94. break;
  95. }
  96. }
  97. if (is_array) {
  98. const items = arena.alloc(msgpack.Value, fields.len) catch return .nil;
  99. for (fields, 0..) |f, i| items[i] = hlToMsgpack(arena, f.value);
  100. return .{ .array = items };
  101. }
  102. const entries = arena.alloc(msgpack.Entry, fields.len) catch return .nil;
  103. for (fields, 0..) |f, i| {
  104. const k = arena.dupe(u8, f.key.ptr[0..f.key.len]) catch return .nil;
  105. entries[i] = .{ .key = .{ .str = k }, .value = hlToMsgpack(arena, f.value) };
  106. }
  107. return .{ .map = entries };
  108. },
  109. else => return .nil,
  110. }
  111. }
  112. /// msgpack value → HlValue tree allocated in `arena` (no deinit hooks — the
  113. /// runtime deep-copies immediately; the arena outlives the call).
  114. fn msgpackToHl(arena: std.mem.Allocator, v: msgpack.Value) HlValue {
  115. switch (v) {
  116. .nil, .undef => return api.makeNull(),
  117. .boolean => |b| return api.makeBool(b),
  118. .number => |n| return api.makeNumber(n),
  119. .str => |s| return api.makeString(s),
  120. .bin => |b| return api.makeString(b),
  121. .array => |items| {
  122. const fields = arena.alloc(HlField, items.len) catch return api.makeNull();
  123. for (items, 0..) |it, i| {
  124. var buf: [20]u8 = undefined;
  125. const k = std.fmt.bufPrint(&buf, "{d}", .{i}) catch "";
  126. const key = arena.dupe(u8, k) catch return api.makeNull();
  127. fields[i] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = msgpackToHl(arena, it) };
  128. }
  129. const obj = arena.create(HlObject) catch return api.makeNull();
  130. obj.* = .{ .fields = if (items.len == 0) EMPTY_LIST_FIELDS else fields.ptr, .field_count = fields.len, .deinit_fn = null };
  131. return api.makeObject(obj);
  132. },
  133. .map => |entries| {
  134. const fields = arena.alloc(HlField, entries.len) catch return api.makeNull();
  135. var n: usize = 0;
  136. for (entries) |e| {
  137. const key: []const u8 = switch (e.key) {
  138. .str => |s| s,
  139. .number => |num| blk: {
  140. var buf: [40]u8 = undefined;
  141. const k = engine.jsNumFmt(&buf, num);
  142. break :blk arena.dupe(u8, k) catch continue;
  143. },
  144. else => continue,
  145. };
  146. fields[n] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = msgpackToHl(arena, e.value) };
  147. n += 1;
  148. }
  149. const obj = arena.create(HlObject) catch return api.makeNull();
  150. obj.* = .{ .fields = fields.ptr, .field_count = n, .deinit_fn = null };
  151. return api.makeObject(obj);
  152. },
  153. .ext => {
  154. if (v.timestampMs()) |ms| return api.makeNumber(ms);
  155. return api.makeNull();
  156. },
  157. }
  158. }
  159. fn hlKey(v: HlValue) ?engine.Key {
  160. return switch (v.type) {
  161. .hl_number => .{ .num = v.data.number },
  162. .hl_string => .{ .str = v.data.string.ptr[0..v.data.string.len] },
  163. else => null,
  164. };
  165. }
  166. // =========================================================================
  167. // Record iterator (eagerly materialized)
  168. // =========================================================================
  169. const RecIterState = struct {
  170. // THE ITERATOR LIVES IN ITS STATE (the emit soak, 2026-10-02): the runtime frees
  171. // only its own wrapper and hands deinit the context, so a separately created
  172. // HlIterator was never freed — 40 bytes per find/range/fetch, for good.
  173. iter: HlIterator = undefined,
  174. arena_state: std.heap.ArenaAllocator,
  175. records: []msgpack.Value = &.{},
  176. idx: usize = 0,
  177. };
  178. fn recIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  179. const state: *RecIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  180. if (state.idx >= state.records.len) {
  181. // THE LAST RECORD IS ALREADY COPIED OUT: the arena goes now, not when the
  182. // collector sweeps the iterator, which counts none of these bytes and so can
  183. // leave thousands of drained lookups' records waiting (hybriel#126, notes)
  184. state.records = &.{};
  185. _ = state.arena_state.reset(.free_all);
  186. return api.makeNull();
  187. }
  188. const v = state.records[state.idx];
  189. state.idx += 1;
  190. return msgpackToHl(state.arena_state.allocator(), v);
  191. }
  192. fn recIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  193. const state: *RecIterState = @ptrCast(@alignCast(ctx orelse return));
  194. state.arena_state.deinit();
  195. gpa.destroy(state);
  196. }
  197. fn makeRecordIterator(records: []msgpack.Value, arena_state: std.heap.ArenaAllocator) HlValue {
  198. const state = gpa.create(RecIterState) catch return api.makeNull();
  199. state.* = .{ .arena_state = arena_state, .records = records };
  200. state.iter = .{
  201. .context = @ptrCast(state),
  202. .next_fn = &recIterNext,
  203. .deinit_fn = &recIterDeinitOuter,
  204. };
  205. return api.makeIterator(&state.iter);
  206. }
  207. // The runtime's IterWrapper deinit calls iter.deinit_fn then frees its own
  208. // wrapper — but the HlIterator struct itself is ours to free.
  209. fn recIterDeinitOuter(ctx: ?*anyopaque) callconv(.c) void {
  210. recIterDeinit(ctx);
  211. }
  212. // =========================================================================
  213. // DB handle
  214. // =========================================================================
  215. //
  216. // Process-wide table registry (ticket #110). Within one process, a table
  217. // path has ONE open engine.Db, shared by every hl_mpackdb_open() on it —
  218. // whatever module instance or realm calls it. `hl:mpackdb`'s .so is loaded
  219. // once and mapped once by the dynamic linker no matter how many realms
  220. // dlopen it (same path, same mapping), so these are already process-wide
  221. // statics; the registry just gives multiple opens of the same table a
  222. // single Db to share instead of a fresh one each time. A single realm's
  223. // event loop drives every call here — mpackdb has never been thread-safe —
  224. // so no mutex.
  225. //
  226. // The file is never compacted or rewritten while a handle on it is live:
  227. // only the FIRST open of a path in this process actually runs
  228. // engine.Db.open (and so is the only one that can compact-on-open, per
  229. // ticket #21's existing rule); every later open of the same path reuses
  230. // that live Db untouched, and its own primaryKey/indexes/compact args are
  231. // ignored — the table's schema was fixed by the first opener. Compaction
  232. // happens only when asked for explicitly (compactNow()) or when the LAST
  233. // handle on a path closes — unless the first opener passed compact=false.
  234. const SharedDb = struct {
  235. db: *engine.Db,
  236. key: []const u8, // owned; also the registry's stored key for this entry
  237. refcount: usize,
  238. };
  239. var registry: std.StringHashMapUnmanaged(*SharedDb) = .empty;
  240. fn acquireShared(path: []const u8, opts: engine.OpenOptions) ?*SharedDb {
  241. const key = engine.tableKey(gpa, path) catch return null;
  242. if (registry.get(key)) |existing| {
  243. gpa.free(key);
  244. existing.refcount += 1;
  245. return existing;
  246. }
  247. const db = engine.Db.open(gpa, path, opts) catch |e| {
  248. std.debug.print("mpackdb plugin: open failed: {s}\n", .{@errorName(e)});
  249. gpa.free(key);
  250. return null;
  251. };
  252. const shared = gpa.create(SharedDb) catch {
  253. db.close();
  254. gpa.free(key);
  255. return null;
  256. };
  257. shared.* = .{ .db = db, .key = key, .refcount = 1 };
  258. registry.put(gpa, key, shared) catch {
  259. db.close();
  260. gpa.destroy(shared);
  261. gpa.free(key);
  262. return null;
  263. };
  264. return shared;
  265. }
  266. /// Drop this handle's reference. On the LAST reference: compact away any
  267. /// tombstones (ticket #110 — the one moment compaction may run implicitly, and
  268. /// only when the first opener did not say compact=false, ticket #192) and
  269. /// close for real.
  270. fn releaseShared(shared: *SharedDb) void {
  271. shared.refcount -= 1;
  272. if (shared.refcount > 0) return;
  273. _ = registry.remove(shared.key);
  274. // compact=false of the opener is honoured here too (ticket #192): the tracker
  275. // opens its stores with compact=false and a stop shrank shows.mpack 1.12 GB -> 424 MB.
  276. if (shared.db.compact_on_open and shared.db.deleted.items.len > 0) {
  277. shared.db.compact() catch |e| {
  278. std.debug.print("mpackdb plugin: close-compact failed: {s}\n", .{@errorName(e)});
  279. };
  280. }
  281. shared.db.close();
  282. gpa.free(shared.key);
  283. gpa.destroy(shared);
  284. }
  285. const DbState = struct {
  286. shared: *SharedDb,
  287. };
  288. export fn hl_mpackdb_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  289. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  290. const raw_path = argv[0].data.string.ptr[0..argv[0].data.string.len];
  291. // mission 077: script-relative, like every other path in Hybriel.
  292. const path = resolvePath(raw_path) orelse return api.makeNull();
  293. defer gpa.free(path);
  294. var opts = engine.OpenOptions{};
  295. if (argc > 1 and argv[1].type == .hl_string and argv[1].data.string.len > 0) {
  296. opts.primary_key = argv[1].data.string.ptr[0..argv[1].data.string.len];
  297. }
  298. var index_names: [64][]const u8 = undefined;
  299. var index_count: usize = 0;
  300. if (argc > 2 and argv[2].type == .hl_object) {
  301. const obj = argv[2].data.object;
  302. for (obj.fields[0..obj.field_count]) |f| {
  303. if (f.value.type != .hl_string) continue;
  304. if (index_count >= index_names.len) break;
  305. index_names[index_count] = f.value.data.string.ptr[0..f.value.data.string.len];
  306. index_count += 1;
  307. }
  308. }
  309. opts.indexes = index_names[0..index_count];
  310. if (argc > 3 and argv[3].type == .hl_bool) {
  311. opts.compact = argv[3].data.boolean;
  312. }
  313. const shared = acquireShared(path, opts) orelse return api.makeNull();
  314. const state = gpa.create(DbState) catch {
  315. releaseShared(shared);
  316. return api.makeNull();
  317. };
  318. state.* = .{ .shared = shared };
  319. const handle = gpa.create(HlHandle) catch {
  320. releaseShared(shared);
  321. gpa.destroy(state);
  322. return api.makeNull();
  323. };
  324. handle.* = .{
  325. .context = @ptrCast(state),
  326. .call_fn = &handleCall,
  327. .close_fn = &handleClose,
  328. .type_name = hlStr("MPackDB"),
  329. };
  330. return api.makeHandle(handle);
  331. }
  332. fn errDeinit(val: *HlValue) callconv(.c) void {
  333. if (val.type == .hl_error) {
  334. const s = val.data.string;
  335. gpa.free(@constCast(s.ptr[0..s.len]));
  336. }
  337. }
  338. /// mission 077 (074 GAP 10): querying a field that carries no index is a
  339. /// MISTAKE, not an empty result — mpackdb only answers through binary-searched
  340. /// indexes, so `[]` was indistinguishable from "no such record" and hid the
  341. /// missing declaration. The message names the field, the op and every index the
  342. /// db was actually opened with (insertion order: primary key first).
  343. fn makeNoIndexError(db: *engine.Db, op: []const u8, field: []const u8) HlValue {
  344. var list: std.ArrayList(u8) = .empty;
  345. defer list.deinit(gpa);
  346. for (db.idx.keys()) |k| {
  347. if (list.items.len > 0) list.appendSlice(gpa, ", ") catch {};
  348. list.append(gpa, '\'') catch {};
  349. list.appendSlice(gpa, k) catch {};
  350. list.append(gpa, '\'') catch {};
  351. }
  352. const declared = if (list.items.len == 0) "none" else list.items;
  353. const msg = std.fmt.allocPrint(
  354. gpa,
  355. "mpackdb.{s}: no index on field '{s}' — this db is indexed on [{s}]; every query goes through an index (declare it in `indexes` when opening, or query the primary key)",
  356. .{ op, field, declared },
  357. ) catch return api.makeError("mpackdb: no index on that field");
  358. var v = api.makeError(msg);
  359. v.deinit_fn = &errDeinit;
  360. return v;
  361. }
  362. fn handleClose(ctx: ?*anyopaque) callconv(.c) void {
  363. const state: *DbState = @ptrCast(@alignCast(ctx orelse return));
  364. releaseShared(state.shared);
  365. gpa.destroy(state);
  366. }
  367. fn pkStringDeinit(val: *HlValue) callconv(.c) void {
  368. if (val.type == .hl_string) {
  369. const s = val.data.string;
  370. gpa.free(@constCast(s.ptr[0..s.len]));
  371. }
  372. }
  373. fn handleCall(ctx: ?*anyopaque, op: HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  374. const state: *DbState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  375. const db = state.shared.db;
  376. const method = op.ptr[0..op.len];
  377. if (std.mem.eql(u8, method, "insert")) {
  378. if (argc < 1 or argv[0].type != .hl_object) return api.makeNull();
  379. var arena_state = std.heap.ArenaAllocator.init(gpa);
  380. defer arena_state.deinit();
  381. const arena = arena_state.allocator();
  382. const rec = hlToMsgpack(arena, argv[0]);
  383. if (rec != .map) return api.makeNull();
  384. const res = db.insert(arena, rec, false) catch |e| {
  385. if (e != error.DuplicateKey) {
  386. std.debug.print("mpackdb plugin: insert failed: {s}\n", .{@errorName(e)});
  387. db.last_error = std.fmt.bufPrint(&db.last_error_buf, "insert failed: {s}", .{@errorName(e)}) catch "insert failed";
  388. }
  389. return api.makeNull();
  390. };
  391. switch (res) {
  392. .pk_num => |n| return api.makeNumber(n),
  393. .pk_str => |s| {
  394. const copy = gpa.dupe(u8, s) catch return api.makeNull();
  395. var out = api.makeString(copy);
  396. out.deinit_fn = &pkStringDeinit;
  397. return out;
  398. },
  399. .record => return api.makeBool(true),
  400. }
  401. }
  402. if (std.mem.eql(u8, method, "find_all")) {
  403. var arena_state = std.heap.ArenaAllocator.init(gpa);
  404. const arena = arena_state.allocator();
  405. var records: std.ArrayList(msgpack.Value) = .empty;
  406. db.refresh();
  407. var scanner = engine.Db.Scanner.init(db, arena, true);
  408. while (true) {
  409. const maybe = scanner.next(arena) catch break;
  410. const rec = maybe orelse break;
  411. records.append(arena, rec.value) catch break;
  412. }
  413. scanner.deinit();
  414. const slice = records.toOwnedSlice(arena) catch &.{};
  415. return makeRecordIterator(@constCast(slice), arena_state);
  416. }
  417. if (std.mem.eql(u8, method, "find_pk")) {
  418. if (argc < 1) return api.makeNull();
  419. const key = hlKey(argv[0]) orelse return api.makeNull();
  420. var arena_state = std.heap.ArenaAllocator.init(gpa);
  421. const arena = arena_state.allocator();
  422. var locs: std.ArrayList(engine.Loc) = .empty;
  423. db.findPkLocs(arena, key, &locs) catch {
  424. arena_state.deinit();
  425. return api.makeNull();
  426. };
  427. return locsToIterator(db, arena_state, locs.items);
  428. }
  429. if (std.mem.eql(u8, method, "find_index")) {
  430. if (argc < 2 or argv[0].type != .hl_string) return api.makeNull();
  431. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  432. const key = hlKey(argv[1]) orelse return api.makeNull();
  433. var arena_state = std.heap.ArenaAllocator.init(gpa);
  434. const arena = arena_state.allocator();
  435. var locs: std.ArrayList(engine.Loc) = .empty;
  436. db.findIndexLocs(arena, field, key, &locs) catch |e| {
  437. arena_state.deinit();
  438. if (e == error.NoSuchIndex) return makeNoIndexError(db, "find", field);
  439. return api.makeNull();
  440. };
  441. return locsToIterator(db, arena_state, locs.items);
  442. }
  443. if (std.mem.eql(u8, method, "find_range")) {
  444. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  445. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  446. const from: ?engine.Key = if (argc > 1) hlKey(argv[1]) else null;
  447. const to: ?engine.Key = if (argc > 2) hlKey(argv[2]) else null;
  448. var arena_state = std.heap.ArenaAllocator.init(gpa);
  449. const arena = arena_state.allocator();
  450. var locs: std.ArrayList(engine.Loc) = .empty;
  451. db.findRangeLocs(arena, field, from, to, &locs) catch |e| {
  452. arena_state.deinit();
  453. if (e == error.NoSuchIndex) return makeNoIndexError(db, "range", field);
  454. return api.makeNull();
  455. };
  456. return locsToIterator(db, arena_state, locs.items);
  457. }
  458. if (std.mem.eql(u8, method, "delete_pk")) {
  459. if (argc < 1) return api.makeNull();
  460. const key = hlKey(argv[0]) orelse return api.makeNull();
  461. var arena_state = std.heap.ArenaAllocator.init(gpa);
  462. defer arena_state.deinit();
  463. const arena = arena_state.allocator();
  464. var deleted: std.ArrayList(msgpack.Value) = .empty;
  465. const n = db.deletePk(arena, key, &deleted) catch |e| {
  466. std.debug.print("mpackdb plugin: delete failed: {s}\n", .{@errorName(e)});
  467. return api.makeNull();
  468. };
  469. return api.makeNumber(@floatFromInt(n));
  470. }
  471. if (std.mem.eql(u8, method, "update_pk")) {
  472. if (argc < 2 or argv[1].type != .hl_object) return api.makeNull();
  473. const key = hlKey(argv[0]) orelse return api.makeNull();
  474. var arena_state = std.heap.ArenaAllocator.init(gpa);
  475. defer arena_state.deinit();
  476. const arena = arena_state.allocator();
  477. const rec = hlToMsgpack(arena, argv[1]);
  478. if (rec != .map) return api.makeNull();
  479. // THE KEY COMES FROM THE ARGUMENT (ticket #171, as in the JS mpackdb): a record
  480. // that does not carry the primary key gets it from `key`, so update never
  481. // refuses or silently drops a record for want of it.
  482. var full = rec;
  483. if (db.pk) |p| {
  484. var carried = false;
  485. for (rec.map) |en| {
  486. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) {
  487. carried = en.value != .nil and en.value != .undef;
  488. break;
  489. }
  490. }
  491. if (!carried) {
  492. var list: std.ArrayList(msgpack.Entry) = .empty;
  493. for (rec.map) |en| {
  494. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) continue;
  495. list.append(arena, en) catch return api.makeNull();
  496. }
  497. const kv: msgpack.Value = switch (key) {
  498. .num => |x| .{ .number = x },
  499. .str => |x| .{ .str = x },
  500. };
  501. list.append(arena, .{ .key = .{ .str = p }, .value = kv }) catch return api.makeNull();
  502. full = .{ .map = list.items };
  503. }
  504. }
  505. const n = db.updatePk(arena, key, full) catch |e| {
  506. if (e == error.RecordLacksPrimaryKey) {
  507. db.last_error = std.fmt.bufPrint(&db.last_error_buf, "update refused: the record carries no '{s}' (update's record must carry the primary key)", .{db.pk orelse ""}) catch "update refused: the record carries no primary key";
  508. return api.makeNull();
  509. }
  510. if (e != error.DuplicateKey) {
  511. std.debug.print("mpackdb plugin: update failed: {s}\n", .{@errorName(e)});
  512. }
  513. return api.makeNull();
  514. };
  515. return api.makeNumber(@floatFromInt(n));
  516. }
  517. if (std.mem.eql(u8, method, "count")) {
  518. var arena_state = std.heap.ArenaAllocator.init(gpa);
  519. defer arena_state.deinit();
  520. const arena = arena_state.allocator();
  521. db.refresh();
  522. var scanner = engine.Db.Scanner.init(db, arena, true);
  523. defer scanner.deinit();
  524. var n: usize = 0;
  525. while (true) {
  526. const maybe = scanner.next(arena) catch break;
  527. if (maybe == null) break;
  528. n += 1;
  529. }
  530. return api.makeNumber(@floatFromInt(n));
  531. }
  532. if (std.mem.eql(u8, method, "compact")) {
  533. db.compact() catch |e| {
  534. std.debug.print("mpackdb plugin: compact failed: {s}\n", .{@errorName(e)});
  535. };
  536. return api.makeNull();
  537. }
  538. if (std.mem.eql(u8, method, "persist")) {
  539. db.persistNow() catch |e| {
  540. std.debug.print("mpackdb plugin: persist failed: {s}\n", .{@errorName(e)});
  541. };
  542. return api.makeNull();
  543. }
  544. if (std.mem.eql(u8, method, "last_error")) {
  545. return api.makeString(db.last_error);
  546. }
  547. // The primary key field name with its */@/! prefixes stripped — the .hl
  548. // wrapper needs the bare name to route find(field, …) to find_pk.
  549. if (std.mem.eql(u8, method, "pk_name")) {
  550. const p = db.pk orelse return api.makeNull();
  551. return api.makeString(p);
  552. }
  553. return api.makeNull();
  554. }
  555. /// Decode records at `locs` into the iterator arena and wrap them.
  556. fn locsToIterator(db: *engine.Db, arena_state: std.heap.ArenaAllocator, locs: []const engine.Loc) HlValue {
  557. var st = arena_state;
  558. const arena = st.allocator();
  559. var records: std.ArrayList(msgpack.Value) = .empty;
  560. for (locs) |loc| {
  561. const rec = db.readAt(arena, loc) catch continue;
  562. records.append(arena, rec) catch break;
  563. }
  564. const slice = records.toOwnedSlice(arena) catch &.{};
  565. return makeRecordIterator(@constCast(slice), st);
  566. }
  567. fn dataIdSize(path: [:0]const u8) struct { ino: u64, size: u64 } {
  568. const linux = std.os.linux;
  569. var stx: linux.Statx = undefined;
  570. std.debug.assert(linux.statx(linux.AT.FDCWD, path, 0, linux.STATX.BASIC_STATS, &stx) == 0);
  571. return .{ .ino = stx.ino, .size = stx.size };
  572. }
  573. fn closeKeepsFile(compact: bool, name: []const u8) !struct { before: @TypeOf(dataIdSize("")), after: @TypeOf(dataIdSize("")) } {
  574. const testing = std.testing;
  575. const dir: []const u8 = if (std.c.getenv("TMPDIR")) |t| std.mem.span(t) else "/tmp";
  576. var buf: [512]u8 = undefined;
  577. const base = try std.fmt.bufPrint(&buf, "{s}/mpackdb-192-{d}-{s}", .{ dir, std.os.linux.getpid(), name });
  578. var pbuf: [520]u8 = undefined;
  579. const data = try std.fmt.bufPrintZ(&pbuf, "{s}.mpack", .{base});
  580. const suffixes = [_][]const u8{ ".mpack", ".meta.json", ".idxstate.json", ".lock", ".flock", ".id.txt" };
  581. for (suffixes) |sf| {
  582. var b: [530]u8 = undefined;
  583. const f = try std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf });
  584. _ = std.os.linux.unlink(f);
  585. }
  586. defer for (suffixes) |sf| {
  587. var b: [530]u8 = undefined;
  588. const f = std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf }) catch continue;
  589. _ = std.os.linux.unlink(f);
  590. };
  591. var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
  592. defer arena_state.deinit();
  593. const arena = arena_state.allocator();
  594. // first process life: write rows and tombstones, close (compact=false: nothing may compact)
  595. {
  596. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = false }) orelse return error.OpenFailed;
  597. for (0..20) |i| {
  598. const entries = try arena.alloc(msgpack.Entry, 1);
  599. entries[0] = .{ .key = .{ .str = "n" }, .value = .{ .number = @floatFromInt(i) } };
  600. _ = try sh.db.insert(arena, .{ .map = entries }, false);
  601. }
  602. releaseShared(sh);
  603. }
  604. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = compact }) orelse return error.OpenFailed;
  605. const before = dataIdSize(data);
  606. var gone: std.ArrayList(msgpack.Value) = .empty;
  607. for (1..11) |i| _ = try sh.db.deletePk(arena, .{ .num = @floatFromInt(i) }, &gone);
  608. releaseShared(sh);
  609. return .{ .before = before, .after = dataIdSize(data) };
  610. }
  611. test "#192: closing the last handle of a compact=false table leaves the data file alone" {
  612. const r = try closeKeepsFile(false, "off");
  613. try std.testing.expectEqual(r.before.ino, r.after.ino);
  614. try std.testing.expectEqual(r.before.size, r.after.size);
  615. }
  616. test "#192: closing the last handle of a compact=true table still compacts" {
  617. const r = try closeKeepsFile(true, "on");
  618. try std.testing.expect(r.after.size < r.before.size);
  619. }
  620. test {
  621. _ = msgpack;
  622. _ = engine;
  623. }

Branches

Latest commits

  • d25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemre
  • 633ee210mission 044: sliced table scans (slices.hl, pk-range slices) for the adult/kind/status/art/credits/details-repair queuesmre
  • 6648ba44mission 042: real-browser E2E on ce6f2e0a re-vendor 69/0 at 390 + 1280mre
  • 3ed3a0efmission 042: gates old/new equal (browser #41 route-table regex accepts unescaped hl:web output), real-data TTFB, E2E blocked by lisbeth lockmre
  • d5b61e90LOG 042mre
  • 4acdbaccmission 042: memory comparison old vs ce6f2e0a (stopped: warm VmHWM higher), reportmre
  • d0f620d6mission 042: re-vendor Hybriel ce6f2e0a (plugins incl. mpackdb; bin runtime built from the same archive, git-ignored), compact=false keptmre
  • 5bd14e12mission 040: theme 76f99f6 gates + E2E green; 44 px fixes (skeleton row, type-word, genre-link/pill); README, reportmre
  • 77cfa45cmission 040: partial report (theme/modal/pagination re-copied, tilelist onPage, 44 px taps; gates new + E2E pending)mre
  • 4b14822fe2e-theme: menu marker by colourmre
  • 09780f4emission 040 WIP: theme, modal, pagination, tokens re-copied from layouts 76f99f6; tilelist uses onPage; tap sizes 44 px for tracker's own small buttons; tests/e2e-theme.mjsmre
  • fb80bb8chotfix: open the 5 show stores without compaction (compact = false) — compact-on-open left another handle on stale offsets, every read gave a bare Number (hybriel mpackdb refresh after a shrink); live down 2026-10-20 05:11mre
  • e00d3bf7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • a8c7f234tracker#36 (mission 039): tools/tmdb-check.hl survives a dropped connection (on Error, asked again, failed lines) and resumes with --from N; tests/tmdbcheck.mjs 6/6 against a fake TMDBmre
  • 9c230516mission brief w39mre
  • 3609121dmission 038 docs + report (quota stop): README/kinds.md for #43 #42 #36, STATUS, LOG; HEAD browser gate 374/8 in the in-app daily run block (hour-boundary suspected, rerun pending), other gates green; #36 real run needs TMDB_READ_TOKENmre
  • a5d06e79tracker#36 (mission 038): tools/tmdb-check.hl + lib/tmdbcheck.hl — every live migrated title's migrated title + year against its TMDB entry (one GET /movie|tv/<id>?append_to_response=alternative_titles, 260 ms apart, passing failures asked once more): ok / ambiguous (one of title, year disagrees) / clear (both, or 404); read-only; token only from TMDB_READ_TOKEN; --stored = a title-only preview from the TMDB names already stored (no request). Tested against a fake TMDB (.scratch/w38/t36): 7 titles, 3 ok, 2 ambiguous, 2 clear, data unchangedmre
  • 982554f3tracker#42 (mission 038): series pages — an unknown slug no longer scans every title (lib/shows.hl showBySlug: the slug map only; new titles are noted by refreshTitleCaches, which both title puts already reach): 10.7–15.7 s → 0.013 s on the real copy (the one-request-at-a-time server was blocked meanwhile); cast/crew rows take name + slug from a person-link cache (personLinkOf) instead of whole person records (SNL: 303 cast with 4,761 credits, ~49k allocations per render) — allocations per series page −5…−40 %; HTML of 20 pages identical to beforemre
  • 4586b6e3docker-compose: init: true (hybriel#156)mre
  • 085c2e5ftracker#43 (mission 038): TVmaze's type makes Variety / Talk Show / Game Show / Reality / News / Panel Show / Award Show / Sports titles Shows (TMDB calls Saturday Night Live UK Scripted) — the #43 part of parked w37-wip a79c8c1 only (no re-vendor, no cache volume): tvmazeType stored by the sync and the TVmaze status backfill (asks every series with a TVmaze id once), kindOfTitle/kindWithTvmaze, tools/tvmaze-types.hl, gate fixture Variety Gate Series; start waits 150 smre