@kedem/okdb 3.0.1 → 3.1.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/docs/pipelines.md CHANGED
@@ -102,21 +102,30 @@ Unlike env-scoped engines, pipelines do **not** use `~system` by default.
102
102
 
103
103
  ### Env-local facade
104
104
 
105
- <!-- not-runnable: needs a license (engines) -->
105
+ <!-- licensed: engines -->
106
106
 
107
107
  ```javascript
108
- const analytics = okdb.env('analytics');
108
+ const analytics = await okdb.createEnvironment('analytics');
109
109
 
110
110
  // Engines must already exist before a pipeline record can be created.
111
+ await analytics.functions.create({ name: 'ingestArticle', source: 'async (ctx) => ({ ok: true })' });
112
+ const handler = { kind: 'function', name: 'ingestArticle' };
113
+ await analytics.engines.createAndStartEngine('queue-worker', 'articles-worker', {
114
+ job_type: 'article-ingest',
115
+ handler,
116
+ });
117
+ // the replaceMember() target below (one consumer per job type, so it reads another one)
118
+ await analytics.engines.createAndStartEngine('queue-worker', 'other-worker', {
119
+ job_type: 'article-ingest-v2',
120
+ handler,
121
+ });
122
+
111
123
  await analytics.pipelines.create({
112
124
  name: 'articles-ingest',
113
125
  template: null,
114
126
  status: 'active',
115
127
  meta: {},
116
- engines: [
117
- { type: 'embedder', name: 'shared-embedder', role: 'embedder' },
118
- { type: 'indexer', name: 'analytics:articles-ingest', role: 'indexer' },
119
- ],
128
+ engines: [{ type: 'queue-worker', name: 'articles-worker', role: 'worker' }],
120
129
  });
121
130
 
122
131
  const record = await analytics.pipelines.get('articles-ingest');
@@ -127,7 +136,7 @@ await analytics.pipelines.start('articles-ingest');
127
136
  await analytics.pipelines.restart('articles-ingest'); // stop + start
128
137
  await analytics.pipelines.update('articles-ingest', { meta: { label: 'Ingest' } }); // meta/status only
129
138
  await analytics.pipelines.rebuild('articles-ingest'); // member engines with api.rebuild(), in order
130
- await analytics.pipelines.replaceMember('articles-ingest', 'embedder', 'other-embedder'); // same-role swap
139
+ await analytics.pipelines.replaceMember('articles-ingest', 'worker', 'other-worker'); // same-role swap
131
140
  await analytics.pipelines.remove('articles-ingest');
132
141
  ```
133
142
 
@@ -216,7 +225,7 @@ A generic `queue-worker` engine type that can run standalone or participate as a
216
225
 
217
226
  Typical flow:
218
227
 
219
- <!-- not-runnable: needs a license (engines) -->
228
+ <!-- licensed: engines -->
220
229
 
221
230
  ```javascript
222
231
  const analytics = await okdb.createEnvironment('analytics');
@@ -237,14 +246,6 @@ await analytics.engines.createAndStartEngine('queue-worker', 'articles-worker',
237
246
  concurrency: 2,
238
247
  });
239
248
 
240
- await analytics.pipelines.create({
241
- name: 'articles-ingest',
242
- template: null,
243
- status: 'active',
244
- meta: { label: 'Articles ingest' },
245
- engines: [{ type: 'queue-worker', name: 'articles-worker', role: 'worker' }],
246
- });
247
-
248
249
  await analytics.queue.enqueue('article-ingest', { id: 'job-1' });
249
250
  ```
250
251
 
@@ -295,7 +296,7 @@ Runtime stats exposed through `engine.api.stats()` include:
295
296
 
296
297
  Minimal pipeline membership example:
297
298
 
298
- <!-- not-runnable: needs a license (engines) -->
299
+ <!-- continues -->
299
300
 
300
301
  ```javascript
301
302
  await analytics.pipelines.create({
@@ -319,7 +320,7 @@ A generic `processor` engine type for change-log driven pipeline members. It is:
319
320
 
320
321
  Typical flow:
321
322
 
322
- <!-- not-runnable: needs a license (engines) -->
323
+ <!-- licensed: engines -->
323
324
 
324
325
  ```javascript
