@reddb-io/cli 1.37.0 → 1.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/sdk",
3
- "version": "1.37.0",
3
+ "version": "1.38.0",
4
4
  "description": "Official embedded RedDB SDK — launches a local red binary over stdio JSON-RPC. The binary arrives as a per-platform optionalDependency — no install script. Use @reddb-io/client for remote HTTP, gRPC, and RedWire.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -104,6 +104,11 @@ export class ScopedQueueClient {
104
104
  sql: `QUEUE NACK ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}${delay}`,
105
105
  })
106
106
  }
107
+ extend(deliveryId) {
108
+ return this.queueClient.client.call('query', {
109
+ sql: `QUEUE EXTEND ${this.name} WITH delivery_id = ${queueStringLiteral(requiredDeliveryId(deliveryId))}`,
110
+ })
111
+ }
107
112
  consumer(options) { return new QueueConsumer(this, options) }
108
113
  }
109
114
 
@@ -117,8 +122,8 @@ export class QueueConsumer {
117
122
  this.consumerName = requiredQueueName(options.consumer, 'consumer')
118
123
  this.group = options.group == null ? null : requiredQueueName(options.group, 'group')
119
124
  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')
125
+ if (!Number.isInteger(this.waitMs) || this.waitMs <= 0) {
126
+ throw new TypeError('queue consumer waitMs must be a positive integer')
122
127
  }
123
128
  this.handleMessage = options.handleMessage
124
129
  this.onError = options.onError ?? null
@@ -127,32 +132,114 @@ export class QueueConsumer {
127
132
  }
128
133
  this.retryDelay = options.retryDelay ?? null
129
134
  queueRetryDelay(this.retryDelay)
130
- this.running = false
135
+ this.concurrency = options.concurrency ?? 1
136
+ if (!Number.isInteger(this.concurrency) || this.concurrency < 1 || this.concurrency > 128) {
137
+ throw new TypeError('queue consumer concurrency must be an integer between 1 and 128')
138
+ }
139
+ this.receiveBackoff = receiveBackoffOptions(options.receiveBackoff)
140
+ this.leaseHeartbeatMs = optionalPositiveInteger(
141
+ options.leaseHeartbeatMs,
142
+ 'queue consumer leaseHeartbeatMs',
143
+ )
144
+ this.handlerTimeoutMs = optionalPositiveInteger(
145
+ options.handlerTimeoutMs,
146
+ 'queue consumer handlerTimeoutMs',
147
+ )
148
+ this.state = 'idle'
149
+ this.paused = false
150
+ this.stopRequested = false
151
+ this.inFlight = 0
131
152
  this.loopPromise = null
153
+ this.pauseWaiters = new Set()
154
+ this.sleepWaiters = new Set()
132
155
  }
133
156
 
134
- get status() { return { isRunning: this.running } }
157
+ get status() {
158
+ return {
159
+ state: this.state,
160
+ isRunning: this.state === 'running' || this.state === 'paused',
161
+ isPaused: this.paused,
162
+ inFlight: this.inFlight,
163
+ concurrency: this.concurrency,
164
+ }
165
+ }
135
166
  start() {
136
- if (this.running) return this
137
- this.running = true
138
- this.loopPromise = this.#run().finally(() => { this.running = false })
167
+ if (this.state === 'running' || this.state === 'paused' || this.state === 'stopping') return this
168
+ this.stopRequested = false
169
+ this.paused = false
170
+ this.state = 'running'
171
+ this.loopPromise = this.#run().then(
172
+ () => { this.state = 'stopped' },
173
+ (error) => {
174
+ this.state = 'failed'
175
+ throw error
176
+ },
177
+ )
178
+ return this
179
+ }
180
+ stop() {
181
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') {
182
+ return this.finished()
183
+ }
184
+ this.requestStop()
185
+ return this.finished()
186
+ }
187
+
188
+ requestStop() {
189
+ if (this.state === 'idle' || this.state === 'stopped' || this.state === 'failed') return this
190
+ this.stopRequested = true
191
+ this.paused = false
192
+ this.state = 'stopping'
193
+ this.#wake(this.pauseWaiters)
194
+ this.#wake(this.sleepWaiters)
195
+ return this
196
+ }
197
+ pause() {
198
+ if (this.state !== 'running') return this
199
+ this.paused = true
200
+ this.state = 'paused'
201
+ return this
202
+ }
203
+ resume() {
204
+ if (this.state !== 'paused') return this
205
+ this.paused = false
206
+ this.state = 'running'
207
+ this.#wake(this.pauseWaiters)
139
208
  return this
140
209
  }
141
- stop() { this.running = false; return this.finished() }
142
210
  finished() { return this.loopPromise ?? Promise.resolve() }
143
211
 
144
212
  async #run() {
