raiton 6.7.0-beta.15 → 6.8.1-beta.17

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/build/bin/index.mjs +1098 -32
  3. package/docs/contributors/README.md +1 -0
  4. package/docs/contributors/core/README.md +8 -0
  5. package/docs/contributors/core/scheduler.md +113 -0
  6. package/docs/contributors/framework/decorators/README.md +4 -0
  7. package/docs/contributors/framework/decorators/scheduler.md +83 -0
  8. package/docs/user-guide/README.md +8 -5
  9. package/docs/user-guide/decorators/README.md +2 -0
  10. package/docs/user-guide/decorators/mcp.md +2 -2
  11. package/docs/user-guide/decorators/scheduler.md +75 -0
  12. package/docs/user-guide/mcp.md +2 -2
  13. package/docs/user-guide/scheduler.md +229 -0
  14. package/package.json +2 -2
  15. package/source/core/builder.ts +12 -0
  16. package/source/core/controller/builder.ts +8 -2
  17. package/source/core/index.ts +1 -0
  18. package/source/core/injection/injection.ts +4 -1
  19. package/source/core/scheduler/builder.ts +25 -0
  20. package/source/core/scheduler/cron.ts +400 -0
  21. package/source/core/scheduler/duration.ts +42 -0
  22. package/source/core/scheduler/index.ts +6 -0
  23. package/source/core/scheduler/manager.ts +542 -0
  24. package/source/core/scheduler/metadata.ts +53 -0
  25. package/source/core/scheduler/queue/backend.ts +142 -0
  26. package/source/core/scheduler/queue/index.ts +3 -0
  27. package/source/core/scheduler/queue/rabbitmq.backend.ts +124 -0
  28. package/source/core/scheduler/queue/redis.backend.ts +144 -0
  29. package/source/core/thread.ts +4 -0
  30. package/source/framework/artifacts.ts +27 -0
  31. package/source/framework/constants/decorators.constant.ts +2 -0
  32. package/source/framework/decorators/index.ts +2 -1
  33. package/source/framework/decorators/scheduler.decorator.ts +139 -0
  34. package/source/framework/enums/index.ts +2 -1
  35. package/source/framework/enums/scheduler.enum.ts +23 -0
  36. package/source/framework/utilities/artifact.util.ts +4 -0
  37. package/source/types/index.ts +2 -1
  38. package/source/types/raiton.ts +1 -0
  39. package/source/types/scheduler.ts +180 -0
