@kedem/okdb 3.0.0 → 3.0.1

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.
Files changed (62) hide show
  1. package/CHANGELOG.md +38 -3
  2. package/README.md +68 -36
  3. package/bin/okdb +1 -1
  4. package/docs/auth-and-sync.md +30 -24
  5. package/docs/auth-permissions.md +5 -4
  6. package/docs/c-bridge.md +94 -0
  7. package/docs/change-log.md +78 -35
  8. package/docs/data-model.md +32 -8
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/files.md +53 -18
  13. package/docs/fts.md +48 -23
  14. package/docs/functions.md +107 -56
  15. package/docs/getting-started.md +125 -9
  16. package/docs/http-api.md +68 -11
  17. package/docs/http-cluster.md +80 -88
  18. package/docs/index.md +33 -15
  19. package/docs/indexes.md +53 -17
  20. package/docs/licensing.md +18 -4
  21. package/docs/logging.md +11 -22
  22. package/docs/manifest.json +4 -2
  23. package/docs/migration.md +40 -15
  24. package/docs/pipelines.md +96 -32
  25. package/docs/plugins.md +47 -15
  26. package/docs/process-registry.md +23 -24
  27. package/docs/processors.md +26 -23
  28. package/docs/querying.md +102 -29
  29. package/docs/queue.md +167 -51
  30. package/docs/resolved-fields.md +24 -1
  31. package/docs/subscriptions.md +4 -4
  32. package/docs/sync.md +9 -6
  33. package/docs/time-machine.md +40 -11
  34. package/docs/transactions.md +63 -15
  35. package/docs/ttl.md +34 -13
  36. package/docs/upgrade-2.0.md +32 -15
  37. package/docs/upgrade-2.1.md +10 -12
  38. package/docs/upgrade-3.0.md +144 -0
  39. package/docs/views.md +131 -42
  40. package/index.js +1 -1
  41. package/native/linux-x64-gnu/okdb +0 -0
  42. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  43. package/native-loader.js +1 -1
  44. package/okdb-native.js +1 -1
  45. package/package.json +1 -1
  46. package/types/environment.d.ts +32 -11
  47. package/types/errors.d.ts +20 -0
  48. package/types/features/admin.d.ts +3 -5
  49. package/types/features/api.d.ts +5 -7
  50. package/types/features/embeddings.d.ts +8 -7
  51. package/types/features/engines.d.ts +9 -1
  52. package/types/features/files.d.ts +2 -1
  53. package/types/features/fts.d.ts +3 -3
  54. package/types/features/functions.d.ts +14 -8
  55. package/types/features/pipelines.d.ts +10 -10
  56. package/types/features/queue.d.ts +15 -10
  57. package/types/features/sync.d.ts +7 -0
  58. package/types/features/time-machine.d.ts +3 -0
  59. package/types/index.d.ts +3 -0
  60. package/types/okdb.d.ts +70 -7
  61. package/types/options.d.ts +12 -8
  62. package/docs/OKDB-ARCHITECTURE.md +0 -1061
package/docs/functions.md CHANGED
@@ -9,7 +9,7 @@ They are designed for:
9
9
  - stable HTTP entry points
10
10
  - MCP-accessible orchestration routines
11
11
 
12
- Custom functions are **stored**, **versioned**, **validated**, **audited**, and executed in a per-process **sandbox thread**.
12
+ Custom functions are **stored**, **versioned**, **validated**, **audited**, and executed in a **sandbox**: an embedded JavaScript engine inside okdb's native core, separate from your Node.js runtime.
13
13
 
14
14
  ---
15
15
 
@@ -93,7 +93,7 @@ The runtime rejects scripts that use unsupported forms or forbidden symbols.
93
93
 
94
94
  ### Forbidden
95
95
 
96
- The current runtime rejects references to:
96
+ The runtime rejects (`FUNCTION_SCRIPT_FORBIDDEN_SYMBOL`) scripts that reference:
97
97
 
98
98
  - `require`
99
99
  - `import`
@@ -104,42 +104,53 @@ The current runtime rejects references to:
104
104
  - `child_process`
105
105
  - `worker_threads`
