@venizia/ignis-helpers 0.4.8 → 0.5.0-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.
Files changed (87) hide show
  1. package/dist/esm/common/constants/http.d.ts +3 -0
  2. package/dist/esm/common/constants/http.js +3 -0
  3. package/dist/esm/common/constants/http.js.map +1 -1
  4. package/dist/esm/common/redact.js +2 -0
  5. package/dist/esm/common/redact.js.map +1 -1
  6. package/dist/esm/core.d.ts +5 -2
  7. package/dist/esm/core.js +5 -2
  8. package/dist/esm/core.js.map +1 -1
  9. package/dist/esm/modules/network/http-request/base-network-request.helper.d.ts +5 -0
  10. package/dist/esm/modules/network/http-request/base-network-request.helper.js +14 -17
  11. package/dist/esm/modules/network/http-request/base-network-request.helper.js.map +1 -1
  12. package/dist/esm/modules/network/http-request/common/constants.d.ts +2 -1
  13. package/dist/esm/modules/network/http-request/common/constants.js +2 -1
  14. package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
  15. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +37 -11
  16. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +181 -38
  17. package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
  18. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +204 -18
  19. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +433 -13
  20. package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
  21. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.d.ts +36 -0
  22. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js +119 -0
  23. package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js.map +1 -0
  24. package/dist/esm/modules/network/http-request/fetcher/common/errors.d.ts +40 -0
  25. package/dist/esm/modules/network/http-request/fetcher/common/errors.js +37 -0
  26. package/dist/esm/modules/network/http-request/fetcher/common/errors.js.map +1 -0
  27. package/dist/esm/modules/network/http-request/fetcher/common/guard.d.ts +27 -0
  28. package/dist/esm/modules/network/http-request/fetcher/common/guard.js +2 -0
  29. package/dist/esm/modules/network/http-request/fetcher/common/guard.js.map +1 -0
  30. package/dist/esm/modules/network/http-request/fetcher/common/index.d.ts +6 -0
  31. package/dist/esm/modules/network/http-request/fetcher/common/index.js +6 -0
  32. package/dist/esm/modules/network/http-request/fetcher/common/index.js.map +1 -1
  33. package/dist/esm/modules/network/http-request/fetcher/common/request-context.d.ts +15 -0
  34. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js +11 -0
  35. package/dist/esm/modules/network/http-request/fetcher/common/request-context.js.map +1 -0
  36. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.d.ts +9 -0
  37. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js +14 -0
  38. package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js.map +1 -0
  39. package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +65 -1
  40. package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
  41. package/dist/esm/modules/network/http-request/fetcher/common/utilities.d.ts +68 -0
  42. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js +143 -0
  43. package/dist/esm/modules/network/http-request/fetcher/common/utilities.js.map +1 -0
  44. package/dist/esm/modules/network/http-request/fetcher/index.d.ts +2 -1
  45. package/dist/esm/modules/network/http-request/fetcher/index.js +2 -1
  46. package/dist/esm/modules/network/http-request/fetcher/index.js.map +1 -1
  47. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.d.ts +83 -0
  48. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js +221 -0
  49. package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js.map +1 -0
  50. package/dist/esm/modules/network/utilities/index.d.ts +1 -0
  51. package/dist/esm/modules/network/utilities/index.js +1 -0
  52. package/dist/esm/modules/network/utilities/index.js.map +1 -1
  53. package/dist/esm/modules/network/utilities/query-string.d.ts +6 -23
  54. package/dist/esm/modules/network/utilities/query-string.js +3 -17
  55. package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
  56. package/dist/esm/modules/network/utilities/url-builder.d.ts +39 -0
  57. package/dist/esm/modules/network/utilities/url-builder.js +102 -0
  58. package/dist/esm/modules/network/utilities/url-builder.js.map +1 -0
  59. package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -3
  60. package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
  61. package/dist/esm/modules/network/utilities/url-safety/common/errors.d.ts +38 -0
  62. package/dist/esm/modules/network/utilities/url-safety/common/errors.js +33 -1
  63. package/dist/esm/modules/network/utilities/url-safety/common/errors.js.map +1 -1
  64. package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +26 -3
  65. package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
  66. package/dist/esm/modules/network/utilities/url-safety/guard.d.ts +46 -0
  67. package/dist/esm/modules/network/utilities/url-safety/guard.js +145 -0
  68. package/dist/esm/modules/network/utilities/url-safety/guard.js.map +1 -0
  69. package/dist/esm/modules/network/utilities/url-safety/index.d.ts +1 -1
  70. package/dist/esm/modules/network/utilities/url-safety/index.js +1 -1
  71. package/dist/esm/modules/network/utilities/url-safety/index.js.map +1 -1
  72. package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +52 -2
  73. package/dist/esm/modules/network/utilities/url-safety/policy.js +161 -14
  74. package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
  75. package/dist/esm/modules/queue/bullmq/helper.d.ts +43 -7
  76. package/dist/esm/modules/queue/bullmq/helper.js +70 -2
  77. package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
  78. package/dist/esm/modules/retry/helper.d.ts +3 -1
  79. package/dist/esm/modules/retry/helper.js +8 -4
  80. package/dist/esm/modules/retry/helper.js.map +1 -1
  81. package/package.json +3 -3
  82. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +0 -41
  83. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +0 -111
  84. package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +0 -1
  85. package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +0 -95
  86. package/dist/esm/modules/network/utilities/url-safety/ingest.js +0 -328
  87. package/dist/esm/modules/network/utilities/url-safety/ingest.js.map +0 -1
@@ -4,6 +4,8 @@ import { RedisDefaults } from '../../redis/index.js';
4
4
  import { ErrorUtility } from '../../../utilities/error.utility.js';
5
5
  import { ModuleUtility } from '../../../utilities/module.utility.js';
6
6
  import { BullMQDefaults, BullQueueRoles, HookUtility } from '../common/index.js';
7
+ /** The key BullMQ stores in a job's `opts` for the metadata block: not the payload, so `job.data` is what the producer added. */
8
+ const METADATA_OPTION = 'metadata';
7
9
  /**
8
10
  * Wraps a BullMQ `Queue` or `Worker` (per `role`) on one Redis connection.
9
11
  * Worker concurrency is `numberOfWorker`; `lockDuration` is in milliseconds.
@@ -14,13 +16,20 @@ export class BullMQHelper extends BaseHelper {
14
16
  this.isClosing = false;
15
17
  /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */
16
18
  this.duplicates = [];
17
- const { queueName, redisConnection, role, numberOfWorker = BullMQDefaults.NUMBER_OF_WORKER, lockDuration = BullMQDefaults.LOCK_DURATION_MS, queueOptions, workerOptions, onWorkerData, onWorkerDataCompleted, onWorkerDataFail, module, } = options;
19
+ const { queueName, redisConnection, role, numberOfWorker = BullMQDefaults.NUMBER_OF_WORKER, lockDuration = BullMQDefaults.LOCK_DURATION_MS, prefix, metadata, queueOptions, workerOptions, onWorkerData, onWorkerDataCompleted, onWorkerDataFail, module, } = options;
18
20
  this.bullmqModule = module;
19
21
  this.queueName = queueName;
20
22
  this.role = role;
21
23
  this.redisConnection = redisConnection;
22
24
  this.numberOfWorker = numberOfWorker;
23
25
  this.lockDuration = lockDuration;
26
+ this.prefix = BullMQHelper.resolvePrefix({
27
+ identifier: this.identifier,
28
+ prefix,
29
+ queueOptions,
30
+ workerOptions,
31
+ });
32
+ this.metadata = metadata;
24
33
  this.queueOptions = queueOptions;
25
34
  this.workerOptions = workerOptions;
26
35
  this.onWorkerData = onWorkerData;
@@ -37,6 +46,61 @@ export class BullMQHelper extends BaseHelper {
37
46
  static newInstance(opts) {
38
47
  return new BullMQHelper(opts);
39
48
  }
49
+ /** `prefix` as the helper keeps it: a non-empty string with no whitespace and no brace (a brace would move the cluster hash tag), the same on the Queue and the Worker; unset stays unset (BullMQ's `bull`). */
50
+ static resolvePrefix(opts) {
51
+ const { identifier, prefix, queueOptions, workerOptions } = opts;
52
+ if (prefix === undefined) {
53
+ return undefined;
54
+ }
55
+ if (typeof prefix !== 'string' || prefix.length === 0 || /[\s{}]/.test(prefix)) {
56
+ throw getError({
57
+ message: `[BullMQHelper][${identifier}] Invalid prefix | value: ${JSON.stringify(prefix)} | it must be a non-empty string without whitespace or braces`,
58
+ });
59
+ }
60
+ for (const [name, other] of [
61
+ ['queueOptions.prefix', queueOptions?.prefix],
62
+ ['workerOptions.prefix', workerOptions?.prefix],
63
+ ]) {
64
+ if (other !== undefined && other !== prefix) {
65
+ throw getError({
66
+ message: `[BullMQHelper][${identifier}] ${name} (${other}) differs from prefix (${prefix}) | the helper owns the prefix of its Queue and Worker: set it once`,
67
+ });
68
+ }
69
+ }
70
+ return prefix;
71
+ }
72
+ /** The metadata a producer's helper stamped on `job`, or `undefined` for a job added without one (a raw `queue.add`, another producer). Not part of `job.data`. Returned as stored: its fields are not validated against `TMetadata`. */
73
+ static readMetadata(opts) {
74
+ const value = Reflect.get(Object(opts.job?.opts), METADATA_OPTION);
75
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
76
+ }
77
+ /**
78
+ * Adds a job, stamped by the `metadata` option: the stamp goes to `opts.metadata`, and `data` is exactly what you pass (any shape). A direct
79
+ * `queue.add` is available and unstamped. Refuses `opts.metadata` from the caller (the stamp is the one source) and a stamp that is not an object.
80
+ */
81
+ async add(opts) {
82
+ if (!this.queue) {
83
+ throw getError({
84
+ message: `[BullMQHelper][${this.identifier}] add needs a helper with role 'queue' | role: ${this.role}`,
85
+ });
86
+ }
87
+ if (opts.opts !== undefined && Reflect.has(opts.opts, METADATA_OPTION)) {
88
+ throw getError({
89
+ message: `[BullMQHelper][${this.identifier}] opts.metadata is stamped by the helper's metadata option | it is not set per call`,
90
+ });
91
+ }
92
+ const stamp = await this.metadata?.();
93
+ if (stamp === undefined) {
94
+ return this.queue.add(opts.name, opts.data, opts.opts);
95
+ }
96
+ if (stamp === null || typeof stamp !== 'object' || Array.isArray(stamp)) {
97
+ throw getError({
98
+ message: `[BullMQHelper][${this.identifier}] The metadata option must answer a plain object | got: ${Array.isArray(stamp) ? 'an array' : typeof stamp}`,
99
+ });
100
+ }
101
+ // BullMQ keeps an option key it does not know, and hands it back on `job.opts`; its type is closed, so the key is added by assignment.
102
+ return this.queue.add(opts.name, opts.data, Object.assign({}, opts.opts, { [METADATA_OPTION]: stamp }));
103
+ }
40
104
  /** Structural, never `instanceof`: ioredis is an optional peer, and a second copy fails `instanceof` anyway. */
41
105
  isClusterClient() {
42
106
  const client = Object(this.redisConnection.getClient());
@@ -78,6 +142,7 @@ export class BullMQHelper extends BaseHelper {
78
142
  removeOnFail: true,
79
143
  },
80
144
  ...this.queueOptions,
145
+ ...(this.prefix === undefined ? {} : { prefix: this.prefix }),
81
146
  connection: this.createConnection(),
82
147
  };
83
148
  }
