@reddb-io/cli 1.36.11 → 1.38.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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/sdk",
3
- "version": "1.36.11",
3
+ "version": "1.38.0",
4
4
  "description": "Official embedded RedDB SDK — launches a local red binary over stdio JSON-RPC. The binary arrives as a per-platform optionalDependency — no install script. Use @reddb-io/client for remote HTTP, gRPC, and RedWire.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -14,6 +14,11 @@ import { RedDBError } from './protocol.js'
14
14
  const UNSUPPORTED_TRANSPORTS = new Set(['embedded'])
15
15
 
16
16
  export class CacheClient {
17
+ static [Symbol.hasInstance](value) {
18
+ const candidate = value?.__reddbClientInstance ?? value
19
+ return this.prototype.isPrototypeOf(candidate)
20
+ }
21
+
17
22
  /**
18
23
  * @param {{ call: Function }} client
19
24
  * @param {string} [transport] Underlying transport label (e.g. 'http',
@@ -25,6 +30,13 @@ export class CacheClient {
25
30
  this._transport = transport ?? null
26
31
  }
27
32
 
33
+ scope(namespace) {
34
+ if (typeof namespace !== 'string' || namespace.length === 0) {
35
+ throw new TypeError('cache(namespace) requires a non-empty namespace')
36
+ }
37
+ return new ScopedCacheClient(this, namespace)
38
+ }
39
+
28
40
  _guard(method) {
29
41
  if (this._transport && UNSUPPORTED_TRANSPORTS.has(this._transport)) {
30
42
  throw new RedDBError(
@@ -129,6 +141,20 @@ export class CacheClient {
129
141
  }
130
142
  }
131
143
 
144
+ export class ScopedCacheClient {
145
+ constructor(cacheClient, namespace) {
146
+ this.cacheClient = cacheClient
147
+ this.namespace = namespace
148
+ }
149
+ get(key) { return this.cacheClient.get(this.namespace, key) }
150
+ put(key, value, options = {}) { return this.cacheClient.put(this.namespace, key, value, options) }
151
+ exists(key) { return this.cacheClient.exists(this.namespace, key) }
152
+ invalidate(key) { return this.cacheClient.invalidate(this.namespace, key) }
153
+ invalidatePrefix(prefix) { return this.cacheClient.invalidatePrefix(this.namespace, prefix) }
154
+ invalidateTags(tags) { return this.cacheClient.invalidateTags(this.namespace, tags) }
155
+ flush() { return this.cacheClient.flushNamespace(this.namespace) }
156
+ }
157
+
132
158
  // ---------------------------------------------------------------------------
133
159
  // Helpers
134
160
  // ---------------------------------------------------------------------------
@@ -32,9 +32,9 @@ import { VaultClient } from './vault.js'
32
32
  import { TypedQueryBuilder, collectionExists, listCollections } from './db-helpers.js'
33
33
 
34
34
  export { RedDBError }
35
- export { CacheClient } from './cache.js'
35
+ export { CacheClient, ScopedCacheClient } from './cache.js'
36
36
  export { KvClient } from './kv.js'
37
- export { QueueClient } from './queue.js'
37
+ export { QueueClient, ScopedQueueClient, QueueConsumer } from './queue.js'
38
38
  export { DocumentClient } from './documents.js'
39
39
  export { ConfigClient } from './config.js'
40
40
  export { VaultClient } from './vault.js'
@@ -57,6 +57,17 @@ const MIN_I64 = -(1n << 63n)
57
57
  const MAX_I64 = (1n << 63n) - 1n
58
58
  const MAX_U64 = (1n << 64n) - 1n
59
59
 
60
+ function callableClient(instance, createScope) {
61
+ const callable = (...args) => createScope(...args)
62
+ Object.defineProperty(callable, '__reddbClientInstance', { value: instance })
63
+ Object.assign(callable, instance)
64
+ for (const name of Object.getOwnPropertyNames(Object.getPrototypeOf(instance))) {
65
+ if (name === 'constructor' || typeof instance[name] !== 'function') continue
66
+ callable[name] = instance[name].bind(instance)
67
+ }
68
+ return callable
69
+ }
70
+
60
71
  /**
61
72
  * Connect to a RedDB instance.
62
73
  *
@@ -461,14 +472,21 @@ export class RedDB {
461
472
  this.client = client
462
473
  this.transport = opts.transport ?? null
463
474
  this.helperSpecVersion = HELPER_SPEC_VERSION
464
- this.cache = new CacheClient(client, this.transport)
465
- this.queue = new QueueClient(client)
475
+ const cacheClient = new CacheClient(client, this.transport)
476
+ this.cache = callableClient(cacheClient, (namespace) => cacheClient.scope(namespace))
477
+ const queueClient = new QueueClient(client)
478
+ this.queue = callableClient(queueClient, (queue) => queueClient.scope(queue))
466
479
  // Spec §6: the canonical namespace is the plural `queues`. `queue` is kept
467
480
  // as a back-compat alias to the same handle.
468
481
  this.queues = this.queue
469
482
  this.documents = new DocumentClient(this)
470
483
  const defaultKv = new KvClient(client)
471
- this.kv = Object.assign((collection = 'kv_default') => new KvClient(client, collection), {
484
+ this.kv = Object.assign((collection) => {
485
+ if (typeof collection !== 'string' || collection.length === 0) {
486
+ throw new TypeError('kv(collection) requires a non-empty collection')
487
+ }
488
+ return new KvClient(client, collection)
489
+ }, {
472
490
  put: defaultKv.put.bind(defaultKv),
473
491
  invalidateTags: defaultKv.invalidateTags.bind(defaultKv),
474
492
  watch: defaultKv.watch.bind(defaultKv),
@@ -476,6 +494,12 @@ export class RedDB {
476
494
  })
477
495
  this.config = (collection = 'red.config') => new ConfigClient(client, collection)
478
496
  this.vault = (collection = 'red.vault') => new VaultClient(client, collection)
497
+ this.secrets = (collection) => {
498
+ if (typeof collection !== 'string' || collection.length === 0) {
499
+ throw new TypeError('secrets(collection) requires a non-empty collection')
500
+ }
501
+ return new VaultClient(client, collection)
502
+ }
479
503
  this.inTransaction = false
480
504
  }
481
505
 
@@ -1,10 +1,19 @@
1
1
  import { RedDBError } from './protocol.js'
2
2
 
3
3
  export class QueueClient {
4
+ static [Symbol.hasInstance](value) {
5
+ const candidate = value?.__reddbClientInstance ?? value
6
+ return this.prototype.isPrototypeOf(candidate)
7
+ }
8
+
4
9
  constructor(client) {
5
10
  this.client = client
6
11
  }
7
12
 
13
+ scope(queue) {
14
+ return new ScopedQueueClient(this, requiredQueueName(queue))
15
+ }
16
+
8
17
  // Spec §6.1 `queues.create`: idempotent (CREATE QUEUE IF NOT EXISTS) so
9
18
  // conformance fixtures can prime a queue the same way the Rust/Go harnesses do.
10
19
  create(queue) {
@@ -56,10 +65,356 @@ export class QueueClient {
56
65
  // default. Server-side cancellation, transport cancellation, and cap
57
66
  // rejection surface as RedDBErrors from the transport path.
58
67
  async readWait(queue, consumer, options = {}) {
68
+ return queuePayloads({ rows: await this.readWaitEntries(queue, consumer, options) })
69
+ }
70
+
71
+ async readWaitEntries(queue, consumer, options = {}) {
59
72
  const sql = buildQueueReadWaitSql(queue, consumer, options)
60
73
  const result = await this.client.call('query', { sql })
61
- return queuePayloads(result)
74
+ return Array.isArray(result?.rows) ? result.rows : []
75
+ }
76
+ }
77
+
78
+ export class ScopedQueueClient {
79
+ constructor(queueClient, queue) {
80
+ this.queueClient = queueClient
81
+ this.name = queue
82
+ }
83
+
84
+ create() { return this.queueClient.create(this.name) }
85
+ push(value, options = {}) { return this.queueClient.push(this.name, value, options) }
86
+ pop(count) { return this.queueClient.pop(this.name, count) }
87
+ peek(count) { return this.queueClient.peek(this.name, count) }
88
+ len() { return this.queueClient.len(this.name) }
89
+ purge() { return this.queueClient.purge(this.name) }
90
+ readWait(consumer, options = {}) {
91
+ return this.queueClient.readWait(this.name, consumer, options)
92
+ }
93
+ readWaitEntries(consumer, options = {}) {
94
+ return this.queueClient.readWaitEntries(this.name, consumer, options)
95
+ }
96
+ ack(deliveryId) {
97
+ return this.queueClient.client.call('query', {
98
+ sql: `QUEUE ACK ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}`,
99
+ })
100
+ }
101
+ nack(deliveryId, options = {}) {
102
+ const delay = queueRetryDelay(options.delay)
103
+ return this.queueClient.client.call('query', {
104
+ sql: `QUEUE NACK ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}${delay}`,
105
+ })
106
+ }
107
+ extend(deliveryId) {
108
+ return this.queueClient.client.call('query', {
109
+ sql: `QUEUE EXTEND ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}`,
110
+ })
111
+ }
112
+ consumer(options) { return new QueueConsumer(this, options) }
113
+ }
114
+
115
+ export class QueueConsumer {
116
+ constructor(queue, options = {}) {
117
+ if (!(queue instanceof ScopedQueueClient)) throw new TypeError('QueueConsumer requires a scoped queue')
118
+ if (typeof options.handleMessage !== 'function') {
119
+ throw new TypeError('queue consumer requires handleMessage(message)')
120
+ }
121
+ this.queue = queue
122
+ this.consumerName = requiredQueueName(options.consumer, 'consumer')
123
+ this.group = options.group == null ? null : requiredQueueName(options.group, 'group')
124
+ this.waitMs = options.waitMs ?? 30_000
125
+ if (!Number.isInteger(this.waitMs) || this.waitMs <= 0) {
126
+ throw new TypeError('queue consumer waitMs must be a positive integer')
127
+ }
128
+ this.handleMessage = options.handleMessage
129
+ this.onError = options.onError ?? null
130
+ if (this.onError != null && typeof this.onError !== 'function') {
131
+ throw new TypeError('queue consumer onError must be a function')
132
+ }
133
+ this.retryDelay = options.retryDelay ?? null
134
+ queueRetryDelay(this.retryDelay)
135
+ this.concurrency = options.concurrency ?? 1
136
+ if (!Number.isInteger(this.concurrency) || this.concurrency < 1 || this.concurrency > 128) {
137
+ throw new TypeError('queue consumer concurrency must be an integer between 1 and 128')
138
+ }
139
+ this.receiveBackoff = receiveBackoffOptions(options.receiveBackoff)
140
+ this.leaseHeartbeatMs = optionalPositiveInteger(
141
+ options.leaseHeartbeatMs,
142
+ 'queue consumer leaseHeartbeatMs',
143
+ )
144
+ this.handlerTimeoutMs = optionalPositiveInteger(
145
+ options.handlerTimeoutMs,
146
+ 'queue consumer handlerTimeoutMs',
147
+ )
148
+ this.state = 'idle'
149
+ this.paused = false
150
+ this.stopRequested = false
151
+ this.inFlight = 0
152
+ this.loopPromise = null
153
+ this.pauseWaiters = new Set()
154
+ this.sleepWaiters = new Set()
155
+ }
156
+
157
+ get status() {
158
+ return {
159
+ state: this.state,
160
+ isRunning: this.state === 'running' || this.state === 'paused',
161
+ isPaused: this.paused,
162
+ inFlight: this.inFlight,
163
+ concurrency: this.concurrency,
164
+ }
165
+ }
166
+ start() {
167
+ if (this.state === 'running' || this.state === 'paused' || this.state === 'stopping') return this
168
+ this.stopRequested = false
169
+ this.paused = false
170
+ this.state = 'running'
171
+ this.loopPromise = this.#run().then(
172
+ () => { this.state = 'stopped' },
173
+ (error) => {
174
+ this.state = 'failed'
175
+ throw error
176
+ },
177
+ )
178
+ return this
179
+ }
180
+ stop() {
181
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') {
182
+ return this.finished()
183
+ }
184
+ this.requestStop()
185
+ return this.finished()
186
+ }
187
+
188
+ requestStop() {
189
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') return this
190
+ this.stopRequested = true
191
+ this.paused = false
192
+ this.state = 'stopping'
193
+ this.#wake(this.pauseWaiters)
194
+ this.#wake(this.sleepWaiters)
195
+ return this
196
+ }
197
+ pause() {
198
+ if (this.state !== 'running') return this
199
+ this.paused = true
200
+ this.state = 'paused'
201
+ return this
202
+ }
203
+ resume() {
204
+ if (this.state !== 'paused') return this
205
+ this.paused = false
206
+ this.state = 'running'
207
+ this.#wake(this.pauseWaiters)
208
+ return this
209
+ }
210
+ finished() { return this.loopPromise ?? Promise.resolve() }
211
+
212
+ async #run() {
213
+ let firstError = null
214
+ const lanes = Array.from({ length: this.concurrency }, () => this.#runLane().catch((error) => {
215
+ if (firstError == null) firstError = error
216
+ this.stopRequested = true
217
+ this.paused = false
218
+ this.#wake(this.pauseWaiters)
219
+ this.#wake(this.sleepWaiters)
220
+ }))
221
+ await Promise.all(lanes)
222
+ if (firstError != null) throw firstError
223
+ }
224
+
225
+ async #runLane() {
226
+ let receiveFailures = 0
227
+ while (!this.stopRequested) {
228
+ await this.#waitWhilePaused()
229
+ if (this.stopRequested) return
230
+ let entries
231
+ try {
232
+ entries = await this.queue.readWaitEntries(this.consumerName, {
233
+ group: this.group, count: 1, waitMs: this.waitMs,
234
+ })
235
+ } catch (error) {
236
+ if (this.stopRequested) return
237
+ await this.#reportError(error, null)
238
+ receiveFailures += 1
239
+ await this.#sleep(receiveBackoffDelay(this.receiveBackoff, receiveFailures))
240
+ continue
241
+ }
242
+ receiveFailures = 0
243
+ if (entries.length === 0) continue
244
+ const message = entries[0]
245
+ const deliveryId = message?.delivery_id
246
+ if (deliveryId == null || String(deliveryId).length === 0) {
247
+ await this.#reportError(
248
+ new RedDBError('INVALID_QUEUE_DELIVERY', 'queue delivery is missing delivery_id'),
249
+ message,
250
+ )
251
+ continue
252
+ }
253
+ await this.#processMessage(message, String(deliveryId))
254
+ }
255
+ }
256
+
257
+ async #processMessage(message, deliveryId) {
258
+ this.inFlight += 1
259
+ const controller = new AbortController()
260
+ let handlerError = null
261
+ let timeoutError = null
262
+ let leaseError = null
263
+ let handlerSettled = false
264
+ let finishHeartbeat
265
+ const heartbeatFinished = new Promise((resolve) => { finishHeartbeat = resolve })
266
+ let timeout = null
267
+ if (this.handlerTimeoutMs != null) {
268
+ timeout = setTimeout(() => {
269
+ timeoutError = new RedDBError(
270
+ 'QUEUE_HANDLER_TIMEOUT',
271
+ `queue handler exceeded ${this.handlerTimeoutMs}ms`,
272
+ )
273
+ controller.abort(timeoutError)
274
+ }, this.handlerTimeoutMs)
275
+ }
276
+ const heartbeat = this.#heartbeat(
277
+ deliveryId,
278
+ controller,
279
+ heartbeatFinished,
280
+ () => handlerSettled,
281
+ (error) => { leaseError = error },
282
+ )
283
+ try {
284
+ await this.handleMessage(message, {
285
+ signal: controller.signal,
286
+ deliveryId,
287
+ extendLease: () => this.queue.extend(deliveryId),
288
+ })
289
+ } catch (error) {
290
+ handlerError = error
291
+ } finally {
292
+ handlerSettled = true
293
+ finishHeartbeat()
294
+ if (timeout != null) clearTimeout(timeout)
295
+ await heartbeat
296
+ this.inFlight -= 1
297
+ }
298
+
299
+ if (leaseError != null) {
300
+ await this.#reportError(leaseError, message)
301
+ return
302
+ }
303
+ const processingError = timeoutError ?? handlerError
304
+ if (processingError != null) {
305
+ try {
306
+ await this.queue.nack(deliveryId, { delay: this.retryDelay })
307
+ } catch (nackError) {
308
+ if (nackError !== processingError && typeof processingError === 'object') {
309
+ processingError.nackError = nackError
310
+ }
311
+ }
312
+ await this.#reportError(processingError, message)
313
+ return
314
+ }
315
+ try {
316
+ await this.queue.ack(deliveryId)
317
+ } catch (error) {
318
+ await this.#reportError(error, message)
319
+ }
320
+ }
321
+
322
+ async #heartbeat(deliveryId, controller, finished, isSettled, setLeaseError) {
323
+ if (this.leaseHeartbeatMs == null) return
324
+ while (!isSettled()) {
325
+ await intervalOrFinished(this.leaseHeartbeatMs, finished)
326
+ if (isSettled()) return
327
+ try {
328
+ await this.queue.extend(deliveryId)
329
+ } catch (error) {
330
+ setLeaseError(error)
331
+ controller.abort(error)
332
+ return
333
+ }
334
+ }
335
+ }
336
+
337
+ async #waitWhilePaused() {
338
+ while (this.paused && !this.stopRequested) {
339
+ await new Promise((resolve) => { this.pauseWaiters.add(resolve) })
340
+ }
341
+ }
342
+
343
+ #sleep(milliseconds) {
344
+ if (milliseconds === 0 || this.stopRequested) return Promise.resolve()
345
+ return new Promise((resolve) => {
346
+ let timer
347
+ const done = () => {
348
+ clearTimeout(timer)
349
+ this.sleepWaiters.delete(done)
350
+ resolve()
351
+ }
352
+ timer = setTimeout(done, milliseconds)
353
+ this.sleepWaiters.add(done)
354
+ })
355
+ }
356
+
357
+ #wake(waiters) {
358
+ for (const resolve of [...waiters]) resolve()
359
+ waiters.clear()
360
+ }
361
+
362
+ async #reportError(error, message) {
363
+ if (this.onError != null) return this.onError(error, message)
364
+ throw error
365
+ }
366
+ }
367
+
368
+ function receiveBackoffOptions(value) {
369
+ if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
370
+ throw new TypeError('queue consumer receiveBackoff must be an object')
371
+ }
372
+ const options = value ?? {}
373
+ const result = {
374
+ initialMs: options.initialMs ?? 250,
375
+ maxMs: options.maxMs ?? 30_000,
376
+ multiplier: options.multiplier ?? 2,
377
+ jitter: options.jitter ?? true,
378
+ }
379
+ if (!Number.isInteger(result.initialMs) || result.initialMs <= 0) {
380
+ throw new TypeError('queue consumer receiveBackoff.initialMs must be a positive integer')
62
381
  }
382
+ if (!Number.isInteger(result.maxMs) || result.maxMs < result.initialMs) {
383
+ throw new TypeError('queue consumer receiveBackoff.maxMs must be an integer >= initialMs')
384
+ }
385
+ if (!Number.isFinite(result.multiplier) || result.multiplier < 1) {
386
+ throw new TypeError('queue consumer receiveBackoff.multiplier must be >= 1')
387
+ }
388
+ if (typeof result.jitter !== 'boolean') {
389
+ throw new TypeError('queue consumer receiveBackoff.jitter must be a boolean')
390
+ }
391
+ return result
392
+ }
393
+
394
+ function receiveBackoffDelay(options, failures) {
395
+ const unjittered = Math.min(
396
+ options.maxMs,
397
+ options.initialMs * (options.multiplier ** Math.max(0, failures - 1)),
398
+ )
399
+ return options.jitter ? Math.floor(Math.random() * (unjittered + 1)) : unjittered
400
+ }
401
+
402
+ function optionalPositiveInteger(value, name) {
403
+ if (value == null) return null
404
+ if (!Number.isInteger(value) || value <= 0) {
405
+ throw new TypeError(`${name} must be a positive integer`)
406
+ }
407
+ return value
408
+ }
409
+
410
+ function intervalOrFinished(milliseconds, finished) {
411
+ return new Promise((resolve) => {
412
+ const timer = setTimeout(resolve, milliseconds)
413
+ finished.then(() => {
414
+ clearTimeout(timer)
415
+ resolve()
416
+ })
417
+ })
63
418
  }
64
419
 
65
420
  function buildQueueReadWaitSql(queue, consumer, options) {
@@ -88,6 +443,28 @@ function queueIdentifier(value) {
88
443
  return ident
89
444
  }
90
445
 
446
+ function requiredQueueName(value, kind = 'queue') {
447
+ if (typeof value !== 'string' || value.length === 0) {
448
+ throw new RedDBError('INVALID_QUEUE_NAME', `${kind} scope requires a non-empty ${kind} name`)
449
+ }
450
+ return queueIdentifier(value)
451
+ }
452
+
453
+ function requiredDeliveryId(value) {
454
+ const deliveryId = String(value ?? '')
455
+ if (deliveryId.length === 0) throw new RedDBError('INVALID_ARGUMENT', 'queue delivery_id must be non-empty')
456
+ return deliveryId
457
+ }
458
+
459
+ function queueRetryDelay(value) {
460
+ if (value == null) return ''
461
+ const delay = String(value)
462
+ if (!/^(?:\d+(?:\.\d+)?)(?:ms|s|sec|secs|m|min|mins|h|hr|hrs|d|day|days)?$/.test(delay)) {
463
+ throw new RedDBError('INVALID_ARGUMENT', `invalid queue retry delay "${delay}"`)
464
+ }
465
+ return ` WITH DELAY ${delay}`
466
+ }
467
+
91
468
  function queueCount(count) {
92
469
  if (count == null) return ''
93
470
  if (!Number.isInteger(count) || count < 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/cli",
3
- "version": "1.36.11",
3
+ "version": "1.38.0",
4
4
  "description": "CLI launcher for RedDB. The red binary arrives as a per-platform optionalDependency (no install script). The JS/TS app driver is published as @reddb-io/sdk.",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -34,11 +34,11 @@
34
34
  "@changesets/cli": "^2.31.0"
35
35
  },
36
36
  "optionalDependencies": {
37
- "@reddb-io/red-linux-x64": "1.36.11",
38
- "@reddb-io/red-linux-x64-musl": "1.36.11",
39
- "@reddb-io/red-linux-arm64": "1.36.11",
40
- "@reddb-io/red-linux-arm64-musl": "1.36.11",
41
- "@reddb-io/red-win32-x64": "1.36.11"
37
+ "@reddb-io/red-linux-x64": "1.38.0",
38
+ "@reddb-io/red-linux-x64-musl": "1.38.0",
39
+ "@reddb-io/red-linux-arm64": "1.38.0",
40
+ "@reddb-io/red-linux-arm64-musl": "1.38.0",
41
+ "@reddb-io/red-win32-x64": "1.38.0"
42
42
  },
43
43
  "scripts": {
44
44
  "test": "node scripts/docs-analytics-boundaries.test.mjs && node --test scripts/connection-quality.test.mjs && node drivers/js/test/smoke.test.mjs",