@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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 sabationok
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,25 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @my-nestjs-kit/queues
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
BullMQ for NestJS. Depends on `@my-nestjs-kit/core` and `@my-nestjs-kit/channels` (dynamic queues sync their
|
|
4
|
+
instances over a channel); both come with it.
|
|
5
|
+
|
|
6
|
+
```sh
|
|
7
|
+
npm i @my-nestjs-kit/queues
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
Peers: `@nestjs/bullmq`, `@nestjs/common`, `@nestjs/core`, `bullmq`, `ioredis`, `reflect-metadata`, plus the peers
|
|
11
|
+
of core and channels.
|
|
12
|
+
|
|
13
|
+
## What's in
|
|
14
|
+
|
|
15
|
+
- **Queue bases:** `QueuesModule`, `QueueServiceBase` + `@QueueService`, `ProcessorBase` with `@Process(name)`
|
|
16
|
+
handlers (bound and awaited), processor middlewares, typed job maps (`JobsMappedType`, `BullQueueType`, ...).
|
|
17
|
+
- **Dynamic queues:** per-id queues created at runtime (`dynamic__<type>__<id>`) with a lease per queue,
|
|
18
|
+
lifecycle / job hooks, `snapshot()` / `health()`, and `proxy__<type>` queues. `DynamicQueuesModule.forRoot[Async]`
|
|
19
|
+
once, `forFeature([{ type, ... }])` per owning module, `@DynamicQueueProcessor` / `@OnDynamicJob` processors.
|
|
20
|
+
Map: `declare module '@my-nestjs-kit/queues' { interface DefaultDynamicQueuesMap { ... } }`. Details:
|
|
21
|
+
[`src/dynamic-queues/README.md`](https://github.com/sabationok/my-nestjs-kit/blob/main/packages/queues/src/dynamic-queues/README.md).
|
|
22
|
+
|
|
23
|
+
## License
|
|
24
|
+
|
|
25
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./queue-service.decorator"), exports);
|
|
18
|
+
__exportStar(require("./processor-meta.decorator"), exports);
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { GlobalJobs } from '../jobs.types';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
export declare const QUEUE_PROCESSOR_META = "queue:processor:meta";
|
|
4
|
+
type DynamicProcessorMeta = {
|
|
5
|
+
queue: string;
|
|
6
|
+
type: GlobalJobs.QueueType;
|
|
7
|
+
};
|
|
8
|
+
export declare function getQueueProcessorMeta(instance: any, reflector?: Reflector): DynamicProcessorMeta | undefined;
|
|
9
|
+
export declare function ProcessorMeta({ queue, type }: DynamicProcessorMeta): <TFunction extends Function, Y>(target: object | TFunction, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ProcessorMeta = exports.getQueueProcessorMeta = exports.QUEUE_PROCESSOR_META = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
const bullmq_1 = require("@nestjs/bullmq");
|
|
6
|
+
exports.QUEUE_PROCESSOR_META = 'queue:processor:meta';
|
|
7
|
+
function getQueueProcessorMeta(instance, reflector) {
|
|
8
|
+
return reflector
|
|
9
|
+
? reflector.get(exports.QUEUE_PROCESSOR_META, instance.constructor)
|
|
10
|
+
: Reflect.getMetadata(exports.QUEUE_PROCESSOR_META, instance.constructor);
|
|
11
|
+
}
|
|
12
|
+
exports.getQueueProcessorMeta = getQueueProcessorMeta;
|
|
13
|
+
function ProcessorMeta({ queue, type }) {
|
|
14
|
+
return (0, common_1.applyDecorators)((0, common_1.SetMetadata)(exports.QUEUE_PROCESSOR_META, {
|
|
15
|
+
queue,
|
|
16
|
+
type,
|
|
17
|
+
}), (0, bullmq_1.Processor)(queue));
|
|
18
|
+
}
|
|
19
|
+
exports.ProcessorMeta = ProcessorMeta;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { GlobalJobs } from '../jobs.types';
|
|
2
|
+
import { Reflector } from '@nestjs/core';
|
|
3
|
+
export declare const QUEUE_SERVICE_META: unique symbol;
|
|
4
|
+
export type DynamicQueueServiceMeta = {
|
|
5
|
+
queue: string;
|
|
6
|
+
type?: GlobalJobs.QueueType;
|
|
7
|
+
/** `proxy__<type>` queue bound by `@my-nestjs-kit/queues` (`bindProxies`). */
|
|
8
|
+
hasProxy?: boolean;
|
|
9
|
+
};
|
|
10
|
+
export declare function getQueueServiceMeta(instance: any, reflector?: Reflector): DynamicQueueServiceMeta | undefined;
|
|
11
|
+
export declare function QueueService(params: DynamicQueueServiceMeta): <TFunction extends Function, Y>(target: object | TFunction, propertyKey?: string | symbol, descriptor?: TypedPropertyDescriptor<Y>) => void;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.QueueService = exports.getQueueServiceMeta = exports.QUEUE_SERVICE_META = void 0;
|
|
4
|
+
const common_1 = require("@nestjs/common");
|
|
5
|
+
exports.QUEUE_SERVICE_META = Symbol('bullmq_queue:service');
|
|
6
|
+
function getQueueServiceMeta(instance, reflector) {
|
|
7
|
+
return reflector
|
|
8
|
+
? reflector.get(exports.QUEUE_SERVICE_META, instance.constructor)
|
|
9
|
+
: Reflect.getMetadata(exports.QUEUE_SERVICE_META, instance.constructor);
|
|
10
|
+
}
|
|
11
|
+
exports.getQueueServiceMeta = getQueueServiceMeta;
|
|
12
|
+
function QueueService(params) {
|
|
13
|
+
return (0, common_1.applyDecorators)((0, common_1.SetMetadata)(exports.QUEUE_SERVICE_META, params));
|
|
14
|
+
}
|
|
15
|
+
exports.QueueService = QueueService;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { DynamicQueueName, DynamicQueueRef, ProxyQueueName } from './dynamic-queues.types';
|
|
2
|
+
export declare const DYNAMIC_QUEUE_ID_MAX_LENGTH = 128;
|
|
3
|
+
/** `('mailer', 'abc')` → `dynamic__mailer__abc`. Throws on an empty / too long / `:` / whitespace part. */
|
|
4
|
+
export declare function toDynamicQueueName<T extends string>(type: T, id: string): DynamicQueueName<T>;
|
|
5
|
+
export declare function isDynamicQueueName(name: string): name is DynamicQueueName;
|
|
6
|
+
/**
|
|
7
|
+
* Inverse of `toDynamicQueueName`; undefined for anything else. The id may contain `__`
|
|
8
|
+
* (split on the first separator only).
|
|
9
|
+
*/
|
|
10
|
+
export declare function parseDynamicQueueName<T extends string = string>(name: string): DynamicQueueRef<T> | undefined;
|
|
11
|
+
/** `'tasks'` → `proxy__tasks` (idempotent). */
|
|
12
|
+
export declare function toProxyQueueName<T extends string>(type: T): ProxyQueueName<T>;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.toProxyQueueName = exports.parseDynamicQueueName = exports.isDynamicQueueName = exports.toDynamicQueueName = exports.DYNAMIC_QUEUE_ID_MAX_LENGTH = void 0;
|
|
4
|
+
const DYNAMIC_PREFIX = 'dynamic__';
|
|
5
|
+
const PROXY_PREFIX = 'proxy__';
|
|
6
|
+
const SEP = '__';
|
|
7
|
+
exports.DYNAMIC_QUEUE_ID_MAX_LENGTH = 128;
|
|
8
|
+
// BullMQ builds Redis keys as `<prefix>:<queue>:…` and rejects ':' in queue names
|
|
9
|
+
const FORBIDDEN = /[:\s]/;
|
|
10
|
+
/** `('mailer', 'abc')` → `dynamic__mailer__abc`. Throws on an empty / too long / `:` / whitespace part. */
|
|
11
|
+
function toDynamicQueueName(type, id) {
|
|
12
|
+
if (typeof type !== 'string' || typeof id !== 'string' || !type || !id)
|
|
13
|
+
throw new Error(`Dynamic queue needs a type and an id, got "${type}", "${id}"`);
|
|
14
|
+
if (type.includes(SEP) || FORBIDDEN.test(type))
|
|
15
|
+
throw new Error(`Dynamic queue type must not contain "${SEP}", ":" or whitespace: "${type}"`);
|
|
16
|
+
if (FORBIDDEN.test(id))
|
|
17
|
+
throw new Error(`Dynamic queue id must not contain ":" or whitespace: "${id}"`);
|
|
18
|
+
if (id.length > exports.DYNAMIC_QUEUE_ID_MAX_LENGTH)
|
|
19
|
+
throw new Error(`Dynamic queue id is longer than ${exports.DYNAMIC_QUEUE_ID_MAX_LENGTH}: "${id.slice(0, 32)}…"`);
|
|
20
|
+
return `${DYNAMIC_PREFIX}${type}${SEP}${id}`;
|
|
21
|
+
}
|
|
22
|
+
exports.toDynamicQueueName = toDynamicQueueName;
|
|
23
|
+
function isDynamicQueueName(name) {
|
|
24
|
+
return parseDynamicQueueName(name) !== undefined;
|
|
25
|
+
}
|
|
26
|
+
exports.isDynamicQueueName = isDynamicQueueName;
|
|
27
|
+
/**
|
|
28
|
+
* Inverse of `toDynamicQueueName`; undefined for anything else. The id may contain `__`
|
|
29
|
+
* (split on the first separator only).
|
|
30
|
+
*/
|
|
31
|
+
function parseDynamicQueueName(name) {
|
|
32
|
+
if (!name?.startsWith(DYNAMIC_PREFIX))
|
|
33
|
+
return undefined;
|
|
34
|
+
const rest = name.slice(DYNAMIC_PREFIX.length);
|
|
35
|
+
const at = rest.indexOf(SEP);
|
|
36
|
+
if (at <= 0 || at + SEP.length >= rest.length)
|
|
37
|
+
return undefined;
|
|
38
|
+
return {
|
|
39
|
+
type: rest.slice(0, at),
|
|
40
|
+
id: rest.slice(at + SEP.length),
|
|
41
|
+
name: name,
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
exports.parseDynamicQueueName = parseDynamicQueueName;
|
|
45
|
+
/** `'tasks'` → `proxy__tasks` (idempotent). */
|
|
46
|
+
function toProxyQueueName(type) {
|
|
47
|
+
return (type.startsWith(PROXY_PREFIX) ? type : `${PROXY_PREFIX}${type}`);
|
|
48
|
+
}
|
|
49
|
+
exports.toProxyQueueName = toProxyQueueName;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import type { Job } from 'bullmq';
|
|
3
|
+
import { DYNAMIC_JOB_ANY } from './dynamic-queues.constants';
|
|
4
|
+
import type { AnyDynamicJobName, DefaultDynamicQueuesMap, DynamicJobContext, DynamicQueueType, DynamicQueuesMap } from './dynamic-queues.types';
|
|
5
|
+
export interface DynamicQueueProcessorMeta {
|
|
6
|
+
type: string;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Marks a provider as the processor of one dynamic queue type. Its `@OnDynamicJob` methods
|
|
10
|
+
* handle the jobs of every `dynamic__<type>__<id>` queue; workers are created by
|
|
11
|
+
* `DynamicQueuesManager`, not by `@nestjs/bullmq`. One processor per type.
|
|
12
|
+
*/
|
|
13
|
+
export declare function DynamicQueueProcessor<T extends DynamicQueueType<M>, M extends DynamicQueuesMap = DefaultDynamicQueuesMap>(type: T): ClassDecorator;
|
|
14
|
+
export declare namespace DynamicQueueProcessor {
|
|
15
|
+
var KEY: string;
|
|
16
|
+
}
|
|
17
|
+
export type DynamicJobHandlerDescriptor<Data> = TypedPropertyDescriptor<(job: Job<Data>, ctx: DynamicJobContext, ...args: any[]) => unknown>;
|
|
18
|
+
/**
|
|
19
|
+
* Handler of one job name of the class' type (`'*'` = any job without its own handler).
|
|
20
|
+
* Gets `(job, ctx)`; its result is the job's return value, a throw fails the job. The name is
|
|
21
|
+
* checked against the jobs of all declared types (a method decorator can't see the class' type).
|
|
22
|
+
*/
|
|
23
|
+
export declare function OnDynamicJob<K extends AnyDynamicJobName<M> | typeof DYNAMIC_JOB_ANY, M extends DynamicQueuesMap = DefaultDynamicQueuesMap>(name: K): <D extends DynamicJobHandlerDescriptor<any>>(target: object, propertyKey: string | symbol, descriptor: D) => void;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.OnDynamicJob = exports.DynamicQueueProcessor = void 0;
|
|
4
|
+
require("reflect-metadata");
|
|
5
|
+
const core_1 = require("@nestjs/core");
|
|
6
|
+
const dynamic_queues_constants_1 = require("./dynamic-queues.constants");
|
|
7
|
+
const discoverable = core_1.DiscoveryService.createDecorator();
|
|
8
|
+
/**
|
|
9
|
+
* Marks a provider as the processor of one dynamic queue type. Its `@OnDynamicJob` methods
|
|
10
|
+
* handle the jobs of every `dynamic__<type>__<id>` queue; workers are created by
|
|
11
|
+
* `DynamicQueuesManager`, not by `@nestjs/bullmq`. One processor per type.
|
|
12
|
+
*/
|
|
13
|
+
function DynamicQueueProcessor(type) {
|
|
14
|
+
return discoverable({ type });
|
|
15
|
+
}
|
|
16
|
+
exports.DynamicQueueProcessor = DynamicQueueProcessor;
|
|
17
|
+
DynamicQueueProcessor.KEY = discoverable.KEY;
|
|
18
|
+
/**
|
|
19
|
+
* Handler of one job name of the class' type (`'*'` = any job without its own handler).
|
|
20
|
+
* Gets `(job, ctx)`; its result is the job's return value, a throw fails the job. The name is
|
|
21
|
+
* checked against the jobs of all declared types (a method decorator can't see the class' type).
|
|
22
|
+
*/
|
|
23
|
+
function OnDynamicJob(name) {
|
|
24
|
+
return (_target, _key, descriptor) => {
|
|
25
|
+
const current = Reflect.getMetadata(dynamic_queues_constants_1.DYNAMIC_JOB_HANDLER_METADATA, descriptor.value) ?? [];
|
|
26
|
+
Reflect.defineMetadata(dynamic_queues_constants_1.DYNAMIC_JOB_HANDLER_METADATA, [...current, name], descriptor.value);
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
exports.OnDynamicJob = OnDynamicJob;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { OnModuleInit } from '@nestjs/common';
|
|
2
|
+
import { DiscoveryService, MetadataScanner } from '@nestjs/core';
|
|
3
|
+
import { DynamicQueuesRegistry } from './dynamic-queues.registry';
|
|
4
|
+
/** Finds `@DynamicQueueProcessor` providers and registers their `@OnDynamicJob` methods. */
|
|
5
|
+
export declare class DynamicQueueProcessorsExplorer implements OnModuleInit {
|
|
6
|
+
private readonly discovery;
|
|
7
|
+
private readonly scanner;
|
|
8
|
+
private readonly registry;
|
|
9
|
+
private readonly logger;
|
|
10
|
+
constructor(discovery: DiscoveryService, scanner: MetadataScanner, registry: DynamicQueuesRegistry);
|
|
11
|
+
onModuleInit(): void;
|
|
12
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
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
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.DynamicQueueProcessorsExplorer = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const core_1 = require("@nestjs/core");
|
|
15
|
+
const dynamic_queue_processor_decorator_1 = require("./dynamic-queue-processor.decorator");
|
|
16
|
+
const dynamic_queues_constants_1 = require("./dynamic-queues.constants");
|
|
17
|
+
const dynamic_queues_registry_1 = require("./dynamic-queues.registry");
|
|
18
|
+
/** Finds `@DynamicQueueProcessor` providers and registers their `@OnDynamicJob` methods. */
|
|
19
|
+
let DynamicQueueProcessorsExplorer = class DynamicQueueProcessorsExplorer {
|
|
20
|
+
constructor(discovery, scanner, registry) {
|
|
21
|
+
this.discovery = discovery;
|
|
22
|
+
this.scanner = scanner;
|
|
23
|
+
this.registry = registry;
|
|
24
|
+
this.logger = new common_1.Logger('DynamicQueueProcessors');
|
|
25
|
+
}
|
|
26
|
+
onModuleInit() {
|
|
27
|
+
const owners = new Map();
|
|
28
|
+
for (const wrapper of this.discovery.getProviders({
|
|
29
|
+
metadataKey: dynamic_queue_processor_decorator_1.DynamicQueueProcessor.KEY,
|
|
30
|
+
})) {
|
|
31
|
+
const { instance } = wrapper;
|
|
32
|
+
if (!instance || typeof instance !== 'object')
|
|
33
|
+
continue;
|
|
34
|
+
const { type } = Reflect.getMetadata(dynamic_queue_processor_decorator_1.DynamicQueueProcessor.KEY, instance.constructor);
|
|
35
|
+
const owner = owners.get(type);
|
|
36
|
+
if (owner)
|
|
37
|
+
throw new Error(`Dynamic queue type "${type}" has two processors: ${owner}, ${instance.constructor.name}`);
|
|
38
|
+
owners.set(type, instance.constructor.name);
|
|
39
|
+
const prototype = Object.getPrototypeOf(instance);
|
|
40
|
+
for (const methodKey of this.scanner.getAllMethodNames(prototype)) {
|
|
41
|
+
const method = prototype[methodKey];
|
|
42
|
+
const names = Reflect.getMetadata(dynamic_queues_constants_1.DYNAMIC_JOB_HANDLER_METADATA, method) ?? [];
|
|
43
|
+
for (const name of names)
|
|
44
|
+
this.registry.addHandler(type, name, method.bind(instance));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (owners.size)
|
|
48
|
+
this.logger.log(`Processors: ${[...owners.keys()].join(', ')}`);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
exports.DynamicQueueProcessorsExplorer = DynamicQueueProcessorsExplorer;
|
|
52
|
+
exports.DynamicQueueProcessorsExplorer = DynamicQueueProcessorsExplorer = __decorate([
|
|
53
|
+
(0, common_1.Injectable)(),
|
|
54
|
+
__metadata("design:paramtypes", [core_1.DiscoveryService,
|
|
55
|
+
core_1.MetadataScanner,
|
|
56
|
+
dynamic_queues_registry_1.DynamicQueuesRegistry])
|
|
57
|
+
], DynamicQueueProcessorsExplorer);
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { DynamicQueueEvent } from './dynamic-queues.constants';
|
|
2
|
+
import { DynamicQueuesManager } from './dynamic-queues.manager';
|
|
3
|
+
type QueueRef = {
|
|
4
|
+
queue: string;
|
|
5
|
+
};
|
|
6
|
+
/** `dynamic-queues` channel: one enum for publishing and handling, so they can't diverge. */
|
|
7
|
+
export type DynamicQueuesChannelEvents = Record<DynamicQueueEvent, QueueRef>;
|
|
8
|
+
declare module '@my-nestjs-kit/channels' {
|
|
9
|
+
interface DefaultChannelsMap {
|
|
10
|
+
'dynamic-queues': DynamicQueuesChannelEvents;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Applies other instances' changes to the local workers (own messages are skipped). */
|
|
14
|
+
export declare class DynamicQueuesChannelListener {
|
|
15
|
+
private readonly manager;
|
|
16
|
+
constructor(manager: DynamicQueuesManager);
|
|
17
|
+
onStarted(data: QueueRef): Promise<void>;
|
|
18
|
+
onPaused(data: QueueRef): Promise<void>;
|
|
19
|
+
onRemoved(data: QueueRef): Promise<void>;
|
|
20
|
+
}
|
|
21
|
+
export {};
|
|
@@ -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
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.DynamicQueuesChannelListener = void 0;
|
|
13
|
+
const common_1 = require("@nestjs/common");
|
|
14
|
+
const channels_1 = require("@my-nestjs-kit/channels");
|
|
15
|
+
const dynamic_queues_constants_1 = require("./dynamic-queues.constants");
|
|
16
|
+
const dynamic_queues_manager_1 = require("./dynamic-queues.manager");
|
|
17
|
+
/** Applies other instances' changes to the local workers (own messages are skipped). */
|
|
18
|
+
let DynamicQueuesChannelListener = class DynamicQueuesChannelListener {
|
|
19
|
+
constructor(manager) {
|
|
20
|
+
this.manager = manager;
|
|
21
|
+
}
|
|
22
|
+
onStarted(data) {
|
|
23
|
+
return this.manager.applyRemote(dynamic_queues_constants_1.DynamicQueueEvent.started, data.queue);
|
|
24
|
+
}
|
|
25
|
+
onPaused(data) {
|
|
26
|
+
return this.manager.applyRemote(dynamic_queues_constants_1.DynamicQueueEvent.paused, data.queue);
|
|
27
|
+
}
|
|
28
|
+
onRemoved(data) {
|
|
29
|
+
return this.manager.applyRemote(dynamic_queues_constants_1.DynamicQueueEvent.removed, data.queue);
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
exports.DynamicQueuesChannelListener = DynamicQueuesChannelListener;
|
|
33
|
+
__decorate([
|
|
34
|
+
(0, channels_1.OnChannelEvent)(dynamic_queues_constants_1.DynamicQueueEvent.started),
|
|
35
|
+
__metadata("design:type", Function),
|
|
36
|
+
__metadata("design:paramtypes", [Object]),
|
|
37
|
+
__metadata("design:returntype", void 0)
|
|
38
|
+
], DynamicQueuesChannelListener.prototype, "onStarted", null);
|
|
39
|
+
__decorate([
|
|
40
|
+
(0, channels_1.OnChannelEvent)(dynamic_queues_constants_1.DynamicQueueEvent.paused),
|
|
41
|
+
__metadata("design:type", Function),
|
|
42
|
+
__metadata("design:paramtypes", [Object]),
|
|
43
|
+
__metadata("design:returntype", void 0)
|
|
44
|
+
], DynamicQueuesChannelListener.prototype, "onPaused", null);
|
|
45
|
+
__decorate([
|
|
46
|
+
(0, channels_1.OnChannelEvent)(dynamic_queues_constants_1.DynamicQueueEvent.removed),
|
|
47
|
+
__metadata("design:type", Function),
|
|
48
|
+
__metadata("design:paramtypes", [Object]),
|
|
49
|
+
__metadata("design:returntype", void 0)
|
|
50
|
+
], DynamicQueuesChannelListener.prototype, "onRemoved", null);
|
|
51
|
+
exports.DynamicQueuesChannelListener = DynamicQueuesChannelListener = __decorate([
|
|
52
|
+
(0, common_1.Injectable)(),
|
|
53
|
+
(0, channels_1.ChannelListener)('dynamic-queues', { ignoreOwn: true }),
|
|
54
|
+
__metadata("design:paramtypes", [dynamic_queues_manager_1.DynamicQueuesManager])
|
|
55
|
+
], DynamicQueuesChannelListener);
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { EventEmitter } from 'events';
|
|
3
|
+
import { ConnectionOptions, Processor, Queue, QueueOptions, Worker, WorkerOptions } from 'bullmq';
|
|
4
|
+
export type DynamicQueueOptions = Omit<QueueOptions, 'connection'>;
|
|
5
|
+
export type DynamicWorkerOptions = Omit<WorkerOptions, 'connection'>;
|
|
6
|
+
/** Builds BullMQ queues/workers; swapped for a fake in tests. */
|
|
7
|
+
export interface DynamicQueuesFactory {
|
|
8
|
+
createQueue(name: string, options?: DynamicQueueOptions): Queue;
|
|
9
|
+
createWorker(name: string, processor: Processor, options?: DynamicWorkerOptions): Worker;
|
|
10
|
+
}
|
|
11
|
+
export interface BullDynamicQueuesFactoryOptions {
|
|
12
|
+
/** BullMQ key prefix; keep it equal to the app's `BullModule` prefix. */
|
|
13
|
+
prefix?: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Real BullMQ factory. For a shared ioredis `connection` set `maxRetriesPerRequest: null`
|
|
17
|
+
* (workers block on it; BullMQ duplicates it for the blocking client).
|
|
18
|
+
*/
|
|
19
|
+
export declare class BullDynamicQueuesFactory implements DynamicQueuesFactory {
|
|
20
|
+
private readonly connection;
|
|
21
|
+
private readonly options;
|
|
22
|
+
constructor(connection: ConnectionOptions, options?: BullDynamicQueuesFactoryOptions);
|
|
23
|
+
createQueue(name: string, options?: DynamicQueueOptions): Queue<any, any, string, any, any, string>;
|
|
24
|
+
createWorker(name: string, processor: Processor, options?: DynamicWorkerOptions): Worker<any, any, string>;
|
|
25
|
+
}
|
|
26
|
+
type InMemoryJobState = 'waiting' | 'active' | 'completed' | 'failed';
|
|
27
|
+
interface InMemoryJob {
|
|
28
|
+
id: string;
|
|
29
|
+
name: string;
|
|
30
|
+
data: unknown;
|
|
31
|
+
opts: Record<string, any>;
|
|
32
|
+
attemptsMade: number;
|
|
33
|
+
returnvalue?: unknown;
|
|
34
|
+
failedReason?: string;
|
|
35
|
+
state: InMemoryJobState;
|
|
36
|
+
}
|
|
37
|
+
declare class InMemoryQueue extends EventEmitter {
|
|
38
|
+
readonly name: string;
|
|
39
|
+
readonly opts: DynamicQueueOptions;
|
|
40
|
+
private readonly factory;
|
|
41
|
+
readonly jobs: InMemoryJob[];
|
|
42
|
+
closed: boolean;
|
|
43
|
+
private seq;
|
|
44
|
+
constructor(name: string, opts: DynamicQueueOptions, factory: InMemoryDynamicQueuesFactory);
|
|
45
|
+
add(name: string, data: unknown, opts?: Record<string, any>): Promise<InMemoryJob>;
|
|
46
|
+
addBulk(jobs: {
|
|
47
|
+
name: string;
|
|
48
|
+
data: unknown;
|
|
49
|
+
opts?: Record<string, any>;
|
|
50
|
+
}[]): Promise<InMemoryJob[]>;
|
|
51
|
+
getJobCounts(...types: string[]): Promise<Record<string, number>>;
|
|
52
|
+
getWorkersCount(): Promise<number>;
|
|
53
|
+
obliterate(): Promise<void>;
|
|
54
|
+
close(): Promise<void>;
|
|
55
|
+
}
|
|
56
|
+
declare class InMemoryWorker extends EventEmitter {
|
|
57
|
+
readonly name: string;
|
|
58
|
+
readonly processor: Processor;
|
|
59
|
+
readonly opts: DynamicWorkerOptions;
|
|
60
|
+
private readonly factory;
|
|
61
|
+
closed: boolean;
|
|
62
|
+
private paused;
|
|
63
|
+
constructor(name: string, processor: Processor, opts: DynamicWorkerOptions, factory: InMemoryDynamicQueuesFactory);
|
|
64
|
+
pause(): Promise<void>;
|
|
65
|
+
resume(): void;
|
|
66
|
+
isPaused(): boolean;
|
|
67
|
+
isRunning(): boolean;
|
|
68
|
+
close(): Promise<void>;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* BullMQ stand-in for tests: queues keep jobs in memory and a running worker of the same name
|
|
72
|
+
* processes them in order (with `attempts` retries), emitting `active` / `completed` / `failed`.
|
|
73
|
+
* Await `idle()` before asserting.
|
|
74
|
+
*/
|
|
75
|
+
export declare class InMemoryDynamicQueuesFactory implements DynamicQueuesFactory {
|
|
76
|
+
readonly queues: InMemoryQueue[];
|
|
77
|
+
readonly workers: InMemoryWorker[];
|
|
78
|
+
private running;
|
|
79
|
+
createQueue(name: string, options?: DynamicQueueOptions): Queue<any, any, string, any, any, string>;
|
|
80
|
+
createWorker(name: string, processor: Processor, options?: DynamicWorkerOptions): Worker<any, any, string>;
|
|
81
|
+
workersOf(name: string): InMemoryWorker[];
|
|
82
|
+
/** Resolves once every queued job that has a running worker is processed. */
|
|
83
|
+
idle(): Promise<void>;
|
|
84
|
+
/** @internal */
|
|
85
|
+
kick(name: string): void;
|
|
86
|
+
private drain;
|
|
87
|
+
}
|
|
88
|
+
export {};
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.InMemoryDynamicQueuesFactory = exports.BullDynamicQueuesFactory = void 0;
|
|
4
|
+
const events_1 = require("events");
|
|
5
|
+
const bullmq_1 = require("bullmq");
|
|
6
|
+
/**
|
|
7
|
+
* Real BullMQ factory. For a shared ioredis `connection` set `maxRetriesPerRequest: null`
|
|
8
|
+
* (workers block on it; BullMQ duplicates it for the blocking client).
|
|
9
|
+
*/
|
|
10
|
+
class BullDynamicQueuesFactory {
|
|
11
|
+
constructor(connection, options = {}) {
|
|
12
|
+
this.connection = connection;
|
|
13
|
+
this.options = options;
|
|
14
|
+
}
|
|
15
|
+
createQueue(name, options = {}) {
|
|
16
|
+
return new bullmq_1.Queue(name, {
|
|
17
|
+
prefix: this.options.prefix,
|
|
18
|
+
...options,
|
|
19
|
+
connection: this.connection,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
createWorker(name, processor, options = {}) {
|
|
23
|
+
return new bullmq_1.Worker(name, processor, {
|
|
24
|
+
prefix: this.options.prefix,
|
|
25
|
+
...options,
|
|
26
|
+
connection: this.connection,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
exports.BullDynamicQueuesFactory = BullDynamicQueuesFactory;
|
|
31
|
+
class InMemoryQueue extends events_1.EventEmitter {
|
|
32
|
+
constructor(name, opts, factory) {
|
|
33
|
+
super();
|
|
34
|
+
this.name = name;
|
|
35
|
+
this.opts = opts;
|
|
36
|
+
this.factory = factory;
|
|
37
|
+
this.jobs = [];
|
|
38
|
+
this.closed = false;
|
|
39
|
+
this.seq = 0;
|
|
40
|
+
}
|
|
41
|
+
async add(name, data, opts = {}) {
|
|
42
|
+
const job = {
|
|
43
|
+
id: opts.jobId ?? String(++this.seq),
|
|
44
|
+
name,
|
|
45
|
+
data,
|
|
46
|
+
opts: { ...this.opts.defaultJobOptions, ...opts },
|
|
47
|
+
attemptsMade: 0,
|
|
48
|
+
state: 'waiting',
|
|
49
|
+
};
|
|
50
|
+
this.jobs.push(job);
|
|
51
|
+
this.factory.kick(this.name);
|
|
52
|
+
return job;
|
|
53
|
+
}
|
|
54
|
+
addBulk(jobs) {
|
|
55
|
+
return Promise.all(jobs.map((j) => this.add(j.name, j.data, j.opts)));
|
|
56
|
+
}
|
|
57
|
+
async getJobCounts(...types) {
|
|
58
|
+
const counts = {};
|
|
59
|
+
for (const state of ['waiting', 'active', 'completed', 'failed', 'delayed'])
|
|
60
|
+
counts[state] = this.jobs.filter((j) => j.state === state).length;
|
|
61
|
+
if (!types.length)
|
|
62
|
+
return counts;
|
|
63
|
+
return Object.fromEntries(types.map((t) => [t, counts[t] ?? 0]));
|
|
64
|
+
}
|
|
65
|
+
async getWorkersCount() {
|
|
66
|
+
return this.factory.workersOf(this.name).length;
|
|
67
|
+
}
|
|
68
|
+
async obliterate() {
|
|
69
|
+
this.jobs.length = 0;
|
|
70
|
+
}
|
|
71
|
+
async close() {
|
|
72
|
+
this.closed = true;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
class InMemoryWorker extends events_1.EventEmitter {
|
|
76
|
+
constructor(name, processor, opts, factory) {
|
|
77
|
+
super();
|
|
78
|
+
this.name = name;
|
|
79
|
+
this.processor = processor;
|
|
80
|
+
this.opts = opts;
|
|
81
|
+
this.factory = factory;
|
|
82
|
+
this.closed = false;
|
|
83
|
+
this.paused = false;
|
|
84
|
+
}
|
|
85
|
+
async pause() {
|
|
86
|
+
this.paused = true;
|
|
87
|
+
}
|
|
88
|
+
resume() {
|
|
89
|
+
this.paused = false;
|
|
90
|
+
this.factory.kick(this.name);
|
|
91
|
+
}
|
|
92
|
+
isPaused() {
|
|
93
|
+
return this.paused;
|
|
94
|
+
}
|
|
95
|
+
isRunning() {
|
|
96
|
+
return !this.paused && !this.closed;
|
|
97
|
+
}
|
|
98
|
+
async close() {
|
|
99
|
+
this.closed = true;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* BullMQ stand-in for tests: queues keep jobs in memory and a running worker of the same name
|
|
104
|
+
* processes them in order (with `attempts` retries), emitting `active` / `completed` / `failed`.
|
|
105
|
+
* Await `idle()` before asserting.
|
|
106
|
+
*/
|
|
107
|
+
class InMemoryDynamicQueuesFactory {
|
|
108
|
+
constructor() {
|
|
109
|
+
this.queues = [];
|
|
110
|
+
this.workers = [];
|
|
111
|
+
this.running = Promise.resolve();
|
|
112
|
+
}
|
|
113
|
+
createQueue(name, options = {}) {
|
|
114
|
+
const queue = new InMemoryQueue(name, options, this);
|
|
115
|
+
this.queues.push(queue);
|
|
116
|
+
return queue;
|
|
117
|
+
}
|
|
118
|
+
createWorker(name, processor, options = {}) {
|
|
119
|
+
const worker = new InMemoryWorker(name, processor, options, this);
|
|
120
|
+
this.workers.push(worker);
|
|
121
|
+
this.kick(name);
|
|
122
|
+
return worker;
|
|
123
|
+
}
|
|
124
|
+
workersOf(name) {
|
|
125
|
+
return this.workers.filter((w) => w.name === name && !w.closed);
|
|
126
|
+
}
|
|
127
|
+
/** Resolves once every queued job that has a running worker is processed. */
|
|
128
|
+
idle() {
|
|
129
|
+
return this.running;
|
|
130
|
+
}
|
|
131
|
+
/** @internal */
|
|
132
|
+
kick(name) {
|
|
133
|
+
this.running = this.running.then(() => this.drain(name));
|
|
134
|
+
}
|
|
135
|
+
async drain(name) {
|
|
136
|
+
const worker = this.workersOf(name).find((w) => w.isRunning());
|
|
137
|
+
if (!worker)
|
|
138
|
+
return;
|
|
139
|
+
const jobs = this.queues
|
|
140
|
+
.filter((q) => q.name === name && !q.closed)
|
|
141
|
+
.flatMap((q) => q.jobs);
|
|
142
|
+
for (const job of jobs) {
|
|
143
|
+
while (job.state === 'waiting' && worker.isRunning()) {
|
|
144
|
+
job.state = 'active';
|
|
145
|
+
worker.emit('active', job);
|
|
146
|
+
try {
|
|
147
|
+
job.returnvalue = await worker.processor(job, 'in-memory');
|
|
148
|
+
job.state = 'completed';
|
|
149
|
+
worker.emit('completed', job, job.returnvalue);
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
job.attemptsMade++;
|
|
153
|
+
job.failedReason = e?.message;
|
|
154
|
+
job.state =
|
|
155
|
+
job.attemptsMade < (job.opts.attempts ?? 1) ? 'waiting' : 'failed';
|
|
156
|
+
worker.emit('failed', job, e);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
exports.InMemoryDynamicQueuesFactory = InMemoryDynamicQueuesFactory;
|