gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit6280c92f6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre6280c92f/plugins/mpackdb/mpackdb.zig

32.0 KB

  1. // hl:mpackdb plugin — native shared library (mission 066)
  2. // Zig port of mpackdb v1.0.7 (MessagePack DB with binary-search indexes).
  3. //
  4. // Layout:
  5. // msgpack.zig — MessagePack codec (msgpackr-compatible, see D12)
  6. // engine.zig — DB engine (MPackDB/IndexManager semantics)
  7. // mpackdb.zig — this file: plugin ABI surface
  8. //
  9. // Exports:
  10. // hl_mpackdb_open(path, primaryKey, indexes, compact) → handle
  11. // handle ops: insert(record) / find_all() / find_pk(v) /
  12. // find_index(field, v) / find_range(field, from, to) /
  13. // delete_pk(v) / update_pk(v, record) / count() /
  14. // compact() / persist() / last_error() / pk_name()
  15. //
  16. // The `hl:mpackdb` .hl surface (MPackDB.hl, cursor.hl, server.hl) is the public
  17. // API; these ops are its transport.
  18. //
  19. // Cursors STREAM (mission 393): find_all and the index queries decode ONE record per
  20. // next() into a per-record arena (see "Streaming iterator" below for the snapshot rule);
  21. // only the eager fallback (no open data file) and find_pk/fetch-sized results are
  22. // materialized. The runtime deep-copies each record on next().
  23. const std = @import("std");
  24. const api = @import("plugin_api");
  25. pub const msgpack = @import("msgpack.zig");
  26. pub const engine = @import("engine.zig");
  27. const HlValue = api.HlValue;
  28. const HlObject = api.HlObject;
  29. const HlField = api.HlField;
  30. const HlIterator = api.HlIterator;
  31. const HlHandle = api.HlHandle;
  32. const HlString = api.HlString;
  33. // the plugins' allocator (plugin_api.zig): a DebugAllocator here mapped and unmapped every
  34. // buffer of a page or more, which the per-operation buffers made a syscall pair per call
  35. const gpa = api.allocator;
  36. fn hlStr(comptime s: []const u8) HlString {
  37. return .{ .ptr = s.ptr, .len = s.len };
  38. }
  39. // =========================================================================
  40. // Path resolution (mission 077, 074 GAP 9)
  41. //
  42. // CONTRACT — the same one hl:fs got in mission 068: a relative db path resolves
  43. // against the MAIN SCRIPT's directory, not the process CWD. `cd /tmp && hybriel
  44. // /srv/app/main.hl` must find /srv/app's database, not create a second one in
  45. // /tmp. Absolute paths are used as-is. The runtime injects the directory through
  46. // the optional plugin hook hl_mpackdb_set_script_dir right after dlopen.
  47. // =========================================================================
  48. var script_dir: ?[]u8 = null;
  49. export fn hl_mpackdb_set_script_dir(ptr: [*]const u8, len: usize) callconv(.c) void {
  50. if (script_dir) |old| gpa.free(old);
  51. script_dir = gpa.dupe(u8, ptr[0..len]) catch null;
  52. }
  53. /// Resolve a (possibly relative) db path against the script dir. The returned
  54. /// slice is gpa-allocated; caller frees.
  55. fn resolvePath(path: []const u8) ?[]u8 {
  56. if (path.len == 0 or path[0] == '/') return gpa.dupe(u8, path) catch null;
  57. if (script_dir) |sd| return std.fmt.allocPrint(gpa, "{s}/{s}", .{ sd, path }) catch null;
  58. return gpa.dupe(u8, path) catch null;
  59. }
  60. // =========================================================================
  61. // HlValue ⇄ msgpack.Value conversion
  62. // =========================================================================
  63. /// AN EMPTY LIST is marked by its `fields` address (ticket #58) — the runtime's
  64. /// contract, stated in native/src/plugin_loader.zig beside the same constant. Zero
  65. /// fields alone read back as an empty hybrid, and `tags = []` was stored as a map.
  66. const EMPTY_LIST_FIELDS: [*]HlField = @ptrFromInt(0x4C49_5354_0000_0008);
  67. fn isEmptyList(obj: *const HlObject) bool {
  68. return obj.field_count == 0 and obj.fields == EMPTY_LIST_FIELDS;
  69. }
  70. /// Hybriel value (as HlObject tree) → msgpack value, allocated in `arena`.
  71. /// An HlObject whose keys are exactly the sequence "0".."n-1" (in order)
  72. /// becomes a msgpack array; everything else becomes a map. Hybriel null and
  73. /// undefined both arrive as hl_null → msgpack nil.
  74. fn hlToMsgpack(arena: std.mem.Allocator, v: HlValue) msgpack.Value {
  75. switch (v.type) {
  76. .hl_null => return .nil,
  77. .hl_bool => return .{ .boolean = v.data.boolean },
  78. .hl_number => return .{ .number = v.data.number },
  79. .hl_string => {
  80. const s = v.data.string.ptr[0..v.data.string.len];
  81. const copy = arena.dupe(u8, s) catch return .nil;
  82. return .{ .str = copy };
  83. },
  84. .hl_object => {
  85. const obj = v.data.object;
  86. const fields = obj.fields[0..obj.field_count];
  87. // strict numeric sequence "0".."n-1" → array; an empty list carries its
  88. // mark (ticket #58), or `tags = []` was stored as an empty map
  89. var is_array = fields.len > 0 or isEmptyList(obj);
  90. for (fields, 0..) |f, i| {
  91. const k = f.key.ptr[0..f.key.len];
  92. var buf: [20]u8 = undefined;
  93. const expect = std.fmt.bufPrint(&buf, "{d}", .{i}) catch "";
  94. if (!std.mem.eql(u8, k, expect)) {
  95. is_array = false;
  96. break;
  97. }
  98. }
  99. if (is_array) {
  100. const items = arena.alloc(msgpack.Value, fields.len) catch return .nil;
  101. for (fields, 0..) |f, i| items[i] = hlToMsgpack(arena, f.value);
  102. return .{ .array = items };
  103. }
  104. const entries = arena.alloc(msgpack.Entry, fields.len) catch return .nil;
  105. for (fields, 0..) |f, i| {
  106. const k = arena.dupe(u8, f.key.ptr[0..f.key.len]) catch return .nil;
  107. entries[i] = .{ .key = .{ .str = k }, .value = hlToMsgpack(arena, f.value) };
  108. }
  109. return .{ .map = entries };
  110. },
  111. else => return .nil,
  112. }
  113. }
  114. /// msgpack value → HlValue tree allocated in `arena` (no deinit hooks — the
  115. /// runtime deep-copies immediately; the arena outlives the call).
  116. fn msgpackToHl(arena: std.mem.Allocator, v: msgpack.Value) HlValue {
  117. switch (v) {
  118. .nil, .undef => return api.makeNull(),
  119. .boolean => |b| return api.makeBool(b),
  120. .number => |n| return api.makeNumber(n),
  121. .str => |s| return api.makeString(s),
  122. .bin => |b| return api.makeString(b),
  123. .array => |items| {
  124. const fields = arena.alloc(HlField, items.len) catch return api.makeNull();
  125. for (items, 0..) |it, i| {
  126. var buf: [20]u8 = undefined;
  127. const k = std.fmt.bufPrint(&buf, "{d}", .{i}) catch "";
  128. const key = arena.dupe(u8, k) catch return api.makeNull();
  129. fields[i] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = msgpackToHl(arena, it) };
  130. }
  131. const obj = arena.create(HlObject) catch return api.makeNull();
  132. obj.* = .{ .fields = if (items.len == 0) EMPTY_LIST_FIELDS else fields.ptr, .field_count = fields.len, .deinit_fn = null };
  133. return api.makeObject(obj);
  134. },
  135. .map => |entries| {
  136. const fields = arena.alloc(HlField, entries.len) catch return api.makeNull();
  137. var n: usize = 0;
  138. for (entries) |e| {
  139. const key: []const u8 = switch (e.key) {
  140. .str => |s| s,
  141. .number => |num| blk: {
  142. var buf: [40]u8 = undefined;
  143. const k = engine.jsNumFmt(&buf, num);
  144. break :blk arena.dupe(u8, k) catch continue;
  145. },
  146. else => continue,
  147. };
  148. fields[n] = .{ .key = .{ .ptr = key.ptr, .len = key.len }, .value = msgpackToHl(arena, e.value) };
  149. n += 1;
  150. }
  151. const obj = arena.create(HlObject) catch return api.makeNull();
  152. obj.* = .{ .fields = fields.ptr, .field_count = n, .deinit_fn = null };
  153. return api.makeObject(obj);
  154. },
  155. .ext => {
  156. if (v.timestampMs()) |ms| return api.makeNumber(ms);
  157. return api.makeNull();
  158. },
  159. }
  160. }
  161. fn hlKey(v: HlValue) ?engine.Key {
  162. return switch (v.type) {
  163. .hl_number => .{ .num = v.data.number },
  164. .hl_string => .{ .str = v.data.string.ptr[0..v.data.string.len] },
  165. else => null,
  166. };
  167. }
  168. // =========================================================================
  169. // Record iterator (eagerly materialized)
  170. // =========================================================================
  171. const RecIterState = struct {
  172. // THE ITERATOR LIVES IN ITS STATE (the emit soak, 2026-10-02): the runtime frees
  173. // only its own wrapper and hands deinit the context, so a separately created
  174. // HlIterator was never freed — 40 bytes per find/range/fetch, for good.
  175. iter: HlIterator = undefined,
  176. arena_state: std.heap.ArenaAllocator,
  177. records: []msgpack.Value = &.{},
  178. idx: usize = 0,
  179. };
  180. fn recIterNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  181. const state: *RecIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  182. if (state.idx >= state.records.len) {
  183. // THE LAST RECORD IS ALREADY COPIED OUT: the arena goes now, not when the
  184. // collector sweeps the iterator, which counts none of these bytes and so can
  185. // leave thousands of drained lookups' records waiting (hybriel#126, notes)
  186. state.records = &.{};
  187. _ = state.arena_state.reset(.free_all);
  188. return api.makeNull();
  189. }
  190. const v = state.records[state.idx];
  191. state.idx += 1;
  192. return msgpackToHl(state.arena_state.allocator(), v);
  193. }
  194. fn recIterDeinit(ctx: ?*anyopaque) callconv(.c) void {
  195. const state: *RecIterState = @ptrCast(@alignCast(ctx orelse return));
  196. state.arena_state.deinit();
  197. gpa.destroy(state);
  198. }
  199. fn makeRecordIterator(records: []msgpack.Value, arena_state: std.heap.ArenaAllocator) HlValue {
  200. const state = gpa.create(RecIterState) catch return api.makeNull();
  201. state.* = .{ .arena_state = arena_state, .records = records };
  202. state.iter = .{
  203. .context = @ptrCast(state),
  204. .next_fn = &recIterNext,
  205. .deinit_fn = &recIterDeinitOuter,
  206. };
  207. return api.makeIterator(&state.iter);
  208. }
  209. // The runtime's IterWrapper deinit calls iter.deinit_fn then frees its own
  210. // wrapper — but the HlIterator struct itself is ours to free.
  211. fn recIterDeinitOuter(ctx: ?*anyopaque) callconv(.c) void {
  212. recIterDeinit(ctx);
  213. }
  214. // =========================================================================
  215. // Streaming iterator (mission 393)
  216. // =========================================================================
  217. //
  218. // find_all (iterate(null, null)) and the index lookups / range scans hand out a cursor
  219. // that decodes ONE record per next() into a per-record arena that is reset each time,
  220. // so memory is O(1) in the table size (O(matches * 16 B) of locations for an index
  221. // query). THE RULE when the store changes while the cursor is open — it is a SNAPSHOT:
  222. // - it yields the records that existed AND were live when the query started (the
  223. // file size and the tombstone set are frozen then);
  224. // - appends / inserts / updates made later (a new version is an append) are not seen;
  225. // - a record deleted later is still yielded (the cursor reads the bytes it saw);
  226. // - a compaction (by this or another process) or a foreign rewrite does not
  227. // invalidate it: the cursor holds its own dup of the data file it started on, and
  228. // keeps reading that (unlinked) file to the end. The price: that file's disk space
  229. // lives until the cursor is exhausted or collected.
  230. // A read error mid-stream ends the cursor early and sets lastError().
  231. const StreamIterState = struct {
  232. iter: HlIterator = undefined,
  233. arena_state: std.heap.ArenaAllocator,
  234. // find_all: a scanner over the whole file
  235. scanner: ?engine.Db.Scanner = null,
  236. // locations (queries): decoded one at a time from `fd`
  237. locs: []engine.Loc = &.{},
  238. pos: usize = 0,
  239. fd: i32 = -1,
  240. gen: ?*engine.DataGen = null, // the reference that keeps `fd` open (fd403: no dup per cursor)
  241. done: bool = false,
  242. fn finish(self: *StreamIterState) void {
  243. if (self.done) return;
  244. self.done = true;
  245. if (self.scanner) |*sc| sc.deinit();
  246. self.scanner = null;
  247. if (self.gen) |g| g.release();
  248. self.gen = null;
  249. self.fd = -1;
  250. if (self.locs.len > 0) gpa.free(self.locs);
  251. self.locs = &.{};
  252. _ = self.arena_state.reset(.free_all);
  253. }
  254. };
  255. fn streamNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  256. const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  257. if (state.done) return api.makeNull();
  258. _ = state.arena_state.reset(.retain_capacity);
  259. const arena = state.arena_state.allocator();
  260. if (state.scanner) |*sc| {
  261. const maybe = sc.next(arena) catch {
  262. state.finish();
  263. return api.makeNull();
  264. };
  265. const rec = maybe orelse {
  266. state.finish();
  267. return api.makeNull();
  268. };
  269. return msgpackToHl(arena, rec.value);
  270. }
  271. while (state.pos < state.locs.len) {
  272. const loc = state.locs[state.pos];
  273. state.pos += 1;
  274. const v = engine.Db.readAtFd(state.fd, arena, loc) catch continue;
  275. return msgpackToHl(arena, v);
  276. }
  277. state.finish();
  278. return api.makeNull();
  279. }
  280. fn streamDeinit(ctx: ?*anyopaque) callconv(.c) void {
  281. const state: *StreamIterState = @ptrCast(@alignCast(ctx orelse return));
  282. state.finish();
  283. state.arena_state.deinit();
  284. gpa.destroy(state);
  285. }
  286. fn finishStream(state: *StreamIterState) HlValue {
  287. state.iter = .{
  288. .context = @ptrCast(state),
  289. .next_fn = &streamNext,
  290. .deinit_fn = &streamDeinit,
  291. };
  292. return api.makeIterator(&state.iter);
  293. }
  294. fn makeStreamIterator(db: *engine.Db) HlValue {
  295. const state = gpa.create(StreamIterState) catch return api.makeNull();
  296. state.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa) };
  297. state.scanner = engine.Db.Scanner.initOpt(db, gpa, true, true);
  298. return finishStream(state);
  299. }
  300. // =========================================================================
  301. // DB handle
  302. // =========================================================================
  303. //
  304. // Process-wide table registry (ticket #110). Within one process, a table
  305. // path has ONE open engine.Db, shared by every hl_mpackdb_open() on it —
  306. // whatever module instance or realm calls it. `hl:mpackdb`'s .so is loaded
  307. // once and mapped once by the dynamic linker no matter how many realms
  308. // dlopen it (same path, same mapping), so these are already process-wide
  309. // statics; the registry just gives multiple opens of the same table a
  310. // single Db to share instead of a fresh one each time. A single realm's
  311. // event loop drives every call here — mpackdb has never been thread-safe —
  312. // so no mutex.
  313. //
  314. // The file is never compacted or rewritten while a handle on it is live:
  315. // only the FIRST open of a path in this process actually runs
  316. // engine.Db.open (and so is the only one that can compact-on-open, per
  317. // ticket #21's existing rule); every later open of the same path reuses
  318. // that live Db untouched, and its own primaryKey/indexes/compact args are
  319. // ignored — the table's schema was fixed by the first opener. Compaction
  320. // happens only when asked for explicitly (compactNow()) or when the LAST
  321. // handle on a path closes — unless the first opener passed compact=false.
  322. const SharedDb = struct {
  323. db: *engine.Db,
  324. key: []const u8, // owned; also the registry's stored key for this entry
  325. refcount: usize,
  326. };
  327. var registry: std.StringHashMapUnmanaged(*SharedDb) = .empty;
  328. fn acquireShared(path: []const u8, opts: engine.OpenOptions) ?*SharedDb {
  329. const key = engine.tableKey(gpa, path) catch return null;
  330. if (registry.get(key)) |existing| {
  331. gpa.free(key);
  332. existing.refcount += 1;
  333. return existing;
  334. }
  335. const db = engine.Db.open(gpa, path, opts) catch |e| {
  336. std.debug.print("mpackdb plugin: open failed: {s}\n", .{@errorName(e)});
  337. gpa.free(key);
  338. return null;
  339. };
  340. const shared = gpa.create(SharedDb) catch {
  341. db.close();
  342. gpa.free(key);
  343. return null;
  344. };
  345. shared.* = .{ .db = db, .key = key, .refcount = 1 };
  346. registry.put(gpa, key, shared) catch {
  347. db.close();
  348. gpa.destroy(shared);
  349. gpa.free(key);
  350. return null;
  351. };
  352. return shared;
  353. }
  354. /// Drop this handle's reference. On the LAST reference: compact away any
  355. /// tombstones (ticket #110 — the one moment compaction may run implicitly, and
  356. /// only when the first opener did not say compact=false, ticket #192) and
  357. /// close for real.
  358. fn releaseShared(shared: *SharedDb) void {
  359. shared.refcount -= 1;
  360. if (shared.refcount > 0) return;
  361. _ = registry.remove(shared.key);
  362. // compact=false of the opener is honoured here too (ticket #192): the tracker
  363. // opens its stores with compact=false and a stop shrank shows.mpack 1.12 GB -> 424 MB.
  364. if (shared.db.compact_on_open and shared.db.deleted.items.len > 0) {
  365. shared.db.compact() catch |e| {
  366. std.debug.print("mpackdb plugin: close-compact failed: {s}\n", .{@errorName(e)});
  367. };
  368. }
  369. shared.db.close();
  370. gpa.free(shared.key);
  371. gpa.destroy(shared);
  372. }
  373. const DbState = struct {
  374. shared: *SharedDb,
  375. };
  376. export fn hl_mpackdb_open(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  377. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  378. const raw_path = argv[0].data.string.ptr[0..argv[0].data.string.len];
  379. // mission 077: script-relative, like every other path in Hybriel.
  380. const path = resolvePath(raw_path) orelse return api.makeNull();
  381. defer gpa.free(path);
  382. var opts = engine.OpenOptions{};
  383. if (argc > 1 and argv[1].type == .hl_string and argv[1].data.string.len > 0) {
  384. opts.primary_key = argv[1].data.string.ptr[0..argv[1].data.string.len];
  385. }
  386. var index_names: [64][]const u8 = undefined;
  387. var index_count: usize = 0;
  388. if (argc > 2 and argv[2].type == .hl_object) {
  389. const obj = argv[2].data.object;
  390. for (obj.fields[0..obj.field_count]) |f| {
  391. if (f.value.type != .hl_string) continue;
  392. if (index_count >= index_names.len) break;
  393. index_names[index_count] = f.value.data.string.ptr[0..f.value.data.string.len];
  394. index_count += 1;
  395. }
  396. }
  397. opts.indexes = index_names[0..index_count];
  398. if (argc > 3 and argv[3].type == .hl_bool) {
  399. opts.compact = argv[3].data.boolean;
  400. }
  401. const shared = acquireShared(path, opts) orelse return api.makeNull();
  402. const state = gpa.create(DbState) catch {
  403. releaseShared(shared);
  404. return api.makeNull();
  405. };
  406. state.* = .{ .shared = shared };
  407. const handle = gpa.create(HlHandle) catch {
  408. releaseShared(shared);
  409. gpa.destroy(state);
  410. return api.makeNull();
  411. };
  412. handle.* = .{
  413. .context = @ptrCast(state),
  414. .call_fn = &handleCall,
  415. .close_fn = &handleClose,
  416. .type_name = hlStr("MPackDB"),
  417. };
  418. return api.makeHandle(handle);
  419. }
  420. fn errDeinit(val: *HlValue) callconv(.c) void {
  421. if (val.type == .hl_error) {
  422. const s = val.data.string;
  423. gpa.free(@constCast(s.ptr[0..s.len]));
  424. }
  425. }
  426. /// mission 077 (074 GAP 10): querying a field that carries no index is a
  427. /// MISTAKE, not an empty result — mpackdb only answers through binary-searched
  428. /// indexes, so `[]` was indistinguishable from "no such record" and hid the
  429. /// missing declaration. The message names the field, the op and every index the
  430. /// db was actually opened with (insertion order: primary key first).
  431. fn makeNoIndexError(db: *engine.Db, op: []const u8, field: []const u8) HlValue {
  432. var list: std.ArrayList(u8) = .empty;
  433. defer list.deinit(gpa);
  434. for (db.idx.keys()) |k| {
  435. if (list.items.len > 0) list.appendSlice(gpa, ", ") catch {};
  436. list.append(gpa, '\'') catch {};
  437. list.appendSlice(gpa, k) catch {};
  438. list.append(gpa, '\'') catch {};
  439. }
  440. const declared = if (list.items.len == 0) "none" else list.items;
  441. const msg = std.fmt.allocPrint(
  442. gpa,
  443. "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)",
  444. .{ op, field, declared },
  445. ) catch return api.makeError("mpackdb: no index on that field");
  446. var v = api.makeError(msg);
  447. v.deinit_fn = &errDeinit;
  448. return v;
  449. }
  450. fn handleClose(ctx: ?*anyopaque) callconv(.c) void {
  451. const state: *DbState = @ptrCast(@alignCast(ctx orelse return));
  452. releaseShared(state.shared);
  453. gpa.destroy(state);
  454. }
  455. fn pkStringDeinit(val: *HlValue) callconv(.c) void {
  456. if (val.type == .hl_string) {
  457. const s = val.data.string;
  458. gpa.free(@constCast(s.ptr[0..s.len]));
  459. }
  460. }
  461. fn handleCall(ctx: ?*anyopaque, op: HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  462. const state: *DbState = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  463. const db = state.shared.db;
  464. const method = op.ptr[0..op.len];
  465. if (std.mem.eql(u8, method, "insert")) {
  466. if (argc < 1 or argv[0].type != .hl_object) return api.makeNull();
  467. var arena_state = std.heap.ArenaAllocator.init(gpa);
  468. defer arena_state.deinit();
  469. const arena = arena_state.allocator();
  470. const rec = hlToMsgpack(arena, argv[0]);
  471. if (rec != .map) return api.makeNull();
  472. const res = db.insert(arena, rec, false) catch |e| {
  473. if (e != error.DuplicateKey) {
  474. std.debug.print("mpackdb plugin: insert failed: {s}\n", .{@errorName(e)});
  475. db.last_error = std.fmt.bufPrint(&db.last_error_buf, "insert failed: {s}", .{@errorName(e)}) catch "insert failed";
  476. }
  477. return api.makeNull();
  478. };
  479. switch (res) {
  480. .pk_num => |n| return api.makeNumber(n),
  481. .pk_str => |s| {
  482. const copy = gpa.dupe(u8, s) catch return api.makeNull();
  483. var out = api.makeString(copy);
  484. out.deinit_fn = &pkStringDeinit;
  485. return out;
  486. },
  487. .record => return api.makeBool(true),
  488. }
  489. }
  490. if (std.mem.eql(u8, method, "find_all")) {
  491. db.refresh();
  492. return makeStreamIterator(db);
  493. }
  494. if (std.mem.eql(u8, method, "find_pk")) {
  495. if (argc < 1) return api.makeNull();
  496. const key = hlKey(argv[0]) orelse return api.makeNull();
  497. var arena_state = std.heap.ArenaAllocator.init(gpa);
  498. const arena = arena_state.allocator();
  499. var locs: std.ArrayList(engine.Loc) = .empty;
  500. db.findPkLocs(arena, key, &locs) catch {
  501. arena_state.deinit();
  502. return api.makeNull();
  503. };
  504. return locsToIterator(db, arena_state, locs.items);
  505. }
  506. if (std.mem.eql(u8, method, "find_index")) {
  507. if (argc < 2 or argv[0].type != .hl_string) return api.makeNull();
  508. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  509. const key = hlKey(argv[1]) orelse return api.makeNull();
  510. var arena_state = std.heap.ArenaAllocator.init(gpa);
  511. const arena = arena_state.allocator();
  512. var locs: std.ArrayList(engine.Loc) = .empty;
  513. db.findIndexLocs(arena, field, key, &locs) catch |e| {
  514. arena_state.deinit();
  515. if (e == error.NoSuchIndex) return makeNoIndexError(db, "find", field);
  516. return api.makeNull();
  517. };
  518. return locsToIterator(db, arena_state, locs.items);
  519. }
  520. if (std.mem.eql(u8, method, "find_range")) {
  521. if (argc < 1 or argv[0].type != .hl_string) return api.makeNull();
  522. const field = argv[0].data.string.ptr[0..argv[0].data.string.len];
  523. const from: ?engine.Key = if (argc > 1) hlKey(argv[1]) else null;
  524. const to: ?engine.Key = if (argc > 2) hlKey(argv[2]) else null;
  525. var arena_state = std.heap.ArenaAllocator.init(gpa);
  526. const arena = arena_state.allocator();
  527. var locs: std.ArrayList(engine.Loc) = .empty;
  528. db.findRangeLocs(arena, field, from, to, &locs) catch |e| {
  529. arena_state.deinit();
  530. if (e == error.NoSuchIndex) return makeNoIndexError(db, "range", field);
  531. return api.makeNull();
  532. };
  533. return locsToIterator(db, arena_state, locs.items);
  534. }
  535. if (std.mem.eql(u8, method, "delete_pk")) {
  536. if (argc < 1) return api.makeNull();
  537. const key = hlKey(argv[0]) orelse return api.makeNull();
  538. var arena_state = std.heap.ArenaAllocator.init(gpa);
  539. defer arena_state.deinit();
  540. const arena = arena_state.allocator();
  541. var deleted: std.ArrayList(msgpack.Value) = .empty;
  542. const n = db.deletePk(arena, key, &deleted) catch |e| {
  543. std.debug.print("mpackdb plugin: delete failed: {s}\n", .{@errorName(e)});
  544. return api.makeNull();
  545. };
  546. return api.makeNumber(@floatFromInt(n));
  547. }
  548. if (std.mem.eql(u8, method, "update_pk")) {
  549. if (argc < 2 or argv[1].type != .hl_object) return api.makeNull();
  550. const key = hlKey(argv[0]) orelse return api.makeNull();
  551. var arena_state = std.heap.ArenaAllocator.init(gpa);
  552. defer arena_state.deinit();
  553. const arena = arena_state.allocator();
  554. const rec = hlToMsgpack(arena, argv[1]);
  555. if (rec != .map) return api.makeNull();
  556. // THE KEY COMES FROM THE ARGUMENT (ticket #171, as in the JS mpackdb): a record
  557. // that does not carry the primary key gets it from `key`, so update never
  558. // refuses or silently drops a record for want of it.
  559. var full = rec;
  560. if (db.pk) |p| {
  561. var carried = false;
  562. for (rec.map) |en| {
  563. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) {
  564. carried = en.value != .nil and en.value != .undef;
  565. break;
  566. }
  567. }
  568. if (!carried) {
  569. var list: std.ArrayList(msgpack.Entry) = .empty;
  570. for (rec.map) |en| {
  571. if (en.key == .str and std.mem.eql(u8, en.key.str, p)) continue;
  572. list.append(arena, en) catch return api.makeNull();
  573. }
  574. const kv: msgpack.Value = switch (key) {
  575. .num => |x| .{ .number = x },
  576. .str => |x| .{ .str = x },
  577. };
  578. list.append(arena, .{ .key = .{ .str = p }, .value = kv }) catch return api.makeNull();
  579. full = .{ .map = list.items };
  580. }
  581. }
  582. const n = db.updatePk(arena, key, full) catch |e| {
  583. if (e == error.RecordLacksPrimaryKey) {
  584. 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";
  585. return api.makeNull();
  586. }
  587. if (e != error.DuplicateKey) {
  588. std.debug.print("mpackdb plugin: update failed: {s}\n", .{@errorName(e)});
  589. }
  590. return api.makeNull();
  591. };
  592. return api.makeNumber(@floatFromInt(n));
  593. }
  594. if (std.mem.eql(u8, method, "count")) {
  595. var arena_state = std.heap.ArenaAllocator.init(gpa);
  596. defer arena_state.deinit();
  597. const arena = arena_state.allocator();
  598. db.refresh();
  599. var scanner = engine.Db.Scanner.init(db, arena, true);
  600. defer scanner.deinit();
  601. const n = scanner.countLive() catch 0;
  602. return api.makeNumber(@floatFromInt(n));
  603. }
  604. if (std.mem.eql(u8, method, "compact")) {
  605. db.compact() catch |e| {
  606. std.debug.print("mpackdb plugin: compact failed: {s}\n", .{@errorName(e)});
  607. };
  608. return api.makeNull();
  609. }
  610. if (std.mem.eql(u8, method, "persist")) {
  611. db.persistNow() catch |e| {
  612. std.debug.print("mpackdb plugin: persist failed: {s}\n", .{@errorName(e)});
  613. };
  614. return api.makeNull();
  615. }
  616. if (std.mem.eql(u8, method, "last_error")) {
  617. return api.makeString(db.last_error);
  618. }
  619. // The primary key field name with its */@/! prefixes stripped — the .hl
  620. // wrapper needs the bare name to route find(field, …) to find_pk.
  621. if (std.mem.eql(u8, method, "pk_name")) {
  622. const p = db.pk orelse return api.makeNull();
  623. return api.makeString(p);
  624. }
  625. return api.makeNull();
  626. }
  627. /// The matches at `locs` as a cursor that decodes ONE record per next() from the
  628. /// (refcounted) data file the offsets are into (mission 393). The locations and the tombstone filter
  629. /// were fixed when the query ran, so the cursor is a snapshot: later writes, deletes or a
  630. /// compaction do not change what it yields. Without an open data file it falls back to
  631. /// decoding eagerly.
  632. fn locsToIterator(db: *engine.Db, arena_state: std.heap.ArenaAllocator, locs: []const engine.Loc) HlValue {
  633. var st = arena_state;
  634. if (db.retainDataGen()) |gen| {
  635. const state = gpa.create(StreamIterState) catch {
  636. gen.release();
  637. st.deinit();
  638. return api.makeNull();
  639. };
  640. const copy = gpa.dupe(engine.Loc, locs) catch {
  641. gen.release();
  642. gpa.destroy(state);
  643. st.deinit();
  644. return api.makeNull();
  645. };
  646. st.deinit(); // the query arena (locs) is done with
  647. state.* = .{ .arena_state = std.heap.ArenaAllocator.init(gpa), .locs = copy, .fd = gen.fd, .gen = gen };
  648. return finishStream(state);
  649. }
  650. const arena = st.allocator();
  651. var records: std.ArrayList(msgpack.Value) = .empty;
  652. for (locs) |loc| {
  653. const rec = db.readAt(arena, loc) catch continue;
  654. records.append(arena, rec) catch break;
  655. }
  656. const slice = records.toOwnedSlice(arena) catch &.{};
  657. return makeRecordIterator(@constCast(slice), st);
  658. }
  659. fn dataIdSize(path: [:0]const u8) struct { ino: u64, size: u64 } {
  660. const linux = std.os.linux;
  661. var stx: linux.Statx = undefined;
  662. std.debug.assert(linux.statx(linux.AT.FDCWD, path, 0, linux.STATX.BASIC_STATS, &stx) == 0);
  663. return .{ .ino = stx.ino, .size = stx.size };
  664. }
  665. fn closeKeepsFile(compact: bool, name: []const u8) !struct { before: @TypeOf(dataIdSize("")), after: @TypeOf(dataIdSize("")) } {
  666. const testing = std.testing;
  667. const dir: []const u8 = if (std.c.getenv("TMPDIR")) |t| std.mem.span(t) else "/tmp";
  668. var buf: [512]u8 = undefined;
  669. const base = try std.fmt.bufPrint(&buf, "{s}/mpackdb-192-{d}-{s}", .{ dir, std.os.linux.getpid(), name });
  670. var pbuf: [520]u8 = undefined;
  671. const data = try std.fmt.bufPrintZ(&pbuf, "{s}.mpack", .{base});
  672. const suffixes = [_][]const u8{ ".mpack", ".meta.json", ".idxstate.json", ".lock", ".flock", ".id.txt" };
  673. for (suffixes) |sf| {
  674. var b: [530]u8 = undefined;
  675. const f = try std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf });
  676. _ = std.os.linux.unlink(f);
  677. }
  678. defer for (suffixes) |sf| {
  679. var b: [530]u8 = undefined;
  680. const f = std.fmt.bufPrintZ(&b, "{s}{s}", .{ base, sf }) catch continue;
  681. _ = std.os.linux.unlink(f);
  682. };
  683. var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
  684. defer arena_state.deinit();
  685. const arena = arena_state.allocator();
  686. // first process life: write rows and tombstones, close (compact=false: nothing may compact)
  687. {
  688. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = false }) orelse return error.OpenFailed;
  689. for (0..20) |i| {
  690. const entries = try arena.alloc(msgpack.Entry, 1);
  691. entries[0] = .{ .key = .{ .str = "n" }, .value = .{ .number = @floatFromInt(i) } };
  692. _ = try sh.db.insert(arena, .{ .map = entries }, false);
  693. }
  694. releaseShared(sh);
  695. }
  696. const sh = acquireShared(base, .{ .primary_key = "*id", .compact = compact }) orelse return error.OpenFailed;
  697. const before = dataIdSize(data);
  698. var gone: std.ArrayList(msgpack.Value) = .empty;
  699. for (1..11) |i| _ = try sh.db.deletePk(arena, .{ .num = @floatFromInt(i) }, &gone);
  700. releaseShared(sh);
  701. return .{ .before = before, .after = dataIdSize(data) };
  702. }
  703. test "#192: closing the last handle of a compact=false table leaves the data file alone" {
  704. const r = try closeKeepsFile(false, "off");
  705. try std.testing.expectEqual(r.before.ino, r.after.ino);
  706. try std.testing.expectEqual(r.before.size, r.after.size);
  707. }
  708. test "#192: closing the last handle of a compact=true table still compacts" {
  709. const r = try closeKeepsFile(true, "on");
  710. try std.testing.expect(r.after.size < r.before.size);
  711. }
  712. test {
  713. _ = msgpack;
  714. _ = engine;
  715. }

