Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

collect-core.ts

361 lines · 14.6 KB · TypeScript
import {
	defaultMaxApiCalls,
	lookbackDays,
	maxDetailedWorkflows,
	maxFailedRunsPerWorkflow,
	maxJobRunsPerWorkflow,
	maxListPagesPerWorkflow,
	maxPrFileLookups,
	maxRerunsPerWorkflow,
	maxTimingRuns,
	minSuccessRunsPerWorkflow,
	requestConcurrency,
} from './shared.ts'
import type { BillableTiming, CacheEntry, Dataset, JobSummary, RunSummary, WorkflowInfo } from './types.ts'

export type GithubResponse = { ok?: boolean; status?: number; data?: any; text?: string }
export type Request = (params: { path: string; method?: 'GET' }) => Promise<GithubResponse>

/** Thrown when a run would exceed its GitHub call budget. */
export class BudgetExhausted extends Error {}

/** Counts GitHub calls and refuses calls past the cap. */
export class CallBudget {
	used = 0
	readonly max: number
	constructor(max: number) {
		this.max = max
	}
	get remaining() {
		return Math.max(0, this.max - this.used)
	}
	take() {
		if (this.used >= this.max) throw new BudgetExhausted(`GitHub call budget of ${this.max} used up`)
		this.used += 1
	}
}

/** Events that count as the CI pipeline for PRs and the default branch. */
const pipelineEvents = new Set(['push', 'pull_request', 'merge_group', 'workflow_run'])

export async function mapLimit<T, R>(items: ReadonlyArray<T>, limit: number, fn: (item: T, index: number) => Promise<R>) {
	const results: Array<R> = new Array(items.length)
	let next = 0
	const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
		while (next < items.length) {
			const index = next++
			results[index] = await fn(items[index], index)
		}
	})
	await Promise.all(workers)
	return results
}

export function toRun(raw: any, workflowName: string): RunSummary {
	return {
		id: Number(raw?.id),
		workflowId: Number(raw?.workflow_id),
		workflowName,
		event: String(raw?.event ?? ''),
		headBranch: String(raw?.head_branch ?? ''),
		headSha: String(raw?.head_sha ?? ''),
		status: String(raw?.status ?? ''),
		conclusion: raw?.conclusion == null ? null : String(raw.conclusion),
		runAttempt: Number(raw?.run_attempt ?? 1) || 1,
		createdAt: String(raw?.created_at ?? ''),
		runStartedAt: String(raw?.run_started_at ?? raw?.created_at ?? ''),
		updatedAt: String(raw?.updated_at ?? ''),
		prNumbers: Array.isArray(raw?.pull_requests) ? raw.pull_requests.map((pr: any) => Number(pr?.number)).filter((n: number) => n > 0) : [],
	}
}

export function toJob(raw: any, runId: number): JobSummary {
	return {
		id: Number(raw?.id),
		runId,
		name: String(raw?.name ?? ''),
		conclusion: raw?.conclusion == null ? null : String(raw.conclusion),
		status: String(raw?.status ?? ''),
		createdAt: raw?.created_at ?? null,
		startedAt: raw?.started_at ?? null,
		completedAt: raw?.completed_at ?? null,
		labels: Array.isArray(raw?.labels) ? raw.labels.map(String) : [],
		runAttempt: Number(raw?.run_attempt ?? 1) || 1,
		steps: Array.isArray(raw?.steps)
			? raw.steps.map((step: any) => ({
					name: String(step?.name ?? ''),
					conclusion: step?.conclusion == null ? null : String(step.conclusion),
					startedAt: step?.started_at ?? null,
					completedAt: step?.completed_at ?? null,
				}))
			: [],
	}
}

/** A run belongs to the pipeline when it is a PR or merge queue run, or a default branch push / chained run. */
export function isPipelineRun(run: RunSummary, defaultBranch: string) {
	if (!pipelineEvents.has(run.event)) return false
	if (run.event === 'pull_request' || run.event === 'merge_group') return true
	return run.headBranch === defaultBranch
}

