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
@@ -4,9 +4,10 @@ import {LBadge, Logger} from "@protorians/logger";
4
4
  import {compileController} from "./compiler.ts";
5
5
  import {compileSocket} from "../socket/builder.ts";
6
6
  import {compileMcp} from "../mcp/builder.ts";
7
+ import {compileScheduler} from "../scheduler/builder.ts";
7
8
  import {RaitonThread} from "../thread.ts";
8
9
  import {Injection} from "../injection/index.ts";
9
- import {isControllerArtifact, isSocketArtifact, isMcpArtifact} from "../../framework/index.ts";
10
+ import {isControllerArtifact, isSocketArtifact, isMcpArtifact, isSchedulerArtifact} from "../../framework/index.ts";
10
11
  import {Artifacts} from "../../framework/artifacts.ts";
11
12
  import path from "node:path";
12
13
  import {ControllerRouteTracker} from "./tracker.ts";
@@ -51,8 +52,9 @@ export class ControllerBuilder {
51
52
  const isController = isControllerArtifact(filename);
52
53
  const isSocket = isSocketArtifact(filename);
53
54
  const isMcp = isMcpArtifact(filename);
55
+ const isScheduler = isSchedulerArtifact(filename);
54
56
 
55
- if (!isController && !isSocket && !isMcp)
57
+ if (!isController && !isSocket && !isMcp && !isScheduler)
56
58
  return undefined;
57
59
 
58
60
  const imported = await import(`${filename}?v=${version || 1}&t=${timestamp || Date.now()}`)
@@ -72,6 +74,10 @@ export class ControllerBuilder {
72
74
  return compileMcp(artifact) as any;
73
75
  }
74
76
 
77
+ if (isScheduler) {
78
+ return compileScheduler(artifact) as any;
79
+ }
80
+
75
81
  const compilated = compileController(artifact, RaitonThread.current.application);
76
82
  return compilated;
77
83
  }
@@ -11,6 +11,7 @@ export * from "./application.ts";
11
11
  export * from "./controller/index.ts";
12
12
  export * from "./socket/index.ts";
13
13
  export * from "./mcp/index.ts";
14
+ export * from "./scheduler/index.ts";
14
15
  export * from "./plugins/index.ts";
15
16
  export * from "./middleware/index.ts";
16
17
  export * from "./router/index.ts";
