@hakodb/client 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Soft-delete / sweeper / restore smoke (core 0.20.0 FFI sync).
3
+ *
4
+ * node --import tsx examples/node/softdel.ts
5
+ */
6
+ import path from "node:path";
7
+ import fs from "node:fs";
8
+ import os from "node:os";
9
+ import { fileURLToPath } from "node:url";
10
+ import { HakoClient } from "../../src/index.ts";
11
+
12
+ const repoRoot = path.resolve(
13
+ path.dirname(fileURLToPath(import.meta.url)),
14
+ "..", ".."
15
+ );
16
+ const libraryPath = path.join(repoRoot, "native", "hakodb.dll");
17
+
18
+ async function main(): Promise<void> {
19
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hako-softdel-"));
20
+ const db = await HakoClient.open(path.join(dir, "smoke.db"), { libraryPath });
21
+ try {
22
+ await db.set("users", "u1", { name: "Alice", age: 32 });
23
+
24
+ // Default delete is soft since core 0.20.0.
25
+ await db.delete("users", "u1");
26
+ if ((await db.get("users", "u1")).exists) {
27
+ throw new Error("deleted doc must be invisible");
28
+ }
29
+
30
+ const avail = await db.restoreAvailable();
31
+ if (!Array.isArray(avail) || avail.length !== 1 || avail[0].col !== "users" || avail[0].id !== "u1") {
32
+ throw new Error("restoreAvailable mismatch: " + JSON.stringify(avail));
33
+ }
34
+
35
+ await db.restore("users", "u1");
36
+ if (!(await db.get("users", "u1")).exists) {
37
+ throw new Error("restore should bring the doc back");
38
+ }
39
+ if ((await db.restoreAvailable()).length !== 0) {
40
+ throw new Error("record should be consumed after restore");
41
+ }
42
+
43
+ // Force parity: legacy shape retains nothing.
44
+ await db.set("users", "u2", { name: "Bob" });
45
+ await db.deleteEx("users", "u2", true);
46
+ if ((await db.restoreAvailable()).length !== 0) {
47
+ throw new Error("force delete must not retain");
48
+ }
49
+
50
+ // deleteQueue shares the shape; nothing is due in a fresh engine.
51
+ const queue = await db.deleteQueue();
52
+ if (!Array.isArray(queue) || queue.length !== 0) {
53
+ throw new Error("deleteQueue mismatch: " + JSON.stringify(queue));
54
+ }
55
+
56
+ // Escape hatch works regardless of maintenance mode.
57
+ const swept = await db.sweepNow();
58
+ if (swept < 0) throw new Error("sweepNow failed: " + swept);
59
+
60
+ console.log("soft-delete smoke OK (sweepNow=" + swept + ")");
61
+ } finally {
62
+ await db.close();
63
+ fs.rmSync(dir, { recursive: true, force: true });
64
+ }
65
+ }
66
+
67
+ main().catch((err) => {
68
+ console.error(err);
69
+ process.exit(1);
70
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hakodb/client",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "High-level HakoDB JavaScript/TypeScript client for Node.js and Bun",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/client.ts CHANGED
@@ -766,6 +766,44 @@ export class HakoClient {
766
766
  ensureOk(this.native.engineDeleteLocal(this.engine, collection, docId), this.native, 'engineDeleteLocal');
767
767
  }
768
768
 
769
+ /** Delete with an explicit mode: force=true reproduces the legacy
770
+ * tombstone-only shape. Default `delete` is soft since core 0.20.0
771
+ * (restoreable via restore() until the sweeper purges the record). */
772
+ async deleteEx(collection: string, docId: string, force: boolean): Promise<void> {
773
+ this.assertOpen();
774
+ ensureOk(this.native.engineDeleteEx(this.engine, collection, docId, force), this.native, 'engineDeleteEx');
775
+ }
776
+
777
+ /** Restore a soft-deleted doc from its retention record (fresh version;
778
+ * consumes the record). Refuses when the id was re-put (cancel rule) or
779
+ * no record exists. */
780
+ async restore(collection: string, docId: string): Promise<void> {
781
+ this.assertOpen();
782
+ ensureOk(this.native.engineRestore(this.engine, collection, docId), this.native, 'engineRestore');
783
+ }
784
+
785
+ /** Restoreable records, all collections or one (soft-delete retention queue). */
786
+ async restoreAvailable(collection?: string): Promise<Array<{ col: string; id: string; deleted_at: number; scheduled_at: number; bytes: number }>> {
787
+ this.assertOpen();
788
+ return JSON.parse(this.native.engineRestoreAvailable(this.engine, collection ?? null) ?? '[]');
789
+ }
790
+
791
+ /** Due-for-sweep subset of the retention queue (same shape as restoreAvailable). */
792
+ async deleteQueue(collection?: string): Promise<Array<{ col: string; id: string; deleted_at: number; scheduled_at: number; bytes: number }>> {
793
+ this.assertOpen();
794
+ return JSON.parse(this.native.engineDeleteQueue(this.engine, collection ?? null) ?? '[]');
795
+ }
796
+
797
+ /** Run one retention sweep pass now; returns the purged record count. */
798
+ async sweepNow(): Promise<number> {
799
+ this.assertOpen();
800
+ const n = this.native.engineSweepNow(this.engine);
801
+ if (n < 0) {
802
+ throw new Error(`engineSweepNow: ${this.native.lastError()}`);
803
+ }
804
+ return n;
805
+ }
806
+
769
807
  /** Mark a collection local-only (never syncs) or rejoin it with `local=false`. */
770
808
  async setCollectionLocal(collection: string, local: boolean): Promise<void> {
771
809
  this.assertOpen();
@@ -1562,6 +1600,14 @@ export class WriteBatch {
1562
1600
  return this;
1563
1601
  }
1564
1602
 
1603
+ /** Batch delete with an explicit mode: 0/soft = restoreable, force = legacy
1604
+ * tombstone-only. batchDelete() keeps legacy/force for frozen contracts. */
1605
+ deleteEx(docRef: DocumentReference, force: boolean): WriteBatch {
1606
+ this.ensureActive();
1607
+ ensureOk(this.native.batchDeleteEx(this.handle, docRef._collection, docRef._id, force), this.native, 'batchDeleteEx');
1608
+ return this;
1609
+ }
1610
+
1565
1611
  async commit(): Promise<void> {
1566
1612
  this.ensureActive();
1567
1613
  ensureOk(this.native.batchCommit(this.client.engineHandle(), this.handle), this.native, 'batchCommit');
package/src/native.ts CHANGED
@@ -61,6 +61,11 @@ export interface NativeBindings {
61
61
  engineGet(engine: Handle, collection: string, docId: string): Handle;
62
62
  engineDelete(engine: Handle, collection: string, docId: string): number;
63
63
  engineDeleteLocal(engine: Handle, collection: string, docId: string): number;
64
+ engineDeleteEx(engine: Handle, collection: string, docId: string, force: boolean): number;
65
+ engineRestore(engine: Handle, collection: string, docId: string): number;
66
+ engineRestoreAvailable(engine: Handle, collection: string | null): string | null;
67
+ engineDeleteQueue(engine: Handle, collection: string | null): string | null;
68
+ engineSweepNow(engine: Handle): number;
64
69
  engineSetCollectionLocal(engine: Handle, collection: string, local: number): number;
65
70
  engineReplicateKey(engine: Handle, collection: string, docId: string): number;
66
71
  engineReplicateCollection(engine: Handle, collection: string): number;
@@ -79,6 +84,7 @@ export interface NativeBindings {
79
84
  batchFree(batch: Handle): void;
80
85
  batchSet(batch: Handle, collection: string, docId: string, doc: Handle): number;
81
86
  batchDelete(batch: Handle, collection: string, docId: string): number;
87
+ batchDeleteEx(batch: Handle, collection: string, docId: string, force: boolean): number;
82
88
  batchCommit(engine: Handle, batch: Handle): number;
83
89
 
84
90
  // Serializable Transactions
@@ -333,6 +339,12 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
333
339
  const ffi = await import('bun:ffi');
334
340
  const { dlopen, FFIType, CString, JSCallback, toArrayBuffer } = ffi as any;
335
341
 
342
+ // Watch trampolines must outlive their native watch: the engine invokes
343
+ // them from its watch thread, and a GC'd JSCallback would leave that
344
+ // thread calling freed memory (issue #21). Closed in watchFree after
345
+ // the native join.
346
+ const watchTrampolines = new Map<unknown, { close(): void }>();
347
+
336
348
  const symbols = dlopen(libPath, {
337
349
  hk_engine_open: { args: [FFIType.cstring], returns: FFIType.ptr },
338
350
  hk_engine_is_indexes_ready: { args: [FFIType.ptr], returns: FFIType.bool },
@@ -377,6 +389,16 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
377
389
  hk_engine_get: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.ptr },
378
390
  hk_engine_delete: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
379
391
  hk_engine_delete_local: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
392
+ hk_engine_delete_ext: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.i32], returns: FFIType.i32 },
393
+ hk_engine_restore: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
394
+ hk_engine_restore_available: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.ptr },
395
+ hk_engine_delete_queue: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.ptr },
396
+ hk_engine_sweep_now: { args: [FFIType.ptr], returns: FFIType.i32 },
397
+ hk_net_syncer_new: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.ptr },
398
+ hk_net_syncer_start: { args: [FFIType.ptr, FFIType.u16], returns: FFIType.i32 },
399
+ hk_net_syncer_set_discovery: { args: [FFIType.ptr, FFIType.i32], returns: FFIType.i32 },
400
+ hk_net_syncer_status: { args: [FFIType.ptr], returns: FFIType.ptr },
401
+ hk_net_syncer_free: { args: [FFIType.ptr], returns: FFIType.void },
380
402
  hk_engine_set_collection_local: { args: [FFIType.ptr, FFIType.cstring, FFIType.i32], returns: FFIType.i32 },
381
403
  hk_engine_replicate_key: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
382
404
  hk_engine_replicate_collection: { args: [FFIType.ptr, FFIType.cstring], returns: FFIType.i32 },
@@ -415,6 +437,7 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
415
437
  hk_batch_free: { args: [FFIType.ptr], returns: FFIType.void },
416
438
  hk_batch_set: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.ptr], returns: FFIType.i32 },
