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