gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/mpackdb/mpackdb.zig

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

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre