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

gitHubConditionalChecks.ts

202 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 pull_requests: Schema.optional(Schema.Array(Schema.Struct({ number: Schema.Int }))),
30 id: Schema.Int,
31 name: Schema.optional(Schema.NullOr(Schema.String)),
32 html_url: Schema.optional(Schema.NullOr(Schema.String)),
33 status: Schema.optional(Schema.NullOr(Schema.String)),
34 conclusion: Schema.optional(Schema.NullOr(Schema.String)),
35 head_branch: Schema.optional(Schema.NullOr(Schema.String)),
36});
37const decodeWorkflowRuns = Schema.decodeUnknownOption(
38 Schema.fromJsonString(Schema.Struct({ workflow_runs: Schema.Array(WorkflowRunSchema) })),
39);
40​
41export type KnownWorkflowRun = typeof WorkflowRunSchema.Type;
42​
43export const KnownWorkflowRuns = Context.Reference<{
44 readonly headSha: string;
45 readonly runs: ReadonlyArray<KnownWorkflowRun>;
46} | null>("@t3tools/source-control-github/server/gitHubConditionalChecks/KnownWorkflowRuns", {
47 defaultValue: () => null,
48});
49​
50type Validator = { etag: string | undefined; next: boolean; body: string };
51​
52const UNSUPPORTED_STATUSES = new Set([404, 405, 501]);
53​
54export const makeChecksRevalidator = Effect.gen(function* () {
55 const api = yield* GitHubRest.GitHubRest;
56 const entries = yield* Cache.makeWith(
57 (_key: string) =>
58 Effect.sync(() => ({
59 gate: Semaphore.makeUnsafe(1),
60 validators: new Map<string, Validator>(),
61 head: null as typeof HeadSchema.Type | null,
62 value: null as PullRequestChecks | null,
63 readAt: 0,
64 supported: true,
65 })),
66 { capacity: 128, timeToLive: () => "30 minutes" },
67 );
68 return (
69 input: ProviderRepositoryRef & { readonly number: number },
70 read: Effect.Effect<
71 Pick<GitHubPullRequestDetail, "state" | "checks" | "headSha"> & {
72 workflowApprovalsRequired?: number;
73 },
74 GitHubPullRequestApiError
75 >,
76 ) =>
77 Effect.gen(function* () {
78 const credential = yield* GitHubRequestPolicy.PinnedGitHubCredential;
79 if (credential === null) return yield* read;
80 const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`;
81 const entry = yield* Cache.get(entries, key);
82 return yield* entry.gate.withPermit(
83 Effect.gen(function* () {
84 if (!entry.supported) return yield* read;
85 const fail = (status: number) =>
86 new GitHubRequestPolicy.GitHubApiResponseError({
87 host: input.host,
88 operation: "revalidateChecks",
89 status,
90 });
91 const get = Effect.fn("gitHubConditionalChecks.get")(function* (
92 endpoint: string,
93 head = false,
94 ) {
95 const previous = entry.validators.get(endpoint);
96 const response = yield* api
97 .rest({
98 host: input.host,
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 = `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`;
146 const endpoints = [
147 `${root}/commits/${head.head.sha}/check-runs?filter=all`,
148 `${root}/commits/${head.head.sha}/status`,
149 runsEndpoint,
150 ];
151 const runPages: Array<string> = [];
152 // Each endpoint has its own cursor; only pages within one endpoint depend on each other.
153 // An unavailable endpoint interrupts the others so the fallback read starts at once.
154 const available = yield* Effect.forEach(
155 endpoints,
156 Effect.fn("gitHubConditionalChecks.revalidateEndpoint")(function* (endpoint) {
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* new ChecksUnavailable();
162 if (endpoint === runsEndpoint) runPages.push(paged);
163 if (!next) return;
164 }
165 }),
166 { concurrency: 3, discard: true },
167 ).pipe(
168 Effect.as(true),
169 Effect.catchTags({ ChecksUnavailable: () => Effect.succeed(false) }),
170 );
171 if (!available) return yield* read;
172 const now = yield* Clock.currentTimeMillis;
173 if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
174 const pages = runPages.map((endpoint) =>
175 decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
176 );
177 const known = pages.every(Option.isSome)
178 ? {
179 headSha: head.head.sha,
180 runs: pages.flatMap((page) =>
181 Option.isSome(page) ? page.value.workflow_runs : [],
182 ),
183 }
184 : null;
185 const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
186 const value = {
187 state: fresh.state,
188 checks: fresh.checks,
189 ...(fresh.workflowApprovalsRequired === undefined
190 ? {}
191 : { workflowApprovalsRequired: fresh.workflowApprovalsRequired }),
192 };
193 entry.value =
194 fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
195 ? value
196 : null;
197 entry.readAt = now;
198 return value;
199 }),
200 );
201 });
202});