@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.
Files changed (60) hide show
  1. package/CHANGELOG.md +366 -0
  2. package/algorithm-worker-thread.js +1 -1
  3. package/bin/okdb.js +1 -1
  4. package/docs/auth-and-sync.md +28 -4
  5. package/docs/auth-permissions.md +19 -6
  6. package/docs/change-log.md +79 -59
  7. package/docs/data-model.md +20 -18
  8. package/docs/deployment.md +25 -0
  9. package/docs/diagnostics.md +59 -17
  10. package/docs/embeddings.md +57 -6
  11. package/docs/files.md +1 -1
  12. package/docs/fts.md +50 -5
  13. package/docs/functions.md +21 -8
  14. package/docs/http-api.md +139 -98
  15. package/docs/http-cluster.md +30 -8
  16. package/docs/indexes.md +5 -4
  17. package/docs/logging.md +18 -0
  18. package/docs/migration.md +94 -2
  19. package/docs/pipelines.md +6 -1
  20. package/docs/plugins.md +12 -18
  21. package/docs/process-registry.md +50 -39
  22. package/docs/processors.md +40 -22
  23. package/docs/querying.md +50 -36
  24. package/docs/queue.md +110 -14
  25. package/docs/subscriptions.md +35 -24
  26. package/docs/sync.md +96 -37
  27. package/docs/time-machine.md +23 -17
  28. package/docs/transactions.md +11 -19
  29. package/docs/ttl.md +118 -67
  30. package/docs/upgrade-2.0.md +2 -2
  31. package/docs/views.md +71 -52
  32. package/okdb-functions-sandbox-worker.js +1 -1
  33. package/okdb-http-worker-child.js +1 -1
  34. package/okdb-views-bootstrap-worker.js +1 -1
  35. package/okdb.js +1 -1
  36. package/package.json +1 -1
  37. package/public/sections/db/parts/type-viewer.ok.js +1 -1
  38. package/public/sections/embeddings/parts/engines-overview.ok.js +1 -1
  39. package/public/sections/queue/parts/queue-jobs.ok.js +1 -1
  40. package/public/sections/system/modals/data-ops-modal.ok.js +1 -1
  41. package/types/environment.d.ts +320 -52
  42. package/types/features/admin.d.ts +8 -2
  43. package/types/features/api.d.ts +10 -16
  44. package/types/features/auth.d.ts +135 -16
  45. package/types/features/embeddings.d.ts +639 -31
  46. package/types/features/engines.d.ts +368 -14
  47. package/types/features/files.d.ts +2 -4
  48. package/types/features/fts.d.ts +98 -26
  49. package/types/features/functions.d.ts +175 -15
  50. package/types/features/mcp.d.ts +23 -10
  51. package/types/features/pipelines.d.ts +268 -9
  52. package/types/features/queue.d.ts +230 -34
  53. package/types/features/sync.d.ts +177 -14
  54. package/types/features/time-machine.d.ts +117 -16
  55. package/types/features/views.d.ts +230 -39
  56. package/types/index.d.ts +357 -254
  57. package/types/okdb.d.ts +377 -0
  58. package/types/options.d.ts +309 -48
  59. package/public/test-cron-input.html +0 -60
  60. package/public/test-json-input.html +0 -280
@@ -1,5 +1,6 @@
1
- import type { OKDBIndexKey } from '../options';
1
+ import type { OKDBIndexEntry } from '../options';
2
2
  import type { EventEmitter } from 'events';
3
+ import type { OKDB } from '../okdb';
3
4
 
4
5
  export type OKDBJobStatus = 'pending' | 'running' | 'done' | 'failed';
5
6
 
