( workflowId: string, blocks: Record<string, BlockState>, tx?: DbOrTx, deploymentVersionId?: string )
| 28 | * is provided, otherwise inside a transaction opened here. |
| 29 | */ |
| 30 | export async function createSchedulesForDeploy( |
| 31 | workflowId: string, |
| 32 | blocks: Record<string, BlockState>, |
| 33 | tx?: DbOrTx, |
| 34 | deploymentVersionId?: string |
| 35 | ): Promise<ScheduleDeployResult> { |
| 36 | const scheduleBlocks = findScheduleBlocks(blocks) |
| 37 | |
| 38 | if (scheduleBlocks.length === 0) { |
| 39 | logger.info(`No schedule blocks found in workflow ${workflowId}`) |
| 40 | return { success: true } |
| 41 | } |
| 42 | |
| 43 | // Phase 1: Validate ALL blocks before making any DB changes |
| 44 | const validatedBlocks: Array<{ |
| 45 | blockId: string |
| 46 | cronExpression: string |
| 47 | nextRunAt: Date |
| 48 | timezone: string |
| 49 | }> = [] |
| 50 | |
| 51 | for (const block of scheduleBlocks) { |
| 52 | const blockId = block.id as string |
| 53 | const validation = validateScheduleBlock(block) |
| 54 | if (!validation.isValid) { |
| 55 | return { |
| 56 | success: false, |
| 57 | error: validation.error, |
| 58 | } |
| 59 | } |
| 60 | validatedBlocks.push({ |
| 61 | blockId, |
| 62 | cronExpression: validation.cronExpression!, |
| 63 | nextRunAt: validation.nextRunAt!, |
| 64 | timezone: validation.timezone!, |
| 65 | }) |
| 66 | } |
| 67 | |
| 68 | // Phase 2: All validations passed - now do DB operations in a transaction |
| 69 | let lastScheduleInfo: { |
| 70 | scheduleId: string |
| 71 | cronExpression?: string |
| 72 | nextRunAt?: Date |
| 73 | timezone?: string |
| 74 | } | null = null |
| 75 | |
| 76 | try { |
| 77 | const writeSchedules = async (trx: DbOrTx) => { |
| 78 | const currentBlockIds = new Set(validatedBlocks.map((b) => b.blockId)) |
| 79 | |
| 80 | const existingSchedules = await trx |
| 81 | .select({ id: workflowSchedule.id, blockId: workflowSchedule.blockId }) |
| 82 | .from(workflowSchedule) |
| 83 | .where( |
| 84 | deploymentVersionId |
| 85 | ? and( |
| 86 | eq(workflowSchedule.workflowId, workflowId), |
| 87 | eq(workflowSchedule.deploymentVersionId, deploymentVersionId), |
no test coverage detected