@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.
- package/CHANGELOG.md +114 -3
- package/README.md +72 -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 +79 -36
- package/docs/data-model.md +35 -9
- package/docs/deployment.md +42 -38
- package/docs/diagnostics.md +61 -125
- package/docs/embeddings.md +143 -51
- package/docs/encryption.md +132 -0
- package/docs/files.md +64 -27
- package/docs/fts.md +48 -23
- package/docs/functions.md +109 -56
- package/docs/getting-started.md +121 -9
- package/docs/http-api.md +66 -11
- package/docs/http-cluster.md +80 -88
- package/docs/index.md +33 -15
- package/docs/indexes.md +53 -17
- package/docs/licensing.md +19 -5
- package/docs/logging.md +11 -22
- package/docs/manifest.json +6 -3
- package/docs/migration.md +41 -16
- package/docs/pipelines.md +111 -46
- 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 +165 -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 +52 -14
- 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 +165 -61
- 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/public/features/files/parts/files-blob-status.ok.js +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/time-machine.md
CHANGED
|
@@ -6,12 +6,28 @@ Time Machine tracks the change history of individual documents. For each tracked
|
|
|
6
6
|
|
|
7
7
|
Time Machine works at the **type** level. You opt in a type for tracking; from that moment, writes to that type are recorded as diffs against the previous state. Tracking is non-blocking and asynchronous — a per-type `single` processor drains the change log after the fact (debounced by `flushDelayMs`, default 1000 ms), so writes are not slowed down. Because it drains the deduplicated change log in batches, several writes to the same key that land within one drain collapse into a single diff.
|
|
8
8
|
|
|
9
|
-
Time Machine is
|
|
9
|
+
Time Machine is a **licensed, opt-in constructor feature**: `env.timeMachine` exists only when the instance is constructed with `timeMachine` set (`true`, or an options object) **and** the active license includes the `timeMachine` feature (the free tier does not). Otherwise `env.timeMachine` is `undefined` and the HTTP routes answer 404 ("Time machine not available"). The `okdb` CLI server turns it on by default (set `"timeMachine": false` in the config file to disable). It is always skipped for `~`-prefixed system envs. See [licensing.md](./licensing.md).
|
|
10
|
+
|
|
11
|
+
On the free tier the option is accepted and ignored:
|
|
12
|
+
|
|
13
|
+
```js
|
|
14
|
+
const path = require('node:path');
|
|
15
|
+
|
|
16
|
+
const tmdb = new OKDB(path.join(__dirname, 'tm-store'), { timeMachine: true });
|
|
17
|
+
await tmdb.open();
|
|
18
|
+
tmdb.env('default').timeMachine; // → undefined without a timeMachine license
|
|
19
|
+
await tmdb.close();
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
With a license that includes it:
|
|
23
|
+
|
|
24
|
+
<!-- licensed: timeMachine -->
|
|
10
25
|
|
|
11
26
|
```js
|
|
12
27
|
const db = new OKDB('./mydb', { timeMachine: true }); // or { timeMachine: { flushDelayMs: 1000 } }
|
|
13
28
|
await db.open();
|
|
14
|
-
const env = db.env('
|
|
29
|
+
const env = db.env('default');
|
|
30
|
+
await db.registerType('Order');
|
|
15
31
|
|
|
16
32
|
// Enable tracking for a single type
|
|
17
33
|
await env.timeMachine.enable('Order');
|
|
@@ -24,6 +40,8 @@ await env.timeMachine.enableAll();
|
|
|
24
40
|
|
|
25
41
|
### Per-type control
|
|
26
42
|
|
|
43
|
+
<!-- continues -->
|
|
44
|
+
|
|
27
45
|
```js
|
|
28
46
|
await env.timeMachine.enable('Order'); // start tracking
|
|
29
47
|
await env.timeMachine.disable('Order'); // stop tracking, keep history
|
|
@@ -36,23 +54,36 @@ await env.timeMachine.drop('Order'); // stop tracking, delete all history
|
|
|
36
54
|
|
|
37
55
|
### Env-wide control
|
|
38
56
|
|
|
57
|
+
<!-- continues -->
|
|
58
|
+
|
|
39
59
|
```js
|
|
40
60
|
await env.timeMachine.enableAll(); // enable all registered types now + auto-enable future types
|
|
41
61
|
await env.timeMachine.disableAll(); // stop all tracking, clear auto-enable flag
|
|
42
62
|
```
|
|
43
63
|
|
|
44
|
-
When `enableAll()` is called, all types registered at that moment are enabled. Any type registered afterward is also automatically enabled
|
|
64
|
+
When `enableAll()` is called, all types registered at that moment are enabled. Any type registered afterward is also automatically enabled.
|
|
65
|
+
|
|
66
|
+
`await env.timeMachine.flush(type?)` drains pending changes now instead of waiting out `flushDelayMs` (useful in tests); `await env.timeMachine.dropAll()` drops every type's history.
|
|
45
67
|
|
|
46
68
|
## Querying history
|
|
47
69
|
|
|
48
70
|
### Full history for a key
|
|
49
71
|
|
|
72
|
+
<!-- continues -->
|
|
73
|
+
|
|
50
74
|
```js
|
|
75
|
+
await env.timeMachine.enable('Order');
|
|
76
|
+
await db.put('Order', 'order-42', { status: 'new', total: 10 });
|
|
77
|
+
await env.timeMachine.flush('Order'); // drain now instead of after flushDelayMs (writes in one drain collapse into one diff)
|
|
78
|
+
const someClock = env.getClock(); // the env change-log clock
|
|
79
|
+
await db.put('Order', 'order-42', { status: 'paid', total: 10 });
|
|
80
|
+
await env.timeMachine.flush('Order');
|
|
81
|
+
|
|
51
82
|
const { diffs, head } = env.timeMachine.getHistory('Order', 'order-42', {
|
|
52
83
|
limit: 50, // max entries, oldest first (optional)
|
|
53
|
-
maxClock: someClock, // only diffs at or before this clock (optional)
|
|
54
|
-
after: someClock, // only diffs after this clock (optional)
|
|
55
84
|
});
|
|
85
|
+
env.timeMachine.getHistory('Order', 'order-42', { maxClock: someClock }); // only diffs at or before this clock: the first
|
|
86
|
+
env.timeMachine.getHistory('Order', 'order-42', { after: someClock }); // only diffs after this clock: the second
|
|
56
87
|
// diffs: [{ clock, fromClock, timestamp, put: {...}, delete: [...] }, ...] (ascending by clock)
|
|
57
88
|
// head: { value, clock } — the latest tracked value, or null (deleted / never tracked)
|
|
58
89
|
```
|
|
@@ -69,14 +100,20 @@ Each diff entry describes what changed at that clock:
|
|
|
69
100
|
|
|
70
101
|
### Point-in-time reconstruction
|
|
71
102
|
|
|
103
|
+
<!-- continues -->
|
|
104
|
+
|
|
72
105
|
```js
|
|
73
|
-
const
|
|
106
|
+
const targetClock = diffs[0].clock;
|
|
107
|
+
const value = env.timeMachine.getStateAt('Order', 'order-42', targetClock); // → { status: 'new', total: 10 }
|
|
74
108
|
// Returns the document value as of `targetClock` (inclusive), or undefined if no diff exists at or before it
|
|
75
109
|
```
|
|
76
110
|
|
|
77
111
|
### Change log across types
|
|
78
112
|
|
|
113
|
+
<!-- continues -->
|
|
114
|
+
|
|
79
115
|
```js
|
|
116
|
+
const [fromClock, toClock] = [diffs[0].clock, head.clock];
|
|
80
117
|
const changes = [...env.timeMachine.getChanges('Order', fromClock, toClock)];
|
|
81
118
|
// Or all types:
|
|
82
119
|
const allChanges = [...env.timeMachine.getChanges(null, fromClock, toClock)];
|
|
@@ -85,6 +122,8 @@ const allChanges = [...env.timeMachine.getChanges(null, fromClock, toClock)];
|
|
|
85
122
|
|
|
86
123
|
## Inspecting status
|
|
87
124
|
|
|
125
|
+
<!-- continues -->
|
|
126
|
+
|
|
88
127
|
```js
|
|
89
128
|
// Per-type status
|
|
90
129
|
const status = env.timeMachine.status('Order');
|
|
@@ -121,6 +160,7 @@ env.timeMachine.list();
|
|
|
121
160
|
| POST | `/api/env/:env/time-machine/types/:type/enable` | Enable tracking |
|
|
122
161
|
| POST | `/api/env/:env/time-machine/types/:type/disable` | Disable tracking |
|
|
123
162
|
| POST | `/api/env/:env/time-machine/types/:type/drop` | Drop history |
|
|
163
|
+
| POST | `/api/env/:env/time-machine/types/:type/flush` | Drain pending now |
|
|
124
164
|
| POST | `/api/env/:env/time-machine/enable-all` | Enable all types |
|
|
125
165
|
| POST | `/api/env/:env/time-machine/disable-all` | Disable all types |
|
|
126
166
|
|
|
@@ -140,7 +180,7 @@ Query params for `/history`: `limit`, `before` (max clock, inclusive), `after` (
|
|
|
140
180
|
|
|
141
181
|
When a type has a registered schema with nested object properties, Time Machine records diffs at the path level rather than the field level. For example, if `User.address` is a nested object:
|
|
142
182
|
|
|
143
|
-
```
|
|
183
|
+
```text
|
|
144
184
|
// Before: { name: 'Alice', address: { city: 'NYC', zip: '10001' } }
|
|
145
185
|
// After: { name: 'Alice', address: { city: 'LA', zip: '10001' } }
|
|
146
186
|
|
|
@@ -151,18 +191,18 @@ When a type has a registered schema with nested object properties, Time Machine
|
|
|
151
191
|
|
|
152
192
|
## Storage
|
|
153
193
|
|
|
154
|
-
Time Machine stores data in a dedicated
|
|
194
|
+
Time Machine stores data in a dedicated store at `<env-path>/time-machine/` with four sub-databases:
|
|
155
195
|
|
|
156
196
|
- `head` — current snapshot of each tracked document (`[type, key]` → `{ value, clock }`)
|
|
157
|
-
- `diffs` —
|
|
197
|
+
- `diffs` — diffs keyed by `[type, key, clock]`
|
|
158
198
|
- `clockToKeys` — reverse index from clock to keys changed at that clock
|
|
159
199
|
- `config` — per-type enabled state, auto-enable flag, and migration metadata
|
|
160
200
|
|
|
161
|
-
|
|
201
|
+
Each type's processor cursor (its change-log watermark, see `getCursor(type)`) is stored with the env's other processor state, not in the time-machine store.
|
|
162
202
|
|
|
163
203
|
## Migration from the old per-env API
|
|
164
204
|
|
|
165
|
-
Before version 1.7, Time Machine was enabled env-wide with `env.timeMachine.enable()` / `env.timeMachine.disable()`.
|
|
205
|
+
Before version 1.7, Time Machine was enabled env-wide with `env.timeMachine.enable()` / `env.timeMachine.disable()`. That API is **deprecated**.
|
|
166
206
|
|
|
167
207
|
**What changed:**
|
|
168
208
|
|
|
@@ -178,6 +218,4 @@ Before version 1.7, Time Machine was enabled env-wide with `env.timeMachine.enab
|
|
|
178
218
|
|
|
179
219
|
**Automatic migration:** on first open after upgrading, OKDB detects the old per-env config and automatically migrates it to the per-type model. All previously tracked types are re-enabled with their history intact, and each type's processor cursor is set to the old global cursor value. This is one-shot and idempotent.
|
|
180
220
|
|
|
181
|
-
The deprecated no-arg forms (`enable()`, `disable()`, `drop()`) still work and log a deprecation warning once per process. They delegate to `enableAll()` / `disableAll()` / `dropAll()` respectively.
|
|
182
|
-
|
|
183
|
-
See `UPGRADING.md` for the full migration guide.
|
|
221
|
+
The deprecated no-arg forms (`enable()`, `disable()`, `drop()`) still work and log a deprecation warning once per process. They delegate to `enableAll()` / `disableAll()` / `dropAll()` respectively. The deprecated HTTP routes still answer, with `Deprecation` / `Sunset` headers.
|
package/docs/transactions.md
CHANGED
|
@@ -6,21 +6,24 @@ OKDB supports two write styles: single-operation writes (the default) and explic
|
|
|
6
6
|
|
|
7
7
|
## Single-operation writes
|
|
8
8
|
|
|
9
|
-
Each of these
|
|
9
|
+
Each of these is atomic on its own. Writes issued in the same event-loop turn are committed together in one LMDB write transaction (each write in its own nested transaction, so a failing write rejects alone), and each promise resolves once its write is durable:
|
|
10
10
|
|
|
11
11
|
```javascript
|
|
12
|
+
await okdb.registerType('orders');
|
|
12
13
|
await okdb.put('orders', 'o1', { item: 'widget', qty: 3, status: 'pending' });
|
|
13
14
|
await okdb.create('orders', 'o2', { item: 'gadget', qty: 1, status: 'pending' });
|
|
14
15
|
await okdb.update('orders', 'o1', { item: 'widget', qty: 5, status: 'pending' });
|
|
16
|
+
await okdb.patch('orders', 'o2', { set: { status: 'paid' }, inc: { qty: 1 } });
|
|
15
17
|
await okdb.remove('orders', 'o1');
|
|
16
18
|
```
|
|
17
19
|
|
|
18
|
-
| Method | Behaviour
|
|
19
|
-
| -------- |
|
|
20
|
-
| `put` | Upsert — create or overwrite
|
|
21
|
-
| `create` | Throws `OKDBAlreadyExistsError` if key exists
|
|
22
|
-
| `update` | Throws `OKDBNotFoundError` if key absent
|
|
23
|
-
| `
|
|
20
|
+
| Method | Behaviour |
|
|
21
|
+
| -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
22
|
+
| `put` | Upsert — create or overwrite |
|
|
23
|
+
| `create` | Throws `OKDBAlreadyExistsError` if key exists |
|
|
24
|
+
| `update` | Throws `OKDBNotFoundError` if key absent |
|
|
25
|
+
| `patch` | Applies a patch document (`set`, `unset`, `inc`, `merge`, `append`, `pull`) to an existing object record; throws `OKDBNotFoundError` if key absent |
|
|
26
|
+
| `remove` | Throws `OKDBNotFoundError` if key absent |
|
|
24
27
|
|
|
25
28
|
---
|
|
26
29
|
|
|
@@ -29,6 +32,9 @@ await okdb.remove('orders', 'o1');
|
|
|
29
32
|
When you need multiple operations to succeed or fail together, use `okdb.transaction()`:
|
|
30
33
|
|
|
31
34
|
```javascript
|
|
35
|
+
await okdb.registerType('accounts');
|
|
36
|
+
await okdb.registerType('transfers');
|
|
37
|
+
|
|
32
38
|
const txn = okdb.transaction();
|
|
33
39
|
|
|
34
40
|
txn.put('accounts', 'alice', { balance: 900 });
|
|
@@ -40,13 +46,40 @@ await txn.commit(); // all three land in one LMDB write transaction
|
|
|
40
46
|
|
|
41
47
|
Rollback (discard without writing):
|
|
42
48
|
|
|
49
|
+
<!-- continues -->
|
|
50
|
+
|
|
51
|
+
```javascript
|
|
52
|
+
const draft = okdb.transaction();
|
|
53
|
+
draft.put('accounts', 'carol', { balance: 0 });
|
|
54
|
+
draft.rollback(); // nothing is written; the transaction is closed
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
A transaction also accepts `setTTL(type, key, ms)` / `clearTTL(type, key)` and has read methods (`get`, `getEntry`, `getMany`, `getRange`, `getKeys`, `getValues`, `byIndex`, `query`, `getClock`, `getCount`). The reads see committed state only — writes queued in the transaction are not visible to them.
|
|
58
|
+
|
|
59
|
+
### `txn(work)`
|
|
60
|
+
|
|
61
|
+
`okdb.txn()` (and `env.txn()`) builds, commits and returns in one call. Pass an async function that queues writes on the handle, or an array of operations; if the function throws, nothing is written:
|
|
62
|
+
|
|
63
|
+
<!-- continues -->
|
|
64
|
+
|
|
43
65
|
```javascript
|
|
44
|
-
txn
|
|
66
|
+
const result = await okdb.txn(async (t) => {
|
|
67
|
+
const alice = t.get('accounts', 'alice');
|
|
68
|
+
t.put('accounts', 'alice', { balance: alice.balance - 50 });
|
|
69
|
+
t.put('accounts', 'bob', { balance: 1150 });
|
|
70
|
+
});
|
|
71
|
+
// result = { id: '…', actions: 2 }
|
|
72
|
+
|
|
73
|
+
// Operation-array form: objects or [action, ...args] tuples
|
|
74
|
+
await okdb.txn([
|
|
75
|
+
{ action: 'put', type: 'accounts', key: 'dave', value: { balance: 10 } },
|
|
76
|
+
['remove', 'accounts', 'dave'],
|
|
77
|
+
]);
|
|
45
78
|
```
|
|
46
79
|
|
|
47
80
|
### How it works
|
|
48
81
|
|
|
49
|
-
`OKDBTransaction` accumulates operations in memory. On `commit()`, it replays them all inside a single LMDB write transaction
|
|
82
|
+
`OKDBTransaction` accumulates operations in memory. On `commit()`, it replays them all inside a single LMDB write transaction. Every secondary index update and change-log entry for all operations is written atomically in that one transaction — there is no partial state. If any operation fails, the whole transaction is aborted and `commit()` rejects.
|
|
50
83
|
|
|
51
84
|
---
|
|
52
85
|
|
|
@@ -55,9 +88,12 @@ txn.rollback();
|
|
|
55
88
|
Guard writes with a version check using `ifVersion`:
|
|
56
89
|
|
|
57
90
|
```javascript
|
|
91
|
+
await okdb.registerType('products');
|
|
92
|
+
await okdb.put('products', 'p42', { name: 'Widget', stock: 10 });
|
|
93
|
+
|
|
58
94
|
// Read the current version
|
|
59
95
|
const entry = okdb.getEntry('products', 'p42');
|
|
60
|
-
// entry.version =
|
|
96
|
+
// entry.version = 1
|
|
61
97
|
|
|
62
98
|
// Only write if the record hasn't changed since we read it
|
|
63
99
|
await okdb.put(
|
|
@@ -74,10 +110,13 @@ This is a classic compare-and-swap. If another writer modified the record betwee
|
|
|
74
110
|
|
|
75
111
|
In a batch transaction:
|
|
76
112
|
|
|
113
|
+
<!-- continues -->
|
|
114
|
+
|
|
77
115
|
```javascript
|
|
116
|
+
const current = okdb.getEntry('products', 'p42');
|
|
78
117
|
const txn = okdb.transaction();
|
|
79
|
-
txn.put('products', 'p42',
|
|
80
|
-
txn.put('products', 'p43',
|
|
118
|
+
txn.put('products', 'p42', { ...current.value, stock: 0 }, { ifVersion: current.version });
|
|
119
|
+
txn.put('products', 'p43', { name: 'Gadget', stock: 5 });
|
|
81
120
|
await txn.commit(); // both succeed or both fail
|
|
82
121
|
```
|
|
83
122
|
|
|
@@ -98,8 +137,12 @@ All errors extend `OKDBError` and carry a `code` property. The error classes are
|
|
|
98
137
|
from the package — branch on `err.code`:
|
|
99
138
|
|
|
100
139
|
```javascript
|
|
140
|
+
await okdb.registerType('products');
|
|
141
|
+
await okdb.put('products', 'p42', { stock: 1 });
|
|
142
|
+
await okdb.put('products', 'p42', { stock: 2 }); // version is now 2
|
|
143
|
+
|
|
101
144
|
try {
|
|
102
|
-
await okdb.put('products', 'p42',
|
|
145
|
+
await okdb.put('products', 'p42', { stock: 3 }, { ifVersion: 1 });
|
|
103
146
|
} catch (err) {
|
|
104
147
|
if (err.code === 'VERSION_MISMATCH') {
|
|
105
148
|
// retry logic
|
|
@@ -150,6 +193,8 @@ nothing is written.
|
|
|
150
193
|
|
|
151
194
|
Every write accepts a `timestamp` and `origin` option used by the sync system:
|
|
152
195
|
|
|
196
|
+
<!-- not-runnable: shape of the sync-internal write options; origin must be a real node id -->
|
|
197
|
+
|
|
153
198
|
```javascript
|
|
154
199
|
await okdb.put('items', 'i1', value, {
|
|
155
200
|
timestamp: Date.now(), // used for LWW conflict resolution
|
|
@@ -163,7 +208,7 @@ You rarely need to set these manually — they are used internally by the sync f
|
|
|
163
208
|
|
|
164
209
|
## What's atomic
|
|
165
210
|
|
|
166
|
-
Everything that happens inside a single `db.transaction()`
|
|
211
|
+
Everything that happens inside a single `db.transaction()` commit (or a single write) is atomic:
|
|
167
212
|
|
|
168
213
|
1. Primary data written to `type:T:data`
|
|
169
214
|
2. All secondary index entries updated (`type:T:index:I` sub-dbs)
|
|
@@ -171,7 +216,7 @@ Everything that happens inside a single `db.transaction()` call is atomic:
|
|
|
171
216
|
|
|
172
217
|
No partial state is ever visible. If the process crashes mid-write, LMDB rolls back the transaction on the next open.
|
|
173
218
|
|
|
174
|
-
Post-commit events (`item:create`, `system:clock_change`, etc.) fire **after** the LMDB transaction has
|
|
219
|
+
Post-commit events (`item:create`, `system:clock_change`, etc.) fire **after** the LMDB transaction has committed — never speculatively.
|
|
175
220
|
|
|
176
221
|
---
|
|
177
222
|
|
|
@@ -182,6 +227,9 @@ FTS writes are **always async** — the FTS index is updated by a background pro
|
|
|
182
227
|
For applications that require read-your-writes consistency after a write, use `fts.flush(type)`:
|
|
183
228
|
|
|
184
229
|
```javascript
|
|
230
|
+
await okdb.registerType('articles');
|
|
231
|
+
await okdb.fts.register('articles', 'main', { fields: ['title'] });
|
|
232
|
+
|
|
185
233
|
await okdb.put('articles', 'a1', { title: 'Hello world' });
|
|
186
234
|
await okdb.fts.flush('articles'); // wait for processor to index the write
|
|
187
235
|
const results = okdb.fts.search('articles', 'main', 'hello'); // guaranteed to include a1
|
package/docs/ttl.md
CHANGED
|
@@ -23,6 +23,8 @@ const ttl = db.getTTL('sessions', 's1');
|
|
|
23
23
|
|
|
24
24
|
// Make the item permanent again
|
|
25
25
|
await db.clearTTL('sessions', 's1');
|
|
26
|
+
|
|
27
|
+
await db.close();
|
|
26
28
|
```
|
|
27
29
|
|
|
28
30
|
---
|
|
@@ -45,6 +47,8 @@ Sets a TTL on an existing item. The item will be eligible for removal after `ttl
|
|
|
45
47
|
- `OKDBInvalidValueError` if `ttlMs` is not a positive number
|
|
46
48
|
|
|
47
49
|
```javascript
|
|
50
|
+
await db.registerType('cache');
|
|
51
|
+
await db.put('cache', 'page:/home', '<html>…</html>');
|
|
48
52
|
await db.setTTL('cache', 'page:/home', 60_000); // expire in 1 minute
|
|
49
53
|
```
|
|
50
54
|
|
|
@@ -53,15 +57,18 @@ Calling `setTTL` on an item that already has a TTL replaces the previous expirat
|
|
|
53
57
|
A TTL can also be given at write time — `put` / `update` / `patch` / `create` accept a `ttl`
|
|
54
58
|
option (ms):
|
|
55
59
|
|
|
60
|
+
<!-- continues -->
|
|
61
|
+
|
|
56
62
|
```javascript
|
|
63
|
+
const html = '<html>…</html>';
|
|
57
64
|
await db.put('cache', 'page:/home', html, { ttl: 60_000 });
|
|
58
65
|
```
|
|
59
66
|
|
|
60
67
|
### `setDefaultTTL(type, ttlMs)` / `getDefaultTTL(type)` / `clearDefaultTTL(type)`
|
|
61
68
|
|
|
62
69
|
A per-type default TTL, applied to items **created** in that type without an explicit `ttl`
|
|
63
|
-
(updates of an existing item do not re-apply it). Available on
|
|
64
|
-
(`db.env('default').setDefaultTTL('sessions', 30 * 60 * 1000)`).
|
|
70
|
+
(updates of an existing item do not re-apply it). Available on `db` (default env) and on any env
|
|
71
|
+
(`db.env('default').setDefaultTTL('sessions', 30 * 60 * 1000)`). `getDefaultTTL(type)` returns the ms value or `null`.
|
|
65
72
|
|
|
66
73
|
### `getTTL(type, key)`
|
|
67
74
|
|
|
@@ -79,6 +86,8 @@ Returns the TTL info for an item, or `null` if no TTL is set.
|
|
|
79
86
|
|
|
80
87
|
`getTTL` throws `OKDBTypeNotRegisteredError` for an unknown type.
|
|
81
88
|
|
|
89
|
+
<!-- continues -->
|
|
90
|
+
|
|
82
91
|
```javascript
|
|
83
92
|
const ttl = db.getTTL('cache', 'page:/home');
|
|
84
93
|
if (ttl && ttl.remainingMs < 5000) {
|
|
@@ -91,6 +100,9 @@ if (ttl && ttl.remainingMs < 5000) {
|
|
|
91
100
|
Removes the TTL from an item, making it permanent. The item itself is not deleted.
|
|
92
101
|
|
|
93
102
|
```javascript
|
|
103
|
+
await db.registerType('sessions');
|
|
104
|
+
await db.put('sessions', 's1', { user: 'alice' }, { ttl: 60_000 });
|
|
105
|
+
|
|
94
106
|
await db.clearTTL('sessions', 's1');
|
|
95
107
|
```
|
|
96
108
|
|
|
@@ -98,9 +110,9 @@ await db.clearTTL('sessions', 's1');
|
|
|
98
110
|
|
|
99
111
|
Manually triggers a sweep of all expired items across all types.
|
|
100
112
|
|
|
101
|
-
| Parameter | Type | Default | Description
|
|
102
|
-
| ----------- | -------- | ------- |
|
|
103
|
-
| `batchSize` | `number` | `1000` | Max items to remove
|
|
113
|
+
| Parameter | Type | Default | Description |
|
|
114
|
+
| ----------- | -------- | ------- | --------------------------------------------- |
|
|
115
|
+
| `batchSize` | `number` | `1000` | Max items to remove in this sweep (all types) |
|
|
104
116
|
|
|
105
117
|
**Returns:** `{ removed: number, types: { [typeName]: number } }`
|
|
106
118
|
|
|
@@ -214,6 +226,8 @@ reading.
|
|
|
214
226
|
TTL operations can be included in batch transactions for atomic create-and-expire patterns:
|
|
215
227
|
|
|
216
228
|
```javascript
|
|
229
|
+
await db.registerType('sessions');
|
|
230
|
+
|
|
217
231
|
const txn = db.transaction();
|
|
218
232
|
|
|
219
233
|
txn.put('sessions', 's1', { user: 'alice', token: 'abc123' });
|
|
@@ -228,6 +242,8 @@ await txn.commit(); // both items and their TTLs set atomically
|
|
|
228
242
|
Also works with the `txn()` helper:
|
|
229
243
|
|
|
230
244
|
```javascript
|
|
245
|
+
await db.registerType('cache');
|
|
246
|
+
|
|
231
247
|
await db.txn(async (t) => {
|
|
232
248
|
t.put('cache', 'k1', { data: 'hello' });
|
|
233
249
|
t.setTTL('cache', 'k1', 30_000);
|
|
@@ -237,6 +253,9 @@ await db.txn(async (t) => {
|
|
|
237
253
|
Clear TTL within a transaction:
|
|
238
254
|
|
|
239
255
|
```javascript
|
|
256
|
+
await db.registerType('sessions');
|
|
257
|
+
await db.put('sessions', 's1', { user: 'alice' }, { ttl: 60_000 });
|
|
258
|
+
|
|
240
259
|
const txn = db.transaction();
|
|
241
260
|
txn.clearTTL('sessions', 's1');
|
|
242
261
|
await txn.commit();
|
|
@@ -378,16 +397,18 @@ await analytics.setTTL('events', 'e1', 86_400_000); // 24h — swept by analytic
|
|
|
378
397
|
|
|
379
398
|
## Stored Functions
|
|
380
399
|
|
|
381
|
-
TTL methods are available
|
|
400
|
+
TTL methods are available on the stored function's `ctx.env` facade (and on its `txn(...)` handle: `setTTL` / `clearTTL`):
|
|
382
401
|
|
|
383
402
|
```javascript
|
|
384
|
-
//
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
await
|
|
390
|
-
|
|
403
|
+
// A stored function body
|
|
404
|
+
const handler = async (ctx) => {
|
|
405
|
+
const key = ctx.payload.key;
|
|
406
|
+
await ctx.env.setTTL('sessions', key, 30 * 60 * 1000);
|
|
407
|
+
const ttl = ctx.env.getTTL('sessions', key);
|
|
408
|
+
await ctx.env.clearTTL('sessions', key);
|
|
409
|
+
await ctx.env.sweepExpiredTTL();
|
|
410
|
+
return ttl;
|
|
411
|
+
};
|
|
391
412
|
```
|
|
392
413
|
|
|
393
414
|
---
|
package/docs/upgrade-2.0.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Upgrading to okdb 2.0
|
|
2
2
|
|
|
3
|
+
> **History.** This page describes the 1.9 → 2.0 upgrade. okdb 3.0 kept the 2.0 runtime model and
|
|
4
|
+
> these APIs (removed options still throw the same codes); where this page describes 2.x
|
|
5
|
+
> internals (the JS writer, lmdb-js, the shmbuf package, Node `cluster`), 3.0's native core does the
|
|
6
|
+
> same job differently. For moving from 2.x to 3.0 see [Upgrading to 3.0](upgrade-3.0.md).
|
|
7
|
+
|
|
3
8
|
okdb 2.0 is a **breaking redesign of the runtime model**. The document model, storage
|
|
4
9
|
formats, HLC, sync wire protocol, and query/index APIs are **unchanged** — your data and
|
|
5
10
|
your read/write code keep working as-is. What changed is **how a process declares the work
|
|
@@ -8,7 +13,7 @@ it does**.
|
|
|
8
13
|
> **The one-sentence shift.** okdb stops being a runtime _orchestrator_ (a managed,
|
|
9
14
|
> auto-scaled "worker population") and becomes a _substrate_: **the process is the control
|
|
10
15
|
> unit**, it **declares** what it runs (it is never told by a supervisor), the per-`(env,type)`
|
|
11
|
-
> lease is the load balancer, and **spawning/placement is the launcher's job** — `
|
|
16
|
+
> lease is the load balancer, and **spawning/placement is the launcher's job** — the `okdb` CLI,
|
|
12
17
|
> systemd/k8s, or your own code. `new OKDB(path)` is still a correct, do-everything
|
|
13
18
|
> single-process node; you only add nodes when you decide you need them.
|
|
14
19
|
|
|
@@ -23,6 +28,8 @@ constructor options and a few cluster/worker APIs.
|
|
|
23
28
|
The constructor declares **what role a node plays**. Every _mechanism_ that used to be a flag
|
|
24
29
|
is now **derived** — okdb turns it on the moment it's needed.
|
|
25
30
|
|
|
31
|
+
<!-- not-runnable: a shape/signature fragment -->
|
|
32
|
+
|
|
26
33
|
```js
|
|
27
34
|
new OKDB(path, {
|
|
28
35
|
processors: true | false, // does this node participate in processing? (claim leases + drain)
|
|
@@ -71,6 +78,7 @@ covered by that consumer's normal bootstrap (snapshot scan + replay tail).
|
|
|
71
78
|
A node either **participates** in processing or it doesn't. That's the whole control surface.
|
|
72
79
|
|
|
73
80
|
```js
|
|
81
|
+
const path = './data';
|
|
74
82
|
new OKDB(path, { processors: true }); // participate: claim every unclaimed `single` lease (default)
|
|
75
83
|
new OKDB(path, { processors: false }); // passive: claim nothing (reads/writes + inline still work)
|
|
76
84
|
```
|
|
@@ -120,7 +128,7 @@ There is exactly **one** execution model, and it is the simple one:
|
|
|
120
128
|
|
|
121
129
|
**Ephemeral nodes** (CLI one-shots, serverless, short-lived scripts) should pass
|
|
122
130
|
`processors: false`: a process that grabs a 1-of-N lease and exits mid-quantum would thrash it.
|
|
123
|
-
`
|
|
131
|
+
The `okdb` CLI's one-shot subcommands already open passive.
|
|
124
132
|
|
|
125
133
|
---
|
|
126
134
|
|
|
@@ -129,12 +137,12 @@ There is exactly **one** execution model, and it is the simple one:
|
|
|
129
137
|
There is **no managed worker population** in 2.0. A "worker" was only ever a process that
|
|
130
138
|
opened the root and claimed processors.
|
|
131
139
|
|
|
132
|
-
| 1.9 | 2.0
|
|
133
|
-
| --------------------------------------------- |
|
|
134
|
-
| `db.workers.ensure({ scale })` | **throws `WORKERS_REMOVED`.** Fork your own nodes: `new OKDB(path, { processors: true })`.
|
|
135
|
-
| `db.workers.destroy()` | **throws `WORKERS_REMOVED`.**
|
|
136
|
-
| autoscaler / desired-state / supervisor | gone from the library; survives only
|
|
137
|
-
| `GET /api/workers`, `POST /api/workers/scale` | **410 `WORKERS_REMOVED`.**
|
|
140
|
+
| 1.9 | 2.0 |
|
|
141
|
+
| --------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
|
142
|
+
| `db.workers.ensure({ scale })` | **throws `WORKERS_REMOVED`.** Fork your own nodes: `new OKDB(path, { processors: true })`. |
|
|
143
|
+
| `db.workers.destroy()` | **throws `WORKERS_REMOVED`.** |
|
|
144
|
+
| autoscaler / desired-state / supervisor | gone from the library; survives only inside the **`okdb` CLI** launcher (the reference launcher). |
|
|
145
|
+
| `GET /api/workers`, `POST /api/workers/scale` | **410 `WORKERS_REMOVED`.** |
|
|
138
146
|
|
|
139
147
|
**To run a multi-process processing tier:** start more nodes over the same path — a plain
|
|
140
148
|
`new OKDB(path, { processors: true })` in a process you launch (pm2, systemd, docker, k8s, or
|
|
@@ -154,7 +162,7 @@ A library node **never forks**. The embeddable child-entry clustering API is rem
|
|
|
154
162
|
| 1.9 | 2.0 |
|
|
155
163
|
| ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
156
164
|
| `http.listen(port, { workers, makeOkdb, primaryOkdb })` | **throws `HTTP_CLUSTER_REMOVED`.** |
|
|
157
|
-
| `
|
|
165
|
+
| `okdb` CLI HTTP cluster | **N identical capable nodes** — each forked worker serves HTTP **and** processes (claims leases, drains on its own loop). No privileged processor; the Node-cluster primary is a thin **passive supervisor** (seeds the shared token secret, owns the registry). A dead worker's claims fail over to the rest. |
|
|
158
166
|
| embedder wants socket-sharing | use plain Node `cluster` yourself — a cluster worker calling `http.listen(port)` shares the socket natively, no okdb involvement. Or run **N independent `new OKDB(path)` full nodes** behind your balancer (same "N capable nodes" shape; they coordinate via the shared LMDB + bus + the 1-of-N lease). |
|
|
159
167
|
|
|
160
168
|
`http.listen(port)` (single-process) is **unchanged** and still returns a plain `http.Server`.
|
|
@@ -199,17 +207,26 @@ Bare closures passed as `handler` to `processor.register()` are no longer accept
|
|
|
199
207
|
- **Named handler** (built-in, resolved at runtime):
|
|
200
208
|
|
|
201
209
|
```js
|
|
202
|
-
// Register once at feature-load time:
|
|
203
|
-
|
|
210
|
+
// Register once at feature-load time (the processor class is env.processor.constructor):
|
|
211
|
+
env.processor.constructor.registerHandler('my:handler', async (ctx, changes, info) => {});
|
|
204
212
|
|
|
205
213
|
// Then register the processor:
|
|
206
|
-
env.
|
|
214
|
+
await env.registerType('MyType');
|
|
215
|
+
env.processor.register('MyType', {
|
|
216
|
+
handler: 'my:handler',
|
|
217
|
+
mode: 'async',
|
|
218
|
+
distribution: 'single',
|
|
219
|
+
cursorKey: 'my:key',
|
|
220
|
+
});
|
|
207
221
|
```
|
|
208
222
|
|
|
209
223
|
- **Module reference** (external file, resolved via `require`):
|
|
210
224
|
```js
|
|
225
|
+
// ./my-handler.js: exports.apply = async (ctx, changes, info) => { ... };
|
|
226
|
+
require('node:fs').writeFileSync('my-handler.js', 'exports.apply = async () => {};');
|
|
227
|
+
await env.registerType('MyType');
|
|
211
228
|
env.processor.register('MyType', {
|
|
212
|
-
module: { path: require.resolve('
|
|
229
|
+
module: { path: require('node:path').resolve('my-handler.js'), export: 'apply' },
|
|
213
230
|
mode: 'async',
|
|
214
231
|
distribution: 'single',
|
|
215
232
|
cursorKey: 'my:key',
|
|
@@ -283,8 +300,8 @@ processEverything()`) with the boolean `processors: true|false`. Place a process
|
|
|
283
300
|
3. Replace `queue.worker(type, module)` or `queue.spawn(type, module)` with `queue.process(type, fn)`
|
|
284
301
|
(in-loop), or run a consumer on another independent process/node.
|
|
285
302
|
4. Replace `db.workers.ensure({scale})` with launching extra `new OKDB(path, { processors: true })`
|
|
286
|
-
nodes (or let `
|
|
287
|
-
5. Replace any `http.listen(port, { workers })` with `
|
|
303
|
+
nodes (or let the `okdb` CLI do it). Use `processors: false` for short-lived/ephemeral processes.
|
|
304
|
+
5. Replace any `http.listen(port, { workers })` with `okdb` CLI clustering or plain Node `cluster`.
|
|
288
305
|
6. Drop `sync: false` on environments — a pure local store simply never attaches a consumer.
|
|
289
306
|
7. If you scraped `/api/workers`, read the registry-sourced `/api/processes/tree` +
|
|
290
307
|
`/api/processors/status` instead.
|
package/docs/upgrade-2.1.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# Upgrading to okdb 2.1 — the safe-range contract
|
|
2
2
|
|
|
3
|
+
> **History.** This page describes a 2.x-era upgrade. okdb 3.0 keeps the safe-range contract and
|
|
4
|
+
> these APIs unchanged (including `READER_HELD_ACROSS_AWAIT` and the `'tolerant'` modes); for moving
|
|
5
|
+
> from 2.x to 3.0 see [Upgrading to 3.0](upgrade-3.0.md).
|
|
6
|
+
|
|
3
7
|
okdb 2.1 fixes the **env-size balloon**: LMDB data files growing far past their live data
|
|
4
8
|
until a compaction rescued them. Storage formats, the document model, and all APIs are
|
|
5
9
|
**unchanged**, and **default-path code needs no changes at all** — including loops that
|
|
@@ -19,8 +23,7 @@ recycled only when **no reader in any process** still holds an older snapshot. A
|
|
|
19
23
|
range cursor held across an `await` blocks free-page reuse for the _entire_ env while
|
|
20
24
|
writes churn, and the file grows by _pages-dirtied-per-commit × commit count_ (≈24 KB
|
|
21
25
|
floor per commit) — completely decoupled from ingestion volume. One parked iterator plus
|
|
22
|
-
background churn = gigabytes.
|
|
23
|
-
`repro/reader-balloon-amplify.js`.
|
|
26
|
+
background churn = gigabytes.
|
|
24
27
|
|
|
25
28
|
## What each surface does now
|
|
26
29
|
|
|
@@ -36,7 +39,11 @@ background churn = gigabytes. Reproduced and measured in `repro/reader-balloon.j
|
|
|
36
39
|
If you hit the error, the fix is one line — materialize before the `await`:
|
|
37
40
|
|
|
38
41
|
```js
|
|
39
|
-
|
|
42
|
+
await env.ensureType('orders', { indexes: [['status']] });
|
|
43
|
+
await env.put('orders', 'o1', { status: 'open' });
|
|
44
|
+
const handle = async (order) => {};
|
|
45
|
+
|
|
46
|
+
for (const { value } of Array.from(env.byIndex('orders', ['status'], { prefix: ['open'] }))) {
|
|
40
47
|
await handle(value);
|
|
41
48
|
}
|
|
42
49
|
```
|
|
@@ -63,12 +70,3 @@ The renewable default and the guards live in the upgraded process. A **2.0.x pee
|
|
|
63
70
|
the same store path can still pin** shared envs the old way until it is upgraded — the
|
|
64
71
|
process-registry mixed-build warning tells you when a fleet is split. Upgrade all
|
|
65
72
|
processes on a path.
|
|
66
|
-
|
|
67
|
-
## History worth keeping (internal)
|
|
68
|
-
|
|
69
|
-
An earlier build shipped the renewable default and **segfaulted** — root cause was okdb's
|
|
70
|
-
_own_ boot loops holding renewable cursors across awaits into env close/rebuild windows.
|
|
71
|
-
Seven internal sites were fixed (materialized or chunked; the boot env-registry loop had
|
|
72
|
-
been pinning `~system` for the entire multi-env open). Internal scans must stay
|
|
73
|
-
synchronous or chunked; `tests/getrange-snapshot-default.test.js` keeps the crash shape
|
|
74
|
-
(env close with a held renewable iterator) permanently covered.
|