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 cwd?: string | undefined;
33 readonly operation: string;
34 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
35 /** Relative to the API root, including query string. */
36 readonly path: string;
37 readonly body?: unknown;
38 /** Defaults to `application/vnd.github+json`. */
39 readonly accept?: string;
40 /** Revalidate cached answers; 304 returns successfully without spending quota. */
41 readonly ifNoneMatch?: string;
42 readonly maxResponseBytes?: number;
43 /** Defaults to 30 seconds; a whole pull request's patch may need longer. */
44 readonly timeout?: Duration.Input;
45 /** Overrides `SourceControlRateLimit.Interactive` for this one request. */
46 readonly allowReserve?: boolean;
47}
48
49export class GitHubRest extends Context.Service<
50 GitHubRest,
51 {
52 readonly rest: (input: GitHubRestInput) => Effect.Effect<GitHubRestResponse, GitHubApiError>;
53 readonly credential: GitHubRequestPolicy.GitHubRequestPolicy["Service"]["credential"];
54 readonly appCredential: GitHubRequestPolicy.GitHubRequestPolicy["Service"]["appCredential"];
55 }
56>()("@t3tools/source-control-github/server/GitHubRest") {}
57
58const decodeRestErrors = Schema.decodeUnknownOption(
59 Schema.fromJsonString(
60 Schema.Struct({
61 message: Schema.optional(Schema.String),
62 errors: Schema.optional(
63 Schema.Array(
64 Schema.Union([
65 Schema.String,
66 Schema.Struct({
67 message: Schema.optional(Schema.String),
68 field: Schema.optional(Schema.String),
69 code: Schema.optional(Schema.String),
70 }),
71 ]),
72 ),
73 ),
74 }),
75 ),
76);
77
78function restErrorMessages(body: string): ReadonlyArray<string> | undefined {
79 return Option.match(decodeRestErrors(body), {
80 onNone: () => undefined,
81 onSome: (decoded) => {
82 const details = (decoded.errors ?? []).flatMap((error) =>
83 typeof error === "string"
84 ? [error]
85 : error.message !== undefined
86 ? [error.message]
87 : error.field !== undefined && error.code !== undefined
88 ? [`${error.field} ${error.code}`]
89 : [],
90 );
91 const messages = [...(decoded.message === undefined ? [] : [decoded.message]), ...details];
92 return messages.length > 0 ? messages : undefined;
93 },
94 });
95}
96
97/** Accept 304 only for cache revalidation. */
98function classify(input: {
99 readonly answer: GitHubRestResponse;
100 readonly acceptNotModified: boolean;
101}): GitHubRequestPolicy.GitHubAnswer<GitHubRestResponse> {
102 const { status, headers, body } = input.answer;
103 const meta = { status, headers };
104 if (GitHubRequestPolicy.isRateLimited({ status, headers, body })) {
105 return { _tag: "RateLimited", ...meta };
106 }
107 if (status === 401) return { _tag: "Unauthorized", ...meta };
108 if (status === 404) return { _tag: "NotFound", ...meta };
109 if ((status >= 200 && status < 300) || (status === 304 && input.acceptNotModified)) {
110 return { _tag: "Ok", value: input.answer, ...meta };
111 }
112 return { _tag: "Failed", messages: restErrorMessages(body), ...meta };
113}
114
115/** @public */
116export const make = Effect.gen(function* () {
117 const httpClient = yield* HttpClient.HttpClient;
118 const policy = yield* GitHubRequestPolicy.GitHubRequestPolicy;
119
120 const send = Effect.fn("GitHubRest.send")(function* (input: {
121 readonly host: string;
122 readonly cwd: string | undefined;
123 readonly operation: string;
124 readonly request: HttpClientRequest.HttpClientRequest;
125 readonly maxResponseBytes: number;
126 readonly timeout?: Duration.Input | undefined;
127 readonly allowReserve: boolean;
128 readonly acceptNotModified: boolean;
129 }) {
130 const host = normalizeHost(input.host);
131 // Query strings can expose SHAs or branches in traces.
132 yield* Effect.annotateCurrentSpan({
133 "github.kind": "rest",
134 "http.request.method": input.request.method,
135 "url.path": new URL(input.request.url).pathname,
136 });
137 return yield* policy.request(
138 {
139 host,
140 cwd: input.cwd,
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 cwd: input.cwd,
204 operation: input.operation,
205 request,
206 maxResponseBytes: input.maxResponseBytes ?? DEFAULT_MAX_RESPONSE_BYTES,
207 timeout: input.timeout,
208 allowReserve: input.allowReserve ?? interactive,
209 acceptNotModified: input.ifNoneMatch !== undefined,
210 }),
211 ),
212 );
213 };
214
215 return GitHubRest.of({
216 rest,
217 credential: policy.credential,
218 appCredential: policy.appCredential,
219 });
220});
221
222export const layer = Layer.effect(GitHubRest, make).pipe(
223 Layer.provideMerge(GitHubRequestPolicy.layer),
224);
225
226/**
227 * REST and the request policy, with the credential and quota reserve the policy reads through.
228 * Built once, so every GitHub reader shares one view of each quota per host. The rate-limit pause
229 * comes from the server, which every host's change request reads share.
230 */
231export const layerWithDependencies = layer.pipe(
232 Layer.provideMerge(GitHubCredentials.layer),
233 Layer.provideMerge(GitHubAppSignIn.layer),
234 Layer.provideMerge(GitHubQuota.layer),
235);