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
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 = Effect.fn("gitHubConditionalChecks.get")(function* (
89 endpoint: string,
90 head = false,
91 ) {
92 const previous = entry.validators.get(endpoint);
93 const response = yield* api
94 .rest({
95 host: input.host,
96 operation: "revalidateChecks",
97 path: endpoint,
98 ...(previous?.etag ? { ifNoneMatch: previous.etag } : {}),
99 })
100 .pipe(
101 Effect.catchTags({
102 GitHubApiNotFoundError: () =>
103 Effect.sync(() => {
104 entry.supported = false;
105 return null;
106 }),
107 GitHubApiResponseError: (error) =>
108 Effect.sync(() => {
109 entry.supported = !UNSUPPORTED_STATUSES.has(error.status);
110 return null;
111 }),
112 }),
113 );
114 if (response === null) {
115 entry.value = null;
116 return null;
117 }
118 if (response.status === 304 && previous) return previous.next;
119 if (response.status !== 200 || response.truncated) {
120 return yield* fail(response.status);
121 }
122 entry.value = null;
123 if (head) {
124 const decoded = yield* decodeHead(response.body).pipe(
125 Effect.mapError(() => fail(response.status)),
126 );
127 if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
128 entry.head = decoded;
129 }
130 const validator = {
131 etag: response.headers["etag"]?.trim(),
132 next: /rel="next"/.test(response.headers["link"] ?? ""),
133 body: response.body,
134 };
135 entry.validators.set(endpoint, validator);
136 return validator.next;
137 });
138 const root = `repos/${input.repository}`;
139 if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
140 const head = entry.head;
141 if (head === null) return yield* fail(200);
142 const runsEndpoint =
143 head.head.repo?.id !== head.base.repo.id
144 ? `${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`
145 : null;
146 const endpoints = [
147 `${root}/commits/${head.head.sha}/check-runs?filter=all`,
148 `${root}/commits/${head.head.sha}/status`,
149 ...(runsEndpoint === null ? [] : [runsEndpoint]),
150 ];
151 const runPages: Array<string> = [];
152 for (const endpoint of endpoints) {
153 for (let page = 1; ; page++) {
154 if (page > 100) return yield* fail(200);
155 const paged = `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`;
156 const next = yield* get(paged);
157 if (next === null) return yield* read;
158 if (endpoint === runsEndpoint) runPages.push(paged);
159 if (!next) break;
160 }
161 }
162 const now = yield* Clock.currentTimeMillis;
163 if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
164 const pages = runPages.map((endpoint) =>
165 decodeWorkflowRuns(entry.validators.get(endpoint)?.body ?? ""),
166 );
167 const known =
168 runsEndpoint !== null && pages.every(Option.isSome)
169 ? {
170 headSha: head.head.sha,
171 runs: pages.flatMap((page) =>
172 Option.isSome(page) ? page.value.workflow_runs : [],
173 ),
174 }
175 : null;
176 const fresh = yield* read.pipe(Effect.provideService(KnownWorkflowRuns, known));
177 const value = {
178 state: fresh.state,
179 checks: fresh.checks,
180 };
181 entry.value =
182 fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
183 ? value
184 : null;
185 entry.readAt = now;
186 return value;
187 }),
188 );
189 });
190});