gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit7d58b36e7d58b36ejukebox JB13 (jukebox#13): Next and Previous ask for the songs after / before the current song's id in the current order, not for place + 1; gate tests/jb13.mjs checks Next with the queue down to one song after the order changedmre7d58b36e/plugins/mpackdb/mpackdb.zig

33.5 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. fn acquireShared(path: []const u8, opts: engine.OpenOptions) ?*SharedDb {
  356. const key = engine.tableKey(gpa, path) catch return null;
  357. if (registry.get(key)) |existing| {
  358. gpa.free(key);
  359. existing.refcount += 1;
  360. return existing;
  361. }
  362. const db = engine.Db.open(gpa, path, opts) catch |e| {
  363. std.debug.print("mpackdb plugin: open failed: {s}\n", .{@errorName(e)});
  364. gpa.free(key);
  365. return null;
  366. };
  367. const shared = gpa.create(SharedDb) catch {
  368. db.close();
  369. gpa.free(key);
  370. return null;
  371. };
  372. shared.* = .{ .db = db, .key = key, .refcount = 1 };
  373. registry.put(gpa, key, shared) catch {
  374. db.close();
  375. gpa.destroy(shared);
  376. gpa.free(key);
  377. return null;
  378. };
  379. return shared;
  380. }
  381. /// Drop this handle's reference. On the LAST reference: compact away any
  382. /// tombstones (ticket #110 — the one moment compaction may run implicitly, and
  383. /// only when the first opener did not say compact=false, ticket #192) and
  384. /// close for real.
  385. fn releaseShared(shared: *SharedDb) void {
  386. shared.refcount -= 1;
  387. if (shared.refcount > 0) return;
  388. _ = registry.remove(shared.key);
  389. // compact=false of the opener is honoured here too (ticket #192): the tracker
  390. // opens its stores with compact=false and a stop shrank shows.mpack 1.12 GB -> 424 MB.
  391. if (shared.db.compact_on_open and shared.db.deleted.items.len > 0) {
  392. shared.db.compact() catch |e| {
  393. std.debug.print("mpackdb plugin: close-compact failed: {s}\n", .{@errorName(e)});
  394. };
  395. }
  396. shared.db.close();
  397. gpa.free(shared.key);
  398. gpa.destroy(shared);
  399. }
  400. const DbState = struct {
  401. shared: *SharedDb,
  402. };
  403. export fn hl_mpackdb_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  404. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  405. const raw_path = argv[0].data.string.ptr[0..argv[0].data.string.len];
  406. // mission 077: script-relative, like every other path in Hybriel.
  407. const path = resolvePath(raw_path) orelse return api.makeNull();
  408. defer gpa.free(path);
  409. var opts = engine.OpenOptions{};
  410. if (argc > 1 and argv[1].type == .hl_string and argv[1].data.string.len > 0) {
  411. opts.primary_key = argv[1].data.string.ptr[0..argv[1].data.string.len];
  412. }
  413. var index_names: [64][]const u8 = undefined;
  414. var index_count: usize = 0;
  415. if (argc > 2 and argv[2].type == .hl_object) {
  416. const obj = argv[2].data.object;
  417. for (obj.fields[0..obj.field_count]) |f| {
  418. if (f.value.type != .hl_string) continue;
  419. if (index_count >= index_names.len) break;
  420. index_names[index_count] = f.value.data.string.ptr[0..f.value.data.string.len];
  421. index_count += 1;
  422. }
  423. }
  424. opts.indexes = index_names[0..index_count];
  425. if (argc > 3 and argv[3].type == .hl_bool) {
  426. opts.compact = argv[3].data.boolean;
  427. }
  428. const shared = acquireShared(path, opts) orelse return api.makeNull();
  429. const state = gpa.create(DbState) catch {
  430. releaseShared(shared);
  431. return api.makeNull();
  432. };
  433. state.* = .{ .shared = shared };
  434. const handle = gpa.create(HlHandle) catch {
  435. releaseShared(shared);
  436. gpa.destroy(state);
  437. return api.makeNull();
  438. };
  439. handle.* = .{
  440. .context = @ptrCast(state),
  441. .call_fn = &handleCall,
  442. .close_fn = &handleClose,
  443. .type_name = hlStr("MPackDB"),
  444. };
  445. return api.makeHandle(handle);
  446. }
  447. fn errDeinit(val: *HlValue) callconv(.c) void {
  448. if (val.type == .hl_error) {
  449. const s = val.data.string;
  450. gpa.free(@constCast(s.ptr[0..s.len]));
  451. }
  452. }
  453. /// mission 077 (074 GAP 10): querying a field that carries no index is a
  454. /// MISTAKE, not an empty result — mpackdb only answers through binary-searched
  455. /// indexes, so `[]` was indistinguishable from "no such record" and hid the
  456. /// missing declaration. The message names the field, the op and every index the
  457. /// db was actually opened with (insertion order: primary key first).
  458. fn makeNoIndexError(db: *engine.Db, op: []const u8, field: []const u8) HlValue {
  459. var list: std.ArrayList(u8) = .empty;
  460. defer list.deinit(gpa);
  461. for (db.idx.keys()) |k| {
  462. if (list.items.len > 0) list.appendSlice(gpa, ", ") catch {};
  463. list.append(gpa, '\'') catch {};
  464. list.appendSlice(gpa, k) catch {};
  465. list.append(gpa, '\'') catch {};
  466. }
  467. const declared = if (list.items.len == 0) "none" else list.items;
  468. const msg = std.fmt.allocPrint(
  469. gpa,
  470. "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)",
  471. .{ op, field, declared },
  472. ) catch return api.makeError("mpackdb: no index on that field");
  473. var v = api.makeError(msg);
  474. v.deinit_fn = &errDeinit;
  475. return v;
  476. }
  477. fn handleClose(ctx: ?*anyopaque) callconv(.c) void {
  478. const state: *DbState = @ptrCast(@alignCast(ctx orelse return));
  479. releaseShared(state.shared);
  480. gpa.destroy(state);
  481. }
  482. fn pkStringDeinit(val: *HlValue) callconv(.c) void {
  483. if (val.type == .hl_string) {
  484. const s = val.data.string;
  485. gpa.free(@constCast(s.ptr[0..s.len]));
  486. }
  487. }
  488. fn handleCall(ctx: ?*anyopaque, op: HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  489. const state: *DbState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  490. const db = state.shared.db;
  491. const method = op.ptr[0..op.len];
  492. if (std.mem.eql(u8, method, "insert")) {
  493. if (argc < 1 or argv[0].type != .hl_object) return api.makeNull();
  494. var arena_state = std.heap.ArenaAllocator.init(gpa);
  495. defer arena_state.deinit();
  496. const arena = arena_state.allocator();
  497. const rec = hlToMsgpack(arena, argv[0]);
  498. if (rec != .map) return api.makeNull();
  499. const res = db.insert(arena, rec, false) catch |e| {
  500. if (e != error.DuplicateKey) {
  501. std.debug.print("mpackdb plugin: insert failed: {s}\n", .{@errorName(e)});
  502. db.last_error = std.fmt.bufPrint(&db.last_error_buf, "insert failed: {s}", .{@errorName(e)}) catch "insert failed";
  503. }
  504. return api.makeNull();
  505. };
  506. switch (res) {
  507. .pk_num => |n| return api.makeNumber(n),
  508. .pk_str => |s| {
  509. const copy = gpa.dupe(u8, s) catch return api.makeNull();
  510. var out = api.makeString(copy);
  511. out.deinit_fn = &pkStringDeinit;
  512. return out;
  513. },
  514. .record => return api.makeBool(true),
  515. }
  516. }
  517. if (std.mem.eql(u8, method, "open_cursors")) return api.makeNumber(@floatFromInt(open_cursors));
  518. if (std.mem.eql(u8, method, "early_closes")) return api.makeNumber(@floatFromInt(early_closes));
  519. if (std.mem.eql(u8, method, "find_all")) {
  520. db.refresh();
  521. return makeStreamIterator(db);
  522. }
  523. if (std.mem.eql(u8, method, "find_pk")) {
  524. if (argc < 1) return api.makeNull();
  525. const key = hlKey(argv[0]) orelse return api.makeNull();
  526. var arena_state = std.heap.ArenaAllocator.init(gpa);
  527. const arena = arena_state.allocator();
  528. var locs: std.ArrayList(engine.Loc) = .empty;
  529. db.findPkLocs(arena, key, &locs) catch {
  530. arena_state.deinit();
  531. return api.makeNull();
  532. };
  533. return locsToIterator(db, arena_state, locs.items);
  534. }
  535. if (std.mem.eql(u8, method, "find_index")) {
  536. if (argc < 2 or argv[0].type != .hl_string) return api.makeNull();
  537. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  538. const key = hlKey(argv[1]) orelse return api.makeNull();
  539. var arena_state = std.heap.ArenaAllocator.init(gpa);
  540. const arena = arena_state.allocator();
  541. var locs: std.ArrayList(engine.Loc) = .empty;
  542. db.findIndexLocs(arena, field, key, &locs) catch |e| {
  543. arena_state.deinit();
  544. if (e == error.NoSuchIndex) return makeNoIndexError(db, "find", field);
  545. return api.makeNull();
  546. };
  547. return locsToIterator(db, arena_state, locs.items);
  548. }
  549. if (std.mem.eql(u8, method, "find_range")) {
  550. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  551. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  552. const from: ?engine.Key = if (argc > 1) hlKey(argv[1]) else null;
  553. const to: ?engine.Key = if (argc > 2) hlKey(argv[2]) else null;
  554. var arena_state = std.heap.ArenaAllocator.init(gpa);
  555. const arena = arena_state.allocator();
  556. var locs: std.ArrayList(engine.Loc) = .empty;
  557. db.findRangeLocs(arena, field, from, to, &locs) catch |e| {
  558. arena_state.deinit();
  559. if (e == error.NoSuchIndex) return makeNoIndexError(db, "range", field);
  560. return api.makeNull();
  561. };
  562. return locsToIterator(db, arena_state, locs.items);
  563. }
  564. if (std.mem.eql(u8, method, "delete_pk")) {
  565. if (argc < 1) return api.makeNull();
  566. const key = hlKey(argv[0]) orelse return api.makeNull();
  567. var arena_state = std.heap.ArenaAllocator.init(gpa);
  568. defer arena_state.deinit();
  569. const arena = arena_state.allocator();
  570. var deleted: std.ArrayList(msgpack.Value) = .empty;
  571. const n = db.deletePk(arena, key, &deleted) catch |e| {
  572. std.debug.print("mpackdb plugin: delete failed: {s}\n", .{@errorName(e)});
  573. return api.makeNull();
  574. };
  575. return api.makeNumber(@floatFromInt(n));
  576. }
  577. if (std.mem.eql(u8, method, "update_pk")) {
  578. if (argc < 2 or argv[1].type != .hl_object) return api.makeNull();
  579. const key = hlKey(argv[0]) orelse return api.makeNull();
  580. var arena_state = std.heap.ArenaAllocator.init(gpa);
  581. defer arena_state.deinit();
  582. const arena = arena_state.allocator();
  583. const rec = hlToMsgpack(arena, argv[1]);
  584. if (rec != .map) return api.makeNull();
  585. // THE KEY COMES FROM THE ARGUMENT (ticket #171, as in the JS mpackdb): a record
  586. // that does not carry the primary key gets it from `key`, so update never
  587. // refuses or silently drops a record for want of it.
  588. var full = rec;
  589. if (db.pk) |p| {
  590. var carried = false;
  591. for (rec.map) |en| {
  592. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) {
  593. carried = en.value != .nil and en.value != .undef;
  594. break;
  595. }
  596. }
  597. if (!carried) {
  598. var list: std.ArrayList(msgpack.Entry) = .empty;
  599. for (rec.map) |en| {
  600. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) continue;
  601. list.append(arena, en) catch return api.makeNull();
  602. }
  603. const kv: msgpack.Value = switch (key) {
  604. .num => |x| .{ .number = x },
  605. .str => |x| .{ .str = x },
  606. };
  607. list.append(arena, .{ .key = .{ .str = p }, .value = kv }) catch return api.makeNull();
  608. full = .{ .map = list.items };
  609. }
  610. }
  611. const n = db.updatePk(arena, key, full) catch |e| {
  612. if (e == error.RecordLacksPrimaryKey) {
  613. 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";
  614. return api.makeNull();
  615. }
  616. if (e != error.DuplicateKey) {
  617. std.debug.print("mpackdb plugin: update failed: {s}\n", .{@errorName(e)});
  618. }
  619. return api.makeNull();
  620. };
  621. return api.makeNumber(@floatFromInt(n));
  622. }
  623. if (std.mem.eql(u8, method, "count")) {
  624. var arena_state = std.heap.ArenaAllocator.init(gpa);
  625. defer arena_state.deinit();
  626. const arena = arena_state.allocator();
  627. db.refresh();
  628. var scanner = engine.Db.Scanner.init(db, arena, true);
  629. defer scanner.deinit();
  630. const n = scanner.countLive() catch 0;
  631. return api.makeNumber(@floatFromInt(n));
  632. }
  633. if (std.mem.eql(u8, method, "compact")) {
  634. db.compact() catch |e| {
  635. std.debug.print("mpackdb plugin: compact failed: {s}\n", .{@errorName(e)});
  636. };
  637. return api.makeNull();
  638. }
  639. if (std.mem.eql(u8, method, "persist")) {
  640. db.persistNow() catch |e| {
  641. std.debug.print("mpackdb plugin: persist failed: {s}\n", .{@errorName(e)});
  642. };
  643. return api.makeNull();
  644. }
  645. if (std.mem.eql(u8, method, "last_error")) {
  646. return api.makeString(db.last_error);
  647. }
  648. // The primary key field name with its */@/! prefixes stripped — the .hl
  649. // wrapper needs the bare name to route find(field, …) to find_pk.
  650. if (std.mem.eql(u8, method, "pk_name")) {
  651. const p = db.pk orelse return api.makeNull();
  652. return api.makeString(p);
  653. }
  654. return api.makeNull();
  655. }
  656. /// The matches at `locs` as a cursor that decodes ONE record per next() from the
  657. /// (refcounted) data file the offsets are into (mission 393). The locations and the tombstone filter
  658. /// were fixed when the query ran, so the cursor is a snapshot: later writes, deletes or a
  659. /// compaction do not change what it yields. Without an open data file it falls back to
  660. /// decoding eagerly.
  661. fn locsToIterator(db: *engine.Db, arena_state: std.heap.ArenaAllocator, locs: []const engine.Loc) HlValue {
  662. var st = arena_state;
  663. if (db.retainDataGen()) |gen| {
  664. const state = gpa.create(StreamIterState) catch {
  665. gen.release();
  666. st.deinit();
  667. return api.makeNull();
  668. };
  669. const copy = gpa.dupe(engine.Loc, locs) catch {
  670. gen.release();
  671. gpa.destroy(state);
  672. st.deinit();
  673. return api.makeNull();
  674. };
  675. st.deinit(); // the query arena (locs) is done with
  676. state.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa), .locs = copy, .fd = gen.fd, .gen = gen };
  677. return finishStream(state);
  678. }
  679. const arena = st.allocator();
  680. var records: std.ArrayList(msgpack.Value) = .empty;
  681. for (locs) |loc| {
  682. const rec = db.readAt(arena, loc) catch continue;
  683. records.append(arena, rec) catch break;
  684. }
  685. const slice = records.toOwnedSlice(arena) catch &.{};
  686. return makeRecordIterator(@constCast(slice), st);
  687. }
  688. fn dataIdSize(path: [:0]const u8) struct { ino: u64, size: u64 } {
  689. const linux = std.os.linux;
  690. var stx: linux.Statx = undefined;
  691. std.debug.assert(linux.statx(linux.AT.FDCWD, path, 0, linux.STATX.BASIC_STATS, &stx) == 0);
  692. return .{ .ino = stx.ino, .size = stx.size };
  693. }
  694. fn closeKeepsFile(compact: bool, name: []const u8) !struct { before: @TypeOf(dataIdSize("")), after: @TypeOf(dataIdSize("")) } {
  695. const testing = std.testing;
  696. const dir: []const u8 = if (std.c.getenv("TMPDIR")) |t| std.mem.span(t) else "/tmp";
  697. var buf: [512]u8 = undefined;
  698. const base = try std.fmt.bufPrint(&buf, "{s}/mpackdb-192-{d}-{s}", .{ dir, std.os.linux.getpid(), name });
  699. var pbuf: [520]u8 = undefined;
  700. const data = try std.fmt.bufPrintZ(&pbuf, "{s}.mpack", .{base});
  701. const suffixes = [_][]const u8{ ".mpack", ".meta.json", ".idxstate.json", ".lock", ".flock", ".id.txt" };
  702. for (suffixes) |sf| {
  703. var b: [530]u8 = undefined;
  704. const f = try std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf });
  705. _ = std.os.linux.unlink(f);
  706. }
  707. defer for (suffixes) |sf| {
  708. var b: [530]u8 = undefined;
  709. const f = std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf }) catch continue;
  710. _ = std.os.linux.unlink(f);
  711. };
  712. var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
  713. defer arena_state.deinit();
  714. const arena = arena_state.allocator();
  715. // first process life: write rows and tombstones, close (compact=false: nothing may compact)
  716. {
  717. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = false }) orelse return error.OpenFailed;
  718. for (0..20) |i| {
  719. const entries = try arena.alloc(msgpack.Entry, 1);
  720. entries[0] = .{ .key = .{ .str = "n" }, .value = .{ .number = @floatFromInt(i) } };
  721. _ = try sh.db.insert(arena, .{ .map = entries }, false);
  722. }
  723. releaseShared(sh);
  724. }
  725. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = compact }) orelse return error.OpenFailed;
  726. const before = dataIdSize(data);
  727. var gone: std.ArrayList(msgpack.Value) = .empty;
  728. for (1..11) |i| _ = try sh.db.deletePk(arena, .{ .num = @floatFromInt(i) }, &gone);
  729. releaseShared(sh);
  730. return .{ .before = before, .after = dataIdSize(data) };
  731. }
  732. test "#192: closing the last handle of a compact=false table leaves the data file alone" {
  733. const r = try closeKeepsFile(false, "off");
  734. try std.testing.expectEqual(r.before.ino, r.after.ino);
  735. try std.testing.expectEqual(r.before.size, r.after.size);
  736. }
  737. test "#192: closing the last handle of a compact=true table still compacts" {
  738. const r = try closeKeepsFile(true, "on");
  739. try std.testing.expect(r.after.size < r.before.size);
  740. }
  741. test {
  742. _ = msgpack;
  743. _ = engine;
  744. }

