gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita06975f9a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmrea06975f9/plugins/mpackdb/mpackdb.zig

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

Branches

Latest commits

  • a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
  • 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
  • ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
  • 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
  • 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
  • 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
  • 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
  • d9e977f0reports/MG-mobile.md, LOGMG
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre
  • da6b20fcgitoria SG: security audit fixes (uploadMax 0, Secure cookie on https, session rotation at login, nosniff on function routes, no identity in page data) + tests/security.mjs gate + reportmre
  • f98c981fgitoria B1: report wordingmre
  • c6364cedgitoria B1: compact Markdown blocks (one kind flag per block/span, empty and false fields omitted); same rendered HTML, page values -67%mre