@reddb-io/sdk 1.36.10 → 1.37.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/index.d.ts CHANGED
@@ -233,6 +233,7 @@ export interface CacheInvalidateResult {
233
233
  * RPC.
234
234
  */
235
235
  export class CacheClient {
236
+ scope(namespace: string): ScopedCacheClient
236
237
  /** Fetch a cached value. Returns Uint8Array on hit, null on miss. */
237
238
  get(namespace: string, key: string): Promise<Uint8Array | null>
238
239
  /** Store a value in the cache. */
@@ -254,6 +255,17 @@ export class CacheClient {
254
255
  flushNamespace(namespace: string): Promise<void>
255
256
  }
256
257
 
258
+ export class ScopedCacheClient {
259
+ readonly namespace: string
260
+ get(key: string): Promise<Uint8Array | null>
261
+ put(key: string, value: Uint8Array | Buffer | string, opts?: CachePutOptions): Promise<void>
262
+ exists(key: string): Promise<CacheExistsStatus>
263
+ invalidate(key: string): Promise<void>
264
+ invalidatePrefix(prefix: string): Promise<number>
265
+ invalidateTags(tags: string[]): Promise<number>
266
+ flush(): Promise<void>
267
+ }
268
+
257
269
  export interface KvWatchEvent {
258
270
  key: string
259
271
  op: 'insert' | 'update' | 'delete'
@@ -322,6 +334,7 @@ export class DocumentClient {
322
334
  }
323
335
 
324
336
  export class QueueClient {
337
+ scope(queue: string): ScopedQueueClient
325
338
  /** Idempotent CREATE QUEUE IF NOT EXISTS (spec §6.1). */
326
339
  create(queue: string): Promise<QueryResult>
327
340
  push(
@@ -345,6 +358,51 @@ export class QueueClient {
345
358
  consumer: string,
346
359
  options: { waitMs: number; group?: string; count?: number },
347
360
  ): Promise<unknown[]>
361
+ readWaitEntries(
362
+ queue: string,
363
+ consumer: string,
364
+ options: { waitMs: number; group?: string; count?: number },
365
+ ): Promise<QueueMessage[]>
366
+ }
367
+
368
+ export interface QueueMessage {
369
+ message_id?: string
370
+ delivery_id: string
371
+ payload: unknown
372
+ consumer?: string
373
+ delivery_count?: number
374
+ [key: string]: unknown
375
+ }
376
+
377
+ export interface QueueConsumerOptions {
378
+ consumer: string
379
+ group?: string
380
+ waitMs?: number
381
+ retryDelay?: string
382
+ handleMessage(message: QueueMessage): void | Promise<void>
383
+ onError?(error: unknown, message: QueueMessage | null): void | Promise<void>
384
+ }
385
+
386
+ export class ScopedQueueClient {
387
+ readonly name: string
388
+ create(): Promise<QueryResult>
389
+ push(value: unknown, options?: { priority?: number; key?: string; dedup?: string; delay?: string; at?: number }): Promise<QueryResult>
390
+ pop(count?: number): Promise<unknown[]>
391
+ peek(count?: number): Promise<unknown[]>
392
+ len(): Promise<number>
393
+ purge(): Promise<QueryResult>
394
+ readWait(consumer: string, options: { waitMs: number; group?: string; count?: number }): Promise<unknown[]>
395
+ readWaitEntries(consumer: string, options: { waitMs: number; group?: string; count?: number }): Promise<QueueMessage[]>
396
+ ack(deliveryId: string): Promise<QueryResult>
397
+ nack(deliveryId: string, options?: { delay?: string }): Promise<QueryResult>
398
+ consumer(options: QueueConsumerOptions): QueueConsumer
399
+ }
400
+
401
+ export class QueueConsumer {
402
+ readonly status: { isRunning: boolean }
403
+ start(): this
404
+ stop(): Promise<void>
405
+ finished(): Promise<void>
348
406
  }
349
407
 
350
408
  /**
@@ -422,14 +480,15 @@ export class RedDB {
422
480
  readonly transport: string | null
423
481
  /** SDK Helper Spec version this driver implements (spec §14). */
424
482
  readonly helperSpecVersion: string
425
- readonly cache: CacheClient
426
- readonly queue: QueueClient
483
+ readonly cache: CacheClient & ((namespace: string) => ScopedCacheClient)
484
+ readonly queue: QueueClient & ((queue: string) => ScopedQueueClient)
427
485
  /** Spec-canonical plural alias for `queue` (spec §6). */
428
- readonly queues: QueueClient
486
+ readonly queues: QueueClient & ((queue: string) => ScopedQueueClient)
429
487
  readonly documents: DocumentClient
430
488
  readonly kv: KvClient & ((collection?: string) => KvClient)
431
489
  readonly config: (collection?: string) => ConfigClient
432
490
  readonly vault: (collection?: string) => VaultClient
491
+ readonly secrets: (collection: string) => VaultClient
433
492
 
434
493
  query(sql: `ASK ${string}`): Promise<AskQueryResult>
435
494
  query(sql: string): Promise<QueryResult>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/sdk",
3
- "version": "1.36.10",
3
+ "version": "1.37.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",
@@ -43,11 +43,11 @@
43
43
  "url": "https://github.com/reddb-io/reddb/issues"
44
44
  },
45
45
  "optionalDependencies": {
46
- "@reddb-io/red-linux-x64": "1.36.10",
47
- "@reddb-io/red-linux-x64-musl": "1.36.10",
48
- "@reddb-io/red-linux-arm64": "1.36.10",
49
- "@reddb-io/red-linux-arm64-musl": "1.36.10",
50
- "@reddb-io/red-win32-x64": "1.36.10"
46
+ "@reddb-io/red-linux-x64": "1.37.0",
47
+ "@reddb-io/red-linux-x64-musl": "1.37.0",
48
+ "@reddb-io/red-linux-arm64": "1.37.0",
49
+ "@reddb-io/red-linux-arm64-musl": "1.37.0",
50
+ "@reddb-io/red-win32-x64": "1.37.0"
51
51
  },
52
52
  "scripts": {
53
53
  "test": "node --test test/ask.test.mjs test/cache.test.mjs test/db-helpers.test.mjs test/embedded-only.test.mjs test/helpers.test.mjs test/insert-ids.test.mjs test/kv.test.mjs test/params.test.mjs test/platform-binary.test.mjs test/native-engine.test.mjs test/queue.test.mjs test/redwire.params.test.mjs test/transaction.test.mjs test/url.test.mjs && node test/smoke.test.mjs && node test/conformance.test.mjs && node test/readme-examples.test.mjs"
package/src/cache.js CHANGED
@@ -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
  // ---------------------------------------------------------------------------
package/src/index.js CHANGED
@@ -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
 
package/src/queue.js CHANGED
@@ -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,9 +65,126 @@ 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
+ consumer(options) { return new QueueConsumer(this, options) }
108
+ }
109
+
110
+ export class QueueConsumer {
111
+ constructor(queue, options = {}) {
112
+ if (!(queue instanceof ScopedQueueClient)) throw new TypeError('QueueConsumer requires a scoped queue')
113
+ if (typeof options.handleMessage !== 'function') {
114
+ throw new TypeError('queue consumer requires handleMessage(message)')
115
+ }
116
+ this.queue = queue
117
+ this.consumerName = requiredQueueName(options.consumer, 'consumer')
118
+ this.group = options.group == null ? null : requiredQueueName(options.group, 'group')
119
+ this.waitMs = options.waitMs ?? 30_000
120
+ if (!Number.isInteger(this.waitMs) || this.waitMs < 0) {
121
+ throw new TypeError('queue consumer waitMs must be a non-negative integer')
122
+ }
123
+ this.handleMessage = options.handleMessage
124
+ this.onError = options.onError ?? null
125
+ if (this.onError != null && typeof this.onError !== 'function') {
126
+ throw new TypeError('queue consumer onError must be a function')
127
+ }
128
+ this.retryDelay = options.retryDelay ?? null
129
+ queueRetryDelay(this.retryDelay)
130
+ this.running = false
131
+ this.loopPromise = null
132
+ }
133
+
134
+ get status() { return { isRunning: this.running } }
135
+ start() {
136
+ if (this.running) return this
137
+ this.running = true
138
+ this.loopPromise = this.#run().finally(() => { this.running = false })
139
+ return this
140
+ }
141
+ stop() { this.running = false; return this.finished() }
142
+ finished() { return this.loopPromise ?? Promise.resolve() }
143
+
144
+ async #run() {
145
+ while (this.running) {
146
+ let entries
147
+ try {
148
+ entries = await this.queue.readWaitEntries(this.consumerName, {
149
+ group: this.group, count: 1, waitMs: this.waitMs,
150
+ })
151
+ } catch (error) {
152
+ if (!this.running) return
153
+ await this.#reportError(error, null)
154
+ continue
155
+ }
156
+ if (entries.length === 0) continue
157
+ const message = entries[0]
158
+ const deliveryId = message?.delivery_id
159
+ if (deliveryId == null || String(deliveryId).length === 0) {
160
+ await this.#reportError(
161
+ new RedDBError('INVALID_QUEUE_DELIVERY', 'queue delivery is missing delivery_id'),
162
+ message,
163
+ )
164
+ continue
165
+ }
166
+ try {
167
+ await this.handleMessage(message)
168
+ } catch (error) {
169
+ try {
170
+ await this.queue.nack(deliveryId, { delay: this.retryDelay })
171
+ } catch (nackError) {
172
+ if (nackError !== error && error != null && typeof error === 'object') error.nackError = nackError
173
+ }
174
+ await this.#reportError(error, message)
175
+ continue
176
+ }
177
+ try {
178
+ await this.queue.ack(deliveryId)
179
+ } catch (error) {
180
+ await this.#reportError(error, message)
181
+ }
182
+ }
183
+ }
184
+
185
+ async #reportError(error, message) {
186
+ if (this.onError != null) return this.onError(error, message)
187
+ throw error
62
188
  }
63
189
  }