417
439
  hk_batch_delete: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring], returns: FFIType.i32 },
440
+ hk_batch_delete_ext: { args: [FFIType.ptr, FFIType.cstring, FFIType.cstring, FFIType.i32], returns: FFIType.i32 },
418
441
  hk_batch_commit: { args: [FFIType.ptr, FFIType.ptr], returns: FFIType.i32 },
419
442
 
420
443
  hk_transaction_begin: { args: [FFIType.ptr], returns: FFIType.ptr },
@@ -614,12 +637,26 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
614
637
  configSetBackgroundMaintenance: (c, e) => symbols.hk_config_set_background_maintenance(c, e),
615
638
 
616
639
  engineWatch: (engine, collection, callback) => {
640
+ // The engine calls the snapshot callback from its native watch
641
+ // thread — bun requires a threadsafe trampoline for that (marshaled
642
+ // onto the JS thread; issue #21).
617
643
  const cb = new JSCallback((c: any, p: any, kind: number) => {
618
644
  callback(new CString(c).toString(), new CString(p).toString(), kind);
619
- }, { args: [FFIType.ptr, FFIType.ptr, FFIType.i32], returns: FFIType.void });
620
- return symbols.hk_engine_watch(engine, toC(collection), cb, null);
645
+ }, { args: [FFIType.ptr, FFIType.ptr, FFIType.i32], returns: FFIType.void, threadsafe: true });
646
+ const watch = symbols.hk_engine_watch(engine, toC(collection), cb, null);
647
+ watchTrampolines.set(watch, cb);
648
+ return watch;
649
+ },
650
+ watchFree: (watch) => {
651
+ // hk_watch_free joins the watch thread — no invocation can follow,
652
+ // so the trampoline is dead and can be closed + dropped.
653
+ symbols.hk_watch_free(watch);
654
+ const cb = watchTrampolines.get(watch);
655
+ if (cb) {
656
+ cb.close();
657
+ watchTrampolines.delete(watch);
658
+ }
621
659
  },