Branches

Latest commits

  • 6280c92fre-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 147744bftests/migration: the fixture app origin follows MIGRATION_GATE_TESTAPP_PORT (oldstore-009 OLD_TESTAPP)mre
  • 48cd36bctests/migration: ports from env (MIGRATION_GATE_PORT, MIGRATION_GATE_TESTAPP_PORT); 8395/8396 were taken by a foreign servermre
  • 3d9b2fd8docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 19b7e3c3deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • c8a596f4re-vendor Hybriel 66c3db71 (web batch 4); e2e: main menu marked after in-place sign-in is a normal check; report 014mre
  • 8f3dc1ectests: delivery allow-list for the stopped server's network errors uses the gate port, not 8700mre
  • 9cc8eddftests: notify and iplimit gate Chrome ports from env (NOTIFY_GATE_CHROME, IPLIMIT_GATE_CHROME_A/B)mre
  • d6da2d02tests: delivery and migration gate ports from env (DELIVERY_GATE_PORT, DELIVERY_GATE_CHROME, MIGRATION_GATE_CHROME) — hard-coded 8700-8719 collided with a worker during deploymre
  • 7276a008ident mission 013: re-vendor Hybriel master f9614007 (#200, #202 mpackdb copy fix); gates and e2e rerunmre
  • e13e30c3ident mission 013: report, mission, repro, LOGmre
  • eff734f3ident mission 013: in-place sign-out also closes the code step (no leftover code form); checksmre
  • b7a61546ident mission 013: e2e — in-place main-menu mark kept as a known gapmre
  • 59b43d81ident mission 013: sign out everywhere keeps this browser's own (signed-out) session so the page goes on in placemre
  • 716e14ffident mission 013: browser gate — Bob signs out everywhere (no second code request)mre
  • 5885f1c9ident mission 013 step 2: stopgap reload removed (in-place sign-in/out reach the shell via emit, notices back, route-marked main menu), gates updatedmre
  • 734ac0a9ident mission 013 step 1: re-vendor Hybriel ce6f2e0a (plugins whole; bin/ is git-ignored)mre
  • b37875ccident mission 012 part 3: real-Chrome fixes (brand 44 px, identity form width), e2e walk, report, logmre
  • f989c2ebident mission 012: stopgap reload after in-place sign-in/sign-out (until hybriel#193), gates wait for cold start, welcome end reloadsmre
  • 443291d4ident mission 012: /start on its own shell (no account), browser gate 152/0, reportmre