gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitac6268e3ac6268e3mission 046a: re-vendor Hybriel 528bc89f (integration 6): plugins mpackdb/time/web (bin/ git-ignored)mreac6268e3/plugins/mpackdb/mpackdb.zig

31.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 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. const StreamIterState = struct {
  232. iter: HlIterator = undefined,
  233. arena_state: std.heap.ArenaAllocator,
  234. // find_all: a scanner over the whole file
  235. scanner: ?engine.Db.Scanner = null,
  236. // locations (queries): decoded one at a time from `fd`
  237. locs: []engine.Loc = &.{},
  238. pos: usize = 0,
  239. fd: i32 = -1,
  240. done: bool = false,
  241. fn finish(self: *StreamIterState) void {
  242. if (self.done) return;
  243. self.done = true;
  244. if (self.scanner) |*sc| sc.deinit();
  245. self.scanner = null;
  246. engine.Db.closeFd(self.fd);
  247. self.fd = -1;
  248. if (self.locs.len > 0) gpa.free(self.locs);
  249. self.locs = &.{};
  250. _ = self.arena_state.reset(.free_all);
  251. }
  252. };
  253. fn streamNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  254. const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  255. if (state.done) return api.makeNull();
  256. _ = state.arena_state.reset(.retain_capacity);
  257. const arena = state.arena_state.allocator();
  258. if (state.scanner) |*sc| {
  259. const maybe = sc.next(arena) catch {
  260. state.finish();
  261. return api.makeNull();
  262. };
  263. const rec = maybe orelse {
  264. state.finish();
  265. return api.makeNull();
  266. };
  267. return msgpackToHl(arena, rec.value);
  268. }
  269. while (state.pos < state.locs.len) {
  270. const loc = state.locs[state.pos];
  271. state.pos += 1;
  272. const v = engine.Db.readAtFd(state.fd, arena, loc) catch continue;
  273. return msgpackToHl(arena, v);
  274. }
  275. state.finish();
  276. return api.makeNull();
  277. }
  278. fn streamDeinit(ctx: ?*anyopaque) callconv(.c) void {
  279. const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return));
  280. state.finish();
  281. state.arena_state.deinit();
  282. gpa.destroy(state);
  283. }
  284. fn finishStream(state: *StreamIterState) HlValue {
  285. state.iter = .{
  286. .context = @ptrCast(state),
  287. .next_fn = &streamNext,
  288. .deinit_fn = &streamDeinit,
  289. };
  290. return api.makeIterator(&state.iter);
  291. }
  292. fn makeStreamIterator(db: *engine.Db) HlValue {
  293. const state = gpa.create(StreamIterState) catch return api.makeNull();
  294. state.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa) };
  295. state.scanner = engine.Db.Scanner.initOpt(db, gpa, true, true);
  296. return finishStream(state);
  297. }
  298. // =========================================================================
  299. // DB handle
  300. // =========================================================================
  301. //
  302. // Process-wide table registry (ticket #110). Within one process, a table
  303. // path has ONE open engine.Db, shared by every hl_mpackdb_open() on it —
  304. // whatever module instance or realm calls it. `hl:mpackdb`'s .so is loaded
  305. // once and mapped once by the dynamic linker no matter how many realms
  306. // dlopen it (same path, same mapping), so these are already process-wide
  307. // statics; the registry just gives multiple opens of the same table a
  308. // single Db to share instead of a fresh one each time. A single realm's
  309. // event loop drives every call here — mpackdb has never been thread-safe —
  310. // so no mutex.
  311. //
  312. // The file is never compacted or rewritten while a handle on it is live:
  313. // only the FIRST open of a path in this process actually runs
  314. // engine.Db.open (and so is the only one that can compact-on-open, per
  315. // ticket #21's existing rule); every later open of the same path reuses
  316. // that live Db untouched, and its own primaryKey/indexes/compact args are
  317. // ignored — the table's schema was fixed by the first opener. Compaction
  318. // happens only when asked for explicitly (compactNow()) or when the LAST
  319. // handle on a path closes — unless the first opener passed compact=false.
  320. const SharedDb = struct {
  321. db: *engine.Db,
  322. key: []const u8, // owned; also the registry's stored key for this entry
  323. refcount: usize,
  324. };
  325. var registry: std.StringHashMapUnmanaged(*SharedDb) = .empty;
  326. fn acquireShared(path: []const u8, opts: engine.OpenOptions) ?*SharedDb {
  327. const key = engine.tableKey(gpa, path) catch return null;
  328. if (registry.get(key)) |existing| {
  329. gpa.free(key);
  330. existing.refcount += 1;
  331. return existing;
  332. }
  333. const db = engine.Db.open(gpa, path, opts) catch |e| {
  334. std.debug.print("mpackdb plugin: open failed: {s}\n", .{@errorName(e)});
  335. gpa.free(key);
  336. return null;
  337. };
  338. const shared = gpa.create(SharedDb) catch {
  339. db.close();
  340. gpa.free(key);
  341. return null;
  342. };
  343. shared.* = .{ .db = db, .key = key, .refcount = 1 };
  344. registry.put(gpa, key, shared) catch {
  345. db.close();
  346. gpa.destroy(shared);
  347. gpa.free(key);
  348. return null;
  349. };
  350. return shared;
  351. }
  352. /// Drop this handle's reference. On the LAST reference: compact away any
  353. /// tombstones (ticket #110 — the one moment compaction may run implicitly, and
  354. /// only when the first opener did not say compact=false, ticket #192) and
  355. /// close for real.
  356. fn releaseShared(shared: *SharedDb) void {
  357. shared.refcount -= 1;
  358. if (shared.refcount > 0) return;
  359. _ = registry.remove(shared.key);
  360. // compact=false of the opener is honoured here too (ticket #192): the tracker
  361. // opens its stores with compact=false and a stop shrank shows.mpack 1.12 GB -> 424 MB.
  362. if (shared.db.compact_on_open and shared.db.deleted.items.len > 0) {
  363. shared.db.compact() catch |e| {
  364. std.debug.print("mpackdb plugin: close-compact failed: {s}\n", .{@errorName(e)});
  365. };
  366. }
  367. shared.db.close();
  368. gpa.free(shared.key);
  369. gpa.destroy(shared);
  370. }
  371. const DbState = struct {
  372. shared: *SharedDb,
  373. };
  374. export fn hl_mpackdb_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  375. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  376. const raw_path = argv[0].data.string.ptr[0..argv[0].data.string.len];
  377. // mission 077: script-relative, like every other path in Hybriel.
  378. const path = resolvePath(raw_path) orelse return api.makeNull();
  379. defer gpa.free(path);
  380. var opts = engine.OpenOptions{};
  381. if (argc > 1 and argv[1].type == .hl_string and argv[1].data.string.len > 0) {
  382. opts.primary_key = argv[1].data.string.ptr[0..argv[1].data.string.len];
  383. }
  384. var index_names: [64][]const u8 = undefined;
  385. var index_count: usize = 0;
  386. if (argc > 2 and argv[2].type == .hl_object) {
  387. const obj = argv[2].data.object;
  388. for (obj.fields[0..obj.field_count]) |f| {
  389. if (f.value.type != .hl_string) continue;
  390. if (index_count >= index_names.len) break;
  391. index_names[index_count] = f.value.data.string.ptr[0..f.value.data.string.len];
  392. index_count += 1;
  393. }
  394. }
  395. opts.indexes = index_names[0..index_count];
  396. if (argc > 3 and argv[3].type == .hl_bool) {
  397. opts.compact = argv[3].data.boolean;
  398. }
  399. const shared = acquireShared(path, opts) orelse return api.makeNull();
  400. const state = gpa.create(DbState) catch {
  401. releaseShared(shared);
  402. return api.makeNull();
  403. };
  404. state.* = .{ .shared = shared };
  405. const handle = gpa.create(HlHandle) catch {
  406. releaseShared(shared);
  407. gpa.destroy(state);
  408. return api.makeNull();
  409. };
  410. handle.* = .{
  411. .context = @ptrCast(state),
  412. .call_fn = &handleCall,
  413. .close_fn = &handleClose,
  414. .type_name = hlStr("MPackDB"),
  415. };
  416. return api.makeHandle(handle);
  417. }
  418. fn errDeinit(val: *HlValue) callconv(.c) void {
  419. if (val.type == .hl_error) {
  420. const s = val.data.string;
  421. gpa.free(@constCast(s.ptr[0..s.len]));
  422. }
  423. }
  424. /// mission 077 (074 GAP 10): querying a field that carries no index is a
  425. /// MISTAKE, not an empty result — mpackdb only answers through binary-searched
  426. /// indexes, so `[]` was indistinguishable from "no such record" and hid the
  427. /// missing declaration. The message names the field, the op and every index the
  428. /// db was actually opened with (insertion order: primary key first).
  429. fn makeNoIndexError(db: *engine.Db, op: []const u8, field: []const u8) HlValue {
  430. var list: std.ArrayList(u8) = .empty;
  431. defer list.deinit(gpa);
  432. for (db.idx.keys()) |k| {
  433. if (list.items.len > 0) list.appendSlice(gpa, ", ") catch {};
  434. list.append(gpa, '\'') catch {};
  435. list.appendSlice(gpa, k) catch {};
  436. list.append(gpa, '\'') catch {};
  437. }
  438. const declared = if (list.items.len == 0) "none" else list.items;
  439. const msg = std.fmt.allocPrint(
  440. gpa,
  441. "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)",
  442. .{ op, field, declared },
  443. ) catch return api.makeError("mpackdb: no index on that field");
  444. var v = api.makeError(msg);
  445. v.deinit_fn = &errDeinit;
  446. return v;
  447. }
  448. fn handleClose(ctx: ?*anyopaque) callconv(.c) void {
  449. const state: *DbState = @ptrCast(@alignCast(ctx orelse return));
  450. releaseShared(state.shared);
  451. gpa.destroy(state);
  452. }
  453. fn pkStringDeinit(val: *HlValue) callconv(.c) void {
  454. if (val.type == .hl_string) {
  455. const s = val.data.string;
  456. gpa.free(@constCast(s.ptr[0..s.len]));
  457. }
  458. }
  459. fn handleCall(ctx: ?*anyopaque, op: HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  460. const state: *DbState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  461. const db = state.shared.db;
  462. const method = op.ptr[0..op.len];
  463. if (std.mem.eql(u8, method, "insert")) {
  464. if (argc < 1 or argv[0].type != .hl_object) return api.makeNull();
  465. var arena_state = std.heap.ArenaAllocator.init(gpa);
  466. defer arena_state.deinit();
  467. const arena = arena_state.allocator();
  468. const rec = hlToMsgpack(arena, argv[0]);
  469. if (rec != .map) return api.makeNull();
  470. const res = db.insert(arena, rec, false) catch |e| {
  471. if (e != error.DuplicateKey) {
  472. std.debug.print("mpackdb plugin: insert failed: {s}\n", .{@errorName(e)});
  473. db.last_error = std.fmt.bufPrint(&db.last_error_buf, "insert failed: {s}", .{@errorName(e)}) catch "insert failed";
  474. }
  475. return api.makeNull();
  476. };
  477. switch (res) {
  478. .pk_num => |n| return api.makeNumber(n),
  479. .pk_str => |s| {
  480. const copy = gpa.dupe(u8, s) catch return api.makeNull();
  481. var out = api.makeString(copy);
  482. out.deinit_fn = &pkStringDeinit;
  483. return out;
  484. },
  485. .record => return api.makeBool(true),
  486. }
  487. }
  488. if (std.mem.eql(u8, method, "find_all")) {
  489. db.refresh();
  490. return makeStreamIterator(db);
  491. }
  492. if (std.mem.eql(u8, method, "find_pk")) {
  493. if (argc < 1) return api.makeNull();
  494. const key = hlKey(argv[0]) orelse return api.makeNull();
  495. var arena_state = std.heap.ArenaAllocator.init(gpa);
  496. const arena = arena_state.allocator();
  497. var locs: std.ArrayList(engine.Loc) = .empty;
  498. db.findPkLocs(arena, key, &locs) catch {
  499. arena_state.deinit();
  500. return api.makeNull();
  501. };
  502. return locsToIterator(db, arena_state, locs.items);
  503. }
  504. if (std.mem.eql(u8, method, "find_index")) {
  505. if (argc < 2 or argv[0].type != .hl_string) return api.makeNull();
  506. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  507. const key = hlKey(argv[1]) orelse return api.makeNull();
  508. var arena_state = std.heap.ArenaAllocator.init(gpa);
  509. const arena = arena_state.allocator();
  510. var locs: std.ArrayList(engine.Loc) = .empty;
  511. db.findIndexLocs(arena, field, key, &locs) catch |e| {
  512. arena_state.deinit();
  513. if (e == error.NoSuchIndex) return makeNoIndexError(db, "find", field);
  514. return api.makeNull();
  515. };
  516. return locsToIterator(db, arena_state, locs.items);
  517. }
  518. if (std.mem.eql(u8, method, "find_range")) {
  519. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  520. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  521. const from: ?engine.Key = if (argc > 1) hlKey(argv[1]) else null;
  522. const to: ?engine.Key = if (argc > 2) hlKey(argv[2]) else null;
  523. var arena_state = std.heap.ArenaAllocator.init(gpa);
  524. const arena = arena_state.allocator();
  525. var locs: std.ArrayList(engine.Loc) = .empty;
  526. db.findRangeLocs(arena, field, from, to, &locs) catch |e| {
  527. arena_state.deinit();
  528. if (e == error.NoSuchIndex) return makeNoIndexError(db, "range", field);
  529. return api.makeNull();
  530. };
  531. return locsToIterator(db, arena_state, locs.items);
  532. }
  533. if (std.mem.eql(u8, method, "delete_pk")) {
  534. if (argc < 1) return api.makeNull();
  535. const key = hlKey(argv[0]) orelse return api.makeNull();
  536. var arena_state = std.heap.ArenaAllocator.init(gpa);
  537. defer arena_state.deinit();
  538. const arena = arena_state.allocator();
  539. var deleted: std.ArrayList(msgpack.Value) = .empty;
  540. const n = db.deletePk(arena, key, &deleted) catch |e| {
  541. std.debug.print("mpackdb plugin: delete failed: {s}\n", .{@errorName(e)});
  542. return api.makeNull();
  543. };
  544. return api.makeNumber(@floatFromInt(n));
  545. }
  546. if (std.mem.eql(u8, method, "update_pk")) {
  547. if (argc < 2 or argv[1].type != .hl_object) return api.makeNull();
  548. const key = hlKey(argv[0]) orelse return api.makeNull();
  549. var arena_state = std.heap.ArenaAllocator.init(gpa);
  550. defer arena_state.deinit();
  551. const arena = arena_state.allocator();
  552. const rec = hlToMsgpack(arena, argv[1]);
  553. if (rec != .map) return api.makeNull();
  554. // THE KEY COMES FROM THE ARGUMENT (ticket #171, as in the JS mpackdb): a record
  555. // that does not carry the primary key gets it from `key`, so update never
  556. // refuses or silently drops a record for want of it.
  557. var full = rec;
  558. if (db.pk) |p| {
  559. var carried = false;
  560. for (rec.map) |en| {
  561. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) {
  562. carried = en.value != .nil and en.value != .undef;
  563. break;
  564. }
  565. }
  566. if (!carried) {
  567. var list: std.ArrayList(msgpack.Entry) = .empty;
  568. for (rec.map) |en| {
  569. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) continue;
  570. list.append(arena, en) catch return api.makeNull();
  571. }
  572. const kv: msgpack.Value = switch (key) {
  573. .num => |x| .{ .number = x },
  574. .str => |x| .{ .str = x },
  575. };
  576. list.append(arena, .{ .key = .{ .str = p }, .value = kv }) catch return api.makeNull();
  577. full = .{ .map = list.items };
  578. }
  579. }
  580. const n = db.updatePk(arena, key, full) catch |e| {
  581. if (e == error.RecordLacksPrimaryKey) {
  582. 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";
  583. return api.makeNull();
  584. }
  585. if (e != error.DuplicateKey) {
  586. std.debug.print("mpackdb plugin: update failed: {s}\n", .{@errorName(e)});
  587. }
  588. return api.makeNull();
  589. };
  590. return api.makeNumber(@floatFromInt(n));
  591. }
  592. if (std.mem.eql(u8, method, "count")) {
  593. var arena_state = std.heap.ArenaAllocator.init(gpa);
  594. defer arena_state.deinit();
  595. const arena = arena_state.allocator();
  596. db.refresh();
  597. var scanner = engine.Db.Scanner.init(db, arena, true);
  598. defer scanner.deinit();
  599. const n = scanner.countLive() catch 0;
  600. return api.makeNumber(@floatFromInt(n));
  601. }
  602. if (std.mem.eql(u8, method, "compact")) {
  603. db.compact() catch |e| {
  604. std.debug.print("mpackdb plugin: compact failed: {s}\n", .{@errorName(e)});
  605. };
  606. return api.makeNull();
  607. }
  608. if (std.mem.eql(u8, method, "persist")) {
  609. db.persistNow() catch |e| {
  610. std.debug.print("mpackdb plugin: persist failed: {s}\n", .{@errorName(e)});
  611. };
  612. return api.makeNull();
  613. }
  614. if (std.mem.eql(u8, method, "last_error")) {
  615. return api.makeString(db.last_error);
  616. }
  617. // The primary key field name with its */@/! prefixes stripped — the .hl
  618. // wrapper needs the bare name to route find(field, …) to find_pk.
  619. if (std.mem.eql(u8, method, "pk_name")) {
  620. const p = db.pk orelse return api.makeNull();
  621. return api.makeString(p);
  622. }
  623. return api.makeNull();
  624. }
  625. /// The matches at `locs` as a cursor that decodes ONE record per next() from a dup of the
  626. /// data file the offsets are into (mission 393). The locations and the tombstone filter
  627. /// were fixed when the query ran, so the cursor is a snapshot: later writes, deletes or a
  628. /// compaction do not change what it yields. Without an open data file it falls back to
  629. /// decoding eagerly.
  630. fn locsToIterator(db: *engine.Db, arena_state: std.heap.ArenaAllocator, locs: []const engine.Loc) HlValue {
  631. var st = arena_state;
  632. const fd = db.dupDataFd();
  633. if (fd >= 0) {
  634. const state = gpa.create(StreamIterState) catch {
  635. engine.Db.closeFd(fd);
  636. st.deinit();
  637. return api.makeNull();
  638. };
  639. const copy = gpa.dupe(engine.Loc, locs) catch {
  640. engine.Db.closeFd(fd);
  641. gpa.destroy(state);
  642. st.deinit();
  643. return api.makeNull();
  644. };
  645. st.deinit(); // the query arena (locs) is done with
  646. state.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa), .locs = copy, .fd = fd };
  647. return finishStream(state);
  648. }
  649. const arena = st.allocator();
  650. var records: std.ArrayList(msgpack.Value) = .empty;
  651. for (locs) |loc| {
  652. const rec = db.readAt(arena, loc) catch continue;
  653. records.append(arena, rec) catch break;
  654. }
  655. const slice = records.toOwnedSlice(arena) catch &.{};
  656. return makeRecordIterator(@constCast(slice), st);
  657. }
  658. fn dataIdSize(path: [:0]const u8) struct { ino: u64, size: u64 } {
  659. const linux = std.os.linux;
  660. var stx: linux.Statx = undefined;
  661. std.debug.assert(linux.statx(linux.AT.FDCWD, path, 0, linux.STATX.BASIC_STATS, &stx) == 0);
  662. return .{ .ino = stx.ino, .size = stx.size };
  663. }
  664. fn closeKeepsFile(compact: bool, name: []const u8) !struct { before: @TypeOf(dataIdSize("")), after: @TypeOf(dataIdSize("")) } {
  665. const testing = std.testing;
  666. const dir: []const u8 = if (std.c.getenv("TMPDIR")) |t| std.mem.span(t) else "/tmp";
  667. var buf: [512]u8 = undefined;
  668. const base = try std.fmt.bufPrint(&buf, "{s}/mpackdb-192-{d}-{s}", .{ dir, std.os.linux.getpid(), name });
  669. var pbuf: [520]u8 = undefined;
  670. const data = try std.fmt.bufPrintZ(&pbuf, "{s}.mpack", .{base});
  671. const suffixes = [_][]const u8{ ".mpack", ".meta.json", ".idxstate.json", ".lock", ".flock", ".id.txt" };
  672. for (suffixes) |sf| {
  673. var b: [530]u8 = undefined;
  674. const f = try std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf });
  675. _ = std.os.linux.unlink(f);
  676. }
  677. defer for (suffixes) |sf| {
  678. var b: [530]u8 = undefined;
  679. const f = std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf }) catch continue;
  680. _ = std.os.linux.unlink(f);
  681. };
  682. var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
  683. defer arena_state.deinit();
  684. const arena = arena_state.allocator();
  685. // first process life: write rows and tombstones, close (compact=false: nothing may compact)
  686. {
  687. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = false }) orelse return error.OpenFailed;
  688. for (0..20) |i| {
  689. const entries = try arena.alloc(msgpack.Entry, 1);
  690. entries[0] = .{ .key = .{ .str = "n" }, .value = .{ .number = @floatFromInt(i) } };
  691. _ = try sh.db.insert(arena, .{ .map = entries }, false);
  692. }
  693. releaseShared(sh);
  694. }
  695. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = compact }) orelse return error.OpenFailed;
  696. const before = dataIdSize(data);
  697. var gone: std.ArrayList(msgpack.Value) = .empty;
  698. for (1..11) |i| _ = try sh.db.deletePk(arena, .{ .num = @floatFromInt(i) }, &gone);
  699. releaseShared(sh);
  700. return .{ .before = before, .after = dataIdSize(data) };
  701. }
  702. test "#192: closing the last handle of a compact=false table leaves the data file alone" {
  703. const r = try closeKeepsFile(false, "off");
  704. try std.testing.expectEqual(r.before.ino, r.after.ino);
  705. try std.testing.expectEqual(r.before.size, r.after.size);
  706. }
  707. test "#192: closing the last handle of a compact=true table still compacts" {
  708. const r = try closeKeepsFile(true, "on");
  709. try std.testing.expect(r.after.size < r.before.size);
  710. }
  711. test {
  712. _ = msgpack;
  713. _ = engine;
  714. }