@@ -0,0 +1,542 @@
1
+ import type {
2
+ JobMetaInterface,
3
+ QueueBackendInterface,
4
+ QueueMessageInterface,
5
+ SchedulerConfigInterface,
6
+ SchedulerControlInterface,
7
+ ScheduledJobInfoInterface,
8
+ TaskContextInterface,
9
+ TaskInvocationInterface,
10
+ TaskTriggerType,
11
+ } from "../../types/index.ts";
12
+ import {TaskTriggerEnum} from "../../framework/enums/index.ts";
13
+ import {Logger} from "@protorians/logger";
14
+ import {CronSchedule, CronScheduleInterface} from "./cron.ts";
15
+ import {MemoryQueueBackend, wait} from "./queue/backend.ts";
16
+ import {parseDuration} from "./duration.ts";
17
+
18
+ interface JobRuntime {
19
+ name: string;
20
+ type: TaskTriggerType;
21
+ instance: any;
22
+ propertyKey: string;
23
+ handler: (ctx: TaskContextInterface) => any;
24
+ options: JobOptions;
25
+ queue: string;
26
+ cron?: CronScheduleInterface;
27
+ interval?: number;
28
+ delay?: number;
29
+ running: number;
30
+ lastRun?: Date;
31
+ nextRun?: Date;
32
+ lastError?: any;
33
+ runCount: number;
34
+ failCount: number;
35
+ paused: boolean;
36
+ missed: boolean;
37
+ timer?: ReturnType<typeof setTimeout>;
38
+ }
39
+
40
+ interface JobOptions {
41
+ singleton: boolean;
42
+ concurrency: number;
43
+ retries: number;
44
+ retryDelay?: number | ((attempt: number) => number);
45
+ timeout?: number;
46
+ catchUp: boolean;
47
+ enabled: boolean;
48
+ consume: boolean;
49
+ immediate: boolean;
50
+ priority?: string;
51
+ data?: any;
52
+ }
53
+
54
+ const DEFAULT_CONFIG: SchedulerConfigInterface = {
55
+ enabled: true,
56
+ timezone: 'UTC',
57
+ maxConcurrentJobs: 100,
58
+ defaultQueue: 'default',
59
+ };
60
+
61
+ export class SchedulerManager implements SchedulerControlInterface {
62
+ private static _instance: SchedulerManager;
63
+
64
+ private readonly _config: SchedulerConfigInterface = {...DEFAULT_CONFIG};
65
+ private readonly _backends = new Map<string, QueueBackendInterface>();
66
+ private readonly _queueBackends = new Map<string, string>();
67
+ private readonly _jobs = new Map<string, JobRuntime>();
68
+ private readonly _timers = new Set<ReturnType<typeof setTimeout>>();
69
+ private readonly _consumers = new Set<Promise<void>>();
70
+ private _defaultBackend: QueueBackendInterface;
71
+ private _running = false;
72
+ private _booted = false;
73
+
74
+ constructor() {
75
+ this._defaultBackend = new MemoryQueueBackend();
76
+ this._backends.set(this._defaultBackend.name, this._defaultBackend);
77
+ }
78
+
79
+ static get current(): SchedulerManager {
80
+ if (!SchedulerManager._instance) {
81
+ SchedulerManager._instance = new SchedulerManager();
82
+ }
83
+ return SchedulerManager._instance;
84
+ }
85
+
86
+ get enabled(): boolean {
87
+ return this._config.enabled;
88
+ }
89
+
90
+ get running(): boolean {
91
+ return this._running;
92
+ }
93
+
94
+ configure(config: Partial<SchedulerConfigInterface>): this {
95
+ Object.assign(this._config, config);
96
+ if (config.backend) {
97
+ this._defaultBackend = config.backend;
98
+ this._backends.set(config.backend.name, config.backend);
99
+ }
100
+ if (config.backends) {
101
+ for (const [name, backend] of Object.entries(config.backends)) {
102
+ this._backends.set(name, backend);
103
+ }
104
+ }
105
+ return this;
106
+ }
107
+
108
+ registerBackend(name: string, backend: QueueBackendInterface): this {
109
+ this._backends.set(name, backend);
110
+ if (!this._defaultBackend || this._backends.size === 1) {
111
+ this._defaultBackend = backend;
112
+ }
113
+ return this;
114
+ }
115
+
116
+ getBackend(queue?: string): QueueBackendInterface {
117
+ if (queue) {
118
+ const backendName = this._queueBackends.get(queue);
119
+ if (backendName) {
120
+ const backend = this._backends.get(backendName);
121
+ if (backend) return backend;
122
+ }
123
+ }
124
+ return this._defaultBackend;
125
+ }
126
+
127
+ mapQueue(queue: string, backendName: string): this {
128
+ this._queueBackends.set(queue, backendName);
129
+ return this;
130
+ }
131
+
132
+ get backends(): Map<string, QueueBackendInterface> {
133
+ return this._backends;
134
+ }
135
+
136
+ register(name: string, instance: any, jobs: JobMetaInterface[]): this {
137
+ for (const meta of jobs) {
138
+ const handler = typeof instance[meta.propertyKey] === 'function'
139
+ ? instance[meta.propertyKey].bind(instance)
140
+ : undefined;
141
+
142
+ if (!handler) {
143
+ Logger.warn(`Scheduler: method "${meta.propertyKey}" not found on "${name}".`);
144
+ continue;
145
+ }
146
+
147
+ const job: JobRuntime = {
148
+ name: meta.name,
149
+ type: meta.type,
150
+ instance,
151
+ propertyKey: meta.propertyKey,
152
+ handler,
153
+ options: this.resolveOptions(meta),
154
+ queue: meta.queue || 'default',
155
+ cron: meta.cron ? new CronSchedule(meta.cron, meta.options.timezone ?? this._config.timezone) : undefined,
156
+ interval: meta.interval,
157
+ delay: meta.delay,
158
+ running: 0,
159
+ runCount: 0,
160
+ failCount: 0,
161
+ paused: false,
162
+ missed: false,
163
+ };
164
+
165
+ const existing = this._jobs.get(job.name);
166
+ if (existing) {
167
+ this.clearTimer(existing);
168
+ existing.paused = true;
169
+ }
170
+
171
+ this._jobs.set(job.name, job);
172
+
173
+ if (this._running) {
174
+ this.startJob(job);
175
+ }
176
+ }
177
+ return this;
178
+ }
179
+
180
+ async start(): Promise<void> {
181
+ if (!this._config.enabled || this._booted) return;
182
+
183
+ for (const backend of this._backends.values()) {
184
+ await backend.connect();
185
+ }
186
+
187
+ this._running = true;
188
+ this._booted = true;
189
+
190
+ for (const job of this._jobs.values()) {
191
+ this.startJob(job);
192
+ }
193
+
194
+ Logger.info(`Scheduler started with ${this._jobs.size} registered job(s).`);
195
+ }
196
+
197
+ async stop(): Promise<void> {
198
+ if (!this._booted) return;
199
+ this._running = false;
200
+
201
+ for (const timer of this._timers) {
202
+ clearTimeout(timer);
203
+ }
204
+ this._timers.clear();
205
+
206
+ for (const job of this._jobs.values()) {
207
+ if (job.timer) clearTimeout(job.timer);
208
+ job.timer = undefined;
209
+ job.paused = true;
210
+ }
211
+
212
+ await Promise.allSettled(this._consumers);
213
+ this._consumers.clear();
214
+
215
+ for (const backend of this._backends.values()) {
216
+ await backend.disconnect();
217
+ }
218
+
219
+ this._booted = false;
220
+ Logger.info('Scheduler stopped.');
221
+ }
222
+
223
+ has(name: string): boolean {
224
+ return this._jobs.has(name);
225
+ }
226
+
227
+ getJob(name: string): ScheduledJobInfoInterface | undefined {
228
+ const job = this._jobs.get(name);
229
+ return job ? this.info(job) : undefined;
230
+ }
231
+
232
+ getJobs(): ScheduledJobInfoInterface[] {
233
+ return Array.from(this._jobs.values()).map(job => this.info(job));
234
+ }
235
+
236
+ async enqueue(name: string, payload?: any, options: Partial<TaskInvocationInterface> = {}): Promise<TaskInvocationInterface> {
237
+ const job = this._jobs.get(name);
238
+ if (!job) throw new Error(`Task "${name}" is not registered.`);
239
+
240
+ const queue = options.queue ?? job.queue ?? this._config.defaultQueue;
241
+ const backend = this.getBackend(queue);
242
+
243
+ const message: QueueMessageInterface = {
244
+ id: options.id ?? randomId(),
245
+ queue,
246
+ payload: options.payload ?? payload,
247
+ attempts: options.attempt ?? 0,
248
+ enqueuedAt: Date.now(),
249
+ availableAt: options.scheduleAt ?? Date.now(),
250
+ };
251
+
252
+ await backend.enqueue(queue, message);
253
+
254
+ return {
255
+ id: message.id,
256
+ name,
257
+ queue,
258
+ payload: message.payload,
259
+ data: options.data ?? job.options.data,
260
+ trigger: options.trigger ?? TaskTriggerEnum.Task,
261
+ attempt: message.attempts,
262
+ priority: options.priority,
263
+ delay: options.delay,
264
+ scheduledAt: options.scheduledAt ?? new Date(),
265
+ scheduleAt: options.scheduleAt,
266
+ };
267
+ }
268
+
269
+ async dispatch(name: string, payload?: any, options: Partial<TaskInvocationInterface> = {}): Promise<any> {
270
+ const job = this._jobs.get(name);
271
+ if (!job) throw new Error(`Task "${name}" is not registered.`);
272
+
273
+ const ctx = this.buildContext(job, options.payload ?? payload, options.trigger ?? TaskTriggerEnum.Task, options.attempt ?? 0, options.id);
274
+ return this.dispatchNow(job, ctx);
275
+ }
276
+
277
+ async trigger(name: string, payload?: any, options: Partial<TaskInvocationInterface> = {}): Promise<any> {
278
+ return this.dispatch(name, payload, options);
279
+ }
280
+
281
+ pause(name: string): void {
282
+ const job = this._jobs.get(name);
283
+ if (!job || job.paused) return;
284
+ job.paused = true;
285
+ this.clearTimer(job);
286
+ }
287
+
288
+ resume(name: string): void {
289
+ const job = this._jobs.get(name);
290
+ if (!job || !job.paused) return;
291
+ job.paused = false;
292
+ if (this._running) this.startJob(job);
293
+ }
294
+
295
+ cancel(name: string): boolean {
296
+ const job = this._jobs.get(name);
297
+ if (!job) return false;
298
+ this.clearTimer(job);
299
+ this._jobs.delete(name);
300
+ return true;
301
+ }
302
+
303
+ private resolveOptions(meta: JobMetaInterface): JobOptions {
304
+ const options = meta.options || {};
305
+ return {
306
+ singleton: options.singleton ?? true,
307
+ concurrency: options.concurrency ?? 1,
308
+ retries: options.retries ?? 0,
309
+ retryDelay: options.retryDelay,
310
+ timeout: options.timeout,
311
+ catchUp: options.catchUp ?? false,
312
+ enabled: options.enabled ?? true,
313
+ consume: options.consume ?? false,
314
+ immediate: options.immediate ?? false,
315
+ priority: options.priority,
316
+ data: options.data,
317
+ };
318
+ }
319
+
320
+ private startJob(job: JobRuntime): void {
321
+ if (!job.options.enabled) return;
322
+
323
+ if (job.options.consume) {
324
+ this._consumers.add(this.consume(job));
325
+ }
326
+
327
+ switch (job.type) {
328
+ case TaskTriggerEnum.Cron:
329
+ this.armCron(job);
330
+ break;
331
+ case TaskTriggerEnum.Interval:
332
+ this.armInterval(job);
333
+ if (job.options.immediate) {
334
+ this.dispatchNow(job, this.buildContext(job, undefined, TaskTriggerEnum.Interval)).catch((e: any) => {
335
+ Logger.error(`Task "${job.name}" failed`, e?.message ?? e);
336
+ });
337
+ }
338
+ break;
339
+ case TaskTriggerEnum.Timeout:
340
+ this.armTimeout(job);
341
+ break;
342
+ case TaskTriggerEnum.Task:
343
+ break;
344
+ }
345
+ }
346
+
347
+ private armCron(job: JobRuntime): void {
348
+ const next = job.cron?.next(new Date());
349
+ if (!next) return;
350
+ job.nextRun = next;
351
+ const delay = Math.max(0, next.getTime() - Date.now());
352
+ job.timer = setTimeout(() => {
353
+ this._timers.delete(job.timer!);
354
+ this.tick(job, TaskTriggerEnum.Cron);
355
+ }, delay);
356
+ this._timers.add(job.timer);
357
+ }
358
+
359
+ private armInterval(job: JobRuntime): void {
360
+ const interval = job.interval ?? parseDuration(0);
361
+ job.nextRun = new Date(Date.now() + interval);
362
+ job.timer = setTimeout(() => {
363
+ this._timers.delete(job.timer!);
364
+ this.tick(job, TaskTriggerEnum.Interval);
365
+ }, interval);
366
+ this._timers.add(job.timer);
367
+ }
368
+
369
+ private armTimeout(job: JobRuntime): void {
370
+ const delay = job.delay ?? 0;
371
+ job.nextRun = new Date(Date.now() + delay);
372
+ job.timer = setTimeout(() => {
373
+ this._timers.delete(job.timer!);
374
+ this.tick(job, TaskTriggerEnum.Timeout);
375
+ }, delay);
376
+ this._timers.add(job.timer);
377
+ }
378
+
379
+ private tick(job: JobRuntime, trigger: TaskTriggerType): void {
380
+ if (!this._running || job.paused || !this._jobs.has(job.name)) return;
381
+
382
+ if (trigger === TaskTriggerEnum.Cron) {
383
+ this.armCron(job);
384
+ } else if (trigger === TaskTriggerEnum.Interval) {
385
+ this.armInterval(job);
386
+ }
387
+
388
+ const ctx = this.buildContext(job, undefined, trigger);
389
+ this.dispatchNow(job, ctx).catch((e: any) => {
390
+ Logger.error(`Task "${job.name}" failed`, e?.message ?? e);
391
+ });
392
+ }
393
+
394
+ private async dispatchNow(job: JobRuntime, ctx: TaskContextInterface): Promise<any> {
395
+ if (!this._running && ctx.trigger !== TaskTriggerEnum.Task) return undefined;
396
+
397
+ if (job.options.singleton && job.running > 0) {
398
+ if (job.options.catchUp) job.missed = true;
399
+ return undefined;
400
+ }
401
+
402
+ const result = await this.runOnce(job, ctx);
403
+
404
+ if (job.missed) {
405
+ job.missed = false;
406
+ setTimeout(() => {
407
+ if (this._jobs.has(job.name)) {
408
+ this.dispatchNow(job, this.buildContext(job, undefined, ctx.trigger)).catch(() => { /* noop */ });
409
+ }
410
+ }, 0);
411
+ }
412
+
413
+ return result;
414
+ }
415
+
416
+ private async runOnce(job: JobRuntime, ctx: TaskContextInterface): Promise<any> {
417
+ job.running += 1;
418
+ job.lastRun = new Date();
419
+ job.runCount += 1;
420
+
421
+ const maxAttempts = job.options.retries;
422
+ let attempt = 0;
423
+
424
+ try {
425
+ while (true) {
426
+ ctx.attempt = attempt;
427
+ ctx.startedAt = new Date();
428
+ try {
429
+ return await withTimeout(job.handler(ctx), job.options.timeout);
430
+ } catch (e) {
431
+ attempt += 1;
432
+ if (attempt > maxAttempts) {
433
+ job.failCount += 1;
434
+ job.lastError = e;
435
+ throw e;
436
+ }
437
+ const delay = resolveRetryDelay(job.options.retryDelay, attempt);
438
+ if (delay > 0) await wait(delay);
439
+ }
440
+ }
441
+ } finally {
442
+ job.running -= 1;
443
+ }
444
+ }
445
+
446
+ private async consume(job: JobRuntime): Promise<void> {
447
+ const backend = this.getBackend(job.queue);
448
+ const count = Math.max(1, job.options.concurrency);
449
+
450
+ while (this._running && this._jobs.get(job.name) === job) {
451
+ try {
452
+ const messages = await backend.dequeue(job.queue, {blockMs: 1000, count});
453
+ if (messages.length === 0) continue;
454
+
455
+ await Promise.all(messages.map(message => this.processMessage(job, backend, message)));
456
+ } catch (e: any) {
457
+ if (this._running) Logger.error(`Queue consumer "${job.name}" error`, e?.message ?? e);
458
+ await wait(1000);
459
+ }
460
+ }
461
+ }
462
+
463
+ private async processMessage(job: JobRuntime, backend: QueueBackendInterface, message: QueueMessageInterface): Promise<void> {
464
+ const ctx = this.buildContext(job, message.payload, TaskTriggerEnum.Task, message.attempts, message.id);
465
+ ctx.scheduledAt = new Date(message.enqueuedAt ?? Date.now());
466
+
467
+ try {
468
+ await this.runOnce(job, ctx);
469
+ await backend.acknowledge(job.queue, message.receipt);
470
+ } catch (e: any) {
471
+ await backend.reject(job.queue, message.receipt, false);
472
+ }
473
+ }
474
+
475
+ private buildContext(job: JobRuntime, payload: any, trigger: TaskTriggerType, attempt = 0, id?: string): TaskContextInterface {
476
+ return {
477
+ id: id ?? randomId(),
478
+ name: job.name,
479
+ queue: job.queue,
480
+ payload,
481
+ data: job.options.data,
482
+ trigger,
483
+ attempt,
484
+ scheduledAt: new Date(),
485
+ startedAt: new Date(),
486
+ scheduler: this,
487
+ };
488
+ }
489
+
490
+ private info(job: JobRuntime): ScheduledJobInfoInterface {
491
+ return {
492
+ name: job.name,
493
+ type: job.type,
494
+ queue: job.queue,
495
+ nextRun: job.nextRun,
496
+ lastRun: job.lastRun,
497
+ lastError: job.lastError,
498
+ running: job.running,
499
+ runCount: job.runCount,
500
+ failCount: job.failCount,
501
+ paused: job.paused,
502
+ enabled: job.options.enabled,
503
+ };
504
+ }
505
+
506
+ private clearTimer(job: JobRuntime): void {
507
+ if (job.timer) {
508
+ clearTimeout(job.timer);
509
+ this._timers.delete(job.timer);
510
+ job.timer = undefined;
511
+ }
512
+ }
513
+ }
514
+
515
+ async function withTimeout<T>(promise: Promise<T>, timeout?: number): Promise<T> {
516
+ if (!timeout || timeout <= 0) return promise;
517
+ let timer: ReturnType<typeof setTimeout>;
518
+
519
+ const guard = new Promise<never>((_, reject) => {
520
+ timer = setTimeout(() => reject(new Error(`Task timed out after ${timeout}ms`)), timeout);
521
+ });
522
+
523
+ try {
524
+ return await Promise.race([promise, guard]);
525
+ } finally {
526
+ clearTimeout(timer!);
527
+ }
528
+ }
529
+
530
+ function resolveRetryDelay(delay: number | ((attempt: number) => number) | undefined, attempt: number): number {
531
+ if (typeof delay === 'function') return delay(attempt);
532
+ if (typeof delay === 'number') return delay;
533
+ return 0;
534
+ }
535
+
536
+ function randomId(): string {
537
+ const g = globalThis as any;
538
+ if (g.crypto && typeof g.crypto.randomUUID === 'function') {
539
+ return g.crypto.randomUUID();
540
+ }
541
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
542
+ }
@@ -0,0 +1,53 @@
1
+ import {SchedulerMetaInterface, SchedulerRegistrationInterface} from "../../types/index.ts";
2
+ import {METADATA_KEYS} from "../../framework/constants/index.ts";
3
+ import "reflect-metadata";
4
+
5
+ const registry = new Map<string, SchedulerRegistrationInterface>();
6
+
7
+ export function getSchedulerMetadata(target: any): SchedulerMetaInterface {
8
+ let metadata = Reflect.getMetadata(METADATA_KEYS.SCHEDULER, target);
9
+ if (!metadata) {
10
+ metadata = {
11
+ name: undefined,
12
+ queue: 'default',
13
+ timezone: undefined,
14
+ jobs: [],
15
+ };
16
+ Reflect.defineMetadata(METADATA_KEYS.SCHEDULER, metadata, target);
17
+ }
18
+ return metadata;
19
+ }
20
+
21
+ export function registerScheduler(construct: any): SchedulerRegistrationInterface {
22
+ const metadata: SchedulerMetaInterface = getSchedulerMetadata(construct.prototype || construct);
23
+ const name = metadata.name || construct.name;
24
+ const entry: SchedulerRegistrationInterface = {
25
+ name,
26
+ queue: metadata.queue || 'default',
27
+ construct,
28
+ metadata,
29
+ };
30
+ registry.set(name, entry);
31
+ return entry;
32
+ }
33
+
34
+ export function unregisterScheduler(constructOrName: string | any): boolean {
35
+ if (typeof constructOrName === 'string') {
36
+ return registry.delete(constructOrName);
37
+ }
38
+ const metadata = getSchedulerMetadata(constructOrName.prototype || constructOrName);
39
+ const name = metadata.name || constructOrName.name;
40
+ return registry.delete(name);
41
+ }
42
+
43
+ export function getSchedulerRegistry(): Map<string, SchedulerRegistrationInterface> {
44
+ return registry;
45
+ }
46
+
47
+ export function getScheduler(name: string): SchedulerRegistrationInterface | undefined {
48
+ return registry.get(name);
49
+ }
50
+
51
+ export function clearSchedulerRegistry(): void {
52
+ registry.clear();
53
+ }