Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

http.ts

270 lines9.2 KB

1import Mime from "@effect/platform-node/Mime";
2import { Data, Effect, FileSystem, Layer, Option, Path } from "effect";
3import { cast } from "effect/Function";
4import {
5 HttpBody,
6 HttpClient,
7 HttpClientResponse,
8 HttpRouter,
9 HttpServerResponse,
10 HttpServerRequest,
11} from "effect/unstable/http";
12import { OtlpTracer } from "effect/unstable/observability";
13​
14import {
15 ATTACHMENTS_ROUTE_PREFIX,
16 normalizeAttachmentRelativePath,
17 resolveAttachmentRelativePath,
18} from "./attachmentPaths";
19import { resolveAttachmentPathById } from "./attachmentStore";
20import { ServerConfig } from "./config";
21import { decodeOtlpTraceRecords } from "./observability/TraceRecord.ts";
22import { BrowserTraceCollector } from "./observability/Services/BrowserTraceCollector.ts";
23import { ProjectFaviconResolver } from "./project/Services/ProjectFaviconResolver";
24​
25const PROJECT_FAVICON_CACHE_CONTROL = "public, max-age=3600";
26const FALLBACK_PROJECT_FAVICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="#6b728080" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" data-fallback="project-favicon"><path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-8l-2-2H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2Z"/></svg>`;
27const OTLP_TRACES_PROXY_PATH = "/api/observability/v1/traces";
28​
29class DecodeOtlpTraceRecordsError extends Data.TaggedError("DecodeOtlpTraceRecordsError")<{
30 readonly cause: unknown;
31 readonly bodyJson: OtlpTracer.TraceData;
32}> {}
33​
34export const otlpTracesProxyRouteLayer = HttpRouter.add(
35 "POST",
36 OTLP_TRACES_PROXY_PATH,
37 Effect.gen(function* () {
38 const request = yield* HttpServerRequest.HttpServerRequest;
39 const config = yield* ServerConfig;
40 const otlpTracesUrl = config.otlpTracesUrl;
41 const browserTraceCollector = yield* BrowserTraceCollector;
42 const httpClient = yield* HttpClient.HttpClient;
43 const bodyJson = cast<unknown, OtlpTracer.TraceData>(yield* request.json);
44​
45 yield* Effect.try({
46 try: () => decodeOtlpTraceRecords(bodyJson),
47 catch: (cause) => new DecodeOtlpTraceRecordsError({ cause, bodyJson }),
48 }).pipe(
49 Effect.flatMap((records) => browserTraceCollector.record(records)),
50 Effect.catch((cause) =>
51 Effect.logWarning("Failed to decode browser OTLP traces", {
52 cause,
53 bodyJson,
54 }),
55 ),
56 );
57​
58 if (otlpTracesUrl === undefined) {
59 return HttpServerResponse.empty({ status: 204 });
60 }
61​
62 return yield* httpClient
63 .post(otlpTracesUrl, {
64 body: HttpBody.jsonUnsafe(bodyJson),
65 })
66 .pipe(
67 Effect.flatMap(HttpClientResponse.filterStatusOk),
68 Effect.as(HttpServerResponse.empty({ status: 204 })),
69 Effect.tapError((cause) =>
70 Effect.logWarning("Failed to export browser OTLP traces", {
71 cause,
72 otlpTracesUrl,
73 }),
74 ),
75 Effect.catch(() =>
76 Effect.succeed(HttpServerResponse.text("Trace export failed.", { status: 502 })),
77 ),
78 );
79 }),
80).pipe(
81 Layer.provide(
82 HttpRouter.cors({
83 allowedMethods: ["POST", "OPTIONS"],
84 allowedHeaders: ["content-type"],
85 maxAge: 600,
86 }),
87 ),
88);
89​
90export const attachmentsRouteLayer = HttpRouter.add(
91 "GET",
92 `${ATTACHMENTS_ROUTE_PREFIX}/*`,
93 Effect.gen(function* () {
94 const request = yield* HttpServerRequest.HttpServerRequest;
95 const url = HttpServerRequest.toURL(request);
96 if (Option.isNone(url)) {
97 return HttpServerResponse.text("Bad Request", { status: 400 });
98 }
99​
100 const config = yield* ServerConfig;
101 const rawRelativePath = url.value.pathname.slice(ATTACHMENTS_ROUTE_PREFIX.length);
102 const normalizedRelativePath = normalizeAttachmentRelativePath(rawRelativePath);
103 if (!normalizedRelativePath) {
104 return HttpServerResponse.text("Invalid attachment path", { status: 400 });
105 }
106​
107 const isIdLookup =
108 !normalizedRelativePath.includes("/") && !normalizedRelativePath.includes(".");
109 const filePath = isIdLookup
110 ? resolveAttachmentPathById({
111 attachmentsDir: config.attachmentsDir,
112 attachmentId: normalizedRelativePath,
113 })
114 : resolveAttachmentRelativePath({
115 attachmentsDir: config.attachmentsDir,
116 relativePath: normalizedRelativePath,
117 });
118 if (!filePath) {
119 return HttpServerResponse.text(isIdLookup ? "Not Found" : "Invalid attachment path", {
120 status: isIdLookup ? 404 : 400,
121 });
122 }
123​
124 const fileSystem = yield* FileSystem.FileSystem;
125 const fileInfo = yield* fileSystem
126 .stat(filePath)
127 .pipe(Effect.catch(() => Effect.succeed(null)));
128 if (!fileInfo || fileInfo.type !== "File") {
129 return HttpServerResponse.text("Not Found", { status: 404 });
130 }
131​
132 return yield* HttpServerResponse.file(filePath, {
133 status: 200,
134 headers: {
135 "Cache-Control": "public, max-age=31536000, immutable",
136 },
137 }).pipe(
138 Effect.catch(() =>
139 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
140 ),
141 );
142 }),
143);
144​
145export const projectFaviconRouteLayer = HttpRouter.add(
146 "GET",
147 "/api/project-favicon",
148 Effect.gen(function* () {
149 const request = yield* HttpServerRequest.HttpServerRequest;
150 const url = HttpServerRequest.toURL(request);
151 if (Option.isNone(url)) {
152 return HttpServerResponse.text("Bad Request", { status: 400 });
153 }
154​
155 const projectCwd = url.value.searchParams.get("cwd");
156 if (!projectCwd) {
157 return HttpServerResponse.text("Missing cwd parameter", { status: 400 });
158 }
159​
160 const faviconResolver = yield* ProjectFaviconResolver;
161 const faviconFilePath = yield* faviconResolver.resolvePath(projectCwd);
162 if (!faviconFilePath) {
163 return HttpServerResponse.text(FALLBACK_PROJECT_FAVICON_SVG, {
164 status: 200,
165 contentType: "image/svg+xml",
166 headers: {
167 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
168 },
169 });
170 }
171​
172 return yield* HttpServerResponse.file(faviconFilePath, {
173 status: 200,
174 headers: {
175 "Cache-Control": PROJECT_FAVICON_CACHE_CONTROL,
176 },
177 }).pipe(
178 Effect.catch(() =>
179 Effect.succeed(HttpServerResponse.text("Internal Server Error", { status: 500 })),
180 ),
181 );
182 }),
183);
184​
185export const staticAndDevRouteLayer = HttpRouter.add(
186 "GET",
187 "*",
188 Effect.gen(function* () {
189 const request = yield* HttpServerRequest.HttpServerRequest;
190 const url = HttpServerRequest.toURL(request);
191 if (Option.isNone(url)) {
192 return HttpServerResponse.text("Bad Request", { status: 400 });
193 }
194​
195 const config = yield* ServerConfig;
196 if (config.devUrl) {
197 return HttpServerResponse.redirect(config.devUrl.href, { status: 302 });
198 }
199​
200 if (!config.staticDir) {
201 return HttpServerResponse.text("No static directory configured and no dev URL set.", {
202 status: 503,
203 });
204 }
205​
206 const fileSystem = yield* FileSystem.FileSystem;
207 const path = yield* Path.Path;
208 const staticRoot = path.resolve(config.staticDir);
209 const staticRequestPath = url.value.pathname === "/" ? "/index.html" : url.value.pathname;
210 const rawStaticRelativePath = staticRequestPath.replace(/^[/\\]+/, "");
211 const hasRawLeadingParentSegment = rawStaticRelativePath.startsWith("..");
212 const staticRelativePath = path.normalize(rawStaticRelativePath).replace(/^[/\\]+/, "");
213 const hasPathTraversalSegment = staticRelativePath.startsWith("..");
214 if (
215 staticRelativePath.length === 0 ||
216 hasRawLeadingParentSegment ||
217 hasPathTraversalSegment ||
218 staticRelativePath.includes("\0")
219 ) {
220 return HttpServerResponse.text("Invalid static file path", { status: 400 });
221 }
222​
223 const isWithinStaticRoot = (candidate: string) =>
224 candidate === staticRoot ||
225 candidate.startsWith(staticRoot.endsWith(path.sep) ? staticRoot : `${staticRoot}${path.sep}`);
226​
227 let filePath = path.resolve(staticRoot, staticRelativePath);
228 if (!isWithinStaticRoot(filePath)) {
229 return HttpServerResponse.text("Invalid static file path", { status: 400 });
230 }
231​
232 const ext = path.extname(filePath);
233 if (!ext) {
234 filePath = path.resolve(filePath, "index.html");
235 if (!isWithinStaticRoot(filePath)) {
236 return HttpServerResponse.text("Invalid static file path", { status: 400 });
237 }
238 }
239​
240 const fileInfo = yield* fileSystem
241 .stat(filePath)
242 .pipe(Effect.catch(() => Effect.succeed(null)));
243 if (!fileInfo || fileInfo.type !== "File") {
244 const indexPath = path.resolve(staticRoot, "index.html");
245 const indexData = yield* fileSystem
246 .readFile(indexPath)
247 .pipe(Effect.catch(() => Effect.succeed(null)));
248 if (!indexData) {
249 return HttpServerResponse.text("Not Found", { status: 404 });
250 }
251 return HttpServerResponse.uint8Array(indexData, {
252 status: 200,
253 contentType: "text/html; charset=utf-8",
254 });
255 }
256​
257 const contentType = Mime.getType(filePath) ?? "application/octet-stream";
258 const data = yield* fileSystem
259 .readFile(filePath)
260 .pipe(Effect.catch(() => Effect.succeed(null)));
261 if (!data) {
262 return HttpServerResponse.text("Internal Server Error", { status: 500 });
263 }
264​
265 return HttpServerResponse.uint8Array(data, {
266 status: 200,
267 contentType,
268 });
269 }),
270);