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

measure-pr-preview.ts

180 lines7.5 KB

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