@@ -154,7 +154,10 @@ export class Injection {
154
154
  static get<T>(name: string, scope?: Symbol): T | undefined {
155
155
  const name_ = this.normalizeName(name);
156
156
  const cls = this._classes.get(name_);
157
- if (!cls) throw new Throwable(`Dependency ${name_} not registered`);
157
+ if (!cls) {
158
+ Logger.trace(`Dependency ${name_} not registered`, name);
159
+ throw new Throwable(`Dependency ${name_} not registered`);
160
+ }
158
161
 
159
162
  const effectiveScope = scope || cls.scope || this.defaultScope;
160
163
  if (this._resolutionStack.includes(name_)) {
@@ -0,0 +1,25 @@
1
+ import {getSchedulerMetadata, registerScheduler, unregisterScheduler} from "./metadata.ts";
2
+ import {Injection} from "../injection/index.ts";
3
+ import {SchedulerManager} from "./manager.ts";
4
+ import {SchedulerRegistrationInterface} from "../../types/index.ts";
5
+
6
+ export function compileScheduler(SchedulerClass: any): SchedulerRegistrationInterface | undefined {
7
+ const metadata = getSchedulerMetadata(SchedulerClass.prototype || SchedulerClass);
8
+ const name = metadata.name || SchedulerClass.name;
9
+
10
+ unregisterScheduler(name);
11
+ Injection.invalidateCascade(name);
12
+
13
+ const entry = registerScheduler(SchedulerClass);
14
+
15
+ let instance: any;
16
+ try {
17
+ instance = Injection.resolve(SchedulerClass);
18
+ } catch (e: any) {
19
+ instance = new SchedulerClass();
20
+ }
21
+
22
+ SchedulerManager.current.register(name, instance, metadata.jobs || []);
23
+
24
+ return entry;
25
+ }
@@ -0,0 +1,400 @@
1
+ /**
2
+ * Pure cron expression parser and next-run engine. No external dependency.
3
+ *
4
+ * Supports the classic 5-field (`minute hour day-of-month month day-of-week`)
5
+ * and extended 6-field (`second minute hour day-of-month month day-of-week`)
6
+ * formats, plus named values, lists, ranges, steps and the standard macros.
7
+ *
8
+ * Day-of-month / day-of-week follow Vixie-cron semantics: when both fields are
9
+ * restricted (not `*` / `?`), a day matches when *either* field matches.
10
+ */
11
+
12
+ export interface CronFieldRange {
13
+ min: number;
14
+ max: number;
15
+ }
16
+
17
+ export interface CronScheduleInterface {
18
+ readonly expression: string;
19
+ readonly timezone?: string;
20
+
21
+ next(from?: Date): Date | null;
22
+
23
+ nextN(count: number, from?: Date): Date[];
24
+
25
+ matches(date: Date): boolean;
26
+ }
27
+
28
+ interface TimeParts {
29
+ year: number;
30
+ month: number;
31
+ day: number;
32
+ hour: number;
33
+ minute: number;
34
+ second: number;
35
+ dayOfWeek: number;
36
+ }
37
+
38
+ interface Field {
39
+ allowed: boolean[];
40
+ wildcard: boolean;
41
+ values: number[];
42
+ }
43
+
44
+ interface ParsedFields {
45
+ seconds: Field;
46
+ minutes: Field;
47
+ hours: Field;
48
+ daysOfMonth: Field;
49
+ months: Field;
50
+ daysOfWeek: Field;
51
+ }
52
+
53
+ const MONTH_NAMES: Record<string, number> = {
54
+ JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6,
55
+ JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12,
56
+ };
57
+
58
+ const DOW_NAMES: Record<string, number> = {
59
+ SUN: 0, MON: 1, TUE: 2, WED: 3, THU: 4, FRI: 5, SAT: 6,
60
+ };
61
+
62
+ const MACROS: Record<string, string> = {
63
+ '@yearly': '0 0 1 1 *',
64
+ '@annually': '0 0 1 1 *',
65
+ '@monthly': '0 0 1 * *',
66
+ '@weekly': '0 0 * * 0',
67
+ '@daily': '0 0 * * *',
68
+ '@midnight': '0 0 * * *',
69
+ '@hourly': '0 * * * *',
70
+ '@minutely': '0 * * * * *',
71
+ '@secondly': '* * * * * *',
72
+ };
73
+
74
+ const MAX_ITERATIONS = 100_000;
75
+
76
+ export function parseCron(expression: string, timezone?: string): CronScheduleInterface {
77
+ return new CronSchedule(expression, timezone);
78
+ }
79
+
80
+ export class CronSchedule implements CronScheduleInterface {
81
+ readonly expression: string;
82
+ readonly timezone?: string;
83
+ private readonly fields: ParsedFields;
84
+
85
+ constructor(expression: string, timezone?: string) {
86
+ const normalized = (MACROS[expression.trim().toLowerCase()] || expression).trim();
87
+ this.expression = normalized;
88
+ this.timezone = timezone;
89
+ this.fields = this.parse(normalized);
90
+ }
91
+
92
+ next(from: Date = new Date()): Date | null {
93
+ const tz = this.timezone;
94
+ let p = zonedParts(from, tz);
95
+ p.second += 1;
96
+ if (p.second > 59) {
97
+ p.second = 0;
98
+ bumpMinute(p);
99
+ }
100
+
101
+ const f = this.fields;
102
+
103
+ for (let i = 0; i < MAX_ITERATIONS; i++) {
104
+ if (!f.months.allowed[p.month]) {
105
+ const next = nextAllowed(f.months.values, p.month);
106
+ if (next === null || next <= p.month) {
107
+ p.year += 1;
108
+ p.month = f.months.values[0];
109
+ } else {
110
+ p.month = next;
111
+ }
112
+ p.day = 1;
113
+ p.hour = 0;
114
+ p.minute = 0;
115
+ p.second = 0;
116
+ continue;
117
+ }
118
+
119
+ if (!dayMatches(p, f)) {
120
+ bumpDay(p);
121
+ p.hour = 0;
122
+ p.minute = 0;
123
+ p.second = 0;
124
+ continue;
125
+ }
126
+
127
+ if (!f.hours.allowed[p.hour]) {
128
+ const next = nextAllowed(f.hours.values, p.hour);
129
+ if (next === null || next <= p.hour) {
130
+ bumpDay(p);
131
+ p.hour = f.hours.values[0];
132
+ } else {
133
+ p.hour = next;
134
+ }
135
+ p.minute = 0;
136
+ p.second = 0;
137
+ continue;
138
+ }
139
+
140
+ if (!f.minutes.allowed[p.minute]) {
141
+ const next = nextAllowed(f.minutes.values, p.minute);
142
+ if (next === null || next <= p.minute) {
143
+ bumpHour(p);
144
+ p.minute = f.minutes.values[0];
145
+ } else {
146
+ p.minute = next;
147
+ }
148
+ p.second = 0;
149
+ continue;
150
+ }
151
+
152
+ if (!f.seconds.allowed[p.second]) {
153
+ const next = nextAllowed(f.seconds.values, p.second);
154
+ if (next === null || next <= p.second) {
155
+ bumpMinute(p);
156
+ p.second = f.seconds.values[0];
157
+ } else {
158
+ p.second = next;
159
+ }
160
+ continue;
161
+ }
162
+
163
+ return fromZoned(p, tz);
164
+ }
165
+
166
+ return null;
167
+ }
168
+
169
+ nextN(count: number, from: Date = new Date()): Date[] {
170
+ const results: Date[] = [];
171
+ let cursor = from;
172
+ for (let i = 0; i < count; i++) {
173
+ const next = this.next(cursor);
174
+ if (next === null) break;
175
+ results.push(next);
176
+ cursor = next;
177
+ }
178
+ return results;
179
+ }
180
+
181
+ matches(date: Date): boolean {
182
+ const p = zonedParts(date, this.timezone);
183
+ const f = this.fields;
184
+ return f.seconds.allowed[p.second]
185
+ && f.minutes.allowed[p.minute]
186
+ && f.hours.allowed[p.hour]
187
+ && f.months.allowed[p.month]
188
+ && dayMatches(p, f);
189
+ }
190
+
191
+ private parse(expression: string): ParsedFields {
192
+ const tokens = expression.trim().split(/\s+/);
193
+ if (tokens.length === 5) {
194
+ tokens.unshift('0');
195
+ }
196
+ if (tokens.length !== 6) {
197
+ throw new Error(`Invalid cron expression "${expression}": expected 5 or 6 fields.`);
198
+ }
199
+
200
+ const [second, minute, hour, dom, month, dow] = tokens;
201
+ return {
202
+ seconds: parseField(second, 0, 59),
203
+ minutes: parseField(minute, 0, 59),
204
+ hours: parseField(hour, 0, 23),
205
+ daysOfMonth: parseField(dom, 1, 31),
206
+ months: parseField(month, 1, 12, MONTH_NAMES),
207
+ daysOfWeek: parseField(dow, 0, 7, DOW_NAMES),
208
+ };
209
+ }
210
+ }
211
+
212
+ function parseField(token: string, min: number, max: number, names?: Record<string, number>): Field {
213
+ const allowed: boolean[] = new Array(max + 1).fill(false);
214
+ const valueSet = new Set<number>();
215
+ let wildcard = false;
216
+
217
+ const upper = token.toUpperCase();
218
+
219
+ for (const rawPart of upper.split(',')) {
220
+ const part = rawPart.trim();
221
+ if (part === '' ) continue;
222
+
223
+ if (part === '*' || part === '?') {
224
+ wildcard = true;
225
+ for (let v = min; v <= max; v++) valueSet.add(v);
226
+ continue;
227
+ }
228
+
229
+ let step = 1;
230
+ let body = part;
231
+ const slashIndex = part.indexOf('/');
232
+ if (slashIndex !== -1) {
233
+ body = part.slice(0, slashIndex);
234
+ step = parseInt(part.slice(slashIndex + 1), 10);
235
+ if (isNaN(step) || step <= 0) {
236
+ throw new Error(`Invalid step in cron field "${token}".`);
237
+ }
238
+ }
239
+
240
+ let lo = min;
241
+ let hi = max;
242
+
243
+ if (body === '*' || body === '?') {
244
+ lo = min;
245
+ hi = max;
246
+ } else {
247
+ const dashIndex = body.indexOf('-');
248
+ if (dashIndex !== -1) {
249
+ lo = resolveValue(body.slice(0, dashIndex), min, max, names);
250
+ hi = resolveValue(body.slice(dashIndex + 1), min, max, names);
251
+ } else {
252
+ lo = resolveValue(body, min, max, names);
253
+ hi = lo;
254
+ }
255
+ }
256
+
257
+ if (lo > hi) {
258
+ throw new Error(`Invalid range in cron field "${token}".`);
259
+ }
260
+
261
+ for (let v = lo; v <= hi; v += step) {
262
+ valueSet.add(v);
263
+ }
264
+ }
265
+
266
+ for (const v of valueSet) {
267
+ if (v >= min && v <= max) allowed[v] = true;
268
+ }
269
+
270
+ const values = Array.from(valueSet).filter(v => v >= min && v <= max).sort((a, b) => a - b);
271
+
272
+ return {allowed, wildcard, values};
273
+ }
274
+
275
+ function resolveValue(raw: string, min: number, max: number, names?: Record<string, number>): number {
276
+ const token = raw.trim().toUpperCase();
277
+ if (names && token in names) {
278
+ const v = names[token];
279
+ if (v < min || v > max) {
280
+ throw new Error(`Named value "${raw}" out of range.`);
281
+ }
282
+ return v;
283
+ }
284
+ const n = parseInt(token, 10);
285
+ if (isNaN(n) || n < min || n > max) {
286
+ throw new Error(`Cron field value "${raw}" out of range [${min}, ${max}].`);
287
+ }
288
+ return n;
289
+ }
290
+
291
+ function nextAllowed(values: number[], current: number): number | null {
292
+ for (const v of values) {
293
+ if (v > current) return v;
294
+ }
295
+ return null;
296
+ }
297
+
298
+ function dayMatches(p: TimeParts, f: ParsedFields): boolean {
299
+ const domMatch = f.daysOfMonth.allowed[p.day];
300
+ const dowMatch = f.daysOfWeek.allowed[p.dayOfWeek === 7 ? 0 : p.dayOfWeek];
301
+ const domRestricted = !f.daysOfMonth.wildcard;
302
+ const dowRestricted = !f.daysOfWeek.wildcard;
303
+
304
+ if (domRestricted && dowRestricted) return domMatch || dowMatch;
305
+ if (domRestricted) return domMatch;
306
+ if (dowRestricted) return dowMatch;
307
+ return true;
308
+ }
309
+
310
+ function daysInMonth(year: number, month: number): number {
311
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
312
+ }
313
+
314
+ function bumpDay(p: TimeParts): void {
315
+ p.day += 1;
316
+ if (p.day > daysInMonth(p.year, p.month)) {
317
+ p.day = 1;
318
+ p.month += 1;
319
+ if (p.month > 12) {
320
+ p.month = 1;
321
+ p.year += 1;
322
+ }
323
+ }
324
+ }
325
+
326
+ function bumpHour(p: TimeParts): void {
327
+ p.hour += 1;
328
+ if (p.hour > 23) {
329
+ p.hour = 0;
330
+ bumpDay(p);
331
+ }
332
+ }
333
+
334
+ function bumpMinute(p: TimeParts): void {
335
+ p.minute += 1;
336
+ if (p.minute > 59) {
337
+ p.minute = 0;
338
+ bumpHour(p);
339
+ }
340
+ }
341
+
342
+ function utcParts(date: Date): TimeParts {
343
+ return {
344
+ year: date.getUTCFullYear(),
345
+ month: date.getUTCMonth() + 1,
346
+ day: date.getUTCDate(),
347
+ hour: date.getUTCHours(),
348
+ minute: date.getUTCMinutes(),
349
+ second: date.getUTCSeconds(),
350
+ dayOfWeek: date.getUTCDay(),
351
+ };
352
+ }
353
+
354
+ function partsToDate(p: TimeParts): Date {
355
+ return new Date(Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second));
356
+ }
357
+
358
+ function zonedParts(date: Date, timezone?: string): TimeParts {
359
+ if (!timezone) return utcParts(date);
360
+ return utcParts(new Date(date.getTime() + timezoneOffsetMs(timezone, date)));
361
+ }
362
+
363
+ function fromZoned(p: TimeParts, timezone?: string): Date {
364
+ const date = partsToDate(p);
365
+ if (!timezone) return date;
366
+ return new Date(date.getTime() - timezoneOffsetMs(timezone, date));
367
+ }
368
+
369
+ function timezoneOffsetMs(timezone: string, date: Date): number {
370
+ const dtf = new Intl.DateTimeFormat('en-US', {
371
+ timeZone: timezone,
372
+ hour12: false,
373
+ year: 'numeric',
374
+ month: '2-digit',
375
+ day: '2-digit',
376
+ hour: '2-digit',
377
+ minute: '2-digit',
378
+ second: '2-digit',
379
+ });
380
+
381
+ const parts: Record<string, string> = {};
382
+ for (const p of dtf.formatToParts(date)) {
383
+ parts[p.type] = p.value;
384
+ }
385
+
386
+ let hour = parseInt(parts.hour, 10);
387
+ if (hour === 24) hour = 0;
388
+
389
+ const asUtc = Date.UTC(
390
+ parseInt(parts.year, 10),
391
+ parseInt(parts.month, 10) - 1,
392
+ parseInt(parts.day, 10),
393
+ hour,
394
+ parseInt(parts.minute, 10),
395
+ parseInt(parts.second, 10),
396
+ );
397
+
398
+ const utcMs = Math.floor(date.getTime() / 1000) * 1000;
399
+ return asUtc - utcMs;
400
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Parses human-readable durations into milliseconds.
3
+ *
4
+ * Accepts a bare number (already milliseconds) or a string made of one or more
5
+ * `<value><unit>` groups such as `"5s"`, `"1m30s"`, `"2 hours"` or `"500ms"`.
6
+ */
7
+
8
+ const UNITS: Record<string, number> = {
9
+ ms: 1, millisecond: 1, milliseconds: 1,
10
+ s: 1000, sec: 1000, secs: 1000, second: 1000, seconds: 1000,
11
+ m: 60_000, min: 60_000, mins: 60_000, minute: 60_000, minutes: 60_000,
12
+ h: 3_600_000, hr: 3_600_000, hrs: 3_600_000, hour: 3_600_000, hours: 3_600_000,
13
+ d: 86_400_000, day: 86_400_000, days: 86_400_000,
14
+ w: 604_800_000, week: 604_800_000, weeks: 604_800_000,
15
+ };
16
+
17
+ const GROUP = /(\d+(?:\.\d+)?)\s*(ms|milliseconds?|s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?|w|weeks?)/gi;
18
+
19
+ export function parseDuration(value: number | string): number {
20
+ if (typeof value === 'number') return Math.max(0, value);
21
+ if (typeof value !== 'string') return 0;
22
+
23
+ const trimmed = value.trim();
24
+ if (trimmed === '') return 0;
25
+ if (/^\d+(\.\d+)?$/.test(trimmed)) return Math.max(0, Number(trimmed));
26
+
27
+ let total = 0;
28
+ let matched = false;
29
+
30
+ for (const match of trimmed.matchAll(GROUP)) {
31
+ const amount = parseFloat(match[1]);
32
+ const unit = match[2].toLowerCase();
33
+ total += amount * UNITS[unit];
34
+ matched = true;
35
+ }
36
+
37
+ if (!matched) {
38
+ throw new Error(`Invalid duration "${value}".`);
39
+ }
40
+
41
+ return Math.max(0, Math.round(total));
42
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./cron.ts"
2
+ export * from "./duration.ts"
3
+ export * from "./metadata.ts"
4
+ export * from "./manager.ts"
5
+ export * from "./builder.ts"
6
+ export * from "./queue/index.ts"