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 TIMEOUT = Duration.seconds(30);
17
18export const GitCafeApiFailure = Schema.Literals([
19 "missing-tool",
20 "unauthenticated",
21 "rate-limited",
22 "not-found",
23 "failed",
24]);
25
26export class GitCafeApiError extends Schema.TaggedError<GitCafeApiError>()("GitCafeApiError", {
27 host: Schema.String,
28 operation: Schema.String,
29 status: Schema.NullOr(Schema.Int),
30 reason: GitCafeApiFailure,
31 detail: Schema.String,
32 cause: Schema.optional(Schema.Defect()),
33}) {
34 override get message(): string {
35 return `GitCafe ${this.operation} failed on ${this.host}: ${this.detail}`;
36 }
37}
38
39export interface GitCafeApiRequest {
40 readonly host: string;
41 readonly operation: string;
42 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
43 readonly path: string;
44 readonly body?: unknown;
45}
46
47export class GitCafeApi extends Context.Service<
48 GitCafeApi,
49 {
50 readonly request: (input: GitCafeApiRequest) => Effect.Effect<string, GitCafeApiError>;
51 }
52>()("@t3tools/source-control-gitcafe/server/GitCafeApi") {}
53
54const decodeProblem = Schema.decodeUnknownOption(
55 Schema.fromJsonString(
56 Schema.Struct({
57 title: Schema.optional(Schema.String),
58 detail: Schema.optional(Schema.String),
59 }),
60 ),
61);
62
63const reasonForStatus = (status: number): typeof GitCafeApiFailure.Type =>
64 status === 401
65 ? "unauthenticated"
66 : status === 429
67 ? "rate-limited"
68 : status === 404
69 ? "not-found"
70 : "failed";
71
72const MAX_PROBLEM_TEXT = 300;
73const boundedProblemText = (text: string | undefined) => {
74 const line = text?.replace(/\s+/gu, " ").trim();
75 if (!line) return undefined;
76 return line.length > MAX_PROBLEM_TEXT ? `${line.slice(0, MAX_PROBLEM_TEXT)}…` : line;
77};
78
79const credentialFailure = (
80 error: GitCafeCredentials.GitCafeCredentialUnavailableError,
81): typeof GitCafeApiFailure.Type =>
82 error._tag === "GitCafeCliMissingError"
83 ? "missing-tool"
84 : error._tag === "GitCafeNotSignedInError"
85 ? "unauthenticated"
86 : "failed";
87
88/** @public Service construction is part of the canonical Effect module API. */
89export const make = Effect.gen(function* () {
90 const httpClient = yield* HttpClient.HttpClient;
91 const credentials = yield* GitCafeCredentials.GitCafeCredentials;
92
93 const request = Effect.fn("GitCafeApi.request")(function* (input: GitCafeApiRequest) {
94 const fail = (
95 fields: Pick<GitCafeApiError, "status" | "reason" | "detail"> & { cause?: unknown },
96 ) =>
97 new GitCafeApiError({
98 host: input.host,
99 operation: input.operation,
100 status: fields.status,
101 reason: fields.reason,
102 detail: fields.detail,
103 ...(fields.cause === undefined ? {} : { cause: fields.cause }),
104 });
105 // The host comes from a remote URL, so a token never leaves for one GitCafe does not own.
106 const host = GitCafeHosts.gitCafeHost(input.host);
107 if (host === null)
108 return yield* fail({
109 status: null,
110 reason: "failed",
111 detail: `GitCafe lives on ${GitCafeHosts.GITCAFE_HOSTS.join(" and ")}, not ${input.host}.`,
112 });
113 yield* Effect.annotateCurrentSpan({
114 "gitcafe.host": host,
115 "gitcafe.operation": input.operation,
116 "http.request.method": input.method ?? "GET",
117 });
118 const credential = yield* credentials
119 .get(host)
120 .pipe(
121 Effect.mapError((cause) =>
122 fail({ status: null, reason: credentialFailure(cause), detail: cause.message, cause }),
123 ),
124 );
125 const base = HttpClientRequest.make(input.method ?? "GET")(
126 `https://${host}/api${input.path}`,
127 ).pipe(
128 HttpClientRequest.bearerToken(Redacted.value(credential.token)),
129 HttpClientRequest.setHeaders({ accept: "application/json", "user-agent": "t3code" }),
130 );
131 const { status, text } = yield* Effect.gen(function* () {
132 const response = yield* httpClient
133 .execute(
134 input.body === undefined ? base : base.pipe(HttpClientRequest.bodyJsonUnsafe(input.body)),
135 )
136 .pipe(
137 // The client's own span would record the query string, which can carry branch names.
138 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
139 // fetch would follow a redirect itself and keep the bearer token on a same-origin hop;
140 // GitCafe's API never redirects a request it serves, so a 3xx is answered as a failure.
141 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
142 );
143 return { status: response.status, text: yield* response.text };
144 }).pipe(
145 Effect.timeout(TIMEOUT),
146 Effect.mapError((cause) =>
147 fail({ status: null, reason: "failed", detail: "Could not reach GitCafe.", cause }),
148 ),
149 );
150 yield* Effect.annotateCurrentSpan({ "http.response.status_code": status });
151 if (status >= 200 && status < 300) return text;
152 // The source may hold a newer token than the one that was refused.
153 if (status === 401) yield* credentials.invalidate(host);
154 const problem = Option.getOrUndefined(decodeProblem(text));
155 return yield* fail({
156 status,
157 reason: reasonForStatus(status),
158 detail:
159 boundedProblemText(problem?.detail ?? problem?.title) ?? `GitCafe answered HTTP ${status}.`,
160 });
161 });
162
163 return GitCafeApi.of({ request });
164});
165
166export const layer = Layer.effect(GitCafeApi, make);