@kedem/okdb 3.0.0 → 3.1.0

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 (64) hide show
  1. package/CHANGELOG.md +114 -3
  2. package/README.md +72 -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 +79 -36
  8. package/docs/data-model.md +35 -9
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/encryption.md +132 -0
  13. package/docs/files.md +64 -27
  14. package/docs/fts.md +48 -23
  15. package/docs/functions.md +109 -56
  16. package/docs/getting-started.md +121 -9
  17. package/docs/http-api.md +66 -11
  18. package/docs/http-cluster.md +80 -88
  19. package/docs/index.md +33 -15
  20. package/docs/indexes.md +53 -17
  21. package/docs/licensing.md +19 -5
  22. package/docs/logging.md +11 -22
  23. package/docs/manifest.json +6 -3
  24. package/docs/migration.md +41 -16
  25. package/docs/pipelines.md +111 -46
  26. package/docs/plugins.md +47 -15
  27. package/docs/process-registry.md +23 -24
  28. package/docs/processors.md +26 -23
  29. package/docs/querying.md +102 -29
  30. package/docs/queue.md +165 -51
  31. package/docs/resolved-fields.md +24 -1
  32. package/docs/subscriptions.md +4 -4
  33. package/docs/sync.md +9 -6
  34. package/docs/time-machine.md +52 -14
  35. package/docs/transactions.md +63 -15
  36. package/docs/ttl.md +34 -13
  37. package/docs/upgrade-2.0.md +32 -15
  38. package/docs/upgrade-2.1.md +10 -12
  39. package/docs/upgrade-3.0.md +144 -0
  40. package/docs/views.md +165 -61
  41. package/index.js +1 -1
  42. package/native/linux-x64-gnu/okdb +0 -0
  43. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  44. package/native-loader.js +1 -1
  45. package/okdb-native.js +1 -1
  46. package/package.json +1 -1
  47. package/public/features/files/parts/files-blob-status.ok.js +1 -1
  48. package/types/environment.d.ts +32 -11
  49. package/types/errors.d.ts +20 -0
  50. package/types/features/admin.d.ts +3 -5
  51. package/types/features/api.d.ts +5 -7
  52. package/types/features/embeddings.d.ts +8 -7
  53. package/types/features/engines.d.ts +9 -1
  54. package/types/features/files.d.ts +2 -1
  55. package/types/features/fts.d.ts +3 -3
  56. package/types/features/functions.d.ts +14 -8
  57. package/types/features/pipelines.d.ts +10 -10
  58. package/types/features/queue.d.ts +15 -10
  59. package/types/features/sync.d.ts +7 -0
  60. package/types/features/time-machine.d.ts +3 -0
  61. package/types/index.d.ts +3 -0
  62. package/types/okdb.d.ts +70 -7
  63. package/types/options.d.ts +12 -8
  64. 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,57 @@ 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. It is an ordinary rejection of that run, not a
145
+ kill: the sandbox thread keeps serving other runs. Writes the function already made with `ctx.env`
146
+ (`put`, `create`, `patch`, …) were committed as they happened and stay; a `ctx.env.txn(...)` batch
147
+ that had not finished when the limit hit is not applied. Use `txn` when a function's writes must be
148
+ all-or-nothing. Each sandbox thread's heap is also capped by
149
+ the `functions.memoryMb` constructor option (default 256 MB, minimum 32). Scripts are validated
150
+ and compile-checked before storage, and every run is written to the run ledger (`listRuns` /
151
+ `getRun`).
138
152
 
139
153
  ### Timeouts
140
154
 
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
155
+ - **Run deadline** — `runtime.timeoutMs` on the stored function (default 5 000 ms) aborts
156
+ `ctx.signal`; a run still going after a further grace period (`OKDB_FN_SANDBOX_GRACE_MS`,
157
+ default 1 500 ms) is interrupted and fails with `FUNCTION_TIMEOUT`. A single call can override it with
143
158
  `functions.run(name, payload, { timeoutMs })`; the value must be a positive finite number
144
159
  (`FUNCTION_INVALID_TIMEOUT` otherwise) and is capped at `OKDB_FN_MAX_TIMEOUT_MS` (default
145
160
  600 000 ms), since a running call holds a sandbox slot for its whole deadline.
@@ -148,6 +163,9 @@ functions suitable for operational entry points without paying spawn cost on eve
148
163
  1 000 ms). A valid source is a bare arrow expression and evaluates in well under a millisecond;
