import { spawnSync } from 'node:child_process'; import { mkdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; export const DEPLOY_BETA_STEP = 'deploy-beta'; export const DEPLOY_WORKFLOW = 'deploy.yml'; export const DEPLOY_REPO = 'udecode/plate'; const DEPLOY_API_PATH = `repos/${DEPLOY_REPO}/actions/workflows/${DEPLOY_WORKFLOW}/runs?branch=next&per_page=10`; const MAX_LOG_LINES = 120; const MAX_OUTPUT_LINES = 12; const IGNORED_CONCLUSIONS = new Set(['cancelled', 'skipped']); export const STARVATION_MIN_CANCELLED = 3; export const STARVATION_WINDOW_MS = 30 * 60_000; const latestDeployEvent = (events) => { for (let i = events.length - 1; i >= 0; i -= 1) { const event = events[i]; if ( event.step === DEPLOY_BETA_STEP && (event.kind === 'red' || event.kind === 'passed') ) { return event; } } return null; }; export const evaluateDeployRuns = ({ events = [], nowMs = Date.now(), runs = [], }) => { const latestCompleted = runs.find( (run) => run.status === 'completed' && !IGNORED_CONCLUSIONS.has(run.conclusion) ); const previous = latestDeployEvent(events); // Detect cancel-storm starvation even while another run is in flight: // >=3 cancelled runs newer than the last completed run spanning >=30 minutes. const latestCompletedIndex = latestCompleted ? runs.indexOf(latestCompleted) : runs.length; const newerRuns = runs.slice(0, latestCompletedIndex); const cancelledNewer = newerRuns.filter( (run) => run.status === 'completed' && run.conclusion === 'cancelled' ); if (cancelledNewer.length >= STARVATION_MIN_CANCELLED) { const timestamps = newerRuns .map((run) => Date.parse(run.created_at ?? run.updated_at ?? '')) .filter((ms) => Number.isFinite(ms)); const oldestMs = timestamps.length > 0 ? Math.min(...timestamps) : null; if (oldestMs !== null && nowMs - oldestMs >= STARVATION_WINDOW_MS) { const newestCancelled = cancelledNewer[0]; if (previous?.kind === 'red' && previous.runId === newestCancelled.id) { return { action: 'noop' }; } return { action: 'red', cancelledCount: cancelledNewer.length, reason: 'starved', run: newestCancelled, stalledMinutes: Math.round((nowMs - oldestMs) / 60_000), }; } } if (!latestCompleted) return { action: 'noop' }; if (latestCompleted.conclusion === 'success') { if (previous?.kind === 'red') { return { action: 'passed', run: latestCompleted }; } return { action: 'noop' }; } if (previous?.kind === 'red' && previous.runId === latestCompleted.id) { return { action: 'noop' }; } // A newer push already started deploying; wait for it instead of waking on a stale failure. const newerInFlight = newerRuns.some( (run) => run.status !== 'completed' && run.head_sha !== latestCompleted.head_sha ); if (newerInFlight) return { action: 'noop' }; return { action: 'red', run: latestCompleted }; }; const isPlateOrigin = (cwd) => { const result = spawnSync('git', ['remote', 'get-url', 'origin'], { cwd, encoding: 'utf-8', timeout: 5000, }); return ( result.status === 0 && /udecode\/plate(?:\.git)?$/u.test(result.stdout.trim()) ); }; const defaultRunGh = (args, cwd) => spawnSync('gh', args, { cwd, encoding: 'utf-8', maxBuffer: 16 << 20, timeout: 20_000, }); export const checkDeployBeta = ({ dry = false, emit, events, logsDir, main, runGh = defaultRunGh, }) => { if (dry) return { action: 'noop' }; if (process.env.LOCAL_CI_DEPLOY_WATCH !== '1' && !isPlateOrigin(main)) { return { action: 'noop' }; } const listResult = runGh(['api', DEPLOY_API_PATH], main); if (listResult.status !== 0) { const detail = (listResult.stderr || listResult.stdout) .trim() .split('\n')[0]; console.error( `[local-ci] deploy-beta check skipped: ${detail || `gh exit ${listResult.status}`}` ); return { action: 'error' }; } let runs = []; try { const parsed = JSON.parse(listResult.stdout); runs = Array.isArray(parsed.workflow_runs) ? parsed.workflow_runs : []; } catch (error) { console.error( `[local-ci] deploy-beta parse error: ${error instanceof Error ? error.message : String(error)}` ); return { action: 'error' }; } const decision = evaluateDeployRuns({ events, runs }); if (decision.action === 'noop') return decision; const { run } = decision; if (decision.action === 'passed') { emit({ kind: 'passed', runId: run.id, step: DEPLOY_BETA_STEP, tip: run.head_sha, url: run.html_url, wake: true, }); return decision; } let tailLines = []; if (decision.reason === 'starved') { tailLines = [ `Deploy starvation: ${decision.cancelledCount} cancelled deploy runs over ${decision.stalledMinutes}m with no completed deploy on next (latest cancelled run ${run.id}).`, ]; } else { const failedLog = runGh( ['run', 'view', String(run.id), '--repo', DEPLOY_REPO, '--log-failed'], main ); const rawLines = ( failedLog.status === 0 ? failedLog.stdout : failedLog.stderr || '' ) .split(/\r?\n/u) .filter((line) => line.length > 0); tailLines = rawLines.slice(-MAX_LOG_LINES); } let logPath; if (logsDir) { mkdirSync(logsDir, { recursive: true }); logPath = join(logsDir, `${DEPLOY_BETA_STEP}-${run.id}.log`); writeFileSync( logPath, `${tailLines.join('\n') || `Deploy run ${run.id} failed (${run.conclusion}).`}\n` ); } emit({ conclusion: run.conclusion, kind: 'red', ...(logPath ? { log: logPath } : {}), output: tailLines.slice(-MAX_OUTPUT_LINES), runId: run.id, step: DEPLOY_BETA_STEP, tip: run.head_sha, url: run.html_url, wake: true, }); return decision; };