325
326
  const analytics = await okdb.createEnvironment('analytics');
@@ -413,7 +414,7 @@ Runtime stats exposed through `engine.api.stats()` / `engine.api.status()` inclu
413
414
 
414
415
  Minimal pipeline membership example:
415
416
 
416
- <!-- not-runnable: needs a license (engines) -->
417
+ <!-- continues -->
417
418
 
418
419
  ```javascript
419
420
  await analytics.pipelines.create({
@@ -444,7 +445,7 @@ Key differences from `processor`:
444
445
 
445
446
  Typical flow:
446
447
 
447
- <!-- not-runnable: needs a license (engines) -->
448
+ <!-- licensed: engines -->
448
449
 
449
450
  ```javascript
450
451
  const analytics = await db.createEnvironment('analytics');
package/docs/querying.md CHANGED
@@ -192,6 +192,34 @@ There is no query planner. If you pass `index`, OKDB uses it without cost analys
192
192
 
193
193
  ---
194
194
 
195
+ ### Paging with `query()`
196
+
197
+ With `index`, page by primary key: pass the last row's `key` of the previous page as `startKey`. That row is skipped, and rows that
198
+ share its index key are paged correctly (several records with the same value never get lost or repeated at a page boundary). This
199
+ works forward and with `reverse: true`, and `endKey` stops before a key the same way.
200
+
201
+ ```javascript
202
+ await okdb.ensureType('orders', { indexes: [['status', 'createdAt']] });
203
+ let last;
204
+ for (;;) {
205
+ const page = Array.from(
206
+ okdb.query(
207
+ 'orders',
208
+ { status: 'open' },
209
+ { index: ['status', 'createdAt'], limit: 50, ...(last ? { startKey: last } : {}) },
210
+ ),
211
+ );
212
+ if (!page.length) break;
213
+ // ... handle page ...
214
+ last = page[page.length - 1].key;
215
+ }
216
+ ```
217
+
218
+ `startIndex` / `endIndex` take index values instead: `startIndex` is inclusive, `endIndex` exclusive (append
219
+ `OKDBEnv.HIGH_SENTINEL` to include the last value), and they are always low / high, also with `reverse`. If the record named by
220
+ `startKey` has been deleted since the previous page, the scan finds no boundary and returns nothing; fall back to `startIndex`
221
+ from the last row's index values in that case.
222
+
195
223
  ## Index scans
196
224
 
197
225
  `byIndex` iterates entries in index order, returning `{ key, value, version, indexKey }`. `indexKey` is the stored index key: the indexed field values followed by a trailing `null` sentinel (`['x', null]` for a one-field index, `['x', 3, null]` for two fields), as in 2.x.
