@reddb-io/client 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.
@@ -135,6 +135,7 @@ export interface CachePutEntry extends CachePutOptions {
135
135
  }
136
136
 
137
137
  export class CacheClient {
138
+ scope(namespace: string): ScopedCacheClient
138
139
  get(namespace: string, key: string): Promise<Uint8Array | null>
139
140
  getEntry(namespace: string, key: string): Promise<CacheHitResult | null>
140
141
  getMany(namespace: string, keys: string[]): Promise<CacheEntryResult[]>
@@ -155,6 +156,23 @@ export class CacheClient {
155
156
  flushNamespace(namespace: string): Promise<void>
156
157
  }
157
158
 
159
+ export class ScopedCacheClient {
160
+ readonly namespace: string
161
+ get(key: string): Promise<Uint8Array | null>
162
+ getEntry(key: string): Promise<CacheEntry | null>
163
+ getMany(keys: string[]): Promise<Array<CacheEntry & { value: Uint8Array | null }>>
164
+ put(key: string, value: Uint8Array | string, options?: CachePutOptions): Promise<void>
165
+ putMany(entries: CachePutEntry[]): Promise<number>
166
+ exists(key: string): Promise<'present' | 'absent' | 'maybe'>
167
+ expire(key: string, ttlMs: number): Promise<boolean>
168
+ expireAt(key: string, expiresAtUnixMs: number): Promise<boolean>
169
+ persist(key: string): Promise<boolean>
170
+ invalidate(key: string): Promise<void>
171
+ invalidatePrefix(prefix: string): Promise<number>
172
+ invalidateTags(tags: string[]): Promise<number>
173
+ flush(): Promise<void>
174
+ }
175
+
158
176
  export interface KvWatchEvent {
159
177
  key: string
160
178
  op: 'insert' | 'update' | 'delete'
@@ -217,6 +235,7 @@ export class DocumentClient {
217
235
  }
218
236
 
219
237
  export class QueueClient {
238
+ scope(queue: string): ScopedQueueClient
220
239
  push(
221
240
  queue: string,
222
241
  value: unknown,
@@ -231,7 +250,7 @@ export class QueueClient {
231
250
  consumer: string,
232
251
  options: { waitMs: number; group?: string; count?: number },
233
252
  ): Promise<unknown[]>
234
- /** Like readWait(), but preserves message_id, consumer and delivery_count. */
253
+ /** Like readWait(), but preserves delivery_id and the complete delivery metadata. */
235
254
  readWaitEntries<T = unknown>(
236
255
  queue: string,
237
256
  consumer: string,
@@ -239,8 +258,83 @@ export class QueueClient {
239
258
  ): Promise<Array<QueueWaitEntry<T>>>
240
259
  }
241
260
 
261
+ export class ScopedQueueClient {
262
+ readonly name: string
263
+ push(
264
+ value: unknown,
265
+ options?: { priority?: number; key?: string; dedup?: string; delay?: string; at?: number },
266
+ ): Promise<QueryResult>
267
+ pop(count?: number): Promise<unknown[]>
268
+ peek(count?: number): Promise<unknown[]>
269
+ len(): Promise<number>
270
+ purge(): Promise<QueryResult>
271
+ readWait<T = unknown>(
272
+ consumer: string,
273
+ options: { waitMs: number; group?: string; count?: number },
274
+ ): Promise<T[]>
275
+ readWaitEntries<T = unknown>(
276
+ consumer: string,
277
+ options: { waitMs: number; group?: string; count?: number },
278
+ ): Promise<Array<QueueWaitEntry<T>>>
279
+ ack(deliveryId: string | number): Promise<QueryResult>
280
+ nack(deliveryId: string | number, options?: { delay?: string }): Promise<QueryResult>
281
+ /** Refreshes the delivery visibility deadline using the queue's current lock policy. */
282
+ extend(deliveryId: string | number): Promise<QueryResult>
283
+ consumer<T = unknown>(options: QueueConsumerOptions<T>): QueueConsumer<T>
284
+ }
285
+
286
+ export interface QueueReceiveBackoffOptions {
287
+ initialMs?: number
288
+ maxMs?: number
289
+ multiplier?: number
290
+ jitter?: boolean
291
+ }
292
+
293
+ export interface QueueConsumerContext {
294
+ readonly signal: AbortSignal
295
+ readonly deliveryId: string
296
+ extendLease(): Promise<QueryResult>
297
+ }
298
+
299
+ export interface QueueConsumerOptions<T = unknown> {
300
+ consumer: string
301
+ group?: string
302
+ waitMs?: number
303
+ retryDelay?: string
304
+ concurrency?: number
305
+ receiveBackoff?: QueueReceiveBackoffOptions
306
+ leaseHeartbeatMs?: number
307
+ /** Cooperative timeout: aborts `context.signal`, then waits for the handler to settle before NACK. */
308
+ handlerTimeoutMs?: number
309
+ handleMessage(message: QueueWaitEntry<T>, context: QueueConsumerContext): void | Promise<void>
310
+ onError?(error: unknown, message: QueueWaitEntry<T> | null): void | Promise<void>
311
+ }
312
+
313
+ export type QueueConsumerState = 'idle' | 'running' | 'paused' | 'stopping' | 'stopped' | 'failed'
314
+
315
+ export interface QueueConsumerStatus {
316
+ readonly state: QueueConsumerState
317
+ readonly isRunning: boolean
318
+ readonly isPaused: boolean
319
+ readonly inFlight: number
320
+ readonly concurrency: number
321
+ }
322
+
323
+ export class QueueConsumer<T = unknown> {
324
+ constructor(queue: ScopedQueueClient, options: QueueConsumerOptions<T>)
325
+ readonly status: QueueConsumerStatus
326
+ start(): this
327
+ stop(): Promise<void>
328
+ /** Request graceful stop without awaiting completion; safe inside the handler. */
329
+ requestStop(): this
330
+ pause(): this
331
+ resume(): this
332
+ finished(): Promise<void>
333
+ }
334
+
242
335
  export interface QueueWaitEntry<T = unknown> {
243
336
  message_id: string | number
337
+ delivery_id: string | number
244
338
  payload: T
245
339
  consumer: string
246
340
  delivery_count: number
@@ -424,12 +518,14 @@ export type ReadOptions = { consistency: 'strong' | 'local' }
424
518
  export class RedDB {
425
519
  queryWithOptions(sql: string, options: ReadOptions, params: QueryParam[]): Promise<QueryResult>
426
520
  queryWithOptions(sql: string, options: ReadOptions, ...params: QueryParam[]): Promise<QueryResult>
427
- readonly cache: CacheClient
428
- readonly queue: QueueClient
521
+ readonly cache: CacheClient & ((namespace: string) => ScopedCacheClient)
522
+ readonly queue: QueueClient & ((queue: string) => ScopedQueueClient)
523
+ readonly queues: QueueClient & ((queue: string) => ScopedQueueClient)
429
524
  readonly documents: DocumentClient
430
- readonly kv: KvClient & ((collection?: string) => KvClient)
525
+ readonly kv: KvClient & ((collection: string) => KvClient)
431
526
  readonly config: (collection?: string) => ConfigClient
432
527
  readonly vault: (collection?: string) => VaultClient
528
+ readonly secrets: (collection: string) => VaultClient
433
529
 
434
530
  query(sql: string): Promise<QueryResult>
435
531
  query(sql: string, params: QueryParam[]): Promise<QueryResult>
package/index.d.ts CHANGED
@@ -131,6 +131,7 @@ export interface CachePutEntry extends CachePutOptions {
131
131
  }
132
132
 
133
133
  export class CacheClient {
134
+ scope(namespace: string): ScopedCacheClient
134
135
  get(namespace: string, key: string): Promise<Uint8Array | null>
135
136
  getEntry(namespace: string, key: string): Promise<CacheHitResult | null>
136
137
  getMany(namespace: string, keys: string[]): Promise<CacheEntryResult[]>
@@ -151,6 +152,23 @@ export class CacheClient {
151
152
  flushNamespace(namespace: string): Promise<void>
152
153
  }
153
154
 
155
+ export class ScopedCacheClient {
156
+ readonly namespace: string
157
+ get(key: string): Promise<Uint8Array | null>
158
+ getEntry(key: string): Promise<CacheEntry | null>
159
+ getMany(keys: string[]): Promise<Array<CacheEntry & { value: Uint8Array | null }>>
160
+ put(key: string, value: Uint8Array | string, options?: CachePutOptions): Promise<void>
161
+ putMany(entries: CachePutEntry[]): Promise<number>
162
+ exists(key: string): Promise<'present' | 'absent' | 'maybe'>
163
+ expire(key: string, ttlMs: number): Promise<boolean>
164
+ expireAt(key: string, expiresAtUnixMs: number): Promise<boolean>
165
+ persist(key: string): Promise<boolean>
166
+ invalidate(key: string): Promise<void>
167
+ invalidatePrefix(prefix: string): Promise<number>
168
+ invalidateTags(tags: string[]): Promise<number>
169
+ flush(): Promise<void>
170
+ }
171
+
154
172
  export interface KvWatchEvent {
155
173
  key: string
156
174
  op: 'insert' | 'update' | 'delete'
@@ -213,6 +231,7 @@ export class DocumentClient {
213
231
  }
214
232
 
215
233
  export class QueueClient {
234
+ scope(queue: string): ScopedQueueClient
216
235
  push(
217
236
  queue: string,
218
237
  value: unknown,
@@ -233,7 +252,7 @@ export class QueueClient {
233
252
  consumer: string,
234
253
  options: { waitMs: number; group?: string; count?: number },
235
254
  ): Promise<unknown[]>
236
- /** Like readWait(), but preserves message_id, consumer and delivery_count. */
255
+ /** Like readWait(), but preserves delivery_id and the complete delivery metadata. */
237
256
  readWaitEntries<T = unknown>(
238
257
  queue: string,
239
258
  consumer: string,
@@ -241,8 +260,83 @@ export class QueueClient {
241
260
  ): Promise<Array<QueueWaitEntry<T>>>
242
261
  }
243
262
 
263
+ export class ScopedQueueClient {
264
+ readonly name: string
265
+ push(
266
+ value: unknown,
267
+ options?: { priority?: number; key?: string; dedup?: string; delay?: string; at?: number },
268
+ ): Promise<QueryResult>
269
+ pop(count?: number): Promise<unknown[]>
270
+ peek(count?: number): Promise<unknown[]>
271
+ len(): Promise<number>
272
+ purge(): Promise<QueryResult>
273
+ readWait<T = unknown>(
274
+ consumer: string,
275
+ options: { waitMs: number; group?: string; count?: number },
276
+ ): Promise<T[]>
277
+ readWaitEntries<T = unknown>(
278
+ consumer: string,
279
+ options: { waitMs: number; group?: string; count?: number },
280
+ ): Promise<Array<QueueWaitEntry<T>>>
281
+ ack(deliveryId: string | number): Promise<QueryResult>
282
+ nack(deliveryId: string | number, options?: { delay?: string }): Promise<QueryResult>
283
+ /** Refreshes the delivery visibility deadline using the queue's current lock policy. */
284
+ extend(deliveryId: string | number): Promise<QueryResult>
285
+ consumer<T = unknown>(options: QueueConsumerOptions<T>): QueueConsumer<T>
286
+ }
287
+
288
+ export interface QueueReceiveBackoffOptions {
289
+ initialMs?: number
290
+ maxMs?: number
291
+ multiplier?: number
292
+ jitter?: boolean
293
+ }
294
+
295
+ export interface QueueConsumerContext {
296
+ readonly signal: AbortSignal
297
+ readonly deliveryId: string
298
+ extendLease(): Promise<QueryResult>
299
+ }
300
+
301
+ export interface QueueConsumerOptions<T = unknown> {
302
+ consumer: string
303
+ group?: string
304
+ waitMs?: number
305
+ retryDelay?: string
306
+ concurrency?: number
307
+ receiveBackoff?: QueueReceiveBackoffOptions
308
+ leaseHeartbeatMs?: number
309
+ /** Cooperative timeout: aborts `context.signal`, then waits for the handler to settle before NACK. */
310
+ handlerTimeoutMs?: number
311
+ handleMessage(message: QueueWaitEntry<T>, context: QueueConsumerContext): void | Promise<void>
312
+ onError?(error: unknown, message: QueueWaitEntry<T> | null): void | Promise<void>
313
+ }
314
+
315
+ export type QueueConsumerState = 'idle' | 'running' | 'paused' | 'stopping' | 'stopped' | 'failed'
316
+
317
+ export interface QueueConsumerStatus {
318
+ readonly state: QueueConsumerState
319
+ readonly isRunning: boolean
320
+ readonly isPaused: boolean
321
+ readonly inFlight: number
322
+ readonly concurrency: number
323
+ }
324
+
325
+ export class QueueConsumer<T = unknown> {
326
+ constructor(queue: ScopedQueueClient, options: QueueConsumerOptions<T>)
327
+ readonly status: QueueConsumerStatus
328
+ start(): this
329
+ stop(): Promise<void>
330
+ /** Request graceful stop without awaiting completion; safe inside the handler. */
331
+ requestStop(): this
332
+ pause(): this
333
+ resume(): this
334
+ finished(): Promise<void>
335
+ }
336
+
244
337
  export interface QueueWaitEntry<T = unknown> {
245
338
  message_id: string | number
339
+ delivery_id: string | number
246
340
  payload: T
247
341
  consumer: string
248
342
  delivery_count: number
@@ -420,12 +514,14 @@ export type ReadOptions = { consistency: 'strong' | 'local' }
420
514
  export class RedDB {
421
515
  queryWithOptions(sql: string, options: ReadOptions, params: QueryParam[]): Promise<QueryResult>
422
516
  queryWithOptions(sql: string, options: ReadOptions, ...params: QueryParam[]): Promise<QueryResult>
423
- readonly cache: CacheClient
424
- readonly queue: QueueClient
517
+ readonly cache: CacheClient & ((namespace: string) => ScopedCacheClient)
518
+ readonly queue: QueueClient & ((queue: string) => ScopedQueueClient)
519
+ readonly queues: QueueClient & ((queue: string) => ScopedQueueClient)
425
520
  readonly documents: DocumentClient
426
- readonly kv: KvClient & ((collection?: string) => KvClient)
521
+ readonly kv: KvClient & ((collection: string) => KvClient)
427
522
  readonly config: (collection?: string) => ConfigClient
428
523
  readonly vault: (collection?: string) => VaultClient
524
+ readonly secrets: (collection: string) => VaultClient
429
525
 
430
526
  query(sql: string): Promise<QueryResult>
431
527
  query(sql: string, params: QueryParam[]): Promise<QueryResult>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/client",
3
- "version": "1.36.11",
3
+ "version": "1.38.0",
4
4
  "description": "Thin remote-only RedDB driver. Pure JavaScript — no install scripts, no native binary. Speaks RedWire/gRPC/HTTP. Embedded URIs (memory://, file://, red:///path) are rejected — use @reddb-io/sdk for those.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
package/src/cache.js CHANGED
@@ -10,11 +10,23 @@
10
10
  */
11
11
 
12
12
  export class CacheClient {
13
+ static [Symbol.hasInstance](value) {
14
+ const candidate = value?.__reddbClientInstance ?? value
15
+ return this.prototype.isPrototypeOf(candidate)
16
+ }
17
+
13
18
  /** @param {{ call: Function }} client */
14
19
  constructor(client) {
15
20
  this._client = client
16
21
  }
17
22
 
23
+ scope(namespace) {
24
+ if (typeof namespace !== 'string' || namespace.length === 0) {
25
+ throw new TypeError('cache(namespace) requires a non-empty namespace')
26
+ }
27
+ return new ScopedCacheClient(this, namespace)
28
+ }
29
+
18
30
  /**
19
31
  * Fetch a cached value. Returns a Uint8Array on hit, null on miss.
20
32
  * @param {string} namespace
@@ -167,6 +179,29 @@ export class CacheClient {
167
179
  }
168
180
  }
169
181
 
182
+ export class ScopedCacheClient {
183
+ constructor(cacheClient, namespace) {
184
+ this.cacheClient = cacheClient
185
+ this.namespace = namespace
186
+ }
187
+
188
+ get(key) { return this.cacheClient.get(this.namespace, key) }
189
+ getEntry(key) { return this.cacheClient.getEntry(this.namespace, key) }
190
+ getMany(keys) { return this.cacheClient.getMany(this.namespace, keys) }
191
+ put(key, value, options = {}) { return this.cacheClient.put(this.namespace, key, value, options) }
192
+ putMany(entries) { return this.cacheClient.putMany(this.namespace, entries) }
193
+ exists(key) { return this.cacheClient.exists(this.namespace, key) }
194
+ expire(key, ttlMs) { return this.cacheClient.expire(this.namespace, key, ttlMs) }
195
+ expireAt(key, expiresAtUnixMs) {
196
+ return this.cacheClient.expireAt(this.namespace, key, expiresAtUnixMs)
197
+ }
198
+ persist(key) { return this.cacheClient.persist(this.namespace, key) }
199
+ invalidate(key) { return this.cacheClient.invalidate(this.namespace, key) }
200
+ invalidatePrefix(prefix) { return this.cacheClient.invalidatePrefix(this.namespace, prefix) }
201
+ invalidateTags(tags) { return this.cacheClient.invalidateTags(this.namespace, tags) }
202
+ flush() { return this.cacheClient.flushNamespace(this.namespace) }
203
+ }
204
+
170
205
  // ---------------------------------------------------------------------------
171
206
  // Helpers
172
207
  // ---------------------------------------------------------------------------
package/src/core/reddb.js CHANGED
@@ -31,6 +31,17 @@ import { TypedQueryBuilder, collectionExists, listCollections } from '../db-help
31
31
 
32
32
  const NESTED_TX_NOT_SUPPORTED = 'NESTED_TX_NOT_SUPPORTED'
33
33
 
34
+ function callableClient(instance, createScope) {
35
+ const callable = (...args) => createScope(...args)
36
+ Object.defineProperty(callable, '__reddbClientInstance', { value: instance })
37
+ Object.assign(callable, instance)
38
+ for (const name of Object.getOwnPropertyNames(Object.getPrototypeOf(instance))) {
39
+ if (name === 'constructor' || typeof instance[name] !== 'function') continue
40
+ callable[name] = instance[name].bind(instance)
41
+ }
42
+ return callable
43
+ }
44
+
34
45
  /**
35
46
  * Connection handle. Methods map 1:1 to JSON-RPC methods on the server.
36
47
  * Identical surface to `@reddb-io/sdk`'s `RedDB`, minus the local-spawn
@@ -105,11 +116,19 @@ export class RedDB {
105
116
  constructor(client, streaming) {
106
117
  this.client = client
107
118
  this._streaming = streaming ?? null
108
- this.cache = new CacheClient(client)
109
- this.queue = new QueueClient(client)
119
+ const cacheClient = new CacheClient(client)
120
+ this.cache = callableClient(cacheClient, (namespace) => cacheClient.scope(namespace))
121
+ const queueClient = new QueueClient(client)
122
+ this.queue = callableClient(queueClient, (queue) => queueClient.scope(queue))
123
+ this.queues = this.queue
110
124
  this.documents = new DocumentClient(this)
111
125
  const defaultKv = new KvClient(client)
112
- this.kv = Object.assign((collection = 'kv_default') => new KvClient(client, collection), {
126
+ this.kv = Object.assign((collection) => {
127
+ if (typeof collection !== 'string' || collection.length === 0) {
128
+ throw new TypeError('kv(collection) requires a non-empty collection')
129
+ }
130
+ return new KvClient(client, collection)
131
+ }, {
113
132
  put: defaultKv.put.bind(defaultKv),
114
133
  invalidateTags: defaultKv.invalidateTags.bind(defaultKv),
115
134
  watch: defaultKv.watch.bind(defaultKv),
@@ -117,6 +136,12 @@ export class RedDB {
117
136
  })
118
137
  this.config = (collection = 'red.config') => new ConfigClient(client, collection)
119
138
  this.vault = (collection = 'red.vault') => new VaultClient(client, collection)
139
+ this.secrets = (collection) => {
140
+ if (typeof collection !== 'string' || collection.length === 0) {
141
+ throw new TypeError('secrets(collection) requires a non-empty collection')
142
+ }
143
+ return new VaultClient(client, collection)
144
+ }
120
145
  this.inTransaction = false
121
146
  }
122
147
 
@@ -47,9 +47,9 @@ import { connectRouted } from './core/routing.js'
47
47
 
48
48
  export { RedDBError, EmbeddedNotSupported, EMBEDDED_REJECTION_MESSAGE, isEmbeddedUri }
49
49
  export { RowReadable, RowWritable } from './streaming-web.js'
50
- export { CacheClient } from './cache.js'
50
+ export { CacheClient, ScopedCacheClient } from './cache.js'
51
51
  export { KvClient } from './kv.js'
52
- export { QueueClient } from './queue.js'
52
+ export { QueueClient, ScopedQueueClient, QueueConsumer } from './queue.js'
53
53
  export { DocumentClient } from './documents.js'
54
54
  export { ConfigClient } from './config.js'
55
55
  export { VaultClient } from './vault.js'
package/src/index.js CHANGED
@@ -48,9 +48,9 @@ import { createSelectStream, createInputStream } from './streaming.js'
48
48
 
49
49
  export { RedDBError, EmbeddedNotSupported, EMBEDDED_REJECTION_MESSAGE, isEmbeddedUri }
50
50
  export { splitNdjson, RowReadable, RowWritable } from './streaming.js'
51
- export { CacheClient } from './cache.js'
51
+ export { CacheClient, ScopedCacheClient } from './cache.js'
52
52
  export { KvClient } from './kv.js'
53
- export { QueueClient } from './queue.js'
53
+ export { QueueClient, ScopedQueueClient, QueueConsumer } from './queue.js'
54
54
  export { DocumentClient } from './documents.js'
55
55
  export { ConfigClient } from './config.js'
56
56
  export { VaultClient } from './vault.js'
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
  push(queue, value, options = {}) {
9
18
  const suffix = queuePushOptions(options)
10
19
  return this.client.call('query', {
@@ -59,6 +68,383 @@ export class QueueClient {
59
68
  }
60
69
  }
61
70
 
71
+ export class ScopedQueueClient {
72
+ constructor(queueClient, queue) {
73
+ this.queueClient = queueClient
74
+ this.name = queue
75
+ }
76
+
77
+ push(value, options = {}) {
78
+ return this.queueClient.push(this.name, value, options)
79
+ }
80
+
81
+ pop(count) {
82
+ return this.queueClient.pop(this.name, count)
83
+ }
84
+
85
+ peek(count) {
86
+ return this.queueClient.peek(this.name, count)
87
+ }
88
+
89
+ len() {
90
+ return this.queueClient.len(this.name)
91
+ }
92
+
93
+ purge() {
94
+ return this.queueClient.purge(this.name)
95
+ }
96
+
97
+ readWait(consumer, options = {}) {
98
+ return this.queueClient.readWait(this.name, consumer, options)
99
+ }
100
+
101
+ readWaitEntries(consumer, options = {}) {
102
+ return this.queueClient.readWaitEntries(this.name, consumer, options)
103
+ }
104
+
105
+ ack(deliveryId) {
106
+ return this.queueClient.client.call('query', {
107
+ sql: `QUEUE ACK ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}`,
108
+ })
109
+ }
110
+
111
+ nack(deliveryId, options = {}) {
112
+ const delay = queueRetryDelay(options.delay)
113
+ return this.queueClient.client.call('query', {
114
+ sql: `QUEUE NACK ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}${delay}`,
115
+ })
116
+ }
117
+
118
+ extend(deliveryId) {
119
+ return this.queueClient.client.call('query', {
120
+ sql: `QUEUE EXTEND ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}`,
121
+ })
122
+ }
123
+
124
+ consumer(options) {
125
+ return new QueueConsumer(this, options)
126
+ }
127
+ }
128
+
129
+ export class QueueConsumer {
130
+ constructor(queue, options = {}) {
131
+ if (!(queue instanceof ScopedQueueClient)) {
132
+ throw new TypeError('QueueConsumer requires a scoped queue')
133
+ }
134
+ if (typeof options.handleMessage !== 'function') {
135
+ throw new TypeError('queue consumer requires handleMessage(message)')
136
+ }
137
+ this.queue = queue
138
+ this.consumerName = requiredQueueName(options.consumer, 'consumer')
139
+ this.group = options.group == null ? null : requiredQueueName(options.group, 'group')
140
+ this.waitMs = options.waitMs ?? 30_000
141
+ if (!Number.isInteger(this.waitMs) || this.waitMs <= 0) {
142
+ throw new TypeError('queue consumer waitMs must be a positive integer')
143
+ }
144
+ this.handleMessage = options.handleMessage
145
+ this.onError = options.onError ?? null
146
+ if (this.onError != null && typeof this.onError !== 'function') {
147
+ throw new TypeError('queue consumer onError must be a function')
148
+ }
149
+ this.retryDelay = options.retryDelay ?? null
150
+ queueRetryDelay(this.retryDelay)
151
+ this.concurrency = options.concurrency ?? 1
152
+ if (!Number.isInteger(this.concurrency) || this.concurrency < 1 || this.concurrency > 128) {
153
+ throw new TypeError('queue consumer concurrency must be an integer between 1 and 128')
154
+ }
155
+ this.receiveBackoff = receiveBackoffOptions(options.receiveBackoff)
156
+ this.leaseHeartbeatMs = optionalPositiveInteger(
157
+ options.leaseHeartbeatMs,
158
+ 'queue consumer leaseHeartbeatMs',
159
+ )
160
+ this.handlerTimeoutMs = optionalPositiveInteger(
161
+ options.handlerTimeoutMs,
162
+ 'queue consumer handlerTimeoutMs',
163
+ )
164
+ this.state = 'idle'
165
+ this.paused = false
166
+ this.stopRequested = false
167
+ this.inFlight = 0
168
+ this.loopPromise = null
169
+ this.pauseWaiters = new Set()
170
+ this.sleepWaiters = new Set()
171
+ }
172
+
173
+ get status() {
174
+ return {
175
+ state: this.state,
176
+ isRunning: this.state === 'running' || this.state === 'paused',
177
+ isPaused: this.paused,
178
+ inFlight: this.inFlight,
179
+ concurrency: this.concurrency,
180
+ }
181
+ }
182
+
183
+ start() {
184
+ if (this.state === 'running' || this.state === 'paused' || this.state === 'stopping') return this
185
+ this.stopRequested = false
186
+ this.paused = false
187
+ this.state = 'running'
188
+ this.loopPromise = this.#run().then(
189
+ () => { this.state = 'stopped' },
190
+ (error) => {
191
+ this.state = 'failed'
192
+ throw error
193
+ },
194
+ )
195
+ return this
196
+ }
197
+
198
+ stop() {
199
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') {
200
+ return this.finished()
201
+ }
202
+ this.requestStop()
203
+ return this.finished()
204
+ }
205
+
206
+ requestStop() {
207
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') return this
208
+ this.stopRequested = true
209
+ this.paused = false
210
+ this.state = 'stopping'
211
+ this.#wake(this.pauseWaiters)
212
+ this.#wake(this.sleepWaiters)
213
+ return this
214
+ }
215
+
216
+ pause() {
217
+ if (this.state !== 'running') return this
218
+ this.paused = true
219
+ this.state = 'paused'
220
+ return this
221
+ }
222
+
223
+ resume() {
224
+ if (this.state !== 'paused') return this
225
+ this.paused = false
226
+ this.state = 'running'
227
+ this.#wake(this.pauseWaiters)
228
+ return this
229
+ }
230
+
231
+ finished() {
232
+ return this.loopPromise ?? Promise.resolve()
233
+ }
234
+
235
+ async #run() {
236
+ let firstError = null
237
+ const lanes = Array.from({ length: this.concurrency }, () => this.#runLane().catch((error) => {
238
+ if (firstError == null) firstError = error
239
+ this.stopRequested = true
240
+ this.paused = false
241
+ this.#wake(this.pauseWaiters)
242
+ this.#wake(this.sleepWaiters)
243
+ }))
244
+ await Promise.all(lanes)
245
+ if (firstError != null) throw firstError
246
+ }
247
+
248
+ async #runLane() {
249
+ let receiveFailures = 0
250
+ while (!this.stopRequested) {
251
+ await this.#waitWhilePaused()
252
+ if (this.stopRequested) return
253
+ let entries
254
+ try {
255
+ entries = await this.queue.readWaitEntries(this.consumerName, {
256
+ group: this.group,
257
+ count: 1,
258
+ waitMs: this.waitMs,
259
+ })
260
+ } catch (error) {
261
+ if (this.stopRequested) return
262
+ await this.#reportError(error, null)
263
+ receiveFailures += 1
264
+ await this.#sleep(receiveBackoffDelay(this.receiveBackoff, receiveFailures))
265
+ continue
266
+ }
267
+ receiveFailures = 0
268
+ if (entries.length === 0) continue
269
+ const message = entries[0]
270
+ const deliveryId = message?.delivery_id
271
+ if (deliveryId == null || String(deliveryId).length === 0) {
272
+ await this.#reportError(
273
+ new RedDBError('INVALID_QUEUE_DELIVERY', 'queue delivery is missing delivery_id'),
274
+ message,
275
+ )
276
+ continue
277
+ }
278
+ await this.#processMessage(message, String(deliveryId))
279
+ }
280
+ }
281
+
282
+ async #processMessage(message, deliveryId) {
283
+ this.inFlight += 1
284
+ const controller = new AbortController()
285
+ let handlerError = null
286
+ let timeoutError = null
287
+ let leaseError = null
288
+ let handlerSettled = false
289
+ let finishHeartbeat
290
+ const heartbeatFinished = new Promise((resolve) => { finishHeartbeat = resolve })
291
+ let timeout = null
292
+ if (this.handlerTimeoutMs != null) {
293
+ timeout = setTimeout(() => {
294
+ timeoutError = new RedDBError(
295
+ 'QUEUE_HANDLER_TIMEOUT',
296
+ `queue handler exceeded ${this.handlerTimeoutMs}ms`,
297
+ )
298
+ controller.abort(timeoutError)
299
+ }, this.handlerTimeoutMs)
300
+ }
301
+ const heartbeat = this.#heartbeat(
302
+ deliveryId,
303
+ controller,
304
+ heartbeatFinished,
305
+ () => handlerSettled,
306
+ (error) => { leaseError = error },
307
+ )
308
+ try {
309
+ await this.handleMessage(message, {
310
+ signal: controller.signal,
311
+ deliveryId,
312
+ extendLease: () => this.queue.extend(deliveryId),
313
+ })
314
+ } catch (error) {
315
+ handlerError = error
316
+ } finally {
317
+ handlerSettled = true
318
+ finishHeartbeat()
319
+ if (timeout != null) clearTimeout(timeout)
320
+ await heartbeat
321
+ this.inFlight -= 1
322
+ }
323
+
324
+ if (leaseError != null) {
325
+ await this.#reportError(leaseError, message)
326
+ return
327
+ }
328
+ const processingError = timeoutError ?? handlerError
329
+ if (processingError != null) {
330
+ try {
331
+ await this.queue.nack(deliveryId, { delay: this.retryDelay })
332
+ } catch (nackError) {
333
+ if (nackError !== processingError && typeof processingError === 'object') {
334
+ processingError.nackError = nackError
335
+ }
336
+ }
337
+ await this.#reportError(processingError, message)
338
+ return
339
+ }
340
+ try {
341
+ await this.queue.ack(deliveryId)
342
+ } catch (error) {
343
+ await this.#reportError(error, message)
344
+ }
345
+ }
346
+
347
+ async #heartbeat(deliveryId, controller, finished, isSettled, setLeaseError) {
348
+ if (this.leaseHeartbeatMs == null) return
349
+ while (!isSettled()) {
350
+ await intervalOrFinished(this.leaseHeartbeatMs, finished)
351
+ if (isSettled()) return
352
+ try {
353
+ await this.queue.extend(deliveryId)
354
+ } catch (error) {
355
+ setLeaseError(error)
356
+ controller.abort(error)
357
+ return
358
+ }
359
+ }
360
+ }
361
+
362
+ async #waitWhilePaused() {
363
+ while (this.paused && !this.stopRequested) {
364
+ await new Promise((resolve) => { this.pauseWaiters.add(resolve) })
365
+ }
366
+ }
367
+
368
+ #sleep(milliseconds) {
369
+ if (milliseconds === 0 || this.stopRequested) return Promise.resolve()
370
+ return new Promise((resolve) => {
371
+ let timer
372
+ const done = () => {
373
+ clearTimeout(timer)
374
+ this.sleepWaiters.delete(done)
375
+ resolve()
376
+ }
377
+ timer = setTimeout(done, milliseconds)
378
+ this.sleepWaiters.add(done)
379
+ })
380
+ }
381
+
382
+ #wake(waiters) {
383
+ for (const resolve of [...waiters]) resolve()
384
+ waiters.clear()
385
+ }
386
+
387
+ async #reportError(error, message) {
388
+ if (this.onError != null) {
389
+ await this.onError(error, message)
390
+ return
391
+ }
392
+ throw error
393
+ }
394
+ }
395
+
396
+ function receiveBackoffOptions(value) {
397
+ if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
398
+ throw new TypeError('queue consumer receiveBackoff must be an object')
399
+ }
400
+ const options = value ?? {}
401
+ const result = {
402
+ initialMs: options.initialMs ?? 250,
403
+ maxMs: options.maxMs ?? 30_000,
404
+ multiplier: options.multiplier ?? 2,
405
+ jitter: options.jitter ?? true,
406
+ }
407
+ if (!Number.isInteger(result.initialMs) || result.initialMs <= 0) {
408
+ throw new TypeError('queue consumer receiveBackoff.initialMs must be a positive integer')
409
+ }
410
+ if (!Number.isInteger(result.maxMs) || result.maxMs < result.initialMs) {
411
+ throw new TypeError('queue consumer receiveBackoff.maxMs must be an integer >= initialMs')
412
+ }
413
+ if (!Number.isFinite(result.multiplier) || result.multiplier < 1) {
414
+ throw new TypeError('queue consumer receiveBackoff.multiplier must be >= 1')
415
+ }
416
+ if (typeof result.jitter !== 'boolean') {
417
+ throw new TypeError('queue consumer receiveBackoff.jitter must be a boolean')
418
+ }
419
+ return result
420
+ }
421
+
422
+ function receiveBackoffDelay(options, failures) {
423
+ const unjittered = Math.min(
424
+ options.maxMs,
425
+ options.initialMs * (options.multiplier ** Math.max(0, failures - 1)),
426
+ )
427
+ return options.jitter ? Math.floor(Math.random() * (unjittered + 1)) : unjittered
428
+ }
429
+
430
+ function optionalPositiveInteger(value, name) {
431
+ if (value == null) return null
432
+ if (!Number.isInteger(value) || value <= 0) {
433
+ throw new TypeError(`${name} must be a positive integer`)
434
+ }
435
+ return value
436
+ }
437
+
438
+ function intervalOrFinished(milliseconds, finished) {
439
+ return new Promise((resolve) => {
440
+ const timer = setTimeout(resolve, milliseconds)
441
+ finished.then(() => {
442
+ clearTimeout(timer)
443
+ resolve()
444
+ })
445
+ })
446
+ }
447
+
62
448
  function buildQueueReadWaitRequest(queue, consumer, options) {
63
449
  const { waitMs, group = null, count = null } = options ?? {}
64
450
  if (!Number.isInteger(waitMs) || waitMs < 0) {
@@ -92,6 +478,30 @@ function queueIdentifier(value) {
92
478
  return ident
93
479
  }
94
480
 
481
+ function requiredQueueName(value, kind = 'queue') {
482
+ if (typeof value !== 'string' || value.length === 0) {
483
+ throw new RedDBError('INVALID_QUEUE_NAME', `${kind} scope requires a non-empty ${kind} name`)
484
+ }
485
+ return queueIdentifier(value)
486
+ }
487
+
488
+ function requiredDeliveryId(value) {
489
+ const deliveryId = String(value ?? '')
490
+ if (deliveryId.length === 0) {
491
+ throw new RedDBError('INVALID_ARGUMENT', 'queue delivery_id must be non-empty')
492
+ }
493
+ return deliveryId
494
+ }
495
+
496
+ function queueRetryDelay(value) {
497
+ if (value == null) return ''
498
+ const delay = String(value)
499
+ if (!/^(?:\d+(?:\.\d+)?)(?:ms|s|sec|secs|m|min|mins|h|hr|hrs|d|day|days)?$/.test(delay)) {
500
+ throw new RedDBError('INVALID_ARGUMENT', `invalid queue retry delay "${delay}"`)
501
+ }
502
+ return ` WITH DELAY ${delay}`
503
+ }
504
+
95
505
  function queueCount(count) {
96
506
  if (count == null) return ''
97
507
  if (!Number.isInteger(count) || count < 0) {