@reddb-io/client 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/README.md CHANGED
@@ -149,7 +149,12 @@ The client follows the SDK Helper Spec for the shared JS/TS surface:
149
149
  fields.
150
150
  - `db.kv(collection?)` preserves exact keys, including namespaced keys such as
151
151
  `characters:hansel`, and exposes `put/get/exists/delete/list`.
152
- - `db.queue` exposes `push/pop/peek/len/purge`.
152
+ - `db.queue` exposes `push/pop/peek/len/purge/readWait/readWaitEntries`.
153
+ On RedWire, a single-message `readWait` uses the native async queue-wait
154
+ frame, so an idle consumer does not occupy an engine execution worker.
155
+ `readWaitEntries` preserves `message_id`, `consumer`, and `delivery_count`
156
+ for ACK/NACK handling. Multi-message waits retain the SQL compatibility
157
+ path until the wire protocol has an explicit terminal frame.
153
158
 
154
159
  ## Accepted URI schemes
155
160
 
@@ -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,6 +250,61 @@ export class QueueClient {
231
250
  consumer: string,
232
251
  options: { waitMs: number; group?: string; count?: number },
233
252
  ): Promise<unknown[]>
253
+ /** Like readWait(), but preserves delivery_id and the complete delivery metadata. */
254
+ readWaitEntries<T = unknown>(
255
+ queue: string,
256
+ consumer: string,
257
+ options: { waitMs: number; group?: string; count?: number },
258
+ ): Promise<Array<QueueWaitEntry<T>>>
259
+ }
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
+ consumer<T = unknown>(options: QueueConsumerOptions<T>): QueueConsumer<T>
282
+ }
283
+
284
+ export interface QueueConsumerOptions<T = unknown> {
285
+ consumer: string
286
+ group?: string
287
+ waitMs?: number
288
+ retryDelay?: string
289
+ handleMessage(message: QueueWaitEntry<T>): void | Promise<void>
290
+ onError?(error: unknown, message: QueueWaitEntry<T> | null): void | Promise<void>
291
+ }
292
+
293
+ export class QueueConsumer<T = unknown> {
294
+ constructor(queue: ScopedQueueClient, options: QueueConsumerOptions<T>)
295
+ readonly status: { isRunning: boolean }
296
+ start(): this
297
+ stop(): Promise<void>
298
+ finished(): Promise<void>
299
+ }
300
+
301
+ export interface QueueWaitEntry<T = unknown> {
302
+ message_id: string | number
303
+ delivery_id: string | number
304
+ payload: T
305
+ consumer: string
306
+ delivery_count: number
307
+ [key: string]: unknown
234
308
  }
235
309
 
236
310
  /**
@@ -410,12 +484,14 @@ export type ReadOptions = { consistency: 'strong' | 'local' }
410
484
  export class RedDB {
411
485
  queryWithOptions(sql: string, options: ReadOptions, params: QueryParam[]): Promise<QueryResult>
412
486
  queryWithOptions(sql: string, options: ReadOptions, ...params: QueryParam[]): Promise<QueryResult>
413
- readonly cache: CacheClient
414
- readonly queue: QueueClient
487
+ readonly cache: CacheClient & ((namespace: string) => ScopedCacheClient)
488
+ readonly queue: QueueClient & ((queue: string) => ScopedQueueClient)
489
+ readonly queues: QueueClient & ((queue: string) => ScopedQueueClient)
415
490
  readonly documents: DocumentClient
416
- readonly kv: KvClient & ((collection?: string) => KvClient)
491
+ readonly kv: KvClient & ((collection: string) => KvClient)
417
492
  readonly config: (collection?: string) => ConfigClient
418
493
  readonly vault: (collection?: string) => VaultClient
494
+ readonly secrets: (collection: string) => VaultClient
419
495
 
420
496
  query(sql: string): Promise<QueryResult>
421
497
  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,6 +252,61 @@ export class QueueClient {
233
252
  consumer: string,
234
253
  options: { waitMs: number; group?: string; count?: number },
235
254
  ): Promise<unknown[]>
255
+ /** Like readWait(), but preserves delivery_id and the complete delivery metadata. */
256
+ readWaitEntries<T = unknown>(
257
+ queue: string,
258
+ consumer: string,
259
+ options: { waitMs: number; group?: string; count?: number },
260
+ ): Promise<Array<QueueWaitEntry<T>>>
261
+ }
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
+ consumer<T = unknown>(options: QueueConsumerOptions<T>): QueueConsumer<T>
284
+ }
285
+
286
+ export interface QueueConsumerOptions<T = unknown> {
287
+ consumer: string
288
+ group?: string
289
+ waitMs?: number
290
+ retryDelay?: string
291
+ handleMessage(message: QueueWaitEntry<T>): void | Promise<void>
292
+ onError?(error: unknown, message: QueueWaitEntry<T> | null): void | Promise<void>
293
+ }
294
+
295
+ export class QueueConsumer<T = unknown> {
296
+ constructor(queue: ScopedQueueClient, options: QueueConsumerOptions<T>)
297
+ readonly status: { isRunning: boolean }
298
+ start(): this
299
+ stop(): Promise<void>
300
+ finished(): Promise<void>
301
+ }
302
+
303
+ export interface QueueWaitEntry<T = unknown> {
304
+ message_id: string | number
305
+ delivery_id: string | number
306
+ payload: T
307
+ consumer: string
308
+ delivery_count: number
309
+ [key: string]: unknown
236
310
  }