Branches

Latest commits

  • 7d58b36ejukebox JB13 (jukebox#13): Next and Previous ask for the songs after / before the current song's id in the current order, not for place + 1; gate tests/jb13.mjs checks Next with the queue down to one song after the order changedmre
  • 51358794jukebox JB14 (jukebox#14): the Songs screen opens sorted the way it was left (kept on the server in storage/ui.json), the sort control shows the sort the rows really have (selected options, autocomplete off); gate tests/jb14.mjsmre
  • cc68a063jukebox JB13 (jukebox#13): a tapped song plays the song that was tapped, found by its id in the list as it is now (not by its row number, which counted plays move); the queue goes on from its place there, the rows refresh on the tap; gate tests/jb13.mjs (songs by plays, favourites)mre
  • 88d3d5c1jukebox JB12b (jukebox#12): the scroll handle is big (2.75rem x 4rem, accent colour, grip) and drawn on every device, no media query; native bar hidden; gate tests/touch.mjs checks the drawn width with and without touchmre
  • b58e4495jukebox JB11 (jukebox#11): the next song starts in the ended event on the same audio element, so it also starts with the screen locked; gate tests/jb11.mjs (hidden tab, no frames)mre
  • 12a26233jukebox JB12 (jukebox#12): the long lists get a scroll handle a finger can use on touch screens (44 px tap area, slim look, drag through all rows), gate tests/touch.mjsmre
  • 0f2157a9jukebox JV1: onto Hybriel set-day27b: readBytes and stat for /stream and the mp3 tags (no dd, head or tail), startup fault exits 1, fs and mpackdb plugins re-vendored; songs with a comma in the title are indexed againmre
  • 63d0f2eejukebox ST1 (jukebox#2): styles of main, songs and search moved into their own Style blocks (styles.hl 81 to 8 rules, pixel-identical at 390 and 1280); artist and album wait for an hl:web fixmre
  • c5b8fde9jukebox JB3b: keyboard gap repro as a reportmre
  • 9daebb4bjukebox JB3b: shuffle, now-playing overlay, next and previous, play counting, media session, gates; keyboard left open (Hybriel gap)mre
  • 59c1373ejukebox JB3 (work in progress): albums without folder and with disc markers folded, compilations, duplicate songs, own play counter, server-side shuffle queuemre
  • 2a4cfc55jukebox: library screens (songs, artists, albums, artist, album, search, favourites), compact player bar, /stream with Range, thumbnails, virtual list vendored, ui gate and real-library checkmre
  • 93a44212jukebox: report, numbers of the full scan, notes on the index key rulemre
  • bf5167dajukebox: index keys without commas (mpackdb loses them after a reopen), comma fixture and gate checksmre
  • 28a82fa2jukebox: README, STATUS, LOG, DECISIONSmre
  • d13987dfjukebox: library scanner, ID3 reader, mpackdb database and JSON API, with fixtures and a gatemre