Open History to see the last commit
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");
41}
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: ({ request, next }) =>
68 Effect.gen(function* () {
69 const target = yield* GitHubGraphQlTarget;
70 const host = GitHubRequestPolicy.normalizeHost(target.host);
71 yield* Effect.annotateCurrentSpan({
72 "github.kind": "graphql",
73 "github.graphql.query_hash": queryHash(request.query),
74 });
75 return yield* policy.request(
76 {
77 host,
78 operation: target.operation,
79 resource: "graphql",
80 allowReserve: target.allowReserve ?? (yield* SourceControlRateLimit.Interactive),
81 },
82 (headers) =>
83 next({ ...request, headers: Headers.setAll(request.headers, headers) }).pipe(
84 Effect.map((answer) => {
85 const status = answer.status;
86 const responseHeaders = answer.headers ?? Headers.empty;
87 const rateLimited = GitHubRequestPolicy.isRateLimited({
88 status: status ?? 200,
89 headers: responseHeaders,
90 ...(answer.errors === undefined ? {} : { graphqlErrors: answer.errors }),
91 });
92 return rateLimited
93 ? { _tag: "RateLimited" as const, status, headers: responseHeaders }
94 : { _tag: "Ok" as const, value: answer, status, headers: responseHeaders };
95 }),
96 Effect.catchIf(GraphQLClientError.isGraphQLClientError, (error) =>
97 refused(error, { host, operation: target.operation }),
98 ),
99 ),
100 );
101 }).pipe(Effect.withSpan("GitHubGraphQlAuth.execute")),
102 subscribe: () => Stream.die(new Error("GitHub GraphQL has no subscriptions.")),
103 });
104 }),
105 );
106}
107
108/**
109 * What a refusal GitHub sent as an HTTP status means, read the way REST reads one. A
110 * failure that never reached GitHub is a request error; one that is not about the transport
111 * (an answer that does not decode) is the client's own.
112 */
113const refused = (
114 error: GraphQLClientError.GraphQLClientError,
115 context: { readonly host: string; readonly operation: string },
116) =>
117 Effect.gen(function* () {
118 const reason = error.reason;
119 if (reason._tag !== "TransportError" && reason._tag !== "ResponseError") {
120 return yield* Effect.fail(error);
121 }
122 const status = reason.status;
123 if (reason._tag === "TransportError" && status === undefined) {
124 return yield* new GitHubRequestPolicy.GitHubApiRequestError({ ...context, cause: error });
125 }
126 const headers = reason.headers ?? Headers.empty;
127 // A secondary limit is a 403 that only its body names, which the transport read.
128 const body =
129 reason._tag === "TransportError" &&
130 HttpClientError.isHttpClientError(reason.cause) &&
131 reason.cause.response !== undefined
132 ? yield* reason.cause.response.text.pipe(Effect.orElseSucceed(() => ""))
133 : "";
134 const tag = GitHubRequestPolicy.isRateLimited({
135 status: status ?? 200,
136 headers,
137 body,
138 ...(reason._tag === "ResponseError" ? { graphqlErrors: reason.errors } : {}),
139 })
140 ? "RateLimited"
141 : status === 401
142 ? "Unauthorized"
143 : status === 404
144 ? "NotFound"
145 : "Failed";
146 return { _tag: tag, status: status ?? 200, headers } as const;
147 });
148
149/**
150 * Reads each answer whole, up to the call's byte cap, before the protocol parses it. A body cut
151 * at the cap hides any `errors` past the cut and cannot be decoded, so it fails, which the
152 * middleware reports as a `GitHubApiResponseError` with the answer's status.
153 */
154const capResponse = (
155 effect: Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>,
156) =>
157 Effect.gen(function* () {
158 const response = yield* effect;
159 const target = yield* Effect.serviceOption(GitHubGraphQlTarget);
160 const maxBytes = Option.match(target, {
161 onNone: () => DEFAULT_MAX_RESPONSE_BYTES,
162 onSome: (target) => target.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
163 });
164 const collected = yield* collectUint8StreamText({ stream: response.stream, maxBytes }).pipe(
165 Effect.catchIf(
166 (error) => error.reason._tag === "EmptyBodyError",
167 () => Effect.succeed({ text: "", truncated: false }),
168 ),
169 );
170 if (collected.truncated) {
171 return yield* new HttpClientError.HttpClientError({
172 reason: new HttpClientError.DecodeError({
173 request: response.request,
174 response,
175 description: `The answer is longer than ${maxBytes} bytes.`,
176 }),
177 });
178 }
179 return HttpClientResponse.fromWeb(
180 response.request,
181 new Response(collected.text === "" ? null : collected.text, {
182 status: response.status,
183 headers: response.headers,
184 }),
185 );
186 });
187
188/**
189 * The HTTP transport, sending each request to its target host's endpoint. Resolvers batch by this
190 * URL, so lookups for different hosts never share a request. `GitHubGraphQlAuth` requires the
191 * target, so every call has one. The middleware's span is the request's: the client's own would add
192 * `url.full`, which can carry SHAs and branch names, so it is off, as for REST.
193 */
194const layerProtocol = GraphQLProtocol.layerHttp({
195 url: ({ context }) =>
196 GitHubRequestPolicy.gitHubApiUrls(Context.getUnsafe(context, GitHubGraphQlTarget).host).graphql,
197}).pipe(
198 Layer.provide(
199 Layer.effect(
200 HttpClient.HttpClient,
201 Effect.gen(function* () {
202 const client = yield* HttpClient.HttpClient;
203 return HttpClient.transformResponse(client, (effect) =>
204 capResponse(effect).pipe(
205 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
206 ),
207 );
208 }),
209 ),
210 ),
211);
212
213/**
214 * What a client built over `.middleware(GitHubGraphQlAuth)` needs beyond `GitHubRequestPolicy`
215 * and the HTTP client.
216 */
217export const layer = Layer.merge(GitHubGraphQlAuth.layer, layerProtocol);
218
219/**
220 * What decides which lookups to one host may share a batched request: the credential and
221 * rate-limit scope it will be sent under. Read from the context the lookup was made in. Resolvers
222 * already keep hosts apart, since they batch by the transport's URL too.
223 */
224export const batchKey = (context: Context.Context<GitHubGraphQlTarget>) =>
225 JSON.stringify([
226 Context.getOrElse(context, GitHubRequestPolicy.PinnedGitHubCredential, () => null)
227 ?.credentialFingerprint ?? null,
228 Context.getOrElse(context, SourceControlRateLimit.CredentialScope, () => ""),
229 ]);
230
231/**
232 * GitHub's `errors` on an answer, as the policy's errors: not found when every error says so,
233 * otherwise a response error carrying GitHub's messages. Any other client error (an answer that
234 * does not decode) is returned as it is.
235 */
236const fromClientError = (
237 target: { readonly host: string; readonly operation: string },
238 error: GraphQLClientError.GraphQLClientError,
239):
240 | GitHubRequestPolicy.GitHubApiNotFoundError
241 | GitHubRequestPolicy.GitHubApiResponseError
242 | GraphQLClientError.GraphQLClientError => {
243 const reason = error.reason;
244 if (reason._tag !== "ResponseError") return error;
245 const context = {
246 host: GitHubRequestPolicy.normalizeHost(target.host),
247 operation: target.operation,
248 };
249 return isNotFoundOnly(error)
250 ? new GitHubRequestPolicy.GitHubApiNotFoundError(context)
251 : new GitHubRequestPolicy.GitHubApiResponseError({
252 ...context,
253 status: reason.status ?? 200,
254 githubErrors: reason.errors.map((graphQlError) => graphQlError.message),
255 });
256};
257
258/**
259 * Runs one generated GraphQL call (or several) against `target`, failing GitHub's `errors` as
260 * `GitHubApiNotFoundError` or `GitHubApiResponseError`. What remains a `GraphQLClientError` is an
261 * answer that did not decode, which the caller reports as its own read error. The middleware's
262 * errors pass through.
263 */
264export const call: {
265 (
266 target: GitHubGraphQlTarget["Service"],
267 ): <A, E, R>(
268 effect: Effect.Effect<A, E, R>,
269 ) => Effect.Effect<
270 A,
271 E | GitHubRequestPolicy.GitHubApiNotFoundError | GitHubRequestPolicy.GitHubApiResponseError,
272 Exclude<R, GitHubGraphQlTarget>
273 >;
274 <A, E, R>(
275 effect: Effect.Effect<A, E, R>,
276 target: GitHubGraphQlTarget["Service"],
277 ): Effect.Effect<
278 A,
279 E | GitHubRequestPolicy.GitHubApiNotFoundError | GitHubRequestPolicy.GitHubApiResponseError,
280 Exclude<R, GitHubGraphQlTarget>
281 >;
282} = dual(2, <A, E, R>(effect: Effect.Effect<A, E, R>, target: GitHubGraphQlTarget["Service"]) =>
283 effect.pipe(
284 // A `GraphQLClientError` left unmapped is one `E` already holds.
285 Effect.mapError((error) =>
286 GraphQLClientError.isGraphQLClientError(error)
287 ? (fromClientError(target, error) as
288 | E
289 | GitHubRequestPolicy.GitHubApiNotFoundError
290 | GitHubRequestPolicy.GitHubApiResponseError)
291 : error,
292 ),
293 Effect.provideService(GitHubGraphQlTarget, target),
294 ),
295);