@nest-omni/core 2.0.1-11 → 2.0.1-12

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nest-omni/core",
3
- "version": "2.0.1-11",
3
+ "version": "2.0.1-12",
4
4
  "description": "framework",
5
5
  "main": "index.js",
6
6
  "types": "index.d.ts",
@@ -16,6 +16,7 @@ const dotenv = require("dotenv");
16
16
  const fs_1 = require("fs");
17
17
  const path_1 = require("path");
18
18
  const process = require("process");
19
+ const mode_setup_1 = require("./mode.setup");
19
20
  function findValidRootPath() {
20
21
  const getAppRootPath = () => {
21
22
  if (require.main && require.main.filename) {
@@ -117,79 +118,21 @@ crud_1.CrudConfigService.load({
117
118
  },
118
119
  },
119
120
  });
120
- const setupProcessHandlers = (app) => {
121
- const logger = app.get(nestjs_pino_1.Logger);
122
- process.on('uncaughtException', (error) => {
123
- logger.fatal({ error, stack: error.stack, pid: process.pid }, 'Uncaught Exception');
124
- process.exit(1);
125
- });
126
- process.on('unhandledRejection', (reason, promise) => {
127
- logger.error({
128
- reason: {
129
- message: reason.message,
130
- stack: reason.stack,
131
- name: reason.name,
132
- },
133
- promise,
134
- pid: process.pid,
135
- }, 'Unhandled Rejection');
136
- });
137
- process.on('exit', (code) => {
138
- logger.warn(`Process exiting with code ${code}`, {
139
- uptime: process.uptime(),
140
- memoryUsage: process.memoryUsage(),
141
- });
142
- });
143
- };
144
- const setupGracefulShutdown = (app) => {
145
- const logger = app.get(nestjs_pino_1.Logger);
146
- const shutdown = (signal) => __awaiter(void 0, void 0, void 0, function* () {
147
- var _a;
148
- try {
149
- logger.warn(`Received ${signal}, starting graceful shutdown...`, {
150
- uptime: process.uptime(),
151
- connections: (_a = app.getHttpServer()) === null || _a === void 0 ? void 0 : _a.address(),
152
- });
153
- yield Promise.race([
154
- app.close(),
155
- new Promise((_, reject) => setTimeout(() => reject(new Error('Shutdown timeout exceeded')), 15000)),
156
- ]);
157
- logger.log('Application successfully closed', {
158
- resourcesReleased: true,
159
- pid: process.pid,
160
- });
161
- process.exit(0);
162
- }
163
- catch (err) {
164
- logger.error('Graceful shutdown failed', {
165
- error: {
166
- message: err.message,
167
- stack: err.stack,
168
- name: err.name,
169
- },
170
- critical: true,
171
- pid: process.pid,
172
- });
173
- process.exit(1);
174
- }
175
- });
176
- process.on('SIGQUIT', () => shutdown('SIGQUIT'));
177
- process.on('SIGHUP', () => shutdown('SIGHUP'));
178
- process.on('SIGTERM', () => shutdown('SIGTERM'));
179
- process.on('SIGINT', () => shutdown('SIGINT'));
180
- };
181
121
  function bootstrapSetup(AppModule, SetupSwagger) {
182
122
  return __awaiter(this, void 0, void 0, function* () {
183
123
  (0, typeorm_transactional_1.initializeTransactionalContext)();
124
+ const shouldStartHttp = (0, mode_setup_1.shouldStartHttpServer)();
184
125
  const app = yield core_1.NestFactory.create(AppModule, {
185
126
  bufferLogs: true,
127
+ abortOnError: false,
128
+ autoFlushLogs: true,
186
129
  });
187
130
  (0, class_validator_1.useContainer)(app.select(AppModule), { fallbackOnErrors: true });
188
131
  const configService = app.select(__1.ServiceRegistryModule).get(__1.ApiConfigService);
189
132
  const logger = app.get(nestjs_pino_1.Logger);
190
- setupProcessHandlers(app);
133
+ logger.log(`Application Mode: ${(0, mode_setup_1.getModeDescription)()}`);
134
+ logger.log(`Environment: ${process.env.NODE_ENV || 'unknown'}`);
191
135
  app.enableShutdownHooks();
192
- setupGracefulShutdown(app);
193
136
  app.enableVersioning();
194
137
  app.enable('trust proxy');
195
138
  app.use(bodyParse.json({ limit: '50mb' }), new nestjs_cls_1.ClsMiddleware({}).use, (0, __1.RequestIdMiddleware)(), (0, __1.PowerByMiddleware)(), (0, __1.OmniAuthMiddleware)(), compression());
@@ -203,26 +146,33 @@ function bootstrapSetup(AppModule, SetupSwagger) {
203
146
  stopAtFirstError: true,
204
147
  validationError: { target: false, value: false },
205
148
  }));
206
- if (configService.documentationEnabled && SetupSwagger) {
207
- SetupSwagger(app, configService.documentationPath);
208
- logger.log(`Swagger docs available at ${configService.documentationPath}`);
209
- }
210
- if (configService.viewsEnabled) {
211
- app.setBaseViewsDir((0, path_1.join)(__1.ApiConfigService.rootPath, 'views'));
212
- app.setViewEngine('ejs');
213
- logger.log('View engine initialized');
214
- }
215
- if (configService.sessionEnabled) {
216
- app.use(session(configService.sessionConfig));
217
- logger.log('Session middleware enabled');
149
+ if (shouldStartHttp) {
150
+ if (configService.documentationEnabled && SetupSwagger) {
151
+ SetupSwagger(app, configService.documentationPath);
152
+ logger.log(`Swagger docs available at ${configService.documentationPath}`);
153
+ }
154
+ if (configService.viewsEnabled) {
155
+ app.setBaseViewsDir((0, path_1.join)(__1.ApiConfigService.rootPath, 'views'));
156
+ app.setViewEngine('ejs');
157
+ logger.log('View engine initialized');
158
+ }
159
+ if (configService.sessionEnabled) {
160
+ app.use(session(configService.sessionConfig));
161
+ logger.log('Session middleware enabled');
162
+ }
163
+ if (configService.corsEnabled) {
164
+ app.enableCors(configService.corsConfig);
165
+ logger.log('CORS configuration applied');
166
+ }
167
+ const port = configService.appConfig.port;
168
+ yield app.listen(port);
169
+ logger.log(`HTTP Server running on ${yield app.getUrl()}`);
218
170
  }
219
- if (configService.corsEnabled) {
220
- app.enableCors(configService.corsConfig);
221
- logger.log('CORS configuration applied');
171
+ else {
172
+ logger.log('Running in Worker-only mode - HTTP server not started');
173
+ logger.log('Application is ready to process background tasks');
174
+ yield app.init();
222
175
  }
223
- const port = configService.appConfig.port;
224
- yield app.listen(port);
225
- logger.log(`Server running on ${yield app.getUrl()}`);
226
176
  return app;
227
177
  });
228
178
  }
package/setup/index.d.ts CHANGED
@@ -1 +1,6 @@
1
1
  export * from './bootstrap.setup';
2
+ export * from './mode.setup';
3
+ export * from './worker.decorator';
4
+ export * from './schedule.decorator';
5
+ export * from './redis.lock.service';
6
+ export * from './redis.lock.decorator';
package/setup/index.js CHANGED
@@ -15,3 +15,8 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./bootstrap.setup"), exports);
18
+ __exportStar(require("./mode.setup"), exports);
19
+ __exportStar(require("./worker.decorator"), exports);
20
+ __exportStar(require("./schedule.decorator"), exports);
21
+ __exportStar(require("./redis.lock.service"), exports);
22
+ __exportStar(require("./redis.lock.decorator"), exports);
@@ -0,0 +1,12 @@
1
+ export declare enum ApplicationMode {
2
+ HTTP = "http",
3
+ WORKER = "worker",
4
+ HYBRID = "hybrid"
5
+ }
6
+ export declare function getApplicationMode(): ApplicationMode;
7
+ export declare function shouldProcessQueues(): boolean;
8
+ export declare function shouldStartHttpServer(): boolean;
9
+ export declare function isHttpMode(): boolean;
10
+ export declare function isWorkerMode(): boolean;
11
+ export declare function isHybridMode(): boolean;
12
+ export declare function getModeDescription(): string;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ApplicationMode = void 0;
4
+ exports.getApplicationMode = getApplicationMode;
5
+ exports.shouldProcessQueues = shouldProcessQueues;
6
+ exports.shouldStartHttpServer = shouldStartHttpServer;
7
+ exports.isHttpMode = isHttpMode;
8
+ exports.isWorkerMode = isWorkerMode;
9
+ exports.isHybridMode = isHybridMode;
10
+ exports.getModeDescription = getModeDescription;
11
+ var ApplicationMode;
12
+ (function (ApplicationMode) {
13
+ ApplicationMode["HTTP"] = "http";
14
+ ApplicationMode["WORKER"] = "worker";
15
+ ApplicationMode["HYBRID"] = "hybrid";
16
+ })(ApplicationMode || (exports.ApplicationMode = ApplicationMode = {}));
17
+ function getApplicationMode() {
18
+ const mode = (process.env.APP_MODE || process.env.MODE || 'hybrid')
19
+ .toLowerCase()
20
+ .trim();
21
+ switch (mode) {
22
+ case 'http':
23
+ return ApplicationMode.HTTP;
24
+ case 'worker':
25
+ return ApplicationMode.WORKER;
26
+ case 'hybrid':
27
+ default:
28
+ return ApplicationMode.HYBRID;
29
+ }
30
+ }
31
+ function shouldProcessQueues() {
32
+ const mode = getApplicationMode();
33
+ return mode === ApplicationMode.WORKER || mode === ApplicationMode.HYBRID;
34
+ }
35
+ function shouldStartHttpServer() {
36
+ const mode = getApplicationMode();
37
+ return mode === ApplicationMode.HTTP || mode === ApplicationMode.HYBRID;
38
+ }
39
+ function isHttpMode() {
40
+ return getApplicationMode() === ApplicationMode.HTTP;
41
+ }
42
+ function isWorkerMode() {
43
+ return getApplicationMode() === ApplicationMode.WORKER;
44
+ }
45
+ function isHybridMode() {
46
+ return getApplicationMode() === ApplicationMode.HYBRID;
47
+ }
48
+ function getModeDescription() {
49
+ const mode = getApplicationMode();
50
+ switch (mode) {
51
+ case ApplicationMode.HTTP:
52
+ return 'HTTP-only mode (no background workers)';
53
+ case ApplicationMode.WORKER:
54
+ return 'Worker-only mode (no HTTP server)';
55
+ case ApplicationMode.HYBRID:
56
+ return 'Hybrid mode (HTTP server + background workers)';
57
+ default:
58
+ return 'Unknown mode';
59
+ }
60
+ }
@@ -0,0 +1,5 @@
1
+ import type { LockOptions } from './redis.lock.service';
2
+ export declare function UseRedisLock(lockKey: string, options?: LockOptions & {
3
+ skipReturnValue?: any;
4
+ }): MethodDecorator;
5
+ export declare function UseRedisLockOrSkip(lockKey: string, ttl?: number): MethodDecorator;
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.UseRedisLock = UseRedisLock;
13
+ exports.UseRedisLockOrSkip = UseRedisLockOrSkip;
14
+ const common_1 = require("@nestjs/common");
15
+ function UseRedisLock(lockKey, options = {}) {
16
+ return function (target, propertyKey, descriptor) {
17
+ const originalMethod = descriptor.value;
18
+ const logger = new common_1.Logger(`RedisLock:${String(propertyKey)}`);
19
+ descriptor.value = function (...args) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ var _a;
22
+ const lockService = this.lockService;
23
+ if (!lockService) {
24
+ logger.error(`RedisLockService not found on ${target.constructor.name}. ` +
25
+ `Please inject RedisLockService as 'lockService' in the constructor.`);
26
+ throw new Error(`RedisLockService not found. Please inject it as 'lockService'.`);
27
+ }
28
+ const skipReturnValue = (_a = options.skipReturnValue) !== null && _a !== void 0 ? _a : null;
29
+ const lockResult = yield lockService.acquireLock(lockKey, options);
30
+ if (!lockResult.acquired) {
31
+ logger.log(`Lock '${lockKey}' is already held, skipping execution of ${String(propertyKey)}`);
32
+ return skipReturnValue;
33
+ }
34
+ logger.debug(`Lock '${lockKey}' acquired, executing ${String(propertyKey)}`);
35
+ try {
36
+ return yield originalMethod.apply(this, args);
37
+ }
38
+ catch (error) {
39
+ logger.error(`Error executing ${String(propertyKey)} with lock '${lockKey}':`, error);
40
+ throw error;
41
+ }
42
+ finally {
43
+ yield lockService.releaseLock(lockKey, lockResult.lockValue, options.keyPrefix);
44
+ logger.debug(`Lock '${lockKey}' released`);
45
+ }
46
+ });
47
+ };
48
+ return descriptor;
49
+ };
50
+ }
51
+ function UseRedisLockOrSkip(lockKey, ttl = 300000) {
52
+ return UseRedisLock(lockKey, {
53
+ ttl,
54
+ skipReturnValue: false,
55
+ });
56
+ }
@@ -0,0 +1,30 @@
1
+ import { OnModuleInit } from '@nestjs/common';
2
+ import { RedisService } from '@liaoliaots/nestjs-redis';
3
+ export interface LockOptions {
4
+ ttl?: number;
5
+ retryCount?: number;
6
+ retryDelay?: number;
7
+ keyPrefix?: string;
8
+ throwOnFailure?: boolean;
9
+ }
10
+ export interface LockResult {
11
+ acquired: boolean;
12
+ lockValue?: string;
13
+ error?: string;
14
+ }
15
+ export declare class RedisLockService implements OnModuleInit {
16
+ private readonly redisService;
17
+ private readonly logger;
18
+ private redis;
19
+ private readonly defaultOptions;
20
+ constructor(redisService: RedisService);
21
+ onModuleInit(): void;
22
+ private generateLockValue;
23
+ private buildLockKey;
24
+ private sleep;
25
+ acquireLock(key: string, options?: LockOptions): Promise<LockResult>;
26
+ releaseLock(key: string, lockValue: string, keyPrefix?: string): Promise<boolean>;
27
+ extendLock(key: string, lockValue: string, ttl: number, keyPrefix?: string): Promise<boolean>;
28
+ isLocked(key: string, keyPrefix?: string): Promise<boolean>;
29
+ withLock<T>(key: string, fn: () => Promise<T>, options?: LockOptions): Promise<T | null>;
30
+ }
@@ -0,0 +1,185 @@
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
12
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
13
+ return new (P || (P = Promise))(function (resolve, reject) {
14
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
15
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
16
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
17
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
18
+ });
19
+ };
20
+ var RedisLockService_1;
21
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.RedisLockService = void 0;
23
+ const common_1 = require("@nestjs/common");
24
+ const nestjs_redis_1 = require("@liaoliaots/nestjs-redis");
25
+ let RedisLockService = RedisLockService_1 = class RedisLockService {
26
+ constructor(redisService) {
27
+ this.redisService = redisService;
28
+ this.logger = new common_1.Logger(RedisLockService_1.name);
29
+ this.defaultOptions = {
30
+ ttl: 300000,
31
+ retryCount: 0,
32
+ retryDelay: 100,
33
+ keyPrefix: 'lock',
34
+ throwOnFailure: false,
35
+ };
36
+ }
37
+ onModuleInit() {
38
+ try {
39
+ this.redis = this.redisService.getOrThrow();
40
+ this.logger.log('RedisLockService initialized successfully');
41
+ }
42
+ catch (error) {
43
+ this.logger.error('Failed to initialize RedisLockService', error);
44
+ throw error;
45
+ }
46
+ }
47
+ generateLockValue() {
48
+ return `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
49
+ }
50
+ buildLockKey(key, prefix = 'lock') {
51
+ return `${prefix}:${key}`;
52
+ }
53
+ sleep(ms) {
54
+ return new Promise((resolve) => setTimeout(resolve, ms));
55
+ }
56
+ acquireLock(key_1) {
57
+ return __awaiter(this, arguments, void 0, function* (key, options = {}) {
58
+ const opts = Object.assign(Object.assign({}, this.defaultOptions), options);
59
+ const lockKey = this.buildLockKey(key, opts.keyPrefix);
60
+ const lockValue = this.generateLockValue();
61
+ let attempts = 0;
62
+ const maxAttempts = opts.retryCount + 1;
63
+ while (attempts < maxAttempts) {
64
+ try {
65
+ const result = yield this.redis.set(lockKey, lockValue, 'PX', opts.ttl, 'NX');
66
+ if (result === 'OK') {
67
+ this.logger.debug(`Lock acquired: ${lockKey} (value: ${lockValue}, ttl: ${opts.ttl}ms)`);
68
+ return { acquired: true, lockValue };
69
+ }
70
+ attempts++;
71
+ if (attempts < maxAttempts) {
72
+ this.logger.debug(`Lock acquisition failed for ${lockKey}, retrying... (${attempts}/${opts.retryCount})`);
73
+ yield this.sleep(opts.retryDelay);
74
+ }
75
+ }
76
+ catch (error) {
77
+ const errorMessage = `Error acquiring lock for ${lockKey}: ${error.message}`;
78
+ this.logger.error(errorMessage, error.stack);
79
+ if (opts.throwOnFailure) {
80
+ throw new Error(errorMessage);
81
+ }
82
+ return { acquired: false, error: errorMessage };
83
+ }
84
+ }
85
+ const failureMessage = `Failed to acquire lock for ${lockKey} after ${attempts} attempts`;
86
+ this.logger.warn(failureMessage);
87
+ if (opts.throwOnFailure) {
88
+ throw new Error(failureMessage);
89
+ }
90
+ return { acquired: false, error: failureMessage };
91
+ });
92
+ }
93
+ releaseLock(key_1, lockValue_1) {
94
+ return __awaiter(this, arguments, void 0, function* (key, lockValue, keyPrefix = 'lock') {
95
+ const lockKey = this.buildLockKey(key, keyPrefix);
96
+ try {
97
+ const script = `
98
+ if redis.call("get", KEYS[1]) == ARGV[1] then
99
+ return redis.call("del", KEYS[1])
100
+ else
101
+ return 0
102
+ end
103
+ `;
104
+ const result = yield this.redis.eval(script, 1, lockKey, lockValue);
105
+ if (result === 1) {
106
+ this.logger.debug(`Lock released: ${lockKey}`);
107
+ return true;
108
+ }
109
+ else {
110
+ this.logger.warn(`Lock release failed: ${lockKey} (lock value mismatch or already expired)`);
111
+ return false;
112
+ }
113
+ }
114
+ catch (error) {
115
+ this.logger.error(`Error releasing lock for ${lockKey}: ${error.message}`, error.stack);
116
+ return false;
117
+ }
118
+ });
119
+ }
120
+ extendLock(key_1, lockValue_1, ttl_1) {
121
+ return __awaiter(this, arguments, void 0, function* (key, lockValue, ttl, keyPrefix = 'lock') {
122
+ const lockKey = this.buildLockKey(key, keyPrefix);
123
+ try {
124
+ const script = `
125
+ if redis.call("get", KEYS[1]) == ARGV[1] then
126
+ return redis.call("pexpire", KEYS[1], ARGV[2])
127
+ else
128
+ return 0
129
+ end
130
+ `;
131
+ const result = yield this.redis.eval(script, 1, lockKey, lockValue, ttl);
132
+ if (result === 1) {
133
+ this.logger.debug(`Lock extended: ${lockKey} (new ttl: ${ttl}ms)`);
134
+ return true;
135
+ }
136
+ else {
137
+ this.logger.warn(`Lock extension failed: ${lockKey} (lock value mismatch or doesn't exist)`);
138
+ return false;
139
+ }
140
+ }
141
+ catch (error) {
142
+ this.logger.error(`Error extending lock for ${lockKey}: ${error.message}`, error.stack);
143
+ return false;
144
+ }
145
+ });
146
+ }
147
+ isLocked(key_1) {
148
+ return __awaiter(this, arguments, void 0, function* (key, keyPrefix = 'lock') {
149
+ const lockKey = this.buildLockKey(key, keyPrefix);
150
+ try {
151
+ const exists = yield this.redis.exists(lockKey);
152
+ return exists === 1;
153
+ }
154
+ catch (error) {
155
+ this.logger.error(`Error checking lock existence for ${lockKey}: ${error.message}`, error.stack);
156
+ return false;
157
+ }
158
+ });
159
+ }
160
+ withLock(key_1, fn_1) {
161
+ return __awaiter(this, arguments, void 0, function* (key, fn, options = {}) {
162
+ const lockResult = yield this.acquireLock(key, options);
163
+ if (!lockResult.acquired) {
164
+ this.logger.warn(`Could not acquire lock for ${key}, skipping execution`);
165
+ return null;
166
+ }
167
+ try {
168
+ const result = yield fn();
169
+ return result;
170
+ }
171
+ catch (error) {
172
+ this.logger.error(`Error executing function with lock ${key}:`, error);
173
+ throw error;
174
+ }
175
+ finally {
176
+ yield this.releaseLock(key, lockResult.lockValue, options.keyPrefix);
177
+ }
178
+ });
179
+ }
180
+ };
181
+ exports.RedisLockService = RedisLockService;
182
+ exports.RedisLockService = RedisLockService = RedisLockService_1 = __decorate([
183
+ (0, common_1.Injectable)(),
184
+ __metadata("design:paramtypes", [nestjs_redis_1.RedisService])
185
+ ], RedisLockService);
@@ -0,0 +1,21 @@
1
+ import type { CronOptions } from '@nestjs/schedule';
2
+ export declare function WorkerCron(cronTime: string | Date, options?: CronOptions): MethodDecorator;
3
+ export declare function WorkerInterval(timeout: number, options?: {
4
+ name?: string;
5
+ }): MethodDecorator;
6
+ export declare function WorkerTimeout(timeout: number, options?: {
7
+ name?: string;
8
+ }): MethodDecorator;
9
+ export declare function WorkerCronWithLock(cronTime: string | Date, lockKey: string, lockTtl?: number, cronOptions?: CronOptions): MethodDecorator;
10
+ export declare function WorkerIntervalWithLock(timeout: number, lockKey: string, lockTtl?: number, intervalOptions?: {
11
+ name?: string;
12
+ }): MethodDecorator;
13
+ export declare function WorkerTimeoutWithLock(timeout: number, lockKey: string, lockTtl?: number, timeoutOptions?: {
14
+ name?: string;
15
+ }): MethodDecorator;
16
+ export declare function WorkerCronAdvanced(cronTime: string | Date, lockKey: string, options?: {
17
+ lockTtl?: number;
18
+ cronOptions?: CronOptions;
19
+ logExecution?: boolean;
20
+ onError?: (error: Error) => void;
21
+ }): MethodDecorator;
@@ -0,0 +1,127 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.WorkerCron = WorkerCron;
13
+ exports.WorkerInterval = WorkerInterval;
14
+ exports.WorkerTimeout = WorkerTimeout;
15
+ exports.WorkerCronWithLock = WorkerCronWithLock;
16
+ exports.WorkerIntervalWithLock = WorkerIntervalWithLock;
17
+ exports.WorkerTimeoutWithLock = WorkerTimeoutWithLock;
18
+ exports.WorkerCronAdvanced = WorkerCronAdvanced;
19
+ const schedule_1 = require("@nestjs/schedule");
20
+ const mode_setup_1 = require("./mode.setup");
21
+ const redis_lock_decorator_1 = require("./redis.lock.decorator");
22
+ const common_1 = require("@nestjs/common");
23
+ function WorkerCron(cronTime, options) {
24
+ if ((0, mode_setup_1.shouldProcessQueues)()) {
25
+ return (0, schedule_1.Cron)(cronTime, options);
26
+ }
27
+ return function (target, propertyKey, descriptor) {
28
+ return descriptor;
29
+ };
30
+ }
31
+ function WorkerInterval(timeout, options) {
32
+ if ((0, mode_setup_1.shouldProcessQueues)()) {
33
+ return (0, schedule_1.Interval)((options === null || options === void 0 ? void 0 : options.name) || `interval-${timeout}`, timeout);
34
+ }
35
+ return function (target, propertyKey, descriptor) {
36
+ return descriptor;
37
+ };
38
+ }
39
+ function WorkerTimeout(timeout, options) {
40
+ if ((0, mode_setup_1.shouldProcessQueues)()) {
41
+ return (0, schedule_1.Timeout)((options === null || options === void 0 ? void 0 : options.name) || `timeout-${timeout}`, timeout);
42
+ }
43
+ return function (target, propertyKey, descriptor) {
44
+ return descriptor;
45
+ };
46
+ }
47
+ function WorkerCronWithLock(cronTime, lockKey, lockTtl = 300000, cronOptions) {
48
+ if (!(0, mode_setup_1.shouldProcessQueues)()) {
49
+ return function (target, propertyKey, descriptor) {
50
+ return descriptor;
51
+ };
52
+ }
53
+ return function (target, propertyKey, descriptor) {
54
+ (0, schedule_1.Cron)(cronTime, cronOptions)(target, propertyKey, descriptor);
55
+ (0, redis_lock_decorator_1.UseRedisLockOrSkip)(lockKey, lockTtl)(target, propertyKey, descriptor);
56
+ return descriptor;
57
+ };
58
+ }
59
+ function WorkerIntervalWithLock(timeout, lockKey, lockTtl, intervalOptions) {
60
+ if (!(0, mode_setup_1.shouldProcessQueues)()) {
61
+ return function (target, propertyKey, descriptor) {
62
+ return descriptor;
63
+ };
64
+ }
65
+ const ttl = lockTtl !== null && lockTtl !== void 0 ? lockTtl : timeout;
66
+ return function (target, propertyKey, descriptor) {
67
+ (0, schedule_1.Interval)((intervalOptions === null || intervalOptions === void 0 ? void 0 : intervalOptions.name) || `interval-with-lock-${timeout}`, timeout)(target, propertyKey, descriptor);
68
+ (0, redis_lock_decorator_1.UseRedisLockOrSkip)(lockKey, ttl)(target, propertyKey, descriptor);
69
+ return descriptor;
70
+ };
71
+ }
72
+ function WorkerTimeoutWithLock(timeout, lockKey, lockTtl = 300000, timeoutOptions) {
73
+ if (!(0, mode_setup_1.shouldProcessQueues)()) {
74
+ return function (target, propertyKey, descriptor) {
75
+ return descriptor;
76
+ };
77
+ }
78
+ return function (target, propertyKey, descriptor) {
79
+ (0, schedule_1.Timeout)((timeoutOptions === null || timeoutOptions === void 0 ? void 0 : timeoutOptions.name) || `timeout-with-lock-${timeout}`, timeout)(target, propertyKey, descriptor);
80
+ (0, redis_lock_decorator_1.UseRedisLockOrSkip)(lockKey, lockTtl)(target, propertyKey, descriptor);
81
+ return descriptor;
82
+ };
83
+ }
84
+ function WorkerCronAdvanced(cronTime, lockKey, options = {}) {
85
+ if (!(0, mode_setup_1.shouldProcessQueues)()) {
86
+ return function (target, propertyKey, descriptor) {
87
+ return descriptor;
88
+ };
89
+ }
90
+ const { lockTtl = 300000, cronOptions, logExecution = true, onError } = options;
91
+ return function (target, propertyKey, descriptor) {
92
+ const originalMethod = descriptor.value;
93
+ const logger = new common_1.Logger(`Scheduler:${String(propertyKey)}`);
94
+ descriptor.value = function (...args) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ const startTime = Date.now();
97
+ try {
98
+ if (logExecution) {
99
+ logger.log(`Starting scheduled task: ${String(propertyKey)}`);
100
+ }
101
+ const result = yield originalMethod.apply(this, args);
102
+ if (logExecution) {
103
+ const duration = Date.now() - startTime;
104
+ logger.log(`Completed scheduled task: ${String(propertyKey)} (${duration}ms)`);
105
+ }
106
+ return result;
107
+ }
108
+ catch (error) {
109
+ const duration = Date.now() - startTime;
110
+ logger.error(`Error in scheduled task: ${String(propertyKey)} (${duration}ms)`, error.stack);
111
+ if (onError) {
112
+ try {
113
+ onError(error);
114
+ }
115
+ catch (handlerError) {
116
+ logger.error('Error handler threw an error:', handlerError);
117
+ }
118
+ }
119
+ throw error;
120
+ }
121
+ });
122
+ };
123
+ (0, schedule_1.Cron)(cronTime, cronOptions)(target, propertyKey, descriptor);
124
+ (0, redis_lock_decorator_1.UseRedisLockOrSkip)(lockKey, lockTtl)(target, propertyKey, descriptor);
125
+ return descriptor;
126
+ };
127
+ }