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

gitHubGraphQlClient.ts

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