106
106
 
107
- Use `ctx.log(...)` instead of `console`.
107
+ Use `ctx.log(...)` instead of `console`. Referencing `ctx.okdb` in a function that is not
108
+ `unsafe: true` is rejected with `FUNCTION_SCRIPT_RESTRICTED_CTX_PROP`.
108
109
 
109
- ---
110
-
111
- ## Runtime model
110
+ ### Globals
112
111
 
113
- A function runs on **the node it was asked on**, in that node's per-process **sandbox thread**:
114
- a dedicated `worker_thread` with its own okdb instance, heap-capped from `runtime.memoryMb` via
115
- `resourceLimits`, with `terminate()` as the timeout/wedge watchdog. One sandbox per process per
116
- memory tier (in the common case — every function at the default `memoryMb` — exactly one thread),
117
- lazy-spawned and idle-reaped; invocations run concurrently in it, capped. Execution **never
118
- blocks the caller's main loop** — untrusted user code always runs off-loop — and containment is
119
- thread-level: a wedged function is `terminate()`d without taking the node's other work down.
120
- This is what makes "run the function locally" safe, so it no longer needs a separate worker
121
- process.
112
+ The sandbox is not Node.js: there is no `require`, no `Buffer`, no `process`, no file system, and
113
+ no code generation from strings (`eval` and `new Function(...)` throw `EvalError`). Besides the
114
+ standard language built-ins (`Object`, `Array`, `Map`, `Set`, `Promise`, `JSON`, `Math`, `Date`,
115
+ `RegExp`, typed arrays, `BigInt`, `Proxy`, `Reflect`, ...) a function sees:
122
116
 
123
- Sandbox concurrency is capped **per process** (`OKDB_FN_SANDBOX_CONCURRENCY`, default 4):
124
- invocations beyond the cap queue at the claim layer. Host-level CPU budgeting is the operator's
125
- job — size the number of okdb processes (and their sandbox caps) to the machine.
117
+ - `setTimeout` / `setInterval` / `clearTimeout` / `clearInterval`, `queueMicrotask`
118
+ - `URL`, `URLSearchParams`, `TextEncoder`, `TextDecoder`
119
+ - `AbortController`, `AbortSignal`, `structuredClone`
120
+ - `crypto` (`crypto.randomUUID()`, `crypto.getRandomValues()`, `crypto.subtle.digest()`)
121
+ - `fetch` — restricted, see [Network access](#network-access-fetch)
126
122
 
127
- Two invocation modes:
123
+ ---
128
124
 
129
- - **Synchronous** (`functions.run()` / HTTP execution) — routed straight to the local sandbox,
130
- no `~fn:requests` round-trip, lowest latency.
131
- - **Durable / run-eventually** (survive the caller, store the result) — a [queue](queue.md) job
132
- on a designated node. The `~fn:requests` / `~fn:responses` substrate is retained as the
133
- durable invocation mode (the UDP bus carries a wake hint so dispatch is ~ms).
125
+ ## Runtime model
134
126
 
135
- Either way: scripts are validated and compile-checked before storage; timeouts terminate and
136
- replace the executor; memory is capped; every run is written to a run ledger. This makes
137
- functions suitable for operational entry points without paying spawn cost on every call.
127
+ A function runs on **the process it was asked on**. Its code executes in an embedded JavaScript
128
+ engine (QuickJS) on a **sandbox thread** inside okdb's native core — not in Node's V8 and not with
129
+ access to your Node.js globals. Each running invocation has its own sandbox thread; threads are
130
+ started on first use and reaped after `OKDB_FN_SANDBOX_IDLE_MS` (default 30 000) idle. At most
131
+ `OKDB_FN_SANDBOX_CONCURRENCY` (default 4) invocations run at once per process; further ones wait.
132
+ A wedged or runaway function is interrupted on its own thread without affecting other runs.
133
+
134
+ The function's `ctx.env` / `ctx.okdb` calls are executed by the okdb instance that started the
135
+ run, on its thread. `functions.run()` is asynchronous: **the Node.js event loop keeps running
136
+ while the function executes** on its sandbox thread (timers and I/O callbacks fire as usual), and
137
+ each `ctx.env` / `ctx.okdb` call is served on the loop as it arrives. `functions.preview()` and
138
+ functions run inline by a sync processor are still served synchronously. Durable, run-eventually
139
+ invocation is a queue job (for example a queue-worker engine, see [Pipelines](./pipelines.md)).
140
+
141
+ Memory is bounded twice. Each run may grow the sandbox heap by at most the stored function's
142
+ `runtime.memoryMb` (default 32, or the `functions.memoryMb` constructor option); a run over it
143
+ fails with `FUNCTION_OOM` (`function sandbox out of memory (<n>MB heap cap)`) and the run record
144
+ has status `error`, while other runs are unaffected. Each sandbox thread's heap is also capped by
145
+ the `functions.memoryMb` constructor option (default 256 MB, minimum 32). Scripts are validated
146
+ and compile-checked before storage, and every run is written to the run ledger (`listRuns` /
147
+ `getRun`).
138
148
 
139
149
  ### Timeouts
140
150
 
141
- - **Run deadline** — `runtime.timeoutMs` on the stored function (default 5 000 ms) drives
142
- `ctx.signal` and the sandbox watchdog (`FUNCTION_TIMEOUT`). A single call can override it with
151
+ - **Run deadline** — `runtime.timeoutMs` on the stored function (default 5 000 ms) aborts
152
+ `ctx.signal`; a run still going after a further grace period (`OKDB_FN_SANDBOX_GRACE_MS`,
153
+ default 1 500 ms) is interrupted and fails with `FUNCTION_TIMEOUT`. A single call can override it with
143
154
  `functions.run(name, payload, { timeoutMs })`; the value must be a positive finite number
144
155
  (`FUNCTION_INVALID_TIMEOUT` otherwise) and is capped at `OKDB_FN_MAX_TIMEOUT_MS` (default
145
156
  600 000 ms), since a running call holds a sandbox slot for its whole deadline.
@@ -148,6 +159,9 @@ functions suitable for operational entry points without paying spawn cost on eve
148
159
  1 000 ms). A valid source is a bare arrow expression and evaluates in well under a millisecond;
