@kedem/okdb 2.3.4 → 2.4.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 +366 -0
- package/algorithm-worker-thread.js +1 -1
- package/bin/okdb.js +1 -1
- package/docs/auth-and-sync.md +28 -4
- package/docs/auth-permissions.md +19 -6
- package/docs/change-log.md +79 -59
- package/docs/data-model.md +20 -18
- package/docs/deployment.md +25 -0
- package/docs/diagnostics.md +59 -17
- package/docs/embeddings.md +57 -6
- package/docs/files.md +1 -1
- package/docs/fts.md +50 -5
- package/docs/functions.md +21 -8
- package/docs/http-api.md +139 -98
- package/docs/http-cluster.md +30 -8
- package/docs/indexes.md +5 -4
- package/docs/logging.md +18 -0
- package/docs/migration.md +94 -2
- package/docs/pipelines.md +6 -1
- package/docs/plugins.md +12 -18
- package/docs/process-registry.md +50 -39
- package/docs/processors.md +40 -22
- package/docs/querying.md +50 -36
- package/docs/queue.md +110 -14
- package/docs/subscriptions.md +35 -24
- package/docs/sync.md +96 -37
- package/docs/time-machine.md +23 -17
- package/docs/transactions.md +11 -19
- package/docs/ttl.md +118 -67
- package/docs/upgrade-2.0.md +2 -2
- package/docs/views.md +71 -52
- package/okdb-functions-sandbox-worker.js +1 -1
- package/okdb-http-worker-child.js +1 -1
- package/okdb-views-bootstrap-worker.js +1 -1
- package/okdb.js +1 -1
- package/package.json +1 -1
- package/public/sections/db/parts/type-viewer.ok.js +1 -1
- package/public/sections/embeddings/parts/engines-overview.ok.js +1 -1
- package/public/sections/queue/parts/queue-jobs.ok.js +1 -1
- package/public/sections/system/modals/data-ops-modal.ok.js +1 -1
- package/types/environment.d.ts +320 -52
- package/types/features/admin.d.ts +8 -2
- package/types/features/api.d.ts +10 -16
- package/types/features/auth.d.ts +135 -16
- package/types/features/embeddings.d.ts +639 -31
- package/types/features/engines.d.ts +368 -14
- package/types/features/files.d.ts +2 -4
- package/types/features/fts.d.ts +98 -26
- package/types/features/functions.d.ts +175 -15
- package/types/features/mcp.d.ts +23 -10
- package/types/features/pipelines.d.ts +268 -9
- package/types/features/queue.d.ts +230 -34
- package/types/features/sync.d.ts +177 -14
- package/types/features/time-machine.d.ts +117 -16
- package/types/features/views.d.ts +230 -39
- package/types/index.d.ts +357 -254
- package/types/okdb.d.ts +377 -0
- package/types/options.d.ts +309 -48
- package/public/test-cron-input.html +0 -60
- package/public/test-json-input.html +0 -280
package/docs/ttl.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# TTL (Time-to-Live)
|
|
2
2
|
|
|
3
|
-
OKDB supports per-record TTL — set an expiration on any item and it will be automatically removed after the specified duration.
|
|
3
|
+
OKDB supports per-record TTL — set an expiration on any item and it will be automatically removed after the specified duration. Removal is done by a sweep, not at read time — see [Expired but not yet swept](#expired-but-not-yet-swept).
|
|
4
4
|
|
|
5
5
|
---
|
|
6
6
|
|
|
@@ -50,6 +50,19 @@ await db.setTTL('cache', 'page:/home', 60_000); // expire in 1 minute
|
|
|
50
50
|
|
|
51
51
|
Calling `setTTL` on an item that already has a TTL replaces the previous expiration.
|
|
52
52
|
|
|
53
|
+
A TTL can also be given at write time — `put` / `update` / `patch` / `create` accept a `ttl`
|
|
54
|
+
option (ms):
|
|
55
|
+
|
|
56
|
+
```javascript
|
|
57
|
+
await db.put('cache', 'page:/home', html, { ttl: 60_000 });
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### `setDefaultTTL(type, ttlMs)` / `getDefaultTTL(type)` / `clearDefaultTTL(type)`
|
|
61
|
+
|
|
62
|
+
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 an env
|
|
64
|
+
(`db.env('default').setDefaultTTL('sessions', 30 * 60 * 1000)`).
|
|
65
|
+
|
|
53
66
|
### `getTTL(type, key)`
|
|
54
67
|
|
|
55
68
|
Returns the TTL info for an item, or `null` if no TTL is set.
|
|
@@ -64,6 +77,8 @@ Returns the TTL info for an item, or `null` if no TTL is set.
|
|
|
64
77
|
- `expiresAt` — absolute Unix timestamp (ms) when the item expires
|
|
65
78
|
- `remainingMs` — milliseconds until expiration (0 if already expired but not yet swept)
|
|
66
79
|
|
|
80
|
+
`getTTL` throws `OKDBTypeNotRegisteredError` for an unknown type.
|
|
81
|
+
|
|
67
82
|
```javascript
|
|
68
83
|
const ttl = db.getTTL('cache', 'page:/home');
|
|
69
84
|
if (ttl && ttl.remainingMs < 5000) {
|
|
@@ -97,7 +112,7 @@ console.log(`Removed ${result.removed} expired items`);
|
|
|
97
112
|
|
|
98
113
|
### `ttlStats(type?)`
|
|
99
114
|
|
|
100
|
-
Returns aggregate TTL statistics for the default environment, optionally filtered to a single type.
|
|
115
|
+
Returns aggregate TTL statistics for the default environment (`env.ttlStats()` for any other), optionally filtered to a single type.
|
|
101
116
|
|
|
102
117
|
| Parameter | Type | Description |
|
|
103
118
|
| --------- | -------- | ------------------------------------------ |
|
|
@@ -105,13 +120,13 @@ Returns aggregate TTL statistics for the default environment, optionally filtere
|
|
|
105
120
|
|
|
106
121
|
**Returns:** `{ enabled, totalEntries, expiredEntries, nextExpiry, byType }`
|
|
107
122
|
|
|
108
|
-
| Field | Type | Description
|
|
109
|
-
| ---------------- | -------------- |
|
|
110
|
-
| `enabled` | `boolean` | Whether
|
|
111
|
-
| `totalEntries` | `number` | Total number of TTL entries
|
|
112
|
-
| `expiredEntries` | `number` | Entries that have already expired but not yet swept
|
|
113
|
-
| `nextExpiry` | `number\|null` |
|
|
114
|
-
| `byType` | `object` | `{ [typeName]: count }` breakdown
|
|
123
|
+
| Field | Type | Description |
|
|
124
|
+
| ---------------- | -------------- | ---------------------------------------------------- |
|
|
125
|
+
| `enabled` | `boolean` | Whether the env's TTL sub-databases exist |
|
|
126
|
+
| `totalEntries` | `number` | Total number of TTL entries |
|
|
127
|
+
| `expiredEntries` | `number` | Entries that have already expired but not yet swept |
|
|
128
|
+
| `nextExpiry` | `number\|null` | This process's cached soonest expiry (ms), or `null` |
|
|
129
|
+
| `byType` | `object` | `{ [typeName]: count }` breakdown |
|
|
115
130
|
|
|
116
131
|
```javascript
|
|
117
132
|
const stats = db.ttlStats();
|
|
@@ -126,51 +141,71 @@ const sessionStats = db.ttlStats('sessions');
|
|
|
126
141
|
|
|
127
142
|
Lists all TTL entries sorted by expiry time (soonest first).
|
|
128
143
|
|
|
129
|
-
| Parameter
|
|
130
|
-
|
|
|
131
|
-
| `opts.type`
|
|
132
|
-
| `opts.limit`
|
|
133
|
-
|
|
144
|
+
| Parameter | Type | Description |
|
|
145
|
+
| ------------ | -------- | --------------------------------------------- |
|
|
146
|
+
| `opts.type` | `string` | _(optional)_ Filter to a single type |
|
|
147
|
+
| `opts.limit` | `number` | _(optional, default 100)_ Max items to return |
|
|
148
|
+
|
|
149
|
+
There is no offset — `total` counts every matching entry, `items` holds the first `limit`.
|
|
134
150
|
|
|
135
151
|
**Returns:** `{ total, items }`
|
|
136
152
|
|
|
137
|
-
Each item: `{ type, key, expiresAt, remainingMs }`
|
|
153
|
+
Each item: `{ type, key, expiresAt, remainingMs, expired }`
|
|
138
154
|
|
|
139
155
|
```javascript
|
|
140
156
|
const result = db.listTTL({ type: 'sessions', limit: 10 });
|
|
141
|
-
// { total: 42, items: [ { type: 'sessions', key: 's1', expiresAt: ..., remainingMs:
|
|
157
|
+
// { total: 42, items: [ { type: 'sessions', key: 's1', expiresAt: ..., remainingMs: ..., expired: false }, ... ] }
|
|
142
158
|
```
|
|
143
159
|
|
|
144
160
|
---
|
|
145
161
|
|
|
146
162
|
## Background Sweep
|
|
147
163
|
|
|
148
|
-
Expired items are not deleted the instant they expire.
|
|
164
|
+
Expired items are not deleted the instant they expire. They are removed by an automatic,
|
|
165
|
+
per-env sweep, or by calling `sweepExpiredTTL()` manually. There is no start/stop API and no
|
|
166
|
+
fixed interval — the sweep is scheduled from each process's in-memory "soonest expiry":
|
|
149
167
|
|
|
150
|
-
|
|
168
|
+
- **A timer** — one per env — is armed for the soonest expiry when the env opens (if it has TTL
|
|
169
|
+
entries), whenever a TTL is set in this process by any path (`setTTL()`, a write option
|
|
170
|
+
`put(..., { ttl })`, a type default, the HTTP PUT body's `ttl`) and it is earlier than the
|
|
171
|
+
armed target, when a replicated TTL is applied from a sync peer, and after every sweep for the
|
|
172
|
+
next remaining expiry. It is `unref()`'d, so it never keeps the process alive, and it is
|
|
173
|
+
cancelled on close.
|
|
174
|
+
- **Every write** to the env in this process checks (in memory, no I/O) whether the soonest
|
|
175
|
+
expiry has passed and, if so, queues a sweep.
|
|
151
176
|
|
|
152
|
-
|
|
153
|
-
|
|
177
|
+
Every process that has the env open runs this — it is not tied to the `processors` role or a
|
|
178
|
+
lease. Concurrent sweeps from several processes are safe: each re-checks the entry inside its
|
|
179
|
+
write transaction and skips items another process already removed.
|
|
154
180
|
|
|
155
|
-
|
|
156
|
-
env.startTTLSweep();
|
|
181
|
+
### Sweep Behaviour
|
|
157
182
|
|
|
158
|
-
|
|
159
|
-
|
|
183
|
+
- Range-scans the env-level `~ttl:expiry` index for entries where `expiresAt <= Date.now()`
|
|
184
|
+
(all types at once), up to `batchSize` (default 1000) per sweep, in one write transaction
|
|
185
|
+
- Removes each expired item using the standard remove path (indexes, foreign keys, change log all updated)
|
|
186
|
+
- Emits a `ttl:expired` event for each removed item
|
|
187
|
+
- Skips (and cleans up) entries whose TTL was changed or cleared since the scan
|
|
160
188
|
|
|
161
|
-
|
|
162
|
-
env.stopTTLSweep();
|
|
163
|
-
```
|
|
189
|
+
### Expired but not yet swept
|
|
164
190
|
|
|
165
|
-
|
|
191
|
+
Reads do **not** check TTL. Until a sweep removes it, an expired item is still returned by
|
|
192
|
+
every read path — `get`, `getEntry`, `query`, index lookups, views, FTS, and the HTTP routes;
|
|
193
|
+
`getTTL` then reports `remainingMs: 0`. The window is normally short:
|
|
166
194
|
|
|
167
|
-
|
|
195
|
+
- the timer fires at the soonest expiry; the sweep then takes a write transaction, so removal
|
|
196
|
+
lands shortly after `expiresAt`, not exactly at it;
|
|
197
|
+
- a sweep removes at most `batchSize` items; if more are already due, the timer is re-armed
|
|
198
|
+
immediately for the next batch;
|
|
199
|
+
- an item whose removal is refused (e.g. a foreign-key `onDelete: 'restrict'` child still
|
|
200
|
+
references it) stays until the removal succeeds; while only such items are due, sweeps back
|
|
201
|
+
off (1 s, doubling to 10 s) instead of retrying continuously, which can also delay other expiries
|
|
202
|
+
by up to the backoff;
|
|
203
|
+
- TTLs written by another process on the same path do not update this process's soonest expiry
|
|
204
|
+
(that process sweeps them itself).
|
|
168
205
|
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
- Respects `batchSize` to avoid long-running transactions
|
|
173
|
-
- Safe to call concurrently — duplicate removal attempts are handled gracefully
|
|
206
|
+
If expiry must be exact, filter on the read side (compare `getTTL(...).remainingMs` or keep an
|
|
207
|
+
`expiresAt` field in the document), or call `sweepExpiredTTL()` / `POST .../ttl/sweep` before
|
|
208
|
+
reading.
|
|
174
209
|
|
|
175
210
|
---
|
|
176
211
|
|
|
@@ -219,10 +254,11 @@ TTL operations emit events on `db.events`:
|
|
|
219
254
|
| `ttl:clear` | `{ type, key, env }` | A TTL is cleared |
|
|
220
255
|
| `ttl:expired` | `{ type, key, env }` | An item is removed by the sweep |
|
|
221
256
|
|
|
222
|
-
|
|
223
|
-
|
|
257
|
+
`ttl:set` / `ttl:clear` payloads are the changelog entry, so they also carry `clock`, `origin`,
|
|
258
|
+
`action` and `timestamp`.
|
|
224
259
|
|
|
225
|
-
|
|
260
|
+
```javascript
|
|
261
|
+
db.events.on('ttl:expired', ({ type, key }) => {
|
|
226
262
|
console.log(`Expired: ${type}/${key}`);
|
|
227
263
|
});
|
|
228
264
|
```
|
|
@@ -234,15 +270,17 @@ db.events.on(EVENTS.TTL_EXPIRED, ({ type, key }) => {
|
|
|
234
270
|
### Get item TTL
|
|
235
271
|
|
|
236
272
|
```
|
|
237
|
-
GET /api/:env/type/:type/item/:key/ttl
|
|
273
|
+
GET /api[/env/:env]/type/:type/item/:key/ttl
|
|
238
274
|
```
|
|
239
275
|
|
|
240
|
-
Returns `{
|
|
276
|
+
Returns `{ data: { expiresAt, remainingMs } }` or `{ data: null }` (inside okdb's usual
|
|
277
|
+
`{ data, error, meta }` envelope). Env-scoped routes take an optional `/env/:env` segment;
|
|
278
|
+
without it they target the default env — see [HTTP API](./http-api.md#environment-prefix).
|
|
241
279
|
|
|
242
280
|
### Set item TTL
|
|
243
281
|
|
|
244
282
|
```
|
|
245
|
-
PUT /api/:env/type/:type/item/:key/ttl
|
|
283
|
+
PUT /api[/env/:env]/type/:type/item/:key/ttl
|
|
246
284
|
Content-Type: application/json
|
|
247
285
|
|
|
248
286
|
{ "ttl": 60000 }
|
|
@@ -251,56 +289,69 @@ Content-Type: application/json
|
|
|
251
289
|
### Clear item TTL
|
|
252
290
|
|
|
253
291
|
```
|
|
254
|
-
DELETE /api/:env/type/:type/item/:key/ttl
|
|
292
|
+
DELETE /api[/env/:env]/type/:type/item/:key/ttl
|
|
255
293
|
```
|
|
256
294
|
|
|
257
295
|
### Put item with TTL
|
|
258
296
|
|
|
259
|
-
The standard PUT item route
|
|
297
|
+
The standard PUT item route stores the **whole request body** as the document; a numeric
|
|
298
|
+
top-level `ttl` field (> 0) is also applied as the TTL in ms:
|
|
260
299
|
|
|
261
300
|
```
|
|
262
|
-
PUT /api/:env/type/:type/item/:key
|
|
301
|
+
PUT /api[/env/:env]/type/:type/item/:key
|
|
263
302
|
Content-Type: application/json
|
|
264
303
|
|
|
265
|
-
{ "
|
|
304
|
+
{ "user": "alice", "ttl": 60000 }
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
Because the body is the document, `ttl: 60000` is stored in the document as well. To keep it
|
|
308
|
+
out, write the item and then call `PUT .../item/:key/ttl`.
|
|
309
|
+
|
|
310
|
+
### Per-type default TTL
|
|
311
|
+
|
|
312
|
+
```
|
|
313
|
+
GET /api[/env/:env]/type/:type/ttl/default → { type, defaultTTL }
|
|
314
|
+
PUT /api[/env/:env]/type/:type/ttl/default { "ttl": 60000 }
|
|
315
|
+
DELETE /api[/env/:env]/type/:type/ttl/default
|
|
266
316
|
```
|
|
267
317
|
|
|
268
318
|
### Sweep expired items
|
|
269
319
|
|
|
270
320
|
```
|
|
271
|
-
POST /api/:env/ttl/sweep
|
|
321
|
+
POST /api[/env/:env]/ttl/sweep
|
|
272
322
|
Content-Type: application/json
|
|
273
323
|
|
|
274
324
|
{ "batchSize": 500 }
|
|
275
325
|
```
|
|
276
326
|
|
|
277
|
-
Returns `{
|
|
327
|
+
Returns `{ data: { removed: 5, types: { sessions: 3, cache: 2 } } }`.
|
|
278
328
|
|
|
279
329
|
### TTL stats
|
|
280
330
|
|
|
281
331
|
```
|
|
282
|
-
GET /api/:env/ttl/stats
|
|
283
|
-
GET /api/:env/ttl/stats?type=sessions
|
|
332
|
+
GET /api[/env/:env]/ttl/stats
|
|
333
|
+
GET /api[/env/:env]/ttl/stats?type=sessions
|
|
284
334
|
```
|
|
285
335
|
|
|
286
|
-
Returns `{
|
|
336
|
+
Returns `{ data: { enabled, totalEntries, expiredEntries, nextExpiry, byType } }`.
|
|
287
337
|
|
|
288
338
|
### List TTL entries
|
|
289
339
|
|
|
290
340
|
```
|
|
291
|
-
GET /api/:env/ttl/list
|
|
292
|
-
GET /api/:env/ttl/list?type=sessions&limit=20
|
|
341
|
+
GET /api[/env/:env]/ttl/list
|
|
342
|
+
GET /api[/env/:env]/ttl/list?type=sessions&limit=20
|
|
293
343
|
```
|
|
294
344
|
|
|
295
|
-
Returns `{
|
|
345
|
+
Returns `{ data: { total, items: [{ type, key, expiresAt, remainingMs, expired }] } }` (`limit`
|
|
346
|
+
default 100, max 1000).
|
|
296
347
|
|
|
297
348
|
### GET item includes TTL
|
|
298
349
|
|
|
299
|
-
When a TTL is set on an item, the `GET /api/:env/type/:type/item/:key` response includes it:
|
|
350
|
+
When a TTL is set on an item, the `GET /api[/env/:env]/type/:type/item/:key` response includes it:
|
|
300
351
|
|
|
301
352
|
```json
|
|
302
353
|
{
|
|
303
|
-
"
|
|
354
|
+
"data": {
|
|
304
355
|
"key": "s1",
|
|
305
356
|
"value": { "user": "alice" },
|
|
306
357
|
"ttl": { "expiresAt": 1712345678000, "remainingMs": 1799432 }
|
|
@@ -320,9 +371,7 @@ const analytics = db.env('analytics');
|
|
|
320
371
|
|
|
321
372
|
await analytics.registerType('events');
|
|
322
373
|
await analytics.put('events', 'e1', { name: 'pageview' });
|
|
323
|
-
await analytics.setTTL('events', 'e1', 86_400_000); // 24h
|
|
324
|
-
|
|
325
|
-
analytics.startTTLSweep(60_000); // independent sweep timer
|
|
374
|
+
await analytics.setTTL('events', 'e1', 86_400_000); // 24h — swept by analytics' own scheduler
|
|
326
375
|
```
|
|
327
376
|
|
|
328
377
|
---
|
|
@@ -345,24 +394,26 @@ async function handler({ db }) {
|
|
|
345
394
|
|
|
346
395
|
## How It Works
|
|
347
396
|
|
|
348
|
-
Each
|
|
397
|
+
Each env has one TTL store shared by all its types — two LMDB sub-databases, created lazily on
|
|
398
|
+
the first TTL write (a `_ttl_enabled` flag reopens them on restart):
|
|
349
399
|
|
|
350
|
-
| Sub-database
|
|
351
|
-
|
|
|
352
|
-
|
|
|
353
|
-
|
|
|
400
|
+
| Sub-database | Key | Value | Purpose |
|
|
401
|
+
| ------------- | ---------------------------- | ----------------------- | ------------------------- |
|
|
402
|
+
| `~ttl:expiry` | `expiresAt` (ordered-binary) | `"type\tkey"` (dupSort) | Range scan for sweep |
|
|
403
|
+
| `~ttl:key` | `"type\tkey"` | `expiresAt` | O(1) lookup for get/clear |
|
|
354
404
|
|
|
355
|
-
- **Setting a TTL** writes to both sub-databases. If a previous TTL exists, the old entry in
|
|
405
|
+
- **Setting a TTL** writes to both sub-databases. If a previous TTL exists, the old entry in `~ttl:expiry` is removed first.
|
|
356
406
|
- **Clearing a TTL** removes from both sub-databases.
|
|
357
|
-
- **Removing an item** (`db.remove()`) automatically clears its TTL entries.
|
|
358
|
-
- **Updating an item** (`db.put()`, `db.update()`) does **not** change its TTL.
|
|
359
|
-
- **Sweeping** does a range scan on
|
|
407
|
+
- **Removing an item** (`db.remove()`) automatically clears its TTL entries; dropping a type clears all of its TTL entries.
|
|
408
|
+
- **Updating an item** (`db.put()`, `db.update()`) does **not** change its TTL unless the write passes a `ttl` option. Otherwise the TTL must be explicitly updated with `setTTL()`.
|
|
409
|
+
- **Sweeping** does a range scan on `~ttl:expiry` for all entries where `expiresAt <= now`, then removes the corresponding items.
|
|
410
|
+
- **Sync**: `setTTL` / `clearTTL` write changelog entries (`setTtl` / `clearTtl`) carrying the absolute `expiresAt`, so TTLs replicate to peers.
|
|
360
411
|
|
|
361
412
|
---
|
|
362
413
|
|
|
363
414
|
## Persistence
|
|
364
415
|
|
|
365
|
-
TTL metadata is stored in LMDB alongside the data. It survives restarts — items that expired while the database was closed
|
|
416
|
+
TTL metadata is stored in LMDB alongside the data. It survives restarts — items that expired while the database was closed are swept soon after the env reopens (the open arms the timer for the soonest expiry, which is already due), or on the next `sweepExpiredTTL()` call.
|
|
366
417
|
|
|
367
418
|
---
|
|
368
419
|
|
package/docs/upgrade-2.0.md
CHANGED
|
@@ -49,7 +49,7 @@ There is no `http` constructor option — the HTTP server exists only when you c
|
|
|
49
49
|
| `asyncProcessors: true` | `processors: true` (participate — claim every unclaimed lease) | _(thrown, with message)_ |
|
|
50
50
|
| `asyncProcessors: false` | `processors: false` (passive — claim nothing) | _(thrown, with message)_ |
|
|
51
51
|
| `processors: '<filter>'` (2.0 draft) | `processors: true \| false` — the filtered claim form was removed before release | _(thrown, with message)_ |
|
|
52
|
-
| `bus: true \| false` | **removed** — auto-enabled
|
|
52
|
+
| `bus: true \| false` | **removed** — auto-enabled whenever the shmbuf native binding is present (pokes throttled, see [sync](sync.md#udp-discovery-bus)) | `BUS_OPTION_REMOVED` |
|
|
53
53
|
| `envs: 'all' \| 'core' \| […]` | **removed** — envs always open lazily; `removeEnvironment` broadcasts a release signal so handles close | `ENVS_REMOVED` |
|
|
54
54
|
| `sync: false` (per env) | **removed** — the changelog auto-enables for every user env; a pure local store simply never gets a consumer | `SYNC_OPTION_REMOVED` |
|
|
55
55
|
| `processing: 'auto' \| 'main'` | **removed** — participation is the `processors` boolean (see below) | `PROCESSING_REMOVED` _(thrown)_ |
|
|
@@ -57,7 +57,7 @@ There is no `http` constructor option — the HTTP server exists only when you c
|
|
|
57
57
|
| `workers: …` | **removed** — there is no managed population (see _Workers dissolved_) | _(see `db.workers` below)_ |
|
|
58
58
|
| `compaction: 'active' \| 'passive'` | **removed** (pre-release draft alias, never shipped) — `compaction` is boolean-only, like the other role flags | `COMPACTION_ALIAS_REMOVED` |
|
|
59
59
|
|
|
60
|
-
**Why these are safe to remove:** `bus` is load-bearing
|
|
60
|
+
**Why these are safe to remove:** `bus` is load-bearing and derived (native shmbuf ⇒ on);
|
|
61
61
|
`envs` was never a real boundary (self-trusted embedded code can `openEnv()` anything) — its
|
|
62
62
|
only job was a Windows file-deletion race, now fixed by the env-release broadcast; the
|
|
63
63
|
changelog only costs anything when something consumes it, so it switches on with the first
|
package/docs/views.md
CHANGED
|
@@ -205,8 +205,8 @@ Filters are evaluated at three levels:
|
|
|
205
205
|
|
|
206
206
|
### Limitations
|
|
207
207
|
|
|
208
|
-
- `$min` and `$max`
|
|
209
|
-
-
|
|
208
|
+
- `$min` and `$max` **work** inside `$group` (tracked per group key in the view's sorted sub-DB), but not inside a _nested_ `$group` — that throws `VIEW_NESTED_GROUP_INDEXED_UNSUPPORTED`; use a compound `by` array instead.
|
|
209
|
+
- `$ref` inside `$group.reduce` is not supported (`VIEW_GROUP_REF_UNSUPPORTED`) — use a top-level `$ref`.
|
|
210
210
|
|
|
211
211
|
### Example
|
|
212
212
|
|
|
@@ -357,7 +357,7 @@ stats.orders.count.value; // → total completed orders across all active stores
|
|
|
357
357
|
stats.orders.revenue.value; // → total revenue
|
|
358
358
|
```
|
|
359
359
|
|
|
360
|
-
`$ref` reducers support the same built-in reducers as top-level `reduce`,
|
|
360
|
+
`$ref` reducers support the same built-in reducers as top-level `reduce`, including `$min` and `$max`.
|
|
361
361
|
|
|
362
362
|
---
|
|
363
363
|
|
|
@@ -396,21 +396,29 @@ Add a `bucket` object to the view definition:
|
|
|
396
396
|
|
|
397
397
|
The `field` value is interpreted as a Unix timestamp in milliseconds or an ISO date string.
|
|
398
398
|
|
|
399
|
-
#### Custom projection (
|
|
399
|
+
#### Custom projection (named)
|
|
400
400
|
|
|
401
|
-
|
|
401
|
+
To map each field value to an arbitrary string bucket key, register a projection function under a name with `OKDB.registerBucketProjection(name, fn)`, then reference that **name** in `bucket.project` (instead of `preset`):
|
|
402
402
|
|
|
403
403
|
```js
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
404
|
+
const OKDB = require('okdb');
|
|
405
|
+
|
|
406
|
+
// Once per process, BEFORE db.open():
|
|
407
|
+
OKDB.registerBucketProjection('lowercase', (value) => String(value ?? 'unknown').toLowerCase());
|
|
408
|
+
|
|
409
|
+
await env.views.create('byCategory', {
|
|
410
|
+
type: 'products',
|
|
411
|
+
reduce: { count: { $count: true } },
|
|
412
|
+
bucket: { field: 'category', granularity: 'category', project: 'lowercase' },
|
|
413
|
+
});
|
|
411
414
|
```
|
|
412
415
|
|
|
413
|
-
|
|
416
|
+
- The stored (and synced) definition keeps the name, so the view recompiles on reopen, on peers and on `views.rebuild()`. Because the definition is plain JSON, a view that names a projection registered in the server process can also be created over HTTP.
|
|
417
|
+
- The registry is per process: **every process that opens the store must register the same name before `open()`**. A stored view whose projection isn't registered at `open()` is held back rather than failing the open: it is not activated, `views.get(name)` returns `null`, `views.getMeta(name)` reports `state: 'error'` with `error.code: 'BUCKET_PROJECT_UNKNOWN'`, and an error is logged. Register the name and call `views.rebuild(name)` to bring it back (a full re-derivation, since it missed writes while held back).
|
|
418
|
+
- Passing a function as `bucket.project` is refused with `BUCKET_PROJECT_NOT_PERSISTABLE` (it could not be stored); an unregistered name is refused with `BUCKET_PROJECT_UNKNOWN`.
|
|
419
|
+
- A projection that throws halts the view (see [States](#states)).
|
|
420
|
+
|
|
421
|
+
Stores that hold a view created with a function projection before this contract (its stored bucket has neither `preset` nor `project`) open normally; that view is held back with `BUCKET_CONFIG_INVALID` — remove it with `views.remove(name)` and re-create it with a registered name.
|
|
414
422
|
|
|
415
423
|
### Create example
|
|
416
424
|
|
|
@@ -490,13 +498,16 @@ const items = view.count.items({ bucket: { granularity: 'day', key: '2024-01-15'
|
|
|
490
498
|
|
|
491
499
|
A view's meta state is available via `views.getMeta(name)`:
|
|
492
500
|
|
|
493
|
-
| State | Meaning
|
|
494
|
-
| ----------- |
|
|
495
|
-
| `creating` | Initial bootstrap scan in progress
|
|
496
|
-
| `ready` | Fully up-to-date; all writes are being processed
|
|
497
|
-
| `halted` | A reducer threw; new writes are queued until the next write recovers the view
|
|
498
|
-
| `stopped` | Manually paused; writes that arrive while stopped are replayed on start
|
|
499
|
-
| `resetting` | Clock regression detected; full rebuild triggered automatically
|
|
501
|
+
| State | Meaning |
|
|
502
|
+
| ----------- | ------------------------------------------------------------------------------ |
|
|
503
|
+
| `creating` | Initial bootstrap scan in progress |
|
|
504
|
+
| `ready` | Fully up-to-date; all writes are being processed |
|
|
505
|
+
| `halted` | A reducer threw; new writes are queued until the next write recovers the view |
|
|
506
|
+
| `stopped` | Manually paused; writes that arrive while stopped are replayed on start |
|
|
507
|
+
| `resetting` | Clock regression detected; full rebuild triggered automatically |
|
|
508
|
+
| `error` | The stored definition could not be compiled at `open()` (held back, see below) |
|
|
509
|
+
|
|
510
|
+
A stored view that can't be compiled when the store opens — a custom reducer or bucket projection this process hasn't registered, a `$where` filter persisted before it was forbidden, a pre-named-projection bucket — never fails `open()`. That view alone is held back: it is not activated, `get()` returns `null`, `getMeta()` returns `{ state: 'error', error: { code, error } }`, and an error naming the view is logged. Every other view boots, rebuilds and serves normally, and `views.remove(name)` still works. `views.rebuild(name)` retries the compile (and fully re-derives the view on success).
|
|
500
511
|
|
|
501
512
|
### Rebuild
|
|
502
513
|
|
|
@@ -533,10 +544,12 @@ await env.views.remove('orderStats', { managedIndexes: 'keep' }); // retain the
|
|
|
533
544
|
|
|
534
545
|
## Custom reducers
|
|
535
546
|
|
|
536
|
-
Register a custom reducer before creating a view that uses it. Custom reducer names must start with
|
|
547
|
+
Register a custom reducer before creating a view that uses it. Custom reducer names must start with `$` and must not be a built-in reducer name (`$count`, `$sum`, `$avg`, `$min`, `$max`, `$countBy`, `$group`) or `$ref` — those are refused with `VIEW_REDUCER_CONFLICT`. A view that references a `$name` no registered reducer matches is refused at `create()` with `VIEW_UNKNOWN_REDUCER`.
|
|
548
|
+
|
|
549
|
+
Reducers are referenced by name (the function isn't persisted), so register them in every process that opens the store. Prefer the process-wide `OKDB.registerViewReducer(name, { apply })`, called **before `db.open()`** — the stored view then compiles at boot and stays live from the first write. `env.views.registerReducer(name, { apply })` registers for one env after it is open; a stored view whose reducer is registered only that way is held back at `open()` (`getMeta` → `state: 'error'`, `error.code: 'VIEW_UNKNOWN_REDUCER'`) and is fully re-derived when `registerReducer` is called, so writes made in between are not lost.
|
|
537
550
|
|
|
538
551
|
```js
|
|
539
|
-
|
|
552
|
+
const product = {
|
|
540
553
|
apply(state, before, after, opts) {
|
|
541
554
|
// state — current accumulated value (null on first call)
|
|
542
555
|
// before — previous doc (null for inserts), post-filter, post-map
|
|
@@ -547,7 +560,8 @@ env.views.registerReducer('$product', {
|
|
|
547
560
|
if (after !== null && typeof after[opts] === 'number') state *= after[opts];
|
|
548
561
|
return state;
|
|
549
562
|
},
|
|
550
|
-
}
|
|
563
|
+
};
|
|
564
|
+
OKDB.registerViewReducer('$product', product); // before db.open()
|
|
551
565
|
|
|
552
566
|
await env.views.create('priceProduct', {
|
|
553
567
|
type: 'items',
|
|
@@ -555,6 +569,8 @@ await env.views.create('priceProduct', {
|
|
|
555
569
|
});
|
|
556
570
|
```
|
|
557
571
|
|
|
572
|
+
Documents that already exist when the view is created are folded in by the bootstrap scan, exactly as live writes are (`views.rebuild()` re-derives the same value). Custom reducers also work as `$group` and `$ref` sub-reducers. Views that use a custom reducer or projection bootstrap on the main thread (the off-thread bootstrap worker has no access to the in-process registries).
|
|
573
|
+
|
|
558
574
|
---
|
|
559
575
|
|
|
560
576
|
## JavaScript API
|
|
@@ -569,13 +585,14 @@ await env.views.create(name, definition) // → { name }
|
|
|
569
585
|
|
|
570
586
|
// Read
|
|
571
587
|
env.views.get(name) // → output object | null (synchronous)
|
|
572
|
-
env.views.getMeta(name) // → { state, clock, error, refs } | null
|
|
588
|
+
env.views.getMeta(name) // → { state, clock, error, refs, storageVersion, ... } | null
|
|
573
589
|
await env.views.getDefinition(name) // → stored definition | null
|
|
574
590
|
await env.views.list() // → string[]
|
|
575
591
|
|
|
576
592
|
// Bucketing (bucketed views only)
|
|
577
593
|
env.views.range(name, options?) // → BucketEntry[] | null (synchronous)
|
|
578
594
|
env.views.listBuckets(name, options) // → { bucketKey, count }[] (synchronous)
|
|
595
|
+
env.views.itemsGroups(name, opts) // → one page of all groups of a grouped reducer
|
|
579
596
|
|
|
580
597
|
// Lifecycle
|
|
581
598
|
await env.views.rebuild(name)
|
|
@@ -584,7 +601,9 @@ await env.views.start(name)
|
|
|
584
601
|
await env.views.remove(name, options?)
|
|
585
602
|
|
|
586
603
|
// Extension
|
|
587
|
-
env.views.registerReducer(name, { apply })
|
|
604
|
+
env.views.registerReducer(name, { apply }) // per env; see Custom reducers
|
|
605
|
+
OKDB.registerViewReducer(name, { apply }) // process-wide, before open()
|
|
606
|
+
OKDB.registerBucketProjection(name, fn) // process-wide, before open()
|
|
588
607
|
```
|
|
589
608
|
|
|
590
609
|
---
|
|
@@ -679,30 +698,30 @@ View definitions are stored in the `~views` system type within their environment
|
|
|
679
698
|
|
|
680
699
|
## Error codes
|
|
681
700
|
|
|
682
|
-
| Code
|
|
683
|
-
|
|
|
684
|
-
| `VIEW_INVALID_NAME`
|
|
685
|
-
| `VIEW_INVALID_DEFINITION`
|
|
686
|
-
| `VIEW_MISSING_TYPE`
|
|
687
|
-
| `VIEW_MISSING_REDUCE`
|
|
688
|
-
| `VIEW_TYPE_NOT_REGISTERED`
|
|
689
|
-
| `VIEW_ALREADY_EXISTS`
|
|
690
|
-
| `VIEW_NOT_FOUND`
|
|
691
|
-
| `VIEW_HAS_ORPHANED_INDEXES`
|
|
692
|
-
| `
|
|
693
|
-
| `
|
|
694
|
-
| `
|
|
695
|
-
| `
|
|
696
|
-
| `
|
|
697
|
-
| `
|
|
698
|
-
| `BUCKET_INVALID_TIME_VALUE`
|
|
699
|
-
| `VIEW_NOT_BUCKETED`
|
|
700
|
-
| `VIEW_RANGE_GRANULARITY_MISMATCH`
|
|
701
|
-
| `VIEW_RANGE_GRANULARITY_REQUIRED`
|
|
702
|
-
| `VIEW_ITEMS_SCOPE_INVALID`
|
|
703
|
-
| `VIEW_ITEMS_REDUCER_NOT_FOUND`
|
|
704
|
-
| `VIEW_ITEMS_REF_NOT_FOUND`
|
|
705
|
-
| `VIEW_ITEMS_GROUP_NOT_FOUND`
|
|
706
|
-
| `VIEW_ITEMS_NOT_AVAILABLE`
|
|
707
|
-
| `VIEW_ITEMS_LIMIT_INVALID`
|
|
708
|
-
| `VIEW_ITEMS_OFFSET_INVALID`
|
|
701
|
+
| Code | Cause |
|
|
702
|
+
| --------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
|
703
|
+
| `VIEW_INVALID_NAME` | Name is empty, contains whitespace, or is not a string |
|
|
704
|
+
| `VIEW_INVALID_DEFINITION` | Definition is not an object |
|
|
705
|
+
| `VIEW_MISSING_TYPE` | `type` field missing or not a string |
|
|
706
|
+
| `VIEW_MISSING_REDUCE` | `reduce` field missing or empty |
|
|
707
|
+
| `VIEW_TYPE_NOT_REGISTERED` | The source type does not exist in this environment |
|
|
708
|
+
| `VIEW_ALREADY_EXISTS` | A view with that name already exists |
|
|
709
|
+
| `VIEW_NOT_FOUND` | No view with that name |
|
|
710
|
+
| `VIEW_HAS_ORPHANED_INDEXES` | Removing the view would leave auto-created indexes with no owner; pass `managedIndexes` option |
|
|
711
|
+
| `VIEW_GROUP_REF_UNSUPPORTED` | `$ref` used as a sub-reducer inside `$group` |
|
|
712
|
+
| `VIEW_NESTED_GROUP_INDEXED_UNSUPPORTED` | `$min`/`$max` inside a nested `$group` |
|
|
713
|
+
| `VIEW_INVALID_REDUCER_NAME` | Custom reducer name does not start with `$` |
|
|
714
|
+
| `VIEW_REDUCER_CONFLICT` | Custom reducer name conflicts with a built-in |
|
|
715
|
+
| `VIEW_INVALID_REDUCER` | Custom reducer missing an `apply` function |
|
|
716
|
+
| `BUCKET_CONFIG_INVALID` | `bucket` config is missing required fields, uses an unsupported preset, or has an invalid granularity |
|
|
717
|
+
| `BUCKET_INVALID_TIME_VALUE` | A document's bucket field could not be parsed as a time value |
|
|
718
|
+
| `VIEW_NOT_BUCKETED` | `range()` or `listBuckets()` was called on a view that has no `bucket` config |
|
|
719
|
+
| `VIEW_RANGE_GRANULARITY_MISMATCH` | The `granularity` option does not match the view's configured granularity |
|
|
720
|
+
| `VIEW_RANGE_GRANULARITY_REQUIRED` | `listBuckets()` was called without a `granularity` option |
|
|
721
|
+
| `VIEW_ITEMS_SCOPE_INVALID` | `scope` is not one of `view`, `reducer`, `ref`, `ref-reducer` |
|
|
722
|
+
| `VIEW_ITEMS_REDUCER_NOT_FOUND` | The named reducer does not exist on the view |
|
|
723
|
+
| `VIEW_ITEMS_REF_NOT_FOUND` | The named `$ref` slot does not exist on the view |
|
|
724
|
+
| `VIEW_ITEMS_GROUP_NOT_FOUND` | The named group key does not exist on the `$countBy` reducer |
|
|
725
|
+
| `VIEW_ITEMS_NOT_AVAILABLE` | `items()` was requested but the reducer does not have `items: true` |
|
|
726
|
+
| `VIEW_ITEMS_LIMIT_INVALID` | `limit` is not a non-negative integer |
|
|
727
|
+
| `VIEW_ITEMS_OFFSET_INVALID` | `offset` is not a non-negative integer |
|