@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/CHANGELOG.md CHANGED
@@ -4,10 +4,121 @@ All notable changes to `@kedem/okdb` are documented here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/); versions follow [SemVer](https://semver.org/).
5
5
  Dates are release dates.
6
6
 
7
+ ## [3.1.0] - 2026-10-19
8
+
9
+ Planned as 3.1.0. **The on-disk layout changes** (see the upgrade notes below).
10
+
11
+ ### Changed (read before upgrading)
12
+
13
+ - **Blobs are per environment.** File blobs move from the shared `<root>/~blobs/` to `<env-path>/~blobs/`, with their
14
+ reference counts (`~file:blob_status`) in the same env. Reference counting, garbage collection and integrity checks
15
+ look only within the env, and `removeEnvironment()` deletes the env's blobs. Identical bytes are still stored once
16
+ within an env but no longer shared between envs. The `/api/files/blobs/*` routes take `?env=<name>` (default
17
+ `default`), as do the peer-sync pulls and announcements.
18
+ - **An encrypted environment keeps no user data in clear.** Every store of an env uses that env's effective key: its own
19
+ `encryptionKey` (`createEnvironment(name, { encryptionKey })`), else the instance key, else none.
20
+ - The full-text index (`~fts/<env>`), the time-machine history and the env's embeddings sub-envs are LMDB stores
21
+ encrypted with that key.
22
+ - Blobs and vector-search snapshots (now under `<env-path>/~vectors/`) use a chunked AES-256-GCM file format
23
+ (streamed; range downloads still work).
24
+ - An encrypted env's blob files are named by `HMAC-SHA256(file key, content hash)`, so a listing reveals no hashes.
25
+ Records and the API keep the real SHA-256, so file ids and hashes do not change.
26
+ - Without a key, files keep exactly the previous bytes and names.
27
+ - `migrate.exportBlobs()` writes every env's blobs decrypted, named by their hash, so an export imports into any store.
28
+ `importBlobs()` writes each blob into every env whose records reference it (the default env when none does),
29
+ encrypted with that env's key.
30
+
31
+ ### Added
32
+
33
+ - **Two layers of keys.** Every encrypted env (`~system` included) has a random 32-byte data key. All of the env's keys
34
+ (LMDB, files, blob names) are derived from it, and it is stored only wrapped (AES-256-GCM) by your key in
35
+ `<env-path>/keyring`. Your key no longer encrypts data directly. Keyless envs have no keyring.
36
+ - **`db.changeEncryptionKey({ env?, to })`** (CLI: `okdb rekey --key <current> --to <new> [--env <name>]`) changes the key
37
+ without rewriting data. It rewraps the data keys and signals the other processes (no key on the wire). Nothing closes.
38
+ Peers with a function key fetch the new key; peers with a static key log that their next open needs it. The old key
39
+ no longer opens the store.
40
+ - **`db.reencrypt({ env, to? })`** (CLI: `okdb rekey --reencrypt --env <name> [--to <key> | --plain]`) re-encrypts an env
41
+ under a new data key, under a new key, or without encryption (`to: null`). This also adds encryption to a plain env.
42
+ - It is automatic across processes: every process closes the env, and its calls wait and then continue. Once no
43
+ process holds the files, the owner rewrites the env, its FTS, time-machine and blob files, then switches the keyring,
44
+ and every process reopens by itself.
45
+ - It is resumable after a crash: the next process that needs the env finishes the run.
46
+ - Its sub-envs follow it. `~system` cannot be re-encrypted (`REKEY_SYSTEM_UNSUPPORTED`).
47
+ - **Function keys:** `encryptionKey` (instance, and per env in `createEnvironment`) may be a function, sync or async,
48
+ returning the key. It is called at open and again when another process changes the key. A function per-env key is never
49
+ stored: pass it again with the new `encryptionKeys: { [env]: key | fn }` option.
50
+ - New error codes: `ENCRYPTION_KEY_INVALID`, `ENCRYPTION_KEY_REQUIRED`, and the retryable `REKEY_IN_PROGRESS`,
51
+ `REKEY_BUSY` and `REKEY_PEERS_BUSY`. See the new docs page `docs/encryption.md`.
52
+ - A second instance in the same process opened with another (or no) key now fails with `ENCRYPTION_KEY_INVALID` /
53
+ `ENCRYPTION_KEY_REQUIRED` from the keyring (it was `ENV_OPEN_CONFLICT`).
54
+
55
+ ### Upgrading
56
+
57
+ - **Every store moves to the 3.1 layout** with the storage migration `per-env-blobs` (3.1.0) on its first open. Close
58
+ every process on the store first.
59
+ - The migration opens every registered env. If one cannot be opened, the migration fails with
60
+ `MIGRATION_ENV_UNAVAILABLE`, nothing is moved, and the next open retries.
61
+ - Each shared blob goes into every env whose records reference it: hard-linked into a keyless env (copied when the
62
+ link would cross file systems), or copied and encrypted under the env's key and opaque name. Its ref count moves
63
+ with it, then the shared `~blobs/` is deleted. Blobs no record references are dropped. Every step is safe to
64
+ repeat after a crash, and blobs keep their mtimes.
65
+ - Before the envs open, an encrypted env's `~fts` and time-machine files written without the key are re-encrypted in
66
+ place (history is kept). The migration does the same for the embeddings sub-envs of an env that has only its own key.
67
+ - The root `~vectors/` is removed; snapshots rebuild under each env.
68
+ - An env that 3.0 encrypted keeps its key as its data key: the migration writes its keyring and rewrites none of its
69
+ encrypted data (`reencrypt` it afterwards for a random data key).
70
+ - **After the migration, a plain file in an encrypted env is an error:** `ENV_ENCRYPTION_MISMATCH` for an LMDB store,
71
+ `FILE_NOT_ENCRYPTED` for a blob. The migration is the only converter.
72
+ - **Downgrade:** the store's layout version becomes 3.1.0, so 3.0.x refuses to open it (`STORE_VERSION_NEWER`) unless
73
+ `OKDB_ALLOW_NEWER_STORE=1` is set. That forced open is not supported: 3.0.x does not see the per-env blobs.
74
+ - All keys of an env (its LMDB key, its file key and the key of its blob names) come from one derivation
75
+ (`derive_env_keys`), the base for key rotation.
76
+
77
+ ### Fixed
78
+
79
+ - A backup (`migrate.backup`) of an encrypted store with time machine enabled reads the history with the store's key,
80
+ and copies each env's blobs into that env's backup dir. A compacting copy of an encrypted environment falls back to a
81
+ page copy instead of aborting inside LMDB.
82
+
83
+ ## [3.0.1] - 2026-10-18
84
+
85
+ A bug-fix release for 3.0.0. Nothing changes on disk.
86
+
87
+ ### Changed (read before upgrading)
88
+
89
+ - **`runtime.memoryMb` is enforced per function run.** A run that grows its heap past the function's limit (default 32
90
+ MB, or the `functions.memoryMb` constructor option) fails with `FUNCTION_OOM`; the process and other functions are
91
+ unaffected. Earlier versions documented the limit but did not apply it. Raise `runtime.memoryMb` for functions that
92
+ need more.
93
+
94
+ ### Fixed
95
+
96
+ - **`functions.run()` no longer blocks the event loop.** The function runs on the sandbox thread while the loop keeps
97
+ serving; timeouts, cancellation, `OKDB_FN_SANDBOX_CONCURRENCY` and the run ledger behave as before.
98
+ - **Full-text indexes after `removeEnvironment()`.** Recreating an environment with the same name in the same process
99
+ no longer fails `fts.ensure` with `ALREADY_EXISTS` for an index of the removed environment.
100
+ - **`query()` refuses unknown options again** with the same messages as 2.x (3.0.0 silently ignored them, including on
101
+ the full-text and vector paths).
102
+ - **`byIndex` / `getIndex` / `countByIndex` accept a scalar `prefix`** (`{ prefix: 'x' }` = `['x']`, as in 2.x);
103
+ 3.0.0 ignored it and scanned the whole index.
104
+ - **The queue's `cron_next` option is honoured again** (a function `(expr, fromTs) => ms` that replaces the built-in
105
+ cron scheduler); 3.0.0 accepted and ignored it.
106
+ - **Engine drivers registered on the database** (stored in `~system`) get a working `ctx` (`okdb`, `storeEnv`, `emit`,
107
+ `updateStatus`); 3.0.0 threw from `ctx.emit`.
108
+ - **Embeddings:** `listAlgorithms()` describes the algorithms as built into the core, and the `flat` / `hnsw` /
109
+ `usearch` config schemas list every option the core reads (`idleEvictMs`, `snapshotMaxLagMs`, `tmpMaxAgeMs`, …)
110
+ instead of rejecting them.
111
+ - **Error and log messages** no longer describe 2.x internals (error codes are unchanged).
112
+
113
+ ### Documentation
114
+
115
+ - Every page reviewed for 3.0; new [Upgrading to 3.0](docs/upgrade-3.0.md) and [C bridge](docs/c-bridge.md) pages; the
116
+ code examples in the docs are now run as tests.
117
+
7
118
  ## [3.0.0] - 2026-10-18
