@kedem/okdb 2.7.1 → 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 (69) hide show
  1. package/CHANGELOG.md +111 -33
  2. package/README.md +68 -36
  3. package/bin/okdb +2 -0
  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 -0
  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.d.ts +20 -0
  44. package/native-loader.js +1 -0
  45. package/okdb-native.js +1 -0
  46. package/package.json +27 -14
  47. package/types/environment.d.ts +32 -11
  48. package/types/errors.d.ts +20 -0
  49. package/types/features/admin.d.ts +3 -5
  50. package/types/features/api.d.ts +5 -7
  51. package/types/features/embeddings.d.ts +8 -7
  52. package/types/features/engines.d.ts +9 -1
  53. package/types/features/files.d.ts +2 -1
  54. package/types/features/fts.d.ts +3 -3
  55. package/types/features/functions.d.ts +14 -8
  56. package/types/features/pipelines.d.ts +10 -10
  57. package/types/features/queue.d.ts +15 -10
  58. package/types/features/sync.d.ts +7 -0
  59. package/types/features/time-machine.d.ts +3 -0
  60. package/types/index.d.ts +3 -0
  61. package/types/okdb.d.ts +70 -7
  62. package/types/options.d.ts +12 -8
  63. package/algorithm-worker-thread.js +0 -1
  64. package/bin/okdb.js +0 -2
  65. package/docs/OKDB-ARCHITECTURE.md +0 -1061
  66. package/okdb-functions-sandbox-worker.js +0 -1
  67. package/okdb-http-worker-child.js +0 -1
  68. package/okdb-views-bootstrap-worker.js +0 -1
  69. package/okdb.js +0 -1
package/CHANGELOG.md CHANGED
@@ -4,47 +4,99 @@ 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
- ## [2.7.1] - 2026-10-18
7
+ ## [3.0.1] - 2026-10-18
8
8
 
9
- 2.7.0 was published from a build made before its last three fixes; 2.7.1 is the intended 2.7 release. Upgrade from
10
- 2.7.0 to 2.7.1. The storage format is unchanged. This is the last Node.js release: okdb 3 is a Rust core that forks
11
- from it. Upgrade to okdb 3 by stopping every 2.x process, then opening the store with okdb 3; do not run 2.x and
12
- 3.x writers on one store at the same time (see Known issue below).
9
+ A bug-fix release for 3.0.0. Nothing changes on disk.
13
10
 
14
- ### Known issue
15
-
16
- - **Opening a store can drop one concurrent write from another process.** The LMDB binding 2.x uses
17
- (lmdb-js) resets a shared transaction counter whenever a process opens an environment. If another process
18
- commits at that moment, that commit can be silently lost, even though it was acknowledged. The window is
19
- narrow (we could not reproduce it in 140 loaded test runs, but it was observed once), and it applies to
20
- stores shared by several 2.x processes, and to stores shared by 2.x and okdb 3 processes. 2.7.0 does not
21
- change this. **To avoid it:** open every process's environments before write traffic starts, and upgrade
22
- to okdb 3, whose storage layer does not have this bug. When upgrading, stop every 2.x process before an
23
- okdb 3 process opens the store, and never run 2.x and 3.x writers on one store at the same time.
11
+ ### Changed (read before upgrading)
24
12
 
25
- - **An environment can fail with `EINVAL` (Invalid argument) on every write after a peer closes it.** When a
26
- process closes an environment while another process is opening it, lmdb-js can destroy the shared locks
27
- the opener then uses; every write transaction in that process fails until all processes close the
28
- environment. Restarting the affected processes recovers. Rare (it needs an open and a close to overlap).
29
- Fixed in okdb 3.0, whose storage layer keeps those locks intact.
30
- - **`queue.samplePayloads(type)` always returns `[]`.** Fixed in okdb 3.0.
31
- - **A view whose `$ref` section crashed mid-scan stays `partially-ready`.** Restarting a halted view after a
32
- reopen can also count an update to an existing key as a new key and miss grouped and `$ref` rows. Rebuild
33
- the view (`views.rebuild(name)`) to recover. Fixed in okdb 3.0, which rebuilds such views on open.
13
+ - **`runtime.memoryMb` is enforced per function run.** A run that grows its heap past the function's limit (default 32
14
+ MB, or the `functions.memoryMb` constructor option) fails with `FUNCTION_OOM`; the process and other functions are
15
+ unaffected. Earlier versions documented the limit but did not apply it. Raise `runtime.memoryMb` for functions that
16
+ need more.
34
17
 
