oqronkit 0.0.1-alpha.1

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 (109) hide show
  1. package/README.md +127 -0
  2. package/dist/chunk-I6QFT3MR.mjs +1732 -0
  3. package/dist/chunk-PLN5A6LU.mjs +1447 -0
  4. package/dist/core/config/config-loader.d.ts +3 -0
  5. package/dist/core/config/config-loader.d.ts.map +1 -0
  6. package/dist/core/config/default-config.d.ts +4 -0
  7. package/dist/core/config/default-config.d.ts.map +1 -0
  8. package/dist/core/config/define-config.d.ts +3 -0
  9. package/dist/core/config/define-config.d.ts.map +1 -0
  10. package/dist/core/config/find-up.d.ts +2 -0
  11. package/dist/core/config/find-up.d.ts.map +1 -0
  12. package/dist/core/config/schema.d.ts +306 -0
  13. package/dist/core/config/schema.d.ts.map +1 -0
  14. package/dist/core/context/cron-context.d.ts +14 -0
  15. package/dist/core/context/cron-context.d.ts.map +1 -0
  16. package/dist/core/context/cron-context.interface.d.ts +14 -0
  17. package/dist/core/context/cron-context.interface.d.ts.map +1 -0
  18. package/dist/core/context/job-context.d.ts +22 -0
  19. package/dist/core/context/job-context.d.ts.map +1 -0
  20. package/dist/core/context/schedule-context.d.ts +31 -0
  21. package/dist/core/context/schedule-context.d.ts.map +1 -0
  22. package/dist/core/errors/base.error.d.ts +13 -0
  23. package/dist/core/errors/base.error.d.ts.map +1 -0
  24. package/dist/core/events/event-bus.d.ts +16 -0
  25. package/dist/core/events/event-bus.d.ts.map +1 -0
  26. package/dist/core/index.d.ts +24 -0
  27. package/dist/core/index.d.ts.map +1 -0
  28. package/dist/core/logger/index.d.ts +30 -0
  29. package/dist/core/logger/index.d.ts.map +1 -0
  30. package/dist/core/registry.d.ts +13 -0
  31. package/dist/core/registry.d.ts.map +1 -0
  32. package/dist/core/types/config.types.d.ts +119 -0
  33. package/dist/core/types/config.types.d.ts.map +1 -0
  34. package/dist/core/types/cron.types.d.ts +53 -0
  35. package/dist/core/types/cron.types.d.ts.map +1 -0
  36. package/dist/core/types/db.types.d.ts +32 -0
  37. package/dist/core/types/db.types.d.ts.map +1 -0
  38. package/dist/core/types/index.d.ts +7 -0
  39. package/dist/core/types/index.d.ts.map +1 -0
  40. package/dist/core/types/lock.types.d.ts +7 -0
  41. package/dist/core/types/lock.types.d.ts.map +1 -0
  42. package/dist/core/types/module.types.d.ts +8 -0
  43. package/dist/core/types/module.types.d.ts.map +1 -0
  44. package/dist/core/types/scheduler.types.d.ts +62 -0
  45. package/dist/core/types/scheduler.types.d.ts.map +1 -0
  46. package/dist/cron-V0k1GcxJ.d.mts +102 -0
  47. package/dist/cron-V0k1GcxJ.d.ts +102 -0
  48. package/dist/cron.d.mts +2 -0
  49. package/dist/cron.d.ts +2 -0
  50. package/dist/cron.d.ts.map +1 -0
  51. package/dist/cron.js +215 -0
  52. package/dist/cron.mjs +1 -0
  53. package/dist/db/adapters/memory.adapter.d.ts +25 -0
  54. package/dist/db/adapters/memory.adapter.d.ts.map +1 -0
  55. package/dist/db/adapters/namespaced.adapter.d.ts +26 -0
  56. package/dist/db/adapters/namespaced.adapter.d.ts.map +1 -0
  57. package/dist/db/adapters/sqlite.adapter.d.ts +30 -0
  58. package/dist/db/adapters/sqlite.adapter.d.ts.map +1 -0
  59. package/dist/db/index.d.ts +4 -0
  60. package/dist/db/index.d.ts.map +1 -0
  61. package/dist/index.d.mts +797 -0
  62. package/dist/index.d.ts +32 -0
  63. package/dist/index.d.ts.map +1 -0
  64. package/dist/index.js +2738 -0
  65. package/dist/index.mjs +747 -0
  66. package/dist/lock/adapters/db-lock.adapter.d.ts +17 -0
  67. package/dist/lock/adapters/db-lock.adapter.d.ts.map +1 -0
  68. package/dist/lock/adapters/memory-lock.adapter.d.ts +13 -0
  69. package/dist/lock/adapters/memory-lock.adapter.d.ts.map +1 -0
  70. package/dist/lock/adapters/namespaced-lock.adapter.d.ts +12 -0
  71. package/dist/lock/adapters/namespaced-lock.adapter.d.ts.map +1 -0
  72. package/dist/lock/heartbeat-worker.d.ts +16 -0
  73. package/dist/lock/heartbeat-worker.d.ts.map +1 -0
  74. package/dist/lock/index.d.ts +7 -0
  75. package/dist/lock/index.d.ts.map +1 -0
  76. package/dist/lock/leader-election.d.ts +16 -0
  77. package/dist/lock/leader-election.d.ts.map +1 -0
  78. package/dist/lock/stall-detector.d.ts +23 -0
  79. package/dist/lock/stall-detector.d.ts.map +1 -0
  80. package/dist/scheduler/cron-engine.d.ts +42 -0
  81. package/dist/scheduler/cron-engine.d.ts.map +1 -0
  82. package/dist/scheduler/define-cron.d.ts +36 -0
  83. package/dist/scheduler/define-cron.d.ts.map +1 -0
  84. package/dist/scheduler/define-schedule.d.ts +52 -0
  85. package/dist/scheduler/define-schedule.d.ts.map +1 -0
  86. package/dist/scheduler/expression-parser.d.ts +2 -0
  87. package/dist/scheduler/expression-parser.d.ts.map +1 -0
  88. package/dist/scheduler/index.d.ts +10 -0
  89. package/dist/scheduler/index.d.ts.map +1 -0
  90. package/dist/scheduler/missed-fire.handler.d.ts +8 -0
  91. package/dist/scheduler/missed-fire.handler.d.ts.map +1 -0
  92. package/dist/scheduler/registry-schedule.d.ts +6 -0
  93. package/dist/scheduler/registry-schedule.d.ts.map +1 -0
  94. package/dist/scheduler/registry.d.ts +6 -0
  95. package/dist/scheduler/registry.d.ts.map +1 -0
  96. package/dist/scheduler/schedule-engine.d.ts +36 -0
  97. package/dist/scheduler/schedule-engine.d.ts.map +1 -0
  98. package/dist/scheduler-HRR3UXGE.mjs +1 -0
  99. package/dist/scheduler.d.mts +248 -0
  100. package/dist/scheduler.d.ts +248 -0
  101. package/dist/scheduler.js +1461 -0
  102. package/dist/scheduler.mjs +1 -0
  103. package/dist/server/express.d.ts +9 -0
  104. package/dist/server/express.d.ts.map +1 -0
  105. package/dist/server/fastify.d.ts +9 -0
  106. package/dist/server/fastify.d.ts.map +1 -0
  107. package/dist/server/handlers.d.ts +15 -0
  108. package/dist/server/handlers.d.ts.map +1 -0
  109. package/package.json +59 -0
