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

GitHubRest.ts

243 lines9.3 KB

1import * as Context from "effect/Context";
2import * as Duration from "effect/Duration";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Redacted from "effect/Redacted";
7import * as Schema from "effect/Schema";
8import { HttpClient, HttpClientRequest, type HttpClientResponse } from "effect/http";
9​
10import { collectUint8StreamText } from "@t3tools/provider-core/server/collectStreamText";
11import * as GitHubCredentials from "./GitHubCredentials.ts";
12import * as GitHubQuota from "./GitHubQuota.ts";
13import * as GitHubRequestPolicy from "./GitHubRequestPolicy.ts";
14import * as SourceControlRateLimit from "@t3tools/source-control-core/server/SourceControlRateLimit";
15​
16const DEFAULT_MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
17const { gitHubApiUrls, normalizeHost } = GitHubRequestPolicy;
18type GitHubApiError = GitHubRequestPolicy.GitHubApiError;
19​
20export interface GitHubRestResponse {
21 readonly status: number;
22 readonly headers: Readonly<Record<string, string | undefined>>;
23 readonly body: string;
24 readonly truncated: boolean;
25 /** The body was not valid UTF-8, which a raw file read takes to mean binary. */
26 readonly invalidUtf8: boolean;
28​
29export interface GitHubRestInput {
30 readonly host: string;
31 readonly operation: string;
32 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
33 /** Relative to the API root, e.g. `repos/acme/web/pulls/7`; query string included. */
34 readonly path: string;
35 readonly body?: unknown;
36 /** Defaults to `application/vnd.github+json`. */
37 readonly accept?: string;
38 /** Revalidates a cached answer. A 304 is returned rather than failed, and is free. */
39 readonly ifNoneMatch?: string;
40 readonly maxResponseBytes?: number;
41 /** Defaults to 30 seconds; a whole pull request's patch may need longer. */
42 readonly timeout?: Duration.Input;
43 /** Overrides `SourceControlRateLimit.Interactive` for this one request. */
44 readonly allowReserve?: boolean;
46​
47export class GitHubRest extends Context.Service<
48 GitHubRest,
49 {
50 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
51 /** The credential a request to `host` would carry right now. */
52 readonly credential: (
53 host: string,
54 ) => Effect.Effect<
55 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
56 GitHubApiError
57 >;
58 }
59>()("@t3tools/source-control-github/server/GitHubRest") {}
60​
61/** A REST failure body: `{ message, errors: [{ message } | { resource, field, code }] }`. */
62const decodeRestErrors = Schema.decodeUnknownOption(
63 Schema.fromJsonString(
64 Schema.Struct({
65 message: Schema.optional(Schema.String),
66 errors: Schema.optional(
67 Schema.Array(
68 Schema.Union([
69 Schema.String,
70 Schema.Struct({
71 message: Schema.optional(Schema.String),
72 field: Schema.optional(Schema.String),
73 code: Schema.optional(Schema.String),
74 }),
75 ]),
76 ),
77 ),
78 }),
79 ),
80);
81​
82function restErrorMessages(body: string): ReadonlyArray<string> | undefined {
83 return Option.match(decodeRestErrors(body), {
84 onNone: () => undefined,
85 onSome: (decoded) => {
86 const details = (decoded.errors ?? []).flatMap((error) =>
87 typeof error === "string"
88 ? [error]
89 : error.message !== undefined
90 ? [error.message]
91 : error.field !== undefined && error.code !== undefined
92 ? [`${error.field} ${error.code}`]
93 : [],
94 );
95 const messages = [...(decoded.message === undefined ? [] : [decoded.message]), ...details];
96 return messages.length > 0 ? messages : undefined;
97 },
98 });
100​
101/** What a REST answer means: a 304 is an answer only when the request revalidated a cached one. */
102function classify(input: {
103 readonly answer: GitHubRestResponse;
104 readonly acceptNotModified: boolean;
105}): GitHubRequestPolicy.GitHubAnswer<GitHubRestResponse> {
106 const { status, headers, body } = input.answer;
107 const meta = { status, headers };
108 if (GitHubRequestPolicy.isRateLimited({ status, headers, body })) {
109 return { _tag: "RateLimited", ...meta };
110 }
111 if (status === 401) return { _tag: "Unauthorized", ...meta };
112 if (status === 404) return { _tag: "NotFound", ...meta };
113 if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
114 return { _tag: "Ok", value: input.answer, ...meta };
115 }
116 return { _tag: "Failed", messages: restErrorMessages(body), ...meta };
118​
119/** @public Service construction is part of the canonical Effect module API. */
120export const make = Effect.gen(function* () {
121 const httpClient = yield* HttpClient.HttpClient;
122 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
123​
124 /**
125 * Sends one request through the request policy and fails a refusal with the error that says
126 * why. The answer is returned only once it is known to be one.
127 */
128 const send = Effect.fn("GitHubRest.send")(function* (input: {
129 readonly host: string;
130 readonly operation: string;
131 readonly request: HttpClientRequest.HttpClientRequest;
132 readonly maxResponseBytes: number;
133 readonly timeout?: Duration.Input | undefined;
134 readonly allowReserve: boolean;
135 readonly acceptNotModified: boolean;
136 }) {
137 const host = normalizeHost(input.host);
138 // Only the path: a query string can carry a SHA or a branch, and never needs to be in a trace.
139 yield* Effect.annotateCurrentSpan({
140 "github.kind": "rest",
141 "http.request.method": input.request.method,
142 "url.path": new URL(input.request.url).pathname,
143 });
144 return yield* policy.request(
145 {
146 host,
147 operation: input.operation,
148 // Every REST path this reads today spends `core`; a `search/` read would need its own
149 // resource here.
150 resource: "core",
151 allowReserve: input.allowReserve,
152 timeout: input.timeout,
153 },
154 (headers) =>
155 Effect.gen(function* () {
156 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
157 .execute(input.request.pipe(HttpClientRequest.setHeaders(headers)))
158 .pipe(
159 // `GitHubRest.send` is the request's span. The client's own span would add
160 // `url.full` and `url.query`, which can carry SHAs and branch names, so it is off.
161 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
162 );
163 const collected = yield* collectUint8StreamText({
164 stream: response.stream,
165 maxBytes: input.maxResponseBytes,
166 }).pipe(
167 // 204, 304 and many refusals carry no body at all, which is an empty answer.
168 Effect.catchIf(
169 (error) => error.reason._tag === "EmptyBodyError",
170 () => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
171 ),
172 );
173 const { status, headers: responseHeaders } = response;
174 const answer = {
175 status,
176 headers: responseHeaders,
177 body: collected.text,
178 truncated: collected.truncated,
179 invalidUtf8: collected.invalidUtf8,
180 };
181 return classify({ answer, acceptNotModified: input.acceptNotModified });
182 }).pipe(
183 Effect.mapError(
184 (cause) =>
185 new GitHubRequestPolicy.GitHubApiRequestError({
186 host,
187 operation: input.operation,
188 cause,
189 }),
190 ),
191 ),
192 );
193 });
194​
195 const rest: GitHubRest["Service"]["rest"] = (input) => {
196 const url = `${gitHubApiUrls(input.host).rest}/${input.path.replace(/^\/+/, "")}`;
197 const base = HttpClientRequest.make(input.method ?? "GET")(url).pipe(
198 HttpClientRequest.setHeader("accept", input.accept ?? "application/vnd.github+json"),
199 );
200 const withEtag =
201 input.ifNoneMatch === undefined
202 ? base
203 : base.pipe(HttpClientRequest.setHeader("if-none-match", input.ifNoneMatch));
204 const request =
205 input.body === undefined
206 ? withEtag
207 : withEtag.pipe(HttpClientRequest.bodyJsonUnsafe(input.body));
208 return SourceControlRateLimit.Interactive.pipe(
209 Effect.flatMap((interactive) =>
210 send({
211 host: input.host,
212 operation: input.operation,
213 request,
214 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
215 timeout: input.timeout,
216 allowReserve: input.allowReserve ?? interactive,
217 acceptNotModified: input.ifNoneMatch !== undefined,
218 }),
219 ),
220 );
221 };
222​
223 return GitHubRest.of({ rest, credential: policy.credential });
224});
225​
226/**
227 * The REST transport together with the request policy it sends through. The generated GraphQL
228 * client sends through the same policy, so REST and GraphQL share one set of request slots.
229 */
230export const layer = Layer.effect(GitHubRest, make).pipe(
231 Layer.provideMerge(GitHubRequestPolicy.layer),
232);
233​
234/**
235 * REST and the request policy, with the credential, quota reserve and rate-limit pause the policy
236 * reads through: everything both transports need. An application builds this once so every GitHub
237 * reader shares one view of each quota per host.
238 */
239export const layerWithDependencies = layer.pipe(
240 Layer.provideMerge(GitHubCredentials.layer),
241 Layer.provideMerge(GitHubQuota.layer),
242 Layer.provideMerge(SourceControlRateLimit.layer),
243);