Open History to see the last commit
1import * as Clock from "effect/Clock";
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 Redacted from "effect/Redacted";
8import * as Schema from "effect/Schema";
9import * as FetchHttpClient from "effect/http/FetchHttpClient";
10import * as HttpClient from "effect/http/HttpClient";
11import * as HttpClientRequest from "effect/http/HttpClientRequest";
12
13import * as Credentials from "./TanStackSourceCredentials.ts";
14import * as Hosts from "./tanStackSourceHosts.ts";
15
16const NO_REDIRECT: RequestInit = { redirect: "manual" };
17const MAX_REDIRECTS = 3;
18const TIMEOUT = Duration.seconds(30);
19
20export const TanStackSourceApiFailure = Schema.Literals([
21 "missing-tool",
22 "unauthenticated",
23 "forbidden",
24 "rate-limited",
25 "not-found",
26 "failed",
27]);
28
29export class TanStackSourceApiError extends Schema.TaggedError<TanStackSourceApiError>()(
30 "TanStackSourceApiError",
31 {
32 host: Schema.String,
33 operation: Schema.String,
34 status: Schema.NullOr(Schema.Int),
35 reason: TanStackSourceApiFailure,
36 detail: Schema.String,
37 retryAt: Schema.optional(Schema.Number),
38 cause: Schema.optional(Schema.Defect()),
39 },
40) {
41 override get message(): string {
42 return `TanStack Source ${this.operation} failed on ${this.host}: ${this.detail}`;
43 }
44}
45
46export interface TanStackSourceApiRequest {
47 readonly host: string;
48 readonly operation: string;
49 readonly method?: "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
50 /** Below `/api/v1`, starting with `/`. */
51 readonly path: string;
52 readonly body?: unknown;
53 readonly accept?: string;
54}
55
56export interface TanStackSourceApiResponse {
57 readonly status: number;
58 readonly headers: Readonly<Record<string, string>>;
59 readonly text: string;
60}
61
62export class TanStackSourceApi extends Context.Service<
63 TanStackSourceApi,
64 {
65 readonly request: (
66 input: TanStackSourceApiRequest,
67 ) => Effect.Effect<string, TanStackSourceApiError>;
68 /** `request` with the response headers, for routes that answer in them (job logs). */
69 readonly response: (
70 input: TanStackSourceApiRequest,
71 ) => Effect.Effect<TanStackSourceApiResponse, TanStackSourceApiError>;
72 }
73>()("@t3tools/source-control-tanstack-source/server/TanStackSourceApi") {}
74
75const decodeProblem = Schema.decodeUnknownOption(
76 Schema.fromJsonString(
77 Schema.Struct({
78 error: Schema.optional(Schema.String),
79 message: Schema.optional(Schema.String),
80 }),
81 ),
82);
83
84const reasonForStatus = (status: number): typeof TanStackSourceApiFailure.Type =>
85 status === 401
86 ? "unauthenticated"
87 : status === 403
88 ? "forbidden"
89 : status === 429
90 ? "rate-limited"
91 : status === 404
92 ? "not-found"
93 : "failed";
94
95const MAX_PROBLEM_TEXT = 300;
96const boundedProblemText = (text: string | undefined) => {
97 const line = text?.replace(/\s+/gu, " ").trim();
98 if (!line) return undefined;
99 return line.length > MAX_PROBLEM_TEXT ? `${line.slice(0, MAX_PROBLEM_TEXT)}…` : line;
100};
101
102const credentialFailure = (
103 error: Credentials.TanStackSourceCredentialUnavailableError,
104): typeof TanStackSourceApiFailure.Type =>
105 error._tag === "TanStackSourceCliMissingError"
106 ? "missing-tool"
107 : error._tag === "TanStackSourceCliFailedError" ||
108 error._tag === "TanStackSourceCliTimeoutError"
109 ? "failed"
110 : "unauthenticated";
111
112const REDIRECTS = new Set([301, 302, 303, 307, 308]);
113// 307 and 308 keep the method and body; the others only safely repeat a read.
114const METHOD_PRESERVING = new Set([307, 308]);
115
116/** A transferred issue answers 301 with its new place; follow it only within this host's API. */
117const redirectTarget = (
118 method: string,
119 origin: string,
120 from: string,
121 response: { readonly status: number; readonly location: string | undefined },
122): string | null => {
123 if (!REDIRECTS.has(response.status) || response.location === undefined) return null;
124 if (method !== "GET" && !METHOD_PRESERVING.has(response.status)) return null;
125 const target = URL.parse(response.location, from);
126 return target !== null &&
127 target.origin === origin &&
128 target.username === "" &&
129 target.password === "" &&
130 target.pathname.startsWith("/api/v1/")
131 ? target.href
132 : null;
133};
134
135const retryAtFrom = (headers: Readonly<Record<string, string>>, now: number) => {
136 const seconds = Number(headers["retry-after"]);
137 return Number.isFinite(seconds) && seconds >= 0 ? now + seconds * 1_000 : undefined;
138};
139
140/** @public */
141export const make = Effect.gen(function* () {
142 const httpClient = yield* HttpClient.HttpClient;
143 const credentials = yield* Credentials.TanStackSourceCredentials;
144
145 const response = Effect.fn("TanStackSourceApi.request")(function* (
146 input: TanStackSourceApiRequest,
147 ) {
148 const fail = (
149 fields: Pick<TanStackSourceApiError, "status" | "reason" | "detail"> & {
150 readonly cause?: unknown;
151 readonly retryAt?: number | undefined;
152 },
153 ) =>
154 new TanStackSourceApiError({
155 host: input.host,
156 operation: input.operation,
157 status: fields.status,
158 reason: fields.reason,
159 detail: fields.detail,
160 ...(fields.retryAt === undefined ? {} : { retryAt: fields.retryAt }),
161 ...(fields.cause === undefined ? {} : { cause: fields.cause }),
162 });
163 // A remote or link may name any host; the token only goes to Source's own.
164 const host = Hosts.tanStackSourceHost(input.host);
165 if (host === null)
166 return yield* fail({
167 status: null,
168 reason: "failed",
169 detail: `TanStack Source lives on ${Hosts.TANSTACK_SOURCE_HOSTS.join(" and ")}, not ${input.host}.`,
170 });
171 const method = input.method ?? "GET";
172 yield* Effect.annotateCurrentSpan({
173 "tanstack_source.host": host,
174 "tanstack_source.operation": input.operation,
175 "http.request.method": method,
176 });
177 const credential = yield* credentials
178 .get(host)
179 .pipe(
180 Effect.mapError((cause) =>
181 fail({ status: null, reason: credentialFailure(cause), detail: cause.message, cause }),
182 ),
183 );
184 const origin = `https://${host}`;
185 const send = (url: string) => {
186 const base = HttpClientRequest.make(method)(url).pipe(
187 HttpClientRequest.bearerToken(Redacted.value(credential.token)),
188 HttpClientRequest.setHeaders({
189 accept: input.accept ?? "application/json",
190 "user-agent": "t3code",
191 }),
192 );
193 return Effect.gen(function* () {
194 const reply = yield* httpClient
195 .execute(
196 input.body === undefined
197 ? base
198 : base.pipe(HttpClientRequest.bodyJsonUnsafe(input.body)),
199 )
200 .pipe(
201 // Client spans expose query strings carrying branch names.
202 Effect.provideService(HttpClient.TracerDisabledWhen, () => true),
203 // fetch would carry the bearer token to any redirect target.
204 Effect.provideService(FetchHttpClient.RequestInit, NO_REDIRECT),
205 );
206 return { status: reply.status, headers: reply.headers, text: yield* reply.text };
207 }).pipe(
208 Effect.timeout(TIMEOUT),
209 Effect.mapError((cause) =>
210 fail({
211 status: null,
212 reason: "failed",
213 detail: "Could not reach TanStack Source.",
214 cause,
215 }),
216 ),
217 );
218 };
219 let url = `${origin}/api/v1${input.path}`;
220 let reply = yield* send(url);
221 for (let hop = 0; hop < MAX_REDIRECTS; hop++) {
222 const next = redirectTarget(method, origin, url, {
223 status: reply.status,
224 location: reply.headers.location,
225 });
226 if (next === null) break;
227 url = next;
228 reply = yield* send(url);
229 }
230 yield* Effect.annotateCurrentSpan({ "http.response.status_code": reply.status });
231 if (reply.status >= 200 && reply.status < 300) return reply;
232 // The source may hold a newer token than the one that was refused.
233 if (reply.status === 401) yield* credentials.invalidate(host);
234 const problem = Option.getOrUndefined(decodeProblem(reply.text));
235 return yield* fail({
236 status: reply.status,
237 reason: reasonForStatus(reply.status),
238 detail:
239 boundedProblemText(problem?.error ?? problem?.message) ??
240 `TanStack Source answered HTTP ${reply.status}.`,
241 retryAt:
242 reply.status === 429
243 ? retryAtFrom(reply.headers, yield* Clock.currentTimeMillis)
244 : undefined,
245 });
246 });
247
248 return TanStackSourceApi.of({
249 response,
250 request: Effect.fn("TanStackSourceApi.requestText")(function* (input) {
251 return (yield* response(input)).text;
252 }),
253 });
254});
255
256export const layer = Layer.effect(TanStackSourceApi, make);