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

measure-pr-preview.ts

135 lines6.1 KB

1// Run with: node apps/server/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 Effect from "effect/Effect";
9import * as Console from "effect/Console";
10import * as Layer from "effect/Layer";
11import * as Schema from "effect/Schema";
12import { FetchHttpClient, HttpClient } from "effect/http";
13​
14import * as GitHubPullRequestApi from "@t3tools/source-control-github/server/GitHubPullRequestApi";
15import * as GitHubPullRequestProvider from "@t3tools/source-control-github/server/GitHubPullRequestProvider";
16import * as GitHubRest from "@t3tools/source-control-github/server/GitHubRest";
17import * as ServerConfig from "../src/config.ts";
18import * as ServerSettings from "../src/serverSettings.ts";
19import * as ServerSourceControlHost from "../src/sourceControl/ServerSourceControlHost.ts";
20import * as GitVcsDriver from "../src/vcs/GitVcsDriver.ts";
21import * as VcsDriverRegistry from "../src/vcs/VcsDriverRegistry.ts";
22import * as VcsProcess from "../src/vcs/VcsProcess.ts";
23import * as VcsProjectConfig from "../src/vcs/VcsProjectConfig.ts";
24​
25const [repository, ...numbers] = process.argv.slice(2);
26if (!repository || numbers.length === 0 || numbers.some((number) => !/^\d+$/.test(number))) {
27 throw new Error("Usage: node apps/server/scripts/measure-pr-preview.ts owner/repo number...");
29​
30type Read = { graphqlRequests: number; restRequests: number; cost: number };
31const reads: Read[] = [];
32​
33/** The `graphql` quota's use so far, and the window it counts in. */
34let graphqlUsed: { used: number; reset: string } | null = null;
35const decodeRateLimit = Schema.decodeUnknownSync(
36 Schema.fromJsonString(
37 Schema.Struct({
38 resources: Schema.Struct({
39 graphql: Schema.Struct({ used: Schema.Number, reset: Schema.Number }),
40 }),
41 }),
42 ),
43);
44​
45/**
46 * What one GraphQL answer spent: how far it moved `used` past the highest value seen, so requests
47 * answered out of order still add up to the window's total. A new window starts from zero.
48 */
49function graphqlCost(headers: Readonly<Record<string, string | undefined>>): number {
50 const used = Number(headers["x-ratelimit-used"]);
51 const reset = headers["x-ratelimit-reset"] ?? "";
52 if (headers["x-ratelimit-resource"] !== "graphql" || !Number.isFinite(used)) return 0;
53 const previous = graphqlUsed?.reset === reset ? graphqlUsed.used : 0;
54 graphqlUsed = { used: Math.max(previous, used), reset };
55 return Math.max(0, used - previous);
57​
58/** The HTTP client the GitHub transports send through, recording each request as it is answered. */
59const measuredHttp = Layer.effect(
60 HttpClient.HttpClient,
61 Effect.gen(function* () {
62 const client = yield* HttpClient.HttpClient;
63 return HttpClient.tap(client, (response) =>
64 Effect.sync(() => {
65 const graphql = new URL(response.request.url).pathname.endsWith("/graphql");
66 reads.push({
67 graphqlRequests: graphql ? 1 : 0,
68 restRequests: graphql ? 0 : 1,
69 cost: graphql ? graphqlCost(response.headers) : 0,
70 });
71 }),
72 );
73 }),
74).pipe(Layer.provide(FetchHttpClient.layer));
75​
76// The server's host port over default settings: gh's own account choice, no saved token.
77const sourceControlHost = ServerSourceControlHost.layer.pipe(
78 Layer.provide(VcsDriverRegistry.layer.pipe(Layer.provide(VcsProjectConfig.layer))),
79 Layer.provide(GitVcsDriver.layer),
80 Layer.provide(ServerSettings.layerTest()),
81 // A scratch state directory, so nothing here touches a real T3 home.
82 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-measure-pr-preview-" })),
83 Layer.provideMerge(VcsProcess.layer),
84 Layer.provideMerge(NodeServices.layer),
85);
86​
87const services = GitHubPullRequestApi.layer.pipe(
88 Layer.provideMerge(GitHubRest.layerWithDependencies),
89 Layer.provideMerge(measuredHttp),
90 Layer.provideMerge(sourceControlHost),
91);
92​
93const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
94​
95for (const mode of ["detail", "preview"] as const) {
96 // Start each side cold, then retain the caches shared across PRs in one session.
97 const rows = await Effect.runPromise(
98 Effect.scoped(
99 Effect.gen(function* () {
100 const provider = yield* GitHubPullRequestProvider.make;
101 // Where the `graphql` quota stands before the first read. `rate_limit` is free.
102 const api = yield* GitHubRest.GitHubRest;
103 const limits = decodeRateLimit(
104 (yield* api.rest({ host: "github.com", operation: "rateLimit", path: "rate_limit" }))
105 .body,
106 ).resources.graphql;
107 graphqlUsed = { used: limits.used, reset: String(limits.reset) };
108 return yield* Effect.forEach(numbers.map(Number), (number) =>
109 Effect.gen(function* () {
110 const input = { cwd: process.cwd(), repository, host: "github.com", number };
111 reads.length = 0;
112 const start = performance.now();
113 const value = yield* mode === "detail"
114 ? provider.getChangeRequest(input)
115 : provider.getChangeRequestPreview!(input);
116 const elapsedMs = Math.round(performance.now() - start);
117 const measured = [...reads];
118 const points = measured.reduce((total, read) => total + read.cost, 0);
119 return {
120 repository,
121 number,
122 mode,
123 state: value.state,
124 elapsedMs,
125 points,
126 graphqlRequests: measured.reduce((total, read) => total + read.graphqlRequests, 0),
127 restRequests: measured.reduce((total, read) => total + read.restRequests, 0),
128 };
129 }),
130 );
131 }),
132 ).pipe(Effect.provide(services)),
133 );
134 for (const row of rows) await Effect.runPromise(Console.log(encodeJson(row)));