@@ -103,6 +168,7 @@ export class BullMQHelper extends BaseHelper {
103
168
  .debug('Building worker options | Queue: %s | ID: %s', opts.queueName, this.identifier);
104
169
  return {
105
170
  ...this.workerOptions,
171
+ ...(this.prefix === undefined ? {} : { prefix: this.prefix }),
106
172
  connection: this.createConnection(),
107
173
  concurrency: this.numberOfWorker,
108
174
  lockDuration: this.lockDuration,
@@ -134,7 +200,9 @@ export class BullMQHelper extends BaseHelper {
134
200
  queueName,
135
201
  processor: async (job) => {
136
202
  if (this.onWorkerData) {
137
- return this.onWorkerData(job);
203
+ return this.onWorkerData(job, {
204
+ metadata: BullMQHelper.readMetadata({ job }),
205
+ });
138
206
  }
139
207
  const { id, name, data } = job;
140
208
  this.logger
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/queue/bullmq/helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAqB,aAAa,EAAqB,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3D,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAuB,MAAM,WAAW,CAAC;AAuC7F;;;GAGG;AACH,MAAM,OAAO,YAA8D,SAAQ,UAAU;IA8B3F,YAAY,OAAoD;QAC9D,KAAK,CAAC,EAAE,KAAK,EAAE,YAAY,CAAC,IAAI,EAAE,UAAU,EAAE,OAAO,CAAC,UAAU,EAAE,CAAC,CAAC;QAL9D,cAAS,GAAG,KAAK,CAAC;QAC1B,gHAAgH;QAC/F,eAAU,GAAmB,EAAE,CAAC;QAI/C,MAAM,EACJ,SAAS,EACT,eAAe,EACf,IAAI,EACJ,cAAc,GAAG,cAAc,CAAC,gBAAgB,EAChD,YAAY,GAAG,cAAc,CAAC,gBAAgB,EAC9C,YAAY,EACZ,aAAa,EACb,YAAY,EACZ,qBAAqB,EACrB,gBAAgB,EAChB,MAAM,GACP,GAAG,OAAO,CAAC;QAEZ,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAE3B,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC3B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,eAAe,GAAG,eAAe,CAAC;QAEvC,IAAI,CAAC,cAAc,GAAG,cAAc,CAAC;QACrC,IAAI,CAAC,YAAY,GAAG,YAAY,C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,CAAC,UAAU,CAAC,CAAC;gBACrF,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;YACzD,CAAC;QACH,CAAC;QAED,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;YACpB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,WAAW,IAAI,CAAC,UAAU,6CAA6C,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;aACvG,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;aACpB,IAAI,CAAC,4CAA4C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACzE,CAAC;CACF","sourcesContent":["import { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { type IRedisHelper, RedisDefaults, type TRedisClient } from '@/modules/redis';\nimport { ErrorUtility } from '@/utilities/error.utility';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport type { Job, Processor, Queue, QueueOptions, Worker, WorkerOptions } from 'bullmq';\nimport { BullMQDefaults, BullQueueRoles, HookUtility, type TBullQueueRole } from '../common';\n\n/** Options for {@link BullMQHelper}. `role` decides whether a `Queue` or a `Worker` is built. */\nexport interface IBullMQOptions<TQueueElement = unknown, TQueueResult = unknown> {\n queueName: string;\n identifier: string;\n role: TBullQueueRole;\n redisConnection: IRedisHelper;\n\n /** `bullmq` itself, for a `bun build --compile` binary that has no `node_modules` to load it from. Omitted, it is loaded when a queue or worker is built. */\n module?: typeof import('bullmq');\n\n /**\n * Worker concurrency.\n * @default BullMQDefaults.NUMBER_OF_WORKER\n */\n numberOfWorker?: number;\n /**\n * How long a worker holds a job's lock, in milliseconds.\n * @default BullMQDefaults.LOCK_DURATION_MS\n */\n lockDuration?: number;\n\n /** Merged over the framework defaults, under the fields the helper owns (`connection`) - see `queueOptionsFor`. */\n queueOptions?: Omit<QueueOptions, 'connection'>;\n /** Merged under the fields the helper owns (`connection`, `concurrency`, `lockDuration`) - see `workerOptionsFor`. */\n workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;\n\n onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<TQueueResult>;\n onWorkerDataCompleted?: (\n job: Job<TQueueElement, TQueueResult>,\n result: TQueueResult,\n ) => Promise<void>;\n onWorkerDataFail?: (\n job: Job<TQueueElement, TQueueResult> | undefined,\n error: Error,\n ) => Promise<void>;\n}\n\n/**\n * Wraps a BullMQ `Queue` or `Worker` (per `role`) on one Redis connection.\n * Worker concurrency is `numberOfWorker`; `lockDuration` is in milliseconds.\n */\nexport class BullMQHelper<TQueueElement = unknown, TQueueResult = unknown> extends BaseHelper {\n protected queueName: string;\n protected role: TBullQueueRole;\n protected redisConnection: IRedisHelper;\n\n queue: Queue<TQueueElement, TQueueResult>;\n worker: Worker<TQueueElement, TQueueResult>;\n\n protected numberOfWorker: number;\n protected lockDuration: number;\n\n protected queueOptions?: Omit<QueueOptions, 'connection'>;\n protected workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;\n\n protected onWorkerData?: (job: Job<TQueueElement, TQueueResult>) => Promise<TQueueResult>;\n protected onWorkerDataCompleted?: (\n job: Job<TQueueElement, TQueueResult>,\n result: TQueueResult,\n ) => Promise<void>;\n\n protected onWorkerDataFail?: (\n job: Job<TQueueElement, TQueueResult> | undefined,\n error: Error,\n ) => Promise<void>;\n\n private readonly bullmqModule?: typeof import('bullmq');\n private isClosing = false;\n /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */\n private readonly duplicates: TRedisClient[] = [];\n\n constructor(options: IBullMQOptions<TQueueElement, TQueueResult>) {\n super({ scope: BullMQHelper.name, identifier: options.identifier });\n const {\n queueName,\n redisConnection,\n role,\n numberOfWorker = BullMQDefaults.NUMBER_OF_WORKER,\n lockDuration = BullMQDefaults.LOCK_DURATION_MS,\n queueOptions,\n workerOptions,\n onWorkerData,\n onWorkerDataCompleted,\n onWorkerDataFail,\n module,\n } = options;\n\n this.bullmqModule = module;\n\n this.queueName = queueName;\n this.role = role;\n this.redisConnection = redisConnection;\n\n this.numberOfWorker = numberOfWorker;\n this.lockDuration = lockDuration;\n\n this.queueOptions = queueOptions;\n this.workerOptions = workerOptions;\n\n this.onWorkerData = onWorkerData;\n this.onWorkerDataCompleted = onWorkerDataCompleted;\n this.onWorkerDataFail = onWorkerDataFail;\n\n this.configure();\n }\n\n /** BullMQ never reconnects a client: once ioredis stops reconnecting (`maxRetry` attempts used up) it is `end` for good, no job moves, and nothing else says so. */\n protected reportClientEnded() {\n this.logger\n .for(this.reportClientEnded.name)\n .error(\n 'The Redis client ended, so BullMQ can no longer move jobs on queue %s | ioredis stopped reconnecting after maxRetry attempts | Back BullMQ with a helper whose maxRetry is %d (forever) | ID: %s',\n this.queueName,\n RedisDefaults.RETRY_FOREVER,\n this.identifier,\n );\n }\n\n static newInstance<T = unknown, R = unknown>(opts: IBullMQOptions<T, R>) {\n return new BullMQHelper<T, R>(opts);\n }\n\n /** Structural, never `instanceof`: ioredis is an optional peer, and a second copy fails `instanceof` anyway. */\n protected isClusterClient(): boolean {\n const client = Object(this.redisConnection.getClient());\n\n if (Reflect.get(client, 'isCluster') === true) {\n return true;\n }\n\n return typeof Reflect.get(client, 'nodes') === 'function';\n }\n\n protected resolveQueueName(): string {\n if (this.isClusterClient() && !this.queueName.startsWith('{')) {\n return `{${this.queueName}}`;\n }\n\n return this.queueName;\n }\n\n configureQueue() {\n if (!this.queueName) {\n this.logger\n .for(this.configureQueue.name)\n .error('Invalid queue name | ID: %s', this.identifier);\n\n return;\n }\n\n const queueName = this.resolveQueueName();\n this.queue = this.buildQueue({ queueName });\n\n // An 'error' event without a listener is re-thrown by EventEmitter - a Redis hiccup would take the whole process down.\n this.queue.on('error', (error) => {\n this.logger\n .for('queue-error')\n .error(\n 'queue: %s | Queue error! Error: %s | ID: %s',\n this.queueName,\n error,\n this.identifier,\n );\n });\n }\n\n /** Full `Queue` options: framework defaults, then `this.queueOptions`, then the connection the helper owns - in that precedence order. */\n protected queueOptionsFor(opts: { queueName: string }): QueueOptions {\n this.logger\n .for(this.queueOptionsFor.name)\n .debug('Building queue options | Queue: %s | ID: %s', opts.queueName, this.identifier);\n\n return {\n defaultJobOptions: {\n removeOnComplete: true,\n removeOnFail: true,\n },\n ...this.queueOptions,\n connection: this.createConnection(),\n };\n }\n\n /**\n * The connection BullMQ owns: a duplicate of the helper's client, so the queue or worker connects it by itself\n * whatever state the shared client is in. BullMQ treats a client it is handed as shared and never quits it, so the\n * helper keeps the duplicate and quits it in `close()`.\n */\n protected createConnection(): TRedisClient {\n const connection = this.redisConnection.duplicateClient();\n this.duplicates.push(connection);\n connection.once('end', () => {\n if (!this.isClosing) {\n this.reportClientEnded();\n }\n });\n\n return connection;\n }\n\n /** Full `Worker` options: `this.workerOptions`, then the connection/concurrency/lock fields the helper owns - in that precedence order. */\n protected workerOptionsFor(opts: {\n queueName: string;\n processor: Processor<TQueueElement, TQueueResult>;\n }): WorkerOptions {\n this.logger\n .for(this.workerOptionsFor.name)\n .debug('Building worker options | Queue: %s | ID: %s', opts.queueName, this.identifier);\n\n return {\n ...this.workerOptions,\n connection: this.createConnection(),\n concurrency: this.numberOfWorker,\n lockDuration: this.lockDuration,\n };\n }\n\n /** `bullmq` is an optional peer: loaded when a queue or worker is built, not when this module is. */\n private loadBullMQ(): typeof import('bullmq') {\n return (\n this.bullmqModule ?? ModuleUtility.loadSync<typeof import('bullmq')>({ module: 'bullmq' })\n );\n }\n\n /** Client factory seam - overridden in tests to run the helper without Redis. */\n protected buildQueue(opts: { queueName: string }): Queue<TQueueElement, TQueueResult> {\n const bullmq = this.loadBullMQ();\n\n return new bullmq.Queue<TQueueElement, TQueueResult>(\n opts.queueName,\n this.queueOptionsFor(opts),\n );\n }\n\n /** Client factory seam - overridden in tests to run the helper without Redis. */\n protected buildWorker(opts: {\n queueName: string;\n processor: Processor<TQueueElement, TQueueResult>;\n }): Worker<TQueueElement, TQueueResult> {\n const bullmq = this.loadBullMQ();\n\n return new bullmq.Worker<TQueueElement, TQueueResult>(\n opts.queueName,\n opts.processor,\n this.workerOptionsFor(opts),\n );\n }\n\n configureWorker() {\n if (!this.queueName) {\n this.logger\n .for(this.configureWorker.name)\n .error('Invalid worker name | ID: %s', this.identifier);\n\n return;\n }\n\n const queueName = this.resolveQueueName();\n this.worker = this.buildWorker({\n queueName,\n processor: async (job) => {\n if (this.onWorkerData) {\n return this.onWorkerData(job);\n }\n\n const { id, name, data } = job;\n this.logger\n .for('onWorkerData')\n .info(\n 'queue: %s | id: %s | name: %s | data: %j | ID: %s',\n this.queueName,\n id,\n name,\n data,\n this.identifier,\n );\n\n return undefined as TQueueResult;\n },\n });\n\n this.worker.on('completed', (job, result) => {\n HookUtility.invoke({\n logger: this.logger,\n scope: 'worker-completed',\n execution: () => this.onWorkerDataCompleted?.(job, result),\n });\n });\n\n this.worker.on('failed', (job, reason) => {\n HookUtility.invoke({\n logger: this.logger,\n scope: 'worker-failed',\n execution: () => this.onWorkerDataFail?.(job, reason),\n });\n });\n\n // An 'error' event without a listener is re-thrown by EventEmitter - a Redis hiccup would take the whole process down.\n this.worker.on('error', (error) => {\n this.logger\n .for('worker-error')\n .error(\n 'queue: %s | Worker error! Error: %s | ID: %s',\n this.queueName,\n error,\n this.identifier,\n );\n });\n }\n\n configure() {\n if (!this.role) {\n this.logger\n .for(this.configure.name)\n .error(\n 'Invalid client role to configure | Valid roles: [queue|worker] | ID: %s',\n this.identifier,\n );\n\n return;\n }\n\n switch (this.role) {\n case BullQueueRoles.QUEUE: {\n this.configureQueue();\n break;\n }\n case BullQueueRoles.WORKER: {\n this.configureWorker();\n break;\n }\n }\n }\n\n /** `quit()` waits for the replies in flight; a client BullMQ already closed is left alone. */\n private static async release(opts: { connection: TRedisClient }) {\n const { connection } = opts;\n\n if (connection.status === 'end') {\n return;\n }\n\n try {\n await connection.quit();\n } catch {\n connection.disconnect();\n }\n }\n\n async close() {\n this.isClosing = true;\n const failures: string[] = [];\n\n // Both connections must be released even when the first close fails - otherwise a failing worker close silently leaks the queue's Redis connection forever.\n try {\n await this.worker?.close();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .error('Error closing BullMQ worker: %s | ID: %s', error, this.identifier);\n failures.push(ErrorUtility.toError({ error }).message);\n }\n\n try {\n await this.queue?.close();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .error('Error closing BullMQ queue: %s | ID: %s', error, this.identifier);\n failures.push(ErrorUtility.toError({ error }).message);\n }\n\n for (const connection of this.duplicates.splice(0)) {\n try {\n await BullMQHelper.release({ connection });\n } catch (error) {\n this.logger\n .for(this.close.name)\n .error('Error closing the BullMQ connection: %s | ID: %s', error, this.identifier);\n failures.push(ErrorUtility.toError({ error }).message);\n }\n }\n\n if (failures.length) {\n throw getError({\n message: `[close][${this.identifier}] Failed to close BullMQ helper | Errors: ${failures.join(' | ')}`,\n });\n }\n\n this.logger\n .for(this.close.name)\n .info('BullMQ helper closed successfully | ID: %s', this.identifier);\n }\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../../src/modules/queue/bullmq/helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAC5C,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAqB,aAAa,EAAqB,MAAM,iBAAiB,CAAC;AACtF,OAAO,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAU3D,OAAO,EAAE,cAAc,EAAE,cAAc,EAAE,WAAW,EAAuB,MAAM,WAAW,CAAC;AAE7F,iIAAiI;AACjI,MAAM,eAAe,GAAG,UAAU,CAAC;AAmEnC;;;GAGG;AACH,MAAM,OAAO,YAIX,SAAQ,UAAU;IA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K,CAAC,IAAI,CAAC;qBACpB,KAAK,CAAC,kDAAkD,EAAE,KAAK,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;gBACrF,QAAQ,CAAC,IAAI,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;YACzD,CAAC;QACH,CAAC;QAED,IAAI,QAAQ,CAAC,MAAM,EAAE,CAAC;YACpB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,WAAW,IAAI,CAAC,UAAU,6CAA6C,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE;aACvG,CAAC,CAAC;QACL,CAAC;QAED,IAAI,CAAC,MAAM;aACR,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC;aACpB,IAAI,CAAC,4CAA4C,EAAE,IAAI,CAAC,UAAU,CAAC,CAAC;IACzE,CAAC;CACF","sourcesContent":["import type { ValueOrPromise } from '@/common';\nimport { BaseHelper } from '@/modules/base';\nimport { getError } from '@/modules/error';\nimport { type IRedisHelper, RedisDefaults, type TRedisClient } from '@/modules/redis';\nimport { ErrorUtility } from '@/utilities/error.utility';\nimport { ModuleUtility } from '@/utilities/module.utility';\nimport type {\n Job,\n JobsOptions,\n Processor,\n Queue,\n QueueOptions,\n Worker,\n WorkerOptions,\n} from 'bullmq';\nimport { BullMQDefaults, BullQueueRoles, HookUtility, type TBullQueueRole } from '../common';\n\n/** The key BullMQ stores in a job's `opts` for the metadata block: not the payload, so `job.data` is what the producer added. */\nconst METADATA_OPTION = 'metadata';\n\n/** `Queue.add` for this helper's element and result types: BullMQ resolves its name and data types through conditional types, so they are read off the method. */\ntype TQueueAdd<TElement, TResult> = Queue<TElement, TResult>['add'];\n\n/** What `onWorkerData` is told beside the job: the metadata the producer's helper stamped, `undefined` for a job added without one. */\nexport interface IBullMQJobContext<TMetadata extends object = Record<string, unknown>> {\n metadata: TMetadata | undefined;\n}\n\n/** Options for {@link BullMQHelper}. `role` decides whether a `Queue` or a `Worker` is built. */\nexport interface IBullMQOptions<\n TQueueElement = unknown,\n TQueueResult = unknown,\n TMetadata extends object = Record<string, unknown>,\n> {\n queueName: string;\n identifier: string;\n role: TBullQueueRole;\n redisConnection: IRedisHelper;\n\n /** `bullmq` itself, for a `bun build --compile` binary that has no `node_modules` to load it from. Omitted, it is loaded when a queue or worker is built. */\n module?: typeof import('bullmq');\n\n /**\n * Worker concurrency.\n * @default BullMQDefaults.NUMBER_OF_WORKER\n */\n numberOfWorker?: number;\n /**\n * How long a worker holds a job's lock, in milliseconds.\n * @default BullMQDefaults.LOCK_DURATION_MS\n */\n lockDuration?: number;\n\n /**\n * The prefix of every Redis key of the queue, on the Queue AND the Worker so they cannot disagree. Opt-in: unset is BullMQ's own\n * `bull`, so no key moves. A `queueOptions.prefix` or `workerOptions.prefix` that differs is refused. Switching it strands the\n * waiting, failed and repeatable jobs and the job schedulers under the old prefix: see the queue helper's migration notes.\n */\n prefix?: string;\n\n /**\n * A block stamped on every job added through `add`, run on each add and stored in the job's `opts.metadata`, outside `job.data`.\n * A throw fails the add; the answer must be a plain object. The worker reads it as `context.metadata`.\n */\n metadata?: () => ValueOrPromise<TMetadata>;\n\n /** Merged over the framework defaults, under the fields the helper owns (`connection`) - see `queueOptionsFor`. */\n queueOptions?: Omit<QueueOptions, 'connection'>;\n /** Merged under the fields the helper owns (`connection`, `concurrency`, `lockDuration`) - see `workerOptionsFor`. */\n workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;\n\n onWorkerData?: (\n job: Job<TQueueElement, TQueueResult>,\n context: IBullMQJobContext<TMetadata>,\n ) => Promise<TQueueResult>;\n onWorkerDataCompleted?: (\n job: Job<TQueueElement, TQueueResult>,\n result: TQueueResult,\n ) => Promise<void>;\n onWorkerDataFail?: (\n job: Job<TQueueElement, TQueueResult> | undefined,\n error: Error,\n ) => Promise<void>;\n}\n\n/**\n * Wraps a BullMQ `Queue` or `Worker` (per `role`) on one Redis connection.\n * Worker concurrency is `numberOfWorker`; `lockDuration` is in milliseconds.\n */\nexport class BullMQHelper<\n TQueueElement = unknown,\n TQueueResult = unknown,\n TMetadata extends object = Record<string, unknown>,\n> extends BaseHelper {\n protected queueName: string;\n protected role: TBullQueueRole;\n protected redisConnection: IRedisHelper;\n\n queue: Queue<TQueueElement, TQueueResult>;\n worker: Worker<TQueueElement, TQueueResult>;\n\n protected numberOfWorker: number;\n protected lockDuration: number;\n\n protected queueOptions?: Omit<QueueOptions, 'connection'>;\n protected workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;\n\n protected prefix?: string;\n protected metadata?: () => ValueOrPromise<TMetadata>;\n\n protected onWorkerData?: (\n job: Job<TQueueElement, TQueueResult>,\n context: IBullMQJobContext<TMetadata>,\n ) => Promise<TQueueResult>;\n\n protected onWorkerDataCompleted?: (\n job: Job<TQueueElement, TQueueResult>,\n result: TQueueResult,\n ) => Promise<void>;\n\n protected onWorkerDataFail?: (\n job: Job<TQueueElement, TQueueResult> | undefined,\n error: Error,\n ) => Promise<void>;\n\n private readonly bullmqModule?: typeof import('bullmq');\n private isClosing = false;\n /** Every duplicate this helper handed to BullMQ: BullMQ never quits a client it is given, so `close()` does. */\n private readonly duplicates: TRedisClient[] = [];\n\n constructor(options: IBullMQOptions<TQueueElement, TQueueResult, TMetadata>) {\n super({ scope: BullMQHelper.name, identifier: options.identifier });\n const {\n queueName,\n redisConnection,\n role,\n numberOfWorker = BullMQDefaults.NUMBER_OF_WORKER,\n lockDuration = BullMQDefaults.LOCK_DURATION_MS,\n prefix,\n metadata,\n queueOptions,\n workerOptions,\n onWorkerData,\n onWorkerDataCompleted,\n onWorkerDataFail,\n module,\n } = options;\n\n this.bullmqModule = module;\n\n this.queueName = queueName;\n this.role = role;\n this.redisConnection = redisConnection;\n\n this.numberOfWorker = numberOfWorker;\n this.lockDuration = lockDuration;\n\n this.prefix = BullMQHelper.resolvePrefix({\n identifier: this.identifier,\n prefix,\n queueOptions,\n workerOptions,\n });\n this.metadata = metadata;\n\n this.queueOptions = queueOptions;\n this.workerOptions = workerOptions;\n\n this.onWorkerData = onWorkerData;\n this.onWorkerDataCompleted = onWorkerDataCompleted;\n this.onWorkerDataFail = onWorkerDataFail;\n\n this.configure();\n }\n\n /** BullMQ never reconnects a client: once ioredis stops reconnecting (`maxRetry` attempts used up) it is `end` for good, no job moves, and nothing else says so. */\n protected reportClientEnded() {\n this.logger\n .for(this.reportClientEnded.name)\n .error(\n 'The Redis client ended, so BullMQ can no longer move jobs on queue %s | ioredis stopped reconnecting after maxRetry attempts | Back BullMQ with a helper whose maxRetry is %d (forever) | ID: %s',\n this.queueName,\n RedisDefaults.RETRY_FOREVER,\n this.identifier,\n );\n }\n\n static newInstance<T = unknown, R = unknown, M extends object = Record<string, unknown>>(\n opts: IBullMQOptions<T, R, M>,\n ) {\n return new BullMQHelper<T, R, M>(opts);\n }\n\n /** `prefix` as the helper keeps it: a non-empty string with no whitespace and no brace (a brace would move the cluster hash tag), the same on the Queue and the Worker; unset stays unset (BullMQ's `bull`). */\n private static resolvePrefix(opts: {\n identifier: string;\n prefix?: string;\n queueOptions?: Omit<QueueOptions, 'connection'>;\n workerOptions?: Omit<WorkerOptions, 'connection' | 'concurrency' | 'lockDuration'>;\n }): string | undefined {\n const { identifier, prefix, queueOptions, workerOptions } = opts;\n\n if (prefix === undefined) {\n return undefined;\n }\n\n if (typeof prefix !== 'string' || prefix.length === 0 || /[\\s{}]/.test(prefix)) {\n throw getError({\n message: `[BullMQHelper][${identifier}] Invalid prefix | value: ${JSON.stringify(prefix)} | it must be a non-empty string without whitespace or braces`,\n });\n }\n\n for (const [name, other] of [\n ['queueOptions.prefix', queueOptions?.prefix],\n ['workerOptions.prefix', workerOptions?.prefix],\n ]) {\n if (other !== undefined && other !== prefix) {\n throw getError({\n message: `[BullMQHelper][${identifier}] ${name} (${other}) differs from prefix (${prefix}) | the helper owns the prefix of its Queue and Worker: set it once`,\n });\n }\n }\n\n return prefix;\n }\n\n /** The metadata a producer's helper stamped on `job`, or `undefined` for a job added without one (a raw `queue.add`, another producer). Not part of `job.data`. Returned as stored: its fields are not validated against `TMetadata`. */\n static readMetadata<TMetadata extends object = Record<string, unknown>>(opts: {\n job: Pick<Job, 'opts'> | undefined;\n }): TMetadata | undefined {\n const value = Reflect.get(Object(opts.job?.opts), METADATA_OPTION);\n\n return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : undefined;\n }\n\n /**\n * Adds a job, stamped by the `metadata` option: the stamp goes to `opts.metadata`, and `data` is exactly what you pass (any shape). A direct\n * `queue.add` is available and unstamped. Refuses `opts.metadata` from the caller (the stamp is the one source) and a stamp that is not an object.\n */\n async add(opts: {\n name: Parameters<TQueueAdd<TQueueElement, TQueueResult>>[0];\n data: Parameters<TQueueAdd<TQueueElement, TQueueResult>>[1];\n opts?: JobsOptions;\n }): ReturnType<TQueueAdd<TQueueElement, TQueueResult>> {\n if (!this.queue) {\n throw getError({\n message: `[BullMQHelper][${this.identifier}] add needs a helper with role 'queue' | role: ${this.role}`,\n });\n }\n\n if (opts.opts !== undefined && Reflect.has(opts.opts, METADATA_OPTION)) {\n throw getError({\n message: `[BullMQHelper][${this.identifier}] opts.metadata is stamped by the helper's metadata option | it is not set per call`,\n });\n }\n\n const stamp = await this.metadata?.();\n\n if (stamp === undefined) {\n return this.queue.add(opts.name, opts.data, opts.opts);\n }\n\n if (stamp === null || typeof stamp !== 'object' || Array.isArray(stamp)) {\n throw getError({\n message: `[BullMQHelper][${this.identifier}] The metadata option must answer a plain object | got: ${Array.isArray(stamp) ? 'an array' : typeof stamp}`,\n });\n }\n\n // BullMQ keeps an option key it does not know, and hands it back on `job.opts`; its type is closed, so the key is added by assignment.\n return this.queue.add(\n opts.name,\n opts.data,\n Object.assign({}, opts.opts, { [METADATA_OPTION]: stamp }),\n );\n }\n\n /** Structural, never `instanceof`: ioredis is an optional peer, and a second copy fails `instanceof` anyway. */\n protected isClusterClient(): boolean {\n const client = Object(this.redisConnection.getClient());\n\n if (Reflect.get(client, 'isCluster') === true) {\n return true;\n }\n\n return typeof Reflect.get(client, 'nodes') === 'function';\n }\n\n protected resolveQueueName(): string {\n if (this.isClusterClient() && !this.queueName.startsWith('{')) {\n return `{${this.queueName}}`;\n }\n\n return this.queueName;\n }\n\n configureQueue() {\n if (!this.queueName) {\n this.logger\n .for(this.configureQueue.name)\n .error('Invalid queue name | ID: %s', this.identifier);\n\n return;\n }\n\n const queueName = this.resolveQueueName();\n this.queue = this.buildQueue({ queueName });\n\n // An 'error' event without a listener is re-thrown by EventEmitter - a Redis hiccup would take the whole process down.\n this.queue.on('error', (error) => {\n this.logger\n .for('queue-error')\n .error(\n 'queue: %s | Queue error! Error: %s | ID: %s',\n this.queueName,\n error,\n this.identifier,\n );\n });\n }\n\n /** Full `Queue` options: framework defaults, then `this.queueOptions`, then the connection the helper owns - in that precedence order. */\n protected queueOptionsFor(opts: { queueName: string }): QueueOptions {\n this.logger\n .for(this.queueOptionsFor.name)\n .debug('Building queue options | Queue: %s | ID: %s', opts.queueName, this.identifier);\n\n return {\n defaultJobOptions: {\n removeOnComplete: true,\n removeOnFail: true,\n },\n ...this.queueOptions,\n ...(this.prefix === undefined ? {} : { prefix: this.prefix }),\n connection: this.createConnection(),\n };\n }\n\n /**\n * The connection BullMQ owns: a duplicate of the helper's client, so the queue or worker connects it by itself\n * whatever state the shared client is in. BullMQ treats a client it is handed as shared and never quits it, so the\n * helper keeps the duplicate and quits it in `close()`.\n */\n protected createConnection(): TRedisClient {\n const connection = this.redisConnection.duplicateClient();\n this.duplicates.push(connection);\n connection.once('end', () => {\n if (!this.isClosing) {\n this.reportClientEnded();\n }\n });\n\n return connection;\n }\n\n /** Full `Worker` options: `this.workerOptions`, then the connection/concurrency/lock fields the helper owns - in that precedence order. */\n protected workerOptionsFor(opts: {\n queueName: string;\n processor: Processor<TQueueElement, TQueueResult>;\n }): WorkerOptions {\n this.logger\n .for(this.workerOptionsFor.name)\n .debug('Building worker options | Queue: %s | ID: %s', opts.queueName, this.identifier);\n\n return {\n ...this.workerOptions,\n ...(this.prefix === undefined ? {} : { prefix: this.prefix }),\n connection: this.createConnection(),\n concurrency: this.numberOfWorker,\n lockDuration: this.lockDuration,\n };\n }\n\n /** `bullmq` is an optional peer: loaded when a queue or worker is built, not when this module is. */\n private loadBullMQ(): typeof import('bullmq') {\n return (\n this.bullmqModule ?? ModuleUtility.loadSync<typeof import('bullmq')>({ module: 'bullmq' })\n );\n }\n\n /** Client factory seam - overridden in tests to run the helper without Redis. */\n protected buildQueue(opts: { queueName: string }): Queue<TQueueElement, TQueueResult> {\n const bullmq = this.loadBullMQ();\n\n return new bullmq.Queue<TQueueElement, TQueueResult>(\n opts.queueName,\n this.queueOptionsFor(opts),\n );\n }\n\n /** Client factory seam - overridden in tests to run the helper without Redis. */\n protected buildWorker(opts: {\n queueName: string;\n processor: Processor<TQueueElement, TQueueResult>;\n }): Worker<TQueueElement, TQueueResult> {\n const bullmq = this.loadBullMQ();\n\n return new bullmq.Worker<TQueueElement, TQueueResult>(\n opts.queueName,\n opts.processor,\n this.workerOptionsFor(opts),\n );\n }\n\n configureWorker() {\n if (!this.queueName) {\n this.logger\n .for(this.configureWorker.name)\n .error('Invalid worker name | ID: %s', this.identifier);\n\n return;\n }\n\n const queueName = this.resolveQueueName();\n this.worker = this.buildWorker({\n queueName,\n processor: async (job) => {\n if (this.onWorkerData) {\n return this.onWorkerData(job, {\n metadata: BullMQHelper.readMetadata<TMetadata>({ job }),\n });\n }\n\n const { id, name, data } = job;\n this.logger\n .for('onWorkerData')\n .info(\n 'queue: %s | id: %s | name: %s | data: %j | ID: %s',\n this.queueName,\n id,\n name,\n data,\n this.identifier,\n );\n\n return undefined as TQueueResult;\n },\n });\n\n this.worker.on('completed', (job, result) => {\n HookUtility.invoke({\n logger: this.logger,\n scope: 'worker-completed',\n execution: () => this.onWorkerDataCompleted?.(job, result),\n });\n });\n\n this.worker.on('failed', (job, reason) => {\n HookUtility.invoke({\n logger: this.logger,\n scope: 'worker-failed',\n execution: () => this.onWorkerDataFail?.(job, reason),\n });\n });\n\n // An 'error' event without a listener is re-thrown by EventEmitter - a Redis hiccup would take the whole process down.\n this.worker.on('error', (error) => {\n this.logger\n .for('worker-error')\n .error(\n 'queue: %s | Worker error! Error: %s | ID: %s',\n this.queueName,\n error,\n this.identifier,\n );\n });\n }\n\n configure() {\n if (!this.role) {\n this.logger\n .for(this.configure.name)\n .error(\n 'Invalid client role to configure | Valid roles: [queue|worker] | ID: %s',\n this.identifier,\n );\n\n return;\n }\n\n switch (this.role) {\n case BullQueueRoles.QUEUE: {\n this.configureQueue();\n break;\n }\n case BullQueueRoles.WORKER: {\n this.configureWorker();\n break;\n }\n }\n }\n\n /** `quit()` waits for the replies in flight; a client BullMQ already closed is left alone. */\n private static async release(opts: { connection: TRedisClient }) {\n const { connection } = opts;\n\n if (connection.status === 'end') {\n return;\n }\n\n try {\n await connection.quit();\n } catch {\n connection.disconnect();\n }\n }\n\n async close() {\n this.isClosing = true;\n const failures: string[] = [];\n\n // Both connections must be released even when the first close fails - otherwise a failing worker close silently leaks the queue's Redis connection forever.\n try {\n await this.worker?.close();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .error('Error closing BullMQ worker: %s | ID: %s', error, this.identifier);\n failures.push(ErrorUtility.toError({ error }).message);\n }\n\n try {\n await this.queue?.close();\n } catch (error) {\n this.logger\n .for(this.close.name)\n .error('Error closing BullMQ queue: %s | ID: %s', error, this.identifier);\n failures.push(ErrorUtility.toError({ error }).message);\n }\n\n for (const connection of this.duplicates.splice(0)) {\n try {\n await BullMQHelper.release({ connection });\n } catch (error) {\n this.logger\n .for(this.close.name)\n .error('Error closing the BullMQ connection: %s | ID: %s', error, this.identifier);\n failures.push(ErrorUtility.toError({ error }).message);\n }\n }\n\n if (failures.length) {\n throw getError({\n message: `[close][${this.identifier}] Failed to close BullMQ helper | Errors: ${failures.join(' | ')}`,\n });\n }\n\n this.logger\n .for(this.close.name)\n .info('BullMQ helper closed successfully | ID: %s', this.identifier);\n }\n}\n"]}
@@ -44,7 +44,9 @@ export declare class RetryHelper extends BaseHelper {
44
44
  signal?: AbortSignal;
45
45
  }) => ValueOrPromise<T>;
46
46
  /** Return `false` to stop retrying and rethrow `context.error` immediately. */
47
- shouldRetry?: (context: IRetryContext) => boolean;
47
+ shouldRetry?: (context: IRetryContext) => ValueOrPromise<boolean>;
48
+ /** The least wait before the next attempt, in milliseconds (a server's `Retry-After`); the backoff delay applies when it is longer. `undefined` leaves the backoff alone. */
49
+ getDelayMs?: (context: IRetryContext) => number | undefined;
48
50
  /** Observability hook, awaited before the backoff sleep. */
49
51
  onRetry?: (context: IRetryContext & {
50
52
  nextDelayMs: number;
@@ -130,7 +130,7 @@ export class RetryHelper extends BaseHelper {
130
130
  }
131
131
  /** One `executeWithRetry` attempt and everything that follows a failure: `shouldRetry` refusing rethrows, otherwise the bounds are checked and - when another attempt is allowed - the retry is logged, `onRetry` awaited and the backoff slept, all before returning. */
132
132
  static async runRetryAttempt(opts) {
133
- const { attempt, attemptTimeoutMs, startedAt, deadline, maxAttempts, operation, signal, logger, backoff, execution, shouldRetry, onRetry, } = opts;
133
+ const { attempt, attemptTimeoutMs, startedAt, deadline, maxAttempts, operation, signal, logger, backoff, execution, shouldRetry, getDelayMs, onRetry, } = opts;
134
134
  try {
135
135
  const value = await RetryHelper.runWithTimeout({
136
136
  operation,
@@ -141,13 +141,16 @@ export class RetryHelper extends BaseHelper {
141
141
  }
142
142
  catch (error) {
143
143
  const elapsedMs = Date.now() - startedAt;
144
- if (shouldRetry && !shouldRetry({ attempt, error, elapsedMs })) {
144
+ const verdict = shouldRetry ? shouldRetry({ attempt, error, elapsedMs }) : true;
145
+ const isRetryAllowed = await verdict;
146
+ if (!isRetryAllowed) {
145
147
  throw error;
146
148
  }
147
149
  if (attempt >= maxAttempts) {
148
150
  return { isResolved: false, error, isRetryAllowed: false };
149
151
  }
150
- const nextDelayMs = RetryHelper.computeBackoffDelayMs({ attempt, backoff });
152
+ // `getDelayMs` is a FLOOR (a server's Retry-After): the backoff never shortens it, and the deadline check below sees the longer wait.
153
+ const nextDelayMs = Math.max(RetryHelper.computeBackoffDelayMs({ attempt, backoff }), getDelayMs?.({ attempt, error, elapsedMs }) ?? 0);
151
154
  if (deadline && Date.now() + nextDelayMs >= deadline) {
152
155
  return { isResolved: false, error, isRetryAllowed: false };
153
156
  }
@@ -163,7 +166,7 @@ export class RetryHelper extends BaseHelper {
163
166
  }
164
167
  /** Retries `execution` with backoff, bounded by `maxAttempts`/`maxTotalMs`. JS cannot cancel a running promise - `signal` only stops between attempts/sleeps, so a timed-out execution keeps running unless it honors the signal itself. */
165
168
  static async executeWithRetry(opts) {
166
- const { operation, execution, maxAttempts = 3, maxTotalMs, perAttemptTimeoutMs, backoff, shouldRetry, onRetry, signal, logger, } = opts;
169
+ const { operation, execution, maxAttempts = 3, maxTotalMs, perAttemptTimeoutMs, backoff, shouldRetry, getDelayMs, onRetry, signal, logger, } = opts;
167
170
  if (maxAttempts < 1) {
168
171
  throw getError({
169
172
  message: `[executeWithRetry][${operation}] maxAttempts must be >= 1 | Got: ${maxAttempts}`,
@@ -195,6 +198,7 @@ export class RetryHelper extends BaseHelper {
195
198
  backoff,
196
199
  execution,
197
200
  shouldRetry,
201
+ getDelayMs,
198
202
  onRetry,
199
203
  });
200
204
  if (outcome.isResolved) {
@@ -1 +1 @@
1
- {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../src/modules/retry/helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE9E,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAM5C;;;GAGG;AACH,MAAM,OAAO,WAAY,SAAQ,UAAU;aACjB,yBAAoB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O,EAAE,OAAO,EAAE,CAAC,CAAC;YAE5E,IAAI,WAAW,GAAG,CAAC,EAAE,CAAC;gBACpB,MAAM,WAAW,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;YAC5E,CAAC;QACH,CAAC;QAED,MAAM;YACJ,EAAE,GAAG,CAAC,uBAAuB,CAAC;aAC7B,IAAI,CAAC,wDAAwD,EAAE,SAAS,CAAC,CAAC;QAE7E,OAAO,UAAe,CAAC;IACzB,CAAC","sourcesContent":["import type { ValueOrPromise } from '@/common';\nimport { getError } from '@/modules/error';\nimport type { ILogger } from '@/modules/logger';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport { RetryBackoffStrategies, RetryJitterModes } from './common/constants';\nimport type { IRetryBackoffOptions, IRetryContext } from './common/types';\nimport { BaseHelper } from '@/modules/base';\n\ntype TRetryAttemptOutcome<T> =\n | { isResolved: true; value: T }\n | { isResolved: false; error: unknown; isRetryAllowed: boolean };\n\n/**\n * Static members call each other through the class name (`RetryHelper.xxx`), never `this` - a\n * detached static method loses its `this` binding.\n */\nexport class RetryHelper extends BaseHelper {\n private static readonly RETRY_TIMEOUT_MARKER = Symbol.for('@venizia/ignis-helpers:retry-timeout');\n\n /** True when `error` is a per-attempt timeout raised by `runWithTimeout`/`executeWithRetry`. */\n static isRetryTimeoutError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && RetryHelper.RETRY_TIMEOUT_MARKER in error;\n }\n\n private static buildTimeoutError(opts: { operation: string; timeoutMs: number }) {\n const error = getError({\n message: `[runWithTimeout][${opts.operation}] Timed out after ${opts.timeoutMs}ms`,\n });\n Object.defineProperty(error, RetryHelper.RETRY_TIMEOUT_MARKER, { value: true });\n\n return error;\n }\n\n private static throwIfAborted(opts: { operation: string; signal?: AbortSignal }) {\n if (opts.signal?.aborted) {\n throw getError({\n message: `[executeWithRetry][${opts.operation}] Aborted | Reason: ${String(opts.signal.reason ?? 'unknown')}`,\n });\n }\n }\n\n /** `sleep` that wakes up early (and rejects) when `signal` aborts mid-wait. */\n private static async sleepWithSignal(opts: {\n ms: number;\n operation: string;\n signal?: AbortSignal;\n }) {\n const { ms, operation, signal } = opts;\n\n if (!signal) {\n await PromiseUtility.sleep({ ms });\n\n return;\n }\n\n RetryHelper.throwIfAborted({ operation, signal });\n\n // The listener is removed in `finally` rather than by the timer callback - the two would otherwise have to reference each other, and a leaked listener on a long-lived signal accumulates across retries.\n let removeAbortListener = () => {};\n\n try {\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(\n getError({\n message: `[executeWithRetry][${operation}] Aborted during backoff | Reason: ${String(signal.reason ?? 'unknown')}`,\n }),\n );\n };\n\n removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n } finally {\n removeAbortListener();\n }\n }\n\n /** Races `execution` against `timeoutMs` (`<= 0`/omitted = no timeout). The losing execution keeps running - JS promises cannot be cancelled - so pass `signal` through for cooperative cancellation. */\n static async runWithTimeout<T>(opts: {\n operation: string;\n timeoutMs?: number;\n execution: () => ValueOrPromise<T>;\n }): Promise<T> {\n const { operation, timeoutMs, execution } = opts;\n\n if (!timeoutMs || timeoutMs <= 0) {\n return execution();\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(RetryHelper.buildTimeoutError({ operation, timeoutMs }));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([Promise.resolve().then(execution), timeoutPromise]);\n\n return result;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** The pre-jitter delay for `attempt` (1-based, i.e. the delay AFTER attempt N failed). */\n static computeBackoffDelayMs(opts: { attempt: number; backoff?: IRetryBackoffOptions }): number {\n const { attempt } = opts;\n const {\n strategy = RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs = 250,\n multiplier = 2,\n maxDelayMs = 30_000,\n scheduleMs,\n jitter = RetryJitterModes.FULL,\n } = opts.backoff ?? {};\n\n let delayMs: number;\n\n switch (strategy) {\n case RetryBackoffStrategies.FIXED: {\n delayMs = initialDelayMs;\n break;\n }\n case RetryBackoffStrategies.LINEAR: {\n delayMs = initialDelayMs * attempt;\n break;\n }\n case RetryBackoffStrategies.EXPONENTIAL: {\n delayMs = initialDelayMs * Math.pow(multiplier, attempt - 1);\n break;\n }\n case RetryBackoffStrategies.SCHEDULE: {\n if (!scheduleMs?.length) {\n throw getError({\n message:\n '[computeBackoffDelayMs] strategy SCHEDULE requires a non-empty backoff.scheduleMs',\n });\n }\n\n delayMs = scheduleMs[Math.min(attempt - 1, scheduleMs.length - 1)];\n break;\n }\n default: {\n throw getError({\n message: `[computeBackoffDelayMs] Unknown backoff strategy '${strategy}' | Expected one of: ${[...RetryBackoffStrategies.SCHEME_SET].join(', ')}`,\n });\n }\n }\n\n delayMs = Math.min(delayMs, maxDelayMs);\n\n if (delayMs <= 0) {\n return 0;\n }\n\n switch (jitter) {\n case RetryJitterModes.NONE: {\n return delayMs;\n }\n case RetryJitterModes.FULL: {\n return Math.floor(Math.random() * delayMs);\n }\n case RetryJitterModes.EQUAL: {\n const half = delayMs / 2;\n\n return Math.floor(half + Math.random() * half);\n }\n default: {\n throw getError({\n message: `[computeBackoffDelayMs] Unknown jitter mode '${jitter}' | Expected one of: ${[...RetryJitterModes.SCHEME_SET].join(', ')}`,\n });\n }\n }\n }\n\n /** One `executeWithRetry` attempt and everything that follows a failure: `shouldRetry` refusing rethrows, otherwise the bounds are checked and - when another attempt is allowed - the retry is logged, `onRetry` awaited and the backoff slept, all before returning. */\n private static async runRetryAttempt<T>(opts: {\n attempt: number;\n attemptTimeoutMs?: number;\n startedAt: number;\n deadline?: number;\n maxAttempts: number;\n operation: string;\n signal?: AbortSignal;\n logger?: ILogger;\n backoff?: IRetryBackoffOptions;\n execution: (context: { attempt: number; signal?: AbortSignal }) => ValueOrPromise<T>;\n shouldRetry?: (context: IRetryContext) => boolean;\n onRetry?: (context: IRetryContext & { nextDelayMs: number }) => ValueOrPromise<void>;\n }): Promise<TRetryAttemptOutcome<T>> {\n const {\n attempt,\n attemptTimeoutMs,\n startedAt,\n deadline,\n maxAttempts,\n operation,\n signal,\n logger,\n backoff,\n execution,\n shouldRetry,\n onRetry,\n } = opts;\n\n try {\n const value = await RetryHelper.runWithTimeout({\n operation,\n timeoutMs: attemptTimeoutMs,\n execution: () => execution({ attempt, signal }),\n });\n\n return { isResolved: true, value };\n } catch (error) {\n const elapsedMs = Date.now() - startedAt;\n\n if (shouldRetry && !shouldRetry({ attempt, error, elapsedMs })) {\n throw error;\n }\n\n if (attempt >= maxAttempts) {\n return { isResolved: false, error, isRetryAllowed: false };\n }\n\n const nextDelayMs = RetryHelper.computeBackoffDelayMs({ attempt, backoff });\n\n if (deadline && Date.now() + nextDelayMs >= deadline) {\n return { isResolved: false, error, isRetryAllowed: false };\n }\n\n logger\n ?.for('executeWithRetry')\n .debug(\n '[%s] Attempt %d/%d failed - retrying in %dms | Error: %s',\n operation,\n attempt,\n maxAttempts,\n nextDelayMs,\n error,\n );\n\n await onRetry?.({ attempt, error, elapsedMs, nextDelayMs });\n\n if (nextDelayMs > 0) {\n await RetryHelper.sleepWithSignal({ ms: nextDelayMs, operation, signal });\n }\n\n return { isResolved: false, error, isRetryAllowed: true };\n }\n }\n\n /** Retries `execution` with backoff, bounded by `maxAttempts`/`maxTotalMs`. JS cannot cancel a running promise - `signal` only stops between attempts/sleeps, so a timed-out execution keeps running unless it honors the signal itself. */\n static async executeWithRetry<T>(opts: {\n signal?: AbortSignal;\n logger?: ILogger;\n operation: string;\n\n /** @default 3 */\n maxAttempts?: number;\n\n /** Total budget across attempts AND sleeps. Unlimited when omitted. */\n maxTotalMs?: number;\n\n /** Per-attempt race. No per-attempt timeout when omitted. */\n perAttemptTimeoutMs?: number;\n\n backoff?: IRetryBackoffOptions;\n\n execution: (context: { attempt: number; signal?: AbortSignal }) => ValueOrPromise<T>;\n\n /** Return `false` to stop retrying and rethrow `context.error` immediately. */\n shouldRetry?: (context: IRetryContext) => boolean;\n\n /** Observability hook, awaited before the backoff sleep. */\n onRetry?: (context: IRetryContext & { nextDelayMs: number }) => ValueOrPromise<void>;\n }): Promise<T> {\n const {\n operation,\n execution,\n maxAttempts = 3,\n maxTotalMs,\n perAttemptTimeoutMs,\n backoff,\n shouldRetry,\n onRetry,\n signal,\n logger,\n } = opts;\n\n if (maxAttempts < 1) {\n throw getError({\n message: `[executeWithRetry][${operation}] maxAttempts must be >= 1 | Got: ${maxAttempts}`,\n });\n }\n\n const startedAt = Date.now();\n // `!== undefined`, never truthiness: a budget of 0 - or a negative one, which is what `deadline - Date.now()` yields under load - means NO time left, not unlimited time.\n const deadline = maxTotalMs !== undefined ? startedAt + maxTotalMs : undefined;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n RetryHelper.throwIfAborted({ operation, signal });\n\n const remainingMs = deadline ? deadline - Date.now() : undefined;\n\n if (remainingMs !== undefined && remainingMs <= 0) {\n break;\n }\n\n let attemptTimeoutMs = perAttemptTimeoutMs;\n\n if (remainingMs !== undefined) {\n attemptTimeoutMs = attemptTimeoutMs ? Math.min(attemptTimeoutMs, remainingMs) : remainingMs;\n }\n\n const outcome = await RetryHelper.runRetryAttempt({\n attempt,\n attemptTimeoutMs,\n startedAt,\n deadline,\n maxAttempts,\n operation,\n signal,\n logger,\n backoff,\n execution,\n shouldRetry,\n onRetry,\n });\n\n if (outcome.isResolved) {\n return outcome.value;\n }\n\n lastError = outcome.error;\n\n if (!outcome.isRetryAllowed) {\n break;\n }\n }\n\n const elapsedMs = Date.now() - startedAt;\n\n // The budget can run out BEFORE the first attempt (an expired `maxTotalMs`), leaving no error to rethrow; `throw undefined` would detonate inside the caller's own handler on `error.message`.\n if (lastError === undefined) {\n throw getError({\n message: `[executeWithRetry][${operation}] Time budget exhausted before any attempt ran | maxTotalMs: ${maxTotalMs}`,\n });\n }\n\n logger\n ?.for('executeWithRetry')\n .warn('[%s] Exhausted retries | Elapsed: %dms | Error: %s', operation, elapsedMs, lastError);\n\n throw lastError;\n }\n\n /** Retries `execution` while `until(result)` returns false - for read-after-write staleness behind a replicated pool. Never worse than a single un-retried call: on exhaustion the LAST result is returned rather than an error, and a thrown error propagates immediately instead of being retried. Only wrap idempotent operations. */\n static async executeWithRetryUntil<T>(opts: {\n signal?: AbortSignal;\n logger?: ILogger;\n operation: string;\n\n /** @default 3 */\n maxAttempts?: number;\n\n /** Bounds when a NEW attempt may start; it never interrupts an attempt already in flight, so the first execution always runs to completion - a budget of 0 just means \"no retries\". */\n maxTotalMs?: number;\n\n backoff?: IRetryBackoffOptions;\n\n execution: (context: { attempt: number; signal?: AbortSignal }) => ValueOrPromise<T>;\n\n /** Retry while this returns false. */\n until: (result: T) => boolean;\n }): Promise<T> {\n const {\n signal,\n logger,\n operation,\n maxAttempts = 3,\n maxTotalMs,\n backoff,\n execution,\n until,\n } = opts;\n\n if (maxAttempts < 1) {\n throw getError({\n message: `[executeWithRetryUntil][${operation}] maxAttempts must be >= 1 | Got: ${maxAttempts}`,\n });\n }\n\n // Surfaced before the first execution - a misconfigured backoff discovered mid-loop would discard an already-fetched result.\n RetryHelper.computeBackoffDelayMs({ attempt: 1, backoff });\n\n const startedAt = Date.now();\n let lastResult: T | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n RetryHelper.throwIfAborted({ operation, signal });\n\n const result2 = await execution({ attempt, signal });\n lastResult = result2;\n\n if (until(lastResult)) {\n return lastResult;\n }\n\n const elapsedMs = Date.now() - startedAt;\n\n if (attempt >= maxAttempts || (maxTotalMs !== undefined && elapsedMs >= maxTotalMs)) {\n break;\n }\n\n logger\n ?.for('executeWithRetryUntil')\n .debug('[%s] until condition not met | Attempt: %d', operation, attempt);\n\n const nextDelayMs = RetryHelper.computeBackoffDelayMs({ attempt, backoff });\n\n if (nextDelayMs > 0) {\n await RetryHelper.sleepWithSignal({ ms: nextDelayMs, operation, signal });\n }\n }\n\n logger\n ?.for('executeWithRetryUntil')\n .warn('[%s] Exhausted retries - returning last (stale) result', operation);\n\n return lastResult as T;\n }\n}\n"]}
1
+ {"version":3,"file":"helper.js","sourceRoot":"","sources":["../../../../src/modules/retry/helper.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,EAAE,cAAc,EAAE,MAAM,6BAA6B,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAE9E,OAAO,EAAE,UAAU,EAAE,MAAM,gBAAgB,CAAC;AAM5C;;;GAGG;AACH,MAAM,OAAO,WAAY,SAAQ,UAAU;aACjB,yBAAoB,GAAG,MAAM,CAAC,GAAG,CAAC,sCAAsC,CAAC,CAAC;IAElG,gGAAgG;IAChG,MAAM,CAAC,mBAAmB,CAAC,KAAc;QACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,WAAW,CAAC,oBAAoB,IAAI,KAAK,CAAC;IAClG,CAAC;IAEO,MAAM,CAAC,iBAAiB,CAAC,IAA8C;QAC7E,MAAM,KAAK,GAAG,QAAQ,CAAC;YACrB,OAAO,EAAE,oBAAoB,IAAI,CAAC,SAAS,qBAAqB,IAAI,CAAC,SAAS,IAAI;SACnF,CAAC,CAAC;QACH,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,WAAW,CAAC,oBAAoB,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;QAEhF,OAAO,KAAK,CAAC;IACf,CAAC;IAEO,MAAM,CAAC,cAAc,CAAC,IAAiD;QAC7E,IAAI,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;YACzB,MAAM,QAAQ,CAAC;gBACb,OAAO,EAAE,sBAAsB,IAAI,CAAC,SAAS,uBAAuB,MA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AAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAC7B,IAAI,UAAyB,CAAC;QAE9B,KAAK,IAAI,OAAO,GAAG,CAAC,EAAE,OAAO,IAAI,WAAW,EAAE,OAAO,EAAE,EAAE,CAAC;YACxD,WAAW,CAAC,cAAc,CAAC,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;YAElD,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC,CAAC;YACrD,UAAU,GAAG,OAAO,CAAC;YAErB,IAAI,KAAK,CAAC,UAAU,CAAC,EAAE,CAAC;gBACtB,OAAO,UAAU,CAAC;YACpB,CAAC;YAED,MAAM,SAAS,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC;YAEzC,IAAI,OAAO,IAAI,WAAW,IAAI,CAAC,UAAU,KAAK,SAAS,IAAI,SAAS,IAAI,UAAU,CAAC,EAAE,CAAC;gBACpF,MAAM;YACR,CAAC;YAED,MAAM;gBACJ,EAAE,GAAG,CAAC,uBAAuB,CAAC;iBAC7B,KAAK,CAAC,4CAA4C,EAAE,SAAS,EAAE,OAAO,CAAC,CAAC;YAE3E,MAAM,WAAW,GAAG,WAAW,CAAC,qBAAqB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;YAE5E,IAAI,WAAW,GAAG,CAAC,EAAE,CAAC;gBACpB,MAAM,WAAW,CAAC,eAAe,CAAC,EAAE,EAAE,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,EAAE,CAAC,CAAC;YAC5E,CAAC;QACH,CAAC;QAED,MAAM;YACJ,EAAE,GAAG,CAAC,uBAAuB,CAAC;aAC7B,IAAI,CAAC,wDAAwD,EAAE,SAAS,CAAC,CAAC;QAE7E,OAAO,UAAe,CAAC;IACzB,CAAC","sourcesContent":["import type { ValueOrPromise } from '@/common';\nimport { getError } from '@/modules/error';\nimport type { ILogger } from '@/modules/logger';\nimport { PromiseUtility } from '@/utilities/promise.utility';\nimport { RetryBackoffStrategies, RetryJitterModes } from './common/constants';\nimport type { IRetryBackoffOptions, IRetryContext } from './common/types';\nimport { BaseHelper } from '@/modules/base';\n\ntype TRetryAttemptOutcome<T> =\n | { isResolved: true; value: T }\n | { isResolved: false; error: unknown; isRetryAllowed: boolean };\n\n/**\n * Static members call each other through the class name (`RetryHelper.xxx`), never `this` - a\n * detached static method loses its `this` binding.\n */\nexport class RetryHelper extends BaseHelper {\n private static readonly RETRY_TIMEOUT_MARKER = Symbol.for('@venizia/ignis-helpers:retry-timeout');\n\n /** True when `error` is a per-attempt timeout raised by `runWithTimeout`/`executeWithRetry`. */\n static isRetryTimeoutError(error: unknown): boolean {\n return typeof error === 'object' && error !== null && RetryHelper.RETRY_TIMEOUT_MARKER in error;\n }\n\n private static buildTimeoutError(opts: { operation: string; timeoutMs: number }) {\n const error = getError({\n message: `[runWithTimeout][${opts.operation}] Timed out after ${opts.timeoutMs}ms`,\n });\n Object.defineProperty(error, RetryHelper.RETRY_TIMEOUT_MARKER, { value: true });\n\n return error;\n }\n\n private static throwIfAborted(opts: { operation: string; signal?: AbortSignal }) {\n if (opts.signal?.aborted) {\n throw getError({\n message: `[executeWithRetry][${opts.operation}] Aborted | Reason: ${String(opts.signal.reason ?? 'unknown')}`,\n });\n }\n }\n\n /** `sleep` that wakes up early (and rejects) when `signal` aborts mid-wait. */\n private static async sleepWithSignal(opts: {\n ms: number;\n operation: string;\n signal?: AbortSignal;\n }) {\n const { ms, operation, signal } = opts;\n\n if (!signal) {\n await PromiseUtility.sleep({ ms });\n\n return;\n }\n\n RetryHelper.throwIfAborted({ operation, signal });\n\n // The listener is removed in `finally` rather than by the timer callback - the two would otherwise have to reference each other, and a leaked listener on a long-lived signal accumulates across retries.\n let removeAbortListener = () => {};\n\n try {\n await new Promise<void>((resolve, reject) => {\n const timer = setTimeout(resolve, ms);\n\n const onAbort = () => {\n clearTimeout(timer);\n reject(\n getError({\n message: `[executeWithRetry][${operation}] Aborted during backoff | Reason: ${String(signal.reason ?? 'unknown')}`,\n }),\n );\n };\n\n removeAbortListener = () => signal.removeEventListener('abort', onAbort);\n signal.addEventListener('abort', onAbort, { once: true });\n });\n } finally {\n removeAbortListener();\n }\n }\n\n /** Races `execution` against `timeoutMs` (`<= 0`/omitted = no timeout). The losing execution keeps running - JS promises cannot be cancelled - so pass `signal` through for cooperative cancellation. */\n static async runWithTimeout<T>(opts: {\n operation: string;\n timeoutMs?: number;\n execution: () => ValueOrPromise<T>;\n }): Promise<T> {\n const { operation, timeoutMs, execution } = opts;\n\n if (!timeoutMs || timeoutMs <= 0) {\n return execution();\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeoutPromise = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n reject(RetryHelper.buildTimeoutError({ operation, timeoutMs }));\n }, timeoutMs);\n });\n\n try {\n const result = await Promise.race([Promise.resolve().then(execution), timeoutPromise]);\n\n return result;\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** The pre-jitter delay for `attempt` (1-based, i.e. the delay AFTER attempt N failed). */\n static computeBackoffDelayMs(opts: { attempt: number; backoff?: IRetryBackoffOptions }): number {\n const { attempt } = opts;\n const {\n strategy = RetryBackoffStrategies.EXPONENTIAL,\n initialDelayMs = 250,\n multiplier = 2,\n maxDelayMs = 30_000,\n scheduleMs,\n jitter = RetryJitterModes.FULL,\n } = opts.backoff ?? {};\n\n let delayMs: number;\n\n switch (strategy) {\n case RetryBackoffStrategies.FIXED: {\n delayMs = initialDelayMs;\n break;\n }\n case RetryBackoffStrategies.LINEAR: {\n delayMs = initialDelayMs * attempt;\n break;\n }\n case RetryBackoffStrategies.EXPONENTIAL: {\n delayMs = initialDelayMs * Math.pow(multiplier, attempt - 1);\n break;\n }\n case RetryBackoffStrategies.SCHEDULE: {\n if (!scheduleMs?.length) {\n throw getError({\n message:\n '[computeBackoffDelayMs] strategy SCHEDULE requires a non-empty backoff.scheduleMs',\n });\n }\n\n delayMs = scheduleMs[Math.min(attempt - 1, scheduleMs.length - 1)];\n break;\n }\n default: {\n throw getError({\n message: `[computeBackoffDelayMs] Unknown backoff strategy '${strategy}' | Expected one of: ${[...RetryBackoffStrategies.SCHEME_SET].join(', ')}`,\n });\n }\n }\n\n delayMs = Math.min(delayMs, maxDelayMs);\n\n if (delayMs <= 0) {\n return 0;\n }\n\n switch (jitter) {\n case RetryJitterModes.NONE: {\n return delayMs;\n }\n case RetryJitterModes.FULL: {\n return Math.floor(Math.random() * delayMs);\n }\n case RetryJitterModes.EQUAL: {\n const half = delayMs / 2;\n\n return Math.floor(half + Math.random() * half);\n }\n default: {\n throw getError({\n message: `[computeBackoffDelayMs] Unknown jitter mode '${jitter}' | Expected one of: ${[...RetryJitterModes.SCHEME_SET].join(', ')}`,\n });\n }\n }\n }\n\n /** One `executeWithRetry` attempt and everything that follows a failure: `shouldRetry` refusing rethrows, otherwise the bounds are checked and - when another attempt is allowed - the retry is logged, `onRetry` awaited and the backoff slept, all before returning. */\n private static async runRetryAttempt<T>(opts: {\n attempt: number;\n attemptTimeoutMs?: number;\n startedAt: number;\n deadline?: number;\n maxAttempts: number;\n operation: string;\n signal?: AbortSignal;\n logger?: ILogger;\n backoff?: IRetryBackoffOptions;\n execution: (context: { attempt: number; signal?: AbortSignal }) => ValueOrPromise<T>;\n shouldRetry?: (context: IRetryContext) => ValueOrPromise<boolean>;\n getDelayMs?: (context: IRetryContext) => number | undefined;\n onRetry?: (context: IRetryContext & { nextDelayMs: number }) => ValueOrPromise<void>;\n }): Promise<TRetryAttemptOutcome<T>> {\n const {\n attempt,\n attemptTimeoutMs,\n startedAt,\n deadline,\n maxAttempts,\n operation,\n signal,\n logger,\n backoff,\n execution,\n shouldRetry,\n getDelayMs,\n onRetry,\n } = opts;\n\n try {\n const value = await RetryHelper.runWithTimeout({\n operation,\n timeoutMs: attemptTimeoutMs,\n execution: () => execution({ attempt, signal }),\n });\n\n return { isResolved: true, value };\n } catch (error) {\n const elapsedMs = Date.now() - startedAt;\n\n const verdict = shouldRetry ? shouldRetry({ attempt, error, elapsedMs }) : true;\n const isRetryAllowed = await verdict;\n\n if (!isRetryAllowed) {\n throw error;\n }\n\n if (attempt >= maxAttempts) {\n return { isResolved: false, error, isRetryAllowed: false };\n }\n\n // `getDelayMs` is a FLOOR (a server's Retry-After): the backoff never shortens it, and the deadline check below sees the longer wait.\n const nextDelayMs = Math.max(\n RetryHelper.computeBackoffDelayMs({ attempt, backoff }),\n getDelayMs?.({ attempt, error, elapsedMs }) ?? 0,\n );\n\n if (deadline && Date.now() + nextDelayMs >= deadline) {\n return { isResolved: false, error, isRetryAllowed: false };\n }\n\n logger\n ?.for('executeWithRetry')\n .debug(\n '[%s] Attempt %d/%d failed - retrying in %dms | Error: %s',\n operation,\n attempt,\n maxAttempts,\n nextDelayMs,\n error,\n );\n\n await onRetry?.({ attempt, error, elapsedMs, nextDelayMs });\n\n if (nextDelayMs > 0) {\n await RetryHelper.sleepWithSignal({ ms: nextDelayMs, operation, signal });\n }\n\n return { isResolved: false, error, isRetryAllowed: true };\n }\n }\n\n /** Retries `execution` with backoff, bounded by `maxAttempts`/`maxTotalMs`. JS cannot cancel a running promise - `signal` only stops between attempts/sleeps, so a timed-out execution keeps running unless it honors the signal itself. */\n static async executeWithRetry<T>(opts: {\n signal?: AbortSignal;\n logger?: ILogger;\n operation: string;\n\n /** @default 3 */\n maxAttempts?: number;\n\n /** Total budget across attempts AND sleeps. Unlimited when omitted. */\n maxTotalMs?: number;\n\n /** Per-attempt race. No per-attempt timeout when omitted. */\n perAttemptTimeoutMs?: number;\n\n backoff?: IRetryBackoffOptions;\n\n execution: (context: { attempt: number; signal?: AbortSignal }) => ValueOrPromise<T>;\n\n /** Return `false` to stop retrying and rethrow `context.error` immediately. */\n shouldRetry?: (context: IRetryContext) => ValueOrPromise<boolean>;\n\n /** The least wait before the next attempt, in milliseconds (a server's `Retry-After`); the backoff delay applies when it is longer. `undefined` leaves the backoff alone. */\n getDelayMs?: (context: IRetryContext) => number | undefined;\n\n /** Observability hook, awaited before the backoff sleep. */\n onRetry?: (context: IRetryContext & { nextDelayMs: number }) => ValueOrPromise<void>;\n }): Promise<T> {\n const {\n operation,\n execution,\n maxAttempts = 3,\n maxTotalMs,\n perAttemptTimeoutMs,\n backoff,\n shouldRetry,\n getDelayMs,\n onRetry,\n signal,\n logger,\n } = opts;\n\n if (maxAttempts < 1) {\n throw getError({\n message: `[executeWithRetry][${operation}] maxAttempts must be >= 1 | Got: ${maxAttempts}`,\n });\n }\n\n const startedAt = Date.now();\n // `!== undefined`, never truthiness: a budget of 0 - or a negative one, which is what `deadline - Date.now()` yields under load - means NO time left, not unlimited time.\n const deadline = maxTotalMs !== undefined ? startedAt + maxTotalMs : undefined;\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n RetryHelper.throwIfAborted({ operation, signal });\n\n const remainingMs = deadline ? deadline - Date.now() : undefined;\n\n if (remainingMs !== undefined && remainingMs <= 0) {\n break;\n }\n\n let attemptTimeoutMs = perAttemptTimeoutMs;\n\n if (remainingMs !== undefined) {\n attemptTimeoutMs = attemptTimeoutMs ? Math.min(attemptTimeoutMs, remainingMs) : remainingMs;\n }\n\n const outcome = await RetryHelper.runRetryAttempt({\n attempt,\n attemptTimeoutMs,\n startedAt,\n deadline,\n maxAttempts,\n operation,\n signal,\n logger,\n backoff,\n execution,\n shouldRetry,\n getDelayMs,\n onRetry,\n });\n\n if (outcome.isResolved) {\n return outcome.value;\n }\n\n lastError = outcome.error;\n\n if (!outcome.isRetryAllowed) {\n break;\n }\n }\n\n const elapsedMs = Date.now() - startedAt;\n\n // The budget can run out BEFORE the first attempt (an expired `maxTotalMs`), leaving no error to rethrow; `throw undefined` would detonate inside the caller's own handler on `error.message`.\n if (lastError === undefined) {\n throw getError({\n message: `[executeWithRetry][${operation}] Time budget exhausted before any attempt ran | maxTotalMs: ${maxTotalMs}`,\n });\n }\n\n logger\n ?.for('executeWithRetry')\n .warn('[%s] Exhausted retries | Elapsed: %dms | Error: %s', operation, elapsedMs, lastError);\n\n throw lastError;\n }\n\n /** Retries `execution` while `until(result)` returns false - for read-after-write staleness behind a replicated pool. Never worse than a single un-retried call: on exhaustion the LAST result is returned rather than an error, and a thrown error propagates immediately instead of being retried. Only wrap idempotent operations. */\n static async executeWithRetryUntil<T>(opts: {\n signal?: AbortSignal;\n logger?: ILogger;\n operation: string;\n\n /** @default 3 */\n maxAttempts?: number;\n\n /** Bounds when a NEW attempt may start; it never interrupts an attempt already in flight, so the first execution always runs to completion - a budget of 0 just means \"no retries\". */\n maxTotalMs?: number;\n\n backoff?: IRetryBackoffOptions;\n\n execution: (context: { attempt: number; signal?: AbortSignal }) => ValueOrPromise<T>;\n\n /** Retry while this returns false. */\n until: (result: T) => boolean;\n }): Promise<T> {\n const {\n signal,\n logger,\n operation,\n maxAttempts = 3,\n maxTotalMs,\n backoff,\n execution,\n until,\n } = opts;\n\n if (maxAttempts < 1) {\n throw getError({\n message: `[executeWithRetryUntil][${operation}] maxAttempts must be >= 1 | Got: ${maxAttempts}`,\n });\n }\n\n // Surfaced before the first execution - a misconfigured backoff discovered mid-loop would discard an already-fetched result.\n RetryHelper.computeBackoffDelayMs({ attempt: 1, backoff });\n\n const startedAt = Date.now();\n let lastResult: T | undefined;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n RetryHelper.throwIfAborted({ operation, signal });\n\n const result2 = await execution({ attempt, signal });\n lastResult = result2;\n\n if (until(lastResult)) {\n return lastResult;\n }\n\n const elapsedMs = Date.now() - startedAt;\n\n if (attempt >= maxAttempts || (maxTotalMs !== undefined && elapsedMs >= maxTotalMs)) {\n break;\n }\n\n logger\n ?.for('executeWithRetryUntil')\n .debug('[%s] until condition not met | Attempt: %d', operation, attempt);\n\n const nextDelayMs = RetryHelper.computeBackoffDelayMs({ attempt, backoff });\n\n if (nextDelayMs > 0) {\n await RetryHelper.sleepWithSignal({ ms: nextDelayMs, operation, signal });\n }\n }\n\n logger\n ?.for('executeWithRetryUntil')\n .warn('[%s] Exhausted retries - returning last (stale) result', operation);\n\n return lastResult as T;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/ignis-helpers",
3
- "version": "0.4.8",
3
+ "version": "0.5.0-0",
4
4
  "description": "Production-ready TypeScript utility library: pluggable logging (winston or pino behind one ILogger contract), Redis single/cluster/sentinel with pub/sub, BullMQ/MQTT/Kafka message queues, MinIO/Disk/Bun-S3 object storage, AES-256/RSA/ECDH cryptography, Snowflake UID generation, cron scheduling, Socket.IO/WebSocket, TCP/TLS/UDP networking, HTTP clients, secrets/Vault, worker thread pools, and environment management. Sub-path imports isolate optional peer dependencies so the root barrel never forces a peer into your bundle.",
5
5
  "keywords": [
6
6
  "aes",
@@ -176,7 +176,7 @@
176
176
  "force-update": "sh ../../scripts/build/force-update.sh"
177
177
  },
178
178
  "dependencies": {
179
- "@venizia/ignis-inversion": "0.4.7",
179
+ "@venizia/ignis-inversion": "0.5.0-0",
180
180
  "reflect-metadata": "^0.2.2",
181
181
  "zod": "^4.6.7"
182
182
  },
@@ -188,7 +188,7 @@
188
188
  "@socket.io/redis-emitter": "^5.1.0",
189
189
  "@types/bun": "^1.4.3",
190
190
  "@types/luxon": "^3.7.6",
191
- "@venizia/dev-configs": "0.4.8",
191
+ "@venizia/dev-configs": "0.5.0-0",
192
192
  "axios": "^1.20.0",
193
193
  "bullmq": "^6.4.0",
194
194
  "cron": "^4.4.0",
@@ -1,41 +0,0 @@
1
- import { type THttpMethod } from '../../../../common/constants/http.js';
2
- import { type IQueryStringOptions } from '../../utilities/query-string.js';
3
- import { BaseNetworkRequest } from '../base-network-request.helper.js';
4
- import { AbstractNetworkFetchableHelper, type IRequestOptions, type TFetcherLogger } from './base-fetcher.js';
5
- /** Request accepted by `NodeFetcher`: `RequestInit` plus `url`; `params` are written into the url query. */
6
- export interface INodeFetchRequestOptions extends RequestInit, IRequestOptions {
7
- url: string;
8
- method?: THttpMethod;
9
- params?: Record<string, unknown>;
10
- }
11
- /** Fetcher over the global `fetch` (`getWorker()`). `timeout` (milliseconds) aborts the request and is combined with a `signal` the caller passes. */
12
- export declare class NodeFetcher extends AbstractNetworkFetchableHelper<'node-fetch', INodeFetchRequestOptions, Awaited<ReturnType<typeof fetch>>, typeof fetch> {
13
- private defaultConfigs;
14
- private queryString;
15
- constructor(opts: {
16
- name: string;
17
- defaultConfigs: RequestInit;
18
- /** How `params` are written into the url; unset fields behave as `node:querystring` does. */
19
- queryString?: IQueryStringOptions;
20
- logger?: TFetcherLogger;
21
- });
22
- /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */
23
- protected serializeBody(opts: {
24
- body: unknown;
25
- }): RequestInit['body'] | undefined;
26
- send(opts: INodeFetchRequestOptions, logger?: TFetcherLogger): Promise<Response>;
27
- }
28
- /** Options of `NodeFetchNetworkRequest`: `RequestInit` plus `baseUrl` and `queryString`, which sets how `params` are written into every url. */
29
- export interface INodeFetchNetworkRequestOptions {
30
- name: string;
31
- networkOptions: RequestInit & {
32
- baseUrl?: string;
33
- /** How `params` are written into every url this request sends; see {@link IQueryStringOptions}. */
34
- queryString?: IQueryStringOptions;
35
- };
36
- }
37
- /** `BaseNetworkRequest` over a `NodeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */
38
- export declare class NodeFetchNetworkRequest extends BaseNetworkRequest<'node-fetch'> {
39
- constructor(opts: INodeFetchNetworkRequestOptions);
40
- }
41
- //# sourceMappingURL=node-fetcher.d.ts.map
@@ -1,111 +0,0 @@
1
- import { RedactUtility } from '../../../../common/redact.js';
2
- import { HTTP } from '../../../../common/constants/http.js';
3
- import { QueryStringSeparators, QueryStringUtility, } from '../../utilities/query-string.js';
4
- import { BaseNetworkRequest } from '../base-network-request.helper.js';
5
- import { AbstractNetworkFetchableHelper, } from './base-fetcher.js';
6
- /** What `fetch` takes as a body as it is: encoding any of these again would change the bytes sent. A constructor is looked up on `globalThis` so a runtime without one (no `FormData`) just never matches it. */
7
- const isRawBody = (body) => {
8
- if (typeof body === 'string' || ArrayBuffer.isView(body) || body instanceof ArrayBuffer) {
9
- return true;
10
- }
11
- return ['Blob', 'FormData', 'URLSearchParams', 'ReadableStream'].some((name) => {
12
- const ctor = Reflect.get(globalThis, name);
13
- return typeof ctor === 'function' && body instanceof ctor;
14
- });
15
- };
16
- /** Fetcher over the global `fetch` (`getWorker()`). `timeout` (milliseconds) aborts the request and is combined with a `signal` the caller passes. */
17
- export class NodeFetcher extends AbstractNetworkFetchableHelper {
18
- constructor(opts) {
19
- super({ name: opts.name, variant: 'node-fetch', worker: fetch });
20
- const { name, defaultConfigs } = opts;
21
- this.name = name;
22
- opts?.logger?.info('Creating new network request worker instance! Name: %s', this.name);
23
- this.defaultConfigs = defaultConfigs;
24
- this.queryString = opts.queryString ?? {};
25
- }
26
- /** A raw body passes through; a plain object or an array is JSON-encoded; no body stays no body. */
27
- serializeBody(opts) {
28
- const { body } = opts;
29
- if (body === undefined || body === null) {
30
- return undefined;
31
- }
32
- return isRawBody(body) ? body : JSON.stringify(body);
33
- }
34
- async send(opts, logger) {
35
- const { url, method = HTTP.Methods.GET, params, body, headers, timeout, signal, ...rest } = opts;
36
- let timeoutId;
37
- let timeoutController;
38
- let effectiveSignal = signal;
39
- if (timeout) {
40
- timeoutController = new AbortController();
41
- timeoutId = setTimeout(() => {
42
- timeoutController?.abort();
43
- }, timeout);
44
- // Composed, never substituted: a timeout must not silently swallow the caller's own signal, or the caller would believe it cancelled a request that is in fact still running. Either source - and a signal already aborted before the call - aborts the request.
45
- effectiveSignal = signal
46
- ? AbortSignal.any([signal, timeoutController.signal])
47
- : timeoutController.signal;
48
- }
49
- const requestConfigs = {
50
- ...this.defaultConfigs,
51
- ...rest,
52
- method: method.toUpperCase(),
53
- body: this.serializeBody({ body }),
54
- // The call's headers REPLACE the defaults (a caller that sends a multipart body leaves the content type out so `fetch` can write the boundary); a call with none keeps them. Spreading an absent `headers` over the config used to erase the defaults.
55
- headers: headers ?? this.defaultConfigs.headers,
56
- signal: effectiveSignal,
57
- };
58
- // `?` only when the url carries no query string of its own - a second `?` is not a separator, so the server would read the previous parameter's value as `1?extra=2`.
59
- const serializedParams = params
60
- ? QueryStringUtility.toQueryString({ params, ...this.queryString })
61
- : '';
62
- const requestUrl = serializedParams
63
- ? `${url}${url.includes(QueryStringSeparators.START) ? QueryStringSeparators.PAIR : QueryStringSeparators.START}${serializedParams}`
64
- : url;
65
- // The body is NEVER logged, only its size. `fetch` bodies are strings, and `redactSecrets` walks
66
- // object keys - so a JSON credential payload passed straight through as a string was printed in
67
- // full, with no key for the redactor to match on. Headers are normalised through `Headers` first
68
- // because the `string[][]` form is a list of tuples, which key matching cannot see either.
69
- const loggableConfigs = {
70
- ...requestConfigs,
71
- body: typeof requestConfigs.body === 'string'
72
- ? `[body ${requestConfigs.body.length} chars]`
73
- : requestConfigs.body
74
- ? '[body]'
75
- : undefined,
76
- headers: requestConfigs.headers,
77
- };
78
- // Straight on the logger it was handed, never `logger.for(...)`: a host logger may carry only `debug` and `info`. With none handed, nothing is logged - no default logger is built, so a browser never reaches the node-only provider.
79
- logger?.debug('[%s] URL: %s | Props: %s | Timeout: %s', this.send.name, url, RedactUtility.redactSecrets({ value: loggableConfigs }), timeout);
80
- try {
81
- const rs = await fetch(requestUrl, requestConfigs);
82
- return rs;
83
- }
84
- finally {
85
- if (timeoutId) {
86
- clearTimeout(timeoutId);
87
- }
88
- }
89
- }
90
- }
91
- /** `BaseNetworkRequest` over a `NodeFetcher`. Request headers default to a JSON content type, and the caller's headers win. */
92
- export class NodeFetchNetworkRequest extends BaseNetworkRequest {
93
- constructor(opts) {
94
- const { name, networkOptions } = opts;
95
- const { headers, baseUrl, queryString, ...rest } = networkOptions;
96
- // Case-insensitive, like the wire: a caller's `Content-Type` replaces the default one.
97
- const mergedHeaders = new Headers({ 'content-type': 'application/json; charset=utf-8' });
98
- new Headers(headers).forEach((value, key) => mergedHeaders.set(key, value));
99
- const defaultConfigs = {
100
- ...rest,
101
- // A plain object, so the request log (which redacts by key) can read it; a `Headers` instance has no own entries.
102
- headers: Object.fromEntries(mergedHeaders),
103
- };
104
- super({
105
- name,
106
- baseUrl,
107
- fetcher: new NodeFetcher({ name, defaultConfigs, queryString }),
108
- });
109
- }
110
- }
111
- //# sourceMappingURL=node-fetcher.js.map