Open History to see the last commit
1import * as Clock from "effect/Clock";
2import * as Cache from "effect/Cache";
3import * as Context from "effect/Context";
4import * as Effect from "effect/Effect";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as Semaphore from "effect/Semaphore";
8import { PositiveInt, type PullRequestChecks } from "@t3tools/contracts";
9
10import * as GitHubApi from "../sourceControl/GitHubApi.ts";
11import type { GitHubPullRequestDetail } from "./gitHubPullRequestJson.ts";
12import type { GitHubPullRequestApiError } from "./GitHubPullRequestApi.ts";
13import type { ProviderRepositoryRef } from "./PullRequestProvider.ts";
14
15const HeadSchema = Schema.Struct({
16 head: Schema.Struct({
17 sha: Schema.String.check(Schema.isPattern(/^[a-f0-9]{40,64}$/)),
18 // Null once the fork a pull request came from has been deleted.
19 repo: Schema.NullOr(Schema.Struct({ id: PositiveInt })),
20 }),
21 base: Schema.Struct({ repo: Schema.Struct({ id: PositiveInt }) }),
22});
23const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(HeadSchema));
24
25const WorkflowRunSchema = Schema.Struct({
26 id: Schema.Int,
27 name: Schema.optional(Schema.NullOr(Schema.String)),
28 html_url: Schema.optional(Schema.NullOr(Schema.String)),
29 status: Schema.optional(Schema.NullOr(Schema.String)),
30 conclusion: Schema.optional(Schema.NullOr(Schema.String)),
31 head_branch: Schema.optional(Schema.NullOr(Schema.String)),
32});
33const decodeWorkflowRuns = Schema.decodeUnknownOption(
34 Schema.fromJsonString(Schema.Struct({ workflow_runs: Schema.Array(WorkflowRunSchema) })),
35);
36
37export type KnownWorkflowRun = typeof WorkflowRunSchema.Type;
38
39/**
40 * Every `pull_request` workflow run of one head, as the revalidator just confirmed them against
41 * GitHub. A read running under it filters these rather than asking for the runs again.
42 */
43export const KnownWorkflowRuns = Context.Reference<{
44 readonly headSha: string;
45 readonly runs: ReadonlyArray<KnownWorkflowRun>;
46} | null>("t3/pullRequest/KnownWorkflowRuns", { defaultValue: () => null });
47
48type Validator = { etag: string | undefined; next: boolean; body: string };
49
50/** A host that answers these with one of them has no conditional REST for it at all. */
51const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
52
53export const makeChecksRevalidator = Effect.gen(function* () {
54 const api = yield* GitHubApi.GitHubApi;
55 const entries = yield* Cache.makeWith(
56 (_key: string) =>
57 Effect.sync(() => ({
58 gate: Semaphore.makeUnsafe(1),
59 validators: new Map<string, Validator>(),
60 head: null as typeof HeadSchema.Type | null,
61 value: null as PullRequestChecks | null,
62 readAt: 0,
63 supported: true,
64 })),
65 { capacity: 128, timeToLive: () => "30 minutes" },
66 );
67 return (
68 input: ProviderRepositoryRef & { readonly number: number },
69 read: Effect.Effect<
70 Pick<GitHubPullRequestDetail, "state" | "checks" | "headSha"> & {
71 workflowApprovalsRequired?: number;
72 },
73 GitHubPullRequestApiError
74 >,
75 ) =>
76 Effect.gen(function* () {
77 const credential = yield* GitHubApi.PinnedGitHubCredential;
78 if (credential === null) return yield* read;
79 const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`;
80 const entry = yield* Cache.get(entries, key);
81 return yield* entry.gate.withPermit(
82 Effect.gen(function* () {
83 if (!entry.supported) return yield* read;
84 const fail = (status: number) =>
85 new GitHubApi.GitHubApiResponseError({
86 host: input.host,
87 operation: "revalidateChecks",
88 status,
89 });
90 /** Whether the endpoint has a next page, or null where the host cannot say. */
91 const get = (endpoint: string, head = false) =>
92 Effect.gen(function* () {
93 const previous = entry.validators.get(endpoint);
94 const response = yield* api
95 .rest({
96 host: input.host,
97 operation: "revalidateChecks",
98 path: endpoint,
99 ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
100 })
101 .pipe(
102 Effect.catchTags({
103 GitHubApiNotFoundError: () =>
104 Effect.sync(() => {
105 entry.supported = false;
106 return null;
107 }),
108 GitHubApiResponseError: (error) =>
109 Effect.sync(() => {
110 entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
111 return null;
112 }),
113 }),
114 );
115 if (response === null) {
116 entry.value = null;
117 return null;
118 }
119 if (response.status === 304 && previous) return previous.next;
120 if (response.status !== 200 || response.truncated) {
121 return yield* fail(response.status);
122 }
123 entry.value = null;
124 if (head) {
125 const decoded = yield* decodeHead(response.body).pipe(
126 Effect.mapError(() => fail(response.status)),
127 );
128 if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
129 entry.head = decoded;
130 }
131 const validator = {
132 etag: response.headers["etag"]?.trim(),
133 next: /rel="next"/.test(response.headers["link"] ?? ""),
134 body: response.body,
135 };
136 entry.validators.set(endpoint, validator);
137 return validator.next;
138 });
139 const root = `repos/${input.repository}`;
140 if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
141 const head = entry.head;
142 if (head === null) return yield* fail(200);
143 const runsEndpoint =
144 head.head.repo?.id !== head.base.repo.id
145 ? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`
146 : null;
147 const endpoints = [
148 `${root}/commits/${head.head.sha}/check-runs?filter=all`,
149 `${root}/commits/${head.head.sha}/status`,
150 ...(runsEndpoint === null ? [] : [runsEndpoint]),
151 ];
152 const runPages: Array<string> = [];
153 for (const endpoint of endpoints) {
154 for (let page = 1; ; page++) {
155 if (page > 100) return yield* fail(200);
156 const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`;
157 const next = yield* get(paged);
158 if (next === null) return yield* read;
159 if (endpoint === runsEndpoint) runPages.push(paged);
160 if (!next) break;
161 }
162 }
163 const now = yield* Clock.currentTimeMillis;
164 if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
165 // Every page of the head's runs was just confirmed current, so the read filters them
166 // rather than listing the runs a second time.
167 const pages = runPages.map((endpoint) =>
168 decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
169 );
170 const known =
171 runsEndpoint !== null && pages.every(Option.isSome)
172 ? {
173 headSha: head.head.sha,
174 runs: pages.flatMap((page) =>
175 Option.isSome(page) ? page.value.workflow_runs : [],
176 ),
177 }
178 : null;
179 const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
180 const value = {
181 state: fresh.state,
182 checks: fresh.checks,
183 };
184 entry.value =
185 fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
186 ? value
187 : null;
188 entry.readAt = now;
189 return value;
190 }),
191 );
192 });
193});