8
119
 
9
120
  okdb 3 is a Rust core with the same JavaScript API. The storage format is unchanged: a store written by 2.x opens
10
- as-is, with no migration and no index rebuild. Read [UPGRADING-v3](rs/UPGRADING-v3.md) before upgrading: stop
121
+ as-is, with no migration and no index rebuild. Read [Upgrading to 3.0](docs/upgrade-3.0.md) before upgrading: stop
11
122
  every 2.x process before okdb 3 opens a store, and never run 2.x and 3.x writers on one store at the same time.
12
123
 
13
124
  ### Changed (read before upgrading)
@@ -19,11 +130,11 @@ every 2.x process before okdb 3 opens a store, and never run 2.x and 3.x writers
19
130
  platform. `OKDB_NATIVE_BINARY` overrides the bundled addon. Runtime dependencies are only `msgpackr` and `sift`.
20
131
  - **The `okdb` command is native** (a small launcher that runs the CLI inside the addon; no Node needed).
21
132
  - **Coded errors** replace several free-text errors (`INVALID_KEY`, `INVALID_TYPE_NAME`, `INVALID_ARGUMENT`,
22
- `INVALID_OPTIONS`, …): see UPGRADING-v3.
133
+ `INVALID_OPTIONS`, …): see [Upgrading to 3.0](docs/upgrade-3.0.md#errors-invalid-arguments-have-codes).
23
134
  - **Opening retries transient storage errors** for about 2.4 s and never quarantines an environment for them;
24
135
  if one outlasts the retries, `open()` fails (restart the process). Corruption still quarantines the tenant env.
25
136
  - **Plugins:** 2.x JS plugins work through the Node binding; `start()` runs after the whole open, and `okdb.api`
26
- / `okdb.admin` are not available. See [PLUGINS-v3](rs/PLUGINS-v3.md).
137
+ / `okdb.admin` are not available. See [Upgrading to 3.0](docs/upgrade-3.0.md#plugins).
27
138
 
28
139
  ### Added
29
140
 
package/README.md CHANGED
@@ -19,7 +19,10 @@
19
19
 
20
20
  **OKDB** is an embedded, document-centric database for Node.js. No separate server. No network hop. Open a path, write data.
21
21
 
22
- It wraps [LMDB](https://www.symas.com/lmdb) — one of the fastest memory-mapped key-value stores ever built — and layers on top: typed collections, composite secondary indexes, full-text search, vector embeddings, multi-node sync, a durable job queue, file storage, point-in-time time-machine queries, reactive materialized views, and a built-in HTTP API. All in one process. All ACID.
22
+ It is built on [LMDB](https://www.symas.com/lmdb) — one of the fastest memory-mapped key-value stores ever built — and layers on top: typed collections, composite secondary indexes, full-text search, vector embeddings, multi-node sync, a durable job queue, file storage, point-in-time time-machine queries, reactive materialized views, and a built-in HTTP API. All in one process. All ACID.
23
+
24
+ okdb 3 runs a native core (written in Rust) behind the same JavaScript API as okdb 2.x. The core ships inside the npm package, for
25
+ Linux x64 (glibc 2.28 or newer). Upgrading from 2.x? Read [Upgrading to 3.0](docs/upgrade-3.0.md).
23
26
 
24
27
  ```js
25
28
  const OKDB = require('@kedem/okdb');
@@ -34,7 +37,9 @@ await db.ensureType('users', {
34
37
  await db.put('users', 'alice', { name: 'Alice', role: 'admin', email: 'alice@example.com' });
35
38
 
36
39
  const alice = db.get('users', 'alice'); // synchronous — instant
37
- const admins = db.query('users', { role: 'admin' }); // MongoDB-style filter
40
+ const admins = [...db.query('users', { role: 'admin' })]; // MongoDB-style filter
41
+
42
+ await db.close();
38
43
  ```
39
44
 
40
45
  ---
@@ -63,7 +68,7 @@ Most Node.js apps reach for a separate database server — Postgres, MongoDB, Re
63
68
 
64
69
  ### ⚡ Synchronous reads
65
70
 
66
- LMDB maps the database file directly into process memory. Reads are pointer dereferences — no `await`, no round-trip, no copy.
71
+ LMDB maps the database file directly into process memory. Reads run in-process and return immediately — no `await`, no round-trip.
67
72
 
68
73
  ### 🔒 ACID transactions
69
74
 
@@ -93,28 +98,33 @@ for (const { key, value } of db.byIndex('orders', ['customerId', 'createdAt'], {
93
98
 
94
99
  ### 🔍 Full-text search
95
100
 
96
- Built-in inverted-index FTS backed by a dedicated LMDB environment. No Elasticsearch. No external process.
101
+ Built-in inverted-index FTS (BM25 ranking) backed by a dedicated LMDB environment. No Elasticsearch. No external process.
97
102
 
98
103
  ```js
104
+ await db.ensureType('articles');
105
+ await db.put('articles', 'a1', { title: 'Hello', body: 'hello world from okdb' });
106
+
99
107
  await db.fts.register('articles', 'content', { fields: ['title', 'body'] });
100
108
  await db.fts.ready('articles', 'content');
101
109
 
102
- const results = await db.fts.search('articles', 'content', 'hello world');
110
+ const results = db.fts.search('articles', 'content', 'hello world');
103
111
  ```
104
112
 
105
113
  ### 🤖 Vector embeddings + semantic search
106
114
 
107
115
  First-class embedding pipeline. Point it at a type and a field, connect an embedder (Ollama, OpenAI, or custom), and OKDB handles indexing automatically. Nearest-neighbour search uses an in-process HNSW graph.
108
116
 
117
+ <!-- not-runnable: needs a running Ollama server -->
118
+
109
119
  ```js
110
- await db.embeddings.createPipeline('articles', {
120
+ const { api } = await db.embeddings.createPipeline('articles', {
111
121
  source_type: 'articles',
112
122
  field: 'body',
113
123
  dims: 1024,
114
124
  embedder: { type: 'ollama', model: 'mxbai-embed-large', url: 'http://localhost:11434' },
115
125
  });
116
126
 
117
- const similar = await db.embeddings.search('articles', queryVector, { limit: 10 });
127
+ const similar = await api.searchDocs('how do I bake bread?', { limit: 10 }); // best chunk per document
118
128
  ```
119
129
 
120
130
  ### 🌍 Geo queries
@@ -123,7 +133,9 @@ Built-in geospatial index for radius and bounding-box queries. See [docs/indexes
123
133
 
124
134
  ### 🔄 Multi-node sync
125
135
 
126
- Peer-to-peer last-write-wins replication over HTTP. No coordinator. No Raft. Nodes exchange deltas; HLC timestamps resolve conflicts.
136
+ Peer-to-peer last-write-wins replication over HTTP. No coordinator. No Raft. Nodes exchange deltas; HLC timestamps resolve conflicts. Sync needs a license (it is off on the free tier, see [Licensing](docs/licensing.md)).
137
+
138
+ <!-- not-runnable: joins a second node at a LAN address -->
127
139
 
128
140
  ```js
129
141
  const db = new OKDB('./node1', {
@@ -138,7 +150,19 @@ await db.sync.join('http://192.168.1.11:8080', { token: 'cluster-bearer-token' }
138
150
 
139
151
  ### 📬 Durable job queue
140
152
 
141
- Crash-safe job queue stored in LMDB. Workers pull jobs, process them, and acknowledge — all without Redis.
153
+ Crash-safe job queue stored in LMDB. Consumers claim jobs, process them, and acknowledge — all without Redis. See [docs/queue.md](docs/queue.md).
154
+
155
+ ```js
156
+ await db.queue.enqueue('email', { to: 'alice@example.com' });
157
+
158
+ // a consumer in this process; run more processes to scale out (each job is claimed exactly once)
159
+ await new Promise((resolve) => {
160
+ db.queue.process('email', async (payload, ctx) => {
161
+ console.log('sending to', payload.to, 'job', ctx.jobId);
162
+ resolve();
163
+ });
164
+ });
165
+ ```
142
166
 
143
167
  ### 📁 File / blob storage
144
168
 
@@ -146,7 +170,7 @@ SHA-256 content-addressable binary blob storage, integrated with the sync system
146
170
 
147
171
  ### 🧩 Sandboxed custom functions
148
172
 
149
- Store JavaScript functions in the database, validate them, and execute them in pooled sandbox runners.
173
+ Store JavaScript functions in the database, validate them, and execute them in a sandbox.
150
174
 
151
175
  - all functions execute with env-local facades: `ctx.env`, `ctx.env.queue`, `ctx.env.files`
152
176
  - mark a function `unsafe: true` to additionally receive `ctx.okdb` for cross-env access
@@ -155,6 +179,8 @@ Store JavaScript functions in the database, validate them, and execute them in p
155
179
  - logging flows through `ctx.log(...)`
156
180
 
157
181
  ```js
182
+ await db.createEnvironment('analytics');
183
+ await db.env('analytics').registerType('events');
158
184
  await db.env('analytics').functions.create({
159
185
  name: 'countEvents',
160
186
  source: '(ctx) => ({ count: ctx.env.getCount("events") })',
@@ -170,10 +196,12 @@ Zero-config REST API and a browser-based admin UI for data exploration, index ma
170
196
 
171
197
  ```js
172
198
  db.http.listen(8080);
173
- // REST API: http://localhost:8080/api/type/users
199
+ // REST API: http://localhost:8080/api/...
174
200
  // Admin UI: http://localhost:8080/admin/
175
201
  ```
176
202
 
203
+ Or without writing code: `npx okdb --path ./mydb --port 8080` (the `okdb` CLI, see [HTTP API](docs/http-api.md)).
204
+
177
205
  ### 🧠 MCP endpoint (Inspector-ready example)
178
206
 
179
207
  OKDB also exposes an MCP server over SSE + POST:
@@ -181,13 +209,7 @@ OKDB also exposes an MCP server over SSE + POST:
181
209
  - `GET /mcp/sse`
182
210
  - `POST /mcp/messages`
183
211
 
184
- For a local working example, run:
185
-
186
- ```bash
187
- node examples/mcp-inspector.js
188
- ```
189
-
190
- Then in MCP Inspector choose the SSE transport and connect to:
212
+ For a local working example, run `examples/mcp-inspector.js` from the okdb repository, then in MCP Inspector choose the SSE transport and connect to:
191
213
 
192
214
  - `http://localhost:8787/mcp/sse`
193
215
 
@@ -200,9 +222,7 @@ The server responds with browser CORS headers for common Inspector origins, acce
200
222
  - `queue_list_jobs`
201
223
  - `processor_list`
202
224
 
203
- OKDB now derives MCP tools primarily from route operation metadata instead of keeping a separate hand-maintained MCP tool list. Routes marked with canonical metadata and `mcp.include !== false` can participate in MCP generation, while streaming/SSE/raw transport routes stay excluded by default.
204
-
205
- If you run Inspector from a different origin, allow that origin in `src/features/mcp/okdb-mcp.js`.
225
+ MCP tools are derived from the HTTP API's route metadata; streaming / SSE routes are not exposed as tools.
206
226
 
207
227
  ### ⚙️ Reactive processors
208
228
 
@@ -210,22 +230,29 @@ Composable change handlers — like database triggers, written in JavaScript. Re
210
230
 
211
231
  ### ⏱️ Time-machine
212
232
 
213
- Full edit history for every record. Ask what any document looked like at any point in the past — OKDB stores diffs automatically and reconstructs the state on demand.
233
+ Full edit history for every record. Ask what any document looked like at any point in the past — OKDB stores diffs automatically and reconstructs the state on demand. Time machine needs a license (it is off on the free tier).
234
+
235
+ <!-- licensed: timeMachine -->
214
236
 
215
237
  ```js
216
- // Enable once; tracking starts from current clock
217
- await db.timeMachine.enable();
238
+ const db = new OKDB('./mydb', { timeMachine: true });
239
+ await db.open();
240
+ const tm = db.env('default').timeMachine;
241
+ await db.registerType('orders');
242
+
243
+ // Enable per type; tracking starts from the current clock
244
+ await tm.enable('orders');
245
+ await db.put('orders', 'ord-42', { status: 'new' });
246
+ await tm.flush('orders'); // tracking is asynchronous; flush() drains it now
247
+ const historicClock = db.env('default').getClock();
248
+ await db.put('orders', 'ord-42', { status: 'shipped' });
249
+ await tm.flush('orders');
218
250
 
219
251
  // Point-in-time read — synchronous, no await
220
- const snapshot = db.timeMachine.getStateAt('orders', 'ord-42', historicClock);
252
+ const snapshot = tm.getStateAt('orders', 'ord-42', historicClock); // → { status: 'new' }
221
253
 
222
254
  // Full history for a single record
223
- const { diffs, head } = db.timeMachine.getHistory('orders', 'ord-42');
224
-
225
- // All changes to a type within a clock range — useful for auditing
226
- for (const change of db.timeMachine.getChanges('orders', fromClock, toClock)) {
227
- console.log(change.key, change.diff);
228
- }
255
+ const history = tm.getHistory('orders', 'ord-42');
229
256
  ```
230
257
 
231
258
  ### 📊 Materialized views
@@ -234,6 +261,8 @@ Reactive aggregations that update automatically on every write. Declare a view w
234
261
 
235
262
  ```js
236
263
  const env = db.env('default');
264
+ await env.ensureType('orders');
265
+ await env.put('orders', 'o1', { status: 'completed', amount: 120, region: 'EU' });
237
266
 
238
267
  await env.views.create('orderStats', {
239
268
  type: 'orders',
@@ -271,10 +300,15 @@ Multi-mode security layer built into the HTTP API. No separate auth service need
271
300
  ## Installation
272
301
 
273
302
  ```bash
274
- npm install okdb
303
+ npm install @kedem/okdb
275
304
  ```
276
305
 
277
- > **Runtime:** Node.js only. Requires a native LMDB build (handled automatically by the `lmdb` package via node-gyp).
306
+ > **Runtime:** Node.js 18 or newer on **Linux x64 with glibc 2.28+**. The native core ships inside the package (no compiler,
307
+ > no install scripts, no separate platform package). npm refuses to install it on other platforms; on a host it slips through
308
+ > (musl/Alpine, a forced install) `require('@kedem/okdb')` throws `NATIVE_UNAVAILABLE`. Those platforms can stay on okdb 2.x.
309
+ >
310
+ > The same native file also serves programs written in other languages through a stable C interface: see
311
+ > [C bridge](docs/c-bridge.md).
278
312
 
279
313
  ---
280
314
 
@@ -325,15 +359,17 @@ main().catch(console.error);
325
359
  | [Full-Text Search](docs/fts.md) | Registering FTS indexes, tokenizer config, search |
326
360
  | [Embeddings](docs/embeddings.md) | Vector pipeline, embedders, HNSW search |
327
361
  | [Sync](docs/sync.md) | Cluster setup, joining peers, conflict resolution |
328
- | [Queue](docs/queue.md) | Durable job queue, workers, retry |
362
+ | [Queue](docs/queue.md) | Durable job queue, consumers, retry |
329
363
  | [Files](docs/files.md) | Blob storage, upload, download, sync |
330
364
  | [Custom Functions](docs/functions.md) | Stored sandboxed JS functions, env/global execution, HTTP routes |
331
365
  | [Pipelines](docs/pipelines.md) | Composable data-flow orchestration with queue and processor drivers |
332
366
  | [HTTP API](docs/http-api.md) | REST endpoints, auth, admin UI |
333
367
  | [Auth](docs/auth-permissions.md) | Token, OIDC, IP allowlist authentication |
334
368
  | [Plugins](docs/plugins.md) | Extending OKDB with custom features |
335
- | [Migration](docs/migration.md) | Schema evolution, data migration |
336
- | [Architecture](OKDB-ARCHITECTURE.md) | Deep-dive technical reference |
369
+ | [Migration](docs/migration.md) | Export, import, backup, restore |
370
+ | [Licensing](docs/licensing.md) | Free tier, license files, limits |
371
+ | [Upgrading to 3.0](docs/upgrade-3.0.md) | What changes when you move from okdb 2.x |
372
+ | [C bridge](docs/c-bridge.md) | Using the native core from C, Rust, Go, ... without Node |
337
373
 
338
374
  ---
339
375
 
package/bin/okdb CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';const _0x43ed0a=_0x534d;(function(_0x386ae9,_0x58d115){const _0x100047=_0x534d,_0x55f4b7=_0x386ae9();while(!![]){try{const _0x35076d=-parseInt(_0x100047(0x9d))/0x1*(parseInt(_0x100047(0xc1))/0x2)+-parseInt(_0x100047(0xb7))/0x3+-parseInt(_0x100047(0xcb))/0x4*(-parseInt(_0x100047(0xa9))/0x5)+parseInt(_0x100047(0xc6))/0x6*(parseInt(_0x100047(0xae))/0x7)+parseInt(_0x100047(0x9f))/0x8+parseInt(_0x100047(0xc8))/0x9*(-parseInt(_0x100047(0xbe))/0xa)+parseInt(_0x100047(0xb1))/0xb;if(_0x35076d===_0x58d115)break;else _0x55f4b7['push'](_0x55f4b7['shift']());}catch(_0x1fc31b){_0x55f4b7['push'](_0x55f4b7['shift']());}}}(_0xb8f6,0xa45ed));const path=require('node:path'),fs=require(_0x43ed0a(0xbc)),root=path[_0x43ed0a(0xa6)](__dirname,'..'),which=process[_0x43ed0a(0xb5)][0x2]==='--okdb-which';function die(_0x1f4b66){const _0x35c563=_0x43ed0a;console[_0x35c563(0xc4)](_0x35c563(0xc3)+_0x1f4b66+_0x35c563(0xaf)+_0x35c563(0xbf)),process['exit'](0x1);}function _0x534d(_0x488a1a,_0x251dbc){_0x488a1a=_0x488a1a-0x99;const _0xb8f67a=_0xb8f6();let _0x534de9=_0xb8f67a[_0x488a1a];return _0x534de9;}function resolveLauncher(){const _0xe050ed=_0x43ed0a;if(process.env.OKDB_SHIM_ACTIVE==='1')return{'reason':_0xe050ed(0xac)};let _0x5d3e53;try{_0x5d3e53=require(path[_0xe050ed(0xbd)](root,_0xe050ed(0xbb)));}catch(_0x419089){return{'reason':_0x419089[_0xe050ed(0x9c)]};}const _0x592b05=_0x5d3e53[_0xe050ed(0xa5)](_0xe050ed(0xa1));if(!_0x592b05['path'])return{'reason':_0x592b05[_0xe050ed(0xaa)]};try{if(fs[_0xe050ed(0xc5)](_0x592b05[_0xe050ed(0xa2)])===fs['realpathSync'](__filename))return{'reason':_0x592b05[_0xe050ed(0xa2)]+_0xe050ed(0xb6)};if(fs[_0xe050ed(0xba)](_0x592b05[_0xe050ed(0xa2)])['subarray'](0x0,0x2)[_0xe050ed(0x9b)]()==='#!')return{'reason':_0x592b05[_0xe050ed(0xa2)]+_0xe050ed(0xb3)};}catch(_0x3c513c){return{'reason':_0x3c513c[_0xe050ed(0x9c)]};}const _0x42b638=_0x5d3e53[_0xe050ed(0xa5)](_0xe050ed(0xca));return{'loc':_0x592b05,'addon':_0x42b638[_0xe050ed(0xa2)]};}const {loc,addon,reason}=resolveLauncher();if(!loc)die(reason);which&&(console[_0x43ed0a(0xc2)]('native\x20'+loc[_0x43ed0a(0xa2)]+'\x20('+loc[_0x43ed0a(0xa4)]+',\x20'+loc[_0x43ed0a(0x99)]+')'+(addon?_0x43ed0a(0xab)+addon:'')),process[_0x43ed0a(0x9e)](0x0));function _0xb8f6(){const _0x2d751b=['reason','\x20addon\x20','nested\x20shim\x20(OKDB_SHIM_ACTIVE)','spawn','238rlvsdM','.\x20okdb\x203.x\x20bundles\x20the\x20CLI\x20under\x20native/<platform>/okdb\x20(3.0:\x20Linux\x20x64\x20glibc\x20','OKDB_BRIDGE_LIB','12936946sTZMAu','public','\x20is\x20a\x20script,\x20not\x20a\x20native\x20binary','kill','argv','\x20resolves\x20to\x20the\x20shim\x20itself','3911496LrzBxX','OKDB_ADMIN_PUBLIC_DIR','SIGHUP','readFileSync','native-loader.js','node:fs','join','10KrKtMf','only);\x20reinstall\x20@kedem/okdb,\x20or\x20set\x20OKDB_NATIVE_CLI\x20to\x20the\x20launcher\x20binary.','slice','8yPHkuN','log','okdb:\x20no\x20native\x20CLI\x20launcher:\x20','error','realpathSync','215802ihsUim','SIGQUIT','3117951viJaya','SIGTERM','addon','62324uZTUTY','source','inherit','toString','message','304457uWQtyO','exit','7768040CQiZIP','pid','launcher','path','SIGINT','key','locate','resolve','cannot\x20run\x20','node:child_process','55MedrJv'];_0xb8f6=function(){return _0x2d751b;};return _0xb8f6();}const env={...process.env,'OKDB_SHIM_ACTIVE':'1'};if(addon&&!env['OKDB_BRIDGE_LIB'])env[_0x43ed0a(0xb0)]=addon;for(const [k,rel]of[[_0x43ed0a(0xb8),_0x43ed0a(0xb2)],['OKDB_DOCS_DIR','docs']]){const p=path['join'](root,rel);if(!env[k]&&fs['existsSync'](p))env[k]=p;}const SIGS=[_0x43ed0a(0xa3),_0x43ed0a(0xc9),_0x43ed0a(0xb9),_0x43ed0a(0xc7)],child=require(_0x43ed0a(0xa8))[_0x43ed0a(0xad)](loc[_0x43ed0a(0xa2)],process['argv'][_0x43ed0a(0xc0)](0x2),{'stdio':_0x43ed0a(0x9a),'env':env}),relay=_0x593b5e=>()=>{try{child['kill'](_0x593b5e);}catch{}};for(const sig of SIGS)process['on'](sig,relay(sig));child['on'](_0x43ed0a(0xc4),_0x3ac40d=>die(_0x43ed0a(0xa7)+loc[_0x43ed0a(0xa2)]+':\x20'+_0x3ac40d['message'])),child['on'](_0x43ed0a(0x9e),(_0x17eb18,_0x20e873)=>{const _0x48d588=_0x43ed0a;if(_0x20e873){for(const _0x363ca2 of SIGS)process['removeAllListeners'](_0x363ca2);process[_0x48d588(0xb4)](process[_0x48d588(0xa0)],_0x20e873),setTimeout(()=>process[_0x48d588(0x9e)](0x80),0x64);}else process[_0x48d588(0x9e)](_0x17eb18??0x0);});
2
+ 'use strict';const _0x2bac0e=_0x5c94;(function(_0x3b39f8,_0x1427b2){const _0x409fa8=_0x5c94,_0x3faa15=_0x3b39f8();while(!![]){try{const _0x55ea75=parseInt(_0x409fa8(0xe1))/0x1*(-parseInt(_0x409fa8(0xfb))/0x2)+parseInt(_0x409fa8(0xf9))/0x3*(-parseInt(_0x409fa8(0xe5))/0x4)+parseInt(_0x409fa8(0xcc))/0x5*(parseInt(_0x409fa8(0xde))/0x6)+parseInt(_0x409fa8(0xf3))/0x7+parseInt(_0x409fa8(0xd3))/0x8*(parseInt(_0x409fa8(0xda))/0x9)+parseInt(_0x409fa8(0xf1))/0xa*(parseInt(_0x409fa8(0xeb))/0xb)+parseInt(_0x409fa8(0xd2))/0xc;if(_0x55ea75===_0x1427b2)break;else _0x3faa15['push'](_0x3faa15['shift']());}catch(_0x4809bb){_0x3faa15['push'](_0x3faa15['shift']());}}}(_0x3ab7,0xbcdd2));function _0x3ab7(){const _0x47d658=['5985960bPYrkT','136smrPic','reason','native-loader.js','realpathSync','exit','toString','slice','387045vsFYgO','node:path','log','okdb:\x20no\x20native\x20CLI\x20launcher:\x20','174zCnfaP','message','node:fs','219WNrFvC','path','docs','SIGTERM','2075224vUOTgx','nested\x20shim\x20(OKDB_SHIM_ACTIVE)','source','only);\x20reinstall\x20@kedem/okdb,\x20or\x20set\x20OKDB_NATIVE_CLI\x20to\x20the\x20launcher\x20binary.','removeAllListeners','inherit','1166561sxrKti','addon','key','OKDB_BRIDGE_LIB','pid','kill','50fJsnZD','error','172039dBKKce','\x20resolves\x20to\x20the\x20shim\x20itself','readFileSync','\x20addon\x20','SIGINT','join','6VIGeGc','.\x20okdb\x203.x\x20bundles\x20the\x20CLI\x20under\x20native/<platform>/okdb\x20(3.0:\x20Linux\x20x64\x20glibc\x20','866icWhsf','20910XQhdvR','native\x20','--okdb-which','resolve','node:child_process','argv'];_0x3ab7=function(){return _0x47d658;};return _0x3ab7();}function _0x5c94(_0x10a57b,_0x4fe5bc){_0x10a57b=_0x10a57b-0xcc;const _0x3ab739=_0x3ab7();let _0x5c94c5=_0x3ab739[_0x10a57b];return _0x5c94c5;}const path=require(_0x2bac0e(0xdb)),fs=require(_0x2bac0e(0xe0)),root=path[_0x2bac0e(0xcf)](__dirname,'..'),which=process[_0x2bac0e(0xd1)][0x2]===_0x2bac0e(0xce);function die(_0x3ff310){const _0x1810ab=_0x2bac0e;console[_0x1810ab(0xf2)](_0x1810ab(0xdd)+_0x3ff310+_0x1810ab(0xfa)+_0x1810ab(0xe8)),process['exit'](0x1);}function resolveLauncher(){const _0x4ee90e=_0x2bac0e;if(process.env.OKDB_SHIM_ACTIVE==='1')return{'reason':_0x4ee90e(0xe6)};let _0x1ab100;try{_0x1ab100=require(path[_0x4ee90e(0xf8)](root,_0x4ee90e(0xd5)));}catch(_0x346e9a){return{'reason':_0x346e9a[_0x4ee90e(0xdf)]};}const _0x3b0c06=_0x1ab100['locate']('launcher');if(!_0x3b0c06[_0x4ee90e(0xe2)])return{'reason':_0x3b0c06[_0x4ee90e(0xd4)]};try{if(fs[_0x4ee90e(0xd6)](_0x3b0c06[_0x4ee90e(0xe2)])===fs['realpathSync'](__filename))return{'reason':_0x3b0c06[_0x4ee90e(0xe2)]+_0x4ee90e(0xf4)};if(fs[_0x4ee90e(0xf5)](_0x3b0c06[_0x4ee90e(0xe2)])['subarray'](0x0,0x2)[_0x4ee90e(0xd8)]()==='#!')return{'reason':_0x3b0c06[_0x4ee90e(0xe2)]+'\x20is\x20a\x20script,\x20not\x20a\x20native\x20binary'};}catch(_0x3b3ffb){return{'reason':_0x3b3ffb[_0x4ee90e(0xdf)]};}const _0x3c214a=_0x1ab100['locate'](_0x4ee90e(0xec));return{'loc':_0x3b0c06,'addon':_0x3c214a[_0x4ee90e(0xe2)]};}const {loc,addon,reason}=resolveLauncher();if(!loc)die(reason);which&&(console[_0x2bac0e(0xdc)](_0x2bac0e(0xcd)+loc[_0x2bac0e(0xe2)]+'\x20('+loc[_0x2bac0e(0xed)]+',\x20'+loc[_0x2bac0e(0xe7)]+')'+(addon?_0x2bac0e(0xf6)+addon:'')),process[_0x2bac0e(0xd7)](0x0));const env={...process.env,'OKDB_SHIM_ACTIVE':'1'};if(addon&&!env['OKDB_BRIDGE_LIB'])env[_0x2bac0e(0xee)]=addon;for(const [k,rel]of[['OKDB_ADMIN_PUBLIC_DIR','public'],['OKDB_DOCS_DIR',_0x2bac0e(0xe3)]]){const p=path[_0x2bac0e(0xf8)](root,rel);if(!env[k]&&fs['existsSync'](p))env[k]=p;}const SIGS=[_0x2bac0e(0xf7),_0x2bac0e(0xe4),'SIGHUP','SIGQUIT'],child=require(_0x2bac0e(0xd0))['spawn'](loc['path'],process[_0x2bac0e(0xd1)][_0x2bac0e(0xd9)](0x2),{'stdio':_0x2bac0e(0xea),'env':env}),relay=_0x1d0e03=>()=>{try{child['kill'](_0x1d0e03);}catch{}};for(const sig of SIGS)process['on'](sig,relay(sig));child['on'](_0x2bac0e(0xf2),_0x34ba37=>die('cannot\x20run\x20'+loc[_0x2bac0e(0xe2)]+':\x20'+_0x34ba37[_0x2bac0e(0xdf)])),child['on'](_0x2bac0e(0xd7),(_0x128e73,_0x4227d9)=>{const _0x2959e7=_0x2bac0e;if(_0x4227d9){for(const _0x51b432 of SIGS)process[_0x2959e7(0xe9)](_0x51b432);process[_0x2959e7(0xf0)](process[_0x2959e7(0xef)],_0x4227d9),setTimeout(()=>process[_0x2959e7(0xd7)](0x80),0x64);}else process[_0x2959e7(0xd7)](_0x128e73??0x0);});
@@ -20,7 +20,7 @@ an optional `name` + `password` (for login), a raw bearer value, `permissions` a
20
20
 
21
21
  Every request goes through `db.auth.authenticateRequest(req)`:
22
22
 
23
- ```
23
+ ```text
24
24
  1. Bootstrap window ~tokens empty and not open mode → localhost gets full access, others refused
25
25
  2. Open mode client IP matches auth.open → full access, no credentials
26
26
  3. Bearer token Authorization: Bearer <token> → see "Bearer verification" below
@@ -43,7 +43,7 @@ const okdb = new OKDB('./data', {
43
43
  });
44
44
  ```
45
45
 
46
- `bin/okdb` passes the `auth` block of `.kdbconfig` through unchanged; `--open` overrides
46
+ The `okdb` CLI passes the `auth` block of `.kdbconfig` through unchanged; `--open` overrides
47
47
  `auth.open`. `auth.token.secret` is only used the first time: the secret is persisted in the store
48
48
  as `__tokenSecret` (local, never replicated) and reused from then on, generated if unset.
49
49
 
@@ -63,7 +63,7 @@ Anything else is rejected; an invalid bearer never falls back to the cookie.
63
63
 
64
64
  ### Login
65
65
 
66
- ```
66
+ ```http
67
67
  POST /auth/login
68
68
  { "username": "admin", "password": "s3cret" }
69
69
  ```
@@ -86,28 +86,32 @@ OAuth only obtains a session: it creates no users and stores nothing. Configure
86
86
  under `auth.providers` (only the first entry is used):
87
87
 
88
88
  ```js
89
- auth: {
90
- providers: {
91
- google: {
92
- issuer: 'https://accounts.google.com', // enables OIDC bearer validation
93
- clientId: 'YOUR_CLIENT_ID',
94
- redirectUri: 'http://localhost:8484/admin/auth/callback',
95
- scopes: ['openid', 'email', 'profile'],
96
-
97
- allowedDomains: ['mycompany.com'], // required: allowedDomains and/or allowedEmails
98
- allowedEmails: ['contractor@gmail.com'],
99
- defaultRoles: ['admin'], // default ['admin']
100
-
101
- getAuthorizationUrl: ({ state, codeChallenge, redirectUri, scopes }) => '...',
102
- exchangeCode: async ({ code, state, redirectUri }) => {
103
- // return { subject, email, claims }
89
+ const okdb = new OKDB('./data', {
90
+ auth: {
91
+ providers: {
92
+ google: {
93
+ issuer: 'https://accounts.google.com', // enables OIDC bearer validation
94
+ clientId: 'YOUR_CLIENT_ID',
95
+ redirectUri: 'http://localhost:8484/admin/auth/callback',
96
+ scopes: ['openid', 'email', 'profile'],
97
+
98
+ allowedDomains: ['mycompany.com'], // required: allowedDomains and/or allowedEmails
99
+ allowedEmails: ['contractor@gmail.com'],
100
+ defaultRoles: ['admin'], // default ['admin']
101
+
102
+ getAuthorizationUrl: ({ state, codeChallenge, redirectUri, scopes }) =>
103
+ `https://accounts.google.com/o/oauth2/v2/auth?state=${state}&code_challenge=${codeChallenge}`,
104
+ exchangeCode: async ({ code, state, redirectUri }) => {
105
+ // call the provider's token endpoint, then:
106
+ return { subject: 'user-1', email: 'me@mycompany.com', claims: {} };
107
+ },
104
108
  },
105
109
  },
106
110
  },
107
- }
111
+ });
108
112
  ```
109
113
 
110
- ```
114
+ ```text
111
115
  GET /admin/auth/start?redirect=/admin/index.html → redirect to the provider (PKCE)
112
116
  GET /admin/auth/callback?code=...&state=... → exchangeCode → email allowlist check
113
117
  allowed → HMAC session token in okdb_session, redirect
@@ -138,7 +142,7 @@ GET /admin/auth/callback?code=...&state=... → exchangeCode → email al
138
142
 
139
143
  Pull-based, last-write-wins replication over HTTP; no coordinator, no consensus.
140
144
 
141
- ```
145
+ ```text
142
146
  1. A write advances the env's HLC clock and logs a change entry
143
147
  2. Peers are poked; each pulls a delta (POST /api/sync/delta) from the changed node
144
148
  3. Changes are compared by HLC — the higher wins; ties broken by origin node id
@@ -192,6 +196,8 @@ okdb join http://node-a:8484 --token <raw-token> --address http://node-b:8484
192
196
 
193
197
  In code:
194
198
 
199
+ <!-- not-runnable: joins a peer node at a remote address -->
200
+
195
201
  ```js
196
202
  const okdb = new OKDB('./node-b', { sync: { address: 'http://node-b:8484' } });
197
203
  await okdb.open();
@@ -202,7 +208,7 @@ await okdb.sync.join('http://node-a:8484', { token: process.env.OKDB_JOIN_TOKEN
202
208
  Over HTTP (the admin UI's **System → Sync → Connect** does this), on node B with a credential
203
209
  for B that has `sync:peer`:
204
210
 
205
- ```
211
+ ```http
206
212
  POST /api/sync/connect
207
213
  { "address": "http://node-a:8484", "token": "<raw-token-on-A>" }
208
214
  ```
@@ -212,8 +218,8 @@ link. If B has no `sync.address`, it is taken from `my_address` in the body or t
212
218
  `Host` header.
213
219
 
214
220
  `join()` fetches `/api/sync/info` from A, stores A in `~sync_nodes`, creates a data link, POSTs to
215
- A's `/api/sync/join` (where A enforces its `sync` license and peer limit — the joiner needs no
216
- license of its own), and pulls an initial delta.
221
+ A's `/api/sync/join`, and pulls an initial delta. Sync is a licensed feature (off on the free
222
+ tier) — see [Licensing](./licensing.md).
217
223
 
218
224
  ### Sync options
219
225
 
@@ -177,8 +177,9 @@ is only applied on routes that resolve their env from the path (see the note abo
177
177
 
178
178
  `join()` first reads `GET /api/sync/info` (`sync:read`); `sync:peer` alone does not imply it.
179
179
 
180
- ## Adding a new permission
180
+ ## Permissions on your own routes
181
181
 
182
- 1. Add the namespace/operation to `src/features/auth/okdb-auth-namespaces.js` in `NAMESPACES`.
183
- 2. Add `permission: 'ns:op'` to the route's `access` object.
184
- 3. The catalog endpoint at `GET /admin/api/auth/permissions` picks it up automatically — no UI changes needed.
182
+ The permission catalog is fixed (it is what `GET /admin/api/auth/permissions` returns, and what
183
+ the admin token editor offers). A route you add with `okdb.http.add()` declares one of these
184
+ permissions in its metadata — `access: { permission: 'data:read' }` — and the auth guard enforces
185
+ it like on a built-in route. There is no API to add a namespace.
@@ -0,0 +1,94 @@
1
+ # C bridge
2
+
3
+ The native file in `@kedem/okdb` (`native/linux-x64-gnu/okdb-node.linux-x64-gnu.node`) is one binary with two front doors:
4
+
5
+ - **Node.js** loads it as an addon (Node-API) — that is what `require('@kedem/okdb')` does;
6
+ - **any other program** (C, C++, Rust, Go, Zig, ...) can `dlopen()` it and talk to okdb through a stable C ABI, without compiling
7
+ okdb in and without Node. An editor or agent process such as okcode uses okdb this way.
8
+
9
+ The contract is the header `okdb_bridge.h`, attached to each okdb release on GitHub next to the native file. This page is an
10
+ overview; the header is the reference.
11
+
12
+ ## Loading
13
+
14
+ ```c
15
+ #include <dlfcn.h>
16
+ #include "okdb_bridge.h"
17
+
18
+ void *so = dlopen("/path/to/okdb-node.linux-x64-gnu.node", RTLD_NOW | RTLD_LOCAL);
19
+ okdb_bridge_fn get = (okdb_bridge_fn)dlsym(so, "okdb_bridge");
20
+ const OkdbBridgeV1 *ok = get ? get(OKDB_BRIDGE_ABI_MAJOR) : NULL; /* NULL: this file does not speak ABI 1 */
21
+ ```
22
+
23
+ The file has no undefined Node-API symbols, so it loads into a plain process. `okdb_bridge(1)` returns the function table
24
+ `OkdbBridgeV1`: `version`, `open`, `attach`, `close`, `dispatch`, `dispatch_batch`, `submit`, `free`, `set_host`, `pump`,
25
+ `cli_main`, and, in later minors, `submit_batch` (1.1) and `read` (1.2).
26
+
27
+ ## Requests
28
+
29
+ Every call carries MessagePack. A request is `[scope, env | nil, method, args]` — the same scopes and methods the JavaScript
30
+ binding uses (`["env", "default", "put", ["docs", "k1", {"body": "hi"}]]`, `["env", "default", "get", ["docs", "k1"]]`). A reply
31
+ is `{"ok": value}` or `{"err": {"code", "message", "details"?}}`, with the same error codes the JavaScript API throws; the return
32
+ status (`OKDB_OK`, `OKDB_ERR`, `OKDB_INVALID`, `OKDB_WRONG_THREAD`, `OKDB_CLOSED`, `OKDB_PANIC`, `OKDB_UNSUPPORTED`) is the coarse
33
+ class. Every buffer okdb returns is released with `free(ptr, len)`. `dispatch_batch` runs an array of requests as one write group.
34
+
35
+ ## Open or attach
36
+
37
+ - **`open(path, opts, flags, &h, ...)`** opens a standalone instance (options as in `new OKDB(path, opts)`). Without flags the
38
+ calling thread is the owner and must call **`pump(h, budget_ms, &next_ms)`** from its loop: it runs processor drains, timers,
39
+ lease heartbeats and queued submits, and says when to call again. `OKDB_OPEN_OWNER_THREAD` makes okdb run its own owner thread
40
+ (no pump needed; `dispatch` from other threads is forwarded). `OKDB_OPEN_DEFER` constructs without opening, so callbacks can be
41
+ registered first; then send `["bridge", nil, "open", []]`.
42
+ - **`attach(native_handle, &h, ...)`** joins an instance a Node.js host in the same process already opened, instead of opening the
43
+ store a second time. Call it on that instance's JavaScript thread; `close()` only detaches. From Node, the host finds the same
44
+ image with `require('@kedem/okdb').nativeBinaryPath` (dlopen it with `RTLD_NOLOAD`), and the handle with
45
+ `db._native.bridgeHandle()` (`db._native.bridgeTable()` is the table's address, `db._native.bridgeLibPath()` the image path).
46
+
47
+ ```js
48
+ // in the Node host, before handing the instance to native code in the same process
49
+ const OKDB = require('@kedem/okdb');
50
+ const db = new OKDB('./mydb');
51
+ await db.open();
52
+
53
+ const image = OKDB.nativeBinaryPath; // dlopen(image, RTLD_NOW | RTLD_NOLOAD)
54
+ const handle = db._native.bridgeHandle(); // pass to table->attach() on this thread
55
+ console.log(image, handle);
56
+ await db.close();
57
+ ```
58
+
59
+ ## Threads
60
+
61
+ An okdb instance is single-threaded: everything runs on its owner thread. `dispatch` / `dispatch_batch` from another thread
62
+ fail with `OKDB_WRONG_THREAD` (except on owner-thread handles, which forward and block). Two calls work from **any** thread:
63
+
64
+ - **`submit` / `submit_batch`** queue a request; its `done(ctx, status, reply, len)` callback runs later on the owner thread.
65
+ - **`read`** (ABI 1.2) runs a read-only request on the **calling** thread, with no hop to the owner and no pump: the env read
66
+ methods (`get`, `getEntry`, `has`, `count`, `getMany`, `getRange`, `getKeys`, `getValues`, `getCount`, `getByPrefix`,
67
+ `getIndex`, `byIndex`, `countByIndex`) against committed data. Anything else answers `READ_METHOD_NOT_ALLOWED`. This is how a
68
+ worker thread reads without blocking the owner.
69
+
70
+ ## Host callbacks
71
+
72
+ Features that call user code — chunk strategies, embedder factories and embedders, queue and processor handlers, event
73
+ subscriptions — take functions in JavaScript. Over the bridge a function is the marker `{"$fn": <id>}` with an id the host picks;
74
+ `set_host(h, &host)` installs the host's `OkdbBridgeHostV1` vtable (`call`, `release`, `free_reply`, `drop`), and okdb calls
75
+ `host.call(ctx, op, args)` on the owner thread when it needs the function.
76
+
77
+ ## The CLI
78
+
79
+ `cli_main(argc, argv)` (also exported as `okdb_cli_main`) runs the `okdb` command line inside the calling process. The `okdb`
80
+ launcher shipped in the package is a small program that does exactly that.
81
+
82
+ ## ABI versions
83
+
84
+ The ABI is **major 1, minor 2**. Within a major, the function table, the host vtable and the message shapes only grow: fields are
85
+ appended, never removed or reordered. Before using a field added in a later minor, check the table's `struct_size`:
86
+
87
+ ```c
88
+ #include <stddef.h>
89
+ int has_read = ok->struct_size >= offsetof(OkdbBridgeV1, read) + sizeof ok->read; /* ABI 1.2 */
90
+ ```
91
+
92
+ okdb reads `host->struct_size` the same way. A breaking change would be a new major (`OkdbBridgeV2`), and `okdb_bridge(1)` keeps
93
+ answering as long as major 1 is supported. `version()` returns the okdb package version, for features newer than the ABI minor
94
+ (new methods).