TypeScript
fix(server): serve static files when the platform cannot open file handles (#14161)
Pujitha Paladugu1d172c3124a1
diff --git a/apps/server/src/http.test.ts b/apps/server/src/http.test.tsindex 058d423d8e3..ddb4b25d707 100644--- a/apps/server/src/http.test.ts+++ b/apps/server/src/http.test.ts@@ -11,6 +11,7 @@ import * as Fiber from "effect/Fiber";import * as FileSystem from "effect/FileSystem";import * as Layer from "effect/Layer";import * as Path from "effect/Path";+import * as PlatformError from "effect/PlatformError";import * as Queue from "effect/Queue";import * as Tracer from "effect/Tracer";import { HttpClient, HttpClientRequest, HttpRouter, HttpServerResponse } from "effect/http";@@ -257,6 +258,180 @@ it.layer(}),);+ it.effect("serves static files without handles and skips fallback reads for HEAD and 304", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-no-open-" });+ const filePath = path.join(staticDir, "app.txt");+ const body = "packaged asset";+ yield* fs.writeFileString(filePath, body);+ let reads = 0;+ // Electron asar files can be statted and read even when opening a handle fails.+ const fileSystem = FileSystem.FileSystem.of({+ ...fs,+ open: (candidate, options) =>+ candidate === filePath+ ? Effect.fail(+ PlatformError.systemError({+ _tag: "NotFound",+ module: "FileSystem",+ method: "open",+ pathOrDescriptor: candidate,+ }),+ )+ : fs.open(candidate, options),+ readFile: (candidate) =>+ Effect.gen(function* () {+ if (candidate === filePath) reads += 1;+ return yield* fs.readFile(candidate);+ }),+ });+ const request = yield* makeStaticRequest(staticDir).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ );++ const get = yield* request("/app.txt");+ expect(get.status).toBe(200);+ expect(yield* get.text).toBe(body);+ expect(reads).toBeGreaterThan(0);+ const readsAfterGet = reads;+ const head = yield* request("/app.txt", { method: "HEAD" });+ expect(head.status).toBe(200);+ expect(yield* head.text).toBe("");+ expect(reads).toBe(readsAfterGet);+ const unchanged = yield* request("/app.txt", {+ headers: { "if-none-match": get.headers["etag"]! },+ });+ expect(unchanged.status).toBe(304);+ expect(yield* unchanged.text).toBe("");+ expect(reads).toBe(readsAfterGet);+ }),+ );++ it.effect("returns 500 for static file open errors other than NotFound", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-open-error-" });+ const filePath = path.join(staticDir, "index.html");+ yield* fs.writeFileString(filePath, "<html>readable</html>");+ const fileSystem = FileSystem.FileSystem.of({+ ...fs,+ open: (candidate, options) =>+ candidate === filePath+ ? Effect.fail(+ PlatformError.systemError({+ _tag: "PermissionDenied",+ module: "FileSystem",+ method: "open",+ pathOrDescriptor: candidate,+ }),+ )+ : fs.open(candidate, options),+ });+ const request = yield* makeStaticRequest(staticDir).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ );++ const response = yield* request("/");+ expect(response.status).toBe(500);+ expect(yield* response.text).toBe("Internal Server Error");+ }),+ );++ it.effect("returns 500 when a static fallback read fails", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-read-error-" });+ const filePath = path.join(staticDir, "index.html");+ yield* fs.writeFileString(filePath, "<html>unreadable</html>");+ const fileSystem = FileSystem.FileSystem.of({+ ...fs,+ open: (candidate, options) =>+ candidate === filePath+ ? Effect.fail(+ PlatformError.systemError({+ _tag: "NotFound",+ module: "FileSystem",+ method: "open",+ pathOrDescriptor: candidate,+ }),+ )+ : fs.open(candidate, options),+ readFile: (candidate) =>+ candidate === filePath+ ? Effect.fail(+ PlatformError.systemError({+ _tag: "PermissionDenied",+ module: "FileSystem",+ method: "readFile",+ pathOrDescriptor: candidate,+ }),+ )+ : fs.readFile(candidate),+ });+ const request = yield* makeStaticRequest(staticDir).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ );++ const response = yield* request("/");+ expect(response.status).toBe(500);+ expect(yield* response.text).toBe("Internal Server Error");+ }),+ );++ it.effect("serves replacement bytes with matching static fallback length and validators", () =>+ Effect.gen(function* () {+ const fs = yield* FileSystem.FileSystem;+ const path = yield* Path.Path;+ const staticDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-static-replaced-" });+ const filePath = path.join(staticDir, "app.txt");+ const before = DateTime.toDateUtc(DateTime.makeUnsafe("1985-10-26T08:15:00.000Z"));+ const after = DateTime.toDateUtc(DateTime.makeUnsafe("2015-10-21T16:29:00.000Z"));+ const replacement = "the replacement asset";+ const replacementPath = path.join(staticDir, "replacement.txt");+ yield* fs.writeFileString(filePath, "old");+ yield* fs.utimes(filePath, before, before);+ yield* fs.writeFileString(replacementPath, replacement);+ yield* fs.utimes(replacementPath, after, after);+ let replaceOnOpen = false;+ const fileSystem = FileSystem.FileSystem.of({+ ...fs,+ open: (candidate, options) =>+ Effect.gen(function* () {+ if (candidate !== filePath) return yield* fs.open(candidate, options);+ if (replaceOnOpen) {+ yield* fs.rename(replacementPath, filePath);+ replaceOnOpen = false;+ }+ return yield* PlatformError.systemError({+ _tag: "NotFound",+ module: "FileSystem",+ method: "open",+ pathOrDescriptor: candidate,+ });+ }),+ });+ const request = yield* makeStaticRequest(staticDir).pipe(+ Effect.provideService(FileSystem.FileSystem, fileSystem),+ );+ const initial = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } });+ expect(yield* initial.text).toBe("old");++ replaceOnOpen = true;+ const response = yield* request("/app.txt", { headers: { "accept-encoding": "identity" } });+ expect(response.status).toBe(200);+ expect(response.headers).toMatchObject({+ "content-length": String(Buffer.byteLength(replacement)),+ "last-modified": after.toUTCString(),+ });+ expect(response.headers["etag"]).not.toBe(initial.headers["etag"]);+ expect(yield* response.text).toBe(replacement);+ }),+ );+it.effect("serves changed HTML when deployments preserve its size and timestamp", () =>Effect.gen(function* () {const fs = yield* FileSystem.FileSystem;diff --git a/apps/server/src/http.ts b/apps/server/src/http.tsindex 9f3f1e87ab4..f623d3441c7 100644--- a/apps/server/src/http.ts+++ b/apps/server/src/http.ts@@ -7,6 +7,7 @@ import {import { isDevProxiedPath } from "@t3tools/shared/devProxy";import { injectMcpAppCookieBootstrap, injectMcpAppThemeBootstrap } from "@t3tools/shared/mcpApp";import { decodeOtlpTraceRecords } from "@t3tools/shared/observability";+import * as ByteSize from "effect/ByteSize";import * as Data from "effect/Data";import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";@@ -533,8 +534,15 @@ const openStaticFile = Effect.fn("openStaticFile")(function* (filePath: string)const fileSystem = yield* FileSystem.FileSystem;const pathInfo = yield* fileSystem.stat(filePath).pipe(Effect.orElseSucceed(() => null));if (pathInfo?.type !== "File") return null;- const file = yield* fileSystem.open(filePath, { flag: "r" });- const info = yield* file.stat;+ const file = yield* fileSystem.open(filePath, { flag: "r" }).pipe(+ Effect.catchTags({+ PlatformError: (error) =>+ error.reason._tag === "NotFound" ? Effect.succeed(null) : Effect.fail(error),+ }),+ );+ // Electron asar can stat and read files even when opening a handle returns NotFound.+ // Refresh path metadata because the file may have been replaced since the first stat.+ const info = yield* file === null ? fileSystem.stat(filePath) : file.stat;return info.type === "File" ? { file, info } : null;});@@ -629,18 +637,23 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(!isHtml &&/^assets\/.+-[\w-]{8}\.[^/]+$/.test(relativePath) &&immutableBuildAssets.has(relativePath);+ const cacheControl = immutable ? "public, max-age=31536000, immutable" : "no-cache";+ const validators = (info: FileSystem.File.Info) => {+ // Deployments can preserve HTML size and mtime while changing its bundle URLs.+ const modifiedAt = isHtml ? undefined : Option.getOrUndefined(info.mtime);+ return modifiedAt+ ? {+ ETag: `W/"${info.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`,+ "Last-Modified": modifiedAt.toUTCString(),+ }+ : {};+ };const headers: Record<string, string> = {- "Cache-Control": immutable ? "public, max-age=31536000, immutable" : "no-cache",+ "Cache-Control": cacheControl,+ ...validators(fileInfo),};- // Deployments can preserve HTML size and mtime while changing its bundle URLs.- const modifiedAt = isHtml ? undefined : Option.getOrUndefined(fileInfo.mtime);- const etag = modifiedAt- ? `W/"${fileInfo.size.toString(16)}-${modifiedAt.getTime().toString(16)}"`- : undefined;- if (etag !== undefined && modifiedAt !== undefined) {- headers.ETag = etag;- headers["Last-Modified"] = modifiedAt.toUTCString();- }+ const etag = headers.ETag;+ const lastModified = headers["Last-Modified"];// If-None-Match takes precedence over dates and uses weak comparison for// GET/HEAD, including when compression changes the transferred bytes.@@ -656,8 +669,8 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")();}): ifModifiedSince !== undefined &&- modifiedAt !== undefined &&- Date.parse(modifiedAt.toUTCString()) <= Date.parse(ifModifiedSince);+ lastModified !== undefined &&+ Date.parse(lastModified) <= Date.parse(ifModifiedSince);if (!isHtml && unchanged) {return HttpServerResponse.empty({status: 304,@@ -666,11 +679,29 @@ const handleStaticAndDevRequest = Effect.fn("handleStaticAndDevRequest")(}const contentType = isHtml ? "text/html; charset=utf-8" : mimeType;- return HttpServerResponse.stream(streamStaticFile(opened.file, fileInfo.size), {- headers,- contentType,- contentLength: Number(fileInfo.size),- });+ if (opened.file === null && request.method !== "HEAD") {+ const fileSystem = yield* FileSystem.FileSystem;+ // Complete fallback reads before success headers; stream errors arrive too late for a 500.+ const bytes = yield* fileSystem.readFile(filePath);+ const info = yield* fileSystem.stat(filePath);+ return HttpServerResponse.uint8Array(bytes, {+ headers: {+ "Cache-Control": cacheControl,+ ...validators({ ...info, size: ByteSize.bytes(bytes.byteLength) }),+ },+ contentType,+ });+ }+ // The request scope closes the handle for GET, HEAD, 304, errors, and cancellation.+ // HEAD still passes through compression, which selects headers without reading the stream.+ return HttpServerResponse.stream(+ opened.file === null ? Stream.empty : streamStaticFile(opened.file, fileInfo.size),+ {+ headers,+ contentType,+ contentLength: Number(fileInfo.size),+ },+ );},Effect.catchTags({PlatformError: () =>