@@ -236,6 +264,8 @@ for (const { key, value } of okdb.byIndex('articles', ['author', 'publishedAt'],
236
264
  | `offset` | number | Skip this many entries |
237
265
  | `includeViolations` | boolean | For unique indexes: include all violating entries |
238
266
 
267
+ Bounds are written from field values alone, and `start` is inclusive while `end` is exclusive: `start: ['b', 1], end: ['b', 3]` returns the entries for `['b', 1]` and `['b', 2]`. To include the last value, append `OKDBEnv.HIGH_SENTINEL`: `end: ['b', 3, OKDBEnv.HIGH_SENTINEL]`. This holds identically for `reverse` (every entry ends in a `null` so a bound never equals a stored key). To page, resume after the last row with `start: [...lastValues, OKDBEnv.HIGH_SENTINEL]` (forward) or `end: lastValues` (backward), where `lastValues` is the row's `indexKey` without its trailing `null`.
268
+
239
269
  `start`/`end` are always the lower/upper bound regardless of `reverse` — `byIndex`/`getIndex`/`countByIndex` swap them internally for a descending scan, so you never need to. Unrecognized option keys throw immediately rather than being silently ignored.
240
270
 
241
271
  `getIndex` returns primary keys from the index sub-database (not full records) as a **lazy iterable**. Spread to an array if you need `.length`: `[...env.getIndex(...)]`.
package/docs/queue.md CHANGED
@@ -341,8 +341,6 @@ systemd, or docker alongside your main service.
341
341
 
342
342
  The canonical way to run queue consumers outside your main process:
343
343
 
344
- <!-- not-runnable: long-running worker process -->
345
-
346
344
  ```javascript
347
345
  // workers/default.js — run alongside the main service
348
346
  const OKDB = require('@kedem/okdb');
package/docs/sync.md CHANGED
@@ -48,7 +48,7 @@ with `sync:read` + `sync:peer`, or a token name + password:
48
48
  okdb token create --label 'cluster join' --permissions 'sync:read,sync:peer'
49
49
  ```
50
50
 
51
- <!-- not-runnable: needs a license (sync) and a peer -->
51
+ <!-- not-runnable: joins a peer node at a LAN address -->
52
52
 
53
53
  ```javascript
54
54
  // Node 2 joins node 1
@@ -65,7 +65,7 @@ await okdb.sync.join('http://192.168.1.10:8080', { token: process.env.OKDB_JOIN_
65
65
 
66
66
  ### Multi-node example
67
67
 
68
- <!-- not-runnable: needs a license (sync) and a peer -->
68
+ <!-- not-runnable: three nodes on fixed addresses, joined with a token created on node 0 -->
69
69
 
70
70
  ```javascript
71
71
  const nodes = [8080, 8081, 8082].map((port) => {
@@ -21,7 +21,7 @@ await tmdb.close();
21
21
 
22
22
  With a license that includes it:
23
23
 
24
- <!-- not-runnable: needs a license (timeMachine) -->
24
+ <!-- licensed: timeMachine -->
25
25
 
26
26
  ```js
27
27
  const db = new OKDB('./mydb', { timeMachine: true }); // or { timeMachine: { flushDelayMs: 1000 } }
@@ -40,7 +40,7 @@ await env.timeMachine.enableAll();
40
40
 
41
41
  ### Per-type control
42
42
 
43
- <!-- not-runnable: needs a license (timeMachine) -->
43
+ <!-- continues -->
44
44
 
45
45
  ```js
46
46
  await env.timeMachine.enable('Order'); // start tracking
@@ -54,7 +54,7 @@ await env.timeMachine.drop('Order'); // stop tracking, delete all history
54
54
 
55
55
  ### Env-wide control
56
56
 
57
- <!-- not-runnable: needs a license (timeMachine) -->
57
+ <!-- continues -->
58
58
 
59
59
  ```js
60
60
  await env.timeMachine.enableAll(); // enable all registered types now + auto-enable future types
@@ -69,14 +69,21 @@ When `enableAll()` is called, all types registered at that moment are enabled. A
69
69
 
70
70
  ### Full history for a key
71
71
 
72
- <!-- not-runnable: needs a license (timeMachine) -->
72
+ <!-- continues -->
73
73
 
74
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
+
75
82
  const { diffs, head } = env.timeMachine.getHistory('Order', 'order-42', {
76
83
  limit: 50, // max entries, oldest first (optional)
77
- maxClock: someClock, // only diffs at or before this clock (optional)
78
- after: someClock, // only diffs after this clock (optional)
79
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
80
87
  // diffs: [{ clock, fromClock, timestamp, put: {...}, delete: [...] }, ...] (ascending by clock)
81
88
  // head: { value, clock } — the latest tracked value, or null (deleted / never tracked)
82
89
  ```
@@ -93,18 +100,20 @@ Each diff entry describes what changed at that clock:
93
100
 
94
101
  ### Point-in-time reconstruction
95
102
 
96
- <!-- not-runnable: needs a license (timeMachine) -->
103
+ <!-- continues -->
97
104
 
98
105
  ```js
99
- const value = env.timeMachine.getStateAt('Order', 'order-42', targetClock);
106
+ const targetClock = diffs[0].clock;
107
+ const value = env.timeMachine.getStateAt('Order', 'order-42', targetClock); // → { status: 'new', total: 10 }
100
108
  // Returns the document value as of `targetClock` (inclusive), or undefined if no diff exists at or before it
101
109
  ```
102
110
 
103
111
  ### Change log across types
104
112
 
105
- <!-- not-runnable: needs a license (timeMachine) -->
113
+ <!-- continues -->
106
114
 
107
115
  ```js
116
+ const [fromClock, toClock] = [diffs[0].clock, head.clock];
108
117
  const changes = [...env.timeMachine.getChanges('Order', fromClock, toClock)];
109
118
  // Or all types:
110
119
  const allChanges = [...env.timeMachine.getChanges(null, fromClock, toClock)];
@@ -113,7 +122,7 @@ const allChanges = [...env.timeMachine.getChanges(null, fromClock, toClock)];
113
122
 
114
123
  ## Inspecting status
115
124
 
116
- <!-- not-runnable: needs a license (timeMachine) -->
125
+ <!-- continues -->
117
126
 
118
127
  ```js
119
128
  // Per-type status
@@ -28,7 +28,7 @@ constructor options and a few cluster/worker APIs.
28
28
  The constructor declares **what role a node plays**. Every _mechanism_ that used to be a flag
29
29
  is now **derived** — okdb turns it on the moment it's needed.
30
30
 
31
- <!-- not-runnable: a pure shape/signature fragment -->
31
+ <!-- not-runnable: a shape/signature fragment -->
32
32
 
33
33
  ```js
34
34
  new OKDB(path, {
package/docs/views.md CHANGED
@@ -44,7 +44,7 @@ const stats = env.views.get('orderStats');
44
44
 
45
45
  ## Definition shape
46
46
 
47
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
47
+ <!-- not-runnable: a shape fragment -->
48
48
 
49
49
  ```js
50
50
  {
@@ -63,7 +63,7 @@ const stats = env.views.get('orderStats');
63
63
 
64
64
  Uses [sift](https://github.com/crcn/sift.js) query operators (MongoDB-style). Only documents that pass the filter contribute to the view.
65
65
 
66
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
66
+ <!-- not-runnable: a shape fragment -->
67
67
 
68
68
  ```js
69
69
  filter: { status: 'active', amount: { $gte: 100 } }
@@ -80,7 +80,7 @@ A declarative transform merged onto each source document before reducers run. Th
80
80
  | Concatenate | `{ label: { $concat: ['$city', ' – ', '$name'] } }` | `$`-prefixed tokens are field refs (dot paths ok); others are literals |
81
81
  | Coalesce | `{ display: { $coalesce: ['$nickname', '$name', 'Unknown'] } }` | First non-null wins; `$`-prefixed tokens are field refs (dot paths supported) |
82
82
 
83
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
83
+ <!-- not-runnable: a shape fragment -->
84
84
 
85
85
  ```js
86
86
  // Example: enrich each store with its region name via a FK lookup,
@@ -169,7 +169,7 @@ const keys = result.total.items({ keysOnly: true }); // result holds keys only
169
169
 
170
170
  ### Syntax
171
171
 
172
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
172
+ <!-- not-runnable: a shape fragment -->
173
173
 
174
174
  ```js
175
175
  reduce: {
@@ -192,7 +192,7 @@ reduce: {
192
192
 
193
193
  Like `$countBy`, the result is the paginated `{ totalGroups, preview, hasMore, cursor }` shape (see [Output shape](#output-shape) above) — not a plain `{ [groupKey]: {...} }` map. Each `preview` entry is `{ key, <subReducerName>: { value }, ... }`:
194
194
 
195
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
195
+ <!-- not-runnable: a shape fragment -->
196
196
 
197
197
  ```js
198
198
  {
@@ -212,16 +212,24 @@ Empty groups (count/sum reaching 0) are removed automatically — they are never
212
212
 
213
213
  Pass an array to `by` to build a key from multiple fields. The fields are joined with a `\x00` separator:
214
214
 
215
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
216
-
217
215
  ```js
218
- $group: {
219
- by: ['product_id', 'region'],
220
- reduce: { count: { $count: true } },
221
- }
216
+ await db.registerType('sales');
217
+ await env.views.create('salesStats', {
218
+ type: 'sales',
219
+ reduce: {
220
+ byProductRegion: {
221
+ $group: {
222
+ by: ['product_id', 'region'],
223
+ reduce: { count: { $count: true } },
224
+ },
225
+ },
226
+ },
227
+ });
228
+ await db.put('sales', 's1', { product_id: 'p1', region: 'EU' });
222
229
 
223
230
  // Key for product_id='p1', region='EU': 'p1\x00EU'
224
- stats.byProductRegion.preview.find((e) => e.key === 'p1\x00EU').count.value;
231
+ const stats = env.views.get('salesStats');
232
+ stats.byProductRegion.preview.find((e) => e.key === 'p1\x00EU').count.value; // → 1
225
233
  ```
226
234
 
227
235
  ### Filter semantics
@@ -274,27 +282,34 @@ p1.count.value; // → 2
274
282
 
275
283
  `$group` also works inside `$ref.reduce`:
276
284
 
277
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
278
-
279
285
  ```js
280
- reduce: {
281
- lineItems: {
282
- $ref: {
283
- type: 'line_items',
284
- key: 'order_id',
285
- reduce: {
286
- byProduct: {
287
- $group: {
288
- by: 'product_id',
289
- reduce: { total: { $sum: 'amount' } },
286
+ await db.registerType('orders');
287
+ await db.registerType('line_items');
288
+ await env.views.create('orderStats', {
289
+ type: 'orders',
290
+ reduce: {
291
+ lineItems: {
292
+ $ref: {
293
+ type: 'line_items',
294
+ key: 'order_id',
295
+ reduce: {
296
+ byProduct: {
297
+ $group: {
298
+ by: 'product_id',
299
+ reduce: { total: { $sum: 'amount' } },
300
+ },
290
301
  },
291
302
  },
292
303
  },
293
304
  },
294
305
  },
295
- }
306
+ });
307
+ await db.put('orders', 'o1', {});
308
+ await db.put('line_items', 'li1', { order_id: 'o1', product_id: 'p1', amount: 1000 });
309
+ await db.put('line_items', 'li2', { order_id: 'o1', product_id: 'p1', amount: 500 });
296
310
 
297
- stats.lineItems.byProduct.preview.find((e) => e.key === 'p1').total.value; // → aggregate revenue for product p1
311
+ const stats = env.views.get('orderStats');
312
+ stats.lineItems.byProduct.preview.find((e) => e.key === 'p1').total.value; // → 1500, aggregate revenue for product p1
298
313
  ```
299
314
 
300
315
  ---
@@ -305,7 +320,7 @@ A map field with `live: true` on its `$ref` spec is a **live enrichment**: when
305
320
 
306
321
  ### Syntax
307
322
 
308
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
323
+ <!-- not-runnable: a shape fragment -->
309
324
 
310
325
  ```js
311
326
  map: {
@@ -322,14 +337,14 @@ The array form is identical to the snapshot `$ref` — the only difference is th
322
337
  | Snapshot (default, no `live: true`) | The referenced field is resolved once when the source doc is written. Later changes to the referenced doc are not reflected in the view. |
323
338
  | Live (`live: true`) | OKDB maintains an inverse index mapping each referenced doc key to all source docs that point to it. When the referenced doc changes, every source doc in that fan-out set is re-processed through the filter, map, and reducers. |
324
339
 
325
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
340
+ <!-- not-runnable: a shape fragment -->
326
341
 
327
342
  ```js
328
343
  // Snapshot — p1's vendor change does NOT update the view
329
- map: { vendor: { $ref: ['products', '$product_id', 'vendor'] } }
344
+ map: { vendor: { $ref: ['products', '$product_id', 'vendor'] } },
330
345
 
331
346
  // Live — p1's vendor change re-evaluates all line_items with product_id='p1'
332
- map: { vendor: { $ref: ['products', '$product_id', 'vendor'], live: true } }
347
+ map: { vendor: { $ref: ['products', '$product_id', 'vendor'], live: true } },
333
348
  ```
334
349
 
335
350
  ### Cost considerations
@@ -416,7 +431,7 @@ Bucketed views partition their aggregations by a time period (or a custom groupi
416
431
 
417
432
  Add a `bucket` object to the view definition:
418
433
 
419
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
434
+ <!-- not-runnable: a shape fragment -->
420
435
 
421
436
  ```js
422
437
  {
@@ -657,7 +672,7 @@ Documents that already exist when the view is created are folded in by the boots
657
672
 
658
673
  All methods are on `env.views` (`OKDBEnv#views`):
659
674
 
660
- <!-- not-runnable: a pure shape/signature fragment that cannot run -->
675
+ <!-- fragment: an API signature list (optional parameters marked `?`) -->
661
676
 
662
677
  ```js
663
678
  const env = db.env('myEnv');