gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitae905f15ae905f15Merge t36a: tracker#36 apply rechecks, reportmreae905f15/plugins/mpackdb/mpackdb.zig

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

Branches

Latest commits

  • ae905f15Merge t36a: tracker#36 apply rechecks, reportmre
  • 796bfaceT36A: report validated fixes, failed live SSH check and verified rollbackmre
  • 55257852log: #53 live, #56 mergedmre
  • 78b39f1bMerge hm56-rows: tracker#56 list builders insert oncemre
  • 7aea52batmdb fix: protect owners without slugs and record passing gatesmre
  • 9b3c2559tmdb fix: revalidate planned identities and reserve target idsmre
  • 6da612fclog: T36A tool defectmre
  • d56ee0daT36A: report unsafe TMDB apply revalidation and stop before livemre
  • 08e55255log: HM56 done, T36A startedmre
  • 91bcdf0eAvoid per-row list copies and reproduce keyed-row blockersmre
  • 5fd2ac75status: #36 GOmre
  • 0d253b45mission: T36Amre
  • 2aa22d23log: #36 GOmre
  • 833aee2flog: #50 closed, HM56 startedmre
  • ac58c1e5mission: HM56mre
  • 58979c0clog: HM54 held for decision, DP65 startedmre
  • bb2ebc67log: #64 live, #53 mergedmre
  • 27cde42fMerge hm53-dom: tracker#53 inputs bound to membersmre
  • 2156cc7flog: HM54 reviewmre
  • 9fb82efclog: HM54 gap, fill continuesmre