149
160
  the bound only stops a source that smuggles top-level work.
150
161
 
162
+ The `functions` constructor option sets the defaults for new functions and the sandbox:
163
+ `new OKDB(path, { functions: { timeoutMs, memoryMb, allowFetch, maxCodeSizeBytes } })`.
164
+
151
165
  ### Network access (`fetch`)
152
166
 
153
167
  `fetch` inside a function is off unless the stored function's `runtime.allowedFetchDomains` permits the
@@ -162,6 +176,10 @@ altogether). Every hop is checked — the first URL **and each redirect**:
162
176
  vouching for it. `OKDB_FN_FETCH_ALLOW_PRIVATE=1` turns the block off for the whole process.
163
177
 
164
178
  Authorization, cookie and proxy-authorization headers are dropped when a redirect leaves the origin.
179
+ At most `OKDB_FN_FETCH_MAX_INFLIGHT` (default 32) sandbox fetches run at once per process, and a
180
+ response body is capped at `OKDB_FN_FETCH_MAX_BYTES` (default 32 MiB).
181
+
182
+ <!-- not-runnable: calls a host on the network -->
165
183
 
166
184
  ```js
167
185
  await env.functions.create({
@@ -175,10 +193,10 @@ await env.functions.create({
175
193
  > function anywhere, and `'*'` reached localhost and the LAN. A function that called a local service
176
194
  > through `'*'` must now list that host.
177
195
 
178
- > **Removed in 2.0:** the anonymous worker-population dispatch and the child-process **fork
179
- > pool** (`OKDB_FN_LEGACY_POOL`). Functions execute in the asking node's local sandbox. See
180
- > [Upgrading to 2.0](upgrade-2.0.md). If you don't want every HTTP node carrying a sandbox,
181
- > designate which nodes serve functions — placement is yours.
196
+ > **Changed in 3.0:** functions run in the native core's embedded engine instead of a Node.js
197
+ > `worker_thread`. The script contract, `ctx` API, globals, fetch rules and error codes are the
198
+ > same. The 2.x durable `~fn:requests` / `~fn:responses` dispatch is gone; use a queue job for
199
+ > run-eventually work.
182
200
 
183
201
  ---
184
202
 
@@ -267,7 +285,7 @@ The function must **not** write directly via `ctx.env`.
267
285
 
268
286
  The returned ops array shape:
269
287
 
270
- ```js
288
+ ```text
271
289
  [
272
290
  { action: 'put', key: 'some-key', value: { ... } },
273
291
  { action: 'remove', key: 'other-key' },
@@ -318,7 +336,7 @@ Change record notes:
318
336
  - `transaction(options)` — low-level transaction object
319
337
  - `txn(workOrOps, options?)` — convenience write-focused transaction helper
320
338
  - `queue` — queue feature for this env
321
- - `files` — files feature for this env: `upload`, `stream`, `read`, `remove`, `get`, `listPath`. `read(id)` resolves the whole blob as a Buffer (rejects with `status: 404` for an unknown id). A function's return value is structured-cloned out of the sandbox and stored as JSON, so convert bytes before returning them — e.g. `buf.toString('utf8')` or `buf.toString('base64')`; a raw Buffer comes back as an index-keyed object.
339
+ - `files` — files feature for this env: `upload`, `stream`, `read`, `remove`, `get`, `listPath`. `read(id)` resolves the whole blob as a Buffer (rejects with `status: 404` for an unknown id). A function's return value is stored as JSON, so convert bytes before returning them — e.g. `buf.toString('utf8')` or `buf.toString('base64')`.
322
340
 
323
341
  Example:
324
342
 
@@ -336,22 +354,26 @@ async (ctx) => {
336
354
 
337
355
  `txn(...)` is a **write-batch helper**, not a full read-your-own-writes transaction view.
338
356
 
339
- Preferred callback form:
357
+ Preferred callback form (inside a function body):
340
358
 
341
359
  ```js
