Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

gitHubConditionalChecks.ts

203 lines8.3 KB

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​
26class ChecksUnavailable extends Schema.TaggedError<ChecksUnavailable>()("ChecksUnavailable", {}) {}
27​
28const WorkflowRunSchema = Schema.Struct({
29 id: Schema.Int,
30 name: Schema.optional(Schema.NullOr(Schema.String)),
31 html_url: Schema.optional(Schema.NullOr(Schema.String)),
32 status: Schema.optional(Schema.NullOr(Schema.String)),
33 conclusion: Schema.optional(Schema.NullOr(Schema.String)),
34 head_branch: Schema.optional(Schema.NullOr(Schema.String)),
35});
36const decodeWorkflowRuns = Schema.decodeUnknownOption(
37 Schema.fromJsonString(Schema.Struct({ workflow_runs: Schema.Array(WorkflowRunSchema) })),
38);
39​
40export type KnownWorkflowRun = typeof WorkflowRunSchema.Type;
41​
42export const KnownWorkflowRuns = Context.Reference<{
43 readonly headSha: string;
44 readonly runs: ReadonlyArray<KnownWorkflowRun>;
45} | null>("@t3tools/source-control-github/server/gitHubConditionalChecks/KnownWorkflowRuns", {
46 defaultValue: () => null,
47});
48​
49type Validator = { etag: string | undefined; next: boolean; body: string };
50​
51const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
52​
53export const makeChecksRevalidator = Effect.gen(function* () {
54 const api = yield* GitHubRest.GitHubRest;
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* GitHubRequestPolicy.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 GitHubRequestPolicy.GitHubApiResponseError({
86 host: input.host,
87 operation: "revalidateChecks",
88 status,
89 });
90 const get = Effect.fn("gitHubConditionalChecks.get")(function* (
91 endpoint: string,
92 head = false,
93 ) {
94 const previous = entry.validators.get(endpoint);
95 const response = yield* api
96 .rest({
97 host: input.host,
98 cwd: input.cwd,
99 operation: "revalidateChecks",
100 path: endpoint,
101 ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
102 })
103 .pipe(
104 Effect.catchTags({
105 GitHubApiNotFoundError: () =>
106 Effect.sync(() => {
107 entry.supported = false;
108 return null;
109 }),
110 GitHubApiResponseError: (error) =>
111 Effect.sync(() => {
112 entry.supported &&= !UNSUPPORTED_STATUSES.has(error.status);
113 return null;
114 }),
115 }),
116 );
117 if (response === null) {
118 entry.value = null;
119 return null;
120 }
121 if (response.status === 304 && previous) return previous.next;
122 if (response.status !== 200 || response.truncated) {
123 return yield* fail(response.status);
124 }
125 entry.value = null;
126 if (head) {
127 const decoded = yield* decodeHead(response.body).pipe(
128 Effect.mapError(() => fail(response.status)),
129 );
130 if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
131 entry.head = decoded;
132 }
133 const validator = {
134 etag: response.headers["etag"]?.trim(),
135 next: /rel="next"/.test(response.headers["link"] ?? ""),
136 body: response.body,
137 };
138 entry.validators.set(endpoint, validator);
139 return validator.next;
140 });
141 const root = `repos/${input.repository}`;
142 if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
143 const head = entry.head;
144 if (head === null) return yield* fail(200);
145 const runsEndpoint =
146 head.head.repo?.id !== head.base.repo.id
147 ? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`
148 : null;
149 const endpoints = [
150 `${root}/commits/${head.head.sha}/check-runs?filter=all`,
151 `${root}/commits/${head.head.sha}/status`,
152 ...(runsEndpoint === null ? [] : [runsEndpoint]),
153 ];
154 const runPages: Array<string> = [];
155 // Each endpoint has its own cursor; only pages within one endpoint depend on each other.
156 // An unavailable endpoint interrupts the others so the fallback read starts at once.
157 const available = yield* Effect.forEach(
158 endpoints,
159 Effect.fn("gitHubConditionalChecks.revalidateEndpoint")(function* (endpoint) {
160 for (let page = 1; ; page++) {
161 if (page > 100) return yield* fail(200);
162 const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`;
163 const next = yield* get(paged);
164 if (next === null) return yield* new ChecksUnavailable();
165 if (endpoint === runsEndpoint) runPages.push(paged);
166 if (!next) return;
167 }
168 }),
169 { concurrency: 3, discard: true },
170 ).pipe(
171 Effect.as(true),
172 Effect.catchTags({ ChecksUnavailable: () => Effect.succeed(false) }),
173 );
174 if (!available) return yield* read;
175 const now = yield* Clock.currentTimeMillis;
176 if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
177 const pages = runPages.map((endpoint) =>
178 decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
179 );
180 const known =
181 runsEndpoint !== null && pages.every(Option.isSome)
182 ? {
183 headSha: head.head.sha,
184 runs: pages.flatMap((page) =>
185 Option.isSome(page) ? page.value.workflow_runs : [],
186 ),
187 }
188 : null;
189 const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
190 const value = {
191 state: fresh.state,
192 checks: fresh.checks,
193 };
194 entry.value =
195 fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
196 ? value
197 : null;
198 entry.readAt = now;
199 return value;
200 }),
201 );
202 });
203});