@hlw-midway/task 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
File without changes
package/dist/base.d.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { Job, JobsOptions, Queue, QueueGetters, Worker } from 'bullmq';
2
+ /**
3
+ * 队列基类
4
+ */
5
+ export declare abstract class BaseHlwQueue {
6
+ /**
7
+ * @deprecated 将在后续版本废弃
8
+ */
9
+ queue: BaseHlwQueue;
10
+ getters: QueueGetters;
11
+ worker: Worker;
12
+ queueName: string;
13
+ metaQueue: Queue;
14
+ constructor();
15
+ data(job: Job, done: Function): Promise<void>;
16
+ /**
17
+ * 发送数据
18
+ * @param data
19
+ * @param opts
20
+ */
21
+ add(data: any, opts?: JobsOptions): Promise<Job<any, any, string>>;
22
+ /**
23
+ * 批量新增
24
+ * @param datas
25
+ * @param opts
26
+ */
27
+ addBulk(datas: any[], opts?: JobsOptions): Promise<Job<any, any, string>[]>;
28
+ defaultJobOptions(): JobsOptions;
29
+ repeat(): Promise<import("bullmq").Repeat>;
30
+ pause(): Promise<void>;
31
+ resume(): Promise<void>;
32
+ isPaused(): Promise<boolean>;
33
+ getJobSchedulers(start?: number, end?: number, asc?: boolean): Promise<import("bullmq").JobSchedulerJson<any>[]>;
34
+ removeJobScheduler(jobId: string): Promise<void>;
35
+ remove(jobId: string): Promise<number>;
36
+ drain(delayed?: boolean): Promise<void>;
37
+ clean(grace: number, limit: number, type?: 'completed' | 'wait' | 'active' | 'paused' | 'delayed' | 'failed'): Promise<string[]>;
38
+ obliterate(opts?: {
39
+ force?: boolean;
40
+ count?: number;
41
+ }): Promise<void>;
42
+ trimEvents(maxLength: number): Promise<number>;
43
+ }
package/dist/base.js ADDED
@@ -0,0 +1,72 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BaseHlwQueue = void 0;
4
+ /**
5
+ * 队列基类
6
+ */
7
+ class BaseHlwQueue {
8
+ constructor() {
9
+ this.queue = this;
10
+ }
11
+ // 数据
12
+ async data(job, done) { }
13
+ /**
14
+ * 发送数据
15
+ * @param data
16
+ * @param opts
17
+ */
18
+ async add(data, opts) {
19
+ return this.metaQueue.add(this.queueName, data, opts);
20
+ }
21
+ /**
22
+ * 批量新增
23
+ * @param datas
24
+ * @param opts
25
+ */
26
+ async addBulk(datas, opts) {
27
+ return this.metaQueue.addBulk(datas.map(data => {
28
+ return {
29
+ name: this.queueName,
30
+ data,
31
+ opts,
32
+ };
33
+ }));
34
+ }
35
+ defaultJobOptions() {
36
+ return this.metaQueue.defaultJobOptions;
37
+ }
38
+ async repeat() {
39
+ return this.metaQueue.repeat;
40
+ }
41
+ async pause() {
42
+ this.metaQueue.pause();
43
+ }
44
+ async resume() {
45
+ this.metaQueue.resume();
46
+ }
47
+ async isPaused() {
48
+ return this.metaQueue.isPaused();
49
+ }
50
+ async getJobSchedulers(start, end, asc) {
51
+ return this.metaQueue.getJobSchedulers(start, end, asc);
52
+ }
53
+ async removeJobScheduler(jobId) {
54
+ this.metaQueue.removeJobScheduler(jobId);
55
+ }
56
+ async remove(jobId) {
57
+ return this.metaQueue.remove(jobId);
58
+ }
59
+ async drain(delayed) {
60
+ this.metaQueue.drain(delayed);
61
+ }
62
+ async clean(grace, limit, type) {
63
+ return this.metaQueue.clean(grace, limit, type);
64
+ }
65
+ async obliterate(opts) {
66
+ this.metaQueue.obliterate(opts);
67
+ }
68
+ async trimEvents(maxLength) {
69
+ return this.metaQueue.trimEvents(maxLength);
70
+ }
71
+ }
72
+ exports.BaseHlwQueue = BaseHlwQueue;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * hlw的配置
3
+ */
4
+ declare const _default: {
5
+ hlw: {};
6
+ };
7
+ export default _default;
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * hlw的配置
5
+ */
6
+ exports.default = {
7
+ hlw: {},
8
+ };
@@ -0,0 +1,4 @@
1
+ import { IMidwayContainer } from '@midwayjs/core';
2
+ export declare class HlwTaskConfiguration {
3
+ onReady(container: IMidwayContainer): Promise<void>;
4
+ }
@@ -0,0 +1,29 @@
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.HlwTaskConfiguration = void 0;
10
+ const core_1 = require("@midwayjs/core");
11
+ const DefaultConfig = require("./config/config.default");
12
+ const queue_1 = require("./queue");
13
+ let HlwTaskConfiguration = class HlwTaskConfiguration {
14
+ async onReady(container) {
15
+ await container.getAsync(queue_1.HlwQueueHandle);
16
+ // TODO something
17
+ }
18
+ };
19
+ exports.HlwTaskConfiguration = HlwTaskConfiguration;
20
+ exports.HlwTaskConfiguration = HlwTaskConfiguration = __decorate([
21
+ (0, core_1.Configuration)({
22
+ namespace: 'hlw:task',
23
+ importConfigs: [
24
+ {
25
+ default: DefaultConfig,
26
+ },
27
+ ],
28
+ })
29
+ ], HlwTaskConfiguration);
@@ -0,0 +1,7 @@
1
+ import { JobsOptions, WorkerOptions } from 'bullmq';
2
+ export declare const HLW_TASK_KEY = "decorator:hlw:task";
3
+ export declare function HlwQueue(config?: {
4
+ type?: "comm" | "getter" | "noworker" | "single";
5
+ queue?: JobsOptions;
6
+ worker?: Omit<WorkerOptions, "connection" | "prefix">;
7
+ }): ClassDecorator;
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HLW_TASK_KEY = void 0;
4
+ exports.HlwQueue = HlwQueue;
5
+ const core_1 = require("@midwayjs/core");
6
+ exports.HLW_TASK_KEY = 'decorator:hlw:task';
7
+ function HlwQueue(config = { type: 'comm', queue: {}, worker: {} }) {
8
+ return (target) => {
9
+ // 将装饰的类,绑定到该装饰器,用于后续能获取到 class
10
+ (0, core_1.saveModule)(exports.HLW_TASK_KEY, target);
11
+ // 保存一些元数据信息,任意你希望存的东西
12
+ (0, core_1.saveClassMetadata)(exports.HLW_TASK_KEY, config, target);
13
+ // 指定 IoC 容器创建实例的作用域,这里注册为请求作用域,这样能取到 ctx
14
+ (0, core_1.Scope)(core_1.ScopeEnum.Singleton)(target);
15
+ };
16
+ }
@@ -0,0 +1,4 @@
1
+ export { HlwTaskConfiguration as Configuration } from './configuration';
2
+ export * from './base';
3
+ export * from './queue';
4
+ export * from './decorator/queue';
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
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
+ exports.Configuration = void 0;
18
+ var configuration_1 = require("./configuration");
19
+ Object.defineProperty(exports, "Configuration", { enumerable: true, get: function () { return configuration_1.HlwTaskConfiguration; } });
20
+ __exportStar(require("./base"), exports);
21
+ __exportStar(require("./queue"), exports);
22
+ __exportStar(require("./decorator/queue"), exports);
@@ -0,0 +1,29 @@
1
+ import { ILogger, IMidwayApplication } from '@midwayjs/core';
2
+ import { BaseHlwQueue } from './base';
3
+ /**
4
+ * 任务队列
5
+ */
6
+ export declare class HlwQueueHandle {
7
+ redisConfig: any;
8
+ coreLogger: ILogger;
9
+ app: IMidwayApplication;
10
+ redis: any;
11
+ init(): Promise<void>;
12
+ /**
13
+ * 扫描队列
14
+ */
15
+ scan(): Promise<void>;
16
+ /**
17
+ * 获得锁
18
+ * @param key 键
19
+ * @param expireTime 过期时间
20
+ * @returns
21
+ */
22
+ getLock(key: any, expireTime: any): Promise<boolean>;
23
+ /**
24
+ * 队列名称
25
+ * @param cls
26
+ * @param mod
27
+ */
28
+ createQueue(cls: BaseHlwQueue, mod: any): Promise<void>;
29
+ }
package/dist/queue.js ADDED
@@ -0,0 +1,145 @@
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.HlwQueueHandle = void 0;
13
+ const core_1 = require("@midwayjs/core");
14
+ const bullmq_1 = require("bullmq");
15
+ const queue_1 = require("./decorator/queue");
16
+ const ioredis_1 = require("ioredis");
17
+ /**
18
+ * 任务队列
19
+ */
20
+ let HlwQueueHandle = class HlwQueueHandle {
21
+ async init() {
22
+ if (!this.redisConfig) {
23
+ this.coreLogger.error('@hlw-midway/task组件 redis未配置');
24
+ }
25
+ await this.scan();
26
+ }
27
+ /**
28
+ * 扫描队列
29
+ */
30
+ async scan() {
31
+ const modules = (0, core_1.listModule)(queue_1.HLW_TASK_KEY);
32
+ for (let mod of modules) {
33
+ const cls = await this.app
34
+ .getApplicationContext()
35
+ .getAsync(mod);
36
+ this.createQueue(cls, mod);
37
+ }
38
+ }
39
+ /**
40
+ * 获得锁
41
+ * @param key 键
42
+ * @param expireTime 过期时间
43
+ * @returns
44
+ */
45
+ async getLock(key, expireTime) {
46
+ const lockSuccessful = await this.redis.setnx(key, 'locked');
47
+ if (lockSuccessful) {
48
+ await this.redis.expire(key, expireTime);
49
+ return true;
50
+ }
51
+ else {
52
+ return false;
53
+ }
54
+ }
55
+ /**
56
+ * 队列名称
57
+ * @param cls
58
+ * @param mod
59
+ */
60
+ async createQueue(cls, mod) {
61
+ this.redis;
62
+ if (this.redisConfig instanceof Array) {
63
+ this.redis = new ioredis_1.default.Cluster(this.redisConfig, {
64
+ enableReadyCheck: false,
65
+ });
66
+ }
67
+ else {
68
+ this.redis = new ioredis_1.default({
69
+ ...this.redisConfig,
70
+ enableReadyCheck: false,
71
+ maxRetriesPerRequest: null,
72
+ });
73
+ }
74
+ const name = mod.name;
75
+ const config = (0, core_1.getClassMetadata)(queue_1.HLW_TASK_KEY, mod);
76
+ const opts = {
77
+ connection: this.redis,
78
+ prefix: `{queue${name}}`,
79
+ defaultJobOptions: {
80
+ removeOnComplete: true,
81
+ removeOnFail: true,
82
+ attempts: 5,
83
+ backoff: {
84
+ type: 'fixed',
85
+ delay: 10000,
86
+ },
87
+ ...(config.queue || {}),
88
+ },
89
+ };
90
+ const queue = new bullmq_1.Queue(name, opts);
91
+ cls.metaQueue = queue;
92
+ cls.queueName = name;
93
+ let lock = false;
94
+ // 本地开发的情况下直接获得锁
95
+ if (config.type == 'single') {
96
+ if (this.app.getEnv() == 'local') {
97
+ lock = true;
98
+ }
99
+ else {
100
+ // cluster 需要配合redis 获得锁
101
+ if (await this.getLock('HLW_QUEUE_SINGLE', 15)) {
102
+ lock = true;
103
+ }
104
+ }
105
+ }
106
+ if (config.type == 'comm' || (config.type == 'single' && lock)) {
107
+ cls.worker = new bullmq_1.Worker(name, async (job) => {
108
+ await cls.data(job, async () => {
109
+ await job.isCompleted();
110
+ });
111
+ }, {
112
+ connection: opts.connection,
113
+ prefix: opts.prefix,
114
+ ...(config.worker || {}),
115
+ });
116
+ }
117
+ else {
118
+ cls.getters = new bullmq_1.QueueGetters(name, opts);
119
+ }
120
+ this.coreLogger.info(`\x1B[36m [hlw:task] create ${name} queue \x1B[0m`);
121
+ }
122
+ };
123
+ exports.HlwQueueHandle = HlwQueueHandle;
124
+ __decorate([
125
+ (0, core_1.Config)('hlw.redis'),
126
+ __metadata("design:type", Object)
127
+ ], HlwQueueHandle.prototype, "redisConfig", void 0);
128
+ __decorate([
129
+ (0, core_1.Logger)(),
130
+ __metadata("design:type", Object)
131
+ ], HlwQueueHandle.prototype, "coreLogger", void 0);
132
+ __decorate([
133
+ (0, core_1.App)(),
134
+ __metadata("design:type", Object)
135
+ ], HlwQueueHandle.prototype, "app", void 0);
136
+ __decorate([
137
+ (0, core_1.Init)(),
138
+ __metadata("design:type", Function),
139
+ __metadata("design:paramtypes", []),
140
+ __metadata("design:returntype", Promise)
141
+ ], HlwQueueHandle.prototype, "init", null);
142
+ exports.HlwQueueHandle = HlwQueueHandle = __decorate([
143
+ (0, core_1.Provide)(),
144
+ (0, core_1.Scope)(core_1.ScopeEnum.Singleton)
145
+ ], HlwQueueHandle);
package/index.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ export * from './dist/index';
2
+
3
+ declare module '@midwayjs/core/dist/interface' {
4
+ interface MidwayConfig {
5
+ book?: PowerPartial<{
6
+ a: number;
7
+ b: string;
8
+ }>;
9
+ }
10
+ }
package/package.json ADDED
@@ -0,0 +1,49 @@
1
+ {
2
+ "name": "@hlw-midway/task",
3
+ "version": "1.0.0",
4
+ "description": "hlw-admin midway task",
5
+ "main": "dist/index.js",
6
+ "typings": "index.d.ts",
7
+ "scripts": {
8
+ "build": "mwtsc --cleanOutDir",
9
+ "test": "cross-env NODE_ENV=unittest jest",
10
+ "cov": "jest --coverage",
11
+ "lint": "mwts check",
12
+ "lint:fix": "mwts fix"
13
+ },
14
+ "keywords": [
15
+ "hlw",
16
+ "hlw-admin"
17
+ ],
18
+ "author": "HLW",
19
+ "files": [
20
+ "dist/**/*.js",
21
+ "dist/**/*.d.ts",
22
+ "index.d.ts"
23
+ ],
24
+ "readme": "README.md",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://www.baidu.com"
29
+ },
30
+ "devDependencies": {
31
+ "@hlw-midway/core": "file:../core",
32
+ "@midwayjs/core": "^3.20.0",
33
+ "@midwayjs/mock": "^3.20.0",
34
+ "@midwayjs/redis": "^3.20.0",
35
+ "@types/jest": "^29.5.14",
36
+ "@types/node": "^22.10.7",
37
+ "cross-env": "^7.0.3",
38
+ "mwtsc": "^1.15.1",
39
+ "jest": "^29.7.0",
40
+ "lodash": "^4.17.21",
41
+ "mwts": "^1.3.0",
42
+ "ts-jest": "^29.2.5",
43
+ "typescript": "^5.7.3"
44
+ },
45
+ "dependencies": {
46
+ "bullmq": "^5.34.10",
47
+ "ioredis": "^5.4.2"
48
+ }
49
+ }