237
311
 
238
312
  /**
@@ -406,12 +480,14 @@ export type ReadOptions = { consistency: 'strong' | 'local' }
406
480
  export class RedDB {
407
481
  queryWithOptions(sql: string, options: ReadOptions, params: QueryParam[]): Promise<QueryResult>
408
482
  queryWithOptions(sql: string, options: ReadOptions, ...params: QueryParam[]): Promise<QueryResult>
409
- readonly cache: CacheClient
410
- readonly queue: QueueClient
483
+ readonly cache: CacheClient & ((namespace: string) => ScopedCacheClient)
484
+ readonly queue: QueueClient & ((queue: string) => ScopedQueueClient)
485
+ readonly queues: QueueClient & ((queue: string) => ScopedQueueClient)
411
486
  readonly documents: DocumentClient
412
- readonly kv: KvClient & ((collection?: string) => KvClient)
487
+ readonly kv: KvClient & ((collection: string) => KvClient)
413
488
  readonly config: (collection?: string) => ConfigClient
414
489
  readonly vault: (collection?: string) => VaultClient
490
+ readonly secrets: (collection: string) => VaultClient
415
491
 
416
492
  query(sql: string): Promise<QueryResult>
417
493
  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.10",
3
+ "version": "1.37.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
 
@@ -59,6 +59,7 @@ export class RoutingClient {
59
59
  this.refreshing = null
60
60
  this.closed = false
61
61
  this.binaryQueryParams = client.binaryQueryParams === true
62
+ this.nativeQueueWait = client.nativeQueueWait === true
62
63
  }
63
64
 
64
65
  async initialize() {
@@ -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', {
@@ -39,17 +48,181 @@ export class QueueClient {
39
48
  })
40
49
  }
41
50
 
42
- // Live `QUEUE READ … WAIT <ms>` helper (PRD #718 / #725). Same
43
- // contract as drivers/js: required `waitMs`, timeout returns empty
44
- // array, cancellation/cap rejection surface as transport errors.
45
51
  async readWait(queue, consumer, options = {}) {
46
- const sql = buildQueueReadWaitSql(queue, consumer, options)
47
- const result = await this.client.call('query', { sql })
48
- return queuePayloads(result)
52
+ return queuePayloads({ rows: await this.readWaitEntries(queue, consumer, options) })
53
+ }
54
+
55
+ // RedWire's QueueWaitOpen parks on the async wait registry instead of
56
+ // occupying an engine execution slot for the wait duration. The v1 frame
57
+ // has no terminal marker after a multi-message delivery, so COUNT != 1
58
+ // deliberately stays on the SQL compatibility path.
59
+ async readWaitEntries(queue, consumer, options = {}) {
60
+ const request = buildQueueReadWaitRequest(queue, consumer, options)
61
+ if (this.client.nativeQueueWait === true && request.count === 1) {
62
+ const { sql: _, ...params } = request
63
+ const result = await this.client.call('queue_wait', params)
64
+ return queueRows(result)
65
+ }
66
+ const result = await this.client.call('query', { sql: request.sql })
67
+ return queueRows(result)
68
+ }
69
+ }
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
+ consumer(options) {
119
+ return new QueueConsumer(this, options)
120
+ }
121
+ }
122
+
123
+ export class QueueConsumer {
124
+ constructor(queue, options = {}) {
125
+ if (!(queue instanceof ScopedQueueClient)) {
126
+ throw new TypeError('QueueConsumer requires a scoped queue')
127
+ }
128
+ if (typeof options.handleMessage !== 'function') {
129
+ throw new TypeError('queue consumer requires handleMessage(message)')
130
+ }
131
+ this.queue = queue
132
+ this.consumerName = requiredQueueName(options.consumer, 'consumer')
133
+ this.group = options.group == null ? null : requiredQueueName(options.group, 'group')
134
+ this.waitMs = options.waitMs ?? 30_000
135
+ if (!Number.isInteger(this.waitMs) || this.waitMs < 0) {
136
+ throw new TypeError('queue consumer waitMs must be a non-negative integer')
137
+ }
138
+ this.handleMessage = options.handleMessage
139
+ this.onError = options.onError ?? null
140
+ if (this.onError != null && typeof this.onError !== 'function') {
141
+ throw new TypeError('queue consumer onError must be a function')
142
+ }
143
+ this.retryDelay = options.retryDelay ?? null
144
+ queueRetryDelay(this.retryDelay)
145
+ this.running = false
146
+ this.loopPromise = null
147
+ }
148
+
149
+ get status() {
150
+ return { isRunning: this.running }
151
+ }
152
+
153
+ start() {
154
+ if (this.running) return this
155
+ this.running = true
156
+ this.loopPromise = this.#run().finally(() => {
157
+ this.running = false
158
+ })
159
+ return this
160
+ }
161
+
162
+ stop() {
163
+ this.running = false
164
+ return this.finished()
165
+ }
166
+
167
+ finished() {
168
+ return this.loopPromise ?? Promise.resolve()
169
+ }
170
+
171
+ async #run() {
172
+ while (this.running) {
173
+ let entries
174
+ try {
175
+ entries = await this.queue.readWaitEntries(this.consumerName, {
176
+ group: this.group,
177
+ count: 1,
178
+ waitMs: this.waitMs,
179
+ })
180
+ } catch (error) {
181
+ if (!this.running) return
182
+ await this.#reportError(error, null)
183
+ continue
184
+ }
185
+ if (entries.length === 0) continue
186
+ const message = entries[0]
187
+ const deliveryId = message?.delivery_id
188
+ if (deliveryId == null || String(deliveryId).length === 0) {
189
+ await this.#reportError(
190
+ new RedDBError('INVALID_QUEUE_DELIVERY', 'queue delivery is missing delivery_id'),
191
+ message,
192
+ )
193
+ continue
194
+ }
195
+ try {
196
+ await this.handleMessage(message)
197
+ } catch (error) {
198
+ try {
199
+ await this.queue.nack(deliveryId, { delay: this.retryDelay })
200
+ } catch (nackError) {
201
+ if (nackError !== error && error != null && typeof error === 'object') {
202
+ error.nackError = nackError
203
+ }
204
+ }
205
+ await this.#reportError(error, message)
206
+ continue
207
+ }
208
+ try {
209
+ await this.queue.ack(deliveryId)
210
+ } catch (error) {
211
+ await this.#reportError(error, message)
212
+ }
213
+ }
214
+ }
215
+
216
+ async #reportError(error, message) {
217
+ if (this.onError != null) {
218
+ await this.onError(error, message)
219
+ return
220
+ }
221
+ throw error
49
222
  }
50
223
  }
51
224
 
52
- function buildQueueReadWaitSql(queue, consumer, options) {
225
+ function buildQueueReadWaitRequest(queue, consumer, options) {
53
226
  const { waitMs, group = null, count = null } = options ?? {}
54
227
  if (!Number.isInteger(waitMs) || waitMs < 0) {
55
228
  throw new RedDBError(
@@ -61,7 +234,14 @@ function buildQueueReadWaitSql(queue, consumer, options) {
61
234
  const c = queueIdentifier(consumer)
62
235
  const g = group != null ? ` GROUP ${queueIdentifier(group)}` : ''
63
236
  const n = count != null ? queueCount(count) : ''
64
- return `QUEUE READ ${q}${g} CONSUMER ${c}${n} WAIT ${waitMs}ms`
237
+ return {
238
+ queue: q,
239
+ group: group != null ? queueIdentifier(group) : null,
240
+ consumer: c,
241
+ count: count ?? 1,
242
+ waitMs,
243
+ sql: `QUEUE READ ${q}${g} CONSUMER ${c}${n} WAIT ${waitMs}ms`,
244
+ }
65
245
  }
66
246
 
67
247
  function queueIdentifier(value) {
@@ -75,6 +255,30 @@ function queueIdentifier(value) {
75
255
  return ident
76
256
  }
77
257
 
258
+ function requiredQueueName(value, kind = 'queue') {
259
+ if (typeof value !== 'string' || value.length === 0) {
260
+ throw new RedDBError('INVALID_QUEUE_NAME', `${kind} scope requires a non-empty ${kind} name`)
261
+ }
262
+ return queueIdentifier(value)
263
+ }
264
+
265
+ function requiredDeliveryId(value) {
266
+ const deliveryId = String(value ?? '')
267
+ if (deliveryId.length === 0) {
268
+ throw new RedDBError('INVALID_ARGUMENT', 'queue delivery_id must be non-empty')
269
+ }
270
+ return deliveryId
271
+ }
272
+
273
+ function queueRetryDelay(value) {
274
+ if (value == null) return ''
275
+ const delay = String(value)
276
+ if (!/^(?:\d+(?:\.\d+)?)(?:ms|s|sec|secs|m|min|mins|h|hr|hrs|d|day|days)?$/.test(delay)) {
277
+ throw new RedDBError('INVALID_ARGUMENT', `invalid queue retry delay "${delay}"`)
278
+ }
279
+ return ` WITH DELAY ${delay}`
280
+ }
281
+
78
282
  function queueCount(count) {
79
283
  if (count == null) return ''
80
284
  if (!Number.isInteger(count) || count < 0) {
@@ -118,5 +322,9 @@ function queueStringLiteral(value) {
118
322
  }
119
323
 
120
324
  function queuePayloads(result) {
121
- return Array.isArray(result?.rows) ? result.rows.map((row) => row.payload) : []
325
+ return queueRows(result).map((row) => row.payload)
326
+ }
327
+
328
+ function queueRows(result) {
329
+ return Array.isArray(result?.rows) ? result.rows : []
122
330
  }
@@ -59,6 +59,9 @@ export const MessageKind = Object.freeze({
59
59
  StreamChunk: 0x2B,
60
60
  StreamError: 0x2C,
61
61
  StreamCancel: 0x2D,
62
+ QueueWaitOpen: 0x2E,
63
+ QueueEventPush: 0x2F,
64
+ QueueWaitTimeout: 0x30,
62
65
  })
63
66
 
64
67
  export const Features = Object.freeze({ PARAMS: 0x0000_0001, TOPOLOGY: 0x0000_0002 })
@@ -238,6 +241,7 @@ export class RedWireClient {
238
241
  this.serverFeatures = serverFeatures >>> 0
239
242
  // RedWire consumes typed views directly; JSON transports use envelopes.
240
243
  this.binaryQueryParams = true
244
+ this.nativeQueueWait = true
241
245
  this.nextCorr = 1n
242
246
  this.nextStream = 1
243
247
  this.closed = false
@@ -267,6 +271,7 @@ export class RedWireClient {
267
271
  return decodeTopology(response.payload)
268
272
  }
269
273
  if (method === 'query') return this.#query(params.sql ?? '', params.params)
274
+ if (method === 'queue_wait') return this.#queueWait(params)
270
275
  if (method === 'insert') return this.#insert({ collection: params.collection, payload: params.payload })
271
276
  if (method === 'bulk_insert') return this.#insert({ collection: params.collection, payloads: params.payloads })
272
277
  if (method === 'bulk_insert_binary') {
@@ -400,6 +405,53 @@ export class RedWireClient {
400
405
  )
401
406
  }
402
407
 
408
+ async #queueWait(params) {
409
+ if (params.count !== 1) {
410
+ throw new RedDBError(
411
+ 'INVALID_QUEUE_WAIT_COUNT',
412
+ 'native RedWire queue wait requires count=1',
413
+ )
414
+ }
415
+ const streamId = this.#stream()
416
+ const corr = this.#corr()
417
+ const payload = {
418
+ queue: params.queue,
419
+ consumer: params.consumer,
420
+ count: 1,
421
+ wait_ms: params.waitMs,
422
+ }
423
+ if (params.group != null) payload.group = params.group
424
+ await this.#writeStreamFrame(MessageKind.QueueWaitOpen, corr, jsonBytes(payload), streamId)
425
+
426
+ const response = await this.reader.next()
427
+ if (response.streamId !== streamId || response.correlationId !== corr) {
428
+ throw new RedDBError(
429
+ 'QUEUE_WAIT_PROTOCOL',
430
+ `queue wait response did not match stream ${streamId} / correlation ${corr}`,
431
+ )
432
+ }
433
+ if (response.kind === MessageKind.QueueEventPush) {
434
+ const message = jsonOf(response.payload)
435
+ if (message == null || typeof message !== 'object' || Array.isArray(message)) {
436
+ throw new RedDBError('QUEUE_WAIT_PROTOCOL', 'QueueEventPush payload must be a JSON object')
437
+ }
438
+ return { rows: [message] }
439
+ }
440
+ if (response.kind === MessageKind.QueueWaitTimeout) return { rows: [] }
441
+ if (response.kind === MessageKind.StreamError || response.kind === MessageKind.Error) {
442
+ const error = jsonOf(response.payload) ?? {}
443
+ throw new RedDBError(
444
+ error.code || 'QUEUE_WAIT_ERROR',
445
+ error.message || new TextDecoder().decode(response.payload),
446
+ error,
447
+ )
448
+ }
449
+ throw new RedDBError(
450
+ 'QUEUE_WAIT_PROTOCOL',
451
+ `expected QueueEventPush/QueueWaitTimeout/StreamError, got ${KIND_NAME[response.kind] ?? response.kind}`,
452
+ )
453
+ }
454
+
403
455
  async #ping() {
404
456
  const corr = this.#corr()
405
457
  await writeFrame(this.socket, MessageKind.Ping, corr, new Uint8Array())