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