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

server-metrics-forge.ts

614 lines22.7 KB

1// A fake GitHub Enterprise host for the server-metrics soak: the GitHub API the server polls for a
2// web client, and a git remote it fetches from, both over HTTPS on loopback.
3// @effect-diagnostics nodeBuiltinImport:off - NodeHttpServer takes a node:http2 server; the proxy is raw.
4import * as NodeHttp from "node:http";
5import * as NodeHttp2 from "node:http2";
6import * as NodeNet from "node:net";
7​
8import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
9import * as HostProcess from "@t3tools/shared/HostProcess";
10import type {
11 PullRequestListInput,
12 PullRequestListResult,
13 PullRequestRef,
14} from "@t3tools/contracts";
15import * as Clock from "effect/Clock";
16import * as Console from "effect/Console";
17import * as Duration from "effect/Duration";
18import * as DateTime from "effect/DateTime";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Path from "effect/Path";
23import * as Schema from "effect/Schema";
24import { HttpServer, HttpServerRequest, HttpServerResponse } from "effect/http";
25​
26import { run, ScenarioError } from "./scenarios/shell.ts";
27​
28const OWNER = "bench";
29const REPO = "project";
30const TOKEN = "ghp_bench_fake";
31/**
32 * The host the project's origin names. It carries no port because pull request listings key a
33 * GitHub host without one, so the server reaches it on 443 through a proxy that tunnels it here.
34 */
35const HOST = "bench.test";
36​
37export interface ForgeRequest {
38 readonly at: number;
39 readonly method: string;
40 readonly path: string;
41 /** The GraphQL operation name, for GraphQL requests. */
42 readonly operation: string | undefined;
43 readonly status: number;
45​
46const GraphQlRequest = Schema.Struct({
47 query: Schema.optional(Schema.String),
48 operationName: Schema.optional(Schema.NullOr(Schema.String)),
49 variables: Schema.optional(Schema.NullOr(Schema.Record(Schema.String, Schema.Unknown))),
50});
51const decodeGraphQl = Schema.decodeUnknownEffect(Schema.fromJsonString(GraphQlRequest));
52​
53const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
54/** FNV-1a, enough to tell bodies apart. */
55const hash = (text: string) => {
56 let value = 0x811c9dc5;
57 for (let index = 0; index < text.length; index++) {
58 value = Math.imul(value ^ text.charCodeAt(index), 0x01000193) >>> 0;
59 }
60 return value.toString(16);
61};
62​
63interface Failure {
64 readonly message: string;
66​
67interface FakePullRequest {
68 readonly number: number;
69 readonly head: string;
70 oid: string;
72​
73/** Serves the fake host until the scope closes. */
74export const serveFakeGitHub = Effect.fn("serverMetrics.serveFakeGitHub")(function* () {
75 const fs = yield* FileSystem.FileSystem;
76 const path = yield* Path.Path;
77 const dir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-server-metrics-forge-" });
78 const keyFile = path.join(dir, "key.pem");
79 const certFile = path.join(dir, "cert.pem");
80 yield* run("openssl", [
81 "req",
82 "-x509",
83 "-newkey",
84 "ec",
85 "-pkeyopt",
86 "ec_paramgen_curve:prime256v1",
87 "-nodes",
88 "-days",
89 "2",
90 "-subj",
91 `/CN=${HOST}`,
92 "-addext",
93 `subjectAltName=DNS:${HOST}`,
94 "-keyout",
95 keyFile,
96 "-out",
97 certFile,
98 ]);
99 const bare = path.join(dir, `${REPO}.git`);
100 yield* run("git", ["init", "-q", "--bare", bare]);
101 const requests: ForgeRequest[] = [];
102 const host = HOST;
103 const pullRequests: Array<FakePullRequest> = [
104 { number: 1, head: "bench/feature", oid: "0".repeat(40) },
105 ...[2, 3, 4, 5].map((number) => ({
106 number,
107 head: `bench/other-${number}`,
108 oid: "0".repeat(40),
109 })),
110 ];
111​
112 const actor = { __typename: "User", id: "U_bench", login: OWNER, name: "Bench", avatarUrl: "" };
113 /** Every field any of the polled reads selects; decoders ignore the ones a read did not ask for. */
114 const pullRequestNode = (pr: FakePullRequest, now: number) => {
115 const minute = Math.floor(now / 60_000);
116 const at = (offsetMinutes: number) =>
117 DateTime.formatIso(DateTime.makeUnsafe((minute - offsetMinutes) * 60_000));
118 // The branch PR's CI reruns every other minute, so checks and their rollup keep changing.
119 const running = pr.number === 1 && minute % 2 === 0;
120 return {
121 __typename: "PullRequest",
122 id: `PR_bench_${pr.number}`,
123 number: pr.number,
124 title: `Bench change ${pr.number}`,
125 url: `https://${host}/${OWNER}/${REPO}/pull/${pr.number}`,
126 body: "A pull request the soak polls.",
127 baseRefName: "main",
128 headRefName: pr.head,
129 headRefOid: pr.oid,
130 state: "OPEN",
131 isDraft: false,
132 mergeable: "MERGEABLE",
133 mergeStateStatus: running ? "BLOCKED" : "CLEAN",
134 reviewDecision: null,
135 additions: 1,
136 deletions: 0,
137 changedFiles: 1,
138 createdAt: at(600 + pr.number),
139 updatedAt: at(0),
140 mergedAt: null,
141 mergeCommit: null,
142 mergedBy: null,
143 closedAt: null,
144 isCrossRepository: false,
145 maintainerCanModify: false,
146 headRepository: { name: REPO, nameWithOwner: `${OWNER}/${REPO}`, viewerPermission: "ADMIN" },
147 headRepositoryOwner: { __typename: "User", login: OWNER },
148 headRef: { id: `REF_bench_${pr.number}` },
149 repository: { nameWithOwner: `${OWNER}/${REPO}` },
150 author: actor,
151 autoMergeRequest: null,
152 viewerCanUpdate: true,
153 viewerDidAuthor: true,
154 viewerCanUpdateBranch: false,
155 baseRef: { compare: { behindBy: 0 } },
156 reviewRequests: { nodes: [] },
157 latestReviews: { nodes: [] },
158 labels: { nodes: [] },
159 commits: {
160 nodes: [
161 {
162 commit: {
163 statusCheckRollup: {
164 state: running ? "PENDING" : "SUCCESS",
165 contexts: {
166 nodes: [
167 {
168 __typename: "CheckRun",
169 name: "test",
170 status: running ? "IN_PROGRESS" : "COMPLETED",
171 conclusion: running ? null : "SUCCESS",
172 startedAt: at(1),
173 completedAt: running ? null : at(0),
174 detailsUrl: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`,
175 checkSuite: {
176 workflowRun: {
177 event: "pull_request",
178 runNumber: minute,
179 workflow: { id: "W_bench", name: "CI" },
180 },
181 },
182 },
183 {
184 __typename: "StatusContext",
185 context: "lint",
186 state: "SUCCESS",
187 targetUrl: null,
188 createdAt: at(5),
189 description: "Lint passed",
190 },
191 ],
192 pageInfo: { hasNextPage: false, endCursor: null },
193 },
194 },
195 },
196 },
197 ],
198 },
199 };
200 };
201 const repositorySettings = {
202 mergeCommitAllowed: true,
203 squashMergeAllowed: true,
204 rebaseMergeAllowed: true,
205 autoMergeAllowed: false,
206 viewerPermission: "ADMIN",
207 };
208 const page = <A>(nodes: ReadonlyArray<A>) => ({
209 pageInfo: { hasNextPage: false, endCursor: null },
210 nodes,
211 });
212​
213 /** The `data` of a GraphQL answer, each aliased slice (`_0_repository`) answered on its own. */
214 const answer = (
215 operation: string,
216 variables: Readonly<Record<string, unknown>>,
217 now: number,
218 ): Record<string, unknown> | undefined => {
219 const prefixes = new Set(
220 Object.keys(variables).map((name) => /^(_\d+_)?/.exec(name)?.[1] ?? ""),
221 );
222 if (prefixes.size === 0) prefixes.add("");
223 const data: Record<string, unknown> = {};
224 for (const prefix of prefixes) {
225 const variable = (name: string) => variables[`${prefix}${name}`];
226 const byNumber = pullRequests.find((pr) => pr.number === variable("number"));
227 const single = byNumber === undefined ? null : pullRequestNode(byNumber, now);
228 const all = pullRequests.map((pr) => pullRequestNode(pr, now));
229 switch (operation) {
230 case "PullRequestsByHead":
231 case "PullRequestHeads":
232 data[`${prefix}repository`] = {
233 pullRequests: page(all.filter((pr) => pr.headRefName === variable("head"))),
234 };
235 break;
236 case "PullRequestList":
237 data[`${prefix}repository`] = { pullRequests: page(all) };
238 break;
239 case "PullRequestSearch":
240 data[`${prefix}search`] = page(all);
241 break;
242 case "PullRequestByNumber":
243 case "PullRequestSummary":
244 case "PullRequestStats":
245 case "PullRequestCheckContexts":
246 data[`${prefix}repository`] = { pullRequest: single };
247 break;
248 case "PullRequestCore":
249 data[`${prefix}repository`] = { ...repositorySettings, pullRequest: single };
250 break;
251 case "RoutingIdentityViewer":
252 data[`${prefix}viewer`] = { databaseId: 1, login: OWNER };
253 break;
254 case "ActorAvatars": {
255 const ids = variable("ids");
256 data[`${prefix}nodes`] = (Array.isArray(ids) ? ids : []).map(() => actor);
257 break;
258 }
259 default:
260 return undefined;
261 }
262 }
263 return data;
264 };
265​
266 /** REST answers by path under /api/v3; the body moves each minute where real polling sees change. */
267 const restAnswer = (path: string, now: number): unknown => {
268 const minute = Math.floor(now / 60_000);
269 const repository = `repos/${OWNER}/${REPO}`;
270 if (path === "user")
271 return { login: OWNER, id: 1, name: "Bench", avatar_url: "", type: "User" };
272 if (path === repository) {
273 return {
274 id: 1,
275 node_id: "R_bench",
276 name: REPO,
277 full_name: `${OWNER}/${REPO}`,
278 private: false,
279 default_branch: "main",
280 html_url: `https://${host}/${OWNER}/${REPO}`,
281 owner: { login: OWNER, id: 1, type: "User" },
282 permissions: { admin: true, maintain: true, push: true, triage: true, pull: true },
283 };
284 }
285 if (path === `${repository}/actions/runs`) {
286 return {
287 total_count: minute % 2 === 0 ? 1 : 0,
288 workflow_runs:
289 minute % 2 === 0
290 ? [
291 {
292 id: minute,
293 name: "CI",
294 html_url: `https://${host}/${OWNER}/${REPO}/actions/runs/${minute}`,
295 status: "in_progress",
296 },
297 ]
298 : [],
299 };
300 }
301 return undefined;
302 };
303​
304 const serveGit = Effect.fn("serverMetrics.fakeGitHub.git")(function* (relative: string) {
305 if (relative.split("/").includes("..")) return HttpServerResponse.empty({ status: 404 });
306 const file = path.join(bare, relative);
307 const body = yield* fs.readFile(file).pipe(Effect.option);
308 return body._tag === "Some"
309 ? HttpServerResponse.uint8Array(body.value, { contentType: "application/octet-stream" })
310 : HttpServerResponse.empty({ status: 404 });
311 });
312​
313 const app = Effect.gen(function* () {
314 const request = yield* HttpServerRequest.HttpServerRequest;
315 const url = new URL(request.url, "https://127.0.0.1");
316 const gitPrefix = `/${OWNER}/${REPO}.git/`;
317 let operation: string | undefined;
318 let response: HttpServerResponse.HttpServerResponse;
319 if (url.pathname.startsWith(gitPrefix)) {
320 // Dumb HTTP: a static info/refs makes git fall back to reading the bare repository's files.
321 response = yield* serveGit(url.pathname.slice(gitPrefix.length));
322 } else if (url.pathname === "/api/graphql") {
323 const raw = yield* request.text;
324 const body = yield* decodeGraphQl(raw).pipe(
325 Effect.orElseSucceed((): typeof GraphQlRequest.Type => ({})),
326 );
327 operation =
328 body.operationName ??
329 /\b(?:query|mutation)\s+(\w+)/.exec(body.query ?? "")?.[1] ??
330 "anonymous";
331 const data = answer(operation, body.variables ?? {}, yield* Clock.currentTimeMillis);
332 response =
333 data === undefined
334 ? HttpServerResponse.jsonUnsafe({ message: "Not Found" }, { status: 404 })
335 : HttpServerResponse.jsonUnsafe({ data });
336 } else {
337 const body = url.pathname.startsWith("/api/v3/")
338 ? restAnswer(url.pathname.slice("/api/v3/".length), yield* Clock.currentTimeMillis)
339 : undefined;
340 if (body === undefined) {
341 response = HttpServerResponse.jsonUnsafe(
342 { message: "Not Found", documentation_url: "https://docs.github.com/rest" },
343 { status: 404 },
344 );
345 } else {
346 // A weak validator of the body, so an unchanged answer revalidates as a 304.
347 const text = encodeJson(body);
348 const etag = `W/"${text.length.toString(16)}-${hash(text)}"`;
349 response =
350 request.headers["if-none-match"] === etag
351 ? HttpServerResponse.empty({ status: 304, headers: { etag } })
352 : HttpServerResponse.text(text, {
353 contentType: "application/json",
354 headers: { etag },
355 });
356 }
357 }
358 requests.push({
359 at: yield* Clock.currentTimeMillis,
360 method: request.method,
361 path: url.pathname + url.search,
362 operation,
363 status: response.status,
364 });
365 return response;
366 }).pipe(Effect.orElseSucceed(() => HttpServerResponse.empty({ status: 500 })));
367​
368 const key = yield* fs.readFileString(keyFile);
369 const cert = yield* fs.readFileString(certFile);
370 const context = yield* Layer.build(
371 NodeHttpServer.layer(() => NodeHttp2.createSecureServer({ key, cert, allowHTTP1: true }), {
372 port: 0,
373 host: "127.0.0.1",
374 }),
375 );
376 const port = yield* Effect.gen(function* () {
377 yield* HttpServer.serveEffect(Effect.interruptible(app));
378 const { address } = yield* HttpServer.HttpServer;
379 return address._tag === "UnixPathAddress" ? 0 : address.port;
380 }).pipe(Effect.provide(context));
381 // Tunnels only the fake host, so nothing the server sends through it reaches the internet.
382 const tunnels = new Set<NodeNet.Socket>();
383 const proxy = NodeHttp.createServer((_request, response) => {
384 response.writeHead(405).end();
385 });
386 proxy.on("connect", (request: NodeHttp.IncomingMessage, client: NodeNet.Socket) => {
387 if (request.url !== `${HOST}:443`) {
388 client.end("HTTP/1.1 403 Forbidden\r\n\r\n");
389 return;
390 }
391 const upstream = NodeNet.connect(port, "127.0.0.1", () => {
392 client.write("HTTP/1.1 200 Connection Established\r\n\r\n");
393 upstream.pipe(client);
394 client.pipe(upstream);
395 });
396 for (const socket of [client, upstream]) {
397 tunnels.add(socket);
398 socket.on("close", () => tunnels.delete(socket));
399 socket.on("error", () => {
400 client.destroy();
401 upstream.destroy();
402 });
403 }
404 });
405 const proxyPort = yield* Effect.acquireRelease(
406 Effect.callback<number, ScenarioError>((resume) => {
407 proxy.once("error", (error) =>
408 resume(
409 Effect.fail(new ScenarioError({ message: `the fake GitHub proxy: ${error.message}` })),
410 ),
411 );
412 proxy.listen(0, "127.0.0.1", () => {
413 const address = proxy.address();
414 resume(Effect.succeed(typeof address === "object" && address !== null ? address.port : 0));
415 });
416 }),
417 () =>
418 Effect.callback<void>((resume) => {
419 for (const socket of tunnels) socket.destroy();
420 proxy.closeAllConnections();
421 proxy.close(() => resume(Effect.void));
422 }),
423 );
424 const proxyUrl = `http://127.0.0.1:${proxyPort}`;
425​
426 /** Publishes the project to the fake remote and checks out a branch with an open PR. */
427 const setupProject = Effect.fn("serverMetrics.fakeGitHub.setupProject")(function* (
428 project: string,
429 ) {
430 const git = (args: ReadonlyArray<string>) => run("git", args, { cwd: project });
431 yield* git(["switch", "-q", "-c", "bench/feature"]);
432 yield* fs.writeFileString(path.join(project, "FEATURE.md"), "# feature\n");
433 yield* git(["add", "."]);
434 yield* git([
435 "-c",
436 "user.email=bench@t3.codes",
437 "-c",
438 "user.name=bench",
439 "commit",
440 "-qm",
441 "feature",
442 ]);
443 yield* git(["push", "-q", bare, "main", "bench/feature"]);
444 yield* run("git", ["--git-dir", bare, "update-server-info"]);
445 yield* git(["remote", "add", "origin", `https://${host}/${OWNER}/${REPO}.git`]);
446 yield* git(["config", "http.sslCAInfo", certFile]);
447 yield* git(["config", "http.proxy", proxyUrl]);
448 // A developer's NO_PROXY could send this past the proxy, which is the only route to the host.
449 const hostEnvironment = yield* HostProcess.Environment;
450 yield* run("git", ["fetch", "-q", "origin"], {
451 cwd: project,
452 env: {
453 ...Object.fromEntries(
454 Object.entries(hostEnvironment).filter(
455 (entry): entry is [string, string] => entry[1] !== undefined,
456 ),
457 ),
458 NO_PROXY: "",
459 no_proxy: "",
460 GIT_SSL_CAINFO: certFile,
461 },
462 });
463 yield* git(["branch", "-q", "--set-upstream-to", "origin/bench/feature"]);
464 const [feature, main] = (yield* git(["rev-parse", "HEAD", "main"])).stdout.trim().split("\n");
465 for (const pr of pullRequests) pr.oid = (pr.number === 1 ? feature : main) ?? pr.oid;
466 setupRequests = requests.length;
467 publishedMain = main;
468 });
469​
470 let pushes = 0;
471 /** Lands a commit on the remote's main, so the server's next fetch transfers something. */
472 const advanceRemote = Effect.gen(function* () {
473 const git = (args: ReadonlyArray<string>) => run("git", ["--git-dir", bare, ...args]);
474 const commit = (yield* git([
475 "-c",
476 "user.email=bench@t3.codes",
477 "-c",
478 "user.name=bench",
479 "commit-tree",
480 "main^{tree}",
481 "-p",
482 "main",
483 "-m",
484 `upstream ${++pushes}`,
485 ])).stdout.trim();
486 yield* git(["update-ref", "refs/heads/main", commit]);
487 yield* git(["update-server-info"]);
488 });
489​
490 /** Requests the project setup made before the server started, which `verify` leaves out. */
491 let setupRequests = 0;
492 let publishedMain: string | undefined;
493 let fetchedPush = false;
494 let completedPolls = 0;
495 const failures: Array<string> = [];
496 /**
497 * What a web client with the pull requests sidebar and the branch's PR open asks for: the list,
498 * then the branch PR's summary and checks, every 30 s until interrupted. Failures are kept, not
499 * thrown, so one bad answer does not end the soak.
500 */
501 const pollLikeWebClient = Effect.fn("serverMetrics.fakeGitHub.poll")(function* (rpc: {
502 readonly list: (input: PullRequestListInput) => Effect.Effect<PullRequestListResult, Failure>;
503 readonly summary: (input: PullRequestRef) => Effect.Effect<unknown, Failure>;
504 readonly checks: (input: PullRequestRef) => Effect.Effect<unknown, Failure>;
505 }) {
506 const record = (what: string) => (error: Failure) =>
507 Effect.sync(() => {
508 failures.push(`${what}: ${error.message}`);
509 });
510 while (true) {
511 const listed = yield* rpc
512 .list({ state: "open" })
513 .pipe(Effect.tapError(record("pullRequests.list")), Effect.option);
514 const entry =
515 listed._tag === "Some"
516 ? listed.value.entries.find((row) => row.headBranch === "bench/feature")
517 : undefined;
518 if (listed._tag === "Some" && entry === undefined) {
519 failures.push(`pullRequests.list: no branch PR in ${listed.value.entries.length} rows`);
520 }
521 if (entry !== undefined) {
522 const ref = {
523 projectId: entry.projectId,
524 host: entry.host,
525 repository: entry.repository,
526 number: entry.number,
527 };
528 const completed = yield* Effect.all([rpc.summary(ref), rpc.checks(ref)]).pipe(
529 Effect.as(true),
530 Effect.catch((error) =>
531 record("pullRequests.summary/checks")(error).pipe(Effect.as(false)),
532 ),
533 );
534 if (completed) completedPolls++;
535 }
536 yield* Effect.sleep(Duration.seconds(30));
537 }
538 });
539​
540 return {
541 host,
542 /** The server's view of the host: the fake token and CA, and none of the developer's logins. */
543 env: {
544 GH_HOST: host,
545 GH_ENTERPRISE_TOKEN: TOKEN,
546 GITHUB_ENTERPRISE_TOKEN: "",
547 GH_TOKEN: "",
548 GITHUB_TOKEN: "",
549 // An empty gh config, so a gh the server runs has no login for any host.
550 GH_CONFIG_DIR: path.join(dir, "gh"),
551 NODE_EXTRA_CA_CERTS: certFile,
552 // Overrides a developer's own GIT_SSL_CAINFO, which would win over the repository's setting.
553 GIT_SSL_CAINFO: certFile,
554 NODE_USE_ENV_PROXY: "1",
555 HTTPS_PROXY: proxyUrl,
556 https_proxy: proxyUrl,
557 // The fake Anthropic API and the server's own loopback listeners stay direct.
558 NO_PROXY: "127.0.0.1,localhost,::1",
559 no_proxy: "127.0.0.1,localhost,::1",
560 },
561 setupProject,
562 advanceRemote,
563 /** Records whether the project's origin/main moved past setup, i.e. the server fetched a push. */
564 checkFetched: (project: string) =>
565 run("git", ["rev-parse", "refs/remotes/origin/main"], { cwd: project }).pipe(
566 Effect.map(({ stdout }) => {
567 fetchedPush = stdout.trim() !== publishedMain;
568 }),
569 ),
570 requests: requests as ReadonlyArray<ForgeRequest>,
571 pollLikeWebClient,
572 /**
573 * Prints what the server asked for, and fails unless it polled pull requests and checks and
574 * fetched from the remote. Poller failures are reported, not fatal: a long soak can see one.
575 */
576 verify: Effect.gen(function* () {
577 const counts = new Map<string, number>();
578 for (const request of requests.slice(setupRequests)) {
579 const key =
580 request.operation ??
581 (request.path.startsWith(`/${OWNER}/${REPO}.git/`)
582 ? request.status !== 200
583 ? undefined
584 : request.path.startsWith(`/${OWNER}/${REPO}.git/info/refs`)
585 ? "git fetch"
586 : undefined
587 : `${request.method} ${request.path.replace(/\?.*/, "")} ${request.status}`);
588 if (key !== undefined) counts.set(key, (counts.get(key) ?? 0) + 1);
589 }
590 const listed = [...counts].map(([key, count]) => `${key} ×${count}`).join(", ");
591 yield* Console.error(`fake GitHub served ${requests.length} requests: ${listed}`);
592 if (failures.length > 0) {
593 yield* Console.error(
594 `fake GitHub: ${failures.length} client polls failed, first: ${failures[0]}`,
595 );
596 }
597 const missing = [
598 "PullRequestsByHead",
599 "PullRequestSearch",
600 "PullRequestCore",
601 "git fetch",
602 ].filter((key) => !counts.has(key));
603 if (pushes > 0 && !fetchedPush) missing.push("a fetch that brought in a pushed commit");
604 if (completedPolls === 0) missing.push("one full client poll (list, summary, checks)");
605 if (missing.length > 0) {
606 return yield* new ScenarioError({
607 message: `the soak never reached the fake GitHub for ${missing.join(", ")}`,
608 });
609 }
610 }),
611 };
612});
613​
614export type FakeGitHub = Effect.Success<ReturnType<typeof serveFakeGitHub>>;