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

gitHubConditionalChecks.ts

188 lines7.6 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​
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​
40export const KnownWorkflowRuns = Context.Reference<{
41 readonly headSha: string;
42 readonly runs: ReadonlyArray<KnownWorkflowRun>;
43} | null>("@t3tools/source-control-github/server/gitHubConditionalChecks/KnownWorkflowRuns", {
44 defaultValue: () => null,
45});
46​
47type Validator = { etag: string | undefined; next: boolean; body: string };
48​
49const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
50​
51export const makeChecksRevalidator = Effect.gen(function* () {
52 const api = yield* GitHubRest.GitHubRest;
53 const entries = yield* Cache.makeWith(
54 (_key: string) =>
55 Effect.sync(() => ({
56 gate: Semaphore.makeUnsafe(1),
57 validators: new Map<string, Validator>(),
58 head: null as typeof HeadSchema.Type | null,
59 value: null as PullRequestChecks | null,
60 readAt: 0,
61 supported: true,
62 })),
63 { capacity: 128, timeToLive: () => "30 minutes" },
64 );
65 return (
66 input: ProviderRepositoryRef & { readonly number: number },
67 read: Effect.Effect<
68 Pick<GitHubPullRequestDetail, "state" | "checks" | "headSha"> & {
69 workflowApprovalsRequired?: number;
70 },
71 GitHubPullRequestApiError
72 >,
73 ) =>
74 Effect.gen(function* () {
75 const credential = yield* GitHubRequestPolicy.PinnedGitHubCredential;
76 if (credential === null) return yield* read;
77 const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`;
78 const entry = yield* Cache.get(entries, key);
79 return yield* entry.gate.withPermit(
80 Effect.gen(function* () {
81 if (!entry.supported) return yield* read;
82 const fail = (status: number) =>
83 new GitHubRequestPolicy.GitHubApiResponseError({
84 host: input.host,
85 operation: "revalidateChecks",
86 status,
87 });
88 const get = (endpoint: string, head = false) =>
89 Effect.gen(function* () {
90 const previous = entry.validators.get(endpoint);
91 const response = yield* api
92 .rest({
93 host: input.host,
94 operation: "revalidateChecks",
95 path: endpoint,
96 ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
97 })
98 .pipe(
99 Effect.catchTags({
100 GitHubApiNotFoundError: () =>
101 Effect.sync(() => {
102 entry.supported = false;
103 return null;
104 }),
105 GitHubApiResponseError: (error) =>
106 Effect.sync(() => {
107 entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
108 return null;
109 }),
110 }),
111 );
112 if (response === null) {
113 entry.value = null;
114 return null;
115 }
116 if (response.status === 304 && previous) return previous.next;
117 if (response.status !== 200 || response.truncated) {
118 return yield* fail(response.status);
119 }
120 entry.value = null;
121 if (head) {
122 const decoded = yield* decodeHead(response.body).pipe(
123 Effect.mapError(() => fail(response.status)),
124 );
125 if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
126 entry.head = decoded;
127 }
128 const validator = {
129 etag: response.headers["etag"]?.trim(),
130 next: /rel="next"/.test(response.headers["link"] ?? ""),
131 body: response.body,
132 };
133 entry.validators.set(endpoint, validator);
134 return validator.next;
135 });
136 const root = `repos/${input.repository}`;
137 if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
138 const head = entry.head;
139 if (head === null) return yield* fail(200);
140 const runsEndpoint =
141 head.head.repo?.id !== head.base.repo.id
142 ? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`
143 : null;
144 const endpoints = [
145 `${root}/commits/${head.head.sha}/check-runs?filter=all`,
146 `${root}/commits/${head.head.sha}/status`,
147 ...(runsEndpoint === null ? [] : [runsEndpoint]),
148 ];
149 const runPages: Array<string> = [];
150 for (const endpoint of endpoints) {
151 for (let page = 1; ; page++) {
152 if (page > 100) return yield* fail(200);
153 const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`;
154 const next = yield* get(paged);
155 if (next === null) return yield* read;
156 if (endpoint === runsEndpoint) runPages.push(paged);
157 if (!next) break;
158 }
159 }
160 const now = yield* Clock.currentTimeMillis;
161 if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
162 const pages = runPages.map((endpoint) =>
163 decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
164 );
165 const known =
166 runsEndpoint !== null && pages.every(Option.isSome)
167 ? {
168 headSha: head.head.sha,
169 runs: pages.flatMap((page) =>
170 Option.isSome(page) ? page.value.workflow_runs : [],
171 ),
172 }
173 : null;
174 const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
175 const value = {
176 state: fresh.state,
177 checks: fresh.checks,
178 };
179 entry.value =
180 fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
181 ? value
182 : null;
183 entry.readAt = now;
184 return value;
185 }),
186 );
187 });
188});