|
| 1 | +/** |
| 2 | + * The read-only twin of runForRepo in ./orchestrate.ts, honoring the sections allowlist by the |
| 3 | + * same rule. |
| 4 | + */ |
| 5 | + |
| 6 | +import { stringify as stringifyYaml } from "yaml"; |
| 7 | +import type { RepoRef } from "../discovery/targets.js"; |
| 8 | +import type { GithubClient } from "../github/api.js"; |
| 9 | +import type { Io } from "../io.js"; |
| 10 | +import { describeProblem } from "../problem.js"; |
| 11 | +import type { SectionKey } from "../schema.js"; |
| 12 | +import { |
| 13 | + type EndpointDecl, |
| 14 | + endpointPath, |
| 15 | + matchesTemplate, |
| 16 | +} from "../sections/contract/endpoints.js"; |
| 17 | +import { PermissionDenied } from "../sections/contract/errors.js"; |
| 18 | +import { |
| 19 | + concealedAbsenceNote, |
| 20 | + gatedAbsentRead, |
| 21 | + type SectionSnapshot, |
| 22 | + snapshotUnsupportedNote, |
| 23 | +} from "../sections/contract/module.js"; |
| 24 | +import { planContext } from "../sections/contract/plan.js"; |
| 25 | +import { SECTIONS } from "../sections/registry.js"; |
| 26 | +import { type ValidatedSettings, validateSettingsDoc } from "./orchestrate.js"; |
| 27 | +import type { SectionSelection } from "./section-selection.js"; |
| 28 | + |
| 29 | +export interface SnapshotOptions { |
| 30 | + /** The target repository, parsed at the caller's validated boundary. */ |
| 31 | + repo: RepoRef; |
| 32 | + /** |
| 33 | + * The allowlist. Its required set goes unread: required-sections governs what must apply, and |
| 34 | + * a snapshot never writes, so a denial classifies on onMissingPermission alone. |
| 35 | + */ |
| 36 | + sections: SectionSelection; |
| 37 | + onMissingPermission: "fail" | "warn"; |
| 38 | +} |
| 39 | + |
| 40 | +/** |
| 41 | + * One section's end state: read back ("snapshot", its notes in detail), denied under the warn |
| 42 | + * policy ("skipped"), without a snapshot handler ("unsupported", the reason in detail), or failed. |
| 43 | + */ |
| 44 | +interface SectionSnapshotOutcome { |
| 45 | + key: SectionKey; |
| 46 | + status: "snapshot" | "skipped" | "unsupported" | "failed"; |
| 47 | + detail: string[]; |
| 48 | +} |
| 49 | + |
| 50 | +/** |
| 51 | + * The document exists only when the run did not fail: a denial under the fail policy and a |
| 52 | + * section producing a value its own schema rejects both withhold it, so a failed result cannot be |
| 53 | + * rendered by mistake. "partial" says a section was skipped or failed without failing the run. |
| 54 | + */ |
| 55 | +export type SnapshotResult = |
| 56 | + | { |
| 57 | + repo: string; |
| 58 | + result: "snapshot" | "partial"; |
| 59 | + settings: ValidatedSettings; |
| 60 | + outcomes: SectionSnapshotOutcome[]; |
| 61 | + } |
| 62 | + | { repo: string; result: "failed"; settings?: never; outcomes: SectionSnapshotOutcome[] }; |
| 63 | + |
| 64 | +/** A snapshot result that carries a document. */ |
| 65 | +export type RenderableSnapshot = Extract<SnapshotResult, { settings: ValidatedSettings }>; |
| 66 | + |
| 67 | +/** What a section without live state says for itself in the outcome and the file header. */ |
| 68 | +const NOTHING_TO_DECLARE = "nothing exists on the repository, so the section is omitted"; |
| 69 | + |
| 70 | +/** A line under its section's key, prefixed once: a section's own notes already lead with the key. */ |
| 71 | +function underKey(key: SectionKey, line: string): string { |
| 72 | + const own = line.startsWith(key) && /^[:.[]/.test(line.slice(key.length)); |
| 73 | + return own ? line : `${key}: ${line}`; |
| 74 | +} |
| 75 | + |
| 76 | +/** |
| 77 | + * The client as one section's snapshot sees it, reporting whether a GET on `read`'s route |
| 78 | + * answered 404 (the observation the concealed-absence note is keyed on). Null passes through. |
| 79 | + */ |
| 80 | +function watchingNotFound( |
| 81 | + api: GithubClient, |
| 82 | + read: EndpointDecl | null, |
| 83 | + seen: { notFound: boolean }, |
| 84 | +): GithubClient { |
| 85 | + if (read === null) { |
| 86 | + return api; |
| 87 | + } |
| 88 | + const template = endpointPath(read.route); |
| 89 | + return { |
| 90 | + tryRequest: async (method, path, payload, options) => { |
| 91 | + const result = await api.tryRequest(method, path, payload, options); |
| 92 | + if ( |
| 93 | + "error" in result && |
| 94 | + result.error.status === 404 && |
| 95 | + method === "GET" && |
| 96 | + matchesTemplate(template, path) |
| 97 | + ) { |
| 98 | + seen.notFound = true; |
| 99 | + } |
| 100 | + return result; |
| 101 | + }, |
| 102 | + tryGraphql: (op, variables, slug) => api.tryGraphql(op, variables, slug), |
| 103 | + }; |
| 104 | +} |
| 105 | + |
| 106 | +/** Read one repository's supported sections back into a validated settings document. */ |
| 107 | +export async function snapshotRepository( |
| 108 | + api: GithubClient, |
| 109 | + opts: SnapshotOptions, |
| 110 | + io: Io, |
| 111 | +): Promise<SnapshotResult> { |
| 112 | + const outcomes: SectionSnapshotOutcome[] = []; |
| 113 | + const document: Record<string, unknown> = {}; |
| 114 | + let partial = false; |
| 115 | + let failed = false; |
| 116 | + |
| 117 | + for (const section of SECTIONS) { |
| 118 | + if (opts.sections.only.size > 0 && !opts.sections.only.has(section.key)) { |
| 119 | + continue; |
| 120 | + } |
| 121 | + if (section.snapshot === undefined) { |
| 122 | + outcomes.push({ |
| 123 | + key: section.key, |
| 124 | + status: "unsupported", |
| 125 | + detail: [snapshotUnsupportedNote(section)], |
| 126 | + }); |
| 127 | + continue; |
| 128 | + } |
| 129 | + const absentRead = gatedAbsentRead(section); |
| 130 | + const seen = { notFound: false }; |
| 131 | + let snapshot: SectionSnapshot; |
| 132 | + try { |
| 133 | + snapshot = await section.snapshot( |
| 134 | + planContext(section, watchingNotFound(api, absentRead, seen), opts.repo), |
| 135 | + ); |
| 136 | + } catch (error) { |
| 137 | + if (error instanceof PermissionDenied) { |
| 138 | + const status = opts.onMissingPermission === "warn" ? "skipped" : "failed"; |
| 139 | + if (status === "skipped") { |
| 140 | + io.annotate("warning", `${section.key}: skipped - ${error.detail}`); |
| 141 | + partial = true; |
| 142 | + } else { |
| 143 | + io.annotate("error", `${section.key}: not snapshotted - ${error.detail}`); |
| 144 | + failed = true; |
| 145 | + } |
| 146 | + outcomes.push({ key: section.key, status, detail: [error.detail] }); |
| 147 | + continue; |
| 148 | + } |
| 149 | + const message = error instanceof Error ? error.message : String(error); |
| 150 | + const prefixed = message.startsWith(`${section.key}:`) |
| 151 | + ? message |
| 152 | + : `${section.key}: ${message}`; |
| 153 | + io.annotate("error", prefixed); |
| 154 | + outcomes.push({ key: section.key, status: "failed", detail: [prefixed] }); |
| 155 | + partial = true; |
| 156 | + continue; |
| 157 | + } |
| 158 | + for (const note of snapshot.notes) { |
| 159 | + io.annotate("notice", underKey(section.key, note)); |
| 160 | + } |
| 161 | + if (snapshot.value === undefined) { |
| 162 | + // Chosen at the engine level so every absent-posture section behaves alike: the 404 keeps |
| 163 | + // its "nothing exists" reading, and the note names the denial it could also be. Keyed on an |
| 164 | + // observed 404, so an empty 200 listing earns no note. |
| 165 | + const concealed = |
| 166 | + absentRead !== null && seen.notFound ? concealedAbsenceNote(section, absentRead) : null; |
| 167 | + if (concealed !== null) { |
| 168 | + io.annotate("notice", concealed); |
| 169 | + } |
| 170 | + outcomes.push({ |
| 171 | + key: section.key, |
| 172 | + status: "snapshot", |
| 173 | + detail: [...snapshot.notes, ...(concealed === null ? [] : [concealed]), NOTHING_TO_DECLARE], |
| 174 | + }); |
| 175 | + continue; |
| 176 | + } |
| 177 | + // Validated per section so the rejection names its producer: a value the section's own |
| 178 | + // schema refuses is a bug in that section, never a document to hand out. |
| 179 | + const verdict = validateSettingsDoc( |
| 180 | + { [section.key]: snapshot.value }, |
| 181 | + `the ${section.key} snapshot of ${opts.repo.slug}`, |
| 182 | + new Set(), |
| 183 | + io, |
| 184 | + ); |
| 185 | + if (verdict.isErr()) { |
| 186 | + const detail = `BUG: ${section.key} produced a snapshot its own schema rejects - ${describeProblem(verdict.error)}`; |
| 187 | + io.annotate("error", detail); |
| 188 | + outcomes.push({ key: section.key, status: "failed", detail: [...snapshot.notes, detail] }); |
| 189 | + failed = true; |
| 190 | + continue; |
| 191 | + } |
| 192 | + document[section.key] = verdict.value[section.key]; |
| 193 | + outcomes.push({ key: section.key, status: "snapshot", detail: [...snapshot.notes] }); |
| 194 | + } |
| 195 | + |
| 196 | + if (failed) { |
| 197 | + return { repo: opts.repo.slug, result: "failed", outcomes }; |
| 198 | + } |
| 199 | + // The brand's one mint, over the already-parsed fragments: every section validated alone |
| 200 | + // above, so the whole cannot fail. |
| 201 | + const verdict = validateSettingsDoc(document, `the snapshot of ${opts.repo.slug}`, new Set(), io); |
| 202 | + if (verdict.isErr()) { |
| 203 | + throw new Error( |
| 204 | + `BUG: the assembled snapshot of ${opts.repo.slug} failed validation after every section validated on its own: ${describeProblem(verdict.error)}`, |
| 205 | + ); |
| 206 | + } |
| 207 | + return { |
| 208 | + repo: opts.repo.slug, |
| 209 | + result: partial ? "partial" : "snapshot", |
| 210 | + settings: verdict.value, |
| 211 | + outcomes, |
| 212 | + }; |
| 213 | +} |
| 214 | + |
| 215 | +/** |
| 216 | + * The snapshot as a settings file: the language-server schema pin, a comment header naming the |
| 217 | + * repository, the moment (supplied by the caller, so the text is deterministic), and every |
| 218 | + * outcome line, then the document as the merge flow writes one. A message spanning several |
| 219 | + * physical lines (an API error body) is commented line by line, so no line escapes the header. |
| 220 | + */ |
| 221 | +export function renderSnapshotYaml( |
| 222 | + result: RenderableSnapshot, |
| 223 | + opts: { schemaUrl: string; timestamp: string }, |
| 224 | +): string { |
| 225 | + const header = [ |
| 226 | + `# yaml-language-server: $schema=${opts.schemaUrl}`, |
| 227 | + `# Snapshot of ${result.repo} taken ${opts.timestamp}`, |
| 228 | + ...result.outcomes.flatMap((outcome) => |
| 229 | + outcome.detail.flatMap((message) => |
| 230 | + message.split(/\r?\n/).map((line) => `# ${underKey(outcome.key, line)}`), |
| 231 | + ), |
| 232 | + ), |
| 233 | + ]; |
| 234 | + return `${header.join("\n")}\n${stringifyYaml(result.settings)}`; |
| 235 | +} |
0 commit comments