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

gitHubConditionalChecks.test.ts

246 lines8.0 KB

1import { expect, it } from "@effect/vitest";
2import * as TestClock from "effect/testing/TestClock";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Schema from "effect/Schema";
6import * as Redacted from "effect/Redacted";
7import type { PullRequestCheck } from "@t3tools/contracts";
8​
9import * as GitHubRest from "./GitHubRest.ts";
10import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
11import { KnownWorkflowRuns, makeChecksRevalidator } from "./gitHubConditionalChecks.ts";
12​
13const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
14​
15const reference = { cwd: "/repo", repository: "acme/web", host: "github.com", number: 1 };
16const credential = {
17 host: "github.com",
18 token: Redacted.make("token"),
19 credentialFingerprint: "one",
20};
21​
22it.effect(
23 "reuses unchanged checks and catches reruns, later pages, fork approvals, pushes and account changes",
24 () =>
25 Effect.gen(function* () {
26 let sha = "a".repeat(40);
27 let changed = "";
28 let reads = 0;
29 const requests: string[] = [];
30 const known: Array<unknown> = [];
31 const revalidate = yield* makeChecksRevalidator.pipe(
32 Effect.provide(
33 Layer.mock(GitHubRest.GitHubRest)({
34 rest: ({ path, ifNoneMatch }) =>
35 Effect.sync(() => {
36 requests.push(path);
37 const head = path.endsWith("/pulls/1");
38 const modified =
39 ifNoneMatch === undefined || (path.includes(changed) && changed !== "");
40 const next = path.includes("check-runs") && path.endsWith("page=1");
41 const runs = path.includes("/actions/runs");
42 return {
43 status: modified ? 200 : 304,
44 headers: modified
45 ? {
46 etag: `"${sha}-${changed}"`,
47 ...(next ? { link: '<https://api.github.com/next>; rel="next"' } : {}),
48 }
49 : {},
50 body: !modified
51 ? ""
52 : head
53 ? encodeJson({ head: { sha, repo: { id: 2 } }, base: { repo: { id: 1 } } })
54 : runs
55 ? encodeJson({
56 workflow_runs: [
57 { id: 9, status: "completed", conclusion: "action_required" },
58 ],
59 })
60 : "{}",
61 truncated: false,
62 invalidUtf8: false,
63 };
64 }),
65 }),
66 ),
67 );
68 const read = Effect.gen(function* () {
69 known.push(yield* KnownWorkflowRuns);
70 reads++;
71 return {
72 state: "open" as const,
73 checks: [
74 { name: "build", status: "success", description: null, url: null },
75 ] satisfies PullRequestCheck[],
76 headSha: sha,
77 workflowApprovalsRequired: 0,
78 };
79 });
80 const poll = (identity = credential) =>
81 revalidate(reference, read).pipe(
82 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, identity),
83 );
84 yield* poll();
85 expect(reads).toBe(1);
86 // The fork's runs were just confirmed, so the read is handed them instead of listing them.
87 expect(known[0]).toEqual({
88 headSha: sha,
89 runs: [{ id: 9, status: "completed", conclusion: "action_required" }],
90 });
91 requests.length = 0;
92 yield* poll();
93 expect(reads).toBe(1);
94 expect(requests).toHaveLength(5);
95 for (const endpoint of [
96 "check-runs?filter=all&per_page=100&page=2",
97 "/status",
98 "/actions/runs",
99 "/pulls/1",
100 ]) {
101 changed = endpoint;
102 yield* poll();
103 changed = "";
104 yield* poll();
105 }
106 expect(reads).toBe(5);
107 sha = "b".repeat(40);
108 changed = "/pulls/1";
109 requests.length = 0;
110 yield* poll();
111 expect(reads).toBe(6);
112 expect(
113 requests
114 .filter((endpoint) => endpoint.includes("/commits/"))
115 .every((endpoint) => endpoint.includes(sha)),
116 ).toBe(true);
117 changed = "";
118 yield* poll({ ...credential, credentialFingerprint: "two" });
119 expect(reads).toBe(7);
120 yield* TestClock.adjust("5 minutes");
121 yield* poll();
122 expect(reads).toBe(8);
123 }),
124);
125​
126it.effect("does not retain failed or incomplete reads, and supports hosts without ETags", () =>
127 Effect.gen(function* () {
128 const sha = "a".repeat(40);
129 let etags = true;
130 let unavailable = false;
131 let fail = true;
132 let complete = true;
133 let reads = 0;
134 const revalidate = yield* makeChecksRevalidator.pipe(
135 Effect.provide(
136 Layer.mock(GitHubRest.GitHubRest)({
137 rest: ({ path, ifNoneMatch }) =>
138 unavailable
139 ? Effect.fail(
140 new GitHubRequestPolicy.GitHubApiResponseError({
141 host: "github.com",
142 operation: "revalidateChecks",
143 status: 502,
144 }),
145 )
146 : Effect.succeed(
147 ifNoneMatch !== undefined && etags
148 ? { status: 304, headers: {}, body: "", truncated: false, invalidUtf8: false }
149 : {
150 status: 200,
151 headers: etags ? { etag: '"one"' } : {},
152 body: path.endsWith("/pulls/1")
153 ? encodeJson({
154 head: { sha, repo: { id: 1 } },
155 base: { repo: { id: 1 } },
156 })
157 : "{}",
158 truncated: false,
159 invalidUtf8: false,
160 },
161 ),
162 }),
163 ),
164 );
165 const read = Effect.suspend(() => {
166 reads++;
167 return fail
168 ? Effect.fail(
169 new GitHubRequestPolicy.GitHubApiResponseError({
170 host: "github.com",
171 operation: "read",
172 status: 500,
173 }),
174 )
175 : Effect.succeed({
176 state: "open" as const,
177 checks: [],
178 headSha: sha,
179 ...(complete ? { workflowApprovalsRequired: 0 } : {}),
180 });
181 });
182 const poll = () =>
183 revalidate(reference, read).pipe(
184 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, credential),
185 );
186 yield* poll().pipe(Effect.flip);
187 fail = false;
188 complete = false;
189 yield* poll();
190 yield* poll();
191 expect(reads).toBe(3);
192 complete = true;
193 yield* poll();
194 yield* poll();
195 expect(reads).toBe(4);
196 yield* TestClock.adjust("5 minutes");
197 complete = false;
198 yield* poll();
199 yield* poll();
200 expect(reads).toBe(6);
201 complete = true;
202 unavailable = true;
203 yield* poll();
204 expect(reads).toBe(7);
205 unavailable = false;
206 yield* poll();
207 yield* poll();
208 expect(reads).toBe(8);
209 etags = false;
210 yield* poll();
211 yield* poll();
212 expect(reads).toBe(10);
213 }),
214);
215​
216it.effect("falls back when REST checks are unavailable without retrying unsupported probes", () =>
217 Effect.gen(function* () {
218 let probes = 0;
219 let reads = 0;
220 const revalidate = yield* makeChecksRevalidator.pipe(
221 Effect.provide(
222 Layer.mock(GitHubRest.GitHubRest)({
223 rest: () => {
224 probes++;
225 return Effect.fail(
226 new GitHubRequestPolicy.GitHubApiNotFoundError({
227 host: "github.com",
228 operation: "revalidateChecks",
229 }),
230 );
231 },
232 }),
233 ),
234 );
235 const read = Effect.sync(() => {
236 reads++;
237 return { state: "open" as const, checks: [] };
238 });
239 for (let tick = 0; tick < 2; tick++)
240 yield* revalidate(reference, read).pipe(
241 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, credential),
242 );
243 expect(probes).toBe(1);
244 expect(reads).toBe(2);
245 }),
246);