@reddb-io/client 1.37.0 → 1.39.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.
@@ -278,23 +278,57 @@ export class ScopedQueueClient {
278
278
  ): Promise<Array<QueueWaitEntry<T>>>
279
279
  ack(deliveryId: string | number): Promise<QueryResult>
280
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>
281
283
  consumer<T = unknown>(options: QueueConsumerOptions<T>): QueueConsumer<T>
282
284
  }
283
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
+
284
299
  export interface QueueConsumerOptions<T = unknown> {
285
300
  consumer: string
286
301
  group?: string
287
302
  waitMs?: number
288
303
  retryDelay?: string
289
- handleMessage(message: QueueWaitEntry<T>): void | Promise<void>
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>
290
310
  onError?(error: unknown, message: QueueWaitEntry<T> | null): void | Promise<void>
291
311
  }
292
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
+
293
323
  export class QueueConsumer<T = unknown> {
294
324
  constructor(queue: ScopedQueueClient, options: QueueConsumerOptions<T>)
295
- readonly status: { isRunning: boolean }
325
+ readonly status: QueueConsumerStatus
296
326
  start(): this
297
327
  stop(): Promise<void>
328
+ /** Request graceful stop without awaiting completion; safe inside the handler. */
329
+ requestStop(): this
330
+ pause(): this
331
+ resume(): this
298
332
  finished(): Promise<void>
299
333
  }
300
334
 
package/index.d.ts CHANGED
@@ -280,23 +280,57 @@ export class ScopedQueueClient {
280
280
  ): Promise<Array<QueueWaitEntry<T>>>
281
281
  ack(deliveryId: string | number): Promise<QueryResult>
282
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>
283
285
  consumer<T = unknown>(options: QueueConsumerOptions<T>): QueueConsumer<T>
284
286
  }
285
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
+
286
301
  export interface QueueConsumerOptions<T = unknown> {
287
302
  consumer: string
288
303
  group?: string
289
304
  waitMs?: number
290
305
  retryDelay?: string
291
- handleMessage(message: QueueWaitEntry<T>): void | Promise<void>
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>
292
312
  onError?(error: unknown, message: QueueWaitEntry<T> | null): void | Promise<void>
293
313
  }
294
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
+
295
325
  export class QueueConsumer<T = unknown> {
296
326
  constructor(queue: ScopedQueueClient, options: QueueConsumerOptions<T>)
297
- readonly status: { isRunning: boolean }
327
+ readonly status: QueueConsumerStatus
298
328
  start(): this
299
329
  stop(): Promise<void>
330
+ /** Request graceful stop without awaiting completion; safe inside the handler. */
331
+ requestStop(): this
332
+ pause(): this
333
+ resume(): this
300
334
  finished(): Promise<void>
301
335
  }
302
336
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/client",
3
- "version": "1.37.0",
3
+ "version": "1.39.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/queue.js CHANGED
@@ -115,6 +115,12 @@ export class ScopedQueueClient {
115
115
  })
116
116
  }
117
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
+
118
124
  consumer(options) {
119
125
  return new QueueConsumer(this, options)
120
126
  }
@@ -132,8 +138,8 @@ export class QueueConsumer {
132
138
  this.consumerName = requiredQueueName(options.consumer, 'consumer')
133
139
  this.group = options.group == null ? null : requiredQueueName(options.group, 'group')
134
140
  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')
141
+ if (!Number.isInteger(this.waitMs) || this.waitMs <= 0) {
142
+ throw new TypeError('queue consumer waitMs must be a positive integer')
137
143
  }
138
144
  this.handleMessage = options.handleMessage
139
145
  this.onError = options.onError ?? null
@@ -142,34 +148,108 @@ export class QueueConsumer {
142
148
  }
143
149
  this.retryDelay = options.retryDelay ?? null
144
150
  queueRetryDelay(this.retryDelay)
145
- this.running = false
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
146
168
  this.loopPromise = null
169
+ this.pauseWaiters = new Set()
170
+ this.sleepWaiters = new Set()
147
171
  }
148
172
 
149
173
  get status() {
150
- return { isRunning: this.running }
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
+ }
151
181
  }
152
182
 
153
183
  start() {
154
- if (this.running) return this
155
- this.running = true
156
- this.loopPromise = this.#run().finally(() => {
157
- this.running = false
158
- })
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
+ )
159
195
  return this
160
196
  }
161
197
 
162
198
  stop() {
163
- this.running = false
199
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') {
200
+ return this.finished()
201
+ }
202
+ this.requestStop()
164
203
  return this.finished()
165
204
  }
166
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
+
167
231
  finished() {
168
232
  return this.loopPromise ?? Promise.resolve()
169
233
  }
170
234
 
171
235
  async #run() {
172
- while (this.running) {
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
173
253
  let entries
174
254
  try {
175
255
  entries = await this.queue.readWaitEntries(this.consumerName, {
@@ -178,10 +258,13 @@ export class QueueConsumer {
178
258
  waitMs: this.waitMs,
179
259
  })
180
260
  } catch (error) {
181
- if (!this.running) return
261
+ if (this.stopRequested) return
182
262
  await this.#reportError(error, null)
263
+ receiveFailures += 1
264
+ await this.#sleep(receiveBackoffDelay(this.receiveBackoff, receiveFailures))
183
265
  continue
184
266
  }
267
+ receiveFailures = 0
185
268
  if (entries.length === 0) continue
186
269
  const message = entries[0]
187
270
  const deliveryId = message?.delivery_id
@@ -192,27 +275,115 @@ export class QueueConsumer {
192
275
  )
193
276
  continue
194
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) {
195
330
  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
- }
331
+ await this.queue.nack(deliveryId, { delay: this.retryDelay })
332
+ } catch (nackError) {
333
+ if (nackError !== processingError && typeof processingError === 'object') {
334
+ processingError.nackError = nackError
204
335
  }
205
- await this.#reportError(error, message)
206
- continue
207
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
208
352
  try {
209
- await this.queue.ack(deliveryId)
353
+ await this.queue.extend(deliveryId)
210
354
  } catch (error) {
211
- await this.#reportError(error, message)
355
+ setLeaseError(error)
356
+ controller.abort(error)
357
+ return
212
358
  }
213
359
  }
214
360
  }
215
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
+
216
387
  async #reportError(error, message) {
217
388
  if (this.onError != null) {
218
389
  await this.onError(error, message)
@@ -222,6 +393,58 @@ export class QueueConsumer {
222
393
  }
223
394
  }
224
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
+
225
448
  function buildQueueReadWaitRequest(queue, consumer, options) {
226
449
  const { waitMs, group = null, count = null } = options ?? {}
227
450
  if (!Number.isInteger(waitMs) || waitMs < 0) {