-
Notifications
You must be signed in to change notification settings - Fork 3.8k
Expand file tree
/
Copy pathroute.ts
More file actions
1314 lines (1192 loc) · 41.9 KB
/
Copy pathroute.ts
File metadata and controls
1314 lines (1192 loc) · 41.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { asyncJobs, db, workflow, workflowDeploymentVersion, workflowSchedule } from '@sim/db'
import { createLogger } from '@sim/logger'
import { sha256Hex } from '@sim/security/hash'
import { toError } from '@sim/utils/errors'
import { sleep } from '@sim/utils/helpers'
import { generateId } from '@sim/utils/id'
import { randomInt } from '@sim/utils/random'
import { Cron } from 'croner'
import { and, asc, eq, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm'
import { type NextRequest, NextResponse } from 'next/server'
import type { ExecuteSchedulesResponse } from '@/lib/api/contracts/schedules'
import { verifyCronAuth } from '@/lib/auth/internal'
import {
assertBillingAttributionSnapshot,
type BillingAttributionSnapshot,
resolveSystemBillingAttribution,
} from '@/lib/billing/core/billing-attribution'
import { getJobQueue, shouldExecuteInline } from '@/lib/core/async-jobs'
import { JOB_STATUS, type Job } from '@/lib/core/async-jobs/types'
import { isRetryableInfrastructureError } from '@/lib/core/errors/retryable-infrastructure'
import { getMaxExecutionTimeout } from '@/lib/core/execution-limits'
import { runDetached } from '@/lib/core/utils/background'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
SCHEDULE_EXECUTION_CONCURRENCY_LIMIT,
SCHEDULE_EXECUTION_QUEUE_NAME,
SCHEDULE_INFRA_RETRY_MAX_ATTEMPTS,
SCHEDULE_JITTER_MAX_MS,
SCHEDULE_WORKFLOW_ENQUEUE_LIMIT,
} from '@/lib/workflows/schedules/execution-limits'
import { calculateScheduleInfraRetryDelayMs } from '@/lib/workflows/schedules/retry'
import {
buildScheduleFailureUpdate,
executeJobInline,
executeScheduleJob,
releaseScheduleLock,
type ScheduleExecutionPayload,
} from '@/background/schedule-execution'
export const dynamic = 'force-dynamic'
export const maxDuration = 3600
const logger = createLogger('ScheduledExecuteAPI')
const WORKFLOW_CHUNK_SIZE = 100
const JOB_CHUNK_SIZE = 100
const MAX_TICK_DURATION_MS = 3 * 60 * 1000
const STALE_SCHEDULE_CLAIM_MS = getMaxExecutionTimeout()
const STALE_SCHEDULE_RECOVERY_BATCH_SIZE = 100
const DATABASE_SCHEDULE_START_TURN_WAIT_MS = 1_000
type DatabaseScheduleStartResult = 'started' | 'capacity_full' | 'not_pending'
let databaseScheduleStartTurn: Promise<void> | null = null
const dueFilter = (queuedAt: Date) =>
and(
isNull(workflowSchedule.archivedAt),
lte(workflowSchedule.nextRunAt, queuedAt),
sql`${workflowSchedule.status} NOT IN ('disabled', 'completed')`,
or(
isNull(workflowSchedule.lastQueuedAt),
lt(workflowSchedule.lastQueuedAt, workflowSchedule.nextRunAt),
lt(workflowSchedule.lastQueuedAt, new Date(queuedAt.getTime() - STALE_SCHEDULE_CLAIM_MS))
)
)
const activeWorkflowDeploymentFilter = () =>
sql`${workflowSchedule.deploymentVersionId} = (select ${workflowDeploymentVersion.id} from ${workflowDeploymentVersion} where ${workflowDeploymentVersion.workflowId} = ${workflowSchedule.workflowId} and ${workflowDeploymentVersion.isActive} = true)`
const workflowScheduleFilter = (queuedAt: Date) =>
and(
dueFilter(queuedAt),
sql`(${workflowSchedule.sourceType} = 'workflow' OR ${workflowSchedule.sourceType} IS NULL)`,
activeWorkflowDeploymentFilter()
)
const jobScheduleFilter = (queuedAt: Date) =>
and(dueFilter(queuedAt), sql`${workflowSchedule.sourceType} = 'job'`)
async function runWithDatabaseScheduleStartTurn(
operation: () => Promise<DatabaseScheduleStartResult>
): Promise<DatabaseScheduleStartResult> {
const activeTurn = databaseScheduleStartTurn
if (activeTurn) {
const turnOpened = await Promise.race([
activeTurn.then(() => true),
sleep(DATABASE_SCHEDULE_START_TURN_WAIT_MS).then(() => false),
])
if (!turnOpened || databaseScheduleStartTurn) return 'capacity_full'
}
let releaseTurn = () => {}
const currentTurn = new Promise<void>((resolve) => {
releaseTurn = resolve
})
databaseScheduleStartTurn = currentTurn
try {
return await operation()
} finally {
if (databaseScheduleStartTurn === currentTurn) {
databaseScheduleStartTurn = null
}
releaseTurn()
}
}
function buildScheduleExecutionJobId(schedule: {
id: string
nextRunAt?: Date | null
lastQueuedAt?: Date | null
}): string {
const occurrence =
schedule.nextRunAt?.toISOString() ?? schedule.lastQueuedAt?.toISOString() ?? 'due'
return `schedule_${sha256Hex(`${schedule.id}:${occurrence}`).slice(0, 32)}`
}
function getNextRunFromCronExpression(
cronExpression?: string | null,
timezone = 'UTC'
): Date | null {
if (!cronExpression) return null
const cron = new Cron(cronExpression, { timezone })
return cron.nextRun()
}
async function claimWorkflowSchedules(queuedAt: Date, limit: number) {
if (limit <= 0) return []
return db.transaction(async (tx) => {
const rows = await tx
.select({
id: workflowSchedule.id,
workspaceId: workflow.workspaceId,
})
.from(workflowSchedule)
.innerJoin(workflow, eq(workflowSchedule.workflowId, workflow.id))
.where(workflowScheduleFilter(queuedAt))
.for('update', { skipLocked: true })
.limit(limit)
if (rows.length === 0) return []
const workspaceIdsByScheduleId = new Map(rows.map((row) => [row.id, row.workspaceId]))
const claimedRows = await tx
.update(workflowSchedule)
.set({ lastQueuedAt: queuedAt, updatedAt: queuedAt })
.where(
and(
workflowScheduleFilter(queuedAt),
inArray(
workflowSchedule.id,
rows.map((row) => row.id)
)
)
)
.returning({
id: workflowSchedule.id,
workflowId: workflowSchedule.workflowId,
blockId: workflowSchedule.blockId,
cronExpression: workflowSchedule.cronExpression,
lastRanAt: workflowSchedule.lastRanAt,
failedCount: workflowSchedule.failedCount,
infraRetryCount: workflowSchedule.infraRetryCount,
nextRunAt: workflowSchedule.nextRunAt,
lastQueuedAt: workflowSchedule.lastQueuedAt,
timezone: workflowSchedule.timezone,
deploymentVersionId: workflowSchedule.deploymentVersionId,
deploymentOperationId: workflowSchedule.deploymentOperationId,
sourceType: workflowSchedule.sourceType,
})
return claimedRows.map((row) => ({
...row,
workspaceId: workspaceIdsByScheduleId.get(row.id) ?? null,
}))
})
}
async function claimJobSchedules(queuedAt: Date, limit: number) {
if (limit <= 0) return []
return db.transaction(async (tx) => {
const rows = await tx
.select({ id: workflowSchedule.id })
.from(workflowSchedule)
.where(jobScheduleFilter(queuedAt))
.for('update', { skipLocked: true })
.limit(limit)
if (rows.length === 0) return []
return tx
.update(workflowSchedule)
.set({ lastQueuedAt: queuedAt, updatedAt: queuedAt })
.where(
and(
jobScheduleFilter(queuedAt),
inArray(
workflowSchedule.id,
rows.map((row) => row.id)
)
)
)
.returning({
id: workflowSchedule.id,
cronExpression: workflowSchedule.cronExpression,
timezone: workflowSchedule.timezone,
failedCount: workflowSchedule.failedCount,
lastQueuedAt: workflowSchedule.lastQueuedAt,
sourceType: workflowSchedule.sourceType,
})
})
}
type ClaimedSchedule = Awaited<ReturnType<typeof claimWorkflowSchedules>>[number]
type ClaimedJob = Awaited<ReturnType<typeof claimJobSchedules>>[number]
type JobQueue = Awaited<ReturnType<typeof getJobQueue>>
type DatabaseScheduleExecutionTarget = Pick<
ClaimedSchedule,
'id' | 'workflowId' | 'cronExpression' | 'timezone'
>
type ScheduleRecoveryMetadata = Pick<
ScheduleExecutionPayload,
'scheduleId' | 'workflowId' | 'now' | 'cronExpression' | 'timezone'
>
type SchedulePayloadValidation =
| { success: true; payload: ScheduleExecutionPayload }
| { success: false; error: string }
function getScheduleRecoveryMetadataFromValue(payload: unknown): ScheduleRecoveryMetadata | null {
if (!payload || typeof payload !== 'object') return null
const candidate = payload as Record<string, unknown>
if (
typeof candidate.scheduleId !== 'string' ||
typeof candidate.workflowId !== 'string' ||
typeof candidate.now !== 'string'
) {
return null
}
return {
scheduleId: candidate.scheduleId,
workflowId: candidate.workflowId,
now: candidate.now,
cronExpression:
typeof candidate.cronExpression === 'string' ? candidate.cronExpression : undefined,
timezone: typeof candidate.timezone === 'string' ? candidate.timezone : undefined,
}
}
function getScheduleRecoveryMetadataFromJob(job: Job): ScheduleRecoveryMetadata | null {
return getScheduleRecoveryMetadataFromValue(job.payload)
}
function getSchedulePayloadValidation(payload: unknown): SchedulePayloadValidation {
const metadata = getScheduleRecoveryMetadataFromValue(payload)
if (!metadata || !payload || typeof payload !== 'object') {
return { success: false, error: 'recovery metadata is invalid' }
}
const candidate = payload as Record<string, unknown>
if (typeof candidate.workspaceId !== 'string' || candidate.workspaceId.length === 0) {
return { success: false, error: 'workspaceId is required' }
}
if (candidate.billingAttribution === undefined || candidate.billingAttribution === null) {
return { success: false, error: 'billingAttribution is required' }
}
let billingAttribution: BillingAttributionSnapshot
try {
billingAttribution = assertBillingAttributionSnapshot(candidate.billingAttribution)
} catch (error) {
return { success: false, error: toError(error).message }
}
if (billingAttribution.workspaceId !== candidate.workspaceId) {
return {
success: false,
error: 'billing attribution workspace does not match payload workspace',
}
}
if (billingAttribution.actorUserId !== billingAttribution.billedAccountUserId) {
return {
success: false,
error: 'billing attribution actor does not match billed account',
}
}
return {
success: true,
payload: {
...metadata,
workspaceId: candidate.workspaceId,
billingAttribution,
executionId: typeof candidate.executionId === 'string' ? candidate.executionId : undefined,
requestId: typeof candidate.requestId === 'string' ? candidate.requestId : undefined,
blockId: typeof candidate.blockId === 'string' ? candidate.blockId : undefined,
deploymentVersionId:
typeof candidate.deploymentVersionId === 'string'
? candidate.deploymentVersionId
: undefined,
lastRanAt: typeof candidate.lastRanAt === 'string' ? candidate.lastRanAt : undefined,
failedCount: typeof candidate.failedCount === 'number' ? candidate.failedCount : undefined,
infraRetryCount:
typeof candidate.infraRetryCount === 'number' ? candidate.infraRetryCount : undefined,
scheduledFor: typeof candidate.scheduledFor === 'string' ? candidate.scheduledFor : undefined,
},
}
}
function getSchedulePayloadClaimedAt(payload: ScheduleRecoveryMetadata | null): Date | null {
if (!payload) return null
const claimedAt = new Date(payload.now)
return Number.isNaN(claimedAt.getTime()) ? null : claimedAt
}
async function restoreScheduleClaim(
scheduleId: string,
requestId: string,
currentClaim: Date,
activeClaim: Date,
context: string
): Promise<void> {
if (currentClaim.getTime() === activeClaim.getTime()) return
const [restored] = await db
.update(workflowSchedule)
.set({ lastQueuedAt: activeClaim, updatedAt: new Date() })
.where(
and(
eq(workflowSchedule.id, scheduleId),
isNull(workflowSchedule.archivedAt),
eq(workflowSchedule.lastQueuedAt, currentClaim)
)
)
.returning({ id: workflowSchedule.id })
.catch((error) => {
logger.error(`[${requestId}] ${context}`, error)
throw error
})
if (!restored) {
const error = new Error(`Schedule claim restore did not update schedule ${scheduleId}`)
logger.warn(`[${requestId}] ${context}`, {
scheduleId,
currentClaim: currentClaim.toISOString(),
activeClaim: activeClaim.toISOString(),
})
throw error
}
}
function getStaleScheduleExecutionCutoff(now: Date): Date {
return new Date(now.getTime() - STALE_SCHEDULE_CLAIM_MS)
}
function isStaleScheduleClaim(claimedAt: Date): boolean {
return claimedAt < getStaleScheduleExecutionCutoff(new Date())
}
function activeScheduleExecutionJobsFilter() {
return sql`${asyncJobs.type} = 'schedule-execution' AND ${asyncJobs.status} = 'processing'`
}
function pendingScheduleExecutionJobsFilter(now: Date) {
return and(
sql`${asyncJobs.type} = 'schedule-execution' AND ${asyncJobs.status} = 'pending'`,
sql`${asyncJobs.attempts} < ${asyncJobs.maxAttempts}`,
or(isNull(asyncJobs.runAt), lte(asyncJobs.runAt, now))
)
}
function staleScheduleExecutionJobsFilter(staleStartedBefore: Date) {
return and(
activeScheduleExecutionJobsFilter(),
or(isNull(asyncJobs.startedAt), lt(asyncJobs.startedAt, staleStartedBefore))
)
}
function getScheduleNextRunAt(
schedule: { cronExpression?: string | null; timezone?: string },
now: Date
): Date {
return (
getNextRunFromCronExpression(schedule.cronExpression, schedule.timezone) ??
new Date(now.getTime() + 24 * 60 * 60 * 1000)
)
}
async function markClaimedScheduleFailed(
schedule: DatabaseScheduleExecutionTarget,
requestId: string,
expectedLastQueuedAt: Date,
context: string
): Promise<void> {
const now = new Date()
await db
.update(workflowSchedule)
.set(buildScheduleFailureUpdate(now, getScheduleNextRunAt(schedule, now)))
.where(
and(
eq(workflowSchedule.id, schedule.id),
isNull(workflowSchedule.archivedAt),
eq(workflowSchedule.lastQueuedAt, expectedLastQueuedAt)
)
)
.catch((error) => {
logger.error(`[${requestId}] ${context}`, error)
throw error
})
}
async function deferClaimedScheduleAfterQueueFailure(
schedule: ClaimedSchedule,
requestId: string,
expectedLastQueuedAt: Date,
error: unknown,
context: string
): Promise<void> {
const now = new Date()
const retryAttempt = (schedule.infraRetryCount || 0) + 1
if (retryAttempt > SCHEDULE_INFRA_RETRY_MAX_ATTEMPTS) {
await markClaimedScheduleFailed(
schedule,
requestId,
expectedLastQueuedAt,
`Failed to mark schedule ${schedule.id} failed after queue retry exhaustion`
)
return
}
const retryDelayMs = calculateScheduleInfraRetryDelayMs(retryAttempt)
const nextRetryAt = new Date(now.getTime() + retryDelayMs)
logger.warn(`[${requestId}] Deferring schedule after queue infrastructure failure`, {
scheduleId: schedule.id,
workflowId: schedule.workflowId,
retryAttempt,
retryDelayMs,
error: toError(error).message,
})
await db
.update(workflowSchedule)
.set({
updatedAt: now,
nextRunAt: nextRetryAt,
lastQueuedAt: null,
infraRetryCount: retryAttempt,
})
.where(
and(
eq(workflowSchedule.id, schedule.id),
isNull(workflowSchedule.archivedAt),
eq(workflowSchedule.lastQueuedAt, expectedLastQueuedAt)
)
)
.catch((updateError) => {
logger.error(`[${requestId}] ${context}`, updateError)
throw updateError
})
}
async function handleClaimedScheduleSetupFailure(
schedule: ClaimedSchedule,
requestId: string,
expectedLastQueuedAt: Date,
error: unknown,
retryContext: string,
failureContext: string
): Promise<void> {
if (isRetryableInfrastructureError(error)) {
await deferClaimedScheduleAfterQueueFailure(
schedule,
requestId,
expectedLastQueuedAt,
error,
retryContext
)
return
}
logger.error(`[${requestId}] Non-retryable schedule setup failure`, {
scheduleId: schedule.id,
workflowId: schedule.workflowId,
error: toError(error).message,
})
await markClaimedScheduleFailed(schedule, requestId, expectedLastQueuedAt, failureContext)
}
async function recoverStaleDatabaseScheduleJobs(now: Date): Promise<void> {
const staleStartedBefore = getStaleScheduleExecutionCutoff(now)
await db.transaction(async (tx) => {
const [lock] = await tx.execute<{ acquired: boolean }>(
sql`SELECT pg_try_advisory_xact_lock(hashtextextended(${SCHEDULE_EXECUTION_QUEUE_NAME}, 0)) AS acquired`
)
if (!lock?.acquired) {
logger.info(
'Skipped stale database schedule job recovery because another worker holds the lock'
)
return
}
const staleRows = await tx
.select({
id: asyncJobs.id,
payload: asyncJobs.payload,
attempts: asyncJobs.attempts,
maxAttempts: asyncJobs.maxAttempts,
})
.from(asyncJobs)
.where(staleScheduleExecutionJobsFilter(staleStartedBefore))
.orderBy(asc(asyncJobs.startedAt), asc(asyncJobs.id))
.limit(STALE_SCHEDULE_RECOVERY_BATCH_SIZE)
const exhaustedRows = staleRows.filter((row) => row.attempts >= row.maxAttempts)
const retryableRows = staleRows.filter((row) => row.attempts < row.maxAttempts)
if (exhaustedRows.length > 0) {
await tx
.update(asyncJobs)
.set({
status: JOB_STATUS.FAILED,
completedAt: now,
error: 'Stale schedule execution processing lease exhausted retry attempts',
updatedAt: now,
})
.where(
inArray(
asyncJobs.id,
exhaustedRows.map((row) => row.id)
)
)
}
for (const row of exhaustedRows) {
const payload = getScheduleRecoveryMetadataFromValue(row.payload)
const claimedAt = getSchedulePayloadClaimedAt(payload)
if (!payload || !claimedAt) continue
await tx
.update(workflowSchedule)
.set(buildScheduleFailureUpdate(now, getScheduleNextRunAt(payload, now)))
.where(
and(
eq(workflowSchedule.id, payload.scheduleId),
isNull(workflowSchedule.archivedAt),
eq(workflowSchedule.lastQueuedAt, claimedAt)
)
)
}
if (retryableRows.length > 0) {
await tx
.update(asyncJobs)
.set({
status: JOB_STATUS.PENDING,
startedAt: null,
error: 'Recovered after stale schedule execution processing lease',
updatedAt: now,
})
.where(
inArray(
asyncJobs.id,
retryableRows.map((row) => row.id)
)
)
}
})
}
function isStaleDatabaseScheduleJob(job: { status: string; startedAt?: Date }): boolean {
return (
job.status === JOB_STATUS.PROCESSING &&
(!job.startedAt || job.startedAt < getStaleScheduleExecutionCutoff(new Date()))
)
}
async function getDatabaseScheduleExecutionSlots(): Promise<number> {
const [row] = await db
.select({
count: sql<number>`count(*)`,
})
.from(asyncJobs)
.where(activeScheduleExecutionJobsFilter())
const processingCount = Number(row?.count ?? 0)
return Math.max(0, SCHEDULE_EXECUTION_CONCURRENCY_LIMIT - processingCount)
}
async function tryStartDatabaseScheduleJob(jobId: string): Promise<DatabaseScheduleStartResult> {
const now = new Date()
return db.transaction(async (tx) => {
const [lock] = await tx.execute<{ acquired: boolean }>(
sql`SELECT pg_try_advisory_xact_lock(hashtextextended(${SCHEDULE_EXECUTION_QUEUE_NAME}, 0)) AS acquired`
)
if (!lock?.acquired) return 'capacity_full'
const [row] = await tx
.select({
count: sql<number>`count(*)`,
})
.from(asyncJobs)
.where(activeScheduleExecutionJobsFilter())
if (Number(row?.count ?? 0) >= SCHEDULE_EXECUTION_CONCURRENCY_LIMIT) {
return 'capacity_full'
}
const [startedJob] = await tx
.update(asyncJobs)
.set({
status: JOB_STATUS.PROCESSING,
startedAt: now,
attempts: sql`${asyncJobs.attempts} + 1`,
updatedAt: now,
})
.where(and(eq(asyncJobs.id, jobId), eq(asyncJobs.status, JOB_STATUS.PENDING)))
.returning({ id: asyncJobs.id })
return startedJob ? 'started' : 'not_pending'
})
}
async function executeDatabaseScheduleJob(
jobQueue: JobQueue,
jobId: string,
payload: ScheduleExecutionPayload,
schedule: DatabaseScheduleExecutionTarget,
queuedAt: Date,
requestId: string,
delayMs: number
): Promise<void> {
if (delayMs > 0) await sleep(delayMs)
const startResult = await runWithDatabaseScheduleStartTurn(() =>
tryStartDatabaseScheduleJob(jobId)
)
if (startResult === 'not_pending') {
logger.info(`[${requestId}] Database schedule execution job is no longer pending`, {
scheduleId: schedule.id,
workflowId: schedule.workflowId,
jobId,
})
return
}
if (startResult === 'capacity_full') {
logger.info(`[${requestId}] Deferred database schedule execution because capacity is full`, {
scheduleId: schedule.id,
workflowId: schedule.workflowId,
jobId,
concurrencyLimit: SCHEDULE_EXECUTION_CONCURRENCY_LIMIT,
})
return
}
try {
const output = await executeScheduleJob(payload)
await jobQueue.completeJob(jobId, output ?? null)
} catch (error) {
const errorMessage = toError(error).message
logger.error(`[${requestId}] Schedule execution failed for workflow ${schedule.workflowId}`, {
scheduleId: schedule.id,
jobId,
error: errorMessage,
})
await jobQueue.markJobFailed(jobId, errorMessage)
await releaseScheduleLock(
schedule.id,
requestId,
new Date(),
`Failed to release lock for schedule ${schedule.id} after inline execution failure`,
undefined,
{ expectedLastQueuedAt: queuedAt }
)
}
}
async function getPendingDatabaseScheduleJobs(limit: number) {
if (limit <= 0) return []
const now = new Date()
return db
.select({
id: asyncJobs.id,
payload: asyncJobs.payload,
})
.from(asyncJobs)
.where(pendingScheduleExecutionJobsFilter(now))
.orderBy(asc(asyncJobs.runAt), asc(asyncJobs.createdAt), asc(asyncJobs.id))
.limit(limit)
}
function getScheduleTargetFromPayload(
payload: ScheduleExecutionPayload
): DatabaseScheduleExecutionTarget {
return {
id: payload.scheduleId,
workflowId: payload.workflowId,
cronExpression: payload.cronExpression ?? null,
timezone: payload.timezone ?? 'UTC',
}
}
async function getScheduleClaimState(
payload: ScheduleRecoveryMetadata,
claimedAt: Date
): Promise<'matches' | 'released' | 'claimed_by_other'> {
const [schedule] = await db
.select({
lastQueuedAt: workflowSchedule.lastQueuedAt,
})
.from(workflowSchedule)
.where(and(eq(workflowSchedule.id, payload.scheduleId), isNull(workflowSchedule.archivedAt)))
.limit(1)
if (!schedule?.lastQueuedAt) return 'released'
return schedule.lastQueuedAt.getTime() === claimedAt.getTime() ? 'matches' : 'claimed_by_other'
}
async function resumePendingDatabaseScheduleJobs(
jobQueue: JobQueue,
requestId: string,
slots: number
): Promise<number> {
const pendingJobs = await getPendingDatabaseScheduleJobs(slots)
if (pendingJobs.length === 0) return 0
const results = await Promise.allSettled(
pendingJobs.map(async (job) => {
const recoveryMetadata = getScheduleRecoveryMetadataFromValue(job.payload)
const claimedAt = getSchedulePayloadClaimedAt(recoveryMetadata)
if (!recoveryMetadata || !claimedAt) {
await jobQueue.markJobFailed(job.id, 'Invalid pending schedule recovery metadata')
return true
}
const claimState = await getScheduleClaimState(recoveryMetadata, claimedAt)
if (claimState === 'released') {
logger.info(`[${requestId}] Completing stale pending schedule execution job`, {
scheduleId: recoveryMetadata.scheduleId,
workflowId: recoveryMetadata.workflowId,
jobId: job.id,
})
await jobQueue.completeJob(job.id, {
skipped: true,
reason: 'schedule claim no longer matches pending job occurrence',
})
return true
}
if (claimState === 'claimed_by_other') {
logger.info(`[${requestId}] Leaving pending schedule execution job for active claimant`, {
scheduleId: recoveryMetadata.scheduleId,
workflowId: recoveryMetadata.workflowId,
jobId: job.id,
})
return false
}
const payloadValidation = getSchedulePayloadValidation(job.payload)
if (!payloadValidation.success) {
const error = `Invalid pending schedule execution payload: ${payloadValidation.error}`
logger.warn(`[${requestId}] Rejecting invalid pending schedule execution payload`, {
scheduleId: recoveryMetadata.scheduleId,
workflowId: recoveryMetadata.workflowId,
jobId: job.id,
error,
})
await jobQueue.markJobFailed(job.id, error)
await releaseScheduleLock(
recoveryMetadata.scheduleId,
requestId,
new Date(),
`Released schedule ${recoveryMetadata.scheduleId} after rejecting invalid pending schedule execution payload`,
undefined,
{ expectedLastQueuedAt: claimedAt }
)
return true
}
logger.info(`[${requestId}] Resuming pending database schedule execution job`, {
scheduleId: recoveryMetadata.scheduleId,
workflowId: recoveryMetadata.workflowId,
jobId: job.id,
})
await executeDatabaseScheduleJob(
jobQueue,
job.id,
payloadValidation.payload,
getScheduleTargetFromPayload(payloadValidation.payload),
claimedAt,
requestId,
0
)
return true
})
)
let processedCount = 0
results.forEach((result, index) => {
if (result.status === 'fulfilled' && result.value) {
processedCount += 1
return
}
if (result.status === 'rejected') {
logger.error(`[${requestId}] Failed to resume pending database schedule execution job`, {
jobId: pendingJobs[index]?.id,
error: toError(result.reason).message,
})
}
})
return processedCount
}
async function processScheduleItem(
schedule: ClaimedSchedule,
queuedAt: Date,
requestId: string,
jobQueue: JobQueue,
useDatabaseFallback: boolean
) {
const queueTime = schedule.lastQueuedAt ?? queuedAt
const executionId = generateId()
const workspaceId = schedule.workspaceId ?? undefined
let billingAttribution: BillingAttributionSnapshot
try {
if (!workspaceId) {
throw new Error(`Unable to resolve workspace for schedule ${schedule.id}`)
}
billingAttribution = await resolveSystemBillingAttribution(workspaceId)
} catch (error) {
await handleClaimedScheduleSetupFailure(
schedule,
requestId,
queueTime,
error,
`Failed to defer schedule ${schedule.id} after billing attribution failure`,
`Failed to mark schedule ${schedule.id} failed after billing attribution failure`
)
return
}
const correlation = {
executionId,
requestId,
source: 'schedule' as const,
workflowId: schedule.workflowId!,
scheduleId: schedule.id,
triggerType: 'schedule',
scheduledFor: schedule.nextRunAt?.toISOString(),
}
const payload = {
scheduleId: schedule.id,
workflowId: schedule.workflowId!,
executionId,
requestId,
correlation,
blockId: schedule.blockId || undefined,
workspaceId,
billingAttribution,
deploymentVersionId: schedule.deploymentVersionId || undefined,
deploymentOperationId: schedule.deploymentOperationId || undefined,
cronExpression: schedule.cronExpression || undefined,
timezone: schedule.timezone || undefined,
lastRanAt: schedule.lastRanAt?.toISOString(),
failedCount: schedule.failedCount || 0,
infraRetryCount: schedule.infraRetryCount || 0,
now: queueTime.toISOString(),
scheduledFor: schedule.nextRunAt?.toISOString(),
} satisfies ScheduleExecutionPayload
let enqueuedJobId: string | null = null
try {
const delayMs = randomInt(0, SCHEDULE_JITTER_MAX_MS)
const scheduleJobId = buildScheduleExecutionJobId(schedule)
const existingJob = await jobQueue.getJob(scheduleJobId)
if (existingJob && ['pending', 'processing'].includes(existingJob.status)) {
const activeJobPayload = getScheduleRecoveryMetadataFromJob(existingJob)
const activeJobClaim = getSchedulePayloadClaimedAt(activeJobPayload)
if (useDatabaseFallback && isStaleDatabaseScheduleJob(existingJob)) {
await recoverStaleDatabaseScheduleJobs(new Date())
logger.info(`[${requestId}] Recovered stale database schedule execution jobs`, {
scheduleId: schedule.id,
jobId: scheduleJobId,
})
}
const databaseJob = useDatabaseFallback ? await jobQueue.getJob(scheduleJobId) : existingJob
const databaseJobPayload = databaseJob
? getScheduleRecoveryMetadataFromJob(databaseJob)
: null
const databaseJobClaim = getSchedulePayloadClaimedAt(databaseJobPayload) ?? activeJobClaim
if (!useDatabaseFallback && activeJobClaim && isStaleScheduleClaim(activeJobClaim)) {
logger.warn(`[${requestId}] Cancelling stale schedule execution job`, {
scheduleId: schedule.id,
jobId: existingJob.id,
claimedAt: activeJobClaim.toISOString(),
})
await jobQueue.cancelJob(existingJob.id)
await releaseScheduleLock(
schedule.id,
requestId,
queuedAt,
`Released stale schedule ${schedule.id} after cancelling stale schedule execution job`,
undefined,
{ expectedLastQueuedAt: queueTime }
)
return
}
if (useDatabaseFallback && databaseJob?.status === JOB_STATUS.PENDING) {
const payloadValidation = getSchedulePayloadValidation(databaseJob.payload)
if (!payloadValidation.success) {
const error = `Invalid pending schedule execution payload: ${payloadValidation.error}`
logger.warn(`[${requestId}] Rejecting invalid pending schedule execution payload`, {
scheduleId: schedule.id,
workflowId: schedule.workflowId,
jobId: scheduleJobId,
error,
})
enqueuedJobId = scheduleJobId
await jobQueue.markJobFailed(scheduleJobId, error)
await releaseScheduleLock(
schedule.id,
requestId,
queuedAt,
`Released schedule ${schedule.id} after rejecting invalid pending schedule execution payload`,
undefined,
{ expectedLastQueuedAt: queueTime }
)
return
}
logger.info(`[${requestId}] Resuming pending database schedule execution job`, {
scheduleId: schedule.id,
jobId: scheduleJobId,
})
if (databaseJobClaim) {
await restoreScheduleClaim(
schedule.id,
requestId,
queueTime,
databaseJobClaim,
`Failed to restore schedule ${schedule.id} claim for pending database fallback job`
)
}
enqueuedJobId = scheduleJobId
await executeDatabaseScheduleJob(
jobQueue,
scheduleJobId,
payloadValidation.payload,
schedule,
databaseJobClaim ?? queueTime,
requestId,
delayMs
)
return
}
if (
useDatabaseFallback &&
databaseJob &&
databaseJob.status !== JOB_STATUS.PENDING &&
databaseJob.status !== JOB_STATUS.PROCESSING
) {
logger.info(`[${requestId}] Database schedule execution job reached terminal state`, {
scheduleId: schedule.id,
jobId: scheduleJobId,
status: databaseJob.status,
})
if (databaseJob.status === JOB_STATUS.FAILED) {
await markClaimedScheduleFailed(
schedule,
requestId,
queueTime,
`Failed to mark schedule ${schedule.id} failed after terminal database fallback job`
)
return
}
await releaseScheduleLock(
schedule.id,
requestId,
queuedAt,
`Released stale schedule ${schedule.id} for terminal database fallback job ${scheduleJobId}`,
getNextRunFromCronExpression(schedule.cronExpression, schedule.timezone),
{ expectedLastQueuedAt: queueTime }
)
return
}
logger.info(`[${requestId}] Schedule execution job already exists`, {