@my-nestjs-kit/queues 0.0.0-stage → 0.1.0-dev.20261129010337
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/LICENSE +21 -0
- package/README.md +24 -2
- package/dist/decorators/index.d.ts +2 -0
- package/dist/decorators/index.js +18 -0
- package/dist/decorators/processor-meta.decorator.d.ts +10 -0
- package/dist/decorators/processor-meta.decorator.js +19 -0
- package/dist/decorators/queue-service.decorator.d.ts +11 -0
- package/dist/decorators/queue-service.decorator.js +15 -0
- package/dist/dynamic-queues/dynamic-queue-names.d.ts +12 -0
- package/dist/dynamic-queues/dynamic-queue-names.js +49 -0
- package/dist/dynamic-queues/dynamic-queue-processor.decorator.d.ts +23 -0
- package/dist/dynamic-queues/dynamic-queue-processor.decorator.js +29 -0
- package/dist/dynamic-queues/dynamic-queue-processors.explorer.d.ts +12 -0
- package/dist/dynamic-queues/dynamic-queue-processors.explorer.js +57 -0
- package/dist/dynamic-queues/dynamic-queues-channel.d.ts +21 -0
- package/dist/dynamic-queues/dynamic-queues-channel.js +55 -0
- package/dist/dynamic-queues/dynamic-queues-factory.d.ts +88 -0
- package/dist/dynamic-queues/dynamic-queues-factory.js +162 -0
- package/dist/dynamic-queues/dynamic-queues-module.options.d.ts +76 -0
- package/dist/dynamic-queues/dynamic-queues-module.options.js +2 -0
- package/dist/dynamic-queues/dynamic-queues-state.d.ts +79 -0
- package/dist/dynamic-queues/dynamic-queues-state.js +142 -0
- package/dist/dynamic-queues/dynamic-queues.constants.d.ts +10 -0
- package/dist/dynamic-queues/dynamic-queues.constants.js +14 -0
- package/dist/dynamic-queues/dynamic-queues.manager.d.ts +85 -0
- package/dist/dynamic-queues/dynamic-queues.manager.js +404 -0
- package/dist/dynamic-queues/dynamic-queues.module.d.ts +16 -0
- package/dist/dynamic-queues/dynamic-queues.module.js +76 -0
- package/dist/dynamic-queues/dynamic-queues.registry.d.ts +18 -0
- package/dist/dynamic-queues/dynamic-queues.registry.js +55 -0
- package/dist/dynamic-queues/dynamic-queues.types.d.ts +81 -0
- package/dist/dynamic-queues/dynamic-queues.types.js +2 -0
- package/dist/dynamic-queues/index.d.ts +13 -0
- package/dist/dynamic-queues/index.js +33 -0
- package/dist/dynamic-queues/proxy-queues.binder.d.ts +17 -0
- package/dist/dynamic-queues/proxy-queues.binder.js +63 -0
- package/dist/index.d.ts +10 -0
- package/dist/index.js +30 -0
- package/dist/jobs.types.d.ts +4 -0
- package/dist/jobs.types.js +2 -0
- package/dist/middlewares/middlewares.types.d.ts +10 -0
- package/dist/middlewares/middlewares.types.js +6 -0
- package/dist/process/index.d.ts +1 -0
- package/dist/process/index.js +17 -0
- package/dist/process/process.decorator.d.ts +13 -0
- package/dist/process/process.decorator.js +45 -0
- package/dist/processor-base.abstract.d.ts +39 -0
- package/dist/processor-base.abstract.js +125 -0
- package/dist/queue-service.base.d.ts +28 -0
- package/dist/queue-service.base.js +73 -0
- package/dist/queues.constants.d.ts +3 -0
- package/dist/queues.constants.js +6 -0
- package/dist/queues.module.d.ts +11 -0
- package/dist/queues.module.js +58 -0
- package/dist/queues.types.d.ts +99 -0
- package/dist/queues.types.js +57 -0
- package/dist/types/index.d.ts +17 -0
- package/dist/types/index.js +2 -0
- package/package.json +102 -3
|
@@ -0,0 +1,404 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.DynamicQueuesManager = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const crypto_1 = require("crypto");
|
|
18
|
+
const os_1 = require("os");
|
|
19
|
+
const channels_1 = require("@my-nestjs-kit/channels");
|
|
20
|
+
const dynamic_queues_constants_1 = require("./dynamic-queues.constants");
|
|
21
|
+
const dynamic_queues_registry_1 = require("./dynamic-queues.registry");
|
|
22
|
+
const dynamic_queue_names_1 = require("./dynamic-queue-names");
|
|
23
|
+
/**
|
|
24
|
+
* Owns this instance's dynamic queues (`dynamic__<type>__<id>`): producer handles, local
|
|
25
|
+
* workers, leases in the cluster state (heartbeat, takeover of dead owners, idle stop) and the
|
|
26
|
+
* `dynamic-queues` channel notifications.
|
|
27
|
+
*/
|
|
28
|
+
let DynamicQueuesManager = class DynamicQueuesManager {
|
|
29
|
+
constructor(options, registry, channels) {
|
|
30
|
+
this.options = options;
|
|
31
|
+
this.registry = registry;
|
|
32
|
+
this.channels = channels;
|
|
33
|
+
this.logger = new common_1.Logger('DynamicQueues');
|
|
34
|
+
this.queues = new Map();
|
|
35
|
+
this.workers = new Map();
|
|
36
|
+
/** Queues whose lease this instance holds. */
|
|
37
|
+
this.owned = new Set();
|
|
38
|
+
this.lastActivity = new Map();
|
|
39
|
+
this.serverId =
|
|
40
|
+
options.serverId ??
|
|
41
|
+
`${(0, os_1.hostname)()}:${process.pid}:${(0, crypto_1.randomUUID)().slice(0, 8)}`;
|
|
42
|
+
}
|
|
43
|
+
get policy() {
|
|
44
|
+
return this.options.workers ?? 'starter';
|
|
45
|
+
}
|
|
46
|
+
get leaseTtlMs() {
|
|
47
|
+
return this.options.leaseTtlMs ?? 30_000;
|
|
48
|
+
}
|
|
49
|
+
get state() {
|
|
50
|
+
return this.options.state;
|
|
51
|
+
}
|
|
52
|
+
async onApplicationBootstrap() {
|
|
53
|
+
if (this.options.restoreOnBoot)
|
|
54
|
+
await this.restore();
|
|
55
|
+
const every = this.options.heartbeatMs ?? 10_000;
|
|
56
|
+
if (every > 0) {
|
|
57
|
+
this.timer = setInterval(() => void this.tick(), every);
|
|
58
|
+
this.timer.unref?.();
|
|
59
|
+
void this.tick();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
async onApplicationShutdown() {
|
|
63
|
+
if (this.timer)
|
|
64
|
+
clearInterval(this.timer);
|
|
65
|
+
await this.ticking;
|
|
66
|
+
const timeout = this.options.shutdownTimeoutMs ?? 10_000;
|
|
67
|
+
await Promise.allSettled([...this.workers.values()].map((w) => this.closeWorker(w, timeout)));
|
|
68
|
+
// released leases are free for the other instances' next takeover
|
|
69
|
+
await this.state
|
|
70
|
+
.heartbeat([...this.owned], this.serverId, 0)
|
|
71
|
+
.catch((e) => this.logger.warn(`Lease release failed: ${e?.message}`));
|
|
72
|
+
await Promise.allSettled([...this.queues.values()].map((q) => q.close()));
|
|
73
|
+
this.workers.clear();
|
|
74
|
+
this.queues.clear();
|
|
75
|
+
this.owned.clear();
|
|
76
|
+
}
|
|
77
|
+
/** Producer handle (lazy, cached). Doesn't start a worker or mark the queue active. */
|
|
78
|
+
queue(type, id) {
|
|
79
|
+
const ref = this.refOf(type, id);
|
|
80
|
+
this.touch(ref.name);
|
|
81
|
+
return this.queueByName(ref.name, ref.type);
|
|
82
|
+
}
|
|
83
|
+
/** Local worker of the queue, if this instance runs one. */
|
|
84
|
+
worker(type, id) {
|
|
85
|
+
return this.workers.get((0, dynamic_queue_names_1.toDynamicQueueName)(type, id));
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Starts the queue here: local worker (resumed if paused), lease owned by this instance,
|
|
89
|
+
* `started` on the channel. Throws when no `@DynamicQueueProcessor` handles the type or
|
|
90
|
+
* `maxLocalWorkers` is reached.
|
|
91
|
+
*/
|
|
92
|
+
async start(type, id) {
|
|
93
|
+
const ref = this.refOf(type, id);
|
|
94
|
+
if (!this.registry.hasProcessor(type))
|
|
95
|
+
throw new Error(`No @DynamicQueueProcessor for dynamic queue type "${type}"`);
|
|
96
|
+
if (!this.workers.has(ref.name) && this.atWorkerLimit())
|
|
97
|
+
throw new Error(`maxLocalWorkers (${this.options.maxLocalWorkers}) reached, can't start ${ref.name}`);
|
|
98
|
+
const queue = this.queueByName(ref.name, type);
|
|
99
|
+
const worker = this.ensureWorker(ref);
|
|
100
|
+
await this.state.withLock(`start:${ref.name}`, () => this.state.activate(ref.name, this.serverId, Date.now()));
|
|
101
|
+
this.owned.add(ref.name);
|
|
102
|
+
this.touch(ref.name);
|
|
103
|
+
await this.notify(dynamic_queues_constants_1.DynamicQueueEvent.started, ref.name);
|
|
104
|
+
this.hook('onQueueStarted', ref, 'start');
|
|
105
|
+
this.logger.log(`Started ${ref.name}`);
|
|
106
|
+
return { queue: queue, worker };
|
|
107
|
+
}
|
|
108
|
+
/** Pauses the local worker, drops the lease, `paused` on the channel. */
|
|
109
|
+
async pause(type, id) {
|
|
110
|
+
const ref = this.refOf(type, id);
|
|
111
|
+
await this.workers.get(ref.name)?.pause();
|
|
112
|
+
await this.state.withLock(`pause:${ref.name}`, () => this.state.deactivate(ref.name));
|
|
113
|
+
this.owned.delete(ref.name);
|
|
114
|
+
await this.notify(dynamic_queues_constants_1.DynamicQueueEvent.paused, ref.name);
|
|
115
|
+
this.hook('onQueuePaused', ref, 'pause');
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Closes the local worker and queue handle, drops the lease, `removed` on the channel.
|
|
119
|
+
* `obliterate` also deletes the queue's jobs from Redis.
|
|
120
|
+
*/
|
|
121
|
+
async stop(type, id, options = {}) {
|
|
122
|
+
await this.stopRef(this.refOf(type, id), 'stop', options);
|
|
123
|
+
}
|
|
124
|
+
isActive(type, id) {
|
|
125
|
+
return this.state.isActive((0, dynamic_queue_names_1.toDynamicQueueName)(type, id));
|
|
126
|
+
}
|
|
127
|
+
/** Active queues of the cluster (names that aren't dynamic queue names are skipped). */
|
|
128
|
+
async active() {
|
|
129
|
+
return (await this.state.list())
|
|
130
|
+
.map((lease) => (0, dynamic_queue_names_1.parseDynamicQueueName)(lease.name))
|
|
131
|
+
.filter(Boolean);
|
|
132
|
+
}
|
|
133
|
+
/** Local workers for every active queue whose type has a processor here (no ownership). */
|
|
134
|
+
async restore() {
|
|
135
|
+
for (const ref of await this.active()) {
|
|
136
|
+
if (!this.registry.hasProcessor(ref.type)) {
|
|
137
|
+
this.logger.warn(`Not restored ${ref.name}: no processor for "${ref.type}"`);
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
if (this.workers.has(ref.name) || this.atWorkerLimit())
|
|
141
|
+
continue;
|
|
142
|
+
this.queueByName(ref.name, ref.type);
|
|
143
|
+
this.ensureWorker(ref);
|
|
144
|
+
this.hook('onQueueStarted', ref, 'restore');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* One maintenance round (runs every `heartbeatMs`): renew own leases, give up the ones another
|
|
149
|
+
* instance took, take over stale ones, stop idle queues. Rounds never overlap.
|
|
150
|
+
*/
|
|
151
|
+
tick() {
|
|
152
|
+
if (!this.ticking)
|
|
153
|
+
this.ticking = this.runTick()
|
|
154
|
+
.catch((e) => this.logger.error(`Tick failed: ${e?.message}`))
|
|
155
|
+
.finally(() => (this.ticking = undefined));
|
|
156
|
+
return this.ticking;
|
|
157
|
+
}
|
|
158
|
+
/** Every active queue of the cluster with its lease and this instance's view of it. */
|
|
159
|
+
async snapshot({ counts = false } = {}) {
|
|
160
|
+
const staleBefore = Date.now() - this.leaseTtlMs;
|
|
161
|
+
const result = [];
|
|
162
|
+
for (const lease of await this.state.list()) {
|
|
163
|
+
const ref = (0, dynamic_queue_names_1.parseDynamicQueueName)(lease.name);
|
|
164
|
+
if (!ref)
|
|
165
|
+
continue;
|
|
166
|
+
const worker = this.workers.get(ref.name);
|
|
167
|
+
const entry = {
|
|
168
|
+
...ref,
|
|
169
|
+
owner: lease.owner,
|
|
170
|
+
heartbeatAt: lease.heartbeatAt,
|
|
171
|
+
stale: lease.heartbeatAt < staleBefore,
|
|
172
|
+
local: {
|
|
173
|
+
worker: worker
|
|
174
|
+
? worker.isPaused()
|
|
175
|
+
? 'paused'
|
|
176
|
+
: 'running'
|
|
177
|
+
: undefined,
|
|
178
|
+
owned: this.owned.has(ref.name),
|
|
179
|
+
lastActivity: this.lastActivity.get(ref.name),
|
|
180
|
+
},
|
|
181
|
+
};
|
|
182
|
+
if (counts) {
|
|
183
|
+
const queue = this.queueByName(ref.name, ref.type);
|
|
184
|
+
[entry.counts, entry.workers] = await Promise.all([
|
|
185
|
+
queue.getJobCounts(),
|
|
186
|
+
queue.getWorkersCount(),
|
|
187
|
+
]);
|
|
188
|
+
}
|
|
189
|
+
result.push(entry);
|
|
190
|
+
}
|
|
191
|
+
return result;
|
|
192
|
+
}
|
|
193
|
+
/** Active queues nobody runs: a stale lease, or (with counts) no worker connected anywhere. */
|
|
194
|
+
async health() {
|
|
195
|
+
const issues = [];
|
|
196
|
+
for (const q of await this.snapshot({ counts: true })) {
|
|
197
|
+
if (q.stale)
|
|
198
|
+
issues.push({ name: q.name, reason: 'stale-lease' });
|
|
199
|
+
else if (q.workers === 0)
|
|
200
|
+
issues.push({ name: q.name, reason: 'no-workers' });
|
|
201
|
+
}
|
|
202
|
+
return { ok: !issues.length, issues };
|
|
203
|
+
}
|
|
204
|
+
/** A change another instance announced on the channel. */
|
|
205
|
+
async applyRemote(event, name) {
|
|
206
|
+
const ref = (0, dynamic_queue_names_1.parseDynamicQueueName)(name);
|
|
207
|
+
if (!ref)
|
|
208
|
+
return;
|
|
209
|
+
const worker = this.workers.get(name);
|
|
210
|
+
switch (event) {
|
|
211
|
+
case dynamic_queues_constants_1.DynamicQueueEvent.started:
|
|
212
|
+
// another instance holds the lease now
|
|
213
|
+
this.owned.delete(name);
|
|
214
|
+
if (worker?.isPaused())
|
|
215
|
+
worker.resume();
|
|
216
|
+
else if (!worker &&
|
|
217
|
+
this.policy === 'all' &&
|
|
218
|
+
this.registry.hasProcessor(ref.type) &&
|
|
219
|
+
!this.atWorkerLimit()) {
|
|
220
|
+
this.queueByName(ref.name, ref.type);
|
|
221
|
+
this.ensureWorker(ref);
|
|
222
|
+
this.hook('onQueueStarted', ref, 'remote');
|
|
223
|
+
}
|
|
224
|
+
return;
|
|
225
|
+
case dynamic_queues_constants_1.DynamicQueueEvent.paused:
|
|
226
|
+
this.owned.delete(name);
|
|
227
|
+
await worker?.pause();
|
|
228
|
+
this.hook('onQueuePaused', ref, 'remote');
|
|
229
|
+
return;
|
|
230
|
+
case dynamic_queues_constants_1.DynamicQueueEvent.removed:
|
|
231
|
+
this.owned.delete(name);
|
|
232
|
+
await this.closeLocal(name);
|
|
233
|
+
this.hook('onQueueStopped', ref, 'remote');
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
async runTick() {
|
|
238
|
+
const now = Date.now();
|
|
239
|
+
// 1. renew own leases; drop the ones taken over meanwhile
|
|
240
|
+
const lost = await this.state.heartbeat([...this.owned], this.serverId, now);
|
|
241
|
+
for (const name of lost) {
|
|
242
|
+
this.owned.delete(name);
|
|
243
|
+
const ref = (0, dynamic_queue_names_1.parseDynamicQueueName)(name);
|
|
244
|
+
if (this.policy === 'starter' && ref) {
|
|
245
|
+
await this.closeLocal(name);
|
|
246
|
+
this.hook('onQueueStopped', ref, 'lost');
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
// 2. take over queues whose owner stopped heartbeating
|
|
250
|
+
if (this.options.takeover ?? true) {
|
|
251
|
+
const staleBefore = now - this.leaseTtlMs;
|
|
252
|
+
for (const lease of await this.state.list()) {
|
|
253
|
+
if (lease.heartbeatAt >= staleBefore || this.owned.has(lease.name))
|
|
254
|
+
continue;
|
|
255
|
+
const ref = (0, dynamic_queue_names_1.parseDynamicQueueName)(lease.name);
|
|
256
|
+
if (!ref || !this.registry.hasProcessor(ref.type))
|
|
257
|
+
continue;
|
|
258
|
+
if (!this.workers.has(ref.name) && this.atWorkerLimit())
|
|
259
|
+
continue;
|
|
260
|
+
if (!(await this.state.claim(ref.name, this.serverId, now, staleBefore)))
|
|
261
|
+
continue;
|
|
262
|
+
this.owned.add(ref.name);
|
|
263
|
+
this.touch(ref.name);
|
|
264
|
+
this.queueByName(ref.name, ref.type);
|
|
265
|
+
this.ensureWorker(ref);
|
|
266
|
+
this.logger.log(`Took over ${ref.name} from ${lease.owner ?? '?'}`);
|
|
267
|
+
this.hook('onQueueStarted', ref, 'takeover');
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
// 3. stop own queues idle for longer than their type's idleTimeoutMs
|
|
271
|
+
for (const name of [...this.owned]) {
|
|
272
|
+
const ref = (0, dynamic_queue_names_1.parseDynamicQueueName)(name);
|
|
273
|
+
const idleMs = ref && this.registry.configOf(ref.type)?.idleTimeoutMs;
|
|
274
|
+
if (!idleMs || now - (this.lastActivity.get(name) ?? now) < idleMs)
|
|
275
|
+
continue;
|
|
276
|
+
const counts = await this.queueByName(ref.name, ref.type).getJobCounts('waiting', 'delayed', 'active', 'prioritized');
|
|
277
|
+
if (Object.values(counts).some((n) => n > 0))
|
|
278
|
+
continue;
|
|
279
|
+
await this.stopRef(ref, 'idle');
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
async stopRef(ref, reason, { obliterate = false } = {}) {
|
|
283
|
+
if (obliterate)
|
|
284
|
+
await this.queueByName(ref.name, ref.type).obliterate({ force: true });
|
|
285
|
+
await this.closeLocal(ref.name);
|
|
286
|
+
await this.state.withLock(`stop:${ref.name}`, () => this.state.deactivate(ref.name));
|
|
287
|
+
this.owned.delete(ref.name);
|
|
288
|
+
this.lastActivity.delete(ref.name);
|
|
289
|
+
await this.notify(dynamic_queues_constants_1.DynamicQueueEvent.removed, ref.name);
|
|
290
|
+
this.hook('onQueueStopped', ref, reason);
|
|
291
|
+
this.logger.log(`Stopped ${ref.name} (${reason})`);
|
|
292
|
+
}
|
|
293
|
+
refOf(type, id) {
|
|
294
|
+
if (!this.registry.isRegistered(type))
|
|
295
|
+
throw new Error(`Dynamic queue type "${type}" is not registered (forFeature or @DynamicQueueProcessor)`);
|
|
296
|
+
const name = (0, dynamic_queue_names_1.toDynamicQueueName)(type, id);
|
|
297
|
+
const verdict = this.registry.configOf(type)?.validateId?.(id) ?? true;
|
|
298
|
+
if (verdict !== true)
|
|
299
|
+
throw new Error(typeof verdict === 'string'
|
|
300
|
+
? verdict
|
|
301
|
+
: `Invalid id "${id}" for dynamic queue type "${type}"`);
|
|
302
|
+
return { type, id, name };
|
|
303
|
+
}
|
|
304
|
+
atWorkerLimit() {
|
|
305
|
+
const max = this.options.maxLocalWorkers;
|
|
306
|
+
return max !== undefined && this.workers.size >= max;
|
|
307
|
+
}
|
|
308
|
+
touch(name) {
|
|
309
|
+
this.lastActivity.set(name, Date.now());
|
|
310
|
+
}
|
|
311
|
+
queueByName(name, type) {
|
|
312
|
+
let queue = this.queues.get(name);
|
|
313
|
+
if (!queue) {
|
|
314
|
+
queue = this.options.factory.createQueue(name, this.registry.configOf(type)?.queueOptions);
|
|
315
|
+
queue.on('error', (e) => this.logger.error(`Queue ${name}: ${e?.message}`));
|
|
316
|
+
this.queues.set(name, queue);
|
|
317
|
+
}
|
|
318
|
+
return queue;
|
|
319
|
+
}
|
|
320
|
+
ensureWorker(ref) {
|
|
321
|
+
const existing = this.workers.get(ref.name);
|
|
322
|
+
if (existing) {
|
|
323
|
+
if (existing.isPaused())
|
|
324
|
+
existing.resume();
|
|
325
|
+
return existing;
|
|
326
|
+
}
|
|
327
|
+
const worker = this.options.factory.createWorker(ref.name, (job, token) => this.process(ref, job, token), this.registry.configOf(ref.type)?.workerOptions);
|
|
328
|
+
worker.on('error', (e) => this.logger.error(`Worker ${ref.name}: ${e?.message}`));
|
|
329
|
+
worker.on('active', () => this.touch(ref.name));
|
|
330
|
+
worker.on('completed', (job, result) => {
|
|
331
|
+
this.touch(ref.name);
|
|
332
|
+
this.hook('onJobCompleted', ref, job, result);
|
|
333
|
+
});
|
|
334
|
+
worker.on('failed', (job, error) => {
|
|
335
|
+
this.touch(ref.name);
|
|
336
|
+
if (!job)
|
|
337
|
+
return;
|
|
338
|
+
const exhausted = job.attemptsMade >= (job.opts?.attempts ?? 1);
|
|
339
|
+
this.hook('onJobFailed', ref, job, error, exhausted);
|
|
340
|
+
if (exhausted)
|
|
341
|
+
this.onExhausted(ref, job, error);
|
|
342
|
+
});
|
|
343
|
+
this.workers.set(ref.name, worker);
|
|
344
|
+
return worker;
|
|
345
|
+
}
|
|
346
|
+
async process(ref, job, token) {
|
|
347
|
+
const handler = this.registry.handlerOf(ref.type, job.name);
|
|
348
|
+
if (!handler)
|
|
349
|
+
throw new Error(`No handler for job "${job.name}" of dynamic queue type "${ref.type}"`);
|
|
350
|
+
return handler(job, this.contextOf(ref, token));
|
|
351
|
+
}
|
|
352
|
+
contextOf(ref, token) {
|
|
353
|
+
return { type: ref.type, id: ref.id, queueName: ref.name, token };
|
|
354
|
+
}
|
|
355
|
+
onExhausted(ref, job, error) {
|
|
356
|
+
const fn = this.registry.configOf(ref.type)?.onExhausted;
|
|
357
|
+
if (!fn)
|
|
358
|
+
return;
|
|
359
|
+
Promise.resolve()
|
|
360
|
+
.then(() => fn(job, error, this.contextOf(ref)))
|
|
361
|
+
.catch((e) => this.logger.error(`onExhausted ${ref.name}: ${e?.message}`));
|
|
362
|
+
}
|
|
363
|
+
hook(name, ...args) {
|
|
364
|
+
const fn = this.options.hooks?.[name];
|
|
365
|
+
if (!fn)
|
|
366
|
+
return;
|
|
367
|
+
Promise.resolve()
|
|
368
|
+
.then(() => fn.apply(this.options.hooks, args))
|
|
369
|
+
.catch((e) => this.logger.error(`Hook ${name}: ${e?.message}`));
|
|
370
|
+
}
|
|
371
|
+
async closeWorker(worker, timeoutMs) {
|
|
372
|
+
let timer;
|
|
373
|
+
const timedOut = new Promise((resolve) => {
|
|
374
|
+
timer = setTimeout(() => resolve('timeout'), timeoutMs);
|
|
375
|
+
});
|
|
376
|
+
const res = await Promise.race([worker.close(), timedOut]);
|
|
377
|
+
clearTimeout(timer);
|
|
378
|
+
if (res === 'timeout') {
|
|
379
|
+
this.logger.warn(`Worker ${worker.name} didn't drain in ${timeoutMs}ms, forcing`);
|
|
380
|
+
await worker.close(true);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
async closeLocal(name) {
|
|
384
|
+
const worker = this.workers.get(name);
|
|
385
|
+
const queue = this.queues.get(name);
|
|
386
|
+
this.workers.delete(name);
|
|
387
|
+
this.queues.delete(name);
|
|
388
|
+
await worker?.close();
|
|
389
|
+
await queue?.close();
|
|
390
|
+
}
|
|
391
|
+
async notify(event, queue) {
|
|
392
|
+
if (!this.channels)
|
|
393
|
+
return;
|
|
394
|
+
await this.channels.publish(dynamic_queues_constants_1.DYNAMIC_QUEUES_CHANNEL, event, { queue });
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
exports.DynamicQueuesManager = DynamicQueuesManager;
|
|
398
|
+
exports.DynamicQueuesManager = DynamicQueuesManager = __decorate([
|
|
399
|
+
(0, common_1.Injectable)(),
|
|
400
|
+
__param(0, (0, common_1.Inject)(dynamic_queues_constants_1.DYNAMIC_QUEUES_MODULE_OPTIONS)),
|
|
401
|
+
__param(2, (0, common_1.Optional)()),
|
|
402
|
+
__metadata("design:paramtypes", [Object, dynamic_queues_registry_1.DynamicQueuesRegistry,
|
|
403
|
+
channels_1.ChannelsPublisher])
|
|
404
|
+
], DynamicQueuesManager);
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { DynamicModule } from '@nestjs/common';
|
|
2
|
+
import type { DynamicQueuesModuleAsyncOptions, DynamicQueuesModuleOptions, DynamicQueueTypeConfig } from './dynamic-queues-module.options';
|
|
3
|
+
/**
|
|
4
|
+
* Per-id BullMQ queues created at runtime.
|
|
5
|
+
* - `forRoot[Async]()` once in the app: `DynamicQueuesManager`, processor discovery, the
|
|
6
|
+
* `dynamic-queues` channel listener (needs `ChannelsModule` for cross-instance notifications;
|
|
7
|
+
* without it the manager works locally) and the proxy binder.
|
|
8
|
+
* - `forFeature([{ type, queueOptions, workerOptions }])` in the module that owns a type; the
|
|
9
|
+
* types come from `declare module '@my-nestjs-kit/queues' { interface DefaultDynamicQueuesMap { … } }`.
|
|
10
|
+
* - processors are `@DynamicQueueProcessor('<type>')` providers of any module.
|
|
11
|
+
*/
|
|
12
|
+
export declare class DynamicQueuesModule {
|
|
13
|
+
static forRoot(options: DynamicQueuesModuleOptions): DynamicModule;
|
|
14
|
+
static forRootAsync(options: DynamicQueuesModuleAsyncOptions): DynamicModule;
|
|
15
|
+
static forFeature(configs: readonly DynamicQueueTypeConfig<any>[]): DynamicModule;
|
|
16
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var DynamicQueuesModule_1;
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.DynamicQueuesModule = void 0;
|
|
11
|
+
const common_1 = require("@nestjs/common");
|
|
12
|
+
const core_1 = require("@nestjs/core");
|
|
13
|
+
const dynamic_queues_constants_1 = require("./dynamic-queues.constants");
|
|
14
|
+
const dynamic_queues_registry_1 = require("./dynamic-queues.registry");
|
|
15
|
+
const dynamic_queue_processors_explorer_1 = require("./dynamic-queue-processors.explorer");
|
|
16
|
+
const dynamic_queues_manager_1 = require("./dynamic-queues.manager");
|
|
17
|
+
const dynamic_queues_channel_1 = require("./dynamic-queues-channel");
|
|
18
|
+
const proxy_queues_binder_1 = require("./proxy-queues.binder");
|
|
19
|
+
let featureSeq = 0;
|
|
20
|
+
let DynamicQueuesFeatureModule = class DynamicQueuesFeatureModule {
|
|
21
|
+
};
|
|
22
|
+
DynamicQueuesFeatureModule = __decorate([
|
|
23
|
+
(0, common_1.Module)({})
|
|
24
|
+
], DynamicQueuesFeatureModule);
|
|
25
|
+
/**
|
|
26
|
+
* Per-id BullMQ queues created at runtime.
|
|
27
|
+
* - `forRoot[Async]()` once in the app: `DynamicQueuesManager`, processor discovery, the
|
|
28
|
+
* `dynamic-queues` channel listener (needs `ChannelsModule` for cross-instance notifications;
|
|
29
|
+
* without it the manager works locally) and the proxy binder.
|
|
30
|
+
* - `forFeature([{ type, queueOptions, workerOptions }])` in the module that owns a type; the
|
|
31
|
+
* types come from `declare module '@my-nestjs-kit/queues' { interface DefaultDynamicQueuesMap { … } }`.
|
|
32
|
+
* - processors are `@DynamicQueueProcessor('<type>')` providers of any module.
|
|
33
|
+
*/
|
|
34
|
+
let DynamicQueuesModule = DynamicQueuesModule_1 = class DynamicQueuesModule {
|
|
35
|
+
static forRoot(options) {
|
|
36
|
+
return DynamicQueuesModule_1.forRootAsync({ useFactory: () => options });
|
|
37
|
+
}
|
|
38
|
+
static forRootAsync(options) {
|
|
39
|
+
return {
|
|
40
|
+
module: DynamicQueuesModule_1,
|
|
41
|
+
global: true,
|
|
42
|
+
imports: [core_1.DiscoveryModule, ...(options.imports ?? [])],
|
|
43
|
+
providers: [
|
|
44
|
+
{
|
|
45
|
+
provide: dynamic_queues_constants_1.DYNAMIC_QUEUES_MODULE_OPTIONS,
|
|
46
|
+
useFactory: options.useFactory,
|
|
47
|
+
inject: options.inject ?? [],
|
|
48
|
+
},
|
|
49
|
+
dynamic_queues_registry_1.DynamicQueuesRegistry,
|
|
50
|
+
dynamic_queue_processors_explorer_1.DynamicQueueProcessorsExplorer,
|
|
51
|
+
dynamic_queues_manager_1.DynamicQueuesManager,
|
|
52
|
+
dynamic_queues_channel_1.DynamicQueuesChannelListener,
|
|
53
|
+
proxy_queues_binder_1.ProxyQueuesBinder,
|
|
54
|
+
],
|
|
55
|
+
exports: [dynamic_queues_manager_1.DynamicQueuesManager, dynamic_queues_registry_1.DynamicQueuesRegistry],
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
static forFeature(configs) {
|
|
59
|
+
// a unique token per call, so Nest doesn't dedupe two forFeature() modules into one
|
|
60
|
+
const token = `DYNAMIC_QUEUES_FEATURE_${++featureSeq}`;
|
|
61
|
+
return {
|
|
62
|
+
module: DynamicQueuesFeatureModule,
|
|
63
|
+
providers: [
|
|
64
|
+
{
|
|
65
|
+
provide: token,
|
|
66
|
+
useFactory: (registry) => registry.addConfig(...configs),
|
|
67
|
+
inject: [dynamic_queues_registry_1.DynamicQueuesRegistry],
|
|
68
|
+
},
|
|
69
|
+
],
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
exports.DynamicQueuesModule = DynamicQueuesModule;
|
|
74
|
+
exports.DynamicQueuesModule = DynamicQueuesModule = DynamicQueuesModule_1 = __decorate([
|
|
75
|
+
(0, common_1.Module)({})
|
|
76
|
+
], DynamicQueuesModule);
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Job } from 'bullmq';
|
|
2
|
+
import type { DynamicQueueTypeConfig } from './dynamic-queues-module.options';
|
|
3
|
+
import type { DynamicJobContext } from './dynamic-queues.types';
|
|
4
|
+
export type DynamicJobHandler = (job: Job, ctx: DynamicJobContext) => unknown | Promise<unknown>;
|
|
5
|
+
/** Per-type options (from `forFeature`) and job handlers (from `@DynamicQueueProcessor`). */
|
|
6
|
+
export declare class DynamicQueuesRegistry {
|
|
7
|
+
private readonly configs;
|
|
8
|
+
private readonly handlers;
|
|
9
|
+
addConfig(...configs: DynamicQueueTypeConfig<any>[]): this;
|
|
10
|
+
configOf(type: string): DynamicQueueTypeConfig<any> | undefined;
|
|
11
|
+
addHandler(type: string, jobName: string, handler: DynamicJobHandler): void;
|
|
12
|
+
hasProcessor(type: string): boolean;
|
|
13
|
+
/** Known through `forFeature` or a `@DynamicQueueProcessor`. */
|
|
14
|
+
isRegistered(type: string): boolean;
|
|
15
|
+
/** Exact job-name handler, then `'*'`; undefined when nothing matches. */
|
|
16
|
+
handlerOf(type: string, jobName: string): DynamicJobHandler | undefined;
|
|
17
|
+
types(): string[];
|
|
18
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
+
exports.DynamicQueuesRegistry = void 0;
|
|
10
|
+
const common_1 = require("@nestjs/common");
|
|
11
|
+
const dynamic_queues_constants_1 = require("./dynamic-queues.constants");
|
|
12
|
+
/** Per-type options (from `forFeature`) and job handlers (from `@DynamicQueueProcessor`). */
|
|
13
|
+
let DynamicQueuesRegistry = class DynamicQueuesRegistry {
|
|
14
|
+
constructor() {
|
|
15
|
+
this.configs = new Map();
|
|
16
|
+
this.handlers = new Map();
|
|
17
|
+
}
|
|
18
|
+
addConfig(...configs) {
|
|
19
|
+
for (const config of configs) {
|
|
20
|
+
if (this.configs.has(config.type))
|
|
21
|
+
throw new Error(`Dynamic queue type "${config.type}" is registered twice`);
|
|
22
|
+
this.configs.set(config.type, config);
|
|
23
|
+
}
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
configOf(type) {
|
|
27
|
+
return this.configs.get(type);
|
|
28
|
+
}
|
|
29
|
+
addHandler(type, jobName, handler) {
|
|
30
|
+
const byName = this.handlers.get(type) ?? new Map();
|
|
31
|
+
if (byName.has(jobName))
|
|
32
|
+
throw new Error(`Dynamic queue type "${type}" has two handlers for job "${jobName}"`);
|
|
33
|
+
byName.set(jobName, handler);
|
|
34
|
+
this.handlers.set(type, byName);
|
|
35
|
+
}
|
|
36
|
+
hasProcessor(type) {
|
|
37
|
+
return !!this.handlers.get(type)?.size;
|
|
38
|
+
}
|
|
39
|
+
/** Known through `forFeature` or a `@DynamicQueueProcessor`. */
|
|
40
|
+
isRegistered(type) {
|
|
41
|
+
return this.configs.has(type) || this.hasProcessor(type);
|
|
42
|
+
}
|
|
43
|
+
/** Exact job-name handler, then `'*'`; undefined when nothing matches. */
|
|
44
|
+
handlerOf(type, jobName) {
|
|
45
|
+
const byName = this.handlers.get(type);
|
|
46
|
+
return byName?.get(jobName) ?? byName?.get(dynamic_queues_constants_1.DYNAMIC_JOB_ANY);
|
|
47
|
+
}
|
|
48
|
+
types() {
|
|
49
|
+
return [...new Set([...this.configs.keys(), ...this.handlers.keys()])];
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
exports.DynamicQueuesRegistry = DynamicQueuesRegistry;
|
|
53
|
+
exports.DynamicQueuesRegistry = DynamicQueuesRegistry = __decorate([
|
|
54
|
+
(0, common_1.Injectable)()
|
|
55
|
+
], DynamicQueuesRegistry);
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { Job, JobsOptions, Queue, Worker } from 'bullmq';
|
|
2
|
+
/**
|
|
3
|
+
* The app's dynamic queue types — empty in the kit. Each module declares its type next to its
|
|
4
|
+
* processor (no file lists every type):
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* declare module '@my-nestjs-kit/queues' {
|
|
8
|
+
* interface DefaultDynamicQueuesMap {
|
|
9
|
+
* mailer: { send: { to: string }; bounce: { id: string } };
|
|
10
|
+
* }
|
|
11
|
+
* }
|
|
12
|
+
* ```
|
|
13
|
+
* Key = queue type, value = its jobs: job name → `data` payload. One type has one queue per id
|
|
14
|
+
* (`dynamic__mailer__<id>`), created at runtime.
|
|
15
|
+
*/
|
|
16
|
+
export interface DefaultDynamicQueuesMap {
|
|
17
|
+
}
|
|
18
|
+
export type DynamicQueuesMap = object;
|
|
19
|
+
export type DynamicQueueType<M extends DynamicQueuesMap = DefaultDynamicQueuesMap> = Extract<keyof M, string>;
|
|
20
|
+
export type DynamicJobName<T extends DynamicQueueType<M>, M extends DynamicQueuesMap = DefaultDynamicQueuesMap> = Extract<keyof M[T], string>;
|
|
21
|
+
/** Job names of every declared type. */
|
|
22
|
+
export type AnyDynamicJobName<M extends DynamicQueuesMap = DefaultDynamicQueuesMap> = {
|
|
23
|
+
[T in DynamicQueueType<M>]: DynamicJobName<T, M>;
|
|
24
|
+
}[DynamicQueueType<M>];
|
|
25
|
+
export type DynamicJobData<T extends DynamicQueueType<M>, K extends DynamicJobName<T, M>, M extends DynamicQueuesMap = DefaultDynamicQueuesMap> = NonNullable<M[T][K]>;
|
|
26
|
+
export type DynamicQueueName<T extends string = string> = `dynamic__${T}__${string}`;
|
|
27
|
+
export type ProxyQueueName<T extends string = string> = `proxy__${T}`;
|
|
28
|
+
export interface DynamicQueueRef<T extends string = string> {
|
|
29
|
+
type: T;
|
|
30
|
+
id: string;
|
|
31
|
+
name: DynamicQueueName<T>;
|
|
32
|
+
}
|
|
33
|
+
/** BullMQ `Queue` with `add` / `addBulk` typed by a jobs map (job name → data). */
|
|
34
|
+
export type TypedDynamicQueue<Jobs extends object = Record<string, any>> = Omit<Queue, 'add' | 'addBulk'> & {
|
|
35
|
+
add<K extends Extract<keyof Jobs, string>>(name: K, data: NonNullable<Jobs[K]>, opts?: JobsOptions): Promise<Job<NonNullable<Jobs[K]>, any, K>>;
|
|
36
|
+
addBulk<K extends Extract<keyof Jobs, string>>(jobs: Array<{
|
|
37
|
+
name: K;
|
|
38
|
+
data: NonNullable<Jobs[K]>;
|
|
39
|
+
opts?: JobsOptions;
|
|
40
|
+
}>): Promise<Array<Job<NonNullable<Jobs[K]>, any, K>>>;
|
|
41
|
+
};
|
|
42
|
+
export interface DynamicQueueHandle<Jobs extends object = Record<string, any>> {
|
|
43
|
+
queue: TypedDynamicQueue<Jobs>;
|
|
44
|
+
/** Local worker; undefined when this instance only produces into the queue. */
|
|
45
|
+
worker?: Worker;
|
|
46
|
+
}
|
|
47
|
+
/** Passed to every `@OnDynamicJob` handler next to the job. */
|
|
48
|
+
export interface DynamicJobContext<T extends string = string> {
|
|
49
|
+
type: T;
|
|
50
|
+
id: string;
|
|
51
|
+
queueName: DynamicQueueName<T>;
|
|
52
|
+
token?: string;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* - `starter` — a worker runs only on the instance that called `start()` (others just produce);
|
|
56
|
+
* - `all` — every instance runs a worker once any instance starts the queue.
|
|
57
|
+
* Either way a remote `pause` / `stop` reaches the local worker through the channel.
|
|
58
|
+
*/
|
|
59
|
+
export type DynamicQueuesWorkersPolicy = 'starter' | 'all';
|
|
60
|
+
/** One active queue as `DynamicQueuesManager.snapshot()` sees it (cluster lease + this instance). */
|
|
61
|
+
export interface DynamicQueueSnapshot extends DynamicQueueRef {
|
|
62
|
+
owner?: string;
|
|
63
|
+
heartbeatAt: number;
|
|
64
|
+
/** Lease not renewed within `leaseTtlMs`: nobody is known to run it. */
|
|
65
|
+
stale: boolean;
|
|
66
|
+
local: {
|
|
67
|
+
worker?: 'running' | 'paused';
|
|
68
|
+
owned: boolean;
|
|
69
|
+
lastActivity?: number;
|
|
70
|
+
};
|
|
71
|
+
/** With `{ counts: true }`: BullMQ job counts and workers connected to the queue (cluster-wide). */
|
|
72
|
+
counts?: Record<string, number>;
|
|
73
|
+
workers?: number;
|
|
74
|
+
}
|
|
75
|
+
export interface DynamicQueuesHealth {
|
|
76
|
+
ok: boolean;
|
|
77
|
+
issues: Array<{
|
|
78
|
+
name: string;
|
|
79
|
+
reason: 'stale-lease' | 'no-workers';
|
|
80
|
+
}>;
|
|
81
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
export * from './dynamic-queues.types';
|
|
2
|
+
export * from './dynamic-queue-names';
|
|
3
|
+
export * from './dynamic-queues-state';
|
|
4
|
+
export * from './dynamic-queues-factory';
|
|
5
|
+
export * from './dynamic-queues-module.options';
|
|
6
|
+
export * from './dynamic-queue-processor.decorator';
|
|
7
|
+
export * from './dynamic-queues.registry';
|
|
8
|
+
export * from './dynamic-queue-processors.explorer';
|
|
9
|
+
export * from './dynamic-queues.manager';
|
|
10
|
+
export * from './dynamic-queues-channel';
|
|
11
|
+
export * from './proxy-queues.binder';
|
|
12
|
+
export * from './dynamic-queues.module';
|
|
13
|
+
export { DYNAMIC_QUEUES_CHANNEL, DYNAMIC_JOB_ANY, DynamicQueueEvent, } from './dynamic-queues.constants';
|