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

gitHubConditionalChecks.ts

152 lines6.2 KB

1import * as Clock from "effect/Clock";
2import * as Cache from "effect/Cache";
3import * as Effect from "effect/Effect";
4import * as Schema from "effect/Schema";
5import * as Semaphore from "effect/Semaphore";
6import { PositiveInt, type PullRequestChecks } from "@t3tools/contracts";
7​
8import * as GitHubCli from "../sourceControl/GitHubCli.ts";
9import type { GitHubPullRequestDetail } from "./gitHubPullRequestJson.ts";
10import type { GitHubPullRequestCliError } from "./GitHubPullRequestCli.ts";
11import type { ProviderRepositoryRef } from "./PullRequestProvider.ts";
12​
13const decodeHeadSchema = Schema.Struct({
14 head: Schema.Struct({ sha: Schema.String.check(Schema.isPattern(/^[a-f0-9]{40,64}$/)) }),
15 base: Schema.Struct({ repo: Schema.Struct({ id: PositiveInt }) }),
16 headRepositoryId: Schema.NullOr(PositiveInt),
17});
18const decodeHead = Schema.decodeUnknownEffect(Schema.fromJsonString(decodeHeadSchema));
19​
20type Validator = { etag: string | undefined; next: boolean };
21​
22export const makeChecksRevalidator = Effect.gen(function* () {
23 const github = yield* GitHubCli.GitHubCli;
24 const entries = yield* Cache.makeWith(
25 (_key: string) =>
26 Effect.sync(() => ({
27 gate: Semaphore.makeUnsafe(1),
28 validators: new Map<string, Validator>(),
29 head: null as Schema.Schema.Type<typeof decodeHeadSchema> | null,
30 value: null as PullRequestChecks | null,
31 readAt: 0,
32 supported: true,
33 })),
34 { capacity: 128, timeToLive: () => "30 minutes" },
35 );
36 return (
37 input: ProviderRepositoryRef & { readonly number: number },
38 read: Effect.Effect<
39 Pick<GitHubPullRequestDetail, "state" | "checks" | "headSha"> & {
40 workflowApprovalsRequired?: number;
41 },
42 GitHubPullRequestCliError
43 >,
44 ) =>
45 Effect.gen(function* () {
46 const credential = yield* GitHubCli.PinnedGitHubCredential;
47 if (credential === null) return yield* read;
48 const key = `${credential.credentialFingerprint}\0${input.host}\0${input.repository}\0${input.number}`;
49 const entry = yield* Cache.get(entries, key);
50 return yield* entry.gate.withPermit(
51 Effect.gen(function* () {
52 if (!entry.supported) return yield* read;
53 const fail = () =>
54 new GitHubCli.GitHubCliCommandError({
55 command: "gh",
56 cwd: input.cwd,
57 cause: new Error("GitHub returned an invalid conditional checks response."),
58 });
59 const get = (endpoint: string, head = false) =>
60 Effect.gen(function* () {
61 const previous = entry.validators.get(endpoint);
62 const result = yield* github
63 .execute({
64 cwd: input.cwd,
65 args: [
66 "api",
67 endpoint,
68 "--hostname",
69 input.host,
70 "--include",
71 ...(head
72 ? [
73 "--jq",
74 "{head:{sha:.head.sha},base:{repo:{id:.base.repo.id}},headRepositoryId:.head.repo.id}",
75 ]
76 : ["--silent"]),
77 ...(previous?.etag ? ["-H", `If-None-Match: ${previous.etag}`] : []),
78 ],
79 acceptNotModified: true,
80 })
81 .pipe(
82 Effect.catchTags({
83 GitHubCliCommandError: (error) =>
84 Effect.sync(() => {
85 entry.supported = ![404, 405, 501].includes(error.httpStatus ?? 0);
86 return null;
87 }),
88 }),
89 );
90 if (result === null) {
91 entry.value = null;
92 return null;
93 }
94 if (result.stdoutTruncated || result.stdoutInvalidUtf8) return yield* fail();
95 const split = result.stdout.search(/\r?\n\r?\n/);
96 const headers = split < 0 ? result.stdout : result.stdout.slice(0, split);
97 const status = /^HTTP\/\S+ (\d+)/.exec(headers)?.[1];
98 if (status === "304" && previous) return previous.next;
99 if (status !== "200") return yield* fail();
100 entry.value = null;
101 if (head) {
102 const decoded = yield* decodeHead(result.stdout.slice(split).trim()).pipe(
103 Effect.mapError(fail),
104 );
105 if (entry.head?.head.sha !== decoded.head.sha) entry.validators.clear();
106 entry.head = decoded;
107 }
108 const validator = {
109 etag: /^etag:\s*(.+)$/im.exec(headers)?.[1]?.trim(),
110 next: /^link:.*rel="next"/im.test(headers),
111 };
112 entry.validators.set(endpoint, validator);
113 return validator.next;
114 });
115 const root = `repos/${input.repository}`;
116 if ((yield* get(`${root}/pulls/${input.number}`, true)) === null) return yield* read;
117 const head = entry.head;
118 if (head === null) return yield* fail();
119 const endpoints = [
120 `${root}/commits/${head.head.sha}/check-runs?filter=all`,
121 `${root}/commits/${head.head.sha}/status`,
122 ...(head.headRepositoryId !== head.base.repo.id
123 ? [`${root}/actions/runs?head_sha=${head.head.sha}&event=pull_request`]
124 : []),
125 ];
126 for (const endpoint of endpoints) {
127 for (let page = 1; ; page++) {
128 if (page > 100) return yield* fail();
129 const next = yield* get(
130 `${endpoint}${endpoint.includes("?") ? "&" : "?"}per_page=100&page=${page}`,
131 );
132 if (next === null) return yield* read;
133 if (!next) break;
134 }
135 }
136 const now = yield* Clock.currentTimeMillis;
137 if (entry.value !== null && now - entry.readAt < 5 * 60_000) return entry.value;
138 const fresh = yield* read;
139 const value = {
140 state: fresh.state,
141 checks: fresh.checks,
142 };
143 entry.value =
144 fresh.workflowApprovalsRequired !== undefined && fresh.headSha === head.head.sha
145 ? value
146 : null;
147 entry.readAt = now;
148 return value;
149 }),
150 );
151 });
152});