@keystrokehq/scheduler 0.0.0-staging-20260714211819

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,739 @@
1
+ import { n as DEFAULT_RETRY_DELAY_MS, r as retryDelayMs, t as defineSchedulerPlugin } from "./contract-E1QJBH6_.mjs";
2
+ import { DEFAULT_DATABASE_URL, claimDueTriggers, claimDueTriggersForOrg, claimNextJob, createPostgresCancelChannel as createPgCancelChannel, disableAllTriggerSchedules, disableTriggerSchedulesNotInSlugs, enqueueJob, failAgentSession, failWorkflowRun, getProjectScopeId, inferDialect, listEnabledScheduledTriggers, listExecutableAttachmentsByTriggerIds, markJobComplete, markJobFailed, requeueExpiredLeases, resolvePostgresUrlFromEnv, resolveProjectDatabaseUrlFromEnv, scheduleJobRetry, selectActiveEphemeralScheduledTriggerSlugs, selectTriggerBySlug, setTriggerScheduleEnabled, triggerTimezoneFromConfig, upsertTriggerScheduleFields } from "@keystrokehq/database";
3
+ import { EventEmitter } from "node:events";
4
+ import { nextTriggerRunAt, resolveCronSchedule } from "@keystrokehq/trigger";
5
+ import { PgBoss } from "pg-boss";
6
+ import { createHash } from "node:crypto";
7
+ //#region src/cancel-channel.ts
8
+ /** In-process cancel pub/sub for single-process queues (memory, db polling). */
9
+ function createInProcessCancelChannel() {
10
+ const emitter = new EventEmitter();
11
+ return {
12
+ async publishCancel(runId) {
13
+ emitter.emit("cancel", runId);
14
+ },
15
+ async subscribeCancel(handler) {
16
+ const listener = (runId) => {
17
+ handler(runId);
18
+ };
19
+ emitter.on("cancel", listener);
20
+ return async () => {
21
+ emitter.off("cancel", listener);
22
+ };
23
+ }
24
+ };
25
+ }
26
+ //#endregion
27
+ //#region src/database-queue.ts
28
+ function toJobPayload(job) {
29
+ return {
30
+ jobId: job.id,
31
+ kind: job.kind,
32
+ targetId: job.targetId,
33
+ runId: job.runId,
34
+ trigger: job.trigger,
35
+ payload: job.payload,
36
+ attempt: job.attempt,
37
+ maxAttempts: job.maxAttempts,
38
+ scheduledAt: job.scheduledAt,
39
+ ...job.parent ? { parent: job.parent } : {}
40
+ };
41
+ }
42
+ function createDatabaseJobQueue() {
43
+ const cancelChannel = createInProcessCancelChannel();
44
+ let handler;
45
+ let running = false;
46
+ let lentSlots = 0;
47
+ let activeLoops = 0;
48
+ let workerIdBase = "";
49
+ let pollIntervalMs = 250;
50
+ let leaseSweepIntervalMs = 3e4;
51
+ let leaseTimer;
52
+ const desiredConcurrency = () => 1 + lentSlots;
53
+ const loop = async (workerId) => {
54
+ try {
55
+ while (running && handler) {
56
+ if (activeLoops > desiredConcurrency()) return;
57
+ try {
58
+ const job = await claimNextJob(workerId);
59
+ if (!job) {
60
+ await sleep$1(pollIntervalMs);
61
+ continue;
62
+ }
63
+ try {
64
+ await handler(toJobPayload(job));
65
+ await markJobComplete(job.id);
66
+ } catch (error) {
67
+ if (job.attempt < job.maxAttempts) await scheduleJobRetry(job.id, job.attempt + 1, retryDelayMs(job.attempt));
68
+ else {
69
+ await markJobFailed(job.id, error);
70
+ if (job.kind === "workflow") await failWorkflowRun(job.runId, error);
71
+ if (job.kind === "agent") {
72
+ const sessionId = job.payload?.sessionId;
73
+ if (sessionId) await failAgentSession(sessionId, error);
74
+ }
75
+ }
76
+ }
77
+ } catch {
78
+ await sleep$1(pollIntervalMs);
79
+ }
80
+ }
81
+ } finally {
82
+ activeLoops -= 1;
83
+ ensureWorkers();
84
+ }
85
+ };
86
+ const ensureWorkers = () => {
87
+ while (running && handler && activeLoops < desiredConcurrency()) {
88
+ activeLoops += 1;
89
+ loop(`${workerIdBase}:${activeLoops}`);
90
+ }
91
+ };
92
+ return {
93
+ async enqueue(input) {
94
+ return enqueueJob(input);
95
+ },
96
+ async startWorker(nextHandler, options = {}) {
97
+ handler = nextHandler;
98
+ running = true;
99
+ workerIdBase = options.workerId ?? crypto.randomUUID();
100
+ pollIntervalMs = options.pollIntervalMs ?? 250;
101
+ leaseSweepIntervalMs = options.leaseSweepIntervalMs ?? 3e4;
102
+ leaseTimer = setInterval(() => {
103
+ requeueExpiredLeases();
104
+ }, leaseSweepIntervalMs);
105
+ ensureWorkers();
106
+ return async () => {
107
+ running = false;
108
+ clearInterval(leaseTimer);
109
+ leaseTimer = void 0;
110
+ };
111
+ },
112
+ async withLentSlot(fn) {
113
+ lentSlots += 1;
114
+ ensureWorkers();
115
+ try {
116
+ return await fn();
117
+ } finally {
118
+ lentSlots -= 1;
119
+ }
120
+ },
121
+ publishCancel: (runId) => cancelChannel.publishCancel(runId),
122
+ subscribeCancel: (handler) => cancelChannel.subscribeCancel(handler)
123
+ };
124
+ }
125
+ function sleep$1(ms) {
126
+ return new Promise((resolve) => setTimeout(resolve, ms));
127
+ }
128
+ //#endregion
129
+ //#region src/schedule-ticker.ts
130
+ function enqueueTriggerJob(jobQueue, row, scheduledAt) {
131
+ const input = {
132
+ kind: "trigger",
133
+ targetId: row.slug,
134
+ runId: crypto.randomUUID(),
135
+ trigger: row.kind,
136
+ payload: {},
137
+ projectId: row.projectId
138
+ };
139
+ if (scheduledAt) input.scheduledAt = scheduledAt;
140
+ return jobQueue.enqueue(input);
141
+ }
142
+ async function claimDue(scope, asOf, resolveNextRunAt, limit) {
143
+ if (scope === "organization") return claimDueTriggersForOrg(asOf, resolveNextRunAt, limit);
144
+ return claimDueTriggers(asOf, resolveNextRunAt, limit).then((rows) => rows.map((row) => ({
145
+ ...row,
146
+ projectId: getProjectScopeId()
147
+ })));
148
+ }
149
+ function createScheduleTicker(ctx) {
150
+ const pollIntervalMs = ctx.pollIntervalMs ?? 1e3;
151
+ const batchSize = ctx.batchSize ?? 10;
152
+ async function fireDueSchedules(asOf = /* @__PURE__ */ new Date()) {
153
+ const claimed = await claimDue(ctx.scope ?? "project", asOf, (schedule, timezone) => nextTriggerRunAt(schedule, asOf, timezone), batchSize);
154
+ for (const row of claimed) {
155
+ if (row.kind !== "cron" && row.kind !== "poll") continue;
156
+ await enqueueTriggerJob(ctx.jobQueue, {
157
+ slug: row.slug,
158
+ kind: row.kind,
159
+ projectId: row.projectId
160
+ });
161
+ }
162
+ return claimed.length;
163
+ }
164
+ async function startScheduleTicker(options = {}) {
165
+ const intervalMs = options.pollIntervalMs ?? pollIntervalMs;
166
+ const limit = options.batchSize ?? batchSize;
167
+ const scope = options.scope ?? ctx.scope ?? "project";
168
+ let running = true;
169
+ const loop = async () => {
170
+ while (running) {
171
+ try {
172
+ const claimed = await claimDue(scope, /* @__PURE__ */ new Date(), (schedule, timezone) => nextTriggerRunAt(schedule, /* @__PURE__ */ new Date(), timezone), limit);
173
+ for (const row of claimed) {
174
+ if (row.kind !== "cron" && row.kind !== "poll") continue;
175
+ await enqueueTriggerJob(ctx.jobQueue, {
176
+ slug: row.slug,
177
+ kind: row.kind,
178
+ projectId: row.projectId
179
+ });
180
+ }
181
+ } catch {}
182
+ await sleep(intervalMs);
183
+ }
184
+ };
185
+ loop();
186
+ return async () => {
187
+ running = false;
188
+ };
189
+ }
190
+ return {
191
+ fireDueSchedules,
192
+ startScheduleTicker
193
+ };
194
+ }
195
+ function sleep(ms) {
196
+ return new Promise((resolve) => setTimeout(resolve, ms));
197
+ }
198
+ //#endregion
199
+ //#region src/resolve-schedule.ts
200
+ function resolveTriggerSchedule(triggerSlug, schedule, overrides) {
201
+ return resolveCronSchedule(triggerSlug, schedule, {
202
+ cronScheduleOverride: overrides?.global,
203
+ attachmentScheduleOverrides: overrides?.byTrigger
204
+ });
205
+ }
206
+ //#endregion
207
+ //#region src/sync-trigger-schedules.ts
208
+ async function syncTriggerSchedules(options) {
209
+ const now = /* @__PURE__ */ new Date();
210
+ const projectSlugs = options.schedules.map((schedule) => schedule.triggerSlug);
211
+ const ephemeralSlugs = await selectActiveEphemeralScheduledTriggerSlugs();
212
+ const slugs = [...projectSlugs, ...ephemeralSlugs];
213
+ if (slugs.length === 0) {
214
+ await disableAllTriggerSchedules(now);
215
+ return;
216
+ }
217
+ await disableTriggerSchedulesNotInSlugs(slugs, now);
218
+ for (const spec of options.schedules) {
219
+ const schedule = resolveTriggerSchedule(spec.triggerSlug, spec.schedule, options.scheduleOverrides);
220
+ const existing = await selectTriggerBySlug(spec.triggerSlug);
221
+ if (!existing) continue;
222
+ const existingTimezone = triggerTimezoneFromConfig(existing.config);
223
+ const nextRunAt = !(existing.schedule !== schedule || existingTimezone !== spec.timezone) && existing.enabled === 1 ? existing.nextRunAt : nextTriggerRunAt(schedule, now, spec.timezone);
224
+ const enabled = (await listExecutableAttachmentsByTriggerIds([existing.id])).length > 0;
225
+ await upsertTriggerScheduleFields({
226
+ triggerSlug: spec.triggerSlug,
227
+ schedule,
228
+ nextRunAt: nextRunAt ?? now,
229
+ enabled,
230
+ updatedAt: now
231
+ });
232
+ }
233
+ }
234
+ //#endregion
235
+ //#region src/database-trigger-scheduler.ts
236
+ /** Postgres poll loop — default trigger scheduler for pg-boss, polling, and memory paths. */
237
+ function createDatabaseTriggerScheduler(options) {
238
+ const ticker = createScheduleTicker({
239
+ jobQueue: options.jobQueue,
240
+ scope: options.scope,
241
+ pollIntervalMs: options.pollIntervalMs,
242
+ batchSize: options.batchSize
243
+ });
244
+ return {
245
+ sync: (syncOptions) => syncTriggerSchedules(syncOptions),
246
+ start: (startOptions) => ticker.startScheduleTicker(startOptions),
247
+ fireDue: (asOf) => ticker.fireDueSchedules(asOf),
248
+ async remove(triggerSlug) {
249
+ await setTriggerScheduleEnabled(triggerSlug, false, /* @__PURE__ */ new Date());
250
+ },
251
+ async upsert(_spec) {}
252
+ };
253
+ }
254
+ //#endregion
255
+ //#region src/pg-boss-client.ts
256
+ let boss;
257
+ function resolveDatabaseUrl(url) {
258
+ const resolved = url ?? resolvePostgresUrlFromEnv(process.env);
259
+ if (!resolved) throw new Error("DATABASE_URL or POSTGRES_HOST/POSTGRES_USER/POSTGRES_PASSWORD/POSTGRES_DB is required");
260
+ return resolved;
261
+ }
262
+ async function startPgBoss(url) {
263
+ if (boss) return boss;
264
+ const next = new PgBoss({
265
+ connectionString: resolveDatabaseUrl(url),
266
+ schema: "pgboss"
267
+ });
268
+ next.on("error", (error) => {
269
+ console.error("[pg-boss]", error);
270
+ });
271
+ await next.start();
272
+ boss = next;
273
+ return next;
274
+ }
275
+ function getPgBoss() {
276
+ if (!boss) throw new Error("PgBoss not started. Call startPgBoss() first.");
277
+ return boss;
278
+ }
279
+ async function stopPgBoss() {
280
+ if (!boss) return;
281
+ await boss.stop();
282
+ boss = void 0;
283
+ }
284
+ //#endregion
285
+ //#region src/pg-cancel-channel.ts
286
+ /** Postgres NOTIFY channel — lowercase identifier (project ids are UUIDs, well under 63 chars). */
287
+ function pgCancelChannelName(scope, id) {
288
+ if (scope === "platform") return "keystroke_cancel_platform";
289
+ if (scope === "organization") return `keystroke_cancel_org_${(id ?? "default").replace(/[^a-z0-9_]/gi, "_").toLowerCase()}`;
290
+ return `keystroke_cancel_${(id ?? "default").replace(/[^a-z0-9_]/gi, "_").toLowerCase()}`;
291
+ }
292
+ //#endregion
293
+ //#region src/pg-boss-queue.ts
294
+ /** Shared queue name for the platform control-plane scope. */
295
+ const DEFAULT_QUEUE_NAME = "keystroke";
296
+ const PGBOSS_SCHEMA = "pgboss";
297
+ /**
298
+ * Derive a per-project pg-boss queue name. pg-boss queue names must be <= 50
299
+ * chars, contain only [A-Za-z0-9_], and not start with a digit. Project ids are
300
+ * usually UUIDs (hyphens, may start with a digit), so we sanitize, and fall back
301
+ * to a hash when the sanitized name would exceed the length limit.
302
+ */
303
+ function pgBossProjectQueueName(projectId) {
304
+ const name = `${DEFAULT_QUEUE_NAME}_${projectId.replace(/[^a-zA-Z0-9_]/g, "_")}`;
305
+ if (name.length <= 50) return name;
306
+ return `${DEFAULT_QUEUE_NAME}_${createHash("sha1").update(projectId).digest("hex").slice(0, 40)}`;
307
+ }
308
+ function pgBossOrgQueueName(organizationId) {
309
+ const name = `${DEFAULT_QUEUE_NAME}_org_${organizationId.replace(/[^a-zA-Z0-9_]/g, "_")}`;
310
+ if (name.length <= 50) return name;
311
+ return `${DEFAULT_QUEUE_NAME}_org_${createHash("sha1").update(organizationId).digest("hex").slice(0, 36)}`;
312
+ }
313
+ function buildPgBossJobQueue(boss, options) {
314
+ const queueName = options.queueName ?? "keystroke";
315
+ const cancelChannel = createPgCancelChannel(options.connectionString, pgCancelChannelName(options.cancelScope ?? "platform", options.cancelScope === "organization" ? options.organizationId : options.projectId));
316
+ return {
317
+ boss,
318
+ queueName,
319
+ async enqueue(input) {
320
+ const jobId = await boss.send(queueName, {
321
+ ...input,
322
+ payload: input.payload
323
+ }, {
324
+ retryLimit: (input.maxAttempts ?? 3) - 1,
325
+ retryDelay: Math.ceil(retryDelayMs(1) / 1e3),
326
+ startAfter: input.scheduledAt,
327
+ singletonKey: input.dedupeKey
328
+ });
329
+ if (!jobId) {
330
+ if (input.dedupeKey) return input.dedupeKey;
331
+ throw new Error("Failed to enqueue job");
332
+ }
333
+ return jobId;
334
+ },
335
+ async startWorker(handler) {
336
+ let stopped = false;
337
+ const workerId = await boss.work(queueName, {
338
+ batchSize: 1,
339
+ includeMetadata: true
340
+ }, async (jobs) => {
341
+ if (stopped) return;
342
+ const job = jobs[0];
343
+ if (!job) return;
344
+ const data = job.data;
345
+ const maxAttempts = data.maxAttempts ?? (job.retryLimit ?? 0) + 1;
346
+ const attempt = (job.retryCount ?? 0) + 1;
347
+ await handler({
348
+ jobId: job.id,
349
+ kind: data.kind,
350
+ targetId: data.targetId,
351
+ runId: data.runId,
352
+ trigger: data.trigger,
353
+ payload: data.payload ?? {},
354
+ attempt,
355
+ maxAttempts,
356
+ exhaustedRetries: attempt >= maxAttempts,
357
+ scheduledAt: data.scheduledAt ? new Date(data.scheduledAt) : /* @__PURE__ */ new Date(),
358
+ projectId: data.projectId,
359
+ parent: data.parent,
360
+ ...data.traceContext ? { traceContext: data.traceContext } : {}
361
+ });
362
+ });
363
+ return async () => {
364
+ stopped = true;
365
+ await boss.offWork(queueName, { id: workerId });
366
+ if (options.stopBossOnWorkerStop) await boss.stop({
367
+ graceful: true,
368
+ timeout: 5e3
369
+ });
370
+ };
371
+ },
372
+ publishCancel: (runId) => cancelChannel.publishCancel(runId),
373
+ subscribeCancel: (handler) => cancelChannel.subscribeCancel(handler)
374
+ };
375
+ }
376
+ async function createPgBossQueue(options) {
377
+ const queueName = options.queueName ?? "keystroke";
378
+ const boss = new PgBoss({
379
+ connectionString: options.connectionString,
380
+ schema: PGBOSS_SCHEMA
381
+ });
382
+ await boss.start();
383
+ await boss.createQueue(queueName);
384
+ return buildPgBossJobQueue(boss, {
385
+ stopBossOnWorkerStop: true,
386
+ queueName,
387
+ connectionString: options.connectionString,
388
+ cancelScope: options.cancelScope ?? "project",
389
+ projectId: options.projectId,
390
+ organizationId: options.organizationId
391
+ });
392
+ }
393
+ async function createSharedPgBossJobQueue(boss, options) {
394
+ const queueName = options.queueName ?? "keystroke";
395
+ await boss.createQueue(queueName);
396
+ return buildPgBossJobQueue(boss, {
397
+ queueName,
398
+ connectionString: options.connectionString,
399
+ cancelScope: "platform"
400
+ });
401
+ }
402
+ //#endregion
403
+ //#region src/pg-boss-trigger-scheduler.ts
404
+ /**
405
+ * pg-boss schedule key for one trigger. Mirrors {@link bullmqTriggerSchedulerId}
406
+ * so the firing backend is interchangeable: `trigger-<projectId>-<slug>`. pg-boss
407
+ * keys allow hyphens, so colons (legal in ids) are swapped for `-`.
408
+ */
409
+ function pgBossTriggerScheduleKey(spec) {
410
+ return `trigger-${(spec.projectId ?? getProjectScopeId()).replaceAll(":", "-")}-${spec.triggerSlug.replaceAll(":", "-")}`;
411
+ }
412
+ /** Key prefix scoping reconcile cleanup to the active project (org queues are shared). */
413
+ function pgBossTriggerScheduleKeyPrefix(projectId) {
414
+ return `trigger-${(projectId ?? getProjectScopeId()).replaceAll(":", "-")}-`;
415
+ }
416
+ function triggerJobData(spec) {
417
+ return {
418
+ kind: "trigger",
419
+ targetId: spec.triggerSlug,
420
+ runId: "",
421
+ trigger: spec.kind,
422
+ payload: {},
423
+ projectId: spec.projectId ?? getProjectScopeId()
424
+ };
425
+ }
426
+ function rowToSpec(row) {
427
+ if (row.kind !== "cron" && row.kind !== "poll") return;
428
+ if (!row.schedule) return;
429
+ const timezone = triggerTimezoneFromConfig(row.config ?? null);
430
+ return {
431
+ triggerSlug: row.slug,
432
+ kind: row.kind,
433
+ schedule: row.schedule,
434
+ ...timezone ? { timezone } : {},
435
+ projectId: row.projectId
436
+ };
437
+ }
438
+ /**
439
+ * Trigger scheduler backed by pg-boss native cron scheduling. Mirrors
440
+ * {@link createBullmqTriggerScheduler}: `boss.schedule` registers a recurring job
441
+ * onto the project/org queue (no per-second DB poll), and reconcile keeps the
442
+ * `pgboss.schedule` table in sync with the `triggers` table (source of truth).
443
+ *
444
+ * Granularity: pg-boss cron is minute-level (it checks schedules every ~30s and
445
+ * dedupes per minute), so sub-minute schedules effectively fire at most once per
446
+ * minute — unlike the DB ticker's 1s loop.
447
+ */
448
+ function createPgBossTriggerScheduler(_ctx, queue) {
449
+ async function upsertScheduler(spec, overrides) {
450
+ const schedule = resolveTriggerSchedule(spec.triggerSlug, spec.schedule, overrides);
451
+ const key = pgBossTriggerScheduleKey(spec);
452
+ await queue.boss.schedule(queue.queueName, schedule, triggerJobData({
453
+ ...spec,
454
+ schedule
455
+ }), {
456
+ key,
457
+ ...spec.timezone ? { tz: spec.timezone } : {}
458
+ });
459
+ }
460
+ async function reconcileFromDatabase(overrides) {
461
+ const projectPrefix = pgBossTriggerScheduleKeyPrefix();
462
+ const rows = await listEnabledScheduledTriggers();
463
+ const expectedKeys = /* @__PURE__ */ new Set();
464
+ const failures = [];
465
+ for (const row of rows) {
466
+ const spec = rowToSpec(row);
467
+ if (!spec) continue;
468
+ expectedKeys.add(pgBossTriggerScheduleKey(spec));
469
+ try {
470
+ await upsertScheduler(spec, overrides);
471
+ } catch (error) {
472
+ failures.push({
473
+ triggerSlug: spec.triggerSlug,
474
+ error
475
+ });
476
+ console.error(`[pg-boss-trigger-scheduler] failed to schedule ${spec.triggerSlug}`, error);
477
+ }
478
+ }
479
+ const schedules = await queue.boss.getSchedules(queue.queueName);
480
+ for (const schedule of schedules) {
481
+ const key = schedule.key;
482
+ if (!key || !key.startsWith(projectPrefix)) continue;
483
+ if (!expectedKeys.has(key)) try {
484
+ await queue.boss.unschedule(queue.queueName, key);
485
+ } catch (error) {
486
+ failures.push({
487
+ triggerSlug: key,
488
+ error
489
+ });
490
+ console.error(`[pg-boss-trigger-scheduler] failed to unschedule stale ${key}`, error);
491
+ }
492
+ }
493
+ if (failures.length > 0) throw new Error(`pg-boss trigger scheduler reconcile failed for ${failures.length} trigger(s)`);
494
+ }
495
+ return {
496
+ async sync(syncOptions) {
497
+ await syncTriggerSchedules(syncOptions);
498
+ await reconcileFromDatabase(syncOptions.scheduleOverrides);
499
+ },
500
+ async start(_options) {
501
+ return async () => void 0;
502
+ },
503
+ fireDue: async () => 0,
504
+ upsert: upsertScheduler,
505
+ async remove(triggerSlug, projectId) {
506
+ await queue.boss.unschedule(queue.queueName, pgBossTriggerScheduleKey({
507
+ triggerSlug,
508
+ projectId
509
+ }));
510
+ }
511
+ };
512
+ }
513
+ //#endregion
514
+ //#region src/plugin.ts
515
+ function resolveUrl(ctx) {
516
+ return ctx.url ?? resolveProjectDatabaseUrlFromEnv(process.env) ?? DEFAULT_DATABASE_URL;
517
+ }
518
+ /** DB poll-loop trigger scheduler — used by the SQLite/self-host polling backend. */
519
+ function createPollingTriggerScheduler(ctx, queue) {
520
+ const scope = ctx.scope === "organization" ? "organization" : "project";
521
+ return Promise.resolve(createDatabaseTriggerScheduler({
522
+ jobQueue: queue,
523
+ scope
524
+ }));
525
+ }
526
+ function isPgBossJobQueue(queue) {
527
+ return "boss" in queue && "queueName" in queue;
528
+ }
529
+ /** Native pg-boss cron scheduler; falls back to the DB ticker if the queue isn't pg-boss. */
530
+ function createPgBossTriggerSchedulerForPlugin(ctx, queue) {
531
+ if (!isPgBossJobQueue(queue)) return createPollingTriggerScheduler(ctx, queue);
532
+ return Promise.resolve(createPgBossTriggerScheduler(ctx, queue));
533
+ }
534
+ /** Postgres pg-boss backend. Platform scope shares one queue; org scope gets one queue per org. */
535
+ function pgBossSchedulerPlugin() {
536
+ return defineSchedulerPlugin({
537
+ name: "pg-boss",
538
+ async createJobQueue(ctx) {
539
+ const url = resolveUrl(ctx);
540
+ if (ctx.scope === "platform") {
541
+ await startPgBoss(url);
542
+ return createSharedPgBossJobQueue(getPgBoss(), { connectionString: url });
543
+ }
544
+ if (ctx.scope === "organization") {
545
+ const organizationId = ctx.organizationId;
546
+ if (!organizationId) throw new Error("organizationId is required for organization-scoped pg-boss queue");
547
+ return createPgBossQueue({
548
+ connectionString: url,
549
+ queueName: pgBossOrgQueueName(organizationId),
550
+ cancelScope: "organization",
551
+ organizationId
552
+ });
553
+ }
554
+ const projectId = ctx.projectId ?? getProjectScopeId();
555
+ return createPgBossQueue({
556
+ connectionString: url,
557
+ queueName: pgBossProjectQueueName(projectId),
558
+ projectId
559
+ });
560
+ },
561
+ createTriggerScheduler: createPgBossTriggerSchedulerForPlugin
562
+ });
563
+ }
564
+ /** DB-table queue (Drizzle `jobs`), for SQLite / self-host. */
565
+ function pollingSchedulerPlugin() {
566
+ return defineSchedulerPlugin({
567
+ name: "polling",
568
+ async createJobQueue() {
569
+ return createDatabaseJobQueue();
570
+ },
571
+ createTriggerScheduler: createPollingTriggerScheduler
572
+ });
573
+ }
574
+ /** Auto-selects pg-boss (postgres) or polling (sqlite) by dialect. */
575
+ function defaultSchedulerPlugin() {
576
+ return defineSchedulerPlugin({
577
+ name: "default",
578
+ async createJobQueue(ctx) {
579
+ if (inferDialect(resolveUrl(ctx), ctx.dialect) === "postgres") return pgBossSchedulerPlugin().createJobQueue(ctx);
580
+ return pollingSchedulerPlugin().createJobQueue(ctx);
581
+ },
582
+ async createTriggerScheduler(ctx, queue) {
583
+ if (inferDialect(resolveUrl(ctx), ctx.dialect) === "postgres") return pgBossSchedulerPlugin().createTriggerScheduler(ctx, queue);
584
+ return pollingSchedulerPlugin().createTriggerScheduler(ctx, queue);
585
+ }
586
+ });
587
+ }
588
+ //#endregion
589
+ //#region src/create-scheduler.ts
590
+ async function createUnderlyingJobQueue(options = {}) {
591
+ if (options.adapter) return options.adapter;
592
+ return (options.plugin ?? defaultSchedulerPlugin()).createJobQueue({
593
+ scope: options.scope ?? "project",
594
+ url: options.url,
595
+ dialect: options.dialect,
596
+ projectId: options.projectId,
597
+ organizationId: options.organizationId
598
+ });
599
+ }
600
+ function pluginContext(options = {}) {
601
+ return {
602
+ scope: options.scope ?? "project",
603
+ url: options.url,
604
+ dialect: options.dialect,
605
+ projectId: options.projectId,
606
+ organizationId: options.organizationId
607
+ };
608
+ }
609
+ async function createTriggerScheduler(options, jobQueue) {
610
+ const scope = options.scope === "organization" ? "organization" : "project";
611
+ const plugin = options.plugin ?? defaultSchedulerPlugin();
612
+ const ctx = pluginContext(options);
613
+ if (plugin.createTriggerScheduler) return plugin.createTriggerScheduler(ctx, jobQueue);
614
+ return createDatabaseTriggerScheduler({
615
+ jobQueue,
616
+ scope
617
+ });
618
+ }
619
+ function wrapScheduler(jobQueue, triggerScheduler) {
620
+ return {
621
+ enqueue: (input) => jobQueue.enqueue(input),
622
+ startWorker: (handler, workerOptions) => jobQueue.startWorker(handler, workerOptions),
623
+ ...jobQueue.withLentSlot ? { withLentSlot: (fn) => jobQueue.withLentSlot(fn) } : {},
624
+ publishCancel: (runId) => jobQueue.publishCancel(runId),
625
+ subscribeCancel: (handler) => jobQueue.subscribeCancel(handler),
626
+ syncTriggerSchedules: (options) => triggerScheduler.sync(options),
627
+ startScheduleTicker: (options) => triggerScheduler.start(options),
628
+ fireDueSchedules: (asOf) => triggerScheduler.fireDue?.(asOf) ?? Promise.resolve(0),
629
+ ...triggerScheduler.upsert ? { upsertTriggerSchedule: (spec, overrides) => triggerScheduler.upsert(spec, overrides) } : {},
630
+ ...triggerScheduler.remove ? { removeTriggerSchedule: (triggerSlug, projectId) => triggerScheduler.remove(triggerSlug, projectId) } : {}
631
+ };
632
+ }
633
+ async function createScheduler(options = {}) {
634
+ const jobQueue = await createUnderlyingJobQueue(options);
635
+ return wrapScheduler(jobQueue, await createTriggerScheduler(options, jobQueue));
636
+ }
637
+ async function createJobQueue(options = {}) {
638
+ return createUnderlyingJobQueue(options);
639
+ }
640
+ async function wrapJobQueueAsScheduler(jobQueue, scope) {
641
+ return wrapScheduler(jobQueue, createDatabaseTriggerScheduler({
642
+ jobQueue,
643
+ scope
644
+ }));
645
+ }
646
+ //#endregion
647
+ //#region src/memory.ts
648
+ function createMemoryJobQueue(options = {}) {
649
+ const cancelChannel = createInProcessCancelChannel();
650
+ const pending = [];
651
+ let handler;
652
+ let draining = false;
653
+ async function drain() {
654
+ if (!handler || draining) return;
655
+ draining = true;
656
+ try {
657
+ while (pending.length > 0) {
658
+ const next = pending.shift();
659
+ if (!next) break;
660
+ const input = next.input;
661
+ await handler({
662
+ jobId: next.id,
663
+ kind: input.kind,
664
+ targetId: input.targetId,
665
+ runId: input.runId,
666
+ trigger: input.trigger,
667
+ payload: input.payload ?? {},
668
+ attempt: input.attempt ?? 1,
669
+ maxAttempts: input.maxAttempts ?? 3,
670
+ scheduledAt: input.scheduledAt ?? next.enqueuedAt,
671
+ ...input.parent ? { parent: input.parent } : {},
672
+ ...input.traceContext ? { traceContext: input.traceContext } : {}
673
+ });
674
+ }
675
+ } finally {
676
+ draining = false;
677
+ }
678
+ }
679
+ return {
680
+ async enqueue(input) {
681
+ const id = crypto.randomUUID();
682
+ pending.push({
683
+ id,
684
+ input,
685
+ enqueuedAt: /* @__PURE__ */ new Date()
686
+ });
687
+ if (options.sync) await drain();
688
+ return id;
689
+ },
690
+ async startWorker(nextHandler, _opts = {}) {
691
+ handler = nextHandler;
692
+ if (!options.sync) drain();
693
+ return async () => {
694
+ handler = void 0;
695
+ };
696
+ },
697
+ publishCancel: (runId) => cancelChannel.publishCancel(runId),
698
+ subscribeCancel: (handler) => cancelChannel.subscribeCancel(handler)
699
+ };
700
+ }
701
+ //#endregion
702
+ //#region src/shared-pgboss-queue.ts
703
+ let sharedJobQueue$1;
704
+ async function createSharedPgBossScheduler() {
705
+ return await wrapJobQueueAsScheduler(await getSharedPgBossJobQueue());
706
+ }
707
+ async function getSharedPgBossJobQueue() {
708
+ if (sharedJobQueue$1) return sharedJobQueue$1;
709
+ const connectionString = resolvePostgresUrlFromEnv(process.env);
710
+ if (!connectionString) throw new Error("Postgres connection string is required for shared pg-boss queue");
711
+ sharedJobQueue$1 = await createSharedPgBossJobQueue(getPgBoss(), { connectionString });
712
+ return sharedJobQueue$1;
713
+ }
714
+ function resetSharedPgBossJobQueueForTests() {
715
+ sharedJobQueue$1 = void 0;
716
+ }
717
+ //#endregion
718
+ //#region src/shared-scheduler.ts
719
+ let configuredPlugin;
720
+ let sharedJobQueue;
721
+ function configureSharedScheduler(plugin) {
722
+ configuredPlugin = plugin;
723
+ sharedJobQueue = void 0;
724
+ }
725
+ async function createSharedScheduler() {
726
+ const plugin = configuredPlugin ?? defaultSchedulerPlugin();
727
+ if (plugin.name === "default") return createSharedPgBossScheduler();
728
+ if (!sharedJobQueue) sharedJobQueue = await plugin.createJobQueue({ scope: "platform" });
729
+ return await wrapJobQueueAsScheduler(sharedJobQueue);
730
+ }
731
+ function resetSharedSchedulerForTests() {
732
+ configuredPlugin = void 0;
733
+ sharedJobQueue = void 0;
734
+ resetSharedPgBossJobQueueForTests();
735
+ }
736
+ //#endregion
737
+ export { DEFAULT_QUEUE_NAME, DEFAULT_RETRY_DELAY_MS, buildPgBossJobQueue, configureSharedScheduler, createDatabaseTriggerScheduler, createJobQueue, createMemoryJobQueue, createPgBossTriggerScheduler, createScheduler, createSharedPgBossJobQueue, createSharedPgBossScheduler, createSharedScheduler, defaultSchedulerPlugin, defineSchedulerPlugin, getPgBoss, getSharedPgBossJobQueue, pgBossProjectQueueName, pgBossSchedulerPlugin, pgBossTriggerScheduleKey, pgBossTriggerScheduleKeyPrefix, pollingSchedulerPlugin, resetSharedPgBossJobQueueForTests, resetSharedSchedulerForTests, resolveTriggerSchedule, retryDelayMs, startPgBoss, stopPgBoss, syncTriggerSchedules, wrapJobQueueAsScheduler };
738
+
739
+ //# sourceMappingURL=index.mjs.map