145
- while (this.running) {
213
+ let firstError = null
214
+ const lanes = Array.from({ length: this.concurrency }, () => this.#runLane().catch((error) => {
215
+ if (firstError == null) firstError = error
216
+ this.stopRequested = true
217
+ this.paused = false
218
+ this.#wake(this.pauseWaiters)
219
+ this.#wake(this.sleepWaiters)
220
+ }))
221
+ await Promise.all(lanes)
222
+ if (firstError != null) throw firstError
223
+ }
224
+
225
+ async #runLane() {
226
+ let receiveFailures = 0
227
+ while (!this.stopRequested) {
228
+ await this.#waitWhilePaused()
229
+ if (this.stopRequested) return
146
230
  let entries
147
231
  try {
148
232
  entries = await this.queue.readWaitEntries(this.consumerName, {
149
233
  group: this.group, count: 1, waitMs: this.waitMs,
150
234
  })
151
235
  } catch (error) {
152
- if (!this.running) return
236
+ if (this.stopRequested) return
153
237
  await this.#reportError(error, null)
238
+ receiveFailures += 1
239
+ await this.#sleep(receiveBackoffDelay(this.receiveBackoff, receiveFailures))
154
240
  continue
155
241
  }
242
+ receiveFailures = 0
156
243
  if (entries.length === 0) continue
157
244
  const message = entries[0]
158
245
  const deliveryId = message?.delivery_id
@@ -163,31 +250,173 @@ export class QueueConsumer {
163
250
  )
164
251
  continue
165
252
  }
253
+ await this.#processMessage(message, String(deliveryId))
254
+ }
255
+ }
256
+
257
+ async #processMessage(message, deliveryId) {
258
+ this.inFlight += 1
259
+ const controller = new AbortController()
260
+ let handlerError = null
261
+ let timeoutError = null
262
+ let leaseError = null
263
+ let handlerSettled = false
264
+ let finishHeartbeat
265
+ const heartbeatFinished = new Promise((resolve) => { finishHeartbeat = resolve })
266
+ let timeout = null
267
+ if (this.handlerTimeoutMs != null) {
268
+ timeout = setTimeout(() => {
269
+ timeoutError = new RedDBError(
270
+ 'QUEUE_HANDLER_TIMEOUT',
271
+ `queue handler exceeded ${this.handlerTimeoutMs}ms`,
272
+ )
273
+ controller.abort(timeoutError)
274
+ }, this.handlerTimeoutMs)
275
+ }
276
+ const heartbeat = this.#heartbeat(
277
+ deliveryId,
278
+ controller,
279
+ heartbeatFinished,
280
+ () => handlerSettled,
281
+ (error) => { leaseError = error },
282
+ )
283
+ try {
284
+ await this.handleMessage(message, {
285
+ signal: controller.signal,
286
+ deliveryId,
287
+ extendLease: () => this.queue.extend(deliveryId),
288
+ })
289
+ } catch (error) {
290
+ handlerError = error
291
+ } finally {
292
+ handlerSettled = true
293
+ finishHeartbeat()
294
+ if (timeout != null) clearTimeout(timeout)
295
+ await heartbeat
296
+ this.inFlight -= 1
297
+ }
298
+
299
+ if (leaseError != null) {
300
+ await this.#reportError(leaseError, message)
301
+ return
302
+ }
303
+ const processingError = timeoutError ?? handlerError
304
+ if (processingError != null) {
166
305
  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
306
+ await this.queue.nack(deliveryId, { delay: this.retryDelay })
307
+ } catch (nackError) {
308
+ if (nackError !== processingError && typeof processingError === 'object') {
309
+ processingError.nackError = nackError
173
310
  }
174
- await this.#reportError(error, message)
175
- continue
176
311
  }
312
+ await this.#reportError(processingError, message)
313
+ return
314
+ }
315
+ try {
316
+ await this.queue.ack(deliveryId)
317
+ } catch (error) {
318
+ await this.#reportError(error, message)
319
+ }
320
+ }
321
+
322
+ async #heartbeat(deliveryId, controller, finished, isSettled, setLeaseError) {
323
+ if (this.leaseHeartbeatMs == null) return
324
+ while (!isSettled()) {
325
+ await intervalOrFinished(this.leaseHeartbeatMs, finished)
326
+ if (isSettled()) return
177
327
  try {
178
- await this.queue.ack(deliveryId)
328
+ await this.queue.extend(deliveryId)
179
329
  } catch (error) {
180
- await this.#reportError(error, message)
330
+ setLeaseError(error)
331
+ controller.abort(error)
332
+ return
181
333
  }
182
334
  }
183
335
  }
184
336
 