149
164
  the bound only stops a source that smuggles top-level work.
150
165
 
166
+ The `functions` constructor option sets the defaults for new functions and the sandbox:
167
+ `new OKDB(path, { functions: { timeoutMs, memoryMb, allowFetch, maxCodeSizeBytes } })`.
168
+
151
169
  ### Network access (`fetch`)
152
170
 
153
171
  `fetch` inside a function is off unless the stored function's `runtime.allowedFetchDomains` permits the
@@ -162,6 +180,8 @@ altogether). Every hop is checked — the first URL **and each redirect**:
162
180
  vouching for it. `OKDB_FN_FETCH_ALLOW_PRIVATE=1` turns the block off for the whole process.
163
181
 
164
182
  Authorization, cookie and proxy-authorization headers are dropped when a redirect leaves the origin.
183
+ At most `OKDB_FN_FETCH_MAX_INFLIGHT` (default 32) sandbox fetches run at once per process, and a
184
+ response body is capped at `OKDB_FN_FETCH_MAX_BYTES` (default 32 MiB).
165
185
 
166
186
  ```js
167
187
  await env.functions.create({
@@ -175,10 +195,10 @@ await env.functions.create({
175
195
  > function anywhere, and `'*'` reached localhost and the LAN. A function that called a local service
176
196
  > through `'*'` must now list that host.
177
197
 
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.
198
+ > **Changed in 3.0:** functions run in the native core's embedded engine instead of a Node.js
199
+ > `worker_thread`. The script contract, `ctx` API, globals, fetch rules and error codes are the
200
+ > same. The 2.x durable `~fn:requests` / `~fn:responses` dispatch is gone; use a queue job for
201
+ > run-eventually work.
182
202
 
183
203
  ---
184
204
 
@@ -267,7 +287,7 @@ The function must **not** write directly via `ctx.env`.
267
287
 
268
288
  The returned ops array shape:
269
289
 
270
- ```js
290
+ ```text
271
291
  [
272
292
  { action: 'put', key: 'some-key', value: { ... } },
273
293
  { action: 'remove', key: 'other-key' },
@@ -318,7 +338,7 @@ Change record notes:
318
338
  - `transaction(options)` — low-level transaction object
319
339
  - `txn(workOrOps, options?)` — convenience write-focused transaction helper
320
340
  - `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.
341
+ - `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
342
 
323
343
  Example:
324
344
 
@@ -336,22 +356,26 @@ async (ctx) => {
336
356
 
337
357
  `txn(...)` is a **write-batch helper**, not a full read-your-own-writes transaction view.
338
358
 
339
- Preferred callback form:
359
+ Preferred callback form (inside a function body):
340
360
 
341
361
  ```js
342
- await ctx.env.txn((txn) => {
343
- txn.create('events', 'e1', { kind: 'view' });
344
- txn.create('events', 'e2', { kind: 'click' });
345
- });
362
+ async (ctx) => {
363
+ await ctx.env.txn((txn) => {
364
+ txn.create('events', 'e1', { kind: 'view' });
365
+ txn.create('events', 'e2', { kind: 'click' });
366
+ });
367
+ };
346
368
  ```
347
369
 
348
370
  Also supported: ops arrays
349
371
 
350
372
  ```js
351
- await ctx.env.txn([
352
- { action: 'create', type: 'events', key: 'e1', value: { kind: 'view' } },
353
- ['create', 'events', 'e2', { kind: 'click' }],
354
- ]);
373
+ async (ctx) => {
374
+ await ctx.env.txn([
375
+ { action: 'create', type: 'events', key: 'e1', value: { kind: 'view' } },
376
+ ['create', 'events', 'e2', { kind: 'click' }],
377
+ ]);
378
+ };
355
379
  ```
356
380
 
357
381
  The `txn` object intentionally exposes **write methods only**:
@@ -378,6 +402,8 @@ an in-memory overlay or transactional read-your-own-writes view.
378
402
  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
403
 
380
404
  ```js
