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

measure-pr-preview.ts

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