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 * as FetchHttpClient from "effect/http/FetchHttpClient";
9import * as HttpClient from "effect/http/HttpClient";
10import * as HttpClientRequest from "effect/http/HttpClientRequest";
11
12import * as GitCafeCredentials from "./GitCafeCredentials.ts";
13import * as GitCafeHosts from "./gitCafeHosts.ts";
14
15const NO_REDIRECT: RequestInit = { redirect: "manual" };
16const MAX_REDIRECTS = 3;
17const TIMEOUT = Duration.seconds(30);
18
19export const GitCafeApiFailure = Schema.Literals([
20 "missing-tool",
21 "unauthenticated",
22 "rate-limited",
23 "not-found",
24 "failed",
25]);
26
27export class GitCafeApiError extends Schema.TaggedError<GitCafeApiError>()("GitCafeApiError", {
28 host: Schema.String,
29 operation: Schema.String,
30 status: Schema.NullOr(Schema.Int),
31 reason: GitCafeApiFailure,
32 detail: Schema.String,
33 userFacingDetail: Schema.optional(Schema.String),
34 cause: Schema.optional(Schema.Defect()),
35}) {
36 override get message(): string {
37 return `GitCafe ${this.operation} failed on ${this.host}: ${this.detail}`;
38 }
39}
40
41export interface GitCafeApiRequest {
42 readonly host: string;
43 readonly operation: string;
44 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
45 readonly path: string;
46 readonly body?: unknown;
47}
48
49export class GitCafeApi extends Context.Service<
50 GitCafeApi,
51 {
52 readonly request: (input: GitCafeApiRequest) => Effect.Effect<string, GitCafeApiError>;
53 }
54>()("@t3tools/source-control-gitcafe/server/GitCafeApi") {}
55
56const decodeProblem = Schema.decodeUnknownOption(
57 Schema.fromJsonString(
58 Schema.Struct({
59 title: Schema.optional(Schema.String),
60 detail: Schema.optional(Schema.String),
61 }),
62 ),
63);
64
65const reasonForStatus = (status: number): typeof GitCafeApiFailure.Type =>
66 status === 401
67 ? "unauthenticated"
68 : status === 429
69 ? "rate-limited"
70 : status === 404
71 ? "not-found"
72 : "failed";
73
74const MAX_PROBLEM_TEXT = 300;
75const boundedProblemText = (text: string | undefined) => {
76 const line = text?.replace(/\s+/gu, " ").trim();
77 if (!line) return undefined;
78 return line.length > MAX_PROBLEM_TEXT ? `${line.slice(0, MAX_PROBLEM_TEXT)}…` : line;
79};
80
81const credentialFailure = (
82 error: GitCafeCredentials.GitCafeCredentialUnavailableError,
83): typeof GitCafeApiFailure.Type =>
84 error._tag === "GitCafeCliMissingError"
85 ? "missing-tool"
86 : error._tag === "GitCafeNotSignedInError" || error._tag === "SettingsSecretUnresolvedError"
87 ? "unauthenticated"
88 : "failed";
89
90const REDIRECTS = new Set([301, 302, 303, 307, 308]);
91// 307 and 308 keep the method and body; the others only safely repeat a read.
92const METHOD_PRESERVING = new Set([307, 308]);
93
94const redirectTarget = (
95 method: string,
96 origin: string,
97 from: string,
98 response: { readonly status: number; readonly location: string | undefined },
99): string | null => {
100 if (!REDIRECTS.has(response.status) || response.location === undefined) return null;
101 if (method !== "GET" && !METHOD_PRESERVING.has(response.status)) return null;
102 const target = URL.parse(response.location, from);
103 return target !== null &&
104 target.origin === origin &&
105 target.username === "" &&
106 target.password === "" &&
107 target.pathname.startsWith("/api/")
108 ? target.href
109 : null;
110};
111
112/** @public */
113export const make = Effect.gen(function* () {
114 const httpClient = yield* HttpClient.HttpClient;
115 const credentials = yield* GitCafeCredentials.GitCafeCredentials;
116
117 const request = Effect.fn("GitCafeApi.request")(function* (input: GitCafeApiRequest) {
118 const fail = (
119 fields: Pick<GitCafeApiError, "status" | "reason" | "detail"> & { cause?: unknown },
120 ) =>
121 new GitCafeApiError({
122 host: input.host,
123 operation: input.operation,
124 status: fields.status,
125 reason: fields.reason,
126 detail: fields.detail,
127 ...(fields.cause === undefined ? {} : { cause: fields.cause }),
128 });
129 // Remote URLs must not send tokens outside GitCafe's hosts.
130 const host = GitCafeHosts.gitCafeHost(input.host);
131 if (host === null)
132 return yield* fail({
133 status: null,
134 reason: "failed",
135 detail: `GitCafe lives on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}, not ${input.host}.`,
136 });
137 yield* Effect.annotateCurrentSpan({
138 "gitcafe.host": host,
139 "gitcafe.operation": input.operation,
140 "http.request.method": input.method ?? "GET",
141 });
142 const credential = yield* credentials
143 .get(host)
144 .pipe(
145 Effect.mapError((cause) =>
146 fail({ status: null, reason: credentialFailure(cause), detail: cause.message, cause }),
147 ),
148 );
149 const origin = `https://${host}`;
150 const method = input.method ?? "GET";
151 const send = (url: string) => {
152 const base = HttpClientRequest.make(method)(url).pipe(
153 HttpClientRequest.bearerToken(Redacted.value(credential.token)),
154 HttpClientRequest.setHeaders({ accept: "application/json", "user-agent": "t3code" }),
155 );
156 return Effect.gen(function* () {
157 const response = yield* httpClient
158 .execute(
159 input.body === undefined
160 ? base
161 : base.pipe(HttpClientRequest.bodyJsonUnsafe(input.body)),
162 )
163 .pipe(
164 // Client spans expose query strings containing branch names.
165 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
166 // fetch would carry the bearer token to any redirect target.
167 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
168 );
169 return {
170 status: response.status,
171 location: response.headers.location,
172 text: yield* response.text,
173 };
174 }).pipe(
175 Effect.timeout(TIMEOUT),
176 Effect.mapError((cause) =>
177 fail({ status: null, reason: "failed", detail: "Could not reach GitCafe.", cause }),
178 ),
179 );
180 };
181 // A renumbered pull request (provisional number replaced by the synced GitHub one)
182 // answers with a redirect; follow it only within this host's API.
183 let url = `${origin}/api${input.path}`;
184 let response = yield* send(url);
185 for (let hop = 0; hop < MAX_REDIRECTS; hop++) {
186 const next = redirectTarget(method, origin, url, response);
187 if (next === null) break;
188 url = next;
189 response = yield* send(url);
190 }
191 const { status, text } = response;
192 yield* Effect.annotateCurrentSpan({ "http.response.status_code": status });
193 if (status >= 200 && status < 300) return text;
194 // The source may hold a newer token than the one that was refused.
195 if (status === 401) yield* credentials.invalidate(host);
196 const problem = Option.getOrUndefined(decodeProblem(text));
197 return yield* fail({
198 status,
199 reason: reasonForStatus(status),
200 detail:
201 boundedProblemText(problem?.detail ?? problem?.title) ?? `GitCafe answered HTTP ${status}.`,
202 });
203 });
204
205 return GitCafeApi.of({ request });
206});
207
208export const layer = Layer.effect(GitCafeApi, make);