35
18
  ### Fixed
36
19
 
37
- - **Sync:** a poke that arrives while a pull from that peer is already running now triggers one more pull
38
- instead of being dropped, so the last write of a burst no longer waits for the next unrelated event. Closing
39
- an instance while a sync pull was running could crash the process; `close()` now waits for the pull (up to a
40
- few seconds) before closing the environments.
41
- - **The queue worker could crash** when a peer's compaction closed its env while it was waiting for work.
20
+ - **`functions.run()` no longer blocks the event loop.** The function runs on the sandbox thread while the loop keeps
21
+ serving; timeouts, cancellation, `OKDB_FN_SANDBOX_CONCURRENCY` and the run ledger behave as before.
22
+ - **Full-text indexes after `removeEnvironment()`.** Recreating an environment with the same name in the same process
23
+ no longer fails `fts.ensure` with `ALREADY_EXISTS` for an index of the removed environment.
24
+ - **`query()` refuses unknown options again** with the same messages as 2.x (3.0.0 silently ignored them, including on
25
+ the full-text and vector paths).
26
+ - **`byIndex` / `getIndex` / `countByIndex` accept a scalar `prefix`** (`{ prefix: 'x' }` = `['x']`, as in 2.x);
27
+ 3.0.0 ignored it and scanned the whole index.
28
+ - **The queue's `cron_next` option is honoured again** (a function `(expr, fromTs) => ms` that replaces the built-in
29
+ cron scheduler); 3.0.0 accepted and ignored it.
30
+ - **Engine drivers registered on the database** (stored in `~system`) get a working `ctx` (`okdb`, `storeEnv`, `emit`,
31
+ `updateStatus`); 3.0.0 threw from `ctx.emit`.
32
+ - **Embeddings:** `listAlgorithms()` describes the algorithms as built into the core, and the `flat` / `hnsw` /
33
+ `usearch` config schemas list every option the core reads (`idleEvictMs`, `snapshotMaxLagMs`, `tmpMaxAgeMs`, …)
34
+ instead of rejecting them.
35
+ - **Error and log messages** no longer describe 2.x internals (error codes are unchanged).
36
+
37
+ ### Documentation
38
+
39
+ - 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
40
+ code examples in the docs are now run as tests.
41
+
42
+ ## [3.0.0] - 2026-10-18
43
+
44
+ okdb 3 is a Rust core with the same JavaScript API. The storage format is unchanged: a store written by 2.x opens
45
+ as-is, with no migration and no index rebuild. Read [Upgrading to 3.0](docs/upgrade-3.0.md) before upgrading: stop
46
+ 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.
47
+
48
+ ### Changed (read before upgrading)
49
+
50
+ - **Native only, bundled, Linux x64 glibc only.** `@kedem/okdb` ships the Rust core inside the package
51
+ (`native/linux-x64-gnu/okdb-node.linux-x64-gnu.node`, no separate platform package); the 2.x JavaScript implementation
52
+ is no longer included and there is no JS fallback. npm refuses other platforms (`"os": ["linux"], "cpu": ["x64"]`,
53
+ `EBADPLATFORM`); on any other host, or when the addon fails to load, `require` throws `NATIVE_UNAVAILABLE` naming the
54
+ platform. `OKDB_NATIVE_BINARY` overrides the bundled addon. Runtime dependencies are only `msgpackr` and `sift`.
55
+ - **The `okdb` command is native** (a small launcher that runs the CLI inside the addon; no Node needed).
56
+ - **Coded errors** replace several free-text errors (`INVALID_KEY`, `INVALID_TYPE_NAME`, `INVALID_ARGUMENT`,
57
+ `INVALID_OPTIONS`, …): see [Upgrading to 3.0](docs/upgrade-3.0.md#errors-invalid-arguments-have-codes).
58
+ - **Opening retries transient storage errors** for about 2.4 s and never quarantines an environment for them;
59
+ if one outlasts the retries, `open()` fails (restart the process). Corruption still quarantines the tenant env.
60
+ - **Plugins:** 2.x JS plugins work through the Node binding; `start()` runs after the whole open, and `okdb.api`
61
+ / `okdb.admin` are not available. See [Upgrading to 3.0](docs/upgrade-3.0.md#plugins).
42
62
 
43
- ## [2.7.0] - 2026-10-18
63
+ ### Added
64
+
65
+ - **A stable C bridge** (`okdb_bridge.h`, ABI 1.2) exported by the addon: open or attach to a live instance,
66
+ dispatch / batch / submit from any thread, read-only `read` from any thread, host callbacks (events, embedders,
67
+ chunk strategies), log routing. Lets native programs use okdb without compiling it in.
68
+ - **Thread-safe reads** in the core (a read-only handle used by the bridge's `read`).
69
+
70
+ ### Measured against 2.x (same machine; recorded once at release)
71
+
72
+ - Real applications: the brain test suite runs in 655 s (2.x 788 s); okcode cold indexing uses 4.5 s CPU
73
+ (2.x 8.6 s), 3.2 s wall (2.x 14.4 s), 311 MB peak memory (2.x 490 MB); its test suite runs in 110 s (238 s).
74
+ A 346 MB production store opened and checked with 0 mismatches across 548 checks; full-text search was ~10×
75
+ faster.
76
+ - Reads (200k docs): `get` 3.4 µs (2.x 3.3), `getRange` 382 ms (370), `byIndex` 590 ms (559), `getChanges`
77
+ 322 ms (449), filtered query 355 ms (396), `getKeys` 32 ms (51), `getMany` of 100 keys 317 µs (380).
78
+ - Index builds: adding 6 indexes to a live production store took 6 s and wrote 1 GB (2.x: 909 s and 38.8 GB,
79
+ unfinished).
80
+ - Responsiveness: the longest event-loop stall while full-text indexing is ~150 ms (2.x 3.1 s); an idle process
81
+ wakes about once every 5 s for okdb's bus listener.
82
+ - Install size: about 29 MB (2.x about 110 MB with its native dependencies).
83
+ - Known gaps: a cold-built full-text index file is 1.3–2.5× the 2.x size; very long scans keep ~30 MB more
84
+ JavaScript heap.
85
+
86
+ ### Fixed (also known issues in 2.7.0)
87
+
88
+ - Opening a store no longer drops a concurrent commit from another process, and a peer closing a store no
89
+ longer breaks its locks for other processes (`EINVAL` on every write).
90
+ - `queue.samplePayloads()` returns data; views recover from a crash during a `$ref` section and from a halted
91
+ restart.
92
+ - Writes with `origin: ""` are checked like local writes; `VIEW_TYPE_NOT_REGISTERED` over HTTP is a 404.
93
+
94
+ ## [2.7.0] - unreleased
44
95
 
45
96
  The last Node.js release line: okdb 3 is a Rust core that forks from this version. 2.7.0 fixes every bug
46
- found while porting, so a 2.7 process and an okdb 3 process can share a store and behave the same. The
47
- storage format is unchanged: no migrations, stores open as-is.
97
+ found while porting, so a store written by 2.7 opens in okdb 3 and behaves the same. The storage format is
98
+ unchanged: no migrations, stores open as-is. Upgrade by stopping every 2.x process, then opening the store
99
+ with okdb 3; do not run 2.x and 3.x writers on one store at the same time (see Known issue below).
48
100
 
49
101
  ### Changed (read before upgrading)
50
102
 
@@ -67,6 +119,27 @@ storage format is unchanged: no migrations, stores open as-is.
67
119
  Restart a process that reports `ENV_SWAPPED_UNDER`.
68
120
  - **Exports carry document versions** (`ver` on data lines). The importer already reads it.
69
121
 
122
+ ### Known issue
123
+
124
+ - **Opening a store can drop one concurrent write from another process.** The LMDB binding 2.x uses
125
+ (lmdb-js) resets a shared transaction counter whenever a process opens an environment. If another process
126
+ commits at that moment, that commit can be silently lost, even though it was acknowledged. The window is
127
+ narrow (we could not reproduce it in 140 loaded test runs, but it was observed once), and it applies to
128
+ stores shared by several 2.x processes, and to stores shared by 2.x and okdb 3 processes. 2.7.0 does not
129
+ change this. **To avoid it:** open every process's environments before write traffic starts, and upgrade
130
+ to okdb 3, whose storage layer does not have this bug. When upgrading, stop every 2.x process before an
131
+ okdb 3 process opens the store, and never run 2.x and 3.x writers on one store at the same time.
132
+
133
+ - **An environment can fail with `EINVAL` (Invalid argument) on every write after a peer closes it.** When a
134
+ process closes an environment while another process is opening it, lmdb-js can destroy the shared locks
135
+ the opener then uses; every write transaction in that process fails until all processes close the
136
+ environment. Restarting the affected processes recovers. Rare (it needs an open and a close to overlap).
137
+ Fixed in okdb 3.0, whose storage layer keeps those locks intact.
138
+ - **`queue.samplePayloads(type)` always returns `[]`.** Fixed in okdb 3.0.
139
+ - **A view whose `$ref` section crashed mid-scan stays `partially-ready`.** Restarting a halted view after a
140
+ reopen can also count an update to an existing key as a new key and miss grouped and `$ref` rows. Rebuild
141
+ the view (`views.rebuild(name)`) to recover. Fixed in okdb 3.0, which rebuilds such views on open.
142
+
70
143
  ### Fixed
71
144
 
72
145
  - **Full-text search lost postings** when a document lost a term and regained it before the next
@@ -75,8 +148,13 @@ storage format is unchanged: no migrations, stores open as-is.
75
148
  writes that a peer process skipped while the build ran.
76
149
  - **Sync:** a replica that was sent a remove for a key it never had wedged for good (`… does not exist`);
77
150
  it is now recorded as a no-op. A control pull no longer rewinds a newer data cursor, and an
78
- acknowledgement that lands during a GC sweep queues another sweep instead of being dropped.
151
+ acknowledgement that lands during a GC sweep queues another sweep instead of being dropped. A poke
152
+ that arrives while a pull from that peer is already running now triggers one more pull instead of
153
+ being dropped, so the last write of a burst no longer waits for the next unrelated event. Closing an
154
+ instance while a sync pull was running could crash the process; `close()` now waits for the pull
155
+ (up to a few seconds) before closing the environments.
79
156
  - **Queue `max_concurrency` never limited anything** (the running-job count scanned an empty range).
157
+ - **The queue worker could crash** when a peer's compaction closed its env while it was waiting for work.
80
158
  - **An index registered by one process was not maintained by processes already running** on the same
81
159
  store; writes now pick up the new index (they retry with `INDEX_SET_CHANGED` internally), and the build
82
160
  no longer overwrites a document written during its scan.
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: needs a license (sync) and a second node -->
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") })',
@@ -168,12 +194,16 @@ console.log(run.result.value.count);
168
194
 
169
195
  Zero-config REST API and a browser-based admin UI for data exploration, index management, and real-time monitoring.
170
196
 
197
+ <!-- not-runnable: starts a long-running server -->
198
+
171
199
  ```js
172
200
  db.http.listen(8080);
173
- // REST API: http://localhost:8080/api/type/users
201
+ // REST API: http://localhost:8080/api/...
174
202
  // Admin UI: http://localhost:8080/admin/
175
203
  ```
176
204
 
205
+ Or without writing code: `npx okdb --path ./mydb --port 8080` (the `okdb` CLI, see [HTTP API](docs/http-api.md)).
206
+
177
207
  ### 🧠 MCP endpoint (Inspector-ready example)
178
208
 
179
209
  OKDB also exposes an MCP server over SSE + POST:
@@ -181,13 +211,7 @@ OKDB also exposes an MCP server over SSE + POST:
181
211
  - `GET /mcp/sse`
182
212
  - `POST /mcp/messages`
183
213
 
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:
214
+ 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
215
 
192
216
  - `http://localhost:8787/mcp/sse`
193
217
 
@@ -200,9 +224,7 @@ The server responds with browser CORS headers for common Inspector origins, acce
200
224
  - `queue_list_jobs`
201
225
  - `processor_list`
202
226
 
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`.
227
+ MCP tools are derived from the HTTP API's route metadata; streaming / SSE routes are not exposed as tools.
206
228
 
207
229
  ### ⚙️ Reactive processors
208
230
 
@@ -210,22 +232,23 @@ Composable change handlers — like database triggers, written in JavaScript. Re
210
232
 
211
233
  ### ⏱️ Time-machine
212
234
 
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.
235
+ 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).
236
+
237
+ <!-- not-runnable: needs a license (timeMachine) -->
214
238
 
215
239
  ```js
216
- // Enable once; tracking starts from current clock
217
- await db.timeMachine.enable();
240
+ const db = new OKDB('./mydb', { timeMachine: true });
241
+ await db.open();
242
+ const tm = db.env('default').timeMachine;
243
+
244
+ // Enable per type; tracking starts from the current clock
245
+ await tm.enable('orders');
218
246
 
219
247
  // Point-in-time read — synchronous, no await
220
- const snapshot = db.timeMachine.getStateAt('orders', 'ord-42', historicClock);
248
+ const snapshot = tm.getStateAt('orders', 'ord-42', historicClock);
221
249
 
222
250
  // 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
- }
251
+ const history = tm.getHistory('orders', 'ord-42');
229
252
  ```
230
253
 
231
254
  ### 📊 Materialized views
@@ -234,6 +257,8 @@ Reactive aggregations that update automatically on every write. Declare a view w
234
257
 
235
258
  ```js
236
259
  const env = db.env('default');
260
+ await env.ensureType('orders');
261
+ await env.put('orders', 'o1', { status: 'completed', amount: 120, region: 'EU' });
237
262
 
238
263
  await env.views.create('orderStats', {
239
264
  type: 'orders',
@@ -271,10 +296,15 @@ Multi-mode security layer built into the HTTP API. No separate auth service need
271
296
  ## Installation
272
297
 
273
298
  ```bash
274
- npm install okdb
299
+ npm install @kedem/okdb
275
300
  ```
276
301
 
277
- > **Runtime:** Node.js only. Requires a native LMDB build (handled automatically by the `lmdb` package via node-gyp).
302
+ > **Runtime:** Node.js 18 or newer on **Linux x64 with glibc 2.28+**. The native core ships inside the package (no compiler,
303
+ > no install scripts, no separate platform package). npm refuses to install it on other platforms; on a host it slips through
304
+ > (musl/Alpine, a forced install) `require('@kedem/okdb')` throws `NATIVE_UNAVAILABLE`. Those platforms can stay on okdb 2.x.
305
+ >
306
+ > The same native file also serves programs written in other languages through a stable C interface: see
307
+ > [C bridge](docs/c-bridge.md).
278
308
 
279
309
  ---
280
310
 
@@ -325,15 +355,17 @@ main().catch(console.error);
325
355
  | [Full-Text Search](docs/fts.md) | Registering FTS indexes, tokenizer config, search |
326
356
  | [Embeddings](docs/embeddings.md) | Vector pipeline, embedders, HNSW search |
327
357
  | [Sync](docs/sync.md) | Cluster setup, joining peers, conflict resolution |
328
- | [Queue](docs/queue.md) | Durable job queue, workers, retry |
358
+ | [Queue](docs/queue.md) | Durable job queue, consumers, retry |
329
359
  | [Files](docs/files.md) | Blob storage, upload, download, sync |
330
360
  | [Custom Functions](docs/functions.md) | Stored sandboxed JS functions, env/global execution, HTTP routes |
331
361
  | [Pipelines](docs/pipelines.md) | Composable data-flow orchestration with queue and processor drivers |
332
362
  | [HTTP API](docs/http-api.md) | REST endpoints, auth, admin UI |
333
363
  | [Auth](docs/auth-permissions.md) | Token, OIDC, IP allowlist authentication |
334
364
  | [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 |
365
+ | [Migration](docs/migration.md) | Export, import, backup, restore |
366
+ | [Licensing](docs/licensing.md) | Free tier, license files, limits |
367
+ | [Upgrading to 3.0](docs/upgrade-3.0.md) | What changes when you move from okdb 2.x |
368
+ | [C bridge](docs/c-bridge.md) | Using the native core from C, Rust, Go, ... without Node |
337
369
 
338
370
  ---
339
371
 
package/bin/okdb ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
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: needs a license (sync) and a peer -->
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.