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

gitHubGraphQlClient.ts

292 lines11.6 KB

1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import { dual } from "effect/Function";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Stream from "effect/Stream";
7import { HttpClient, HttpClientError, HttpClientResponse } from "effect/http";
8import * as Headers from "effect/http/Headers";
9import { GraphQLClientError, GraphQLMiddleware, GraphQLProtocol } from "effect/graphql";
10import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
11import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
12​
13import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
14​
15const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
16​
17/**
18 * The GitHub host and operation a generated GraphQL call is sent as. One client serves every host,
19 * so each call names its own.
20 */
21export class GitHubGraphQlTarget extends Context.Service<
22 GitHubGraphQlTarget,
23 {
24 readonly host: string;
25 readonly operation: string;
26 /** Overrides `SourceControlRateLimit.Interactive` for this one call. */
27 readonly allowReserve?: boolean | undefined;
28 /** A longer answer fails as a `GitHubApiResponseError`. Defaults to 8 MB. */
29 readonly maxResponseBytes?: number | undefined;
30 }
31>()("@t3tools/source-control-github/server/gitHubGraphQlClient/GitHubGraphQlTarget") {}
32​
33/** A stable short id for a GraphQL document, so traces group by query without its text. */
34function queryHash(query: string): string {
35 let hash = 0x811c9dc5;
36 for (let index = 0; index < query.length; index++) {
37 hash ^= query.charCodeAt(index);
38 hash = Math.imul(hash, 0x01000193);
39 }
40 return (hash >>> 0).toString(16).padStart(8, "0");
42​
43/**
44 * Whether GitHub's `errors` all say the thing asked for does not exist, or that the credential
45 * cannot see it. A batch reports that for one pull request alone.
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/**
53 * GitHub's auth and rate limits around a generated GraphQL call, through `GitHubRequestPolicy`:
54 * the same credential, request slots, quota and pause as REST. It fails with the policy's
55 * errors, which every GitHub caller already maps. GraphQL `errors` that are not a rate limit are
56 * the client's: a batch settles them per pull request, and `call` maps the rest.
57 */
58export class GitHubGraphQlAuth extends GraphQLMiddleware.Service<
59 GitHubGraphQlAuth,
60 { requires: GitHubGraphQlTarget; error: GitHubRequestPolicy.GitHubApiError }
61>()("@t3tools/source-control-github/server/gitHubGraphQlClient/GitHubGraphQlAuth") {
62 static readonly layer = Layer.effect(
63 GitHubGraphQlAuth,
64 Effect.gen(function* () {
65 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
66 return GitHubGraphQlAuth.of({
67 execute: Effect.fn("GitHubGraphQlAuth.execute")(function* ({ request, next }) {
68 const target = yield* GitHubGraphQlTarget;
69 const host = GitHubRequestPolicy.normalizeHost(target.host);
70 yield* Effect.annotateCurrentSpan({
71 "github.kind": "graphql",
72 "github.graphql.query_hash": queryHash(request.query),
73 });
74 return yield* policy.request(
75 {
76 host,
77 operation: target.operation,
78 resource: "graphql",
79 allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
80 },
81 (headers) =>
82 next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
83 Effect.map((answer) => {
84 const status = answer.status;
85 const responseHeaders = answer.headers ?? Headers.empty;
86 const rateLimited = GitHubRequestPolicy.isRateLimited({
87 status: status ?? 200,
88 headers: responseHeaders,
89 ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),
90 });
91 return rateLimited
92 ? { _tag: "RateLimited" as const, status, headers: responseHeaders }
93 : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };
94 }),
95 Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>
96 refused(error, { host, operation: target.operation }),
97 ),
98 ),
99 );
100 }),
101 subscribe: () => Stream.die(new Error("GitHub GraphQL has no subscriptions.")),
102 });
103 }),
104 );
106​
107/**
108 * What a refusal GitHub sent as an HTTP status means, read the way REST reads one. A
109 * failure that never reached GitHub is a request error; one that is not about the transport
110 * (an answer that does not decode) is the client's own.
111 */
112const refused = Effect.fn("gitHubGraphQlClient.refused")(function* (
113 error: GraphQLClientError.GraphQLClientError,
114 context: { readonly host: string; readonly operation: string },
115) {
116 const reason = error.reason;
117 if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {
118 return yield* Effect.fail(error);
119 }
120 const status = reason.status;
121 if (reason._tag === "TransportError" && status === undefined) {
122 return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });
123 }
124 const headers = reason.headers ?? Headers.empty;
125 // A secondary limit is a 403 that only its body names, which the transport read.
126 const body =
127 reason._tag === "TransportError" &&
128 HttpClientError.isHttpClientError(reason.cause) &&
129 reason.cause.response !== undefined
130 ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))
131 : "";
132 const tag = GitHubRequestPolicy.isRateLimited({
133 status: status ?? 200,
134 headers,
135 body,
136 ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),
137 })
138 ? "RateLimited"
139 : status === 401
140 ? "Unauthorized"
141 : status === 404
142 ? "NotFound"
143 : "Failed";
144 return { _tag: tag, status: status ?? 200, headers } as const;
145});
146​
147/**
148 * Reads each answer whole, up to the call's byte cap, before the protocol parses it. A body cut
149 * at the cap hides any `errors` past the cut and cannot be decoded, so it fails, which the
150 * middleware reports as a `GitHubApiResponseError` with the answer's status.
151 */
152const capResponse = Effect.fn("gitHubGraphQlClient.capResponse")(function* (
153 effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
154) {
155 const response = yield* effect;
156 const target = yield* Effect.serviceOption(GitHubGraphQlTarget);
157 const maxBytes = Option.match(target, {
158 onNone: () => DEFAULT_MAX_RESPONSE_BYTES,
159 onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
160 });
161 const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(
162 Effect.catchIf(
163 (error) => error.reason._tag === "EmptyBodyError",
164 () => Effect.succeed({ text: "", truncated: false }),
165 ),
166 );
167 if (collected.truncated) {
168 return yield* new HttpClientError.HttpClientError({
169 reason: new HttpClientError.DecodeError({
170 request: response.request,
171 response,
172 description: `The answer is longer than ${maxBytes} bytes.`,
173 }),
174 });
175 }
176 return HttpClientResponse.fromWeb(
177 response.request,
178 new Response(collected.text === "" ? null : collected.text, {
179 status: response.status,
180 headers: response.headers,
181 }),
182 );
183});
184​
185/**
186 * The HTTP transport, sending each request to its target host's endpoint. Resolvers batch by this
187 * URL, so lookups for different hosts never share a request. `GitHubGraphQlAuth` requires the
188 * target, so every call has one. The middleware's span is the request's: the client's own would add
189 * `url.full`, which can carry SHAs and branch names, so it is off, as for REST.
190 */
191const layerProtocol = GraphQLProtocol.layerHttp({
192 url: ({ context }) =>
193 GitHubRequestPolicy.gitHubApiUrls(Context.getUnsafe(context, GitHubGraphQlTarget).host).graphql,
194}).pipe(
195 Layer.provide(
196 Layer.effect(
197 HttpClient.HttpClient,
198 Effect.gen(function* () {
199 const client = yield* HttpClient.HttpClient;
200 return HttpClient.transformResponse(client, (effect) =>
201 capResponse(effect).pipe(
202 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
203 ),
204 );
205 }),
206 ),
207 ),
208);
209​
210/**
211 * What a client built over `.middleware(GitHubGraphQlAuth)` needs beyond `GitHubRequestPolicy`
212 * and the HTTP client.
213 */
214export const layer = Layer.merge(GitHubGraphQlAuth.layer, layerProtocol);
215​
216/**
217 * What decides which lookups to one host may share a batched request: the credential and
218 * rate-limit scope it will be sent under. Read from the context the lookup was made in. Resolvers
219 * already keep hosts apart, since they batch by the transport's URL too.
220 */
221export const batchKey = (context: Context.Context<GitHubGraphQlTarget>) =>
222 JSON.stringify([
223 Context.getOrElse(context, GitHubRequestPolicy.PinnedGitHubCredential, () => null)
224 ?.credentialFingerprint ?? null,
225 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
226 ]);
227​
228/**
229 * GitHub's `errors` on an answer, as the policy's errors: not found when every error says so,
230 * otherwise a response error carrying GitHub's messages. Any other client error (an answer that
231 * does not decode) is returned as it is.
232 */
233const fromClientError = (
234 target: { readonly host: string; readonly operation: string },
235 error: GraphQLClientError.GraphQLClientError,
236):
237 | GitHubRequestPolicy.GitHubApiNotFoundError
238 | GitHubRequestPolicy.GitHubApiResponseError
239 | GraphQLClientError.GraphQLClientError => {
240 const reason = error.reason;
241 if (reason._tag !== "ResponseError") return error;
242 const context = {
243 host: GitHubRequestPolicy.normalizeHost(target.host),
244 operation: target.operation,
245 };
246 return isNotFoundOnly(error)
247 ? new GitHubRequestPolicy.GitHubApiNotFoundError(context)
248 : new GitHubRequestPolicy.GitHubApiResponseError({
249 ...context,
250 status: reason.status ?? 200,
251 githubErrors: reason.errors.map((graphQlError) => graphQlError.message),
252 });
253};
254​
255/**
256 * Runs one generated GraphQL call (or several) against `target`, failing GitHub's `errors` as
257 * `GitHubApiNotFoundError` or `GitHubApiResponseError`. What remains a `GraphQLClientError` is an
258 * answer that did not decode, which the caller reports as its own read error. The middleware's
259 * errors pass through.
260 */
261export const call: {
262 (
263 target: GitHubGraphQlTarget["Service"],
264 ): <A, E, R>(
265 effect: Effect.Effect<A, E, R>,
266 ) => Effect.Effect<
267 A,
268 E | GitHubRequestPolicy.GitHubApiNotFoundError | GitHubRequestPolicy.GitHubApiResponseError,
269 Exclude<R, GitHubGraphQlTarget>
270 >;
271 <A, E, R>(
272 effect: Effect.Effect<A, E, R>,
273 target: GitHubGraphQlTarget["Service"],
274 ): Effect.Effect<
275 A,
276 E | GitHubRequestPolicy.GitHubApiNotFoundError | GitHubRequestPolicy.GitHubApiResponseError,
277 Exclude<R, GitHubGraphQlTarget>
278 >;
279} = dual(2, <A, E, R>(effect: Effect.Effect<A, E, R>, target: GitHubGraphQlTarget["Service"]) =>
280 effect.pipe(
281 // A `GraphQLClientError` left unmapped is one `E` already holds.
282 Effect.mapError((error) =>
283 GraphQLClientError.isGraphQLClientError(error)
284 ? (fromClientError(target, error) as
285 | E
286 | GitHubRequestPolicy.GitHubApiNotFoundError
287 | GitHubRequestPolicy.GitHubApiResponseError)
288 : error,
289 ),
290 Effect.provideService(GitHubGraphQlTarget, target),
291 ),
292);