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