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

gitHubGraphQlClient.ts

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