342
- await ctx.env.txn((txn) => {
343
- txn.create('events', 'e1', { kind: 'view' });
344
- txn.create('events', 'e2', { kind: 'click' });
345
- });
360
+ async (ctx) => {
361
+ await ctx.env.txn((txn) => {
362
+ txn.create('events', 'e1', { kind: 'view' });
363
+ txn.create('events', 'e2', { kind: 'click' });
364
+ });
365
+ };
346
366
  ```
347
367
 
348
368
  Also supported: ops arrays
349
369
 
350
370
  ```js
351
- await ctx.env.txn([
352
- { action: 'create', type: 'events', key: 'e1', value: { kind: 'view' } },
353
- ['create', 'events', 'e2', { kind: 'click' }],
354
- ]);
371
+ async (ctx) => {
372
+ await ctx.env.txn([
373
+ { action: 'create', type: 'events', key: 'e1', value: { kind: 'view' } },
374
+ ['create', 'events', 'e2', { kind: 'click' }],
375
+ ]);
376
+ };
355
377
  ```
356
378
 
357
379
  The `txn` object intentionally exposes **write methods only**:
@@ -378,6 +400,8 @@ an in-memory overlay or transactional read-your-own-writes view.
378
400
  By default a function can only access its own environment. Mark a function `unsafe: true` to additionally receive `ctx.okdb` — a privileged root facade. The name `unsafe` reflects the consequence: these functions can reach any env.
379
401
 
380
402
  ```js