622
- watchFree: (watch) => symbols.hk_watch_free(watch),
623
660
 
624
661
  docNew: () => symbols.hk_doc_new(),
625
662
  docFree: (doc) => symbols.hk_doc_free(doc),
@@ -638,6 +675,11 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
638
675
  engineGet: (engine, collection, docId) => symbols.hk_engine_get(engine, toC(collection), toC(docId)),
639
676
  engineDelete: (engine, collection, docId) => symbols.hk_engine_delete(engine, toC(collection), toC(docId)),
640
677
  engineDeleteLocal: (engine, collection, docId) => symbols.hk_engine_delete_local(engine, toC(collection), toC(docId)),
678
+ engineDeleteEx: (engine, collection, docId, force) => symbols.hk_engine_delete_ext(engine, toC(collection), toC(docId), force ? 1 : 0),
679
+ engineRestore: (engine, collection, docId) => symbols.hk_engine_restore(engine, toC(collection), toC(docId)),
680
+ engineRestoreAvailable: (engine, collection) => ptrToStringAndFree(symbols.hk_engine_restore_available(engine, (collection ? toC(collection) : null) as unknown as string)),
681
+ engineDeleteQueue: (engine, collection) => ptrToStringAndFree(symbols.hk_engine_delete_queue(engine, (collection ? toC(collection) : null) as unknown as string)),
682
+ engineSweepNow: (engine) => symbols.hk_engine_sweep_now(engine),
641
683
  engineSetCollectionLocal: (engine, collection, local) => symbols.hk_engine_set_collection_local(engine, toC(collection), local),
