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

gitHubGraphQlClient.ts

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