@kedem/okdb 3.0.0 → 3.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +38 -3
- package/README.md +68 -36
- package/bin/okdb +1 -1
- package/docs/auth-and-sync.md +30 -24
- package/docs/auth-permissions.md +5 -4
- package/docs/c-bridge.md +94 -0
- package/docs/change-log.md +78 -35
- package/docs/data-model.md +32 -8
- package/docs/deployment.md +42 -38
- package/docs/diagnostics.md +61 -125
- package/docs/embeddings.md +143 -51
- package/docs/files.md +53 -18
- package/docs/fts.md +48 -23
- package/docs/functions.md +107 -56
- package/docs/getting-started.md +125 -9
- package/docs/http-api.md +68 -11
- package/docs/http-cluster.md +80 -88
- package/docs/index.md +33 -15
- package/docs/indexes.md +53 -17
- package/docs/licensing.md +18 -4
- package/docs/logging.md +11 -22
- package/docs/manifest.json +4 -2
- package/docs/migration.md +40 -15
- package/docs/pipelines.md +96 -32
- package/docs/plugins.md +47 -15
- package/docs/process-registry.md +23 -24
- package/docs/processors.md +26 -23
- package/docs/querying.md +102 -29
- package/docs/queue.md +167 -51
- package/docs/resolved-fields.md +24 -1
- package/docs/subscriptions.md +4 -4
- package/docs/sync.md +9 -6
- package/docs/time-machine.md +40 -11
- package/docs/transactions.md +63 -15
- package/docs/ttl.md +34 -13
- package/docs/upgrade-2.0.md +32 -15
- package/docs/upgrade-2.1.md +10 -12
- package/docs/upgrade-3.0.md +144 -0
- package/docs/views.md +131 -42
- package/index.js +1 -1
- package/native/linux-x64-gnu/okdb +0 -0
- package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
- package/native-loader.js +1 -1
- package/okdb-native.js +1 -1
- package/package.json +1 -1
- package/types/environment.d.ts +32 -11
- package/types/errors.d.ts +20 -0
- package/types/features/admin.d.ts +3 -5
- package/types/features/api.d.ts +5 -7
- package/types/features/embeddings.d.ts +8 -7
- package/types/features/engines.d.ts +9 -1
- package/types/features/files.d.ts +2 -1
- package/types/features/fts.d.ts +3 -3
- package/types/features/functions.d.ts +14 -8
- package/types/features/pipelines.d.ts +10 -10
- package/types/features/queue.d.ts +15 -10
- package/types/features/sync.d.ts +7 -0
- package/types/features/time-machine.d.ts +3 -0
- package/types/index.d.ts +3 -0
- package/types/okdb.d.ts +70 -7
- package/types/options.d.ts +12 -8
- package/docs/OKDB-ARCHITECTURE.md +0 -1061
package/docs/change-log.md
CHANGED
|
@@ -9,6 +9,9 @@ Every write in OKDB — put, remove, registerType, registerIndex — increments
|
|
|
9
9
|
A per-environment monotonic integer. Starts at 0, increments by 1 for every logged change (each put or remove inside a transaction gets its own clock). The clock is shared across processes open on the same path.
|
|
10
10
|
|
|
11
11
|
```javascript
|
|
12
|
+
await okdb.registerType('users');
|
|
13
|
+
await okdb.put('users', 'alice', { name: 'Alice' });
|
|
14
|
+
|
|
12
15
|
// Current clock value
|
|
13
16
|
const clock = okdb.getClock();
|
|
14
17
|
|
|
@@ -20,6 +23,8 @@ const usersClock = okdb.getClock('users');
|
|
|
20
23
|
|
|
21
24
|
## Reading the change log
|
|
22
25
|
|
|
26
|
+
<!-- continues -->
|
|
27
|
+
|
|
23
28
|
```javascript
|
|
24
29
|
// Get changes between clock 100 and 200 (both inclusive).
|
|
25
30
|
// Returns a lazy iterable over a pinned snapshot — consume it synchronously
|
|
@@ -35,7 +40,7 @@ for (const change of changes) {
|
|
|
35
40
|
// action: 'put', // 'put' | 'remove' | 'registerType' | 'dropType' | 'registerIndex' | 'dropIndex' | 'resetIndex' | 'setSchema' | …
|
|
36
41
|
// timestamp: 1833234737026049, // HLC value (wall-clock ms * 1024 + logical counter)
|
|
37
42
|
// origin: 'node-uuid',
|
|
38
|
-
// txnId: 'txn-uuid',
|
|
43
|
+
// txnId: 'txn-uuid', // item changes only
|
|
39
44
|
// }
|
|
40
45
|
}
|
|
41
46
|
|
|
@@ -56,6 +61,8 @@ OKDB emits events on `okdb.events` (a standard Node.js `EventEmitter`) after eac
|
|
|
56
61
|
### Data events
|
|
57
62
|
|
|
58
63
|
```javascript
|
|
64
|
+
await okdb.registerType('users');
|
|
65
|
+
|
|
59
66
|
okdb.events.on('item:create', ({ env, type, key, newValue, clock, origin }) => {
|
|
60
67
|
console.log(`Created ${type}/${key}`);
|
|
61
68
|
});
|
|
@@ -67,21 +74,27 @@ okdb.events.on('item:update', ({ type, key, newValue, oldValue, clock }) => {
|
|
|
67
74
|
okdb.events.on('item:remove', ({ type, key, oldValue, clock }) => {
|
|
68
75
|
console.log(`Removed ${type}/${key}`);
|
|
69
76
|
});
|
|
77
|
+
|
|
78
|
+
await okdb.put('users', 'alice', { name: 'Alice' }); // item:create
|
|
79
|
+
await okdb.put('users', 'alice', { name: 'Alice B.' }); // item:update
|
|
80
|
+
await okdb.remove('users', 'alice'); // item:remove
|
|
70
81
|
```
|
|
71
82
|
|
|
83
|
+
Data-event payloads are the change record: `{ env, type, key, action, clock, version, timestamp, origin, txnId, newValue, oldValue, expiresAt }`.
|
|
84
|
+
|
|
72
85
|
### System events
|
|
73
86
|
|
|
74
87
|
```javascript
|
|
75
|
-
okdb.events.on('system:clock_change', ({ clock, type }) =>
|
|
76
|
-
okdb.events.on('system:clock_change@users', () =>
|
|
77
|
-
okdb.events.on('system:ready', (
|
|
78
|
-
okdb.events.on('system:stopped', () =>
|
|
79
|
-
okdb.events.on('env:opened', ({ name
|
|
88
|
+
okdb.events.on('system:clock_change', ({ clock, type }) => console.log('clock', clock, type));
|
|
89
|
+
okdb.events.on('system:clock_change@users', () => console.log('users changed')); // type-specific — emitted with no payload
|
|
90
|
+
okdb.events.on('system:ready', () => console.log('ready')); // end of open(), no payload
|
|
91
|
+
okdb.events.on('system:stopped', () => console.log('stopped')); // during close()
|
|
92
|
+
okdb.events.on('env:opened', ({ name }) => console.log('env opened', name));
|
|
80
93
|
```
|
|
81
94
|
|
|
82
95
|
`okdb.events` is one emitter shared by every env (`env.events === okdb.events`); data-event payloads carry `env` so you can tell them apart. The events are in-process only — for writes made by other processes on the same path, use a processor with `originMode: 'all'` or the SSE subscriptions API.
|
|
83
96
|
|
|
84
|
-
Events fire **after** the LMDB transaction
|
|
97
|
+
Events fire **after** the LMDB transaction has committed. Listeners never see speculative data.
|
|
85
98
|
|
|
86
99
|
:::warning Backpressure
|
|
87
100
|
Events are emitted synchronously via `EventEmitter`. A slow listener blocks subsequent event delivery. For heavy processing, use the **Processor** system instead.
|
|
@@ -101,6 +114,10 @@ Handlers are **named, not bare closures** — every process that registers the p
|
|
|
101
114
|
|
|
102
115
|
```javascript
|
|
103
116
|
// ./fulfillment.js
|
|
117
|
+
async function scheduleShipment(key, order) {
|
|
118
|
+
console.log('ship', key, order.item);
|
|
119
|
+
}
|
|
120
|
+
|
|
104
121
|
exports.apply = async (ctx, changes, info) => {
|
|
105
122
|
for (const ch of changes) {
|
|
106
123
|
if (ch.action !== 'put') continue;
|
|
@@ -109,50 +126,66 @@ exports.apply = async (ctx, changes, info) => {
|
|
|
109
126
|
}
|
|
110
127
|
}
|
|
111
128
|
};
|
|
129
|
+
```
|
|
112
130
|
|
|
113
|
-
|
|
131
|
+
Register it (here the module file is written first so the example is self-contained; normally it is a file in your project):
|
|
132
|
+
|
|
133
|
+
```javascript
|
|
134
|
+
const fs = require('node:fs');
|
|
135
|
+
const path = require('node:path');
|
|
136
|
+
fs.writeFileSync(
|
|
137
|
+
path.resolve('fulfillment.js'),
|
|
138
|
+
'exports.apply = async (ctx, changes) => { for (const ch of changes) console.log(ch.action, ch.key); };',
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
await okdb.registerType('orders');
|
|
114
142
|
const stop = okdb.env('default').processor.register('orders', {
|
|
115
143
|
name: 'orders:fulfillment', // human-readable name
|
|
116
144
|
cursorKey: 'orders:fulfillment', // durable resume position
|
|
117
145
|
mode: 'async', // default — 1-of-N, leased, durable cursor
|
|
118
146
|
originMode: 'all', // 'self' (default) | 'remote' | 'all'
|
|
119
|
-
module: { path:
|
|
147
|
+
module: { path: path.resolve('fulfillment.js'), export: 'apply' },
|
|
120
148
|
});
|
|
121
149
|
|
|
150
|
+
await okdb.put('orders', 'o1', { item: 'widget', status: 'paid' });
|
|
151
|
+
await stop.awaitIdle(5000); // wait until the handler has drained the backlog
|
|
152
|
+
|
|
122
153
|
// Stop the handler
|
|
123
154
|
await stop();
|
|
124
155
|
```
|
|
125
156
|
|
|
126
|
-
Passing `handler: async (changes) => …` (a bare closure) throws. The alternative to `module` is `handler: '<name>'` for a function registered with `
|
|
157
|
+
Passing `handler: async (changes) => …` (a bare closure) throws. The alternative to `module` is `handler: '<name>'` for a function registered in-process with `env.processor.constructor.registerHandler(name, fn)` (the processor class is not exported from the package root) — see [Processors](processors.md#registering-a-processor).
|
|
127
158
|
|
|
128
159
|
### Register options reference
|
|
129
160
|
|
|
130
|
-
| Option | Type | Default | Description
|
|
131
|
-
| -------------------- | --------- | ---------- |
|
|
132
|
-
| `module` | `object` | — | `{ path, export }` — file handler, called as `fn(ctx, changes[], info)` with `ctx = { env, payload }`. Exactly one of `module` / `handler` is required.
|
|
133
|
-
| `handler` | `string` | — | Name of a function registered with `
|
|
134
|
-
| `payload` | `any` | `null` | Registration-time value passed to the handler as `ctx.payload`
|
|
135
|
-
| `mode` | `string` | `'async'` | `'async'` (background drain) \| `'sync'` (every writer, inside the commit). Deprecated single-string aliases `'single'`/`'worker'`/`'fanout'`/`'inline'` still map with a warning; bare `'async'` is **not** fanout.
|
|
136
|
-
| `distribution` | `string` | `'single'` | `mode:'async'` only: `'single'` (1-of-N, leased, durable cursor) \| `'fanout'` (N-of-N, per-process in-memory cursor starting at "now")
|
|
137
|
-
| `bootstrap` | `string` | `'log'` | `'snapshot'` \| `'log'` — how the initial backfill runs
|
|
138
|
-
| `originMode` | `string` | `'self'` | `'all'` \| `'self'` \| `'remote'`
|
|
139
|
-
| `batchSize` | `number` | `256` | Max changes delivered per handler call
|
|
140
|
-
| `hydrateValues` | `boolean` | `true` | Attach current document value to each change
|
|
141
|
-
| `cursorKey` | `string` | `null` | Persist the cursor under this key so progress survives restarts
|
|
142
|
-
| `lockMode` | `string` | `null` | `'exclusive'` — serialise concurrent flushes for this processor
|
|
143
|
-
| `failOnHandlerError` | `boolean` | `false` | Put the processor into error state on handler exception
|
|
144
|
-
| `flushDebounce` | `number` | `0` | Trailing-edge debounce in ms. Rapid write bursts coalesce into a single flush after `flushDebounce` ms of quiet. `0` = flush immediately (default).
|
|
145
|
-
| `flushInterval` | `number` | `null` |
|
|
146
|
-
| `name` | `string` | `null` | Human-readable label shown in admin UI and status
|
|
147
|
-
| `meta` | `object` | `{}` | Arbitrary metadata attached to status objects
|
|
148
|
-
| `leaseTtlMs` | `number` | `30000` | Lease TTL for cross-process exclusive execution
|
|
149
|
-
|
|
150
|
-
`stop.status()` (alias `stop.getStatus()`)
|
|
161
|
+
| Option | Type | Default | Description |
|
|
162
|
+
| -------------------- | --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
163
|
+
| `module` | `object` | — | `{ path, export }` — file handler, called as `fn(ctx, changes[], info)` with `ctx = { env, payload }`. Exactly one of `module` / `handler` is required. |
|
|
164
|
+
| `handler` | `string` | — | Name of a function registered with `env.processor.constructor.registerHandler(name, fn)`; same call signature. Bare closures throw. |
|
|
165
|
+
| `payload` | `any` | `null` | Registration-time value passed to the handler as `ctx.payload` |
|
|
166
|
+
| `mode` | `string` | `'async'` | `'async'` (background drain) \| `'sync'` (every writer, inside the commit). Deprecated single-string aliases `'single'`/`'worker'`/`'fanout'`/`'inline'` still map with a warning; bare `'async'` is **not** fanout. |
|
|
167
|
+
| `distribution` | `string` | `'single'` | `mode:'async'` only: `'single'` (1-of-N, leased, durable cursor) \| `'fanout'` (N-of-N, per-process in-memory cursor starting at "now") |
|
|
168
|
+
| `bootstrap` | `string` | `'log'` | `'snapshot'` \| `'log'` — how the initial backfill runs |
|
|
169
|
+
| `originMode` | `string` | `'self'` | `'all'` \| `'self'` \| `'remote'` |
|
|
170
|
+
| `batchSize` | `number` | `256` | Max changes delivered per handler call |
|
|
171
|
+
| `hydrateValues` | `boolean` | `true` | Attach current document value to each change |
|
|
172
|
+
| `cursorKey` | `string` | `null` | Persist the cursor under this key so progress survives restarts |
|
|
173
|
+
| `lockMode` | `string` | `null` | `'exclusive'` — serialise concurrent flushes for this processor |
|
|
174
|
+
| `failOnHandlerError` | `boolean` | `false` | Put the processor into error state on handler exception |
|
|
175
|
+
| `flushDebounce` | `number` | `0` | Trailing-edge debounce in ms. Rapid write bursts coalesce into a single flush after `flushDebounce` ms of quiet. `0` = flush immediately (default). |
|
|
176
|
+
| `flushInterval` | `number` | `null` | Also schedule a drain every `flushInterval` ms after bootstrap. Useful for polling-style processors or `originMode: 'remote'` subscriptions where local writes don't trigger a drain. `null` = disabled. |
|
|
177
|
+
| `name` | `string` | `null` | Human-readable label shown in admin UI and status |
|
|
178
|
+
| `meta` | `object` | `{}` | Arbitrary metadata attached to status objects |
|
|
179
|
+
| `leaseTtlMs` | `number` | `30000` | Lease TTL for cross-process exclusive execution |
|
|
180
|
+
|
|
181
|
+
The returned `stop` function also carries `stop.status()` (alias `stop.getStatus()`) — the live processor state including `lag`, `state`, `flushDebounce` and `flushInterval` — plus `stop.pause()`, `stop.resume()`, `stop.kick()`, `stop.retry()` and `stop.awaitIdle(timeoutMs)`. `stop.pause()` clears both timers; `stop.resume()` restarts the interval if configured.
|
|
151
182
|
|
|
152
183
|
### Change object shape
|
|
153
184
|
|
|
154
185
|
Async (`single`/`fanout`) handlers receive change-log records:
|
|
155
186
|
|
|
187
|
+
<!-- not-runnable: shape of a change record, not a program -->
|
|
188
|
+
|
|
156
189
|
```javascript
|
|
157
190
|
{
|
|
158
191
|
id: 'item:orders@o42',
|
|
@@ -181,20 +214,26 @@ Async (`single`/`fanout`) handlers receive change-log records:
|
|
|
181
214
|
|
|
182
215
|
This is useful for reacting differently to local vs. replicated changes — e.g., sending a notification only when your own node creates a record, not when it receives one from a peer.
|
|
183
216
|
|
|
184
|
-
**Multi-process deployments:** Async processors with `originMode: 'all'` or `'remote'` automatically subscribe to
|
|
217
|
+
**Multi-process deployments:** Async processors with `originMode: 'all'` or `'remote'` automatically subscribe to the cross-process commit signal (`system:poke`, carried by okdb's UDP bus). When another process writes to the same LMDB environment, it sends a `POKE` via the bus; the local process receives it and wakes all eligible processors within tens of milliseconds. No configuration is needed — the behavior is automatic based on `originMode`. Processors with `originMode: 'self'` do not subscribe (they explicitly don't care about remote-origin changes).
|
|
185
218
|
|
|
186
219
|
### Processor on a custom env
|
|
187
220
|
|
|
188
221
|
Each environment has its own processor:
|
|
189
222
|
|
|
223
|
+
<!-- continues -->
|
|
224
|
+
|
|
190
225
|
```javascript
|
|
191
|
-
|
|
192
|
-
|
|
226
|
+
fs.writeFileSync(path.resolve('aggregate.js'), 'exports.apply = async (ctx, changes) => {};');
|
|
227
|
+
|
|
228
|
+
const analytics = await okdb.createEnvironment('analytics');
|
|
229
|
+
await analytics.registerType('events');
|
|
230
|
+
const stopAggregate = analytics.processor.register('events', {
|
|
193
231
|
originMode: 'all',
|
|
194
232
|
name: 'analytics:aggregate',
|
|
195
233
|
cursorKey: 'analytics:aggregate',
|
|
196
|
-
module: { path:
|
|
234
|
+
module: { path: path.resolve('aggregate.js'), export: 'apply' },
|
|
197
235
|
});
|
|
236
|
+
await stopAggregate();
|
|
198
237
|
```
|
|
199
238
|
|
|
200
239
|
---
|
|
@@ -204,6 +243,10 @@ const stop = env.processor.register('events', {
|
|
|
204
243
|
The `timestamp` field on change objects is a **Hybrid Logical Clock** value: a 64-bit integer encoding both wall-clock milliseconds and a logical counter. HLC values are monotonically increasing even when system clocks skew backwards, which makes them safe for LWW conflict resolution in sync.
|
|
205
244
|
|
|
206
245
|
```javascript
|
|
246
|
+
await okdb.registerType('users');
|
|
247
|
+
await okdb.put('users', 'alice', { name: 'Alice' });
|
|
248
|
+
const [change] = [...okdb.getChanges('users')].slice(-1);
|
|
249
|
+
|
|
207
250
|
// Decode an HLC value: physicalTime * 1024 + logicalCounter
|
|
208
251
|
const wallMs = Math.floor(change.timestamp / 1024);
|
|
209
252
|
const logical = change.timestamp % 1024;
|
package/docs/data-model.md
CHANGED
|
@@ -38,6 +38,7 @@ A **record** is a key-value pair inside a type.
|
|
|
38
38
|
- **Value**: any JSON-serialisable value
|
|
39
39
|
|
|
40
40
|
```javascript
|
|
41
|
+
await okdb.registerType('articles');
|
|
41
42
|
await okdb.put('articles', 'how-lmdb-works', {
|
|
42
43
|
title: 'How LMDB works',
|
|
43
44
|
author: 'alice',
|
|
@@ -49,15 +50,17 @@ await okdb.put('articles', 'how-lmdb-works', {
|
|
|
49
50
|
|
|
50
51
|
Values can also be direct JSON scalars or arrays (`"hello"`, `42`, `true`, `null`, `[]`). Those values are stored and read back normally. However, object-oriented features such as `patch()` and observed field schema only apply to plain object records.
|
|
51
52
|
|
|
52
|
-
Values are
|
|
53
|
+
Values are encoded with msgpack and LZ4-compressed above a small size threshold (`compression: true` by default). Keys and secondary-index keys use the [ordered-binary](https://github.com/DoctorEvidence/ordered-binary) encoding, which preserves type ordering in scans.
|
|
53
54
|
|
|
54
55
|
### Versions
|
|
55
56
|
|
|
56
|
-
Every record implicitly has a **version** — an integer that monotonically increases with each write.
|
|
57
|
+
Every record implicitly has a **version** — an integer that monotonically increases with each write. It is stored with the record and drives optimistic concurrency (`ifVersion`, see [Transactions](./transactions.md#optimistic-concurrency)).
|
|
58
|
+
|
|
59
|
+
<!-- continues -->
|
|
57
60
|
|
|
58
61
|
```javascript
|
|
59
62
|
const entry = okdb.getEntry('articles', 'how-lmdb-works');
|
|
60
|
-
// entry = { value: {...}, version:
|
|
63
|
+
// entry = { value: {...}, version: 1 }
|
|
61
64
|
```
|
|
62
65
|
|
|
63
66
|
---
|
|
@@ -95,6 +98,8 @@ const evt = analyticsEnv.get('events', 'e1');
|
|
|
95
98
|
Accessing an environment:
|
|
96
99
|
|
|
97
100
|
```javascript
|
|
101
|
+
await okdb.createEnvironment('analytics');
|
|
102
|
+
|
|
98
103
|
okdb.env('default'); // the default env
|
|
99
104
|
okdb.env('analytics'); // custom env by name
|
|
100
105
|
okdb.default; // shorthand for okdb.env('default')
|
|
@@ -157,6 +162,8 @@ FTS indexes are **async by default**. When a document is written, the change is
|
|
|
157
162
|
- Use `fts.ready(type)` to wait for the initial index build to complete after registering a new index.
|
|
158
163
|
|
|
159
164
|
```javascript
|
|
165
|
+
await okdb.registerType('articles');
|
|
166
|
+
|
|
160
167
|
// Register an FTS index
|
|
161
168
|
await okdb.fts.register('articles', 'main', { fields: ['title', 'body'] });
|
|
162
169
|
|
|
@@ -208,12 +215,15 @@ LMDB never shrinks `data.mdb` in place — freed pages are reused by future writ
|
|
|
208
215
|
OKDB observes field types as you write data and maintains a coarse schema (`string | number | boolean | null | array | object`) per field. You can inspect it:
|
|
209
216
|
|
|
210
217
|
```javascript
|
|
218
|
+
await okdb.ensureType('articles', { indexes: [['author'], ['author', 'publishedAt']] });
|
|
219
|
+
await okdb.put('articles', 'a1', { title: 'Hello', author: 'alice', publishedAt: Date.now(), tags: ['x'] });
|
|
220
|
+
|
|
211
221
|
const desc = okdb.meta.describeType('articles'); // synchronous
|
|
212
222
|
// {
|
|
213
223
|
// type: 'articles',
|
|
214
|
-
// count:
|
|
215
|
-
// fields: { title: ['string'], publishedAt: ['number'], tags: ['array'], ... }, // every type seen per field
|
|
224
|
+
// count: 1,
|
|
216
225
|
// indexes: ['author', 'author~publishedAt'],
|
|
226
|
+
// fields: { title: ['string'], author: ['string'], publishedAt: ['number'], tags: ['array'] }, // every type seen per field
|
|
217
227
|
// }
|
|
218
228
|
```
|
|
219
229
|
|
|
@@ -223,7 +233,7 @@ The observed schema is **descriptive only** — it never rejects a write. For va
|
|
|
223
233
|
|
|
224
234
|
## Durability modes
|
|
225
235
|
|
|
226
|
-
Set at construction time via the `durability` option
|
|
236
|
+
Set at construction time via the `durability` option (default `'balanced'`), or per environment with `createEnvironment(name, { durability })`:
|
|
227
237
|
|
|
228
238
|
| Mode | Underlying LMDB flag | Behaviour | Use when |
|
|
229
239
|
| ---------- | -------------------- | ------------------------------------ | --------------------------------- |
|
|
@@ -234,11 +244,15 @@ Set at construction time via the `durability` option:
|
|
|
234
244
|
|
|
235
245
|
```javascript
|
|
236
246
|
const okdb = new OKDB('./db', { durability: 'fast' });
|
|
247
|
+
await okdb.open();
|
|
248
|
+
await okdb.close();
|
|
237
249
|
```
|
|
238
250
|
|
|
251
|
+
On Linux, `strict` and `custom` also open the environment with LMDB's overlapping sync unless `noSync` is set; pass `lmdb: { overlappingSync: false }` to turn it off explicitly. `okdb.getResolvedOptions()` / `env.getResolvedOptions()` return `{ durability, lmdbOptions, warnings }` — the resolved preset plus your `lmdb` flags, and any guardrail warnings.
|
|
252
|
+
|
|
239
253
|
### Raw LMDB passthrough
|
|
240
254
|
|
|
241
|
-
For workloads like replication followers or append-only archives where you need precise control, pass
|
|
255
|
+
For workloads like replication followers or append-only archives where you need precise control, pass LMDB flags via the `lmdb` option. The recognised flags are `noSync`, `noMetaSync`, `overlappingSync` and `useWritemap`. Use `durability: 'custom'` to disable preset interference:
|
|
242
256
|
|
|
243
257
|
```javascript
|
|
244
258
|
const okdb = new OKDB('./db', {
|
|
@@ -248,8 +262,18 @@ const okdb = new OKDB('./db', {
|
|
|
248
262
|
noMetaSync: true, // skip metadata page fsync — partial durability improvement
|
|
249
263
|
},
|
|
250
264
|
});
|
|
265
|
+
await okdb.open();
|
|
266
|
+
await okdb.close();
|
|
251
267
|
```
|
|
252
268
|
|
|
253
269
|
`noSync: true` is equivalent to `durability: 'fast'` but lets you combine it with other raw flags. `noMetaSync: true` without `noSync` is the middle ground: data pages are synced, metadata pages are not — faster than `strict`, safer than `noSync`.
|
|
254
270
|
|
|
255
|
-
OKDB enforces guardrails
|
|
271
|
+
OKDB enforces guardrails, checked when an environment opens:
|
|
272
|
+
|
|
273
|
+
- `noSync` or `noMetaSync` together with `durability: 'strict'` throws `UNSAFE_CONFIG`.
|
|
274
|
+
- `useWritemap` with `strict` or `balanced` throws `UNSAFE_CONFIG` (use `fast` or `custom`).
|
|
275
|
+
- `noSync` + `useWritemap` only warns (`warnings` in `getResolvedOptions()`).
|
|
276
|
+
- `noSync: true` with an environment that opens with overlapping sync (`balanced`, or `lmdb.overlappingSync: true`) is refused.
|
|
277
|
+
- An unknown `durability` value throws `INVALID_CONFIG`.
|
|
278
|
+
|
|
279
|
+
`allowUnsafe: true` downgrades the `UNSAFE_CONFIG` errors to warnings. Use `durability: 'custom'` when passing these flags explicitly.
|
package/docs/deployment.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Roles & Deployment
|
|
2
2
|
|
|
3
|
-
okdb
|
|
3
|
+
okdb has one runtime model (since 2.0, unchanged in 3.0): **the process is the control unit**. Every process that opens
|
|
4
4
|
a data path declares — at construction — which background work it runs, and okdb never forks
|
|
5
5
|
or supervises processes for you. Scale-out is always the same move: **run more okdb processes
|
|
6
6
|
on the same path**; the per-processor 1-of-N lease distributes the work automatically, with no
|
|
@@ -14,18 +14,18 @@ do-everything node and the defaults are correct.
|
|
|
14
14
|
## The role flags
|
|
15
15
|
|
|
16
16
|
```js
|
|
17
|
-
new OKDB(
|
|
17
|
+
const node = new OKDB('./data', {
|
|
18
18
|
processors: true, // claim processor leases + drain derived work (default true)
|
|
19
|
-
engines: true, // run
|
|
19
|
+
engines: true, // run queue / pipeline / embeddings engines (default true)
|
|
20
20
|
compaction: true, // eligible to claim the per-env compaction lease (default true)
|
|
21
21
|
});
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
-
| Flag | `true` (default)
|
|
25
|
-
| ------------ |
|
|
26
|
-
| `processors` | Claim every unclaimed `single` processor lease; drain FTS / views / time-machine / materializer / embeddings
|
|
27
|
-
| `engines` | Run queue worker engines, pipeline workers, embeddings engines
|
|
28
|
-
| `compaction` | Eligible to claim the per-env compaction lease
|
|
24
|
+
| Flag | `true` (default) | `false` (passive) |
|
|
25
|
+
| ------------ | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
|
|
26
|
+
| `processors` | Claim every unclaimed `single` processor lease; drain FTS / views / time-machine / materializer / embeddings in this process | Claim nothing. Reads, writes, and **inline** processors (indexes, schema, FK, TTL) still run |
|
|
27
|
+
| `engines` | Run queue worker engines, pipeline workers, embeddings engines | None of those start here |
|
|
28
|
+
| `compaction` | Eligible to claim the per-env compaction lease | Never auto-compacts (`env.compact()` still works when called explicitly) |
|
|
29
29
|
|
|
30
30
|
Three things to internalize:
|
|
31
31
|
|
|
@@ -49,22 +49,25 @@ const db = new OKDB('./data');
|
|
|
49
49
|
await db.open();
|
|
50
50
|
```
|
|
51
51
|
|
|
52
|
-
Serves your app's reads/writes and does all derived work
|
|
52
|
+
Serves your app's reads/writes and does all derived work in the same process, in bounded quanta.
|
|
53
53
|
This is crash-safe and correct on its own; you add processes when you decide you need them.
|
|
54
54
|
|
|
55
55
|
### 2. Embedded + HTTP
|
|
56
56
|
|
|
57
57
|
```js
|
|
58
|
-
db.http.listen(
|
|
58
|
+
const server = db.http.listen(0); // an http.Server-compatible handle (0 = any free port)
|
|
59
|
+
server.on('listening', () => console.log(server.address().port));
|
|
60
|
+
await db.http.close();
|
|
59
61
|
```
|
|
60
62
|
|
|
61
|
-
Same single process, plus the REST API and admin UI
|
|
62
|
-
single-process — `http.listen(port, { workers })` throws
|
|
63
|
+
Same single process, plus the REST API and admin UI (the server runs inside okdb's native core).
|
|
64
|
+
The embedded server is always single-process — `http.listen(port, { workers })` throws
|
|
65
|
+
`HTTP_CLUSTER_REMOVED`.
|
|
63
66
|
|
|
64
67
|
### 3. N capable nodes (the CLI's shape)
|
|
65
68
|
|
|
66
|
-
Run N identical full-role processes on the same path — either via `
|
|
67
|
-
|
|
69
|
+
Run N identical full-role processes on the same path — either via the `okdb` CLI (one listen
|
|
70
|
+
port, thin passive supervisor; see [HTTP Clustering](./http-cluster.md)) or as N independent
|
|
68
71
|
`new OKDB(path)` + `http.listen()` processes behind your own load balancer. Each node serves
|
|
69
72
|
**and** processes; the leases spread the processors across them and fail over when a node dies.
|
|
70
73
|
|
|
@@ -72,13 +75,19 @@ socket, thin passive supervisor; see [HTTP Clustering](./http-cluster.md)) or as
|
|
|
72
75
|
|
|
73
76
|
When you want the serving loop insulated from heavy backfill/indexing work:
|
|
74
77
|
|
|
78
|
+
<!-- not-runnable: shows two separate processes (a long-running server and a worker) -->
|
|
79
|
+
|
|
75
80
|
```js
|
|
76
|
-
|
|
81
|
+
const path = '/srv/okdb';
|
|
82
|
+
|
|
83
|
+
// serving process — only serves; never claims, never compacts
|
|
77
84
|
const front = new OKDB(path, { processors: false, engines: false, compaction: false });
|
|
85
|
+
await front.open();
|
|
78
86
|
front.http.listen(8080);
|
|
79
87
|
|
|
80
88
|
// N worker processes — headless, do all the processing
|
|
81
89
|
const worker = new OKDB(path, { processors: true }); // engines/compaction default true
|
|
90
|
+
await worker.open();
|
|
82
91
|
```
|
|
83
92
|
|
|
84
93
|
With the CLI, the serving node takes the same flags from its config file (they apply to the
|
|
@@ -89,24 +98,14 @@ single process and to every cluster worker; see [HTTP Clustering](./http-cluster
|
|
|
89
98
|
{ "processors": false, "engines": false, "compaction": false }
|
|
90
99
|
```
|
|
91
100
|
|
|
92
|
-
Workers need no ports: coordination is the shared LMDB + the
|
|
93
|
-
are your launcher's job (systemd, pm2, docker, k8s
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
Why it matters: lmdb-js (3.5.x) has a bug where opening an LMDB environment while another
|
|
101
|
-
process commits to it can rewind the shared transaction id, which later shows up as native
|
|
102
|
-
crashes (`SIGSEGV`, `MDB_PROBLEM`) or a lost commit. okdb works around the worst case itself:
|
|
103
|
-
while a store is being **initialised** (an env it opens at boot has no data file yet), `open()`
|
|
104
|
-
takes a cross-process **boot lock**, so several processes starting on a brand-new path boot one
|
|
105
|
-
at a time. A dead or stale holder is taken over; a waiter that exceeds
|
|
106
|
-
`OKDB_BOOT_LOCK_TIMEOUT_MS` (default 60 000) logs a warning and proceeds unserialised. On an
|
|
107
|
-
established store the lock is not taken, so opening a process alongside a peer that is actively
|
|
108
|
-
writing — and runtime `createEnvironment()` / `removeEnvironment()` — remain exposed until the
|
|
109
|
-
lmdb-js issue is fixed upstream; staggered starts keep that window small.
|
|
101
|
+
Workers need no ports: coordination is the shared LMDB files + the bus. Placement and respawn
|
|
102
|
+
are your launcher's job (systemd, pm2, docker, k8s — anything that can start N processes).
|
|
103
|
+
|
|
104
|
+
**Starting several processes on a brand-new path** is safe: while a store is being initialised
|
|
105
|
+
(an env it opens has no data file yet), `open()` takes a cross-process boot lock, so first-opens
|
|
106
|
+
run one at a time. A dead or stale holder is taken over; a waiter that exceeds
|
|
107
|
+
`OKDB_BOOT_LOCK_TIMEOUT_MS` (default 60 000) logs a warning and proceeds. On an established store
|
|
108
|
+
the lock is not taken and processes open in parallel.
|
|
110
109
|
|
|
111
110
|
---
|
|
112
111
|
|
|
@@ -120,17 +119,22 @@ db.processors.start(); // begin participating: un-gate claiming, run the deferre
|
|
|
120
119
|
db.processors.stop(); // cease: finish in-flight quanta, release leases (peers fail over)
|
|
121
120
|
```
|
|
122
121
|
|
|
123
|
-
Both are idempotent and resolve `true` when the state actually changed
|
|
122
|
+
Both are idempotent and resolve `true` when the state actually changed (`db.processors.participating`
|
|
123
|
+
reads the current state). `stop()` never
|
|
124
124
|
touches reads, writes, or inline processors — the node stays a full read/write citizen.
|
|
125
125
|
|
|
126
126
|
**Fast startup** falls out of this: open without participating, start once your service is up.
|
|
127
127
|
|
|
128
128
|
```js
|
|
129
|
-
const
|
|
129
|
+
const http = require('node:http');
|
|
130
|
+
const db = new OKDB('./data', { processors: false });
|
|
130
131
|
await db.open(); // fast — no view boot, no FTS/TM drains competing with your startup
|
|
131
132
|
|
|
132
|
-
app.
|
|
133
|
+
const app = http.createServer((req, res) => res.end('ok'));
|
|
134
|
+
app.listen(0, async () => {
|
|
133
135
|
await db.processors.start(); // now begin claiming + draining
|
|
136
|
+
app.close();
|
|
137
|
+
await db.close();
|
|
134
138
|
});
|
|
135
139
|
```
|
|
136
140
|
|
|
@@ -159,13 +163,13 @@ through durable desired-state (applies across every process, no IPC):
|
|
|
159
163
|
- **`db.pressure()`** — the composite of those signals for THIS node (writer stall/depth, max
|
|
160
164
|
durable lag, queue backlog, loop lag, and a normalized `score`), cached 250 ms. Feed it to a
|
|
161
165
|
queue consumer's `admission` option (`() => db.pressure().score < 1`) for load-aware
|
|
162
|
-
consumption, or poll it from your orchestrator. See
|
|
166
|
+
consumption, or poll it from your orchestrator. See [Queue](./queue.md).
|
|
163
167
|
|
|
164
168
|
---
|
|
165
169
|
|
|
166
170
|
## Liveness guarantees (what you can rely on)
|
|
167
171
|
|
|
168
|
-
- Cross-process wakes ride the
|
|
172
|
+
- Cross-process wakes ride the bus; because it is lossy by design, every participating node also
|
|
169
173
|
runs an idle **catch-up tick** (`OKDB_PROCESSOR_CATCHUP_MS`, default 15 s) that drains any
|
|
170
174
|
backlog a lost poke left behind — a write from a short-lived process is picked up within
|
|
171
175
|
one tick, not "whenever the next write happens".
|