gitoriaLog in with ident

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain4f47843egate: ticket links use the tickets short URL (/<slug>/<n>, tickets#25)mremain/plugins/mpackdb/mpackdb.zig

23.9 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.
  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 — that's the one moment compaction may run
  268. /// implicitly) and close for real.
  269. fn releaseShared(shared: *SharedDb) void {
  270. shared.refcount -= 1;
  271. if (shared.refcount > 0) return;
  272. _ = registry.remove(shared.key);
  273. if (shared.db.deleted.items.len > 0) {
  274. shared.db.compact() catch |e| {
  275. std.debug.print("mpackdb plugin: close-compact failed: {s}\n", .{@errorName(e)});
  276. };
  277. }
  278. shared.db.close();
  279. gpa.free(shared.key);
  280. gpa.destroy(shared);
  281. }
  282. const DbState = struct {
  283. shared: *SharedDb,
  284. };
  285. export fn hl_mpackdb_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  286. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  287. const raw_path = argv[0].data.string.ptr[0..argv[0].data.string.len];
  288. // mission 077: script-relative, like every other path in Hybriel.
  289. const path = resolvePath(raw_path) orelse return api.makeNull();
  290. defer gpa.free(path);
  291. var opts = engine.OpenOptions{};
  292. if (argc > 1 and argv[1].type == .hl_string and argv[1].data.string.len > 0) {
  293. opts.primary_key = argv[1].data.string.ptr[0..argv[1].data.string.len];
  294. }
  295. var index_names: [64][]const u8 = undefined;
  296. var index_count: usize = 0;
  297. if (argc > 2 and argv[2].type == .hl_object) {
  298. const obj = argv[2].data.object;
  299. for (obj.fields[0..obj.field_count]) |f| {
  300. if (f.value.type != .hl_string) continue;
  301. if (index_count >= index_names.len) break;
  302. index_names[index_count] = f.value.data.string.ptr[0..f.value.data.string.len];
  303. index_count += 1;
  304. }
  305. }
  306. opts.indexes = index_names[0..index_count];
  307. if (argc > 3 and argv[3].type == .hl_bool) {
  308. opts.compact = argv[3].data.boolean;
  309. }
  310. const shared = acquireShared(path, opts) orelse return api.makeNull();
  311. const state = gpa.create(DbState) catch {
  312. releaseShared(shared);
  313. return api.makeNull();
  314. };
  315. state.* = .{ .shared = shared };
  316. const handle = gpa.create(HlHandle) catch {
  317. releaseShared(shared);
  318. gpa.destroy(state);
  319. return api.makeNull();
  320. };
  321. handle.* = .{
  322. .context = @ptrCast(state),
  323. .call_fn = &handleCall,
  324. .close_fn = &handleClose,
  325. .type_name = hlStr("MPackDB"),
  326. };
  327. return api.makeHandle(handle);
  328. }
  329. fn errDeinit(val: *HlValue) callconv(.c) void {
  330. if (val.type == .hl_error) {
  331. const s = val.data.string;
  332. gpa.free(@constCast(s.ptr[0..s.len]));
  333. }
  334. }
  335. /// mission 077 (074 GAP 10): querying a field that carries no index is a
  336. /// MISTAKE, not an empty result — mpackdb only answers through binary-searched
  337. /// indexes, so `[]` was indistinguishable from "no such record" and hid the
  338. /// missing declaration. The message names the field, the op and every index the
  339. /// db was actually opened with (insertion order: primary key first).
  340. fn makeNoIndexError(db: *engine.Db, op: []const u8, field: []const u8) HlValue {
  341. var list: std.ArrayList(u8) = .empty;
  342. defer list.deinit(gpa);
  343. for (db.idx.keys()) |k| {
  344. if (list.items.len > 0) list.appendSlice(gpa, ", ") catch {};
  345. list.append(gpa, '\'') catch {};
  346. list.appendSlice(gpa, k) catch {};
  347. list.append(gpa, '\'') catch {};
  348. }
  349. const declared = if (list.items.len == 0) "none" else list.items;
  350. const msg = std.fmt.allocPrint(
  351. gpa,
  352. "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)",
  353. .{ op, field, declared },
  354. ) catch return api.makeError("mpackdb: no index on that field");
  355. var v = api.makeError(msg);
  356. v.deinit_fn = &errDeinit;
  357. return v;
  358. }
  359. fn handleClose(ctx: ?*anyopaque) callconv(.c) void {
  360. const state: *DbState = @ptrCast(@alignCast(ctx orelse return));
  361. releaseShared(state.shared);
  362. gpa.destroy(state);
  363. }
  364. fn pkStringDeinit(val: *HlValue) callconv(.c) void {
  365. if (val.type == .hl_string) {
  366. const s = val.data.string;
  367. gpa.free(@constCast(s.ptr[0..s.len]));
  368. }
  369. }
  370. fn handleCall(ctx: ?*anyopaque, op: HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  371. const state: *DbState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  372. const db = state.shared.db;
  373. const method = op.ptr[0..op.len];
  374. if (std.mem.eql(u8, method, "insert")) {
  375. if (argc < 1 or argv[0].type != .hl_object) return api.makeNull();
  376. var arena_state = std.heap.ArenaAllocator.init(gpa);
  377. defer arena_state.deinit();
  378. const arena = arena_state.allocator();
  379. const rec = hlToMsgpack(arena, argv[0]);
  380. if (rec != .map) return api.makeNull();
  381. const res = db.insert(arena, rec, false) catch |e| {
  382. if (e != error.DuplicateKey) {
  383. std.debug.print("mpackdb plugin: insert failed: {s}\n", .{@errorName(e)});
  384. db.last_error = std.fmt.bufPrint(&db.last_error_buf, "insert failed: {s}", .{@errorName(e)}) catch "insert failed";
  385. }
  386. return api.makeNull();
  387. };
  388. switch (res) {
  389. .pk_num => |n| return api.makeNumber(n),
  390. .pk_str => |s| {
  391. const copy = gpa.dupe(u8, s) catch return api.makeNull();
  392. var out = api.makeString(copy);
  393. out.deinit_fn = &pkStringDeinit;
  394. return out;
  395. },
  396. .record => return api.makeBool(true),
  397. }
  398. }
  399. if (std.mem.eql(u8, method, "find_all")) {
  400. var arena_state = std.heap.ArenaAllocator.init(gpa);
  401. const arena = arena_state.allocator();
  402. var records: std.ArrayList(msgpack.Value) = .empty;
  403. db.refresh();
  404. var scanner = engine.Db.Scanner.init(db, arena, true);
  405. while (true) {
  406. const maybe = scanner.next(arena) catch break;
  407. const rec = maybe orelse break;
  408. records.append(arena, rec.value) catch break;
  409. }
  410. scanner.deinit();
  411. const slice = records.toOwnedSlice(arena) catch &.{};
  412. return makeRecordIterator(@constCast(slice), arena_state);
  413. }
  414. if (std.mem.eql(u8, method, "find_pk")) {
  415. if (argc < 1) return api.makeNull();
  416. const key = hlKey(argv[0]) orelse return api.makeNull();
  417. var arena_state = std.heap.ArenaAllocator.init(gpa);
  418. const arena = arena_state.allocator();
  419. var locs: std.ArrayList(engine.Loc) = .empty;
  420. db.findPkLocs(arena, key, &locs) catch {
  421. arena_state.deinit();
  422. return api.makeNull();
  423. };
  424. return locsToIterator(db, arena_state, locs.items);
  425. }
  426. if (std.mem.eql(u8, method, "find_index")) {
  427. if (argc < 2 or argv[0].type != .hl_string) return api.makeNull();
  428. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  429. const key = hlKey(argv[1]) orelse return api.makeNull();
  430. var arena_state = std.heap.ArenaAllocator.init(gpa);
  431. const arena = arena_state.allocator();
  432. var locs: std.ArrayList(engine.Loc) = .empty;
  433. db.findIndexLocs(arena, field, key, &locs) catch |e| {
  434. arena_state.deinit();
  435. if (e == error.NoSuchIndex) return makeNoIndexError(db, "find", field);
  436. return api.makeNull();
  437. };
  438. return locsToIterator(db, arena_state, locs.items);
  439. }
  440. if (std.mem.eql(u8, method, "find_range")) {
  441. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  442. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  443. const from: ?engine.Key = if (argc > 1) hlKey(argv[1]) else null;
  444. const to: ?engine.Key = if (argc > 2) hlKey(argv[2]) else null;
  445. var arena_state = std.heap.ArenaAllocator.init(gpa);
  446. const arena = arena_state.allocator();
  447. var locs: std.ArrayList(engine.Loc) = .empty;
  448. db.findRangeLocs(arena, field, from, to, &locs) catch |e| {
  449. arena_state.deinit();
  450. if (e == error.NoSuchIndex) return makeNoIndexError(db, "range", field);
  451. return api.makeNull();
  452. };
  453. return locsToIterator(db, arena_state, locs.items);
  454. }
  455. if (std.mem.eql(u8, method, "delete_pk")) {
  456. if (argc < 1) return api.makeNull();
  457. const key = hlKey(argv[0]) orelse return api.makeNull();
  458. var arena_state = std.heap.ArenaAllocator.init(gpa);
  459. defer arena_state.deinit();
  460. const arena = arena_state.allocator();
  461. var deleted: std.ArrayList(msgpack.Value) = .empty;
  462. const n = db.deletePk(arena, key, &deleted) catch |e| {
  463. std.debug.print("mpackdb plugin: delete failed: {s}\n", .{@errorName(e)});
  464. return api.makeNull();
  465. };
  466. return api.makeNumber(@floatFromInt(n));
  467. }
  468. if (std.mem.eql(u8, method, "update_pk")) {
  469. if (argc < 2 or argv[1].type != .hl_object) return api.makeNull();
  470. const key = hlKey(argv[0]) orelse return api.makeNull();
  471. var arena_state = std.heap.ArenaAllocator.init(gpa);
  472. defer arena_state.deinit();
  473. const arena = arena_state.allocator();
  474. const rec = hlToMsgpack(arena, argv[1]);
  475. if (rec != .map) return api.makeNull();
  476. const n = db.updatePk(arena, key, rec) catch |e| {
  477. if (e == error.RecordLacksPrimaryKey) {
  478. 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";
  479. return api.makeNull();
  480. }
  481. if (e != error.DuplicateKey) {
  482. std.debug.print("mpackdb plugin: update failed: {s}\n", .{@errorName(e)});
  483. }
  484. return api.makeNull();
  485. };
  486. return api.makeNumber(@floatFromInt(n));
  487. }
  488. if (std.mem.eql(u8, method, "count")) {
  489. var arena_state = std.heap.ArenaAllocator.init(gpa);
  490. defer arena_state.deinit();
  491. const arena = arena_state.allocator();
  492. db.refresh();
  493. var scanner = engine.Db.Scanner.init(db, arena, true);
  494. defer scanner.deinit();
  495. var n: usize = 0;
  496. while (true) {
  497. const maybe = scanner.next(arena) catch break;
  498. if (maybe == null) break;
  499. n += 1;
  500. }
  501. return api.makeNumber(@floatFromInt(n));
  502. }
  503. if (std.mem.eql(u8, method, "compact")) {
  504. db.compact() catch |e| {
  505. std.debug.print("mpackdb plugin: compact failed: {s}\n", .{@errorName(e)});
  506. };
  507. return api.makeNull();
  508. }
  509. if (std.mem.eql(u8, method, "persist")) {
  510. db.persistNow() catch |e| {
  511. std.debug.print("mpackdb plugin: persist failed: {s}\n", .{@errorName(e)});
  512. };
  513. return api.makeNull();
  514. }
  515. if (std.mem.eql(u8, method, "last_error")) {
  516. return api.makeString(db.last_error);
  517. }
  518. // The primary key field name with its */@/! prefixes stripped — the .hl
  519. // wrapper needs the bare name to route find(field, …) to find_pk.
  520. if (std.mem.eql(u8, method, "pk_name")) {
  521. const p = db.pk orelse return api.makeNull();
  522. return api.makeString(p);
  523. }
  524. return api.makeNull();
  525. }
  526. /// Decode records at `locs` into the iterator arena and wrap them.
  527. fn locsToIterator(db: *engine.Db, arena_state: std.heap.ArenaAllocator, locs: []const engine.Loc) HlValue {
  528. var st = arena_state;
  529. const arena = st.allocator();
  530. var records: std.ArrayList(msgpack.Value) = .empty;
  531. for (locs) |loc| {
  532. const rec = db.readAt(arena, loc) catch continue;
  533. records.append(arena, rec) catch break;
  534. }
  535. const slice = records.toOwnedSlice(arena) catch &.{};
  536. return makeRecordIterator(@constCast(slice), st);
  537. }
  538. test {
  539. _ = msgpack;
  540. _ = engine;
  541. }