64
190
 
@@ -88,6 +214,28 @@ function queueIdentifier(value) {
88
214
  return ident
89
215
  }
90
216
 
217
+ function requiredQueueName(value, kind = 'queue') {
218
+ if (typeof value !== 'string' || value.length === 0) {
219
+ throw new RedDBError('INVALID_QUEUE_NAME', `${kind} scope requires a non-empty ${kind} name`)
220
+ }
221
+ return queueIdentifier(value)
222
+ }
223
+
224
+ function requiredDeliveryId(value) {
225
+ const deliveryId = String(value ?? '')
226
+ if (deliveryId.length === 0) throw new RedDBError('INVALID_ARGUMENT', 'queue delivery_id must be non-empty')
227
+ return deliveryId
228
+ }
229
+
230
+ function queueRetryDelay(value) {
231
+ if (value == null) return ''
232
+ const delay = String(value)
233
+ if (!/^(?:\d+(?:\.\d+)?)(?:ms|s|sec|secs|m|min|mins|h|hr|hrs|d|day|days)?$/.test(delay)) {
234
+ throw new RedDBError('INVALID_ARGUMENT', `invalid queue retry delay "${delay}"`)
235
+ }
236
+ return ` WITH DELAY ${delay}`
237
+ }
238
+
91
239
  function queueCount(count) {
92
240
  if (count == null) return ''
93
241
  if (!Number.isInteger(count) || count < 0) {