337
+ async #waitWhilePaused() {
338
+ while (this.paused && !this.stopRequested) {
339
+ await new Promise((resolve) => { this.pauseWaiters.add(resolve) })
340
+ }
341
+ }
342
+
343
+ #sleep(milliseconds) {
344
+ if (milliseconds === 0 || this.stopRequested) return Promise.resolve()
345
+ return new Promise((resolve) => {
346
+ let timer
347
+ const done = () => {
348
+ clearTimeout(timer)
349
+ this.sleepWaiters.delete(done)
350
+ resolve()
351
+ }
352
+ timer = setTimeout(done, milliseconds)
353
+ this.sleepWaiters.add(done)
354
+ })
355
+ }
356
+
357
+ #wake(waiters) {
358
+ for (const resolve of [...waiters]) resolve()
359
+ waiters.clear()
360
+ }
361
+
185
362
  async #reportError(error, message) {
186
363
  if (this.onError != null) return this.onError(error, message)
187
364
  throw error
188
365
  }
189
366
  }
190
367
 
368
+ function receiveBackoffOptions(value) {
369
+ if (value != null && (typeof value !== 'object' || Array.isArray(value))) {
370
+ throw new TypeError('queue consumer receiveBackoff must be an object')
371
+ }
372
+ const options = value ?? {}
373
+ const result = {
374
+ initialMs: options.initialMs ?? 250,
375
+ maxMs: options.maxMs ?? 30_000,
376
+ multiplier: options.multiplier ?? 2,
377
+ jitter: options.jitter ?? true,
378
+ }
379
+ if (!Number.isInteger(result.initialMs) || result.initialMs <= 0) {
380
+ throw new TypeError('queue consumer receiveBackoff.initialMs must be a positive integer')
381
+ }
382
+ if (!Number.isInteger(result.maxMs) || result.maxMs < result.initialMs) {
383
+ throw new TypeError('queue consumer receiveBackoff.maxMs must be an integer >= initialMs')
384
+ }
385
+ if (!Number.isFinite(result.multiplier) || result.multiplier < 1) {
386
+ throw new TypeError('queue consumer receiveBackoff.multiplier must be >= 1')
387
+ }
388
+ if (typeof result.jitter !== 'boolean') {
389
+ throw new TypeError('queue consumer receiveBackoff.jitter must be a boolean')
390
+ }
391
+ return result
392
+ }
393
+
394
+ function receiveBackoffDelay(options, failures) {
395
+ const unjittered = Math.min(
396
+ options.maxMs,
397
+ options.initialMs * (options.multiplier ** Math.max(0, failures - 1)),
398
+ )
399
+ return options.jitter ? Math.floor(Math.random() * (unjittered + 1)) : unjittered
400
+ }
401
+
402
+ function optionalPositiveInteger(value, name) {
403
+ if (value == null) return null
404
+ if (!Number.isInteger(value) || value <= 0) {
405
+ throw new TypeError(`${name} must be a positive integer`)
406
+ }
407
+ return value
408
+ }
409
+
410
+ function intervalOrFinished(milliseconds, finished) {
411
+ return new Promise((resolve) => {
412
+ const timer = setTimeout(resolve, milliseconds)
413
+ finished.then(() => {
414
+ clearTimeout(timer)
415
+ resolve()
416
+ })
417
+ })
418
+ }
419
+
191
420
  function buildQueueReadWaitSql(queue, consumer, options) {
192
421
  const { waitMs, group = null, count = null } = options ?? {}
193
422
  if (!Number.isInteger(waitMs) || waitMs < 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reddb-io/cli",
3
- "version": "1.37.0",
3
+ "version": "1.38.0",
4
4
  "description": "CLI launcher for RedDB. The red binary arrives as a per-platform optionalDependency (no install script). The JS/TS app driver is published as @reddb-io/sdk.",
5
5
  "type": "commonjs",
6
6
  "bin": {
@@ -34,11 +34,11 @@
34
34
  "@changesets/cli": "^2.31.0"
35
35
  },
36
36
  "optionalDependencies": {
37
- "@reddb-io/red-linux-x64": "1.37.0",
38
- "@reddb-io/red-linux-x64-musl": "1.37.0",
39
- "@reddb-io/red-linux-arm64": "1.37.0",
40
- "@reddb-io/red-linux-arm64-musl": "1.37.0",
41
- "@reddb-io/red-win32-x64": "1.37.0"
37
+ "@reddb-io/red-linux-x64": "1.38.0",
38
+ "@reddb-io/red-linux-x64-musl": "1.38.0",
39
+ "@reddb-io/red-linux-arm64": "1.38.0",
40
+ "@reddb-io/red-linux-arm64-musl": "1.38.0",
41
+ "@reddb-io/red-win32-x64": "1.38.0"
42
42
  },
43
43
  "scripts": {
44
44
  "test": "node scripts/docs-analytics-boundaries.test.mjs && node --test scripts/connection-quality.test.mjs && node drivers/js/test/smoke.test.mjs",