@venizia/ignis-helpers 0.4.8 → 0.5.0-1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/esm/common/constants/http.d.ts +17 -1
- package/dist/esm/common/constants/http.js +17 -0
- package/dist/esm/common/constants/http.js.map +1 -1
- package/dist/esm/common/redact.js +2 -0
- package/dist/esm/common/redact.js.map +1 -1
- package/dist/esm/core.d.ts +5 -2
- package/dist/esm/core.js +5 -2
- package/dist/esm/core.js.map +1 -1
- package/dist/esm/modules/network/http-request/base-network-request.helper.d.ts +5 -0
- package/dist/esm/modules/network/http-request/base-network-request.helper.js +14 -17
- package/dist/esm/modules/network/http-request/base-network-request.helper.js.map +1 -1
- package/dist/esm/modules/network/http-request/common/constants.d.ts +2 -1
- package/dist/esm/modules/network/http-request/common/constants.js +2 -1
- package/dist/esm/modules/network/http-request/common/constants.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.d.ts +37 -11
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js +181 -38
- package/dist/esm/modules/network/http-request/fetcher/axios-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.d.ts +204 -18
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js +433 -13
- package/dist/esm/modules/network/http-request/fetcher/base-fetcher.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/body-limit.d.ts +36 -0
- package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js +119 -0
- package/dist/esm/modules/network/http-request/fetcher/common/body-limit.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/errors.d.ts +40 -0
- package/dist/esm/modules/network/http-request/fetcher/common/errors.js +37 -0
- package/dist/esm/modules/network/http-request/fetcher/common/errors.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/guard.d.ts +27 -0
- package/dist/esm/modules/network/http-request/fetcher/common/guard.js +2 -0
- package/dist/esm/modules/network/http-request/fetcher/common/guard.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/index.d.ts +6 -0
- package/dist/esm/modules/network/http-request/fetcher/common/index.js +6 -0
- package/dist/esm/modules/network/http-request/fetcher/common/index.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/request-context.d.ts +15 -0
- package/dist/esm/modules/network/http-request/fetcher/common/request-context.js +11 -0
- package/dist/esm/modules/network/http-request/fetcher/common/request-context.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/response-reader.d.ts +133 -0
- package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js +264 -0
- package/dist/esm/modules/network/http-request/fetcher/common/response-reader.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/common/types.d.ts +65 -1
- package/dist/esm/modules/network/http-request/fetcher/common/types.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/common/utilities.d.ts +68 -0
- package/dist/esm/modules/network/http-request/fetcher/common/utilities.js +143 -0
- package/dist/esm/modules/network/http-request/fetcher/common/utilities.js.map +1 -0
- package/dist/esm/modules/network/http-request/fetcher/index.d.ts +2 -1
- package/dist/esm/modules/network/http-request/fetcher/index.js +2 -1
- package/dist/esm/modules/network/http-request/fetcher/index.js.map +1 -1
- package/dist/esm/modules/network/http-request/fetcher/native-fetcher.d.ts +85 -0
- package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js +221 -0
- package/dist/esm/modules/network/http-request/fetcher/native-fetcher.js.map +1 -0
- package/dist/esm/modules/network/utilities/index.d.ts +1 -0
- package/dist/esm/modules/network/utilities/index.js +1 -0
- package/dist/esm/modules/network/utilities/index.js.map +1 -1
- package/dist/esm/modules/network/utilities/query-string.d.ts +6 -23
- package/dist/esm/modules/network/utilities/query-string.js +3 -17
- package/dist/esm/modules/network/utilities/query-string.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-builder.d.ts +39 -0
- package/dist/esm/modules/network/utilities/url-builder.js +102 -0
- package/dist/esm/modules/network/utilities/url-builder.js.map +1 -0
- package/dist/esm/modules/network/utilities/url-safety/common/constants.d.ts +0 -3
- package/dist/esm/modules/network/utilities/url-safety/common/constants.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/common/errors.d.ts +38 -0
- package/dist/esm/modules/network/utilities/url-safety/common/errors.js +33 -1
- package/dist/esm/modules/network/utilities/url-safety/common/errors.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/common/types.d.ts +26 -3
- package/dist/esm/modules/network/utilities/url-safety/common/types.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/guard.d.ts +46 -0
- package/dist/esm/modules/network/utilities/url-safety/guard.js +145 -0
- package/dist/esm/modules/network/utilities/url-safety/guard.js.map +1 -0
- package/dist/esm/modules/network/utilities/url-safety/index.d.ts +1 -1
- package/dist/esm/modules/network/utilities/url-safety/index.js +1 -1
- package/dist/esm/modules/network/utilities/url-safety/index.js.map +1 -1
- package/dist/esm/modules/network/utilities/url-safety/policy.d.ts +52 -2
- package/dist/esm/modules/network/utilities/url-safety/policy.js +161 -14
- package/dist/esm/modules/network/utilities/url-safety/policy.js.map +1 -1
- package/dist/esm/modules/queue/bullmq/helper.d.ts +43 -7
- package/dist/esm/modules/queue/bullmq/helper.js +70 -2
- package/dist/esm/modules/queue/bullmq/helper.js.map +1 -1
- package/dist/esm/modules/retry/helper.d.ts +3 -1
- package/dist/esm/modules/retry/helper.js +8 -4
- package/dist/esm/modules/retry/helper.js.map +1 -1
- package/dist/esm/utilities/request.utility.d.ts +1 -25
- package/dist/esm/utilities/request.utility.js +0 -46
- package/dist/esm/utilities/request.utility.js.map +1 -1
- package/package.json +4 -4
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.d.ts +0 -41
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js +0 -111
- package/dist/esm/modules/network/http-request/fetcher/node-fetcher.js.map +0 -1
- package/dist/esm/modules/network/utilities/url-safety/ingest.d.ts +0 -95
- package/dist/esm/modules/network/utilities/url-safety/ingest.js +0 -328
- 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,SAA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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;IAqClB,YAAY,OAA+D;QACzE,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,MAAM,EACN,QAAQ,EACR,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,S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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
|
-
|
|
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
|
-
|
|
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,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,MAA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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":[],"m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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"]}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { TContentDispositionType } from '../common/constants/http.js';
|
|
1
2
|
import type { TConstValue } from '../common/types/index.js';
|
|
2
3
|
/** A request remark: `id`, `url` and `method`, plus any extra keys. */
|
|
3
4
|
export interface IRequestedRemark {
|
|
@@ -43,15 +44,6 @@ export interface IParsedMultipartBody {
|
|
|
43
44
|
files: IParsedFile[];
|
|
44
45
|
fields: Record<string, string>;
|
|
45
46
|
}
|
|
46
|
-
/** How a client treats a download: ATTACHMENT saves it, INLINE shows it. */
|
|
47
|
-
export declare class ContentDispositionTypes {
|
|
48
|
-
static readonly ATTACHMENT = "attachment";
|
|
49
|
-
static readonly INLINE = "inline";
|
|
50
|
-
static readonly SCHEME_SET: Set<string>;
|
|
51
|
-
static isValid(value: string): boolean;
|
|
52
|
-
}
|
|
53
|
-
/** Valid Content-Disposition type values. */
|
|
54
|
-
export type TContentDispositionType = TConstValue<typeof ContentDispositionTypes>;
|
|
55
47
|
/** Multipart body parsing and `Content-Disposition` header building and parsing for requests and uploads. */
|
|
56
48
|
export declare class RequestUtility {
|
|
57
49
|
/** Built on first use: a helper opens a logger, which is work an import alone should not do. */
|
|
@@ -72,22 +64,6 @@ export declare class RequestUtility {
|
|
|
72
64
|
filename: string;
|
|
73
65
|
type: TContentDispositionType;
|
|
74
66
|
}): string;
|
|
75
|
-
/**
|
|
76
|
-
* Reads a filename out of a `Content-Disposition` value.
|
|
77
|
-
*
|
|
78
|
-
* Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,
|
|
79
|
-
* and the one hand-rolled parsers miss), a quoted `filename="..."`, and a bare `filename=...`.
|
|
80
|
-
* Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in
|
|
81
|
-
* a product with non-English filenames is most of them.
|
|
82
|
-
*
|
|
83
|
-
* The pair of {@link RequestUtility.buildContentDispositionHeader}: one writes the header, this one reads it.
|
|
84
|
-
*/
|
|
85
|
-
static parseContentDisposition(opts: {
|
|
86
|
-
header: string | null | undefined;
|
|
87
|
-
}): {
|
|
88
|
-
type?: string;
|
|
89
|
-
filename?: string;
|
|
90
|
-
};
|
|
91
67
|
}
|
|
92
68
|
export {};
|
|
93
69
|
//# sourceMappingURL=request.utility.d.ts.map
|
|
@@ -15,15 +15,6 @@ export class MultipartStorages {
|
|
|
15
15
|
/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */
|
|
16
16
|
const UNENCODABLE_FILENAME_CHARACTERS = /(?![])[\p{Cc}\p{Cf}\p{Cs}]/gu;
|
|
17
17
|
const LEADING_DOTS = /^\.+/;
|
|
18
|
-
/** How a client treats a download: ATTACHMENT saves it, INLINE shows it. */
|
|
19
|
-
export class ContentDispositionTypes {
|
|
20
|
-
static { this.ATTACHMENT = 'attachment'; }
|
|
21
|
-
static { this.INLINE = 'inline'; }
|
|
22
|
-
static { this.SCHEME_SET = new Set([this.ATTACHMENT, this.INLINE]); }
|
|
23
|
-
static isValid(value) {
|
|
24
|
-
return this.SCHEME_SET.has(value);
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
18
|
/** Multipart body parsing and `Content-Disposition` header building and parsing for requests and uploads. */
|
|
28
19
|
export class RequestUtility {
|
|
29
20
|
/** Uniqueness for a spooled filename, not a secret; the helper's 16-byte floor is the shortest it makes. */
|
|
@@ -165,42 +156,5 @@ export class RequestUtility {
|
|
|
165
156
|
// filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.
|
|
166
157
|
return `${type}; filename="${sanitized}"; filename*=UTF-8''${encoded}`;
|
|
167
158
|
}
|
|
168
|
-
/**
|
|
169
|
-
* Reads a filename out of a `Content-Disposition` value.
|
|
170
|
-
*
|
|
171
|
-
* Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,
|
|
172
|
-
* and the one hand-rolled parsers miss), a quoted `filename="..."`, and a bare `filename=...`.
|
|
173
|
-
* Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in
|
|
174
|
-
* a product with non-English filenames is most of them.
|
|
175
|
-
*
|
|
176
|
-
* The pair of {@link RequestUtility.buildContentDispositionHeader}: one writes the header, this one reads it.
|
|
177
|
-
*/
|
|
178
|
-
static parseContentDisposition(opts) {
|
|
179
|
-
const { header } = opts;
|
|
180
|
-
if (!header) {
|
|
181
|
-
return {};
|
|
182
|
-
}
|
|
183
|
-
const type = header.split(';')[0]?.trim() || undefined;
|
|
184
|
-
// `filename*` wins when both are present - it is the one that can carry a non-ASCII name.
|
|
185
|
-
const extended = header.match(/filename\*\s*=\s*([^;]+)/i);
|
|
186
|
-
if (extended) {
|
|
187
|
-
const value = extended[1].trim();
|
|
188
|
-
// `UTF-8''name` or `UTF-8'lang'name`; anything before the last quote is charset and language.
|
|
189
|
-
const encoded = value.slice(value.lastIndexOf("'") + 1);
|
|
190
|
-
try {
|
|
191
|
-
return { type, filename: decodeURIComponent(encoded) };
|
|
192
|
-
// eslint-disable-next-line venizia/no-silent-catch -- a malformed `filename*` falls through to the plain `filename` parameter; only the extended name is lost
|
|
193
|
-
}
|
|
194
|
-
catch {
|
|
195
|
-
// A malformed sequence is not worth failing a download over - fall through to `filename`.
|
|
196
|
-
}
|
|
197
|
-
}
|
|
198
|
-
const quoted = header.match(/filename\s*=\s*"([^"]*)"/i);
|
|
199
|
-
if (quoted) {
|
|
200
|
-
return { type, filename: quoted[1] };
|
|
201
|
-
}
|
|
202
|
-
const bare = header.match(/filename\s*=\s*([^;]+)/i);
|
|
203
|
-
return { type, filename: bare ? bare[1].trim() : undefined };
|
|
204
|
-
}
|
|
205
159
|
}
|
|
206
160
|
//# sourceMappingURL=request.utility.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.utility.js","sourceRoot":"","sources":["../../../src/utilities/request.utility.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,iBAAiB,E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A2B,CAAC,CAAC;QAEzD,IAAI,MAAM,EAAE,CAAC;YACX,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC;QACvC,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,CAAC,KAAK,CAAC,yBAAyB,CAAC,CAAC;QAErD,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,SAAS,EAAE,CAAC;IAC/D,CAAC;CACF","sourcesContent":["import type { TConstValue } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { MIN_TOKEN_BYTES, TokenUidHelper, UidTokenEncodings } from '@/modules/uid';\nimport { FormBodyUtility, RequestBodyErrors } from './form-body.utility';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/** A request remark: `id`, `url` and `method`, plus any extra keys. */\nexport interface IRequestedRemark {\n id: string;\n url: string;\n method: string;\n [extra: string | symbol]: unknown;\n}\n\n/** Where `RequestUtility.parseMultipartBody` keeps an uploaded file: MEMORY (a buffer) or DISK (spooled to `uploadDir`). */\nexport class MultipartStorages {\n static readonly MEMORY = 'memory';\n static readonly DISK = 'disk';\n\n static readonly SCHEME_SET = new Set<string>([this.MEMORY, this.DISK]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid multipart storage values. */\nexport type TMultipartStorage = TConstValue<typeof MultipartStorages>;\n\n/** The part of a request context a multipart body is read from: its `formData()`. A Hono context satisfies it. */\ninterface IMultipartContext {\n req: { formData: () => Promise<FormData> };\n}\n\ninterface IParseMultipartOptions<C extends IMultipartContext = IMultipartContext> {\n storage?: TMultipartStorage;\n uploadDir?: string;\n /** The most file parts one request may carry; more is refused (413) before anything is spooled. Unset: no limit. */\n maxFiles?: number;\n context: C;\n}\n\ninterface IParsedFile {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer?: Buffer;\n filename?: string;\n path?: string;\n}\n\n/** Files and the text fields posted beside them - dropping the second silently loses what the client sent. */\nexport interface IParsedMultipartBody {\n files: IParsedFile[];\n fields: Record<string, string>;\n}\n\n/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */\nconst UNENCODABLE_FILENAME_CHARACTERS = /(?![])[\\p{Cc}\\p{Cf}\\p{Cs}]/gu;\nconst LEADING_DOTS = /^\\.+/;\n\n/** How a client treats a download: ATTACHMENT saves it, INLINE shows it. */\nexport class ContentDispositionTypes {\n static readonly ATTACHMENT = 'attachment';\n static readonly INLINE = 'inline';\n\n static readonly SCHEME_SET = new Set<string>([this.ATTACHMENT, this.INLINE]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid Content-Disposition type values. */\nexport type TContentDispositionType = TConstValue<typeof ContentDispositionTypes>;\n\n/** Multipart body parsing and `Content-Disposition` header building and parsing for requests and uploads. */\nexport class RequestUtility {\n /** Built on first use: a helper opens a logger, which is work an import alone should not do. */\n private static uploadTokens?: TokenUidHelper;\n\n /** Uniqueness for a spooled filename, not a secret; the helper's 16-byte floor is the shortest it makes. */\n private static getUploadTokens(): TokenUidHelper {\n RequestUtility.uploadTokens ??= new TokenUidHelper({\n bytes: MIN_TOKEN_BYTES,\n encoding: UidTokenEncodings.HEX,\n });\n\n return RequestUtility.uploadTokens;\n }\n\n static async parseMultipartBody<C extends IMultipartContext = IMultipartContext>(\n opts: IParseMultipartOptions<C>,\n ): Promise<IParsedMultipartBody> {\n const { storage = MultipartStorages.MEMORY, uploadDir = './uploads', context, maxFiles } = opts;\n\n if (storage === MultipartStorages.DISK && !fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n const formData = await FormBodyUtility.readFormBody({ req: context.req });\n const files: IParsedFile[] = [];\n const fields: Record<string, string> = {};\n\n if (maxFiles !== undefined) {\n if (!Number.isInteger(maxFiles) || maxFiles < 0) {\n throw getError({\n message: `[parseMultipartBody] maxFiles must be a non-negative integer | received: ${maxFiles}`,\n });\n }\n\n let fileParts = 0;\n\n for (const [, value] of formData.entries()) {\n if (typeof value !== 'string') {\n fileParts += 1;\n }\n }\n\n if (fileParts > maxFiles) {\n throw getError({\n error: RequestBodyErrors.TOO_MANY_FILES,\n message: `[parseMultipartBody] Too many files in one request | received: ${fileParts} | max: ${maxFiles}`,\n });\n }\n }\n\n try {\n await RequestUtility.readParts({ formData, storage, uploadDir, files, fields });\n } catch (error) {\n // Files already written to disk belong to a request that failed; nothing else knows their names.\n RequestUtility.removeSpooled({ files });\n\n throw error;\n }\n\n return { files, fields };\n }\n\n private static removeSpooled(opts: { files: IParsedFile[] }): void {\n for (const file of opts.files) {\n if (!file.path) {\n continue;\n }\n\n try {\n fs.rmSync(file.path, { force: true });\n // eslint-disable-next-line venizia/no-silent-catch -- cleanup of a failed request: one file that will not go must not hide the original error or stop the others\n } catch {\n continue;\n }\n }\n }\n\n private static async readParts(opts: {\n formData: FormData;\n storage: TMultipartStorage;\n uploadDir: string;\n files: IParsedFile[];\n fields: Record<string, string>;\n }): Promise<void> {\n const { formData, storage, uploadDir, files, fields } = opts;\n const entries = formData.entries();\n\n for (const [fieldname, value] of entries) {\n if (typeof value === 'string') {\n // Last one wins, like a repeated query parameter.\n fields[fieldname] = value;\n continue;\n }\n\n const file = value as File;\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const parsedFile: IParsedFile = {\n fieldname,\n originalname: file.name,\n encoding: 'utf8',\n mimetype: file.type,\n size: file.size,\n };\n\n switch (storage) {\n case MultipartStorages.MEMORY: {\n parsedFile.buffer = buffer;\n break;\n }\n case MultipartStorages.DISK: {\n const timestamp = Date.now();\n const randomString = RequestUtility.getUploadTokens().nextId();\n // Sanitize filename to prevent path traversal\n const sanitizedName = path.basename(file.name).replace(/[^a-zA-Z0-9._-]/g, '_');\n const filename = `${timestamp}-${randomString}-${sanitizedName}`;\n const filepath = path.join(uploadDir, filename);\n\n try {\n fs.writeFileSync(filepath, buffer);\n } catch (error) {\n // A write that dies midway (a full disk) leaves a partial file this part never got to list.\n RequestUtility.removeSpooled({ files: [{ ...parsedFile, path: filepath }] });\n\n throw error;\n }\n\n parsedFile.filename = filename;\n parsedFile.path = filepath;\n break;\n }\n default: {\n throw getError({\n message: `[parseMultipartBody] storage: ${storage} | Invalid storage type | Valids: ['memory', 'disk']`,\n });\n }\n }\n\n files.push(parsedFile);\n }\n }\n\n /** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */\n static sanitizeFilename(opts: { filename: string }): string {\n const basename = path.basename(opts.filename);\n let sanitized = basename.replace(/[^\\w .-]/g, '_');\n sanitized = sanitized.replace(/^\\.+/, '');\n sanitized = sanitized.replace(/\\.{2,}/g, '.');\n sanitized = sanitized.replace(/\\.\\./g, '.');\n\n if (!sanitized || sanitized === '.' || sanitized.includes('..')) {\n sanitized = 'download';\n }\n\n return sanitized;\n }\n\n static encodeRfc5987(opts: { filename: string }): string {\n return encodeURIComponent(opts.filename)\n .replace(/['()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replace(/\\*/g, '%2A');\n }\n\n static buildContentDispositionHeader(opts: {\n filename: string;\n type: TContentDispositionType;\n }): string {\n const { filename, type } = opts;\n const sanitized = RequestUtility.sanitizeFilename({ filename });\n const extendedName = path\n .basename(filename)\n .replace(UNENCODABLE_FILENAME_CHARACTERS, '_')\n .replace(LEADING_DOTS, '');\n const encoded = RequestUtility.encodeRfc5987({ filename: extendedName || sanitized });\n\n // filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.\n return `${type}; filename=\"${sanitized}\"; filename*=UTF-8''${encoded}`;\n }\n\n /**\n * Reads a filename out of a `Content-Disposition` value.\n *\n * Three forms, in the order the RFC gives them precedence: `filename*=UTF-8''...` (percent-encoded,\n * and the one hand-rolled parsers miss), a quoted `filename=\"...\"`, and a bare `filename=...`.\n * Splitting on `filename=` alone returns the percent-encoded bytes for any non-ASCII name, which in\n * a product with non-English filenames is most of them.\n *\n * The pair of {@link RequestUtility.buildContentDispositionHeader}: one writes the header, this one reads it.\n */\n static parseContentDisposition(opts: { header: string | null | undefined }): {\n type?: string;\n filename?: string;\n } {\n const { header } = opts;\n\n if (!header) {\n return {};\n }\n\n const type = header.split(';')[0]?.trim() || undefined;\n\n // `filename*` wins when both are present - it is the one that can carry a non-ASCII name.\n const extended = header.match(/filename\\*\\s*=\\s*([^;]+)/i);\n\n if (extended) {\n const value = extended[1].trim();\n // `UTF-8''name` or `UTF-8'lang'name`; anything before the last quote is charset and language.\n const encoded = value.slice(value.lastIndexOf(\"'\") + 1);\n\n try {\n return { type, filename: decodeURIComponent(encoded) };\n // eslint-disable-next-line venizia/no-silent-catch -- a malformed `filename*` falls through to the plain `filename` parameter; only the extended name is lost\n } catch {\n // A malformed sequence is not worth failing a download over - fall through to `filename`.\n }\n }\n\n const quoted = header.match(/filename\\s*=\\s*\"([^\"]*)\"/i);\n\n if (quoted) {\n return { type, filename: quoted[1] };\n }\n\n const bare = header.match(/filename\\s*=\\s*([^;]+)/i);\n\n return { type, filename: bare ? bare[1].trim() : undefined };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"request.utility.js","sourceRoot":"","sources":["../../../src/utilities/request.utility.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,eAAe,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACzE,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAU7B,4HAA4H;AAC5H,MAAM,OAAO,iBAAiB;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AS,CAAC,OAAO,CAAC,SAAS,EAAE,GAAG,CAAC,CAAC;QAC9C,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC;QAE5C,IAAI,CAAC,SAAS,IAAI,SAAS,KAAK,GAAG,IAAI,SAAS,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;YAChE,SAAS,GAAG,UAAU,CAAC;QACzB,CAAC;QAED,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,MAAM,CAAC,aAAa,CAAC,IAA0B;QAC7C,OAAO,kBAAkB,CAAC,IAAI,CAAC,QAAQ,CAAC;aACrC,OAAO,CAAC,QAAQ,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,GAAG,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC;aAC1E,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC3B,CAAC;IAED,MAAM,CAAC,6BAA6B,CAAC,IAGpC;QACC,MAAM,EAAE,QAAQ,EAAE,IAAI,EAAE,GAAG,IAAI,CAAC;QAChC,MAAM,SAAS,GAAG,cAAc,CAAC,gBAAgB,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC;QAChE,MAAM,YAAY,GAAG,IAAI;aACtB,QAAQ,CAAC,QAAQ,CAAC;aAClB,OAAO,CAAC,+BAA+B,EAAE,GAAG,CAAC;aAC7C,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;QAC7B,MAAM,OAAO,GAAG,cAAc,CAAC,aAAa,CAAC,EAAE,QAAQ,EAAE,YAAY,IAAI,SAAS,EAAE,CAAC,CAAC;QAEtF,+FAA+F;QAC/F,OAAO,GAAG,IAAI,eAAe,SAAS,uBAAuB,OAAO,EAAE,CAAC;IACzE,CAAC;CACF","sourcesContent":["import type { TContentDispositionType } from '@/common/constants/http';\nimport type { TConstValue } from '@/common/types';\nimport { getError } from '@/modules/error';\nimport { MIN_TOKEN_BYTES, TokenUidHelper, UidTokenEncodings } from '@/modules/uid';\nimport { FormBodyUtility, RequestBodyErrors } from './form-body.utility';\nimport fs from 'node:fs';\nimport path from 'node:path';\n\n/** A request remark: `id`, `url` and `method`, plus any extra keys. */\nexport interface IRequestedRemark {\n id: string;\n url: string;\n method: string;\n [extra: string | symbol]: unknown;\n}\n\n/** Where `RequestUtility.parseMultipartBody` keeps an uploaded file: MEMORY (a buffer) or DISK (spooled to `uploadDir`). */\nexport class MultipartStorages {\n static readonly MEMORY = 'memory';\n static readonly DISK = 'disk';\n\n static readonly SCHEME_SET = new Set<string>([this.MEMORY, this.DISK]);\n\n static isValid(value: string): boolean {\n return this.SCHEME_SET.has(value);\n }\n}\n\n/** Valid multipart storage values. */\nexport type TMultipartStorage = TConstValue<typeof MultipartStorages>;\n\n/** The part of a request context a multipart body is read from: its `formData()`. A Hono context satisfies it. */\ninterface IMultipartContext {\n req: { formData: () => Promise<FormData> };\n}\n\ninterface IParseMultipartOptions<C extends IMultipartContext = IMultipartContext> {\n storage?: TMultipartStorage;\n uploadDir?: string;\n /** The most file parts one request may carry; more is refused (413) before anything is spooled. Unset: no limit. */\n maxFiles?: number;\n context: C;\n}\n\ninterface IParsedFile {\n fieldname: string;\n originalname: string;\n encoding: string;\n mimetype: string;\n size: number;\n buffer?: Buffer;\n filename?: string;\n path?: string;\n}\n\n/** Files and the text fields posted beside them - dropping the second silently loses what the client sent. */\nexport interface IParsedMultipartBody {\n files: IParsedFile[];\n fields: Record<string, string>;\n}\n\n/** Control, format (bidi overrides, zero-width space) and lone surrogate characters: a format character reorders the name a client shows, a lone surrogate makes `encodeURIComponent` throw. The zero-width joiner and non-joiner stay: they build emoji sequences and Persian words, and reorder nothing. */\nconst UNENCODABLE_FILENAME_CHARACTERS = /(?![])[\\p{Cc}\\p{Cf}\\p{Cs}]/gu;\nconst LEADING_DOTS = /^\\.+/;\n\n/** Multipart body parsing and `Content-Disposition` header building and parsing for requests and uploads. */\nexport class RequestUtility {\n /** Built on first use: a helper opens a logger, which is work an import alone should not do. */\n private static uploadTokens?: TokenUidHelper;\n\n /** Uniqueness for a spooled filename, not a secret; the helper's 16-byte floor is the shortest it makes. */\n private static getUploadTokens(): TokenUidHelper {\n RequestUtility.uploadTokens ??= new TokenUidHelper({\n bytes: MIN_TOKEN_BYTES,\n encoding: UidTokenEncodings.HEX,\n });\n\n return RequestUtility.uploadTokens;\n }\n\n static async parseMultipartBody<C extends IMultipartContext = IMultipartContext>(\n opts: IParseMultipartOptions<C>,\n ): Promise<IParsedMultipartBody> {\n const { storage = MultipartStorages.MEMORY, uploadDir = './uploads', context, maxFiles } = opts;\n\n if (storage === MultipartStorages.DISK && !fs.existsSync(uploadDir)) {\n fs.mkdirSync(uploadDir, { recursive: true });\n }\n\n const formData = await FormBodyUtility.readFormBody({ req: context.req });\n const files: IParsedFile[] = [];\n const fields: Record<string, string> = {};\n\n if (maxFiles !== undefined) {\n if (!Number.isInteger(maxFiles) || maxFiles < 0) {\n throw getError({\n message: `[parseMultipartBody] maxFiles must be a non-negative integer | received: ${maxFiles}`,\n });\n }\n\n let fileParts = 0;\n\n for (const [, value] of formData.entries()) {\n if (typeof value !== 'string') {\n fileParts += 1;\n }\n }\n\n if (fileParts > maxFiles) {\n throw getError({\n error: RequestBodyErrors.TOO_MANY_FILES,\n message: `[parseMultipartBody] Too many files in one request | received: ${fileParts} | max: ${maxFiles}`,\n });\n }\n }\n\n try {\n await RequestUtility.readParts({ formData, storage, uploadDir, files, fields });\n } catch (error) {\n // Files already written to disk belong to a request that failed; nothing else knows their names.\n RequestUtility.removeSpooled({ files });\n\n throw error;\n }\n\n return { files, fields };\n }\n\n private static removeSpooled(opts: { files: IParsedFile[] }): void {\n for (const file of opts.files) {\n if (!file.path) {\n continue;\n }\n\n try {\n fs.rmSync(file.path, { force: true });\n // eslint-disable-next-line venizia/no-silent-catch -- cleanup of a failed request: one file that will not go must not hide the original error or stop the others\n } catch {\n continue;\n }\n }\n }\n\n private static async readParts(opts: {\n formData: FormData;\n storage: TMultipartStorage;\n uploadDir: string;\n files: IParsedFile[];\n fields: Record<string, string>;\n }): Promise<void> {\n const { formData, storage, uploadDir, files, fields } = opts;\n const entries = formData.entries();\n\n for (const [fieldname, value] of entries) {\n if (typeof value === 'string') {\n // Last one wins, like a repeated query parameter.\n fields[fieldname] = value;\n continue;\n }\n\n const file = value as File;\n const arrayBuffer = await file.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n\n const parsedFile: IParsedFile = {\n fieldname,\n originalname: file.name,\n encoding: 'utf8',\n mimetype: file.type,\n size: file.size,\n };\n\n switch (storage) {\n case MultipartStorages.MEMORY: {\n parsedFile.buffer = buffer;\n break;\n }\n case MultipartStorages.DISK: {\n const timestamp = Date.now();\n const randomString = RequestUtility.getUploadTokens().nextId();\n // Sanitize filename to prevent path traversal\n const sanitizedName = path.basename(file.name).replace(/[^a-zA-Z0-9._-]/g, '_');\n const filename = `${timestamp}-${randomString}-${sanitizedName}`;\n const filepath = path.join(uploadDir, filename);\n\n try {\n fs.writeFileSync(filepath, buffer);\n } catch (error) {\n // A write that dies midway (a full disk) leaves a partial file this part never got to list.\n RequestUtility.removeSpooled({ files: [{ ...parsedFile, path: filepath }] });\n\n throw error;\n }\n\n parsedFile.filename = filename;\n parsedFile.path = filepath;\n break;\n }\n default: {\n throw getError({\n message: `[parseMultipartBody] storage: ${storage} | Invalid storage type | Valids: ['memory', 'disk']`,\n });\n }\n }\n\n files.push(parsedFile);\n }\n }\n\n /** Sanitizes a filename by removing path components and dangerous characters. The result is printable ASCII. */\n static sanitizeFilename(opts: { filename: string }): string {\n const basename = path.basename(opts.filename);\n let sanitized = basename.replace(/[^\\w .-]/g, '_');\n sanitized = sanitized.replace(/^\\.+/, '');\n sanitized = sanitized.replace(/\\.{2,}/g, '.');\n sanitized = sanitized.replace(/\\.\\./g, '.');\n\n if (!sanitized || sanitized === '.' || sanitized.includes('..')) {\n sanitized = 'download';\n }\n\n return sanitized;\n }\n\n static encodeRfc5987(opts: { filename: string }): string {\n return encodeURIComponent(opts.filename)\n .replace(/['()]/g, (c) => '%' + c.charCodeAt(0).toString(16).toUpperCase())\n .replace(/\\*/g, '%2A');\n }\n\n static buildContentDispositionHeader(opts: {\n filename: string;\n type: TContentDispositionType;\n }): string {\n const { filename, type } = opts;\n const sanitized = RequestUtility.sanitizeFilename({ filename });\n const extendedName = path\n .basename(filename)\n .replace(UNENCODABLE_FILENAME_CHARACTERS, '_')\n .replace(LEADING_DOTS, '');\n const encoded = RequestUtility.encodeRfc5987({ filename: extendedName || sanitized });\n\n // filename= is the ASCII fallback for old browsers, filename*= the UTF-8 form for modern ones.\n return `${type}; filename=\"${sanitized}\"; filename*=UTF-8''${encoded}`;\n }\n}\n"]}
|