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

measure-pr-preview.ts

151 lines6.2 KB

1// Run with: node packages/source-control-github/scripts/measure-pr-preview.ts owner/repo 123 456
2// Real GitHub reads share repository-permission caches, excluding browser and service caches.
3// HTTP client request counts are exact; GraphQL cost uses changes in `x-ratelimit-used`,
4// which are approximate when other clients spend the same token's quota.
5import * as NodeServices from "@effect/platform-node/NodeServices";
6import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
7import * as TestSourceControlHost from "@t3tools/source-control-testing/TestSourceControlHost";
8import * as Effect from "effect/Effect";
9import * as Console from "effect/Console";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import * as Stream from "effect/Stream";
13import { FetchHttpClient, HttpClient } from "effect/http";
14import { ChildProcess, ChildProcessSpawner } from "effect/process";
15​
16import * as GitHubAppAccess from "../src/server/GitHubAppAccess.ts";
17import * as GitHubPullRequestApi from "../src/server/GitHubPullRequestApi.ts";
18import * as GitHubPullRequestProvider from "../src/server/GitHubPullRequestProvider.ts";
19import * as GitHubRest from "../src/server/GitHubRest.ts";
20​
21const [repository, ...numbers] = process.argv.slice(2);
22if (!repository || numbers.length === 0 || numbers.some((number) => !/^\d+$/.test(number))) {
23 throw new Error(
24 "Usage: node packages/source-control-github/scripts/measure-pr-preview.ts owner/repo number...",
25 );
27​
28type Read = { graphqlRequests: number; restRequests: number; cost: number };
29const reads: Read[] = [];
30​
31let graphqlUsed: { used: number; reset: string } | null = null;
32const decodeRateLimit = Schema.decodeUnknownSync(
33 Schema.fromJsonString(
34 Schema.Struct({
35 resources: Schema.Struct({
36 graphql: Schema.Struct({ used: Schema.Number, reset: Schema.Number }),
37 }),
38 }),
39 ),
40);
41​
42// Count only increases in `used` so out-of-order answers do not double-count quota.
43function graphqlCost(headers: Readonly<Record<string, string | undefined>>): number {
44 const used = Number(headers["x-ratelimit-used"]);
45 const reset = headers["x-ratelimit-reset"] ?? "";
46 if (headers["x-ratelimit-resource"] !== "graphql" || !Number.isFinite(used)) return 0;
47 const previous = graphqlUsed?.reset === reset ? graphqlUsed.used : 0;
48 graphqlUsed = { used: Math.max(previous, used), reset };
49 return Math.max(0, used - previous);
51​
52const measuredHttp = Layer.effect(
53 HttpClient.HttpClient,
54 Effect.gen(function* () {
55 const client = yield* HttpClient.HttpClient;
56 return HttpClient.tap(client, (response) =>
57 Effect.sync(() => {
58 const graphql = new URL(response.request.url).pathname.endsWith("/graphql");
59 reads.push({
60 graphqlRequests: graphql ? 1 : 0,
61 restRequests: graphql ? 0 : 1,
62 cost: graphql ? graphqlCost(response.headers) : 0,
63 });
64 }),
65 );
66 }),
67).pipe(Layer.provide(FetchHttpClient.layer));
68​
69// Default settings, so `gh` picks the account and no saved token applies. Only the credential
70// lookup runs a process, and it needs no more than its output.
71const sourceControlHost = Layer.unwrap(
72 Effect.gen(function* () {
73 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
74 return TestSourceControlHost.layer({
75 process: {
76 run: (input) =>
77 Effect.scoped(
78 Effect.gen(function* () {
79 const handle = yield* spawner.spawn(
80 ChildProcess.make(input.command, [...input.args], {
81 cwd: input.spawnCwd ?? input.cwd,
82 env: input.env,
83 extendEnv: true,
84 }),
85 );
86 const [stdout, stderr, exitCode] = yield* Effect.all(
87 [
88 Stream.mkString(Stream.decodeText(handle.stdout)),
89 Stream.mkString(Stream.decodeText(handle.stderr)),
90 handle.exitCode,
91 ],
92 { concurrency: "unbounded" },
93 );
94 return { exitCode, stdout, stderr, stdoutTruncated: false, stderrTruncated: false };
95 }),
96 ).pipe(Effect.orDie),
97 },
98 });
99 }),
100).pipe(Layer.provideMerge(NodeServices.layer));
101​
102const services = GitHubPullRequestApi.layer.pipe(
103 Layer.provideMerge(GitHubAppAccess.layer),
104 Layer.provideMerge(GitHubRest.layerWithDependencies),
105 Layer.provideMerge(SourceControlRateLimit.layer),
106 Layer.provideMerge(measuredHttp),
107 Layer.provideMerge(sourceControlHost),
108);
109​
110const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
111​
112for (const mode of ["detail", "preview"] as const) {
113 const rows = await Effect.runPromise(
114 Effect.scoped(
115 Effect.gen(function* () {
116 const provider = yield* GitHubPullRequestProvider.make;
117 // `rate_limit` reads do not spend GraphQL quota.
118 const api = yield* GitHubRest.GitHubRest;
119 const limits = decodeRateLimit(
120 (yield* api.rest({ host: "github.com", operation: "rateLimit", path: "rate_limit" }))
121 .body,
122 ).resources.graphql;
123 graphqlUsed = { used: limits.used, reset: String(limits.reset) };
124 return yield* Effect.forEach(numbers.map(Number), (number) =>
125 Effect.gen(function* () {
126 const input = { cwd: process.cwd(), repository, host: "github.com", number };
127 reads.length = 0;
128 const start = performance.now();
129 const value = yield* mode === "detail"
130 ? provider.getChangeRequest(input)
131 : provider.getChangeRequestPreview!(input);
132 const elapsedMs = Math.round(performance.now() - start);
133 const measured = [...reads];
134 const points = measured.reduce((total, read) => total + read.cost, 0);
135 return {
136 repository,
137 number,
138 mode,
139 state: value.state,
140 elapsedMs,
141 points,
142 graphqlRequests: measured.reduce((total, read) => total + read.graphqlRequests, 0),
143 restRequests: measured.reduce((total, read) => total + read.restRequests, 0),
144 };
145 }),
146 );
147 }),
148 ).pipe(Effect.provide(services)),
149 );
150 for (const row of rows) await Effect.runPromise(Console.log(encodeJson(row)));