Branches

Latest commits

  • ac6268e3mission 046a: re-vendor Hybriel 528bc89f (integration 6): plugins mpackdb/time/web (bin/ git-ignored)mre
  • 322b3293mission 046: photoQueue guard for non-row fetch results (damaged persons index)mre
  • e5b99aecmission 046: photoQueue in slices (people.hl photoQueueStart/Step, jobs.hl photoTick), tests/photoqueue.hlmre
  • 31dcf2admission 045: report, LOGmre
  • 9c3971d0tests/persons-skip-count.hlmre
  • 4d72e365mission 045mre
  • b9cae4c9slices: skip and count non-row values from range(); merge persons pass falls back to iterate; guard testmre
  • 3db7dc31merge w44-jobs-slices into w43-trkmemmre
  • 593dab6fmission 043: report, LOGmre
  • 1a5a4818boot scans back to iterate (slices measured slower: titles 114 s, episodes 141 s, persons failed); lambda per rowmre
  • 03d29893boot scans read primary-key slices (lib/slices.hl from mission 044): iterate is eager too; people view log line back; allShows/allEpisodes stay for toolsmre
  • 23375c58mission 044: report, LOG, STATUSmre
  • c6fd928emission 044: 4096 slices for tables over 200 K rows, 15 ms budget, TRACKER_SLICE_DEPTH for testsmre
  • fb057680mission 044: jobs.hl imports mergeLeft (gate found it), mission file, slices benchmre
  • 0d6293ebmission 043: mission filemre
  • 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
  • 55bbd619boot: one streamed pass per table (lib/bootscan.hl) instead of find(null,null) per module; follows/watches/franchises scans streammre
  • 1d465d3ere-vendor plugins to Hybriel master f9614007 (mpackdb #202 copy fix, libmpackdb sha 6fb3b9d6)mre
  • 6648ba44mission 042: real-browser E2E on ce6f2e0a re-vendor 69/0 at 390 + 1280mre