/** Cheap text checks on a workflow file (no YAML parser needed for these signals). */
export function inspectWorkflowFile(text: string) {
	const onBlock = text.split(/\n(?=[a-z_]+:)/).find((block) => /^on:/m.test(block)) ?? ''
	const prBlock = onBlock.split(/\n {2}(?=[a-z_]+:)/).find((block) => /^\s*pull_request:/m.test(block)) ?? ''
	return {
		hasPullRequestPaths: /\n\s+paths(-ignore)?:/.test(prBlock),
		hasConcurrency: /^concurrency:/m.test(text) || /\n\s+concurrency:/.test(text),
		cancelInProgress: /cancel-in-progress:\s*(true|\$\{\{)/.test(text),
	}
}

/** Evenly spaced picks, keeping order. */
export function spread<T>(items: ReadonlyArray<T>, count: number) {
	if (count <= 0) return []
	if (items.length <= count) return [...items]
	const step = items.length / count
	return Array.from({ length: count }, (_, index) => items[Math.floor(index * step)])
}

/** Day-sized created ranges covering [since, until). */
export function dayRanges(since: Date, until: Date) {
	const ranges: Array<string> = []
	for (let start = since.getTime(); start < until.getTime(); start += 86400000) {
		const end = Math.min(start + 86400000, until.getTime())
		ranges.push(`${new Date(start).toISOString().replace('.000Z', 'Z')}..${new Date(end - 1000).toISOString().replace('.000Z', 'Z')}`)
	}
	return ranges
}

export type CollectInput = {
	repo: string
	now?: Date
	days?: number
	maxApiCalls?: number
	request: Request
}

/**
 * Deterministic GitHub Actions collector. Read-only. Every call goes through
 * one budget; when the budget runs out the collector keeps what it has and
 * records a note instead of failing.
 */
export async function collectDataset(input: CollectInput): Promise<Dataset> {
	const now = input.now ?? new Date()
	const days = input.days ?? lookbackDays
	const since = new Date(now.getTime() - days * 86400000)
	const budget = new CallBudget(input.maxApiCalls ?? defaultMaxApiCalls)
	const notes: string[] = []
	const repo = input.repo

	async function get(path: string) {
		budget.take()
		const response = await input.request({ path })
		if (response?.ok === false || (response?.status && response.status >= 400)) {
			const error = new Error(`GitHub GET ${path.split('?')[0]} failed (${response?.status}): ${String(response?.text ?? '').slice(0, 160)}`)
			;(error as Error & { status?: number }).status = response?.status
			throw error
		}
		return response?.data
	}

	async function soft<T>(what: string, fn: () => Promise<T>): Promise<T | null> {
		try {
			return await fn()
		} catch (error) {
			if (error instanceof BudgetExhausted) {
				if (!notes.includes('api budget reached')) notes.push('api budget reached')
				return null
			}
			notes.push(`${what}: ${(error instanceof Error ? error.message : String(error)).slice(0, 200)}`)
			return null
		}
	}

	const repoData = await get(`/repos/${repo}`)
	const defaultBranch = String(repoData?.default_branch ?? 'main')
	const workflowList = await get(`/repos/${repo}/actions/workflows?per_page=100`)
	const files = (workflowList?.workflows ?? []).filter(
		(workflow: any) => workflow?.state === 'active' && String(workflow?.path ?? '').startsWith('.github/workflows/'),
	)

	const runMinutes = (run: RunSummary) => Math.max(0, (Date.parse(run.updatedAt) - Date.parse(run.runStartedAt)) / 60000)
	const median = (values: number[]) => {
		const sorted = [...values].sort((a, b) => a - b)
		return sorted.length ? sorted[Math.floor(sorted.length / 2)] : 0
	}

	const createdFilter = `${since.toISOString().replace(/\.\d+Z$/, 'Z')}..${now.toISOString().replace(/\.\d+Z$/, 'Z')}`

	async function listRuns(workflow: any): Promise<WorkflowInfo> {
		const info: WorkflowInfo = {
			id: Number(workflow.id),
			name: String(workflow.name ?? ''),
			path: String(workflow.path ?? ''),
			state: String(workflow.state ?? ''),
			totalInWindow: 0,
			runs: [],
			file: null,
			listingScale: 1,
		}
		const base = `/repos/${repo}/actions/workflows/${info.id}/runs?per_page=100&exclude_pull_requests=false`
		const first = await soft(`list ${info.name}`, () => get(`${base}&created=${encodeURIComponent(createdFilter)}`))
		if (!first) return info
		info.totalInWindow = Number(first.total_count ?? 0)
		const firstRuns: any[] = first.workflow_runs ?? []
		// Skip workflows that are not part of the PR / default branch pipeline.
		const firstPipeline = firstRuns.map((raw) => toRun(raw, info.name)).filter((run) => isPipelineRun(run, defaultBranch))
		if (firstPipeline.length === 0) return info
		const raws: any[] = [...firstRuns]
		let pages = 1
		// Light workflows (median run under a minute) keep the first page as a sample.
		const light = median(firstPipeline.map(runMinutes)) < 1
		if (light && info.totalInWindow > firstRuns.length) {
			info.listingScale = info.totalInWindow / Math.max(1, firstRuns.length)
		} else if (info.totalInWindow > firstRuns.length) {
			// GitHub returns at most 1000 results per filtered query: page per day when needed.
			const ranges = info.totalInWindow > 1000 ? dayRanges(since, now) : [createdFilter]
			if (info.totalInWindow > 1000) raws.length = 0
			for (const range of ranges) {
				for (let page = info.totalInWindow > 1000 ? 1 : 2; page <= 10; page++) {
					if (pages >= maxListPagesPerWorkflow) {
						notes.push(`${info.name}: listing capped at ${maxListPagesPerWorkflow} pages`)
						break
					}
					const data = await soft(`list ${info.name}`, () => get(`${base}&created=${encodeURIComponent(range)}&page=${page}`))
					if (!data) break
					pages += 1
					const batch: any[] = data.workflow_runs ?? []
					raws.push(...batch)
					if (batch.length < 100) break
				}
				if (pages >= maxListPagesPerWorkflow) break
			}
		}
		const seen = new Set<number>()
		for (const raw of raws) {
			const run = toRun(raw, info.name)
			if (seen.has(run.id)) continue
			seen.add(run.id)
			if (isPipelineRun(run, defaultBranch)) info.runs.push(run)
		}
		info.runs.sort((a, b) => a.createdAt.localeCompare(b.createdAt))
		return info
	}

	const workflows = (await mapLimit(files, requestConcurrency, listRuns)).filter(Boolean)
	const pipeline = workflows.filter((workflow) => workflow.runs.length > 0)

	// Heaviest workflows by total run time get job detail.
	const weight = (workflow: WorkflowInfo) => workflow.listingScale * workflow.runs.reduce((sum, run) => sum + runMinutes(run), 0)
	const detailed = [...pipeline].sort((a, b) => weight(b) - weight(a)).slice(0, maxDetailedWorkflows)

	await mapLimit(detailed, 3, async (workflow) => {
		const text = await soft(`read ${workflow.path}`, async () => {
			const data = await get(`/repos/${repo}/contents/${workflow.path}?ref=${encodeURIComponent(defaultBranch)}`)
			return typeof data?.content === 'string' ? atob(data.content.replace(/\s+/g, '')) : null
		})
		if (typeof text === 'string') workflow.file = inspectWorkflowFile(text)
	})

	const jobsByRun: Record<string, JobSummary[]> = {}
	const previousAttemptJobs: Record<string, JobSummary[]> = {}
	type Pick = { run: RunSummary; previous: boolean }
	const picks: Pick[] = []
	for (const workflow of detailed) {
		const completed = workflow.runs.filter((run) => run.status === 'completed' && run.conclusion !== 'skipped')
		const failed = completed.filter((run) => run.conclusion === 'failure' || run.conclusion === 'timed_out').slice(-maxFailedRunsPerWorkflow)
		const reruns = completed.filter((run) => run.runAttempt > 1).slice(-maxRerunsPerWorkflow)
		const chosen = new Set<number>([...failed, ...reruns].map((run) => run.id))
		// First-attempt successes keep their own share so durations and paths are not biased toward reruns.
		const rest = completed.filter((run) => !chosen.has(run.id) && run.conclusion === 'success' && run.runAttempt === 1)
		const room = Math.max(minSuccessRunsPerWorkflow, maxJobRunsPerWorkflow - chosen.size)
		for (const run of spread(rest, room)) chosen.add(run.id)
		for (const run of completed) if (chosen.has(run.id)) picks.push({ run, previous: false })
		for (const run of reruns) picks.push({ run, previous: true })
	}

	await mapLimit(picks, requestConcurrency, async ({ run, previous }) => {
		const path = previous
			? `/repos/${repo}/actions/runs/${run.id}/attempts/${run.runAttempt - 1}/jobs?per_page=100`
			: `/repos/${repo}/actions/runs/${run.id}/jobs?per_page=100`
		const data = await soft(`jobs ${run.id}`, () => get(path))
		if (!data) return
		const jobs = (data.jobs ?? []).map((raw: any) => toJob(raw, run.id))
		if (previous) previousAttemptJobs[String(run.id)] = jobs
		else jobsByRun[String(run.id)] = jobs
	})

	const timing: Record<string, BillableTiming> = {}
	const timingRuns = spread(
		picks.filter((pick) => !pick.previous && pick.run.conclusion === 'success' && pick.run.runAttempt === 1).map((pick) => pick.run),
		maxTimingRuns,
	)
	await mapLimit(timingRuns, requestConcurrency, async (run) => {
		const data = await soft(`timing ${run.id}`, () => get(`/repos/${repo}/actions/runs/${run.id}/timing`))
		if (data?.billable) timing[String(run.id)] = data.billable
	})

	const caches = await soft('caches', async () => {
		const entries: CacheEntry[] = []
		for (let page = 1; page <= 3; page++) {
			const data = await get(`/repos/${repo}/actions/caches?per_page=100&page=${page}&sort=last_accessed_at&direction=desc`)
			const batch: any[] = data?.actions_caches ?? []
			for (const raw of batch) {
				entries.push({
					key: String(raw?.key ?? ''),
					sizeBytes: Number(raw?.size_in_bytes ?? 0),
					createdAt: String(raw?.created_at ?? ''),
					lastAccessedAt: String(raw?.last_accessed_at ?? ''),
					ref: String(raw?.ref ?? ''),
				})
			}
			if (batch.length < 100) break
		}
		return entries
	})

	// Run listings often omit pull_requests, so map PR head branches to numbers from the pulls list.
	const prByBranch = new Map<string, number>()
	for (let page = 1; page <= 3; page++) {
		const data = await soft('pulls', () => get(`/repos/${repo}/pulls?state=all&base=${encodeURIComponent(defaultBranch)}&sort=updated&direction=desc&per_page=100&page=${page}`))
		if (!Array.isArray(data)) break
		for (const pr of data) {
			const ref = String(pr?.head?.ref ?? '')
			if (ref && !prByBranch.has(ref)) prByBranch.set(ref, Number(pr?.number))
		}
		const oldest = data[data.length - 1]?.updated_at
		if (data.length < 100 || (oldest && String(oldest) < since.toISOString())) break
	}
	for (const workflow of pipeline) {
		for (const run of workflow.runs) {
			if (run.event === 'pull_request' && run.prNumbers.length === 0 && prByBranch.has(run.headBranch)) run.prNumbers = [prByBranch.get(run.headBranch)!]
		}
	}

	// Changed files for a sample of PRs (docs-only detection for path filters).
	const prNumbers = [...new Set(pipeline.flatMap((workflow) => workflow.runs.filter((run) => run.event === 'pull_request').flatMap((run) => run.prNumbers)))]
	const prFiles: Record<string, string[]> = {}
	const prPicks = spread(prNumbers, Math.min(maxPrFileLookups, Math.max(0, budget.remaining - 5)))
	await mapLimit(prPicks, requestConcurrency, async (number) => {
		const data = await soft(`pr files ${number}`, () => get(`/repos/${repo}/pulls/${number}/files?per_page=100`))
		if (Array.isArray(data)) prFiles[String(number)] = data.map((file: any) => String(file?.filename ?? ''))
	})

	return {
		repo,
		defaultBranch,
		since: since.toISOString(),
		until: now.toISOString(),
		workflows,
		jobsByRun,
		previousAttemptJobs,
		timing,
		caches,
		prFiles,
		apiCalls: budget.used,
		maxApiCalls: budget.max,
		notes,
	}
}