raiton 6.7.0-beta.15 → 6.8.2-beta.18

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 +26 -0
  2. package/build/bin/index.mjs +1100 -34
  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 +4 -4
  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,142 @@
1
+ import type {QueueBackendInterface, QueueDequeueOptionsInterface, QueueMessageInterface} from "../../../types/index.ts";
2
+
3
+ export abstract class BaseQueueBackend implements QueueBackendInterface {
4
+ abstract readonly name: string;
5
+ protected connected = false;
6
+
7
+ get isConnected(): boolean {
8
+ return this.connected;
9
+ }
10
+
11
+ abstract connect(): Promise<void>;
12
+
13
+ abstract disconnect(): Promise<void>;
14
+
15
+ abstract enqueue(queue: string, message: QueueMessageInterface): Promise<string>;
16
+
17
+ abstract dequeue(queue: string, options?: QueueDequeueOptionsInterface): Promise<QueueMessageInterface[]>;
18
+
19
+ abstract acknowledge(queue: string, receipt: any): Promise<void>;
20
+
21
+ abstract reject(queue: string, receipt: any, requeue?: boolean): Promise<void>;
22
+
23
+ abstract length(queue: string): Promise<number>;
24
+
25
+ abstract purge(queue: string): Promise<void>;
26
+ }
27
+
28
+ export function wait(milliseconds: number): Promise<void> {
29
+ return new Promise(resolve => setTimeout(resolve, milliseconds));
30
+ }
31
+
32
+ interface MemoryEntry {
33
+ message: QueueMessageInterface;
34
+ receipt: MemoryReceipt;
35
+ availableAt: number;
36
+ locked: boolean;
37
+ }
38
+
39
+ interface MemoryReceipt {
40
+ queue: string;
41
+ id: string;
42
+ }
43
+
44
+ /**
45
+ * In-process queue backend used by default when no external broker is
46
+ * configured. Supports blocking dequeue, visibility timeout and ack/nack.
47
+ */
48
+ export class MemoryQueueBackend extends BaseQueueBackend {
49
+ readonly name = 'memory';
50
+ private readonly queues = new Map<string, MemoryEntry[]>();
51
+ private readonly visibilityMs: number;
52
+
53
+ constructor(options: {visibilityMs?: number} = {}) {
54
+ super();
55
+ this.visibilityMs = options.visibilityMs ?? 30_000;
56
+ }
57
+
58
+ async connect(): Promise<void> {
59
+ this.connected = true;
60
+ }
61
+
62
+ async disconnect(): Promise<void> {
63
+ this.connected = false;
64
+ }
65
+
66
+ async enqueue(queue: string, message: QueueMessageInterface): Promise<string> {
67
+ const entry: MemoryEntry = {
68
+ message,
69
+ receipt: {queue, id: message.id},
70
+ availableAt: message.availableAt ?? Date.now(),
71
+ locked: false,
72
+ };
73
+ this.list(queue).push(entry);
74
+ return message.id;
75
+ }
76
+
77
+ async dequeue(queue: string, options: QueueDequeueOptionsInterface = {}): Promise<QueueMessageInterface[]> {
78
+ const blockMs = options.blockMs ?? 0;
79
+ const count = options.count ?? 1;
80
+ const deadline = Date.now() + blockMs;
81
+
82
+ while (true) {
83
+ const messages = this.tryDequeue(queue, count);
84
+ if (messages.length > 0) return messages;
85
+ if (Date.now() >= deadline) return [];
86
+ await wait(Math.min(25, Math.max(0, deadline - Date.now())));
87
+ }
88
+ }
89
+
90
+ async acknowledge(_queue: string, receipt: MemoryReceipt): Promise<void> {
91
+ const list = this.list(receipt.queue);
92
+ const index = list.findIndex(e => e.receipt.id === receipt.id);
93
+ if (index !== -1) list.splice(index, 1);
94
+ }
95
+
96
+ async reject(queue: string, receipt: MemoryReceipt, requeue = true): Promise<void> {
97
+ const list = this.list(queue);
98
+ const index = list.findIndex(e => e.receipt.id === receipt.id);
99
+ if (index === -1) return;
100
+ const entry = list[index];
101
+ if (requeue) {
102
+ entry.locked = false;
103
+ entry.availableAt = Date.now();
104
+ entry.message.attempts += 1;
105
+ } else {
106
+ list.splice(index, 1);
107
+ }
108
+ }
109
+
110
+ async length(queue: string): Promise<number> {
111
+ return this.list(queue).length;
112
+ }
113
+
114
+ async purge(queue: string): Promise<void> {
115
+ this.list(queue).length = 0;
116
+ }
117
+
118
+ private list(queue: string): MemoryEntry[] {
119
+ let list = this.queues.get(queue);
120
+ if (!list) {
121
+ list = [];
122
+ this.queues.set(queue, list);
123
+ }
124
+ return list;
125
+ }
126
+
127
+ private tryDequeue(queue: string, count: number): QueueMessageInterface[] {
128
+ const now = Date.now();
129
+ const list = this.list(queue);
130
+ const result: QueueMessageInterface[] = [];
131
+
132
+ for (const entry of list) {
133
+ if (result.length >= count) break;
134
+ if (entry.locked || entry.availableAt > now) continue;
135
+ entry.locked = true;
136
+ entry.availableAt = now + this.visibilityMs;
137
+ result.push({...entry.message, receipt: entry.receipt});
138
+ }
139
+
140
+ return result;
141
+ }
142
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./backend.ts"
2
+ export * from "./redis.backend.ts"
3
+ export * from "./rabbitmq.backend.ts"
@@ -0,0 +1,124 @@
1
+ import {BaseQueueBackend, wait} from "./backend.ts";
2
+ import type {QueueDequeueOptionsInterface, QueueMessageInterface} from "../../../types/index.ts";
3
+
4
+ export interface RabbitMqQueueBackendOptions {
5
+ url?: string;
6
+ connection?: any;
7
+ channel?: any;
8
+ exchange?: string;
9
+ persistent?: boolean;
10
+ }
11
+
12
+ /**
13
+ * RabbitMQ-backed queue using a single AMQP channel (`sendToQueue` to publish,
14
+ * `get` + manual ack/nack to consume).
15
+ *
16
+ * The `amqplib` package is imported lazily so the framework never requires it
17
+ * unless this backend is actually used:
18
+ *
19
+ * ```ts
20
+ * import {SchedulerManager, RabbitMqQueueBackend} from 'raiton/core';
21
+ * SchedulerManager.current.registerBackend('default', new RabbitMqQueueBackend({url: 'amqp://localhost'}))
22
+ * ```
23
+ */
24
+ export class RabbitMqQueueBackend extends BaseQueueBackend {
25
+ readonly name = 'rabbitmq';
26
+ private connection: any;
27
+ private channel: any;
28
+ private readonly options: RabbitMqQueueBackendOptions;
29
+
30
+ constructor(options: RabbitMqQueueBackendOptions = {}) {
31
+ super();
32
+ this.options = options;
33
+ }
34
+
35
+ async connect(): Promise<void> {
36
+ if (this.connected) return;
37
+ if (this.options.channel) {
38
+ this.channel = this.options.channel;
39
+ } else if (this.options.connection) {
40
+ this.connection = this.options.connection;
41
+ this.channel = await this.connection.createChannel();
42
+ } else {
43
+ const amqp = await importAmqplib();
44
+ this.connection = await amqp.connect(this.options.url ?? 'amqp://localhost');
45
+ this.channel = await this.connection.createChannel();
46
+ }
47
+ this.connected = true;
48
+ }
49
+
50
+ async disconnect(): Promise<void> {
51
+ if (!this.connected) return;
52
+ if (typeof this.channel.close === 'function') await this.channel.close();
53
+ if (this.connection && typeof this.connection.close === 'function') await this.connection.close();
54
+ this.connected = false;
55
+ }
56
+
57
+ async enqueue(queue: string, message: QueueMessageInterface): Promise<string> {
58
+ await this.ensureConnected();
59
+ await this.channel.assertQueue(queue, {durable: true});
60
+ this.channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)), {
61
+ persistent: this.options.persistent ?? true,
62
+ });
63
+ return message.id;
64
+ }
65
+
66
+ async dequeue(queue: string, options: QueueDequeueOptionsInterface = {}): Promise<QueueMessageInterface[]> {
67
+ await this.ensureConnected();
68
+ await this.channel.assertQueue(queue, {durable: true});
69
+ const blockMs = options.blockMs ?? 0;
70
+ const count = options.count ?? 1;
71
+ const deadline = Date.now() + blockMs;
72
+ const results: QueueMessageInterface[] = [];
73
+
74
+ while (results.length < count) {
75
+ const message = await this.channel.get(queue, {noAck: false});
76
+ if (message) {
77
+ const parsed = JSON.parse(message.content.toString()) as QueueMessageInterface;
78
+ parsed.receipt = {channel: this.channel, tag: message.fields.deliveryTag};
79
+ results.push(parsed);
80
+ continue;
81
+ }
82
+ if (Date.now() >= deadline) break;
83
+ await wait(Math.min(25, Math.max(0, deadline - Date.now())));
84
+ }
85
+
86
+ return results;
87
+ }
88
+
89
+ async acknowledge(_queue: string, receipt: any): Promise<void> {
90
+ await this.ensureConnected();
91
+ receipt.channel.ack(receipt.tag);
92
+ }
93
+
94
+ async reject(_queue: string, receipt: any, requeue = true): Promise<void> {
95
+ await this.ensureConnected();
96
+ receipt.channel.nack(receipt.tag, false, requeue);
97
+ }
98
+
99
+ async length(queue: string): Promise<number> {
100
+ await this.ensureConnected();
101
+ const info = await this.channel.checkQueue(queue);
102
+ return info.messageCount;
103
+ }
104
+
105
+ async purge(queue: string): Promise<void> {
106
+ await this.ensureConnected();
107
+ await this.channel.purgeQueue(queue);
108
+ }
109
+
110
+ private async ensureConnected(): Promise<void> {
111
+ if (!this.connected) await this.connect();
112
+ }
113
+ }
114
+
115
+ async function importAmqplib(): Promise<any> {
116
+ try {
117
+ // @ts-ignore - optional peer dependency, imported lazily
118
+ return await import('amqplib');
119
+ } catch (e: any) {
120
+ throw new Error(
121
+ 'RabbitMqQueueBackend requires the "amqplib" package. Install it with `bun add amqplib` or `npm install amqplib`.',
122
+ );
123
+ }
124
+ }
@@ -0,0 +1,144 @@
1
+ import {BaseQueueBackend, wait} from "./backend.ts";
2
+ import type {QueueDequeueOptionsInterface, QueueMessageInterface} from "../../../types/index.ts";
3
+
4
+ export interface RedisQueueBackendOptions {
5
+ url?: string;
6
+ client?: any;
7
+ prefix?: string;
8
+ [key: string]: any;
9
+ }
10
+
11
+ /**
12
+ * Redis-backed queue using a reliable list pattern (enqueue with `RPUSH`,
13
+ * dequeue atomically with `LMOVE` to a processing list, ack with `LREM`).
14
+ *
15
+ * The `redis` package is imported lazily so the framework never requires it
16
+ * unless this backend is actually used:
17
+ *
18
+ * ```ts
19
+ * import {SchedulerManager, RedisQueueBackend} from 'raiton/core';
20
+ * SchedulerManager.current.registerBackend('default', new RedisQueueBackend({url: 'redis://localhost:6379'}))
21
+ * ```
22
+ */
23
+ export class RedisQueueBackend extends BaseQueueBackend {
24
+ readonly name = 'redis';
25
+ private client: any;
26
+ private readonly options: RedisQueueBackendOptions;
27
+ private readonly prefix: string;
28
+
29
+ constructor(options: RedisQueueBackendOptions = {}) {
30
+ super();
31
+ this.options = options;
32
+ this.prefix = options.prefix ?? 'raiton:queue:';
33
+ }
34
+
35
+ async connect(): Promise<void> {
36
+ if (this.connected) return;
37
+ if (this.options.client) {
38
+ this.client = this.options.client;
39
+ } else {
40
+ const redis = await importRedis();
41
+ this.client = redis.createClient({url: this.options.url, ...this.options});
42
+ this.client.on?.('error', (err: any) => {
43
+ // Keep the process alive on transient redis errors.
44
+ });
45
+ }
46
+ if (typeof this.client.connect === 'function' && !this.client.isOpen) {
47
+ await this.client.connect();
48
+ }
49
+ this.connected = true;
50
+ }
51
+
52
+ async disconnect(): Promise<void> {
53
+ if (!this.connected) return;
54
+ if (typeof this.client.disconnect === 'function') {
55
+ await this.client.disconnect();
56
+ } else if (typeof this.client.quit === 'function') {
57
+ await this.client.quit();
58
+ }
59
+ this.connected = false;
60
+ }
61
+
62
+ async enqueue(queue: string, message: QueueMessageInterface): Promise<string> {
63
+ await this.ensureConnected();
64
+ const raw = JSON.stringify(message);
65
+ await this.client.rPush(this.key(queue), raw);
66
+ return message.id;
67
+ }
68
+
69
+ async dequeue(queue: string, options: QueueDequeueOptionsInterface = {}): Promise<QueueMessageInterface[]> {
70
+ await this.ensureConnected();
71
+ const blockMs = options.blockMs ?? 0;
72
+ const count = options.count ?? 1;
73
+ const deadline = Date.now() + blockMs;
74
+ const results: QueueMessageInterface[] = [];
75
+
76
+ while (results.length < count) {
77
+ const raw = await this.client.lMove(
78
+ this.key(queue),
79
+ this.processingKey(queue),
80
+ 'RIGHT',
81
+ 'LEFT',
82
+ );
83
+
84
+ if (raw !== null && raw !== undefined) {
85
+ const message = JSON.parse(raw) as QueueMessageInterface;
86
+ message.receipt = raw;
87
+ results.push(message);
88
+ continue;
89
+ }
90
+
91
+ if (Date.now() >= deadline) break;
92
+ await wait(Math.min(25, Math.max(0, deadline - Date.now())));
93
+ }
94
+
95
+ return results;
96
+ }
97
+
98
+ async acknowledge(queue: string, receipt: any): Promise<void> {
99
+ await this.ensureConnected();
100
+ await this.client.lRem(this.processingKey(queue), 1, receipt);
101
+ }
102
+
103
+ async reject(queue: string, receipt: any, requeue = true): Promise<void> {
104
+ await this.ensureConnected();
105
+ if (requeue) {
106
+ await this.client.rPush(this.key(queue), receipt);
107
+ }
108
+ await this.client.lRem(this.processingKey(queue), 1, receipt);
109
+ }
110
+
111
+ async length(queue: string): Promise<number> {
112
+ await this.ensureConnected();
113
+ return Number(await this.client.lLen(this.key(queue)));
114
+ }
115
+
116
+ async purge(queue: string): Promise<void> {
117
+ await this.ensureConnected();
118
+ await this.client.del(this.key(queue));
119
+ await this.client.del(this.processingKey(queue));
120
+ }
121
+
122
+ private key(queue: string): string {
123
+ return `${this.prefix}${queue}`;
124
+ }
125
+
126
+ private processingKey(queue: string): string {
127
+ return `${this.prefix}${queue}:processing`;
128
+ }
129
+
130
+ private async ensureConnected(): Promise<void> {
131
+ if (!this.connected) await this.connect();
132
+ }
133
+ }
134
+
135
+ async function importRedis(): Promise<any> {
136
+ try {
137
+ // @ts-ignore - optional peer dependency, imported lazily
138
+ return await import('redis');
139
+ } catch (e: any) {
140
+ throw new Error(
141
+ 'RedisQueueBackend requires the "redis" package. Install it with `bun add redis` or `npm install redis`.',
142
+ );
143
+ }
144
+ }
@@ -16,6 +16,7 @@ import {Runtime} from "../framework/runtime/index.ts";
16
16
  import {LBadge, Logger} from "@protorians/logger";
