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

gitHubGraphQlClient.ts

318 lines12.7 KB

1import { normalizeHost } from "@t3tools/source-control-core/server/pullRequestUtils";
2import * as Context from "effect/Context";
3import * as Effect from "effect/Effect";
4import { dual } from "effect/Function";
5import * as Layer from "effect/Layer";
6import * as Option from "effect/Option";
7import * as Schema from "effect/Schema";
8import * as Stream from "effect/Stream";
9import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
10import * as Headers from "effect/http/Headers";
11import { GraphQLClientError, GraphQLMiddleware, GraphQLProtocol } from "effect/graphql";
12import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
13import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
14​
15import * as GitHubCredentials from "./GitHubCredentials.ts";
16import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
17​
18const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
19/** Added to the answer, never sent: names the credential an errored answer was given to. */
20const CREDENTIAL_SOURCE_HEADER = "x-t3code-credential-source";
21const isCredentialSource = Schema.is(GitHubCredentials.GitHubCredentialSource);
22​
23/** One client serves all hosts; each call must supply its target. */
24export class GitHubGraphQlTarget extends Context.Service<
25 GitHubGraphQlTarget,
26 {
27 readonly host: string;
28 readonly cwd?: string | undefined;
29 readonly operation: string;
30 /** Overrides `SourceControlRateLimit.Interactive` for this one call. */
31 readonly allowReserve?: boolean | undefined;
32 /** A longer answer fails as a `GitHubApiResponseError`. Defaults to 8 MB. */
33 readonly maxResponseBytes?: number | undefined;
34 }
35>()("@t3tools/source-control-github/server/gitHubGraphQlClient/GitHubGraphQlTarget") {}
36​
37// Group traces by query without exposing query text.
38function queryHash(query: string): string {
39 let hash = 0x811c9dc5;
40 for (let index = 0; index < query.length; index++) {
41 hash ^= query.charCodeAt(index);
42 hash = Math.imul(hash, 0x01000193);
43 }
44 return (hash >>> 0).toString(16).padStart(8, "0");
46​
47export const isNotFoundOnly = (error: unknown): boolean =>
48 GraphQLClientError.isGraphQLClientError(error) &&
49 error.reason._tag === "ResponseError" &&
50 error.reason.errors.every((graphQlError) => graphQlError["type"] === "NOT_FOUND");
51​
52/** Share REST's credentials/slots/quota/pause; leave non-rate-limit errors to each lookup. */
53export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
54 GitHubGraphQlAuth,
55 { requires: GitHubGraphQlTarget; error: GitHubRequestPolicy.GitHubApiError }
56>()("@t3tools/source-control-github/server/gitHubGraphQlClient/GitHubGraphQlAuth") {
57 static readonly layer = Layer.effect(
58 GitHubGraphQlAuth,
59 Effect.gen(function* () {
60 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
61 return GitHubGraphQlAuth.of({
62 execute: Effect.fn("GitHubGraphQlAuth.execute")(function* ({ request, next }) {
63 const target = yield* GitHubGraphQlTarget;
64 const host = normalizeHost(target.host);
65 yield* Effect.annotateCurrentSpan({
66 "github.kind": "graphql",
67 "github.graphql.query_hash": queryHash(request.query),
68 });
69 return yield* policy.request(
70 {
71 host,
72 cwd: target.cwd,
73 operation: target.operation,
74 resource: "graphql",
75 allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
76 },
77 (headers, source) =>
78 next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
79 Effect.map((answer) => {
80 const status = answer.status;
81 const responseHeaders = answer.headers ?? Headers.empty;
82 const rateLimited = GitHubRequestPolicy.isRateLimited({
83 status: status ?? 200,
84 headers: responseHeaders,
85 ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),
86 });
87 const withheld = (answer.errors ?? []).some(
88 (error) => error["type"] === "NOT_FOUND" || error["type"] === "FORBIDDEN",
89 );
90 return rateLimited
91 ? { _tag: "RateLimited" as const, status, headers: responseHeaders }
92 : {
93 _tag: "Ok" as const,
94 // The source is local; never trust one GitHub's answer carries.
95 value: {
96 ...answer,
97 headers:
98 source === undefined
99 ? Headers.remove(responseHeaders, CREDENTIAL_SOURCE_HEADER)
100 : Headers.set(responseHeaders, CREDENTIAL_SOURCE_HEADER, source),
101 },
102 withheld,
103 status,
104 headers: responseHeaders,
105 };
106 }),
107 Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>
108 refused(error, { host, operation: target.operation }),
109 ),
110 ),
111 );
112 }),
113 subscribe: () => Stream.die(new Error("GitHub GraphQL has no subscriptions.")),
114 });
115 }),
116 );
118​
119/**
120 * What a refusal GitHub sent as an HTTP status means, read the way REST reads one. A
121 * failure that never reached GitHub is a request error; one that is not about the transport
122 * (an answer that does not decode) is the client's own.
123 */
124const refused = Effect.fn("gitHubGraphQlClient.refused")(function* (
125 error: GraphQLClientError.GraphQLClientError,
126 context: { readonly host: string; readonly operation: string },
127) {
128 const reason = error.reason;
129 if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {
130 return yield* error;
131 }
132 const status = reason.status;
133 if (reason._tag === "TransportError" && status === undefined) {
134 return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });
135 }
136 const headers = reason.headers ?? Headers.empty;
137 // A secondary limit is a 403 that only its body names, which the transport read.
138 const body =
139 reason._tag === "TransportError" &&
140 HttpClientError.isHttpClientError(reason.cause) &&
141 reason.cause.response !== undefined
142 ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))
143 : "";
144 const tag = GitHubRequestPolicy.isRateLimited({
145 status: status ?? 200,
146 headers,
147 body,
148 ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),
149 })
150 ? "RateLimited"
151 : status === 401
152 ? "Unauthorized"
153 : status === 404
154 ? "NotFound"
155 : "Failed";
156 return { _tag: tag, status: status ?? 200, headers } as const;
157});
158​
159/**
160 * Reads each answer whole, up to the call's byte cap, before the protocol parses it. A body cut
161 * at the cap hides any `errors` past the cut and cannot be decoded, so it fails, which the
162 * middleware reports as a `GitHubApiResponseError` with the answer's status.
163 */
164const capResponse = Effect.fn("gitHubGraphQlClient.capResponse")(function* (
165 effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
166) {
167 const response = yield* effect;
168 const target = yield* Effect.serviceOption(GitHubGraphQlTarget);
169 const maxBytes = Option.match(target, {
170 onNone: () => DEFAULT_MAX_RESPONSE_BYTES,
171 onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
172 });
173 const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(
174 Effect.catchIf(
175 (error) => error.reason._tag === "EmptyBodyError",
176 () => Effect.succeed({ text: "", truncated: false }),
177 ),
178 );
179 if (collected.truncated) {
180 return yield* new HttpClientError.HttpClientError({
181 reason: new HttpClientError.DecodeError({
182 request: response.request,
183 response,
184 description: `The answer is longer than ${maxBytes} bytes.`,
185 }),
186 });
187 }
188 return HttpClientResponse.fromWeb(
189 response.request,
190 new Response(collected.text === "" ? null : collected.text, {
191 status: response.status,
192 headers: response.headers,
193 }),
194 );
195});
196​
197// Endpoint URLs isolate hosts. Disable client tracing to protect SHAs and branches in url.full.
198const layerProtocol = GraphQLProtocol.layerHttp({
199 url: ({ context }) =>
200 GitHubRequestPolicy.gitHubApiUrls(Context.getUnsafe(context, GitHubGraphQlTarget).host).graphql,
201}).pipe(
202 Layer.provide(
203 Layer.effect(
204 HttpClient.HttpClient,
205 Effect.gen(function* () {
206 const client = yield* HttpClient.HttpClient;
207 return HttpClient.transformResponse(client, (effect) =>
208 capResponse(effect).pipe(
209 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
210 ),
211 );
212 }),
213 ),
214 ),
215);
216​
217export const layer = Layer.merge(GitHubGraphQlAuth.layer, layerProtocol);
218​
219/** Isolate credentials/rate-limit scopes; transport URLs already separate hosts. */
220export const batchKey = (context: Context.Context<GitHubGraphQlTarget>) => {
221 const pinned = Context.getOrElse(context, GitHubRequestPolicy.PinnedGitHubCredential, () => null);
222 return JSON.stringify([
223 pinned?.credentialFingerprint ?? null,
224 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
225 // An unpinned (app) batch falls back to one checkout's login, so checkouts must not share one.
226 pinned === null ? (Context.get(context, GitHubGraphQlTarget).cwd ?? null) : null,
227 ]);
228};
229​
230/**
231 * Pin before joining a resolver: its batch key must reflect the token that will send it. The
232 * app's token is the same for every checkout and stays unpinned, keeping its fallback to the
233 * checkout's own login.
234 */
235export const withCheckoutCredential = Effect.fn("gitHubGraphQlClient.withCheckoutCredential")(
236 function* <A, E, R>(
237 credential: GitHubRequestPolicy.GitHubRequestPolicy["Service"]["credential"],
238 input: { readonly cwd: string; readonly host: string },
239 effect: Effect.Effect<A, E, R>,
240 ) {
241 const host = normalizeHost(input.host);
242 const held = yield* credential(host, { cwd: input.cwd });
243 if (held.source === "app") return yield* effect;
244 return yield* effect.pipe(
245 Effect.provideService(GitHubRequestPolicy.PinnedGitHubCredential, {
246 host,
247 token: held.token,
248 credentialFingerprint: held.fingerprint,
249 ...(held.source === undefined ? {} : { source: held.source }),
250 }),
251 );
252 },
253);
254​
255const fromClientError = (
256 target: { readonly host: string; readonly operation: string },
257 error: GraphQLClientError.GraphQLClientError,
258):
259 | GitHubRequestPolicy.GitHubApiNotFoundError
260 | GitHubRequestPolicy.GitHubApiResponseError
261 | GraphQLClientError.GraphQLClientError => {
262 const reason = error.reason;
263 if (reason._tag !== "ResponseError") return error;
264 const context = {
265 host: normalizeHost(target.host),
266 operation: target.operation,
267 };
268 const credential = Option.filter(
269 Headers.get(reason.headers ?? Headers.empty, CREDENTIAL_SOURCE_HEADER),
270 isCredentialSource,
271 );
272 return isNotFoundOnly(error)
273 ? new GitHubRequestPolicy.GitHubApiNotFoundError({
274 ...context,
275 ...(Option.isSome(credential) ? { credential: credential.value } : {}),
276 })
277 : new GitHubRequestPolicy.GitHubApiResponseError({
278 ...context,
279 status: reason.status ?? 200,
280 githubErrors: reason.errors.map((graphQlError) => graphQlError.message),
281 githubErrorTypes: reason.errors.map((graphQlError) =>
282 typeof graphQlError["type"] === "string" ? graphQlError["type"] : null,
283 ),
284 });
285};
286​
287/** Map response errors to policy errors; callers map decode errors to read errors. */
288export const call: {
289 (
290 target: GitHubGraphQlTarget["Service"],
291 ): <A, E, R>(
292 effect: Effect.Effect<A, E, R>,
293 ) => Effect.Effect<
294 A,
295 E | GitHubRequestPolicy.GitHubApiNotFoundError | GitHubRequestPolicy.GitHubApiResponseError,
296 Exclude<R, GitHubGraphQlTarget>
297 >;
298 <A, E, R>(
299 effect: Effect.Effect<A, E, R>,
300 target: GitHubGraphQlTarget["Service"],
301 ): Effect.Effect<
302 A,
303 E | GitHubRequestPolicy.GitHubApiNotFoundError | GitHubRequestPolicy.GitHubApiResponseError,
304 Exclude<R, GitHubGraphQlTarget>
305 >;
306} = dual(2, <A, E, R>(effect: Effect.Effect<A, E, R>, target: GitHubGraphQlTarget["Service"]) =>
307 effect.pipe(
308 Effect.mapError((error) =>
309 GraphQLClientError.isGraphQLClientError(error)
310 ? (fromClientError(target, error) as
311 | E
312 | GitHubRequestPolicy.GitHubApiNotFoundError
313 | GitHubRequestPolicy.GitHubApiResponseError)
314 : error,
315 ),
316 Effect.provideService(GitHubGraphQlTarget, target),
317 ),
318);