Open History to see the last commit
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...");
28}
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);
56}
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 Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-measure-pr-preview-" })),
82 Layer.provideMerge(VcsProcess.layer),
83 Layer.provideMerge(NodeServices.layer),
84);
85
86const services = GitHubPullRequestApi.layer.pipe(
87 Layer.provideMerge(GitHubRest.layerWithDependencies),
88 Layer.provideMerge(measuredHttp),
89 Layer.provideMerge(sourceControlHost),
90);
91
92const encodeJson = Schema.encodeSync(Schema.fromJsonString(Schema.Unknown));
93
94for (const mode of ["detail", "preview"] as const) {
95 const rows = await Effect.runPromise(
96 Effect.scoped(
97 Effect.gen(function* () {
98 const provider = yield* GitHubPullRequestProvider.make;
99 // Where the `graphql` quota stands before the first read. `rate_limit` is free.
100 const api = yield* GitHubRest.GitHubRest;
101 const limits = decodeRateLimit(
102 (yield* api.rest({ host: "github.com", operation: "rateLimit", path: "rate_limit" }))
103 .body,
104 ).resources.graphql;
105 graphqlUsed = { used: limits.used, reset: String(limits.reset) };
106 return yield* Effect.forEach(numbers.map(Number), (number) =>
107 Effect.gen(function* () {
108 const input = { cwd: process.cwd(), repository, host: "github.com", number };
109 reads.length = 0;
110 const start = performance.now();
111 const value = yield* mode === "detail"
112 ? provider.getChangeRequest(input)
113 : provider.getChangeRequestPreview!(input);
114 const elapsedMs = Math.round(performance.now() - start);
115 const measured = [...reads];
116 const points = measured.reduce((total, read) => total + read.cost, 0);
117 return {
118 repository,
119 number,
120 mode,
121 state: value.state,
122 elapsedMs,
123 points,
124 graphqlRequests: measured.reduce((total, read) => total + read.graphqlRequests, 0),
125 restRequests: measured.reduce((total, read) => total + read.restRequests, 0),
126 };
127 }),
128 );
129 }),
130 ).pipe(Effect.provide(services)),
131 );
132 for (const row of rows) await Effect.runPromise(Console.log(encodeJson(row)));
133}