17
17
  import {ControllerBuilder} from "./controller/index.ts";
18
18
  import {registerDefaultHealthCheck} from "../framework/health-check.ts";
19
+ import {SchedulerManager} from "./scheduler/index.ts";
19
20
  import {bodyParserPlugin} from "../framework/plugins/body-parser.plugin.ts";
20
21
  import {Injection} from "./injection/injection.ts";
21
22
  import {Throwable} from "../framework/exceptions/index.ts";
@@ -61,6 +62,7 @@ export class RaitonThread implements ThreadInterface {
61
62
  }
62
63
 
63
64
  public async stop(): Promise<void> {
65
+ await SchedulerManager.current.stop();
64
66
  await Injection.shutdown();
65
67
  if (isDenoUsed) {
66
68
  (globalThis as any).Deno.exit(0)
@@ -115,6 +117,8 @@ export class RaitonThread implements ThreadInterface {
115
117
  registerDefaultHealthCheck(this.application)
116
118
  }
117
119
 
120
+ await SchedulerManager.current.start();
121
+
118
122
  if (this._options.serve) {
119
123
  if (isDenoUsed) {
120
124
  const addSignalListener = (globalThis as any).Deno.addSignalListener;
@@ -4,6 +4,7 @@ import type {ConstructorType} from "../types/index.ts";
4
4
  import {Raiton} from "../core/raiton.ts";
5
5
  import {isArtifact} from "./utilities/index.ts";
6
6
  import {compileMcp} from "../core/mcp/builder.ts";
7
+ import {compileScheduler} from "../core/scheduler/builder.ts";
7
8
 
8
9
  export type HmrChannel =
9
10
  | 'hmr:di'
@@ -13,6 +14,7 @@ export type HmrChannel =
13
14
  | 'hmr:hook'
14
15
  | 'hmr:mcp'
15
16
  | 'hmr:health-check'
17
+ | 'hmr:scheduler'
16
18
 
17
19
  export interface ArtifactClassification {
18
20
  channel: HmrChannel
@@ -48,6 +50,7 @@ export const HMR_CHANNELS: Record<HmrChannel, readonly string[]> = {
48
50
  'hmr:hook': ['hook', 'event', 'listener'],
49
51
  'hmr:mcp': ['mcp'],
50
52
  'hmr:health-check': ['health-check'],
53
+ 'hmr:scheduler': ['scheduler', 'task', 'cron', 'job'],
51
54
  }
52
55
 
53
56
  export class Artifacts {
@@ -84,6 +87,10 @@ export class Artifacts {
84
87
  'socket',
85
88
  'mcp',
86
89
  'health-check',
90
+ 'scheduler',
91
+ 'task',
92
+ 'cron',
93
+ 'job',
87
94
  ]
88
95
 
89
96
  static register(type: string) {
@@ -237,4 +244,24 @@ export class Artifacts {
237
244
  }
238
245
  }
239
246
  }
247
+
248
+ static reloadScheduler(modulo: any, filename?: string) {
249
+
250
+ if (Raiton.thread?.builder.options.serve === false)
251
+ return Logger.warn(
252
+ 'Artifact reload is only available in development mode'
253
+ )
254
+
255
+ for (const mod of Object.values(modulo)) {
256
+ const name = (mod && typeof mod === 'object' && 'name' in mod) ? mod.name : (
257
+ typeof mod === 'function' ? mod.name ?? mod.constructor.name : undefined
258
+ );
259
+
260
+ if (typeof name === 'string' && typeof mod === 'function') {
261
+ Injection.invalidateCascade(name)
262
+ if (filename) Injection.registerArtifactPath(name, filename)
263
+ compileScheduler(mod)
264
+ }
265
+ }
266
+ }
240
267
  }
@@ -26,4 +26,6 @@ export const METADATA_KEYS = {
26
26
  MCP: Symbol('mcp:meta'),
27
27
  MCP_ELEMENTS: Symbol('mcp:elements'),
28
28
  MCP_ARGUMENTS: Symbol('mcp:arguments'),
29
+ // Scheduler metadata keys
30
+ SCHEDULER: Symbol('scheduler:meta'),
29
31
  }
@@ -11,4 +11,5 @@ export * from "./api-response.decorator.ts"
11
11
  export * from "./api.decorator.ts"
12
12
  export * from "./route-interaction.decorator.ts"
13
13
  export * from "./health-check.decorator.ts"
14
- export * from "./mcp.decorator.ts"
14
+ export * from "./mcp.decorator.ts"
15
+ export * from "./scheduler.decorator.ts"
@@ -0,0 +1,139 @@
1
+ import "reflect-metadata";
2
+ import {getSchedulerMetadata, registerScheduler, unregisterScheduler} from "../../core/scheduler/index.ts";
3
+ import {Injectable} from "./index.ts";
4
+ import {LifetimeEnum} from "@protorians/core";
5
+ import {parseDuration} from "../../core/scheduler/duration.ts";
6
+ import {TaskTriggerEnum} from "../enums/index.ts";
7
+ import type {
8
+ CronOptionsInterface,
9
+ IntervalOptionsInterface,
10
+ JobMetaInterface,
11
+ SchedulerOptionsInterface,
12
+ TaskDeclarationInterface,
13
+ TimeoutOptionsInterface,
14
+ } from "../../types/index.ts";
15
+
16
+ /**
17
+ * Marks a class as a scheduler: a container for scheduled jobs
18
+ * ({@link Cron}, {@link Every}, {@link Timeout}) and named tasks
19
+ * ({@link Task}).
20
+ *
21
+ * @example
22
+ * ```ts
23
+ * @Scheduler({ name: 'maintenance', queue: 'default' })
24
+ * class MaintenanceScheduler {
25
+ * @Cron('0 0 * * *', { name: 'daily-cleanup' })
26
+ * async cleanup(ctx: TaskContextInterface) { ... }
27
+ *
28
+ * @Every('5m', { name: 'heartbeat' })
29
+ * async heartbeat() { ... }
30
+ *
31
+ * @Task('send-email', { consume: true, queue: 'emails' })
32
+ * async sendEmail(ctx: TaskContextInterface<Email>) { ... }
33
+ * }
34
+ * ```
35
+ */
36
+ export function Scheduler(options: SchedulerOptionsInterface = {}) {
37
+ return (target: any) => {
38
+ const name = options.name || target.name;
39
+ Injectable(LifetimeEnum.TRANSIENT, name)(target);
40
+
41
+ const meta = getSchedulerMetadata(target.prototype || target);
42
+ meta.name = name;
43
+ meta.queue = options.queue || 'default';
44
+ meta.timezone = options.timezone;
45
+
46
+ unregisterScheduler(name);
47
+ registerScheduler(target);
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Schedule a method using a cron expression (5 or 6 fields).
53
+ */
54
+ export function Cron(expression: string, options: CronOptionsInterface = {}) {
55
+ return (target: any, propertyKey: string) => {
56
+ const meta = getSchedulerMetadata(target);
57
+ const job: JobMetaInterface = {
58
+ propertyKey,
59
+ name: options.name || `${meta.name}:${propertyKey}`,
60
+ type: TaskTriggerEnum.Cron,
61
+ cron: expression,
62
+ queue: options.queue,
63
+ options,
64
+ };
65
+ meta.jobs.push(job);
66
+ };
67
+ }
68
+
69
+ /**
70
+ * Schedule a method at a fixed interval. `interval` is a number of
71
+ * milliseconds or a human-readable duration such as `"5s"` or `"1h"`.
72
+ */
73
+ export function Every(interval: number | string, options: IntervalOptionsInterface = {}) {
74
+ return (target: any, propertyKey: string) => {
75
+ const meta = getSchedulerMetadata(target);
76
+ const job: JobMetaInterface = {
77
+ propertyKey,
78
+ name: options.name || `${meta.name}:${propertyKey}`,
79
+ type: TaskTriggerEnum.Interval,
80
+ interval: parseDuration(interval),
81
+ queue: options.queue,
82
+ options,
83
+ };
84
+ meta.jobs.push(job);
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Schedule a one-shot method after a delay. `delay` is a number of
90
+ * milliseconds or a human-readable duration such as `"30s"`.
91
+ */
92
+ export function Timeout(delay: number | string, options: TimeoutOptionsInterface = {}) {
93
+ return (target: any, propertyKey: string) => {
94
+ const meta = getSchedulerMetadata(target);
95
+ const job: JobMetaInterface = {
96
+ propertyKey,
97
+ name: options.name || `${meta.name}:${propertyKey}`,
98
+ type: TaskTriggerEnum.Timeout,
99
+ delay: parseDuration(delay),
100
+ queue: options.queue,
101
+ options,
102
+ };
103
+ meta.jobs.push(job);
104
+ };
105
+ }
106
+
107
+ /**
108
+ * Register a named task. Tasks are dispatachable in-process
109
+ * (`SchedulerManager.current.dispatch(name, payload)`), enqueueable on a
110
+ * queue backend (`SchedulerManager.current.enqueue(name, payload)`) and,
111
+ * when `options.consume` is `true`, consumed from the queue as a worker.
112
+ *
113
+ * @example
114
+ * ```ts
115
+ * @Scheduler()
116
+ * class Jobs {
117
+ * @Task('email:welcome', { queue: 'emails', consume: true, retries: 3 })
118
+ * async welcome(ctx: TaskContextInterface) { ... }
119
+ * }
120
+ * ```
121
+ */
122
+ export function Task(name: string, options: TaskDeclarationInterface = {}) {
123
+ return (target: any, propertyKey: string) => {
124
+ const meta = getSchedulerMetadata(target);
125
+ const job: JobMetaInterface = {
126
+ propertyKey,
127
+ name,
128
+ type: TaskTriggerEnum.Task,
129
+ queue: options.queue,
130
+ options: {
131
+ ...options,
132
+ name,
133
+ },
134
+ };
135
+ meta.jobs.push(job);
136
+ };
137
+ }
138
+
139
+ export {Every as Interval};
@@ -5,4 +5,5 @@ export * from "./encrypted.enum.ts"
5
5
  export * from "./event.message.enum.ts"
6
6
  export * from "./timestamp.enum.ts"
7
7
  export * from "./runtime.enum.ts"
8
- export * from "./csrf.enum.ts"
8
+ export * from "./csrf.enum.ts"
9
+ export * from "./scheduler.enum.ts"
@@ -0,0 +1,23 @@
1
+ export enum TaskTriggerEnum {
2
+ Cron = 'cron',
3
+ Interval = 'interval',
4
+ Timeout = 'timeout',
5
+ Task = 'task',
6
+ }
7
+
8
+ export enum TaskStatusEnum {
9
+ Pending = 'pending',
10
+ Running = 'running',
11
+ Completed = 'completed',
12
+ Failed = 'failed',
13
+ Cancelled = 'cancelled',
14
+ TimedOut = 'timed-out',
15
+ }
16
+
17
+ export enum TaskPriorityEnum {
18
+ Lowest = 'lowest',
19
+ Low = 'low',
20
+ Normal = 'normal',
21
+ High = 'high',
22
+ Highest = 'highest',
23
+ }