Open History to see the last commit
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 /** Invalid UTF-8 indicates a binary raw file. */
26 readonly invalidUtf8: boolean;
27}
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, including query string. */
34 readonly path: string;
35 readonly body?: unknown;
36 /** Defaults to `application/vnd.github+json`. */
37 readonly accept?: string;
38 /** Revalidate cached answers; 304 returns successfully without spending quota. */
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;
45}
46
47export class GitHubRest extends Context.Service<
48 GitHubRest,
49 {
50 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
51 readonly credential: (
52 host: string,
53 ) => Effect.Effect<
54 { readonly token: Redacted.Redacted<string>; readonly fingerprint: string },
55 GitHubApiError
56 >;
57 }
58>()("@t3tools/source-control-github/server/GitHubRest") {}
59
60const decodeRestErrors = Schema.decodeUnknownOption(
61 Schema.fromJsonString(
62 Schema.Struct({
63 message: Schema.optional(Schema.String),
64 errors: Schema.optional(
65 Schema.Array(
66 Schema.Union([
67 Schema.String,
68 Schema.Struct({
69 message: Schema.optional(Schema.String),
70 field: Schema.optional(Schema.String),
71 code: Schema.optional(Schema.String),
72 }),
73 ]),
74 ),
75 ),
76 }),
77 ),
78);
79
80function restErrorMessages(body: string): ReadonlyArray<string> | undefined {
81 return Option.match(decodeRestErrors(body), {
82 onNone: () => undefined,
83 onSome: (decoded) => {
84 const details = (decoded.errors ?? []).flatMap((error) =>
85 typeof error === "string"
86 ? [error]
87 : error.message !== undefined
88 ? [error.message]
89 : error.field !== undefined && error.code !== undefined
90 ? [`${error.field} ${error.code}`]
91 : [],
92 );
93 const messages = [...(decoded.message === undefined ? [] : [decoded.message]), ...details];
94 return messages.length > 0 ? messages : undefined;
95 },
96 });
97}
98
99/** Accept 304 only for cache revalidation. */
100function classify(input: {
101 readonly answer: GitHubRestResponse;
102 readonly acceptNotModified: boolean;
103}): GitHubRequestPolicy.GitHubAnswer<GitHubRestResponse> {
104 const { status, headers, body } = input.answer;
105 const meta = { status, headers };
106 if (GitHubRequestPolicy.isRateLimited({ status, headers, body })) {
107 return { _tag: "RateLimited", ...meta };
108 }
109 if (status === 401) return { _tag: "Unauthorized", ...meta };
110 if (status === 404) return { _tag: "NotFound", ...meta };
111 if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
112 return { _tag: "Ok", value: input.answer, ...meta };
113 }
114 return { _tag: "Failed", messages: restErrorMessages(body), ...meta };
115}
116
117/** @public */
118export const make = Effect.gen(function* () {
119 const httpClient = yield* HttpClient.HttpClient;
120 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
121
122 const send = Effect.fn("GitHubRest.send")(function* (input: {
123 readonly host: string;
124 readonly operation: string;
125 readonly request: HttpClientRequest.HttpClientRequest;
126 readonly maxResponseBytes: number;
127 readonly timeout?: Duration.Input | undefined;
128 readonly allowReserve: boolean;
129 readonly acceptNotModified: boolean;
130 }) {
131 const host = normalizeHost(input.host);
132 // Query strings can expose SHAs or branches in traces.
133 yield* Effect.annotateCurrentSpan({
134 "github.kind": "rest",
135 "http.request.method": input.request.method,
136 "url.path": new URL(input.request.url).pathname,
137 });
138 return yield* policy.request(
139 {
140 host,
141 operation: input.operation,
142 // All current paths spend `core`; search would need a different resource.
143 resource: "core",
144 allowReserve: input.allowReserve,
145 timeout: input.timeout,
146 },
147 (headers) =>
148 Effect.gen(function* () {
149 const response: HttpClientResponse.HttpClientResponse = yield* httpClient
150 .execute(input.request.pipe(HttpClientRequest.setHeaders(headers)))
151 .pipe(
152 // Client spans expose SHAs and branches through url.full/url.query.
153 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
154 );
155 const collected = yield* collectUint8StreamText({
156 stream: response.stream,
157 maxBytes: input.maxResponseBytes,
158 }).pipe(
159 Effect.catchIf(
160 (error) => error.reason._tag === "EmptyBodyError",
161 () => Effect.succeed({ text: "", truncated: false, invalidUtf8: false }),
162 ),
163 );
164 const { status, headers: responseHeaders } = response;
165 const answer = {
166 status,
167 headers: responseHeaders,
168 body: collected.text,
169 truncated: collected.truncated,
170 invalidUtf8: collected.invalidUtf8,
171 };
172 return classify({ answer, acceptNotModified: input.acceptNotModified });
173 }).pipe(
174 Effect.mapError(
175 (cause) =>
176 new GitHubRequestPolicy.GitHubApiRequestError({
177 host,
178 operation: input.operation,
179 cause,
180 }),
181 ),
182 ),
183 );
184 });
185
186 const rest: GitHubRest["Service"]["rest"] = (input) => {
187 const url = `${gitHubApiUrls(input.host).rest}/${input.path.replace(/^\/+/, "")}`;
188 const base = HttpClientRequest.make(input.method ?? "GET")(url).pipe(
189 HttpClientRequest.setHeader("accept", input.accept ?? "application/vnd.github+json"),
190 );
191 const withEtag =
192 input.ifNoneMatch === undefined
193 ? base
194 : base.pipe(HttpClientRequest.setHeader("if-none-match", input.ifNoneMatch));
195 const request =
196 input.body === undefined
197 ? withEtag
198 : withEtag.pipe(HttpClientRequest.bodyJsonUnsafe(input.body));
199 return SourceControlRateLimit.Interactive.pipe(
200 Effect.flatMap((interactive) =>
201 send({
202 host: input.host,
203 operation: input.operation,
204 request,
205 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
206 timeout: input.timeout,
207 allowReserve: input.allowReserve ?? interactive,
208 acceptNotModified: input.ifNoneMatch !== undefined,
209 }),
210 ),
211 );
212 };
213
214 return GitHubRest.of({ rest, credential: policy.credential });
215});
216
217export const layer = Layer.effect(GitHubRest, make).pipe(
218 Layer.provideMerge(GitHubRequestPolicy.layer),
219);
220
221/**
222 * REST and the request policy, with the credential and quota reserve the policy reads through.
223 * Built once, so every GitHub reader shares one view of each quota per host. The rate-limit pause
224 * comes from the server, which every host's change request reads share.
225 */
226export const layerWithDependencies = layer.pipe(
227 Layer.provideMerge(GitHubCredentials.layer),
228 Layer.provideMerge(GitHubQuota.layer),
229);