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