642
684
  engineReplicateKey: (engine, collection, docId) => symbols.hk_engine_replicate_key(engine, toC(collection), toC(docId)),
643
685
  engineReplicateCollection: (engine, collection) => symbols.hk_engine_replicate_collection(engine, toC(collection)),
@@ -655,6 +697,7 @@ async function createBunBindings(libPath: string): Promise<NativeBindings> {
655
697
  batchFree: (batch) => symbols.hk_batch_free(batch),
656
698
  batchSet: (batch, collection, docId, doc) => symbols.hk_batch_set(batch, toC(collection), toC(docId), doc),
657
699
  batchDelete: (batch, collection, docId) => symbols.hk_batch_delete(batch, toC(collection), toC(docId)),
700
+ batchDeleteEx: (batch, collection, docId, force) => symbols.hk_batch_delete_ext(batch, toC(collection), toC(docId), force ? 1 : 0),
658
701
  batchCommit: (engine, batch) => symbols.hk_batch_commit(engine, batch),
659
702
 
660
703
  transactionBegin: (engine) => symbols.hk_transaction_begin(engine),
@@ -991,6 +1034,11 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
991
1034
  hk_engine_get: lib.func('HK_Doc* hk_engine_get(HK_Engine* engine, const char* collection, const char* doc_id)'),
992
1035
  hk_engine_delete: lib.func('int hk_engine_delete(HK_Engine* engine, const char* collection, const char* doc_id)'),
993
1036
  hk_engine_delete_local: lib.func('int hk_engine_delete_local(HK_Engine* engine, const char* collection, const char* doc_id)'),
1037
+ hk_engine_delete_ext: lib.func('int hk_engine_delete_ext(HK_Engine* engine, const char* collection, const char* doc_id, int32_t mode)'),
1038
+ hk_engine_restore: lib.func('int hk_engine_restore(HK_Engine* engine, const char* collection, const char* doc_id)'),
1039
+ hk_engine_restore_available: lib.func('HeapStr hk_engine_restore_available(HK_Engine* engine, const char* collection)'),
1040
+ hk_engine_delete_queue: lib.func('HeapStr hk_engine_delete_queue(HK_Engine* engine, const char* collection)'),
1041
+ hk_engine_sweep_now: lib.func('int hk_engine_sweep_now(HK_Engine* engine)'),
994
1042
  hk_engine_set_collection_local: lib.func('int hk_engine_set_collection_local(HK_Engine* engine, const char* collection, int local)'),
995
1043
  hk_engine_replicate_key: lib.func('int hk_engine_replicate_key(HK_Engine* engine, const char* collection, const char* doc_id)'),
996
1044
  hk_engine_replicate_collection: lib.func('int hk_engine_replicate_collection(HK_Engine* engine, const char* collection)'),
@@ -1029,6 +1077,7 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
1029
1077
  hk_batch_free: lib.func('void hk_batch_free(HK_Batch* batch)'),
1030
1078
  hk_batch_set: lib.func('int hk_batch_set(HK_Batch* batch, const char* collection, const char* doc_id, const HK_Doc* doc)'),
1031
1079
  hk_batch_delete: lib.func('int hk_batch_delete(HK_Batch* batch, const char* collection, const char* doc_id)'),
1080
+ hk_batch_delete_ext: lib.func('int hk_batch_delete_ext(HK_Batch* batch, const char* collection, const char* doc_id, int32_t mode)'),
1032
1081
  hk_batch_commit: lib.func('int hk_batch_commit(HK_Engine* engine, HK_Batch* batch)'),
1033
1082
 
1034
1083
  hk_transaction_begin: lib.func('HK_Transaction* hk_transaction_begin(HK_Engine* engine)'),
@@ -1257,6 +1306,11 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
1257
1306
  engineGet: (engine, collection, docId) => fn.hk_engine_get(engine, collection, docId),
1258
1307
  engineDelete: (engine, collection, docId) => fn.hk_engine_delete(engine, collection, docId),
1259
1308
  engineDeleteLocal: (engine, collection, docId) => fn.hk_engine_delete_local(engine, collection, docId),
1309
+ engineDeleteEx: (engine, collection, docId, force) => fn.hk_engine_delete_ext(engine, collection, docId, force ? 1 : 0),
1310
+ engineRestore: (engine, collection, docId) => fn.hk_engine_restore(engine, collection, docId),
1311
+ engineRestoreAvailable: (engine, collection) => ptrToStringAndFree(fn.hk_engine_restore_available(engine, collection as unknown as string)),
1312
+ engineDeleteQueue: (engine, collection) => ptrToStringAndFree(fn.hk_engine_delete_queue(engine, collection as unknown as string)),
1313
+ engineSweepNow: (engine) => fn.hk_engine_sweep_now(engine),
1260
1314
  engineSetCollectionLocal: (engine, collection, local) => fn.hk_engine_set_collection_local(engine, collection, local),
1261
1315
  engineReplicateKey: (engine, collection, docId) => fn.hk_engine_replicate_key(engine, collection, docId),
1262
1316
  engineReplicateCollection: (engine, collection) => fn.hk_engine_replicate_collection(engine, collection),
@@ -1274,6 +1328,7 @@ async function createNodeBindings(libPath: string): Promise<NativeBindings> {
1274
1328
  batchFree: (batch) => fn.hk_batch_free(batch),
1275
1329
  batchSet: (batch, collection, docId, doc) => fn.hk_batch_set(batch, collection, docId, doc),
1276
1330
  batchDelete: (batch, collection, docId) => fn.hk_batch_delete(batch, collection, docId),
1331
+ batchDeleteEx: (batch, collection, docId, force) => fn.hk_batch_delete_ext(batch, collection, docId, force ? 1 : 0),
1277
1332
  batchCommit: (engine, batch) => fn.hk_batch_commit(engine, batch),
1278
1333
 
1279
1334
  transactionBegin: (engine) => fn.hk_transaction_begin(engine),