403
+ await okdb.createEnvironment('analytics');
404
+
381
405
  await okdb.env('default').functions.create({
382
406
  name: 'copySummary',
383
407
  unsafe: true,
@@ -416,20 +440,20 @@ Use `ctx.log(...)` for structured function logs. All log levels are available:
416
440
  ctx.log('starting run', { function: ctx.info.functionName });
417
441
  ctx.log.info('doing work');
418
442
  ctx.log.warn('slow path');
419
- ctx.log.error('something broke', { err: err.message });
443
+ ctx.log.error('something broke', { code: 'E42' });
420
444
  return { ok: true };
421
445
  };
422
446
  ```
423
447
 
424
448
  Every entry emitted from a function is automatically stamped with run identity in the `meta` field:
425
449
 
426
- | `meta` field | Value |
427
- | --------------- | -------------------------------------------------------------------- |
428
- | `meta.feature` | `'functions'` |
429
- | `meta.env` | The environment name |
430
- | `meta.fn` | The function name |
431
- | `meta.runId` | Unique ID for this invocation |
432
- | `meta.runnerId` | Executor id (e.g. `'sandbox-12345'` — the sandbox thread's host pid) |
450
+ | `meta` field | Value |
451
+ | --------------- | --------------------------------------------------------------------- |
452
+ | `meta.feature` | `'functions'` |
453
+ | `meta.env` | The environment name |
454
+ | `meta.fn` | The function name |
455
+ | `meta.runId` | Unique ID for this invocation |
456
+ | `meta.runnerId` | Executor id (e.g. `'sandbox-12345'` — the pid of the running process) |
433
457
 
434
458
  The second argument to any log call becomes the `context` field in the log entry — this is the user-provided data visible in the Admin UI function log panel.
435
459
 
@@ -440,7 +464,8 @@ Function logs are suppressed from the console (they are stored in the run record
440
464
  ## JavaScript API
441
465
 
442
466
  ```js
443
- const env = okdb.env('analytics');
467
+ const env = await okdb.createEnvironment('analytics');
468
+ await env.registerType('events');
444
469
 
445
470
  await env.functions.create({
446
471
  name: 'countEvents',
@@ -453,6 +478,8 @@ console.log(run.status, run.result.value);
453
478
 
454
479
  For unsafe cross-env functions:
455
480
 
481
+ <!-- continues -->
482
+
456
483
  ```js
457
484
  await okdb.env('default').functions.create({
458
485
  name: 'crossEnvCount',
@@ -460,8 +487,28 @@ await okdb.env('default').functions.create({
460
487
  source: '(ctx) => ({ analytics: ctx.okdb.env("analytics").getCount("events") })',
461
488
  });
462
489
 
463
- const run = await okdb.env('default').functions.run('crossEnvCount');
464
- console.log(run.result.value);
490
+ const run2 = await okdb.env('default').functions.run('crossEnvCount');
491
+ console.log(run2.result.value);
492
+ ```
493
+
494
+ Other methods (all on `env.functions` / `db.functions`): `list()`, `get(name)`,
495
+ `update(name, patch)`, `remove(name)`, `preview(definition, payload)` (run an unsaved definition;
496
+ `definition` needs a `name` and `source`), `listRuns({ functionName })` and `getRun(runId)`.
497
+ `run(name, payload, { timeoutMs, signal })` resolves to the run record (`status`, `result.value`,
498
+ `logs`, `execution`, …); a failed run rejects with the error, its run record attached as
499
+ `err.details.runRecord`.
500
+
501
+ <!-- continues -->
502
+
503
+ ```js
504
+ const draft = await env.functions.preview(
505
+ { name: 'draft', source: '(ctx) => ({ doubled: ctx.payload.n * 2 })' },
506
+ { n: 21 },
507
+ );
508
+ console.log(draft.result.value); // { doubled: 42 }
509
+
510
+ const runs = await env.functions.listRuns({ functionName: 'countEvents' });
511
+ console.log(runs.length);
465
512
  ```
466
513
 
467
514
  ---
@@ -534,7 +581,11 @@ Common error codes:
534
581
  - `FUNCTION_SCRIPT_INVALID_SHAPE`
535
582
  - `FUNCTION_SCRIPT_FORBIDDEN_SYMBOL`
536
583
  - `FUNCTION_SCRIPT_COMPILE_FAILED`
584
+ - `FUNCTION_SCRIPT_RESTRICTED_CTX_PROP`
585
+ - `FUNCTION_INVALID_TIMEOUT`
537
586
  - `FUNCTION_TIMEOUT`
587
+ - `FUNCTION_OOM`
588
+ - `FUNCTION_CANCELLED`
538
589
 
539
590
  ---
540
591
 
@@ -546,7 +597,7 @@ Current implementation intentionally does **not** yet include:
546
597
  - arbitrary module imports
547
598
  - direct console access
548
599
  - transactional read-your-own-writes overlays inside `txn(...)`
549
- - admin UI for functions
600
+ - Node.js APIs (`Buffer`, `fs`, `process`, ...) — the sandbox is not Node.js
550
601
 
551
602
  ---
552
603
 
@@ -2,15 +2,44 @@
2
2
 
3
3
  ## Installation
4
4
 
5
- OKDB is a private package. Reference it from its local path or your monorepo:
5
+ ```bash
6
+ npm install @kedem/okdb
7
+ ```
8
+
9
+ Requirements: **Node.js 18+ on Linux x64 with glibc 2.28 or newer** (Debian 10+, Ubuntu 18.10+, RHEL 8+, Amazon Linux 2023, ...).
10
+
11
+ okdb 3 is a native core (written in Rust) with a JavaScript API. The compiled core ships **inside** the package
12
+ (`node_modules/@kedem/okdb/native/linux-x64-gnu/`), so there is nothing to compile and no install script. The only JavaScript
13
+ dependencies are `msgpackr` and `sift`.
14
+
15
+ - npm refuses to install the package on other platforms (`EBADPLATFORM`: macOS, Windows, arm64). If it gets installed anyway
16
+ (musl/Alpine, `--force`), `require('@kedem/okdb')` throws an error with `code: 'NATIVE_UNAVAILABLE'` that names the platform;
17
+ `err.cause` holds the loader error when the native file exists but cannot load (for example an older glibc). Stay on okdb 2.x
18
+ on those platforms for now.
19
+ - `OKDB_NATIVE_BINARY=/path/to/okdb-node.linux-x64-gnu.node` loads a specific native file instead of the bundled one (a missing
20
+ file is an error, not a fallback). `OKDB_NATIVE_DEBUG=1` prints which file was loaded.
21
+
22
+ ```js
23
+ const OKDB = require('@kedem/okdb');
24
+
25
+ console.log(OKDB.implementation); // 'native'
26
+ console.log(OKDB.nativeBinaryPath); // the .node file this process loaded
27
+ ```
28
+
29
+ ### The `okdb` command
30
+
31
+ The package also installs the `okdb` CLI: a standalone HTTP server with the admin UI, plus backup / restore / export / import,
32
+ tokens, licenses and health checks. It is a small native launcher that runs the CLI inside the same native file the library uses
33
+ (no Node.js needed to run it):
6
34
 
7
35
  ```bash
8
- npm install /path/to/okdb
9
- # or in package.json:
10
- # "okdb": "file:../okdb"
36
+ npx okdb --path ./mydb --port 8080 # serve ./mydb on :8080 (REST API + admin UI)
37
+ npx okdb --help # every command and option
38
+ npx okdb --okdb-which # where the native launcher lives
11
39
  ```
12
40
 
13
- Dependencies that OKDB needs internally (`lmdb`, `sift`, `hnswlib-node`, etc.) are all declared in its own `package.json` and will install automatically.
41
+ `npx okdb` goes through a tiny Node wrapper. Containers can run the launcher directly:
42
+ `node_modules/@kedem/okdb/native/linux-x64-gnu/okdb`.
14
43
 
15
44
  ---
16
45
 
@@ -19,7 +48,7 @@ Dependencies that OKDB needs internally (`lmdb`, `sift`, `hnswlib-node`, etc.) a
19
48
  ```javascript
20
49
  const OKDB = require('@kedem/okdb');
21
50
 
22
- const okdb = new OKDB('./mydb', options);
51
+ const okdb = new OKDB('./mydb');
23
52
  await okdb.open();
24
53
 
25
54
  // ... use the database ...
@@ -31,6 +60,8 @@ The path is the root directory. OKDB creates subdirectories inside it for each e
31
60
 
32
61
  ### Constructor options
33
62
 
63
+ <!-- not-runnable: an annotated list of options, not a program -->
64
+
34
65
  ```javascript
35
66
  const okdb = new OKDB('./mydb', {
36
67
  // Durability preset: 'strict' | 'balanced' (default) | 'fast'
@@ -62,7 +93,7 @@ const okdb = new OKDB('./mydb', {
62
93
  address: 'http://localhost:8080', // this node's public sync address
63
94
  },
64
95
 
65
- // Role flags (okdb 2.0) — what background work THIS process runs.
96
+ // Role flags — what background work THIS process runs.
66
97
  // All default to true; a plain `new OKDB(path)` is a full do-everything node.
67
98
  // `processors` is the INITIAL participation only — okdb.processors.start()/stop()
68
99
  // flip it at runtime (open with false + start() later = fast startup).
@@ -126,6 +157,8 @@ await okdb.ensureType('users', {
126
157
 
127
158
  ## Writing records
128
159
 
160
+ <!-- continues -->
161
+
129
162
  ```javascript
130
163
  // Upsert — create or overwrite
131
164
  await okdb.put('users', 'alice', { name: 'Alice', role: 'admin', email: 'alice@example.com', createdAt: Date.now() });
@@ -155,6 +188,8 @@ All write methods return a Promise. The record is durable once the promise resol
155
188
 
156
189
  Reads are **synchronous** — no `await` needed.
157
190
 
191
+ <!-- continues -->
192
+
158
193
  ```javascript
159
194
  // Single record (returns value or undefined)
160
195
  const user = okdb.get('users', 'bob');
@@ -185,6 +220,8 @@ const count = okdb.getCount('users');
185
220
 
186
221
  MongoDB-style filters via [sift](https://github.com/crcn/sift.js):
187
222
 
223
+ <!-- continues -->
224
+
188
225
  ```javascript
189
226
  const admins = okdb.query('users', { role: 'admin' });
190
227
  for (const { key, value } of admins) {
@@ -208,12 +245,14 @@ const recent = okdb.query('users', {
208
245
 
209
246
  OKDB includes a built-in HTTP server with a REST API and admin UI:
210
247
 
248
+ <!-- not-runnable: starts a long-running server -->
249
+
211
250
  ```javascript
212
251
  // Start listening
213
252
  okdb.http.listen(8080);
214
253
 
215
- console.log('API: http://localhost:8080/api/type/users');
216
- console.log('Admin: http://localhost:8080/admin/index.html');
254
+ console.log('API: http://localhost:8080/api/');
255
+ console.log('Admin: http://localhost:8080/admin/');
217
256
  ```
218
257
 
219
258
  The admin UI provides a browser-based data explorer, index manager, and real-time monitoring.
@@ -224,6 +263,8 @@ The admin UI provides a browser-based data explorer, index manager, and real-tim
224
263
 
225
264
  Always close cleanly so processors drain and LMDB flushes properly:
226
265
 
266
+ <!-- not-runnable: installs process signal handlers -->
267
+
227
268
  ```javascript
228
269
  process.on('SIGINT', () => okdb.close().then(() => process.exit(0)));
229
270
  process.on('SIGTERM', () => okdb.close().then(() => process.exit(0)));
@@ -231,6 +272,81 @@ process.on('SIGTERM', () => okdb.close().then(() => process.exit(0)));
231
272
 
232
273
  ---
233
274
 
275
+ ## The OKDB object at a glance
276
+
277
+ `require('@kedem/okdb')` exports the `OKDB` class (also as `.OKDB` and `.default`). Error classes are not exported: branch on
278
+ `err.code` (every okdb error is an `OKDBError` with a stable `code`, a message and `details`).
279
+
280
+ **Statics**
281
+
282
+ | Static | What it is |
283
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
284
+ | `OKDB.defaults` | default storage options (`mapSize`, `pageSize`, `compression`, `durability`, …) |
285
+ | `OKDB.KNOWN_OPTIONS` | `Set` of every constructor option name; an unknown key logs one warning per process |
286
+ | `OKDB.implementation` | always `'native'` in okdb 3 |
287
+ | `OKDB.nativeBinaryPath` | the native file this process loaded ([C bridge](./c-bridge.md)) |
288
+ | `OKDB.HIGH_SENTINEL` | open-ended upper bound for index ranges ([Querying](./querying.md)) |
289
+ | `OKDB.clone(src, dst)` / `OKDB.reidentify(path)` | copy a store as a new node ([Migration](./migration.md#cloning-a-store-new-identity)) |
290
+ | `OKDB.registerViewReducer()` / `OKDB.registerBucketProjection()` | process-wide view extensions ([Views](./views.md)) |
291
+
292
+ **Instance**
293
+
294
+ | Member | What it is |
295
+ | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
296
+ | `open()` / `close()` / `state` | lifecycle (`created` → `started` → `stopped`; a failed `open()` leaves it `stopped`) |
297
+ | `env(name)` / `default` / `openEnv(name)` | an open env / the default env / open a registered env on demand |
298
+ | `createEnvironment(name, config)` / `removeEnvironment(name)` | create / delete an env ([Data Model](./data-model.md)) |
299
+ | `put`, `get`, `query`, `registerType`, … on `db` | shortcuts to the `default` env |
300
+ | `queue`, `files`, `views`, `processor` | the default env's queue, files, views and processor |
301
+ | `fts`, `embeddings`, `engines`, `pipelines`, `functions`, `sync`, `auth`, `http`, `mcp`, `licenses`, `migrate`, `plugins` | feature APIs (see their pages) |
302
+ | `processors.start()` / `stop()` / `status()` | processing participation ([Roles & Deployment](./deployment.md)) |
303
+ | `role`, `info`, `id`, `version`, `getResolvedOptions()`, `quarantinedEnvs` | introspection |
304
+ | `pressure()`, `diag()` | load signal and diagnostics ([Diagnostics](./diagnostics.md)) |
305
+ | `locks` | named cross-process mutexes: `await db.locks.tryAcquire(id)` → `{ acquired, handle, current }`, then `handle.release()` |
306
+ | `bus` | the local UDP bus that wakes peer processes on the same store (`state`, `isRunning`), or null |
307
+ | `bootRuntimeDeclarations()` | boot stored engines / pipelines / views now (what `open()` does unless `runtimeDeclarations: false`) |
308
+ | `meta`, `processes` | type/index metadata ([Data Model](./data-model.md)) and the [process registry](./process-registry.md) |
309
+
310
+ ```js
311
+ const OKDB = require('@kedem/okdb');
312
+
313
+ console.log(OKDB.defaults.durability); // 'balanced'
314
+ console.log(OKDB.KNOWN_OPTIONS.has('processors')); // true
315
+
316
+ const db = new OKDB('./mydb');
317
+ await db.open();
318
+ const { acquired, handle } = await db.locks.tryAcquire('nightly-report');
319
+ if (acquired) {
320
+ // ... only one process on this store runs this at a time ...
321
+ await handle.release();
322
+ }
323
+ await db.close();
324
+ ```
325
+
326
+ ### The native loader
327
+
328
+ `@kedem/okdb/native-loader` is the module the package entry uses to find the native file. It is useful for health checks and
329
+ for hosts that need the paths without opening a store:
330
+
331
+ <!-- not-runnable: needs the installed package layout (native/ next to the loader) -->
332
+
333
+ ```js
334
+ const loader = require('@kedem/okdb/native-loader');
335
+
336
+ loader.platformKey(); // 'linux-x64-gnu' on a supported host, null elsewhere
337
+ loader.bundledKeys(); // platforms bundled in this package: ['linux-x64-gnu']
338
+ loader.bundledPath('linux-x64-gnu', 'addon'); // .../native/linux-x64-gnu/okdb-node.linux-x64-gnu.node
339
+ loader.bundledPath('linux-x64-gnu', 'launcher'); // .../native/linux-x64-gnu/okdb
340
+ loader.locate('addon'); // { path, key, source: 'env' | 'bundled', reason? } — never throws
341
+ const p = loader.probe(); // loads the addon once: { ok: true, path, key, bindingVersion } or { ok: false, reason }
342
+ if (!p.ok) console.error('okdb unavailable:', p.reason);
343
+ ```
344
+
345
+ `describeHost()` names the host (`'linux/x64/glibc'`), `isMusl()` detects musl, and `loadedPath()` is the real path of the
346
+ loaded addon (null before `probe()`).
347
+
348
+ ---
349
+
234
350
  ## Full minimal example
235
351
 
236
352
  ```javascript