Branches

Latest commits

  • 4f47843egate: ticket links use the tickets short URL (/<slug>/<n>, tickets#25)mre
  • 86605446mission 002 (code order) 4/4: README file map + import order + 'Same output' test + gate run with a tickets HEAD copy, STATUS (entry, lessons), LOG, report; tests/realdata-baseline.mjs + realdata-compare.py (a cleanup answers the same on live data: pages, modules, API, git over HTTPS and SSH, faces), tests/letcount.pymre
  • cc7bf7bamission 002 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (289 lets → plain declarations; 213 left: 125 reassigned, 88 loop-bound; no member/import/param clash). gates 200/0, 46/0, 44/0; real-data reads + writes identical (browser modules: var → const only)mre
  • 090a20c6mission 002 (code order) 2/4: one lib/ file per topic — git.hl split into git (calls, branches, init, temp folder) / homepage / code / pulls / releases (+ git-helpers: paths, ids, |||PR/|||RL markers); repos-helpers, tickets-helpers, transport-helpers; util.hl = localtime + env, storage dir, addresses, lists, text checks, one newest-first sort (was 3 copies); the function routes out of project.hl into lib/api.hl (thin; plumbing in api-helpers.hl), sshgate.hl folded into api.hl + sshkeys.hl keyLine + repos.hl mayPush; 'Make main' and the merge answer out of the faces (code.hl makeMain, pulls.hl pullsView), one login helper (users.hl userOfLoginCode); project.hl is the map. Session-writing routes get &req + &server.sessions. gates 200/0, 46/0, 44/0; real-data identical except /login/failed now shows the parked reason for a browser that already had a session (the old copy-of-req lost it)mre
  • 110c2799mission 002 (code order) 1/4: .hl files out of the root — lib/ (api, git, localtime, markdown, repos, sshgate, sshkeys, tickets, tokens, transport, users), components/styles.hl; jsoncheck.hl removed (imported nowhere); import paths only. gates 200/0, 46/0, 44/0; real-data reads + writes identicalmre
  • fdfb4b1bgitoria: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 200/0, 46/0, 44/0mre
  • 5b46ac84antcolony#40: LOG.md — missions 069/072 are antcolony missions (report paths on Byrodin)mre
  • 5602ff41gitoria: Hybriel master 190aa11d (fc838894 GC correctness, #127 mountKids by reference, #126, #48) — tracker README flat; gates 200/0, 46/0, 44/0mre
  • e85eaf01gitoria: 069 round 2 — hybriel 1a096ad3 not adopted (Markdown SSR still grows); browser gate waits for the server-side logout before restartmre
  • 09ce4f3fgitoria: mission 069 re-vendor hybriel 8efba065 stopped (big SSR pages grow + slow down); lambda audit clean; old vendor keptmre
  • 3dc43108antcolony#40: mission references point to the moved missionsmre
  • 8d9450fdantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 205d5fe4gitoria: Hybriel master ff51cf46; ssh keys/tokens no double rows (session sync); gates follow #20mre
  • 9b27cb26gitoria#21: installable app (manifest, service worker, offline start page), own iconmre
  • 68dcb603deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • e2deed6dgitoria#20: "Add code" only on the Code page of an empty repository, no collapsiblemre
  • 8bb97ffddeploy.sh: never send .git or .gitignore to Byrodinmre
  • fd981932State of 2026-09-27; bin/ no longer tracked (Hybriel commit is in README)mre
  • 4a2d7125initial commitmre