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