405
+ await okdb.createEnvironment('analytics');
406
+
381
407
  await okdb.env('default').functions.create({
382
408
  name: 'copySummary',
383
409
  unsafe: true,
@@ -416,20 +442,20 @@ Use `ctx.log(...)` for structured function logs. All log levels are available:
416
442
  ctx.log('starting run', { function: ctx.info.functionName });
417
443
  ctx.log.info('doing work');
418
444
  ctx.log.warn('slow path');
419
- ctx.log.error('something broke', { err: err.message });
445
+ ctx.log.error('something broke', { code: 'E42' });
420
446
  return { ok: true };
421
447
  };
422
448
  ```
423
449
 
424
450
  Every entry emitted from a function is automatically stamped with run identity in the `meta` field:
425
451
 
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) |
452
+ | `meta` field | Value |
453
+ | --------------- | --------------------------------------------------------------------- |
454
+ | `meta.feature` | `'functions'` |
455
+ | `meta.env` | The environment name |
456
+ | `meta.fn` | The function name |
457
+ | `meta.runId` | Unique ID for this invocation |
458
+ | `meta.runnerId` | Executor id (e.g. `'sandbox-12345'` — the pid of the running process) |
433
459
 
434
460
  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
461
 
@@ -440,7 +466,8 @@ Function logs are suppressed from the console (they are stored in the run record
440
466
  ## JavaScript API
441
467
 
442
468
  ```js
443
- const env = okdb.env('analytics');
469
+ const env = await okdb.createEnvironment('analytics');
470
+ await env.registerType('events');
444
471
 
445
472
  await env.functions.create({
446
473
  name: 'countEvents',
@@ -453,6 +480,8 @@ console.log(run.status, run.result.value);
453
480
 
454
481
  For unsafe cross-env functions:
455
482
 
483
+ <!-- continues -->
484
+
456
485
  ```js
457
486
  await okdb.env('default').functions.create({
458
487
  name: 'crossEnvCount',
@@ -460,8 +489,28 @@ await okdb.env('default').functions.create({
460
489
  source: '(ctx) => ({ analytics: ctx.okdb.env("analytics").getCount("events") })',
461
490
  });
462
491
 
463
- const run = await okdb.env('default').functions.run('crossEnvCount');
464
- console.log(run.result.value);
492
+ const run2 = await okdb.env('default').functions.run('crossEnvCount');
493
+ console.log(run2.result.value);
494
+ ```
495
+
496
+ Other methods (all on `env.functions` / `db.functions`): `list()`, `get(name)`,
497
+ `update(name, patch)`, `remove(name)`, `preview(definition, payload)` (run an unsaved definition;
498
+ `definition` needs a `name` and `source`), `listRuns({ functionName })` and `getRun(runId)`.
499
+ `run(name, payload, { timeoutMs, signal })` resolves to the run record (`status`, `result.value`,
500
+ `logs`, `execution`, …); a failed run rejects with the error, its run record attached as
501
+ `err.details.runRecord`.
502
+
503
+ <!-- continues -->
504
+
505
+ ```js
506
+ const draft = await env.functions.preview(
507
+ { name: 'draft', source: '(ctx) => ({ doubled: ctx.payload.n * 2 })' },
508
+ { n: 21 },
509
+ );
510
+ console.log(draft.result.value); // { doubled: 42 }
511
+
512
+ const runs = await env.functions.listRuns({ functionName: 'countEvents' });
513
+ console.log(runs.length);
465
514
  ```
466
515
 
467
516
  ---
@@ -534,7 +583,11 @@ Common error codes:
534
583
  - `FUNCTION_SCRIPT_INVALID_SHAPE`
535
584
  - `FUNCTION_SCRIPT_FORBIDDEN_SYMBOL`
536
585
  - `FUNCTION_SCRIPT_COMPILE_FAILED`
586
+ - `FUNCTION_SCRIPT_RESTRICTED_CTX_PROP`
587
+ - `FUNCTION_INVALID_TIMEOUT`
537
588
  - `FUNCTION_TIMEOUT`
589
+ - `FUNCTION_OOM`
590
+ - `FUNCTION_CANCELLED`
538
591
 
539
592
  ---
540
593
 
@@ -546,7 +599,7 @@ Current implementation intentionally does **not** yet include:
546
599
  - arbitrary module imports
547
600
  - direct console access
548
601
  - transactional read-your-own-writes overlays inside `txn(...)`
549
- - admin UI for functions
602
+ - Node.js APIs (`Buffer`, `fs`, `process`, ...) — the sandbox is not Node.js
550
603
 
551
604
  ---
552
605
 
@@ -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) {
@@ -212,8 +249,8 @@ OKDB includes a built-in HTTP server with a REST API and admin UI:
212
249
  // Start listening
213
250
  okdb.http.listen(8080);
214
251
 
215
- console.log('API: http://localhost:8080/api/type/users');
216
- console.log('Admin: http://localhost:8080/admin/index.html');
252
+ console.log('API: http://localhost:8080/api/');
253
+ console.log('Admin: http://localhost:8080/admin/');
217
254
  ```
218
255
 
219
256
  The admin UI provides a browser-based data explorer, index manager, and real-time monitoring.
@@ -231,6 +268,81 @@ process.on('SIGTERM', () => okdb.close().then(() => process.exit(0)));
231
268
 
232
269
  ---
233
270
 
271
+ ## The OKDB object at a glance
272
+
273
+ `require('@kedem/okdb')` exports the `OKDB` class (also as `.OKDB` and `.default`). Error classes are not exported: branch on
274
+ `err.code` (every okdb error is an `OKDBError` with a stable `code`, a message and `details`).
275
+
276
+ **Statics**
277
+
278
+ | Static | What it is |
279
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------- |
280
+ | `OKDB.defaults` | default storage options (`mapSize`, `pageSize`, `compression`, `durability`, …) |
281
+ | `OKDB.KNOWN_OPTIONS` | `Set` of every constructor option name; an unknown key logs one warning per process |
282
+ | `OKDB.implementation` | always `'native'` in okdb 3 |
283
+ | `OKDB.nativeBinaryPath` | the native file this process loaded ([C bridge](./c-bridge.md)) |
284
+ | `OKDB.HIGH_SENTINEL` | open-ended upper bound for index ranges ([Querying](./querying.md)) |
285
+ | `OKDB.clone(src, dst)` / `OKDB.reidentify(path)` | copy a store as a new node ([Migration](./migration.md#cloning-a-store-new-identity)) |
286
+ | `OKDB.registerViewReducer()` / `OKDB.registerBucketProjection()` | process-wide view extensions ([Views](./views.md)) |
287
+
288
+ **Instance**
289
+
290
+ | Member | What it is |
291
+ | ------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
292
+ | `open()` / `close()` / `state` | lifecycle (`created` → `started` → `stopped`; a failed `open()` leaves it `stopped`) |
293
+ | `env(name)` / `default` / `openEnv(name)` | an open env / the default env / open a registered env on demand |
294
+ | `createEnvironment(name, config)` / `removeEnvironment(name)` | create / delete an env ([Data Model](./data-model.md)) |
295
+ | `put`, `get`, `query`, `registerType`, … on `db` | shortcuts to the `default` env |
296
+ | `queue`, `files`, `views`, `processor` | the default env's queue, files, views and processor |
297
+ | `fts`, `embeddings`, `engines`, `pipelines`, `functions`, `sync`, `auth`, `http`, `mcp`, `licenses`, `migrate`, `plugins` | feature APIs (see their pages) |
298
+ | `processors.start()` / `stop()` / `status()` | processing participation ([Roles & Deployment](./deployment.md)) |
299
+ | `role`, `info`, `id`, `version`, `getResolvedOptions()`, `quarantinedEnvs` | introspection |
300
+ | `pressure()`, `diag()` | load signal and diagnostics ([Diagnostics](./diagnostics.md)) |
301
+ | `locks` | named cross-process mutexes: `await db.locks.tryAcquire(id)` → `{ acquired, handle, current }`, then `handle.release()` |
302
+ | `bus` | the local UDP bus that wakes peer processes on the same store (`state`, `isRunning`), or null |
303
+ | `bootRuntimeDeclarations()` | boot stored engines / pipelines / views now (what `open()` does unless `runtimeDeclarations: false`) |
304
+ | `meta`, `processes` | type/index metadata ([Data Model](./data-model.md)) and the [process registry](./process-registry.md) |
305
+
306
+ ```js
307
+ const OKDB = require('@kedem/okdb');
308
+
309
+ console.log(OKDB.defaults.durability); // 'balanced'
310
+ console.log(OKDB.KNOWN_OPTIONS.has('processors')); // true
311
+
312
+ const db = new OKDB('./mydb');
313
+ await db.open();
314
+ const { acquired, handle } = await db.locks.tryAcquire('nightly-report');
315
+ if (acquired) {
316
+ // ... only one process on this store runs this at a time ...
317
+ await handle.release();
318
+ }
319
+ await db.close();
320
+ ```
321
+
322
+ ### The native loader
323
+
324
+ `@kedem/okdb/native-loader` is the module the package entry uses to find the native file. It is useful for health checks and
325
+ for hosts that need the paths without opening a store:
326
+
327
+ <!-- not-runnable: needs the installed package layout (native/ next to the loader) -->
328
+
329
+ ```js
330
+ const loader = require('@kedem/okdb/native-loader');
331
+
332
+ loader.platformKey(); // 'linux-x64-gnu' on a supported host, null elsewhere
333
+ loader.bundledKeys(); // platforms bundled in this package: ['linux-x64-gnu']
334
+ loader.bundledPath('linux-x64-gnu', 'addon'); // .../native/linux-x64-gnu/okdb-node.linux-x64-gnu.node
335
+ loader.bundledPath('linux-x64-gnu', 'launcher'); // .../native/linux-x64-gnu/okdb
336
+ loader.locate('addon'); // { path, key, source: 'env' | 'bundled', reason? } — never throws
337
+ const p = loader.probe(); // loads the addon once: { ok: true, path, key, bindingVersion } or { ok: false, reason }
338
+ if (!p.ok) console.error('okdb unavailable:', p.reason);
339
+ ```
340
+
341
+ `describeHost()` names the host (`'linux/x64/glibc'`), `isMusl()` detects musl, and `loadedPath()` is the real path of the
342
+ loaded addon (null before `probe()`).
343
+
344
+ ---
345
+
234
346
  ## Full minimal example
235
347
 
236
348
  ```javascript
package/docs/http-api.md CHANGED
@@ -51,16 +51,27 @@ In practice that means:
51
51
  ## Starting the server
52
52
 
53
53
  ```javascript
54
- okdb.http.listen(8080); // all interfaces (Node's default)
54
+ const port = 0; // e.g. 8080; 0 picks a free port
55
+
56
+ okdb.http.listen(port); // all interfaces
57
+ await okdb.http.close();
58
+
55
59
  // bind one address only:
56
- okdb.http.listen(8080, { host: '127.0.0.1' }); // a string 2nd argument is shorthand for { host }
60
+ okdb.http.listen(port, { host: '127.0.0.1' }); // a string 2nd argument is shorthand for { host }
61
+ await okdb.http.close();
62
+
57
63
  // bind several — one server per address, all sharing one request handler:
58
- okdb.http.listen(8080, { host: ['127.0.0.1', '10.0.0.5'] });
64
+ const server = okdb.http.listen(port, { host: ['127.0.0.1', '127.0.0.2'] });
65
+ server.on('listening', () => console.log(server.address()));
66
+ await okdb.http.close();
59
67
  ```
60
68
 
61
- `listen()` returns the Node `http.Server`. With an array it returns the server bound to the
62
- **first** address; every server is on `okdb.http.servers`, an `'error'` from any of them is
63
- re-emitted on the returned one, and `okdb.http.close()` closes them all. The process registry's
69
+ `listen()` returns an `http.Server`-compatible handle (`address()`, `close()`, `'listening'`);
70
+ the server itself runs inside okdb's native core, so it is not a Node socket server you can attach
71
+ your own request handlers to — add routes with `okdb.http.add()` instead. With an array it returns
72
+ the server bound to the **first** address; every server is on `okdb.http.servers`, and
73
+ `okdb.http.close()` closes them all. One instance runs one server (a second `listen()` before
74
+ `close()` throws). The process registry's
64
75
  `listenAddr` shows the bound address(es) (`:8080` for all interfaces, else `127.0.0.1:8080, …`).
65
76
  The CLI takes the same value from its config file: `{ "http": { "host": "127.0.0.1" } }` (string
66
77
  or array; single-process and every cluster worker). There is no `--host` flag.
@@ -118,8 +129,8 @@ Representative fields include:
118
129
  ### Example
119
130
 
120
131
  ```javascript
121
- http.add('GET', '/api/info', () => ({ result: okdb.info }), {
122
- id: 'system_info',
132
+ okdb.http.add('GET', '/api/my-info', () => ({ result: okdb.info }), {
133
+ id: 'my_info',
123
134
  summary: 'Database info',
124
135
  tags: ['system'],
125
136
  inputSchema: {
@@ -148,7 +159,7 @@ http.add('GET', '/api/info', () => ({ result: okdb.info }), {
148
159
  },
149
160
  mcp: {
150
161
  include: true,
151
- tool: 'system_info',
162
+ tool: 'my_info',
152
163
  readOnlyHint: true,
153
164
  },
154
165
  });
@@ -211,6 +222,8 @@ OKDB's MCP surface now derives tools primarily from route operation metadata.
211
222
 
212
223
  Routes may opt into MCP with metadata like:
213
224
 
225
+ <!-- not-runnable: a fragment of route metadata -->
226
+
214
227
  ```javascript
215
228
  mcp: {
216
229
  capability: 'queue',
@@ -319,7 +332,7 @@ MCP exposes these routes through `okdb_engine`, so clients can discover engine t
319
332
 
320
333
  ## Contributor guidance for new routes
321
334
 
322
- When adding a new route in any `*-http.js` file:
335
+ When adding a route with `okdb.http.add()`:
323
336
 
324
337
  1. provide a stable `id`
325
338
  2. add `summary`, `description`, and `tags`
@@ -622,10 +635,16 @@ Add your own middleware before route handlers:
622
635
  ```javascript
623
636
  okdb.http.use(async (req, res, next) => {
624
637
  console.log(`${req.method} ${req.url}`);
638
+ if (req.url.startsWith('/api/blocked')) return res.status(403).send({ error: 'blocked' });
625
639
  await next();
626
640
  });
627
641
  ```
628
642
 
643
+ A middleware runs before the route. Call `next()` to let the request through; otherwise answer it
644
+ with `res.status(code)`, `res.setHeader(name, value)` and `res.send(body)`. `next()` does not wait
645
+ for the route — code after it runs before the handler, so a middleware cannot post-process the
646
+ response.
647
+
629
648
  Register custom routes:
630
649
 
631
650
  ```javascript
@@ -634,6 +653,38 @@ okdb.http.add('GET', '/api/custom/health', () => ({
634
653
  }));
635
654
  ```
636
655
 
656
+ The rest of the route surface:
657
+
658
+ - `okdb.http.guard(matchFn, handlerFn)` — runs before access checks and the route for every request
659
+ where `matchFn(req)` is true; `handlerFn(req, res)` returning `false` ends the request (answer it
660
+ with `res.status()` / `res.send()`).
661
+ - `okdb.http.addSSE(path, setupFn, meta?)` — a Server-Sent Events route: `setupFn({ send, close,
662
+ params, query, headers, context, setHeader })` runs per connection and may return a cleanup
663
+ function; `send(event, data)` pushes a frame.
664
+ - `okdb.http.addRaw(method, path, handler, meta?)` — like `add()`, but the request body is not
665
+ parsed; the handler streams it itself (the file-upload routes use this).
666
+ - `okdb.http.listRoutes()` (or `okdb.http.routes`) — the registered route rows
667
+ (`{ method, path, operation, ... }`); `okdb.http.maxBodyBytes` — the JSON body limit (default 5 MB).
668
+
669
+ ```javascript
670
+ okdb.http.guard(
671
+ (req) => req.url.startsWith('/api/custom/'),
672
+ (req, res) => {
673
+ if (req.headers['x-api-key'] !== 'let-me-in') {
674
+ res.status(401).send({ error: 'missing key' });
675
+ return false;
676
+ }
677
+ },
678
+ );
679
+
680
+ okdb.http.addSSE('/api/custom/ticks', ({ send }) => {
681
+ const t = setInterval(() => send('tick', { at: Date.now() }), 1000);
682
+ return () => clearInterval(t); // runs when the client disconnects
683
+ });
684
+
685
+ console.log(okdb.http.listRoutes().length, okdb.http.maxBodyBytes);
686
+ ```
687
+
637
688
  ---
638
689
 
639
690
  ## Integrating with an existing framework
@@ -644,6 +695,8 @@ OKDB's HTTP layer is **framework-agnostic**. `okdb.http.listen()` is entirely op
644
695
 
645
696
  ### Express
646
697
 
698
+ <!-- not-runnable: needs express (not an okdb dependency) and runs a long-lived server -->
699
+
647
700
  ```javascript
648
701
  const express = require('express');
649
702
  const OKDB = require('@kedem/okdb');
@@ -687,6 +740,8 @@ app.listen(3000);
687
740
 
688
741
  ### Fastify
689
742
 
743
+ <!-- not-runnable: needs fastify (not an okdb dependency) and runs a long-lived server -->
744
+
690
745
  ```javascript
691
746
  const fastify = require('fastify')({ logger: false });
692
747
  const OKDB = require('@kedem/okdb');
@@ -813,7 +868,7 @@ When you bring your own server, don't call `okdb.http.listen()`. OKDB's routes a
813
868
  The admin UI is served at (`/` and `/admin` redirect there; pass `admin: false` to the
814
869
  constructor to disable it):
815
870
 
816
- ```
871
+ ```text
817
872
  http://localhost:8080/admin/index.html
818
873
  ```
819
874