@@ -0,0 +1,1732 @@
1
+ import { randomUUID } from 'crypto';
2
+ import { pathToFileURL } from 'url';
3
+ import { findUp } from 'find-up';
4
+ import { z } from 'zod';
5
+ import { EventEmitter } from 'eventemitter3';
6
+ import { redactionMiddleware, prettyTransport, consoleTransport, createLogger as createLogger$1 } from 'voltlog-io';
7
+ import Database from 'better-sqlite3';
8
+ import _cronParser from 'cron-parser';
9
+ import { rrulestr, RRule } from 'rrule';
10
+
11
+ // src/scheduler/cron-engine.ts
12
+
13
+ // src/core/config/default-config.ts
14
+ var defaultConfig = {
15
+ project: "oqronkit",
16
+ environment: "development",
17
+ db: {
18
+ adapter: "memory",
19
+ poolMin: 2,
20
+ poolMax: 10,
21
+ tablePrefix: "chrono_",
22
+ migrations: "auto",
23
+ ssl: false
24
+ },
25
+ lock: {
26
+ adapter: "memory",
27
+ ttl: 3e4,
28
+ retryDelay: 200,
29
+ retryCount: 5
30
+ },
31
+ modules: [],
32
+ cron: {
33
+ enable: true,
34
+ timezone: "UTC",
35
+ tickInterval: 1e3,
36
+ missedFirePolicy: "run-once",
37
+ maxConcurrentJobs: 5,
38
+ leaderElection: true,
39
+ keepJobHistory: true,
40
+ keepFailedJobHistory: true
41
+ },
42
+ scheduler: {
43
+ enable: true,
44
+ tickInterval: 1e3,
45
+ keepJobHistory: true,
46
+ keepFailedJobHistory: true
47
+ },
48
+ jobsDir: "./src/jobs",
49
+ tags: [],
50
+ worker: {
51
+ concurrency: 50,
52
+ gracefulShutdownMs: 3e4
53
+ },
54
+ logger: {
55
+ enabled: true,
56
+ level: "info",
57
+ prettify: false,
58
+ showMetadata: true,
59
+ redact: []
60
+ },
61
+ telemetry: {
62
+ prometheus: {
63
+ enabled: false,
64
+ path: "/metrics"
65
+ },
66
+ opentelemetry: {
67
+ enabled: false
68
+ }
69
+ },
70
+ shutdown: {
71
+ enabled: true,
72
+ timeout: 3e4,
73
+ signals: ["SIGINT", "SIGTERM"]
74
+ }
75
+ };
76
+ function reconfigureConfig(config) {
77
+ const isIOqronAdapter2 = (val) => val && typeof val === "object" && typeof val.upsertSchedule === "function";
78
+ const isILockAdapter2 = (val) => val && typeof val === "object" && typeof val.acquire === "function";
79
+ return {
80
+ project: config.project ?? defaultConfig.project,
81
+ environment: config.environment ?? defaultConfig.environment,
82
+ db: config.db ? isIOqronAdapter2(config.db) ? config.db : { ...defaultConfig.db, ...config.db } : defaultConfig.db,
83
+ lock: config.lock ? isILockAdapter2(config.lock) ? config.lock : { ...defaultConfig.lock, ...config.lock } : defaultConfig.lock,
84
+ broker: config.broker,
85
+ modules: config.modules ?? defaultConfig.modules,
86
+ cron: {
87
+ ...defaultConfig.cron,
88
+ ...config.cron
89
+ },
90
+ scheduler: {
91
+ ...defaultConfig.scheduler,
92
+ ...config.scheduler
93
+ },
94
+ jobsDir: config.jobsDir ?? defaultConfig.jobsDir,
95
+ tags: config.tags ?? defaultConfig.tags,
96
+ worker: {
97
+ ...defaultConfig.worker,
98
+ ...config.worker
99
+ },
100
+ logger: config.logger === false ? false : {
101
+ ...defaultConfig.logger,
102
+ ...config.logger
103
+ },
104
+ telemetry: {
105
+ prometheus: {
106
+ ...defaultConfig.telemetry.prometheus,
107
+ ...config.telemetry?.prometheus
108
+ },
109
+ opentelemetry: {
110
+ ...defaultConfig.telemetry.opentelemetry,
111
+ ...config.telemetry?.opentelemetry
112
+ }
113
+ },
114
+ shutdown: {
115
+ ...defaultConfig.shutdown,
116
+ ...config.shutdown
117
+ }
118
+ };
119
+ }
120
+ var isIOqronAdapter = (val) => {
121
+ if (!val || typeof val !== "object") return false;
122
+ return typeof val.upsertSchedule === "function" && typeof val.getDueSchedules === "function";
123
+ };
124
+ var isILockAdapter = (val) => {
125
+ if (!val || typeof val !== "object") return false;
126
+ return typeof val.acquire === "function" && typeof val.renew === "function";
127
+ };
128
+ var OqronConfigSchema = z.object({
129
+ project: z.string().optional(),
130
+ environment: z.string().default("development"),
131
+ // Infrastructure — Union of explicit DI or declarative config
132
+ db: z.union([
133
+ z.custom(
134
+ isIOqronAdapter,
135
+ "db must be an instance of IOqronAdapter"
136
+ ),
137
+ z.object({
138
+ adapter: z.enum([
139
+ "sqlite",
140
+ "memory",
141
+ "postgres",
142
+ "mysql",
143
+ "mongodb",
144
+ "redis"
145
+ ]),
146
+ url: z.string().optional(),
147
+ poolMin: z.number().default(2),
148
+ poolMax: z.number().default(10),
149
+ tablePrefix: z.string().default("chrono_"),
150
+ migrations: z.union([z.enum(["auto", "manual"]), z.literal(false)]).default("auto"),
151
+ ssl: z.boolean().default(false)
152
+ })
153
+ ]).optional(),
154
+ lock: z.union([
155
+ z.custom(
156
+ isILockAdapter,
157
+ "lock must be an instance of ILockAdapter"
158
+ ),
159
+ z.object({
160
+ adapter: z.enum(["db", "memory", "redis"]),
161
+ url: z.string().optional(),
162
+ ttl: z.number().default(3e4),
163
+ retryDelay: z.number().default(200),
164
+ retryCount: z.number().default(5)
165
+ })
166
+ ]).optional(),
167
+ broker: z.any().optional(),
168
+ // Modules
169
+ modules: z.array(
170
+ z.enum([
171
+ "cron",
172
+ "scheduler",
173
+ "queue",
174
+ "workflow",
175
+ "batch",
176
+ "webhook",
177
+ "pipeline"
178
+ ])
179
+ ).default([]),
180
+ // Module-specific configs
181
+ cron: z.object({
182
+ enable: z.boolean().default(true),
183
+ timezone: z.string().optional(),
184
+ tickInterval: z.number().default(1e3),
185
+ missedFirePolicy: z.enum(["skip", "run-once", "run-all"]).default("run-once"),
186
+ maxConcurrentJobs: z.number().default(5),
187
+ leaderElection: z.boolean().default(true),
188
+ keepJobHistory: z.union([z.boolean(), z.number()]).default(true),
189
+ keepFailedJobHistory: z.union([z.boolean(), z.number()]).default(true)
190
+ }).default({}),
191
+ scheduler: z.object({
192
+ enable: z.boolean().default(true),
193
+ tickInterval: z.number().default(1e3),
194
+ keepJobHistory: z.union([z.boolean(), z.number()]).default(true),
195
+ keepFailedJobHistory: z.union([z.boolean(), z.number()]).default(true)
196
+ }).default({}),
197
+ // Auto-discovery directory
198
+ jobsDir: z.string().default("./src/jobs"),
199
+ // Global tags
200
+ tags: z.array(z.string()).default([]),
201
+ // Worker
202
+ worker: z.object({
203
+ concurrency: z.number().default(50),
204
+ gracefulShutdownMs: z.number().default(3e4)
205
+ }).default({ concurrency: 50, gracefulShutdownMs: 3e4 }),
206
+ // Logger (voltlog-io config or false to disable)
207
+ logger: z.union([
208
+ z.literal(false),
209
+ z.object({
210
+ enabled: z.boolean().default(true),
211
+ level: z.string().default("info"),
212
+ prettify: z.boolean().default(false),
213
+ showMetadata: z.boolean().default(true),
214
+ redact: z.array(z.string()).default([])
215
+ })
216
+ ]).default({
217
+ enabled: true,
218
+ level: "info",
219
+ prettify: false,
220
+ showMetadata: true,
221
+ redact: []
222
+ }),
223
+ // Telemetry
224
+ telemetry: z.object({
225
+ prometheus: z.object({
226
+ enabled: z.boolean().default(false),
227
+ path: z.string().default("/metrics")
228
+ }).default({}),
229
+ opentelemetry: z.object({
230
+ enabled: z.boolean().default(false)
231
+ }).default({})
232
+ }).default({}),
233
+ // Shutdown
234
+ shutdown: z.object({
235
+ enabled: z.boolean().default(true),
236
+ timeout: z.number().default(3e4),
237
+ signals: z.array(z.string()).default(["SIGINT", "SIGTERM"])
238
+ }).default({})
239
+ });
240
+
241
+ // src/core/config/config-loader.ts
242
+ async function loadConfig(cwd = process.cwd()) {
243
+ const configPath = await findUp("oqron.config.ts", { cwd }) || await findUp("oqron.config.js", { cwd });
244
+ if (!configPath) {
245
+ return OqronConfigSchema.parse({});
246
+ }
247
+ let rawConfig;
248
+ try {
249
+ const mod = await import(
250
+ /* @vite-ignore */
251
+ pathToFileURL(configPath).href
252
+ );
253
+ rawConfig = mod;
254
+ while (rawConfig && typeof rawConfig === "object" && "default" in rawConfig) {
255
+ rawConfig = rawConfig.default;
256
+ }
257
+ } catch (err) {
258
+ throw new Error(
259
+ `[OqronKit] Failed to load config from: ${configPath}
260
+ ${err}`
261
+ );
262
+ }
263
+ const parseResult = OqronConfigSchema.safeParse(rawConfig);
264
+ if (!parseResult.success) {
265
+ throw new Error(
266
+ `[OqronKit] Invalid oqron.config.ts:
267
+ ${parseResult.error.message}`
268
+ );
269
+ }
270
+ return reconfigureConfig(parseResult.data);
271
+ }
272
+
273
+ // src/core/config/define-config.ts
274
+ function defineConfig(config) {
275
+ return config;
276
+ }
277
+
278
+ // src/core/context/job-context.ts
279
+ var JobContext = class {
280
+ id;
281
+ log;
282
+ signal;
283
+ environment;
284
+ project;
285
+ _progress = 0;
286
+ _onProgress;
287
+ constructor(opts) {
288
+ this.id = opts.id;
289
+ this.log = opts.logger;
290
+ this.signal = opts.signal;
291
+ this.environment = opts.environment;
292
+ this.project = opts.project;
293
+ this._onProgress = opts.onProgress;
294
+ this.progress = this.progress.bind(this);
295
+ }
296
+ progress(value, label) {
297
+ this._progress = Math.max(0, Math.min(100, value));
298
+ if (this._onProgress) {
299
+ this._onProgress(this._progress, label);
300
+ }
301
+ }
302
+ getProgress() {
303
+ return this._progress;
304
+ }
305
+ };
306
+
307
+ // src/core/context/cron-context.ts
308
+ var CronContext = class extends JobContext {
309
+ firedAt;
310
+ scheduleName;
311
+ startedLocalAt;
312
+ constructor(opts) {
313
+ super(opts);
314
+ this.firedAt = opts.firedAt;
315
+ this.scheduleName = opts.scheduleName;
316
+ this.startedLocalAt = Date.now();
317
+ }
318
+ get duration() {
319
+ return Date.now() - this.startedLocalAt;
320
+ }
321
+ };
322
+
323
+ // src/core/context/schedule-context.ts
324
+ var ScheduleContext = class {
325
+ id;
326
+ name;
327
+ firedAt;
328
+ payload;
329
+ environment;
330
+ project;
331
+ logger;
332
+ signal;
333
+ startedLocalAt;
334
+ _onProgress;
335
+ constructor(opts) {
336
+ this.id = opts.id;
337
+ this.name = opts.scheduleName;
338
+ this.firedAt = opts.firedAt;
339
+ this.payload = opts.payload;
340
+ this.logger = opts.logger;
341
+ this.signal = opts.signal;
342
+ this.environment = opts.environment;
343
+ this.project = opts.project;
344
+ this.startedLocalAt = Date.now();
345
+ this._onProgress = opts.onProgress;
346
+ this.log = this.log.bind(this);
347
+ this.progress = this.progress.bind(this);
348
+ }
349
+ get aborted() {
350
+ return this.signal.aborted;
351
+ }
352
+ get duration() {
353
+ return Date.now() - this.startedLocalAt;
354
+ }
355
+ log(level, message, meta) {
356
+ if (this.logger && typeof this.logger[level] === "function") {
357
+ this.logger[level](message, meta);
358
+ }
359
+ }
360
+ progress(percent, label) {
361
+ if (this._onProgress) {
362
+ this._onProgress(percent, label);
363
+ } else {
364
+ this.logger.debug("Progress updated", { percent, label, runId: this.id });
365
+ }
366
+ }
367
+ };
368
+ var OqronEventBusClass = class _OqronEventBusClass extends EventEmitter {
369
+ static _instance;
370
+ static getInstance() {
371
+ if (!_OqronEventBusClass._instance) {
372
+ _OqronEventBusClass._instance = new _OqronEventBusClass();
373
+ }
374
+ return _OqronEventBusClass._instance;
375
+ }
376
+ };
377
+ var OqronEventBus = OqronEventBusClass.getInstance();
378
+ var NOOP_LOGGER = {
379
+ trace() {
380
+ },
381
+ debug() {
382
+ },
383
+ info() {
384
+ },
385
+ warn() {
386
+ },
387
+ error() {
388
+ },
389
+ fatal() {
390
+ },
391
+ child() {
392
+ return NOOP_LOGGER;
393
+ },
394
+ addTransport() {
395
+ },
396
+ removeTransport() {
397
+ },
398
+ addMiddleware() {
399
+ },
400
+ removeMiddleware() {
401
+ },
402
+ setLevel() {
403
+ },
404
+ getLevel() {
405
+ return "SILENT";
406
+ },
407
+ isLevelEnabled() {
408
+ return false;
409
+ },
410
+ startTimer() {
411
+ return { done() {
412
+ }, elapsed: () => 0 };
413
+ },
414
+ async flush() {
415
+ },
416
+ async close() {
417
+ }
418
+ };
419
+ function createLogger(config, context) {
420
+ if (typeof config?.enabled !== "undefined" && config?.enabled === false)
421
+ return NOOP_LOGGER;
422
+ if (config?.logger) return config.logger;
423
+ const level = (config?.level ?? "INFO").toUpperCase();
424
+ const opts = {
425
+ level,
426
+ transports: [],
427
+ context
428
+ };
429
+ if (config?.redact?.length) {
430
+ const keys = config.redact;
431
+ opts.middleware = [
432
+ redactionMiddleware({
433
+ paths: keys,
434
+ deep: true
435
+ })
436
+ ];
437
+ }
438
+ if (config?.prettify) {
439
+ opts.transports.push(prettyTransport());
440
+ } else {
441
+ opts.transports.push(consoleTransport());
442
+ }
443
+ return createLogger$1(opts);
444
+ }
445
+
446
+ // src/core/registry.ts
447
+ var OqronRegistry = class _OqronRegistry {
448
+ static _instance;
449
+ _modules = /* @__PURE__ */ new Map();
450
+ constructor() {
451
+ }
452
+ static getInstance() {
453
+ if (!_OqronRegistry._instance) {
454
+ _OqronRegistry._instance = new _OqronRegistry();
455
+ }
456
+ return _OqronRegistry._instance;
457
+ }
458
+ register(mod) {
459
+ if (this._modules.has(mod.name)) {
460
+ throw new Error(`[OqronKit] Module "${mod.name}" is already registered.`);
461
+ }
462
+ this._modules.set(mod.name, mod);
463
+ }
464
+ get(name) {
465
+ return this._modules.get(name);
466
+ }
467
+ getAll() {
468
+ return [...this._modules.values()];
469
+ }
470
+ /** Reset registry — useful for testing */
471
+ _reset() {
472
+ this._modules.clear();
473
+ }
474
+ };
475
+ var DbLockAdapter = class {
476
+ db;
477
+ defaultTtl;
478
+ /**
479
+ * @param dbOrPath - Either a `better-sqlite3` Database instance or a file path.
480
+ * When sharing the same SQLite file as SqliteAdapter, pass the same path.
481
+ * @param defaultTtlMs - Default TTL for locks if not provided in acquire (optional)
482
+ */
483
+ constructor(dbOrPath = "oqron.sqlite", defaultTtlMs = 3e4) {
484
+ this.defaultTtl = defaultTtlMs;
485
+ if (typeof dbOrPath === "string") {
486
+ this.db = new Database(dbOrPath);
487
+ } else {
488
+ this.db = dbOrPath;
489
+ }
490
+ }
491
+ async acquire(key, ownerId, ttlMs) {
492
+ const finalTtl = ttlMs ?? this.defaultTtl;
493
+ const now = (/* @__PURE__ */ new Date()).toISOString();
494
+ const expiresAt = new Date(Date.now() + finalTtl).toISOString();
495
+ this.db.prepare(
496
+ `
497
+ INSERT INTO chrono_locks (resourceKey, ownerId, expiresAt)
498
+ VALUES (?, ?, ?)
499
+ ON CONFLICT(resourceKey) DO UPDATE SET
500
+ ownerId = CASE WHEN expiresAt < ? THEN excluded.ownerId ELSE ownerId END,
501
+ expiresAt = CASE WHEN expiresAt < ? THEN excluded.expiresAt ELSE expiresAt END
502
+ `
503
+ ).run(key, ownerId, expiresAt, now, now);
504
+ const row = this.db.prepare(`SELECT ownerId FROM chrono_locks WHERE resourceKey = ?`).get(key);
505
+ return row?.ownerId === ownerId;
506
+ }
507
+ async renew(key, ownerId, ttlMs) {
508
+ const finalTtl = ttlMs ?? this.defaultTtl;
509
+ const expiresAt = new Date(Date.now() + finalTtl).toISOString();
510
+ const result = this.db.prepare(
511
+ `
512
+ UPDATE chrono_locks SET expiresAt = ?
513
+ WHERE resourceKey = ? AND ownerId = ?
514
+ `
515
+ ).run(expiresAt, key, ownerId);
516
+ return result.changes > 0;
517
+ }
518
+ async release(key, ownerId) {
519
+ this.db.prepare(`DELETE FROM chrono_locks WHERE resourceKey = ? AND ownerId = ?`).run(key, ownerId);
520
+ }
521
+ async isOwner(key, ownerId) {
522
+ const row = this.db.prepare(
523
+ `SELECT ownerId, expiresAt FROM chrono_locks WHERE resourceKey = ?`
524
+ ).get(key);
525
+ if (!row) return false;
526
+ const expired = new Date(row.expiresAt) < /* @__PURE__ */ new Date();
527
+ return !expired && row.ownerId === ownerId;
528
+ }
529
+ };
530
+
531
+ // src/lock/adapters/memory-lock.adapter.ts
532
+ var MemoryLockAdapter = class {
533
+ locks = /* @__PURE__ */ new Map();
534
+ async acquire(key, ownerId, ttlMs) {
535
+ const existing = this.locks.get(key);
536
+ if (existing && existing.expiresAt > Date.now()) {
537
+ return existing.ownerId === ownerId;
538
+ }
539
+ this.locks.set(key, { ownerId, expiresAt: Date.now() + ttlMs });
540
+ return true;
541
+ }
542
+ async renew(key, ownerId, ttlMs) {
543
+ const existing = this.locks.get(key);
544
+ if (!existing || existing.ownerId !== ownerId) return false;
545
+ existing.expiresAt = Date.now() + ttlMs;
546
+ return true;
547
+ }
548
+ async release(key, ownerId) {
549
+ const existing = this.locks.get(key);
550
+ if (existing?.ownerId === ownerId) this.locks.delete(key);
551
+ }
552
+ async isOwner(key, ownerId) {
553
+ const existing = this.locks.get(key);
554
+ return !!existing && existing.ownerId === ownerId && existing.expiresAt > Date.now();
555
+ }
556
+ };
557
+
558
+ // src/lock/adapters/namespaced-lock.adapter.ts
559
+ var NamespacedLockAdapter = class {
560
+ constructor(base, project = "default", environment = "development") {
561
+ this.base = base;
562
+ this.prefix = `${project}:${environment}:`;
563
+ }
564
+ prefix;
565
+ ns(key) {
566
+ return `${this.prefix}${key}`;
567
+ }
568
+ async acquire(key, ownerId, ttlMs) {
569
+ return this.base.acquire(this.ns(key), ownerId, ttlMs);
570
+ }
571
+ async renew(key, ownerId, ttlMs) {
572
+ return this.base.renew(this.ns(key), ownerId, ttlMs);
573
+ }
574
+ async release(key, ownerId) {
575
+ return this.base.release(this.ns(key), ownerId);
576
+ }
577
+ async isOwner(key, ownerId) {
578
+ return this.base.isOwner(this.ns(key), ownerId);
579
+ }
580
+ /**
581
+ * Note: Some lock adapters might implement advanced prefixing natively,
582
+ * but we proxy all core lock operations through the namespace.
583
+ */
584
+ };
585
+
586
+ // src/lock/heartbeat-worker.ts
587
+ var HeartbeatWorker = class {
588
+ constructor(lock, logger, key, ownerId, ttlMs = 3e4, heartbeatMs) {
589
+ this.lock = lock;
590
+ this.logger = logger;
591
+ this.key = key;
592
+ this.ownerId = ownerId;
593
+ this.ttlMs = ttlMs;
594
+ this.heartbeatMs = heartbeatMs;
595
+ }
596
+ heartbeatTimer;
597
+ _active = false;
598
+ async start() {
599
+ const acquired = await this.lock.acquire(
600
+ this.key,
601
+ this.ownerId,
602
+ this.ttlMs
603
+ );
604
+ if (!acquired) return false;
605
+ this._active = true;
606
+ const pingInterval = this.heartbeatMs ?? Math.floor(this.ttlMs / 3);
607
+ this.heartbeatTimer = setInterval(async () => {
608
+ if (!this._active) return;
609
+ try {
610
+ const renewed = await this.lock.renew(
611
+ this.key,
612
+ this.ownerId,
613
+ this.ttlMs
614
+ );
615
+ if (!renewed) {
616
+ this.logger.warn("Heartbeat renewal failed \u2014 lock lost", {
617
+ key: this.key,
618
+ ownerId: this.ownerId
619
+ });
620
+ this._active = false;
621
+ clearInterval(this.heartbeatTimer);
622
+ }
623
+ } catch (err) {
624
+ this.logger.error("Heartbeat renewal threw", {
625
+ key: this.key,
626
+ err: String(err)
627
+ });
628
+ }
629
+ }, pingInterval);
630
+ return true;
631
+ }
632
+ async stop() {
633
+ this._active = false;
634
+ if (this.heartbeatTimer) {
635
+ clearInterval(this.heartbeatTimer);
636
+ this.heartbeatTimer = void 0;
637
+ }
638
+ try {
639
+ await this.lock.release(this.key, this.ownerId);
640
+ } catch (err) {
641
+ this.logger.error("Failed to release lock cleanly", {
642
+ key: this.key,
643
+ err: String(err)
644
+ });
645
+ }
646
+ }
647
+ get isActive() {
648
+ return this._active;
649
+ }
650
+ };
651
+
652
+ // src/lock/leader-election.ts
653
+ var LeaderElection = class {
654
+ constructor(lock, logger, leaderKey, nodeId, ttlMs = 3e4) {
655
+ this.lock = lock;
656
+ this.logger = logger;
657
+ this.leaderKey = leaderKey;
658
+ this.nodeId = nodeId;
659
+ this.ttlMs = ttlMs;
660
+ }
661
+ electionTimer;
662
+ _isLeader = false;
663
+ async start() {
664
+ await this.campaign();
665
+ const interval = Math.floor(this.ttlMs / 3);
666
+ this.electionTimer = setInterval(() => void this.campaign(), interval);
667
+ }
668
+ async campaign() {
669
+ try {
670
+ if (this._isLeader) {
671
+ const ok = await this.lock.renew(
672
+ this.leaderKey,
673
+ this.nodeId,
674
+ this.ttlMs
675
+ );
676
+ if (!ok) {
677
+ this._isLeader = false;
678
+ this.logger.warn("Lost leadership", {
679
+ leaderKey: this.leaderKey,
680
+ nodeId: this.nodeId
681
+ });
682
+ }
683
+ } else {
684
+ const ok = await this.lock.acquire(
685
+ this.leaderKey,
686
+ this.nodeId,
687
+ this.ttlMs
688
+ );
689
+ if (ok) {
690
+ this._isLeader = true;
691
+ this.logger.info("Became leader", {
692
+ leaderKey: this.leaderKey,
693
+ nodeId: this.nodeId
694
+ });
695
+ }
696
+ }
697
+ } catch (err) {
698
+ this.logger.error("Leader election error", {
699
+ leaderKey: this.leaderKey,
700
+ err: String(err)
701
+ });
702
+ this._isLeader = false;
703
+ }
704
+ }
705
+ get isLeader() {
706
+ return this._isLeader;
707
+ }
708
+ async stop() {
709
+ if (this.electionTimer) {
710
+ clearInterval(this.electionTimer);
711
+ this.electionTimer = void 0;
712
+ }
713
+ if (this._isLeader) {
714
+ try {
715
+ await this.lock.release(this.leaderKey, this.nodeId);
716
+ } catch {
717
+ }
718
+ this._isLeader = false;
719
+ }
720
+ }
721
+ };
722
+
723
+ // src/lock/stall-detector.ts
724
+ var StallDetector = class {
725
+ constructor(lock, logger, checkIntervalMs = 15e3) {
726
+ this.lock = lock;
727
+ this.logger = logger;
728
+ this.checkIntervalMs = checkIntervalMs;
729
+ }
730
+ timer;
731
+ /**
732
+ * Start the stall detection loop.
733
+ * @param getActiveJobs - Returns a list of { key, ownerId } for all currently tracked jobs.
734
+ * @param onStalled - Called when a job is detected as stalled (lock lost).
735
+ */
736
+ start(getActiveJobs, onStalled) {
737
+ this.timer = setInterval(async () => {
738
+ try {
739
+ const jobs = getActiveJobs();
740
+ for (const job of jobs) {
741
+ const owned = await this.lock.isOwner(job.key, job.ownerId);
742
+ if (!owned) {
743
+ this.logger.warn("Stalled job detected \u2014 lock lost", {
744
+ key: job.key,
745
+ ownerId: job.ownerId
746
+ });
747
+ onStalled(job.key);
748
+ }
749
+ }
750
+ } catch (err) {
751
+ this.logger.error("StallDetector tick error", { err: String(err) });
752
+ }
753
+ }, this.checkIntervalMs);
754
+ }
755
+ stop() {
756
+ if (this.timer) {
757
+ clearInterval(this.timer);
758
+ this.timer = void 0;
759
+ }
760
+ }
761
+ };
762
+ var cronParser = _cronParser.default ?? _cronParser;
763
+ function getNextRunDate(expression, timezone, from = /* @__PURE__ */ new Date()) {
764
+ const opts = { currentDate: from };
765
+ if (timezone) opts.tz = timezone;
766
+ return cronParser.parseExpression(expression, opts).next().toDate();
767
+ }
768
+ var cronParser2 = _cronParser.default ?? _cronParser;
769
+ var MissedFireHandler = class {
770
+ constructor(logger, _db) {
771
+ this.logger = logger;
772
+ this._db = _db;
773
+ }
774
+ async checkMissed(def, lastRunAt, now) {
775
+ if (!lastRunAt) return false;
776
+ try {
777
+ let missed = false;
778
+ if (def.expression) {
779
+ const opts = { currentDate: now, tz: def.timezone };
780
+ const prevRun = cronParser2.parseExpression(def.expression, opts).prev().toDate();
781
+ missed = prevRun > lastRunAt;
782
+ } else if (def.intervalMs) {
783
+ const elapsed = now.getTime() - lastRunAt.getTime();
784
+ missed = elapsed > def.intervalMs;
785
+ }
786
+ if (missed) {
787
+ this.logger.warn("Missed execution detected", {
788
+ name: def.name,
789
+ policy: def.missedFire
790
+ });
791
+ if (def.hooks?.onMissedFire) {
792
+ try {
793
+ const ctx = {
794
+ id: randomUUID(),
795
+ log: this.logger.child({
796
+ schedule: def.name,
797
+ scope: "missed-fire"
798
+ }),
799
+ logger: this.logger.child({
800
+ schedule: def.name,
801
+ scope: "missed-fire"
802
+ }),
803
+ signal: new AbortController().signal,
804
+ firedAt: now,
805
+ scheduleName: def.name,
806
+ progress: () => {
807
+ }
808
+ };
809
+ await def.hooks.onMissedFire(ctx, lastRunAt);
810
+ } catch (err) {
811
+ this.logger.error("onMissedFire hook threw", {
812
+ name: def.name,
813
+ err: String(err)
814
+ });
815
+ }
816
+ }
817
+ if (def.missedFire === "run-once" || def.missedFire === "run-all") {
818
+ return true;
819
+ }
820
+ }
821
+ } catch {
822
+ }
823
+ return false;
824
+ }
825
+ };
826
+
827
+ // src/scheduler/cron-engine.ts
828
+ var SchedulerModule = class {
829
+ constructor(schedules, db, lock, logger, environment, project, config) {
830
+ this.schedules = schedules;
831
+ this.db = db;
832
+ this.lock = lock;
833
+ this.environment = environment;
834
+ this.project = project;
835
+ this.config = config;
836
+ this.nodeId = randomUUID();
837
+ this.logger = logger ?? createLogger({ level: "info" }, { module: "scheduler" });
838
+ this.stallDetector = new StallDetector(this.lock, this.logger, 15e3);
839
+ this.missedFireHandler = new MissedFireHandler(this.logger, this.db);
840
+ }
841
+ name = "cron";
842
+ enabled = true;
843
+ nodeId;
844
+ logger;
845
+ leader;
846
+ stallDetector;
847
+ missedFireHandler;
848
+ tickTimer;
849
+ activeJobs = /* @__PURE__ */ new Map();
850
+ _hasRunLeaderInit = false;
851
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
852
+ async init() {
853
+ this.logger.info("Initializing scheduler", {
854
+ nodeId: this.nodeId,
855
+ count: this.schedules.length
856
+ });
857
+ for (const def of this.schedules) {
858
+ await this.db.upsertSchedule(def);
859
+ this.logger.debug("Registered schedule", {
860
+ name: def.name,
861
+ expression: def.expression,
862
+ intervalMs: def.intervalMs
863
+ });
864
+ }
865
+ const existing = await this.db.getSchedules();
866
+ const now = /* @__PURE__ */ new Date();
867
+ for (const record of existing) {
868
+ if (record.nextRunAt !== null) continue;
869
+ const def = this.schedules.find((s) => s.name === record.name);
870
+ if (!def) continue;
871
+ const nextRun = this.computeNextRun(def, now);
872
+ if (nextRun) {
873
+ await this.db.updateNextRun(def.name, nextRun);
874
+ this.logger.debug("Seeded nextRunAt", {
875
+ name: def.name,
876
+ nextRunAt: nextRun.toISOString()
877
+ });
878
+ }
879
+ }
880
+ }
881
+ async start() {
882
+ if (this.config?.leaderElection !== false) {
883
+ this.leader = new LeaderElection(
884
+ this.lock,
885
+ this.logger,
886
+ "oqron:scheduler:leader",
887
+ this.nodeId,
888
+ 3e4
889
+ );
890
+ await this.leader.start();
891
+ }
892
+ const interval = this.config?.tickInterval ?? 1e3;
893
+ this.tickTimer = setInterval(() => {
894
+ void this.tick();
895
+ }, interval);
896
+ this.logger.info("Scheduler started", { nodeId: this.nodeId, interval });
897
+ }
898
+ async stop() {
899
+ if (this.tickTimer) clearInterval(this.tickTimer);
900
+ if (this.leader) await this.leader.stop();
901
+ this.stallDetector.stop();
902
+ for (const job of this.activeJobs.values()) {
903
+ if (job.abort) job.abort.abort();
904
+ if (job.worker) {
905
+ await job.worker.stop();
906
+ } else {
907
+ await this.lock.release(job.lockKey, this.nodeId).catch(() => {
908
+ });
909
+ }
910
+ }
911
+ this.activeJobs.clear();
912
+ this.logger.info("Scheduler stopped");
913
+ }
914
+ // ── Core scheduling helpers ─────────────────────────────────────────────────
915
+ /**
916
+ * Compute the next fire time for a definition.
917
+ * Returns null if computation fails (invalid expression, etc).
918
+ */
919
+ computeNextRun(def, from) {
920
+ if (def.expression) {
921
+ try {
922
+ const timezone = def.timezone ?? this.config?.timezone;
923
+ return getNextRunDate(def.expression, timezone, from);
924
+ } catch (err) {
925
+ this.logger.error("Failed to compute next run from expression", {
926
+ name: def.name,
927
+ expression: def.expression,
928
+ err: String(err)
929
+ });
930
+ return null;
931
+ }
932
+ }
933
+ if (def.intervalMs) {
934
+ return new Date(from.getTime() + def.intervalMs);
935
+ }
936
+ this.logger.error("Schedule has neither expression nor intervalMs", {
937
+ name: def.name
938
+ });
939
+ return null;
940
+ }
941
+ // ── Leader init (missed-fire recovery + stall detector) ─────────────────────
942
+ async handleLeaderInit() {
943
+ this.logger.info("Performing leader initialization...");
944
+ const knownSchedules = await this.db.getSchedules();
945
+ const now = /* @__PURE__ */ new Date();
946
+ for (const record of knownSchedules) {
947
+ const def = this.schedules.find((s) => s.name === record.name);
948
+ if (!def) continue;
949
+ const missed = await this.missedFireHandler.checkMissed(
950
+ def,
951
+ record.lastRunAt,
952
+ now
953
+ );
954
+ if (missed) {
955
+ this.logger.info("Triggering recovery run for missed schedule", {
956
+ name: def.name
957
+ });
958
+ void this.fire(def);
959
+ }
960
+ }
961
+ this.stallDetector.start(
962
+ () => {
963
+ return Array.from(this.activeJobs.values()).filter((job) => job.worker !== void 0).map((job) => ({
964
+ key: job.lockKey,
965
+ ownerId: this.nodeId
966
+ }));
967
+ },
968
+ (key) => {
969
+ this.logger.warn("Local stall detected", { key });
970
+ }
971
+ );
972
+ }
973
+ async detectClusterStalls() {
974
+ try {
975
+ const activeDbJobs = await this.db.getActiveJobs();
976
+ for (const job of activeDbJobs) {
977
+ if (!job.scheduleId) continue;
978
+ const def = this.schedules.find((s) => s.name === job.scheduleId);
979
+ if (!def?.guaranteedWorker) continue;
980
+ const ageMs = Date.now() - job.startedAt.getTime();
981
+ const ttl = def.lockTtlMs ?? 5e4;
982
+ if (ageMs > ttl + 1e4) {
983
+ this.logger.warn("Cluster stall detected", { runId: job.id });
984
+ await this.db.recordExecution({
985
+ id: job.id,
986
+ scheduleId: job.scheduleId,
987
+ status: "failed",
988
+ error: "Stall detected (lock assumed expired)",
989
+ startedAt: job.startedAt,
990
+ completedAt: /* @__PURE__ */ new Date()
991
+ });
992
+ }
993
+ }
994
+ } catch (err) {
995
+ this.logger.error("Failed to detect cluster stalls", {
996
+ err: String(err)
997
+ });
998
+ }
999
+ }
1000
+ // ── Tick loop ───────────────────────────────────────────────────────────────
1001
+ async tick() {
1002
+ if (this.leader && !this.leader.isLeader) return;
1003
+ if (!this._hasRunLeaderInit) {
1004
+ this._hasRunLeaderInit = true;
1005
+ await this.handleLeaderInit();
1006
+ }
1007
+ try {
1008
+ if (Math.random() < 0.1) {
1009
+ void this.detectClusterStalls();
1010
+ }
1011
+ const now = /* @__PURE__ */ new Date();
1012
+ const due = await this.db.getDueSchedules(now, 50);
1013
+ for (const { name } of due) {
1014
+ const def = this.schedules.find((s) => s.name === name);
1015
+ if (!def) continue;
1016
+ const nextRun = this.computeNextRun(def, now);
1017
+ if (!nextRun) {
1018
+ this.logger.error(
1019
+ "Cannot compute next run \u2014 suspending cron to prevent runaway loop",
1020
+ { name: def.name }
1021
+ );
1022
+ await this.db.updateNextRun(def.name, null).catch(() => {
1023
+ });
1024
+ continue;
1025
+ }
1026
+ await this.db.updateNextRun(def.name, nextRun);
1027
+ void this.fire(def);
1028
+ }
1029
+ } catch (err) {
1030
+ this.logger.error("Tick error", { err: String(err) });
1031
+ }
1032
+ }
1033
+ // ── Fire handler ────────────────────────────────────────────────────────────
1034
+ async fire(def) {
1035
+ const isOverlapSkip = def.overlap === "skip" || def.overlap === false;
1036
+ if (isOverlapSkip) {
1037
+ for (const job of this.activeJobs.values()) {
1038
+ if (job.lockKey === `oqron:run:${def.name}`) {
1039
+ this.logger.debug("Skipping overlapping run", { name: def.name });
1040
+ return;
1041
+ }
1042
+ }
1043
+ }
1044
+ const runId = randomUUID();
1045
+ const lockKey = isOverlapSkip ? `oqron:run:${def.name}` : `oqron:run:${def.name}:${runId}`;
1046
+ const startedAt = /* @__PURE__ */ new Date();
1047
+ let worker;
1048
+ let acquired = false;
1049
+ if (def.guaranteedWorker) {
1050
+ worker = new HeartbeatWorker(
1051
+ this.lock,
1052
+ this.logger,
1053
+ lockKey,
1054
+ this.nodeId,
1055
+ def.lockTtlMs ?? 3e4,
1056
+ def.heartbeatMs ?? 1e4
1057
+ );
1058
+ acquired = await worker.start();
1059
+ } else {
1060
+ acquired = await this.lock.acquire(
1061
+ lockKey,
1062
+ this.nodeId,
1063
+ def.lockTtlMs ?? 3e4
1064
+ );
1065
+ }
1066
+ if (!acquired) return;
1067
+ const abort = new AbortController();
1068
+ this.activeJobs.set(runId, { runId, lockKey, worker, abort });
1069
+ await this.db.recordExecution({
1070
+ id: runId,
1071
+ scheduleId: def.name,
1072
+ status: "running",
1073
+ startedAt
1074
+ });
1075
+ void Promise.resolve().then(async () => {
1076
+ const ctx = new CronContext({
1077
+ id: runId,
1078
+ logger: this.logger.child({ schedule: def.name }),
1079
+ signal: abort.signal,
1080
+ firedAt: startedAt,
1081
+ scheduleName: def.name,
1082
+ environment: this.environment,
1083
+ project: this.project,
1084
+ onProgress: (percent, label) => {
1085
+ this.db.updateJobProgress(runId, percent, label).catch(
1086
+ (err) => this.logger.error("Failed to update progress", { runId, err })
1087
+ );
1088
+ }
1089
+ });
1090
+ let status = "completed";
1091
+ let error;
1092
+ let timeoutHandle;
1093
+ let finalResult;
1094
+ let attempts = 1;
1095
+ const maxAttempts = (def.retries?.max ?? 0) + 1;
1096
+ while (attempts <= maxAttempts) {
1097
+ try {
1098
+ if (def.hooks?.beforeRun) await def.hooks.beforeRun(ctx);
1099
+ if (def.timeout) {
1100
+ const timeoutPromise = new Promise((_, reject) => {
1101
+ timeoutHandle = setTimeout(() => {
1102
+ abort.abort();
1103
+ reject(new Error(`Handler timed out after ${def.timeout}ms`));
1104
+ }, def.timeout);
1105
+ });
1106
+ finalResult = await Promise.race([
1107
+ def.handler(ctx),
1108
+ timeoutPromise
1109
+ ]);
1110
+ } else {
1111
+ finalResult = await def.handler(ctx);
1112
+ }
1113
+ if (def.hooks?.afterRun) {
1114
+ await def.hooks.afterRun(ctx, finalResult);
1115
+ }
1116
+ status = "completed";
1117
+ error = void 0;
1118
+ break;
1119
+ } catch (err) {
1120
+ error = err instanceof Error ? err.message : String(err);
1121
+ status = "failed";
1122
+ if (def.hooks?.onError && err instanceof Error) {
1123
+ try {
1124
+ await Promise.resolve(def.hooks.onError(ctx, err));
1125
+ } catch (e) {
1126
+ this.logger.error("onError hook threw", { err: String(e) });
1127
+ }
1128
+ }
1129
+ if (attempts < maxAttempts) {
1130
+ this.logger.warn("Job handler threw, retrying...", {
1131
+ name: def.name,
1132
+ runId,
1133
+ attempt: attempts,
1134
+ error
1135
+ });
1136
+ const baseDelay = def.retries?.baseDelay ?? 2e3;
1137
+ const delay = def.retries?.strategy === "exponential" ? baseDelay * 2 ** (attempts - 1) : baseDelay;
1138
+ attempts++;
1139
+ await new Promise((resolve) => setTimeout(resolve, delay));
1140
+ } else {
1141
+ this.logger.error("Job handler failed completely", {
1142
+ name: def.name,
1143
+ runId,
1144
+ attempts,
1145
+ error
1146
+ });
1147
+ break;
1148
+ }
1149
+ } finally {
1150
+ if (timeoutHandle) clearTimeout(timeoutHandle);
1151
+ }
1152
+ }
1153
+ const completedAt = /* @__PURE__ */ new Date();
1154
+ await this.db.recordExecution({
1155
+ id: runId,
1156
+ scheduleId: def.name,
1157
+ status,
1158
+ startedAt,
1159
+ completedAt,
1160
+ error,
1161
+ result: finalResult !== void 0 ? JSON.stringify(finalResult) : void 0,
1162
+ attempts,
1163
+ durationMs: completedAt.getTime() - startedAt.getTime(),
1164
+ ...status === "completed" ? { progressPercent: 100, progressLabel: "Completed" } : {}
1165
+ });
1166
+ if (worker) {
1167
+ await worker.stop();
1168
+ } else {
1169
+ await this.lock.release(lockKey, this.nodeId).catch(() => {
1170
+ });
1171
+ }
1172
+ this.activeJobs.delete(runId);
1173
+ if (def.intervalMs) {
1174
+ const nextRun = this.computeNextRun(def, /* @__PURE__ */ new Date());
1175
+ if (nextRun) {
1176
+ await this.db.updateNextRun(def.name, nextRun).catch(() => {
1177
+ });
1178
+ }
1179
+ }
1180
+ const keepJobHistory = def.keepHistory ?? this.config?.keepJobHistory ?? true;
1181
+ const keepFailedHistory = def.keepFailedHistory ?? this.config?.keepFailedJobHistory ?? true;
1182
+ if (keepJobHistory !== true || keepFailedHistory !== true) {
1183
+ this.db.pruneHistoryForSchedule(def.name, keepJobHistory, keepFailedHistory).catch(
1184
+ (err) => this.logger.debug("Failed to prune history", {
1185
+ err,
1186
+ name: def.name
1187
+ })
1188
+ );
1189
+ }
1190
+ this.logger.info("Job finished", {
1191
+ name: def.name,
1192
+ runId,
1193
+ status,
1194
+ attempts
1195
+ });
1196
+ });
1197
+ }
1198
+ };
1199
+
1200
+ // src/scheduler/registry.ts
1201
+ var GLOBAL_KEY = "__oqronkit_pending_crons__";
1202
+ function _getPending() {
1203
+ if (!globalThis[GLOBAL_KEY]) {
1204
+ globalThis[GLOBAL_KEY] = [];
1205
+ }
1206
+ return globalThis[GLOBAL_KEY];
1207
+ }
1208
+ function _registerCron(def) {
1209
+ _getPending().push(def);
1210
+ }
1211
+ function _drainPending() {
1212
+ const pending = _getPending();
1213
+ return pending.splice(0);
1214
+ }
1215
+
1216
+ // src/scheduler/define-cron.ts
1217
+ var cronParser3 = _cronParser.default ?? _cronParser;
1218
+ function everyToIntervalMs(every) {
1219
+ let ms = 0;
1220
+ if (every.seconds) ms += every.seconds * 1e3;
1221
+ if (every.minutes) ms += every.minutes * 6e4;
1222
+ if (every.hours) ms += every.hours * 36e5;
1223
+ if (ms <= 0)
1224
+ throw new Error(
1225
+ "[OqronKit] `every` config must resolve to a positive interval"
1226
+ );
1227
+ return ms;
1228
+ }
1229
+ var cron = (options) => {
1230
+ let expression;
1231
+ let intervalMs;
1232
+ if ("expression" in options && options.expression) {
1233
+ try {
1234
+ cronParser3.parseExpression(options.expression, { tz: options.timezone });
1235
+ } catch {
1236
+ throw new Error(
1237
+ `[OqronKit] Invalid cron expression for "${options.name}": "${options.expression}"`
1238
+ );
1239
+ }
1240
+ expression = options.expression;
1241
+ } else if ("every" in options && options.every) {
1242
+ intervalMs = everyToIntervalMs(options.every);
1243
+ } else {
1244
+ throw new Error(
1245
+ `[OqronKit] Cron "${options.name}" must specify either "expression" or "every"`
1246
+ );
1247
+ }
1248
+ const def = {
1249
+ name: options.name,
1250
+ expression,
1251
+ intervalMs,
1252
+ timezone: options.timezone,
1253
+ missedFire: options.missedFire ?? "skip",
1254
+ overlap: options.overlap ?? "skip",
1255
+ guaranteedWorker: options.guaranteedWorker ?? false,
1256
+ heartbeatMs: options.heartbeatMs,
1257
+ lockTtlMs: options.lockTtlMs,
1258
+ timeout: options.timeout,
1259
+ tags: options.tags ?? [],
1260
+ handler: options.handler,
1261
+ hooks: options.hooks,
1262
+ retries: options.retries
1263
+ };
1264
+ _registerCron(def);
1265
+ return def;
1266
+ };
1267
+
1268
+ // src/scheduler/registry-schedule.ts
1269
+ var GLOBAL_KEY2 = "__oqronkit_pending_schedules__";
1270
+ function _getPending2() {
1271
+ if (!globalThis[GLOBAL_KEY2]) {
1272
+ globalThis[GLOBAL_KEY2] = [];
1273
+ }
1274
+ return globalThis[GLOBAL_KEY2];
1275
+ }
1276
+ function _registerSchedule(def) {
1277
+ _getPending2().push(def);
1278
+ }
1279
+ function _drainPendingSchedules() {
1280
+ const pending = _getPending2();
1281
+ return pending.splice(0);
1282
+ }
1283
+
1284
+ // src/scheduler/define-schedule.ts
1285
+ var engineRef = { current: null };
1286
+ function _attachScheduleEngine(engine) {
1287
+ engineRef.current = engine;
1288
+ }
1289
+ var schedule = (options) => {
1290
+ const def = {
1291
+ name: options.name,
1292
+ runAt: options.runAt,
1293
+ runAfter: options.runAfter,
1294
+ recurring: options.recurring,
1295
+ rrule: options.rrule,
1296
+ every: options.every,
1297
+ timezone: options.timezone,
1298
+ missedFire: options.missedFire ?? "skip",
1299
+ overlap: options.overlap ?? "skip",
1300
+ guaranteedWorker: options.guaranteedWorker ?? false,
1301
+ heartbeatMs: options.heartbeatMs,
1302
+ lockTtlMs: options.lockTtlMs,
1303
+ timeout: options.timeout,
1304
+ tags: options.tags ?? [],
1305
+ condition: options.condition,
1306
+ handler: options.handler,
1307
+ hooks: options.hooks,
1308
+ payload: options.payload,
1309
+ retries: options.retries
1310
+ };
1311
+ _registerSchedule(def);
1312
+ return {
1313
+ ...def,
1314
+ trigger: async (opts) => {
1315
+ if (!engineRef.current) {
1316
+ throw new Error(
1317
+ `[OqronKit] Cannot trigger "${options.name}" \u2014 ScheduleEngine is not running.`
1318
+ );
1319
+ }
1320
+ const dynamicDef = { ...def };
1321
+ if (opts) {
1322
+ if (opts.nameSuffix) dynamicDef.name = `${def.name}:${opts.nameSuffix}`;
1323
+ if (opts.runAt) dynamicDef.runAt = opts.runAt;
1324
+ if (opts.runAfter) dynamicDef.runAfter = opts.runAfter;
1325
+ if (opts.recurring) dynamicDef.recurring = opts.recurring;
1326
+ if (opts.rrule) dynamicDef.rrule = opts.rrule;
1327
+ if (opts.every) dynamicDef.every = opts.every;
1328
+ if (opts.payload) dynamicDef.payload = opts.payload;
1329
+ }
1330
+ if (!opts?.runAt && !opts?.runAfter && !opts?.recurring && !opts?.rrule && !opts?.every) {
1331
+ dynamicDef.runAt = /* @__PURE__ */ new Date();
1332
+ }
1333
+ await engineRef.current.registerDynamic(dynamicDef);
1334
+ },
1335
+ schedule: async (opts) => {
1336
+ if (!engineRef.current) {
1337
+ throw new Error(
1338
+ `[OqronKit] Cannot schedule "${options.name}" \u2014 ScheduleEngine is not running.`
1339
+ );
1340
+ }
1341
+ const dynamicDef = { ...def };
1342
+ if (opts) {
1343
+ if (opts.nameSuffix) dynamicDef.name = `${def.name}:${opts.nameSuffix}`;
1344
+ if (opts.runAt) dynamicDef.runAt = opts.runAt;
1345
+ if (opts.runAfter) dynamicDef.runAfter = opts.runAfter;
1346
+ if (opts.recurring) dynamicDef.recurring = opts.recurring;
1347
+ if (opts.rrule) dynamicDef.rrule = opts.rrule;
1348
+ if (opts.every) dynamicDef.every = opts.every;
1349
+ if (opts.payload) dynamicDef.payload = opts.payload;
1350
+ }
1351
+ await engineRef.current.registerDynamic(dynamicDef);
1352
+ },
1353
+ cancel: async () => {
1354
+ if (!engineRef.current) return;
1355
+ await engineRef.current.cancel(def.name);
1356
+ }
1357
+ };
1358
+ };
1359
+ var ScheduleEngine = class {
1360
+ constructor(staticSchedules, db, lock, logger, environment, project, config) {
1361
+ this.db = db;
1362
+ this.lock = lock;
1363
+ this.environment = environment;
1364
+ this.project = project;
1365
+ this.config = config;
1366
+ this.nodeId = randomUUID();
1367
+ this.logger = logger ?? createLogger({ level: "info" }, { module: "scheduler" });
1368
+ this.stallDetector = new StallDetector(this.lock, this.logger, 15e3);
1369
+ for (const def of staticSchedules) {
1370
+ this.schedules.set(def.name, def);
1371
+ }
1372
+ }
1373
+ name = "scheduler";
1374
+ enabled = true;
1375
+ nodeId;
1376
+ logger;
1377
+ leader;
1378
+ stallDetector;
1379
+ tickTimer;
1380
+ activeJobs = /* @__PURE__ */ new Map();
1381
+ // Includes static instances and dynamically triggered instances
1382
+ schedules = /* @__PURE__ */ new Map();
1383
+ _hasRunLeaderInit = false;
1384
+ // ── Lifecycle ───────────────────────────────────────────────────────────────
1385
+ async init() {
1386
+ this.logger.info("Initializing schedule engine", {
1387
+ nodeId: this.nodeId,
1388
+ staticCount: this.schedules.size
1389
+ });
1390
+ _attachScheduleEngine(this);
1391
+ const now = /* @__PURE__ */ new Date();
1392
+ for (const def of this.schedules.values()) {
1393
+ await this.upsertAndSeed(def, now);
1394
+ }
1395
+ }
1396
+ async upsertAndSeed(def, now) {
1397
+ await this.db.upsertSchedule(def);
1398
+ const nextRun = this.computeNextRun(def, now);
1399
+ if (nextRun) {
1400
+ await this.db.updateNextRun(def.name, nextRun);
1401
+ }
1402
+ }
1403
+ /** Dynamically register and schedule a definition from trigger/schedule call */
1404
+ async registerDynamic(def) {
1405
+ this.schedules.set(def.name, def);
1406
+ await this.upsertAndSeed(def, /* @__PURE__ */ new Date());
1407
+ this.logger.debug("Registered dynamic schedule", { name: def.name });
1408
+ }
1409
+ async cancel(name) {
1410
+ this.schedules.delete(name);
1411
+ }
1412
+ async start() {
1413
+ this.leader = new LeaderElection(
1414
+ this.lock,
1415
+ this.logger,
1416
+ "oqron:scheduleengine:leader",
1417
+ this.nodeId,
1418
+ 3e4
1419
+ );
1420
+ await this.leader.start();
1421
+ const interval = this.config?.tickInterval ?? 1e3;
1422
+ this.tickTimer = setInterval(() => {
1423
+ void this.tick();
1424
+ }, interval);
1425
+ this.logger.info("Schedule engine started", {
1426
+ nodeId: this.nodeId,
1427
+ interval
1428
+ });
1429
+ }
1430
+ async stop() {
1431
+ if (this.tickTimer) clearInterval(this.tickTimer);
1432
+ if (this.leader) await this.leader.stop();
1433
+ this.stallDetector.stop();
1434
+ for (const job of this.activeJobs.values()) {
1435
+ if (job.abort) job.abort.abort();
1436
+ if (job.worker) {
1437
+ await job.worker.stop();
1438
+ } else {
1439
+ await this.lock.release(job.lockKey, this.nodeId).catch(() => {
1440
+ });
1441
+ }
1442
+ }
1443
+ this.activeJobs.clear();
1444
+ this.logger.info("Schedule engine stopped");
1445
+ }
1446
+ // ── Core scheduling helpers ─────────────────────────────────────────────────
1447
+ computeNextRun(def, from) {
1448
+ try {
1449
+ if (def.runAt) {
1450
+ return new Date(def.runAt);
1451
+ }
1452
+ if (def.runAfter) {
1453
+ const add = (def.runAfter.days ?? 0) * 864e5 + (def.runAfter.hours ?? 0) * 36e5 + (def.runAfter.minutes ?? 0) * 6e4 + (def.runAfter.seconds ?? 0) * 1e3;
1454
+ return new Date(from.getTime() + add);
1455
+ }
1456
+ if (def.rrule) {
1457
+ const rule = rrulestr(def.rrule);
1458
+ return rule.after(from);
1459
+ }
1460
+ if (def.recurring) {
1461
+ const freqMapHash = {
1462
+ daily: RRule.DAILY,
1463
+ weekly: RRule.WEEKLY,
1464
+ monthly: RRule.MONTHLY,
1465
+ yearly: RRule.YEARLY
1466
+ };
1467
+ const freq = freqMapHash[def.recurring.frequency] ?? RRule.DAILY;
1468
+ const options = { freq };
1469
+ if (def.recurring.months?.length)
1470
+ options.bymonth = def.recurring.months;
1471
+ if (def.recurring.dayOfMonth)
1472
+ options.bymonthday = [def.recurring.dayOfMonth];
1473
+ if (def.recurring.at) {
1474
+ options.byhour = [def.recurring.at.hour];
1475
+ options.byminute = [def.recurring.at.minute];
1476
+ options.bysecond = [0];
1477
+ }
1478
+ const rule = new RRule(options);
1479
+ return rule.after(from);
1480
+ }
1481
+ if (def.every) {
1482
+ const add = (def.every.hours ?? 0) * 36e5 + (def.every.minutes ?? 0) * 6e4 + (def.every.seconds ?? 0) * 1e3;
1483
+ return new Date(from.getTime() + add);
1484
+ }
1485
+ } catch (err) {
1486
+ this.logger.error("Failed to compute next run", {
1487
+ name: def.name,
1488
+ err: String(err)
1489
+ });
1490
+ }
1491
+ return null;
1492
+ }
1493
+ // ── Leader init (missed-fire recovery + stall detector) ─────────────────────
1494
+ async handleLeaderInit() {
1495
+ this.logger.info("Schedule Engine: Performing leader initialization...");
1496
+ this.stallDetector.start(
1497
+ () => {
1498
+ return Array.from(this.activeJobs.values()).filter((job) => job.worker !== void 0).map((job) => ({
1499
+ key: job.lockKey,
1500
+ ownerId: this.nodeId
1501
+ }));
1502
+ },
1503
+ (key) => {
1504
+ this.logger.warn("Local stall detected", { key });
1505
+ }
1506
+ );
1507
+ }
1508
+ // ── Tick loop ───────────────────────────────────────────────────────────────
1509
+ async tick() {
1510
+ if (!this.leader?.isLeader) return;
1511
+ if (!this._hasRunLeaderInit) {
1512
+ this._hasRunLeaderInit = true;
1513
+ await this.handleLeaderInit();
1514
+ }
1515
+ try {
1516
+ const now = /* @__PURE__ */ new Date();
1517
+ const due = await this.db.getDueSchedules(now, 50);
1518
+ for (const { name } of due) {
1519
+ const def = this.schedules.get(name);
1520
+ if (!def) continue;
1521
+ if (def.condition) {
1522
+ try {
1523
+ const conditionVal = await def.condition(
1524
+ new ScheduleContext({
1525
+ id: "eval",
1526
+ scheduleName: def.name,
1527
+ firedAt: now,
1528
+ logger: this.logger,
1529
+ signal: new AbortController().signal,
1530
+ payload: def.payload,
1531
+ environment: this.environment,
1532
+ project: this.project
1533
+ })
1534
+ );
1535
+ if (!conditionVal) {
1536
+ const nextRun2 = this.computeNextRun(def, now);
1537
+ if (nextRun2) await this.db.updateNextRun(def.name, nextRun2);
1538
+ continue;
1539
+ }
1540
+ } catch (e) {
1541
+ this.logger.error("Condition crashed", {
1542
+ name: def.name,
1543
+ error: String(e)
1544
+ });
1545
+ continue;
1546
+ }
1547
+ }
1548
+ let nextRun = null;
1549
+ if (!def.runAt && !def.runAfter) {
1550
+ nextRun = this.computeNextRun(def, now);
1551
+ if (!nextRun) {
1552
+ this.logger.error(
1553
+ "Cannot compute next run \u2014 suspending schedule to prevent runaway loop",
1554
+ { name: def.name }
1555
+ );
1556
+ await this.db.updateNextRun(def.name, null).catch(() => {
1557
+ });
1558
+ continue;
1559
+ }
1560
+ }
1561
+ await this.db.updateNextRun(def.name, nextRun);
1562
+ void this.fire(def);
1563
+ }
1564
+ } catch (err) {
1565
+ this.logger.error("Tick error", { err: String(err) });
1566
+ }
1567
+ }
1568
+ // ── Fire handler ────────────────────────────────────────────────────────────
1569
+ async fire(def) {
1570
+ const isOverlapSkip = def.overlap === "skip" || def.overlap === false;
1571
+ if (isOverlapSkip) {
1572
+ for (const job of this.activeJobs.values()) {
1573
+ if (job.lockKey === `oqron:schedule:run:${def.name}`) {
1574
+ this.logger.debug("Skipping overlapping run", { name: def.name });
1575
+ return;
1576
+ }
1577
+ }
1578
+ }
1579
+ const runId = randomUUID();
1580
+ const lockKey = isOverlapSkip ? `oqron:schedule:run:${def.name}` : `oqron:schedule:run:${def.name}:${runId}`;
1581
+ const startedAt = /* @__PURE__ */ new Date();
1582
+ let worker;
1583
+ let acquired = false;
1584
+ if (def.guaranteedWorker) {
1585
+ worker = new HeartbeatWorker(
1586
+ this.lock,
1587
+ this.logger,
1588
+ lockKey,
1589
+ this.nodeId,
1590
+ def.lockTtlMs ?? 3e4,
1591
+ def.heartbeatMs ?? 1e4
1592
+ );
1593
+ acquired = await worker.start();
1594
+ } else {
1595
+ acquired = await this.lock.acquire(
1596
+ lockKey,
1597
+ this.nodeId,
1598
+ def.lockTtlMs ?? 3e4
1599
+ );
1600
+ }
1601
+ if (!acquired) return;
1602
+ const abort = new AbortController();
1603
+ this.activeJobs.set(runId, { runId, lockKey, worker, abort });
1604
+ await this.db.recordExecution({
1605
+ id: runId,
1606
+ scheduleId: def.name,
1607
+ status: "running",
1608
+ startedAt
1609
+ });
1610
+ void Promise.resolve().then(async () => {
1611
+ const ctx = new ScheduleContext({
1612
+ id: runId,
1613
+ logger: this.logger.child({ schedule: def.name }),
1614
+ signal: abort.signal,
1615
+ firedAt: startedAt,
1616
+ scheduleName: def.name,
1617
+ payload: def.payload,
1618
+ environment: this.environment,
1619
+ project: this.project,
1620
+ onProgress: (percent, label) => {
1621
+ this.db.updateJobProgress(runId, percent, label).catch(
1622
+ (err) => this.logger.error("Failed to update schedule progress", {
1623
+ runId,
1624
+ err
1625
+ })
1626
+ );
1627
+ }
1628
+ });
1629
+ let status = "completed";
1630
+ let error;
1631
+ let timeoutHandle;
1632
+ let finalResult;
1633
+ let attempts = 1;
1634
+ const maxAttempts = (def.retries?.max ?? 0) + 1;
1635
+ while (attempts <= maxAttempts) {
1636
+ try {
1637
+ if (def.hooks?.beforeRun) await def.hooks.beforeRun(ctx);
1638
+ if (def.timeout) {
1639
+ const timeoutPromise = new Promise((_, reject) => {
1640
+ timeoutHandle = setTimeout(() => {
1641
+ abort.abort();
1642
+ reject(new Error(`Handler timed out after ${def.timeout}ms`));
1643
+ }, def.timeout);
1644
+ });
1645
+ finalResult = await Promise.race([
1646
+ def.handler(ctx),
1647
+ timeoutPromise
1648
+ ]);
1649
+ } else {
1650
+ finalResult = await def.handler(ctx);
1651
+ }
1652
+ if (def.hooks?.afterRun) {
1653
+ await def.hooks.afterRun(ctx, finalResult);
1654
+ }
1655
+ status = "completed";
1656
+ error = void 0;
1657
+ break;
1658
+ } catch (err) {
1659
+ error = err instanceof Error ? err.message : String(err);
1660
+ status = "failed";
1661
+ if (def.hooks?.onError && err instanceof Error) {
1662
+ try {
1663
+ await Promise.resolve(def.hooks.onError(ctx, err));
1664
+ } catch (e) {
1665
+ this.logger.error("onError hook threw", { err: String(e) });
1666
+ }
1667
+ }
1668
+ if (attempts < maxAttempts) {
1669
+ this.logger.warn("Schedule handler threw, retrying...", {
1670
+ name: def.name,
1671
+ runId,
1672
+ attempt: attempts,
1673
+ error
1674
+ });
1675
+ const baseDelay = def.retries?.baseDelay ?? 2e3;
1676
+ const delay = def.retries?.strategy === "exponential" ? baseDelay * 2 ** (attempts - 1) : baseDelay;
1677
+ attempts++;
1678
+ await new Promise((resolve) => setTimeout(resolve, delay));
1679
+ } else {
1680
+ this.logger.error("Schedule handler failed completely", {
1681
+ name: def.name,
1682
+ runId,
1683
+ attempts,
1684
+ error
1685
+ });
1686
+ break;
1687
+ }
1688
+ } finally {
1689
+ if (timeoutHandle) clearTimeout(timeoutHandle);
1690
+ }
1691
+ }
1692
+ const completedAt = /* @__PURE__ */ new Date();
1693
+ await this.db.recordExecution({
1694
+ id: runId,
1695
+ scheduleId: def.name,
1696
+ status,
1697
+ startedAt,
1698
+ completedAt,
1699
+ error,
1700
+ result: finalResult !== void 0 ? JSON.stringify(finalResult) : void 0,
1701
+ attempts,
1702
+ durationMs: completedAt.getTime() - startedAt.getTime(),
1703
+ ...status === "completed" ? { progressPercent: 100, progressLabel: "Completed" } : {}
1704
+ });
1705
+ if (worker) {
1706
+ await worker.stop();
1707
+ } else {
1708
+ await this.lock.release(lockKey, this.nodeId).catch(() => {
1709
+ });
1710
+ }
1711
+ this.activeJobs.delete(runId);
1712
+ const keepJobHistory = def.keepHistory ?? this.config?.keepJobHistory ?? true;
1713
+ const keepFailedHistory = def.keepFailedHistory ?? this.config?.keepFailedJobHistory ?? true;
1714
+ if (keepJobHistory !== true || keepFailedHistory !== true) {
1715
+ this.db.pruneHistoryForSchedule(def.name, keepJobHistory, keepFailedHistory).catch(
1716
+ (err) => this.logger.debug("Failed to prune history", {
1717
+ err,
1718
+ name: def.name
1719
+ })
1720
+ );
1721
+ }
1722
+ this.logger.info("Schedule finished", {
1723
+ name: def.name,
1724
+ runId,
1725
+ status,
1726
+ attempts
1727
+ });
1728
+ });
1729
+ }
1730
+ };
1731
+
1732
+ export { DbLockAdapter, MemoryLockAdapter, NamespacedLockAdapter, OqronEventBus, OqronRegistry, ScheduleEngine, SchedulerModule, _drainPending, _drainPendingSchedules, _registerCron, _registerSchedule, createLogger, cron, defineConfig, getNextRunDate, loadConfig, reconfigureConfig, schedule };