@@ -12,15 +13,21 @@ export interface OKDBJob {
12
13
  id: string;
13
14
  type: string;
14
15
  idempotency_key: string | null;
16
+ /** Present only when enqueued with `idempotency_scope: 'pending'`. */
17
+ idempotency_scope?: 'pending';
15
18
  status: OKDBJobStatus;
19
+ /** e.g. `'cancelled'` (cancelJob), `'manual_retry'` (retryJob), `'shutdown'` / `'paused'` (released claim), or the fail code. */
16
20
  status_code: string | null;
17
21
  status_message: string | null;
18
22
  error_stack: string | null;
19
- progress: string | null;
23
+ progress?: string | null;
24
+ /** Handler / markJobComplete result, stored when JSON-serializable and ≤ 16 KB; else null. */
25
+ result?: unknown;
20
26
  when: number;
21
27
  priority: number;
22
28
  tags: string[];
23
29
  tag: string | null;
30
+ /** Legacy single-bucket fields (null on new jobs). */
24
31
  bucket: string | null;
25
32
  bucket_tokens: number | null;
26
33
  buckets: OKDBJobBucket[] | null;
@@ -29,13 +36,32 @@ export interface OKDBJob {
29
36
  updated: number;
30
37
  finished: number | null;
31
38
  tries: number;
39
+ /** null = unlimited. */
32
40
  max_tries: number | null;
33
41
  retry_delay: number;
34
42
  backoff_multiplier: number;
35
43
  claim_id: string | null;
36
44
  claim_expires: number | null;
45
+ /** Pid / hostname of the claiming process (set at claim). */
46
+ claim_pid?: number;
47
+ claim_host?: string;
48
+ /** Per-job log ring-buffer cap. */
49
+ logCap?: number;
37
50
  done_ttl: number | null;
38
51
  failed_ttl: number | null;
52
+ /**
53
+ * Cron jobs only: how the previous occurrence ended. Every terminal path of a cron run
54
+ * (done, permanently failed, claim timeout) re-queues the same row as `pending` at the next
55
+ * cron time with `tries: 0`, recording the finished run here. Cancel stops the series.
56
+ */
57
+ last_run?: {
58
+ status: 'done' | 'failed';
59
+ status_code: string | null;
60
+ status_message: string | null;
61
+ tries: number;
62
+ finished: number;
63
+ };
64
+ /** Included by getJob / claim / updateJob; not on `list()` items. */
39
65
  payload?: unknown;
40
66
  }
41
67
 
@@ -63,18 +89,21 @@ export interface OKDBJobType {
63
89
  export interface OKDBJobDefaults {
64
90
  max_tries: number | null;
65
91
  retry_delay: number;
66
- backoff_multiplier: number;
92
+ backoff_multiplier: number | null;
67
93
  priority: number;
94
+ /** Default claim TTL (ms) for this type. */
68
95
  ttl: number | null;
69
96
  done_ttl: number | null;
70
97
  failed_ttl: number | null;
71
98
  buckets: OKDBJobBucket[] | null;
99
+ logCap: number | null;
72
100
  }
73
101
 
74
102
  export interface OKDBEnqueueOptions {
75
103
  when?: number;
76
104
  priority?: number;
77
- tags?: string[];
105
+ tags?: string[] | string;
106
+ /** Legacy single bucket; prefer `buckets`. */
78
107
  bucket?: string;
79
108
  bucket_tokens?: number;
80
109
  buckets?: OKDBJobBucket[];
@@ -84,13 +113,23 @@ export interface OKDBEnqueueOptions {
84
113
  backoff_multiplier?: number;
85
114
  done_ttl?: number | null;
86
115
  failed_ttl?: number | null;
116
+ /**
117
+ * Dedups against a LIVE (pending / running) job with the same key and returns that job's id.
118
+ * Every terminal state (done, failed, cancelled, timed out) releases the key, so a later
119
+ * enqueue with it creates a new job. A cron job keeps its key across occurrences.
120
+ */
87
121
  idempotency_key?: string | number;
122
+ /** `'active'` (default): dedup against pending or running. `'pending'`: pending only (key released at claim). */
123
+ idempotency_scope?: 'active' | 'pending';
124
+ /** Per-job log ring-buffer cap (1–50 000; default 500). */
125
+ logCap?: number;
88
126
  txn?: OKDBQueueTransaction;
89
127
  }
90
128
 
91
129
  export interface OKDBClaimOptions {
130
+ /** Claim TTL in ms (default: job-type `defaults.ttl` ?? queue `default_ttl`, 30 000). */
92
131
  ttl?: number;
93
- tags?: string[];
132
+ tags?: string[] | string;
94
133
  bucket?: string;
95
134
  }
96
135
 
@@ -101,8 +140,32 @@ export interface OKDBListJobsOptions {
101
140
  tag?: string | null;
102
141
  sort?: 'when' | 'priority';
103
142
  direction?: 'asc' | 'desc';
143
+ /** 1–1000, default 50. */
104
144
  limit?: number;
105
- cursor?: OKDBIndexKey | null;
145
+ /**
146
+ * Opaque string from the previous page's `cursor` (exclusive: the next page starts after
147
+ * that row). Bound to the type/status/sort it was issued for — reusing it with a different
148
+ * filter, or passing an old index-key array cursor, throws BAD_PARAM.
149
+ */
150
+ cursor?: string | null;
151
+ }
152
+
153
+ /** Fields accepted by `updateJob`. `payload: undefined` removes the payload. */
154
+ export interface OKDBUpdateJobPatch {
155
+ type?: string;
156
+ when?: number;
157
+ priority?: number;
158
+ tags?: string[] | string;
159
+ bucket?: string | null;
160
+ bucket_tokens?: number;
161
+ buckets?: OKDBJobBucket[] | null;
162
+ cron?: string | null;
163
+ max_tries?: number | null;
164
+ retry_delay?: number;
165
+ backoff_multiplier?: number;
166
+ status_message?: string | null;
167
+ progress?: string | null;
168
+ payload?: unknown;
106
169
  }
107
170
 
108
171
  export interface OKDBAddBucketOptions {
@@ -123,76 +186,207 @@ export interface OKDBQueueTransaction {
123
186
  put(type: string, key: string | number, value: unknown): void;
124
187
  remove(type: string, key: string | number): void;
125
188
  update(type: string, key: string | number, value: unknown, opts?: unknown): void;
126
- commit(): Promise<void>;
189
+ commit(): Promise<unknown>;
127
190
  }
128
191
 
129
- export interface OKDBQueueWorker {
130
- stop(timeout?: number): Promise<void>;
192
+ export type OKDBJobLogLevel = 'debug' | 'info' | 'warn' | 'error';
193
+
194
+ /** Input to `appendJobLog` / `ctx.log`: a message string or an entry object. */
195
+ export type OKDBJobLogInput =
196
+ string | { message: string; level?: OKDBJobLogLevel; fields?: Record<string, unknown> | null };
197
+
198
+ export interface OKDBJobLogEntry {
199
+ level: OKDBJobLogLevel;
200
+ message: string;
201
+ fields: Record<string, unknown> | null;
202
+ ts: number;
203
+ }
204
+
205
+ /** Context passed to a `process()` handler. None of its methods reject. */
206
+ export interface OKDBQueueHandlerContext {
207
+ /** The root OKDB instance. */
208
+ okdb: OKDB;
209
+ /** The claimed job record (includes `payload`). */
210
+ job: OKDBJob;
211
+ jobId: string;
212
+ /**
213
+ * Cooperative cancellation. Aborted when the job is cancelled (`reason.code`
214
+ * `'JOB_CANCELLED'`), its claim is lost — removed, reclaimed after expiry, completed
215
+ * elsewhere (`'CLAIM_LOST'`; same-process changes abort at once, others at the next
216
+ * heartbeat) — or `stop(timeout)` runs out of time (`'WORKER_STOPPING'`). `reason` is an
217
+ * OKDBError. okdb never kills a handler: check the signal / pass it to fetch & co. and return
218
+ * or throw promptly. After a JOB_CANCELLED / CLAIM_LOST abort the outcome is ignored.
219
+ */
220
+ signal: AbortSignal;
221
+ /** Extend the claim by the TTL the job was claimed with; a lost claim aborts `signal`. */
222
+ heartbeat(): Promise<OKDBJob | void>;
223
+ /** Set the job's `progress` field. */
224
+ markProgress(message: string): Promise<OKDBJob | void>;
225
+ /** Append a log line to the current attempt. */
226
+ log(messageOrEntry: OKDBJobLogInput, level?: OKDBJobLogLevel): Promise<{ attempt: number; seq: number } | void>;
227
+ }
228
+
229
+ /** Return value is stored as the job's `result` (JSON-serializable, ≤ 16 KB); a throw fails the attempt. */
230
+ export type OKDBQueueHandler<TPayload = unknown> = (payload: TPayload, ctx: OKDBQueueHandlerContext) => unknown;
231
+
232
+ /** Per-type knobs, shared by the single form's options and each pool lane. */
233
+ export interface OKDBQueueLaneOptions extends OKDBClaimOptions {
234
+ /** Keep the claim alive while the handler runs (default true; every ttl/3, min 1 s). */
235
+ autoHeartbeat?: boolean;
236
+ /** Called once a job fails with no retries left. */
237
+ onPermanentFail?: (job: OKDBJob, err: unknown) => unknown;
131
238
  }
132
239
 
133
- export interface OKDBQueueSpawnedWorker {
240
+ /** Pool knobs shared by every lane of one consumer. */
241
+ export interface OKDBQueuePoolOptions {
242
+ /** Parallel lanes across ALL entries (default 1) — the process-wide cap for this pool. */
243
+ concurrency?: number;
244
+ /** Caps the idle backstop in ms (wake is event-driven) and spreads lane start-up (default 1000). */
245
+ pollInterval?: number;
246
+ /** Consulted before every claim sweep; false (or a throw) = don't claim. E.g. `() => db.pressure().score < 1`. */
247
+ admission?: () => boolean | Promise<boolean>;
248
+ /** ms between admission rechecks while gated (default 500). */
249
+ admissionInterval?: number;
250
+ }
251
+
252
+ /** Options of the single form `process(type, handler, options)` — lane and pool knobs in one object. */
253
+ export interface OKDBQueueProcessOptions extends OKDBQueueLaneOptions, OKDBQueuePoolOptions {}
254
+
255
+ /** One entry of the pool form `process([entry, …], poolOptions)`. */
256
+ export interface OKDBQueuePoolLane<TPayload = unknown> extends OKDBQueueLaneOptions {
257
+ type: string;
258
+ handler: OKDBQueueHandler<TPayload>;
259
+ /** Claim-sweep bias (int 1–32, default 1): weight 3 gets ~3× the first-claim attempts of weight 1. */
260
+ weight?: number;
261
+ }
262
+
263
+ /** Handle returned by `process()`. */
264
+ export interface OKDBQueueConsumer {
265
+ /** The type, or comma-joined types for a pool. */
266
+ readonly type: string;
267
+ readonly running: boolean;
268
+ /**
269
+ * Stop claiming and wait up to `timeout` ms (default 30 000) for in-flight handlers. Handlers
270
+ * still running then have `ctx.signal` aborted (`'WORKER_STOPPING'`) but KEEP their claim —
271
+ * never handed to another consumer while running. When one settles its job is completed
272
+ * (resolved) or released to pending without burning a try (threw). If the process exits
273
+ * first, reconcile reclaims the job (at-least-once).
274
+ */
134
275
  stop(timeout?: number): Promise<void>;
276
+ /** `stop(0)`. */
277
+ kill(): Promise<void>;
135
278
  }
136
279
 
280
+ /** Event names emitted on the root `okdb.events`. */
281
+ export type OKDBQueueEventName =
282
+ | 'queue:enqueued'
283
+ | 'queue:done'
284
+ | 'queue:failed'
285
+ | 'queue:retry'
286
+ /** A cron run ended (done / failed / timeout) and the job is pending for its next occurrence. */
287
+ | 'queue:rescheduled'
288
+ | 'queue:removed'
289
+ | 'queue:reconciled'
290
+ | 'queue:clear-progress'
291
+ | 'queue:clear-done'
292
+ | 'queue:log';
293
+
294
+ /**
295
+ * Durable job queue (per env). okdb coordinates — CAS claim = exactly one consumer,
296
+ * at-least-once — and handlers run wherever `process()` is called.
297
+ *
298
+ * Removed: worker(), spawn() — throw QUEUE_WORKER_REMOVED; use process()
299
+ */
137
300
  export declare class OKDBQueue {
301
+ /** Unused: queue events (`OKDBQueueEventName`) are emitted on the root `okdb.events`. */
138
302
  events: EventEmitter;
139
303
 
140
304
  // ── Core job lifecycle ────────────────────────────────────────────────────
305
+ /** Resolves to the new job id (or the existing id on an idempotency hit). */
141
306
  enqueue(type: string, payload: unknown, options?: OKDBEnqueueOptions): Promise<string>;
142
307
  claim(type: string, options?: OKDBClaimOptions): Promise<OKDBJob | null>;
143
- worker(
308
+
309
+ /** In-loop consumer for one type. */
310
+ process<TPayload = unknown>(
144
311
  type: string,
145
- handler: (job: OKDBJob) => Promise<unknown> | unknown,
146
- options?: Record<string, unknown>,
147
- ): OKDBQueueWorker;
148
- spawn(type: string, modulePath: string, options?: Record<string, unknown>): Promise<OKDBQueueSpawnedWorker>;
312
+ handler: OKDBQueueHandler<TPayload>,
313
+ options?: OKDBQueueProcessOptions,
314
+ ): OKDBQueueConsumer;
315
+ /** One lane pool over several types (shared concurrency cap, weighted fairness, admission gate). */
316
+ process(entries: OKDBQueuePoolLane<any>[], poolOptions?: OKDBQueuePoolOptions): OKDBQueueConsumer;
317
+
318
+ /** Stop every consumer started by `process()` on this queue. */
149
319
  stopAll(timeout?: number): Promise<void>;
150
320
 
151
321
  // ── Job retrieval / management ────────────────────────────────────────────
152
322
  getJob(id: string): Promise<OKDBJob | null>;
153
- updateJob(
154
- id: string,
155
- patch: Partial<OKDBJob & { payload: unknown }>,
156
- options?: { txn?: OKDBQueueTransaction },
157
- ): Promise<OKDBJob>;
323
+ updateJob(id: string, patch: OKDBUpdateJobPatch, options?: { txn?: OKDBQueueTransaction }): Promise<OKDBJob>;
158
324
  removeJob(id: string, options?: { txn?: OKDBQueueTransaction }): Promise<boolean>;
325
+ /** Reset to pending with `tries: 0`, clearing result and logs. */
159
326
  retryJob(id: string): Promise<OKDBJob>;
327
+ /**
328
+ * Pending/running → failed with `status_code: 'cancelled'`; otherwise throws BAD_STATE.
329
+ * Releases the idempotency key, stops a cron series, and aborts a running handler's `ctx.signal`.
330
+ */
160
331
  cancelJob(id: string): Promise<OKDBJob>;
161
- list(options?: OKDBListJobsOptions): Promise<{ items: OKDBJob[]; cursor: OKDBIndexKey | null }>;
162
-
163
- // ── Worker callbacks ──────────────────────────────────────────────────────
164
- heartbeat(jobId: string, claimId: string, ttl?: number | null): Promise<OKDBJob>;
165
- markJobHeartbeat(jobId: string, claimId: string, ttl?: number | null): Promise<OKDBJob>;
166
- markJobProgress(jobId: string, claimId: string, message: string): Promise<OKDBJob>;
167
- markJobComplete(jobId: string, claimId: string, result?: unknown): Promise<OKDBJob>;
168
- completeJob(jobId: string, claimId: string, result?: unknown): Promise<OKDBJob>;
332
+ /** Items are index entries (`value` is the job, without payload). `cursor` is null on the last page. */
333
+ list(options?: OKDBListJobsOptions): Promise<{ items: OKDBIndexEntry<OKDBJob>[]; cursor: string | null }>;
334
+
335
+ // ── Worker callbacks (manual claim flow) ─────────────────────────────────
336
+ /** Extends the claim. A lost claim rejects: NOT_FOUND (removed), INVALID_STATE (not running), CLAIM_MISMATCH (re-claimed). */
337
+ markJobHeartbeat(jobId: string, claimId: string, ttl?: number | null): Promise<OKDBJob | null>;
338
+ /** Alias of markJobHeartbeat. */
339
+ heartbeat(jobId: string, claimId: string, ttl?: number | null): Promise<OKDBJob | null>;
340
+ markJobProgress(jobId: string, claimId: string, message: string): Promise<OKDBJob | null>;
341
+ markJobComplete(jobId: string, claimId: string, result?: unknown): Promise<OKDBJob | null>;
342
+ /** Alias of markJobComplete. */
343
+ completeJob(jobId: string, claimId: string, result?: unknown): Promise<OKDBJob | null>;
169
344
  markJobFail(
170
345
  jobId: string,
171
346
  claimId: string,
172
- err: Error | unknown,
347
+ err: unknown,
173
348
  code?: string,
174
- ): Promise<{ permanentlyFailed: boolean; job: OKDBJob }>;
349
+ ): Promise<{ permanentlyFailed: boolean; job: OKDBJob | null }>;
350
+ /** Alias of markJobFail. */
175
351
  failJob(
176
352
  jobId: string,
177
353
  claimId: string,
178
- err: Error | unknown,
354
+ err: unknown,
179
355
  code?: string,
180
- ): Promise<{ permanentlyFailed: boolean; job: OKDBJob }>;
356
+ ): Promise<{ permanentlyFailed: boolean; job: OKDBJob | null }>;
357
+ /** Running → pending. Returns false if the job isn't running under this claim. */
181
358
  releaseClaim(
182
359
  jobId: string,
183
360
  claimId: string,
184
361
  options?: { when?: number; statusCode?: string; keepTry?: boolean },
185
362
  ): Promise<boolean>;
186
363
 
187
- // ── Bulk operations ───────────────────────────────────────────────────────
364
+ // ── Job logs ──────────────────────────────────────────────────────────────
365
+ /** Append to a running job's current attempt; `claimId: null` skips the claim check. */
366
+ appendJobLog(
367
+ jobId: string,
368
+ claimId: string | null,
369
+ entry: OKDBJobLogInput,
370
+ ): Promise<{ attempt: number; seq: number }>;
371
+ /** Chronological, paginated; `cursor` is the opaque string from the previous page. */
372
+ getJobLogs(
373
+ jobId: string,
374
+ options?: { attempt?: number; limit?: number; cursor?: string | null },
375
+ ): Promise<{ items: Array<{ key: [string, number, number]; value: OKDBJobLogEntry }>; cursor: string | null }>;
376
+
377
+ // ── Bulk operations (resolve to the count affected) ──────────────────────
188
378
  clearDone(type?: string | null, limit?: number): Promise<number>;
189
379
  clearFailed(type?: string | null, limit?: number): Promise<number>;
380
+ /** Deletes running jobs whose claim has expired. */
190
381
  clearStuck(type?: string | null, limit?: number): Promise<number>;
191
382
  retryFailed(type?: string | null, limit?: number): Promise<number>;
192
383
 
193
384
  // ── Token buckets ─────────────────────────────────────────────────────────
194
385
  addBucket(id: string, options?: OKDBAddBucketOptions): Promise<void>;
195
- updateBucket(id: string, patch: Partial<OKDBJobBucketRecord>): Promise<void>;
386
+ updateBucket(
387
+ id: string,
388
+ patch: Partial<Pick<OKDBJobBucketRecord, 'capacity' | 'tokens' | 'refill_amount' | 'refill_every'>>,
389
+ ): Promise<void>;
196
390
  removeBucket(id: string): Promise<void>;
197
391
  getBucket(id: string): OKDBJobBucketRecord | null;
198
392
  tryClaimTokens(bucketId: string, tokens?: number): Promise<boolean>;
@@ -204,8 +398,10 @@ export declare class OKDBQueue {
204
398
  removeJobType(id: string): Promise<boolean>;
205
399
  pauseJobType(id: string): Promise<OKDBJobType>;
206
400
  resumeJobType(id: string): Promise<OKDBJobType>;
401
+ /** Draining: enqueue throws TYPE_DRAINING; existing jobs still run. */
207
402
  drainJobType(id: string): Promise<OKDBJobType>;
208
403
  setJobTypeSchema(id: string, definition: unknown, enforce?: boolean): Promise<OKDBJobType>;
209
404
  removeJobTypeSchema(id: string): Promise<OKDBJobType>;
405
+ /** Up to `limit` (≤ 100) recent payloads of a type. */
210
406
  samplePayloads(type: string, limit?: number): Promise<unknown[]>;
211
407
  }
@@ -1,34 +1,197 @@
1
+ /**
2
+ * A node record as stored in the replicated `~sync_nodes` type (in `~system`).
3
+ * `getSelfNode()` returns this node's record; peers carry the same shape.
4
+ */
1
5
  export interface OKDBSyncNode {
2
6
  id: string;
3
7
  address: string | null;
4
8
  meta: Record<string, unknown>;
9
+ /** Normalized node tags (used for engine affinity). */
5
10
  tags: string[];
6
- updated: number;
7
- publicKey?: string;
8
- }
9
-
10
- export interface OKDBSyncLink {
11
- id: string;
12
- nodeA: string;
13
- nodeB: string;
14
- createdAt: number;
11
+ updated: number | null;
12
+ /** Ed25519 public key peers use to verify this node's signed sync requests. */
13
+ publicKey?: string | null;
14
+ created?: number;
15
+ joined?: number;
15
16
  [key: string]: unknown;
16
17
  }
17
18
 
19
+ /** Returned by `db.sync.info()`. */
18
20
  export interface OKDBSyncInfo {
19
21
  node_id: string;
22
+ /** Local clock (0 before open). */
20
23
  clock: number;
21
24
  auto_reconcile: boolean;
25
+ /** Number of known peers (self excluded). */
22
26
  peers: number;
27
+ /** Peer ids with a data-plane reconcile currently in flight. */
23
28
  reconciling: string[];
24
29
  }
25
30
 
31
+ /** Link direction, canonical relative to the sorted (node_lo, node_hi) pair. */
32
+ export type OKDBSyncLinkDirection = 'both' | 'lo_to_hi' | 'hi_to_lo';
33
+
34
+ /** A data-link record (replicated `~sync_links` type). */
35
+ export interface OKDBSyncLink {
36
+ /** Canonical id `"<lo>:<hi>"` — (A,B) and (B,A) map to the same link. */
37
+ id: string;
38
+ node_lo: string;
39
+ node_hi: string;
40
+ direction: OKDBSyncLinkDirection;
41
+ /** Env names the link replicates; null = all user envs. */
42
+ envs: string[] | null;
43
+ enabled: boolean;
44
+ created: number;
45
+ updated: number;
46
+ }
47
+
48
+ export interface OKDBSyncLinkOptions {
49
+ /** Default 'both'. */
50
+ direction?: OKDBSyncLinkDirection;
51
+ /** Env names to replicate; null (default) = all user envs. */
52
+ envs?: string[] | null;
53
+ /** Default true. */
54
+ enabled?: boolean;
55
+ }
56
+
57
+ /** One entry of `db.sync.peers()` — the peer's node record merged with local (non-replicated) progress. */
58
+ export interface OKDBSyncPeer {
59
+ peer_id: string;
60
+ address: string | null;
61
+ meta: Record<string, unknown>;
62
+ tags: string[];
63
+ node_updated: number | null;
64
+ link: { direction: OKDBSyncLinkDirection; envs: string[] | null; enabled: boolean } | null;
65
+ status: 'idle' | 'reconciling' | 'error' | (string & {});
66
+ /** Last pulled `default`-env clock. */
67
+ clock: number;
68
+ /** Last pulled clock per env. */
69
+ clocks?: Record<string, number>;
70
+ last_seen: number | null;
71
+ last_error: string | null;
72
+ last_error_at?: number;
73
+ created?: number;
74
+ updated?: number;
75
+ }
76
+
77
+ export interface OKDBSyncJoinOptions {
78
+ /** Bearer token accepted by the remote node (one-time handshake credential). */
79
+ token?: string;
80
+ /** Username for the remote's /auth/login (exchanged for a token). */
81
+ username?: string;
82
+ password?: string;
83
+ /** Patch applied to this node's own record before joining (see `patchSelf`). */
84
+ my_info?: Record<string, unknown>;
85
+ /** Create a bidirectional data link to the remote. Default true. */
86
+ dataLink?: boolean;
87
+ }
88
+
89
+ /** A change record inside a sync delta. */
90
+ export interface OKDBSyncChange {
91
+ type: string;
92
+ key: unknown;
93
+ action: string;
94
+ clock: number;
95
+ timestamp: number;
96
+ origin?: string;
97
+ /** Present for puts. */
98
+ value?: unknown;
99
+ version?: number;
100
+ /** Env the change belongs to. */
101
+ _env: string;
102
+ [key: string]: unknown;
103
+ }
104
+
105
+ /** Returned by `db.sync.calculateDelta()`. */
106
+ export interface OKDBSyncDelta {
107
+ /** The `default` env's clock (0 when not included). */
108
+ clock: number;
109
+ /** Current clock per included env. */
110
+ clocks: Record<string, number>;
111
+ changes: OKDBSyncChange[];
112
+ /**
113
+ * With `peer`: requested envs the link does not let this node send to that peer — omitted
114
+ * from `changes`/`clocks`. (The HTTP response only carries it when non-empty.)
115
+ */
116
+ denied: string[];
117
+ }
118
+
119
+ export interface OKDBSyncPeerAck {
120
+ peer_id: string;
121
+ /** Highest clock the peer has acknowledged, per env. */
122
+ envs: Record<string, number>;
123
+ last_seen: number | null;
124
+ since_ms: number;
125
+ stale: boolean;
126
+ }
127
+
128
+ export interface OKDBSyncGcResult {
129
+ removed: number;
130
+ durationMs: number;
131
+ /** Entries removed per env. */
132
+ byEnv: Record<string, number>;
133
+ /** Set when the sweep was skipped (passive instance, or another process is sweeping). */
134
+ skipped?: 'passive' | 'peer-sweeping';
135
+ }
136
+
137
+ export interface OKDBSyncGcStatus {
138
+ peers: OKDBSyncPeerAck[];
139
+ envs: Array<{ env: string; currentClock: number; gcHorizon: number; entryCount: number }>;
140
+ running: boolean;
141
+ peerStalenessLimitMs: number;
142
+ }
143
+
144
+ /** Watermark-based changelog GC (`db.sync.gc`). Sweeps automatically on processor-role instances. */
145
+ export declare class OKDBSyncGC {
146
+ /** Changelog entries strictly below this clock are safe to prune for the env; 0 = don't prune. */
147
+ getGcHorizon(envName: string): number;
148
+ getPeerAcks(): OKDBSyncPeerAck[];
149
+ /** Run a sweep now (1-of-N across processes; skipped on a passive instance). */
150
+ runGc(): Promise<OKDBSyncGcResult>;
151
+ /** Reset a peer's ACK watermarks to 0 so the log is retained for a full resync. */
152
+ forceResync(peer_id: string): Promise<void>;
153
+ getStatus(): OKDBSyncGcStatus;
154
+ }
155
+
156
+ /**
157
+ * Peer-to-peer LWW replication (`db.sync`). Always attached; configured by the
158
+ * `sync` constructor option (`address`, `token`, `delta_limit`, `auto_reconcile`, …).
159
+ * Removed: per-env `createEnvironment(name, { sync: false })` throws `SYNC_OPTION_REMOVED`
160
+ * (every user env replicates; internal `~` envs never do).
161
+ */
26
162
  export declare class OKDBSync {
163
+ /** Changelog GC controller. */
164
+ readonly gc: OKDBSyncGC;
165
+
27
166
  info(): OKDBSyncInfo;
167
+ /** This node's `~sync_nodes` record (a synthetic one before open). */
28
168
  getSelfNode(): OKDBSyncNode;
29
- addPeer(address: string, options?: Record<string, unknown>): Promise<void>;
30
- removePeer(nodeId: string): Promise<void>;
31
- listPeers(): OKDBSyncNode[];
32
- reconcile(nodeId?: string): Promise<void>;
33
- stop(): void;
169
+ /** Known peers (self excluded) with local reconcile progress. */
170
+ peers(): OKDBSyncPeer[];
171
+ /**
172
+ * Join a remote node: exchange node records/public keys, optionally create a data link,
173
+ * then pull an initial delta. Requires the `sync.address` option (else `SYNC_NO_ADDRESS`).
174
+ */
175
+ join(address: string, options?: OKDBSyncJoinOptions): Promise<void>;
176
+ /** Merge a patch into this node's own record (e.g. `{ tags, meta }`); returns the new record. */
177
+ patchSelf(patch: Record<string, unknown>): Promise<OKDBSyncNode>;
178
+ /** Reconcile with all peers now. No-op without a sync address. */
179
+ reconcile(): Promise<void>;
180
+ /** Reconcile with one peer now. No-op without a sync address. */
181
+ reconcilePeer(peer_id: string): Promise<void>;
182
+ listLinks(): OKDBSyncLink[];
183
+ /** Create or update the data link between this node and `peer_id`. */
184
+ upsertLink(peer_id: string, options?: OKDBSyncLinkOptions): Promise<OKDBSyncLink>;
185
+ removeLink(peer_id: string): Promise<void>;
186
+ /**
187
+ * Low-level: compute the outbound delta after `from_clocks` (per env). `envs: null` = all
188
+ * changelog-enabled envs. This is what the `/api/sync/delta` endpoint serves. `peer` (the
189
+ * endpoint passes the signed requester's node id) enforces that peer's link scope: only
190
+ * `~system` plus the data envs the link lets this node send it (all envs while no link exists
191
+ * anywhere — legacy full mesh).
192
+ */
193
+ calculateDelta(
194
+ from_clocks?: Record<string, number>,
195
+ options?: { limit?: number; envs?: string[] | null; peer?: string | null },
196
+ ): Promise<OKDBSyncDelta>;
34
197
  }