|
| 1 | +import { execSync, SpawnSyncReturns } from 'node:child_process'; |
| 2 | + |
| 3 | +import { |
| 4 | + ApplicationState, |
| 5 | + WorkflowPublisherPayload, |
| 6 | +} from '@amazeelabs/publisher-shared'; |
| 7 | +import { pairwise } from 'rxjs'; |
| 8 | + |
| 9 | +import { getConfigGithubWorkflow as config } from '../tools/config'; |
| 10 | +import { saveBuildInfo } from '../tools/database'; |
| 11 | +import { TaskController, TaskJob } from '../tools/queue'; |
| 12 | +import { core } from './core'; |
| 13 | + |
| 14 | +export const buildTask: (args?: { clean: boolean }) => TaskJob = |
| 15 | + (args) => async (controller) => { |
| 16 | + core.state.buildNumber++; |
| 17 | + core.state.applicationState$.next( |
| 18 | + core.state.buildNumber === 1 |
| 19 | + ? ApplicationState.Starting |
| 20 | + : ApplicationState.Updating, |
| 21 | + ); |
| 22 | + |
| 23 | + const startedAt = Date.now(); |
| 24 | + |
| 25 | + const output: Array<string> = []; |
| 26 | + const outputSubscription = core.output$.subscribe((chunk) => { |
| 27 | + output.push( |
| 28 | + `${new Date().toISOString().substring(0, 19).replace('T', ' ')} ${chunk}`, |
| 29 | + ); |
| 30 | + }); |
| 31 | + |
| 32 | + const finalizeBuild = (isSuccess: boolean): boolean => { |
| 33 | + core.state.applicationState$.next( |
| 34 | + isSuccess ? ApplicationState.Ready : ApplicationState.Error, |
| 35 | + ); |
| 36 | + saveBuildInfo({ |
| 37 | + type: 'github-workflow', |
| 38 | + startedAt, |
| 39 | + finishedAt: Date.now(), |
| 40 | + success: isSuccess, |
| 41 | + logs: output.join(''), |
| 42 | + }); |
| 43 | + outputSubscription.unsubscribe(); |
| 44 | + return isSuccess; |
| 45 | + }; |
| 46 | + |
| 47 | + const attempts = |
| 48 | + core.state.buildNumber === 1 |
| 49 | + ? 3 // The first build gets 3 attempts. |
| 50 | + : 1; |
| 51 | + for (let attempt = 1; attempt <= attempts; attempt++) { |
| 52 | + const result = |
| 53 | + attempt === 2 |
| 54 | + ? await runWorkflow({ controller, clean: true }) |
| 55 | + : await runWorkflow({ controller, clean: !!args?.clean }); |
| 56 | + if (result) { |
| 57 | + return finalizeBuild(true); |
| 58 | + } |
| 59 | + } |
| 60 | + return finalizeBuild(false); |
| 61 | + }; |
| 62 | + |
| 63 | +async function runWorkflow(args: { |
| 64 | + clean: boolean; |
| 65 | + controller: TaskController; |
| 66 | +}): Promise<boolean> { |
| 67 | + return new Promise<boolean>((resolve) => { |
| 68 | + core.output$.next('Starting the workflow', 'info'); |
| 69 | + |
| 70 | + const timeout = setTimeout(() => { |
| 71 | + core.output$.next('Timeout reached', 'error'); |
| 72 | + args.controller.cancel(); |
| 73 | + }, config().workflowTimeout); |
| 74 | + |
| 75 | + args.controller.onCancel(async () => { |
| 76 | + core.output$.next('Cancelling the workflow', 'warning'); |
| 77 | + await cancelWorkflow(); |
| 78 | + clearTimeout(timeout); |
| 79 | + return resolve(false); |
| 80 | + }); |
| 81 | + |
| 82 | + try { |
| 83 | + execSync( |
| 84 | + `gh workflow run ${config().workflow} --repo ${config().repo} --ref ${config().ref} --json`, |
| 85 | + { |
| 86 | + input: JSON.stringify({ |
| 87 | + ...config().inputs, |
| 88 | + publisher_payload: JSON.stringify({ |
| 89 | + callbackUrl: |
| 90 | + config().publisherBaseUrl + '/github-workflow-status', |
| 91 | + clearCache: args.clean, |
| 92 | + environmentVariables: config().environmentVariables, |
| 93 | + } satisfies WorkflowPublisherPayload), |
| 94 | + }), |
| 95 | + }, |
| 96 | + ); |
| 97 | + } catch (error) { |
| 98 | + core.output$.next('Error starting the workflow', 'error'); |
| 99 | + logExecError(error); |
| 100 | + |
| 101 | + clearTimeout(timeout); |
| 102 | + return resolve(false); |
| 103 | + } |
| 104 | + |
| 105 | + const subscription = core.state.workflowState$ |
| 106 | + .pipe(pairwise()) |
| 107 | + .subscribe(([previous, current]) => { |
| 108 | + if (current === 'started') { |
| 109 | + core.output$.next('Workflow started', 'info'); |
| 110 | + core.output$.next('Logs: ' + core.state.workflowRunUrl); |
| 111 | + return; |
| 112 | + } |
| 113 | + if ( |
| 114 | + previous === 'started' && |
| 115 | + (current === 'success' || current === 'failure') |
| 116 | + ) { |
| 117 | + subscription.unsubscribe(); |
| 118 | + current === 'success' |
| 119 | + ? core.output$.next('Workflow succeeded', 'success') |
| 120 | + : core.output$.next('Workflow failed or cancelled', 'error'); |
| 121 | + core.output$.next('Logs: ' + core.state.workflowRunUrl); |
| 122 | + |
| 123 | + clearTimeout(timeout); |
| 124 | + return resolve(current === 'success'); |
| 125 | + } |
| 126 | + }); |
| 127 | + }); |
| 128 | +} |
| 129 | + |
| 130 | +async function cancelWorkflow(): Promise<void> { |
| 131 | + type Run = { name: string; conclusion: string; databaseId: number }; |
| 132 | + |
| 133 | + function matchesEnvironment(run: Run): boolean { |
| 134 | + return run.name.includes(`[env: ${config().environment}]`); |
| 135 | + } |
| 136 | + function isCompleted(run: Run): boolean { |
| 137 | + return !!run.conclusion; |
| 138 | + } |
| 139 | + |
| 140 | + const listCommand = `gh run list --workflow=${config().workflow} --repo ${config().repo} --json name,conclusion,databaseId --limit 100`; |
| 141 | + |
| 142 | + try { |
| 143 | + // Cancel the running workflows. |
| 144 | + const result = execSync(listCommand).toString(); |
| 145 | + const runs = JSON.parse(result) as Array<Run>; |
| 146 | + for (const run of runs) { |
| 147 | + if (!isCompleted(run) && matchesEnvironment(run)) { |
| 148 | + execSync(`gh run cancel ${run.databaseId} --repo ${config().repo}`); |
| 149 | + } |
| 150 | + } |
| 151 | + |
| 152 | + // Wait for the workflows to stop. Give it a minute. |
| 153 | + // This may slightly impact the GitHub API rate limits, but cancellations |
| 154 | + // are quite rare operations. |
| 155 | + const checkAttempts = 6; |
| 156 | + const delay = 10_000; |
| 157 | + for (let checkAttempt = 1; checkAttempt <= checkAttempts; checkAttempt++) { |
| 158 | + await new Promise((resolve) => setTimeout(resolve, delay)); |
| 159 | + const result = execSync(listCommand).toString(); |
| 160 | + const runs = JSON.parse(result) as Array<Run>; |
| 161 | + if (runs.every((run) => isCompleted(run) || !matchesEnvironment(run))) { |
| 162 | + return; |
| 163 | + } |
| 164 | + } |
| 165 | + } catch (error) { |
| 166 | + core.output$.next('Error canceling the workflow', 'error'); |
| 167 | + logExecError(error); |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +function isSpawnError(error: unknown): error is SpawnSyncReturns<Buffer> { |
| 172 | + return !!error && typeof error === 'object' && 'status' in error; |
| 173 | +} |
| 174 | + |
| 175 | +function logExecError(error: unknown): void { |
| 176 | + if (isSpawnError(error)) { |
| 177 | + core.output$.next(`Error: ${error}`); |
| 178 | + core.output$.next(`Exit code: ${error.status}`); |
| 179 | + core.output$.next(`Stdout: ${error.stdout?.toString()}`); |
| 180 | + core.output$.next(`Stderr: ${error.stderr?.toString()}`); |
| 181 | + } |
| 182 | + console.error(error); |
| 183 | +} |
0 commit comments