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

HttpStaticServerConditional.test.ts

296 lines9.3 KB

1import { assert, describe, it } from "@effect/vitest"
2import * as Effect from "effect/Effect"
3import * as FileSystem from "effect/FileSystem"
4import * as Layer from "effect/Layer"
5import * as Option from "effect/Option"
6import * as Path from "effect/Path"
7import * as PlatformError from "effect/PlatformError"
8import {
9 HttpEffect,
10 HttpPlatform,
11 HttpRouter,
12 HttpServerError,
13 HttpServerRequest,
14 HttpServerResponse,
15 HttpStaticServer
16} from "effect/unstable/http"
17​
18const root = "/root"
19const filePath = `${root}/file.txt`
20const fileBody = "hello static"
21const lastModified = "Wed, 01 Jan 2025 00:00:00 GMT"
22​
23const notFoundError = (path: string) =>
24 PlatformError.systemError({
25 _tag: "NotFound",
26 module: "FileSystem",
27 method: "stat",
28 description: "No such file or directory",
29 pathOrDescriptor: path
30 })
31​
32const permissionDeniedError = (path: string) =>
33 PlatformError.systemError({
34 _tag: "PermissionDenied",
35 module: "FileSystem",
36 method: "stat",
37 description: "Operation not permitted",
38 pathOrDescriptor: path
39 })
40​
41const fileInfo: FileSystem.File.Info = {
42 type: "File",
43 mtime: Option.some(new Date(lastModified)),
44 atime: Option.none(),
45 birthtime: Option.none(),
46 dev: 0,
47 ino: Option.none(),
48 mode: 0,
49 nlink: Option.none(),
50 uid: Option.none(),
51 gid: Option.none(),
52 rdev: Option.none(),
53 size: FileSystem.Size(fileBody.length),
54 blksize: Option.none(),
55 blocks: Option.none()
57​
58const makeHandler = async () => {
59 const fileSystem = FileSystem.makeNoop({
60 stat: (path) => path === filePath ? Effect.succeed(fileInfo) : Effect.fail(notFoundError(path))
61 })
62​
63 const httpPlatform = HttpPlatform.HttpPlatform.of({
64 fileResponse: (_path, options) =>
65 Effect.succeed(HttpServerResponse.text(fileBody, {
66 status: options?.status,
67 headers: {
68 ETag: "\"etag-value\"",
69 "Last-Modified": lastModified
70 }
71 })),
72 fileWebResponse: () => Effect.die("not implemented")
73 })
74​
75 const app = await Effect.runPromise(
76 HttpStaticServer.make({
77 root,
78 cacheControl: "public, max-age=60"
79 }).pipe(
80 Effect.provide(Path.layer),
81 Effect.provideService(FileSystem.FileSystem, fileSystem),
82 Effect.provideService(HttpPlatform.HttpPlatform, httpPlatform)
83 )
84 )
85​
86 return HttpEffect.toWebHandler(app)
88​
89const makeFailingApp = async (options: {
90 readonly statError?: PlatformError.PlatformError
91 readonly fileResponseError?: PlatformError.PlatformError
92}) => {
93 const fileSystem = FileSystem.makeNoop({
94 stat: (path) => {
95 if (options.statError !== undefined) {
96 return Effect.fail(options.statError)
97 }
98 return path === filePath ? Effect.succeed(fileInfo) : Effect.fail(notFoundError(path))
99 }
100 })
101​
102 const httpPlatform = HttpPlatform.HttpPlatform.of({
103 fileResponse: (_path, fileOptions) => {
104 if (options.fileResponseError !== undefined) {
105 return Effect.fail(options.fileResponseError)
106 }
107 return Effect.succeed(HttpServerResponse.text(fileBody, {
108 status: fileOptions?.status,
109 headers: {
110 ETag: "\"etag-value\"",
111 "Last-Modified": lastModified
112 }
113 }))
114 },
115 fileWebResponse: () => Effect.die("not implemented")
116 })
117​
118 return Effect.runPromise(
119 HttpStaticServer.make({ root }).pipe(
120 Effect.provide(Path.layer),
121 Effect.provideService(FileSystem.FileSystem, fileSystem),
122 Effect.provideService(HttpPlatform.HttpPlatform, httpPlatform)
123 )
124 )
126​
127const makeLayerHandler = (options: {
128 readonly statError?: PlatformError.PlatformError
129 readonly fileResponseError?: PlatformError.PlatformError
130}) => {
131 const fileSystem = FileSystem.makeNoop({
132 stat: (path) => {
133 if (options.statError !== undefined) {
134 return Effect.fail(options.statError)
135 }
136 return path === filePath ? Effect.succeed(fileInfo) : Effect.fail(notFoundError(path))
137 }
138 })
139 const httpPlatform = HttpPlatform.HttpPlatform.of({
140 fileResponse: () =>
141 options.fileResponseError !== undefined
142 ? Effect.fail(options.fileResponseError)
143 : Effect.succeed(HttpServerResponse.text(fileBody)),
144 fileWebResponse: () => Effect.die("not implemented")
145 })
146​
147 const dependencies = Layer.mergeAll(
148 Path.layer,
149 Layer.succeed(FileSystem.FileSystem, fileSystem),
150 Layer.succeed(HttpPlatform.HttpPlatform, httpPlatform)
151 )
152​
153 return HttpRouter.toWebHandler(
154 HttpStaticServer.layer({ root }).pipe(Layer.provideMerge(dependencies)),
155 { disableLogger: true }
156 )
158​
159describe("HttpStaticServer", () => {
160 it("304 with If-None-Match exact, weak, and wildcard", async () => {
161 const handler = await makeHandler()
162 const warmupResponse = await handler(new Request("http://localhost/file.txt"))
163 const etag = warmupResponse.headers.get("etag")
164 assert.strictEqual(etag, "\"etag-value\"")
165 if (etag === null) {
166 throw new Error("expected ETag header")
167 }
168​
169 const exact = await handler(new Request("http://localhost/file.txt", { headers: { "If-None-Match": etag } }))
170 const weak = await handler(new Request("http://localhost/file.txt", { headers: { "If-None-Match": `W/${etag}` } }))
171 const list = await handler(
172 new Request("http://localhost/file.txt", { headers: { "If-None-Match": `"other", W/${etag}` } })
173 )
174 const any = await handler(new Request("http://localhost/file.txt", { headers: { "If-None-Match": "*" } }))
175​
176 assert.deepStrictEqual([exact.status, weak.status, list.status, any.status], [304, 304, 304, 304])
177 assert.strictEqual(exact.headers.get("etag"), "\"etag-value\"")
178 assert.strictEqual(exact.headers.get("cache-control"), "public, max-age=60")
179 assert.strictEqual(exact.headers.get("last-modified"), lastModified)
180 assert.strictEqual(exact.headers.get("content-type"), null)
181 assert.strictEqual(exact.headers.get("content-length"), null)
182 })
183​
184 it("304 with If-Modified-Since and no If-None-Match", async () => {
185 const handler = await makeHandler()
186​
187 const notModified = await handler(
188 new Request("http://localhost/file.txt", {
189 headers: {
190 "If-Modified-Since": lastModified
191 }
192 })
193 )
194 const modified = await handler(
195 new Request("http://localhost/file.txt", {
196 headers: {
197 "If-Modified-Since": "Tue, 31 Dec 2024 23:59:59 GMT"
198 }
199 })
200 )
201 const invalidDate = await handler(
202 new Request("http://localhost/file.txt", {
203 headers: {
204 "If-Modified-Since": "not-a-date"
205 }
206 })
207 )
208​
209 assert.strictEqual(notModified.status, 304)
210 assert.strictEqual(modified.status, 200)
211 assert.strictEqual(invalidDate.status, 200)
212 })
213​
214 it("If-None-Match takes precedence over If-Modified-Since", async () => {
215 const handler = await makeHandler()
216​
217 const response = await handler(
218 new Request("http://localhost/file.txt", {
219 headers: {
220 "If-None-Match": "\"different\"",
221 "If-Modified-Since": "Thu, 02 Jan 2025 00:00:00 GMT"
222 }
223 })
224 )
225​
226 assert.strictEqual(response.status, 200)
227 })
228​
229 it("matched If-None-Match takes precedence over Range", async () => {
230 const handler = await makeHandler()
231​
232 const response = await handler(
233 new Request("http://localhost/file.txt", {
234 headers: {
235 "If-None-Match": "\"etag-value\"",
236 Range: "bytes=1000-1001"
237 }
238 })
239 )
240​
241 assert.strictEqual(response.status, 304)
242 assert.strictEqual(response.headers.get("etag"), "\"etag-value\"")
243 assert.strictEqual(response.headers.get("cache-control"), "public, max-age=60")
244 assert.strictEqual(response.headers.get("last-modified"), lastModified)
245 assert.strictEqual(response.headers.get("content-range"), null)
246 assert.strictEqual(response.headers.get("accept-ranges"), null)
247 assert.strictEqual(response.headers.get("content-type"), null)
248 assert.strictEqual(response.headers.get("content-length"), null)
249 })
250​
251 it("wraps missing routes as HttpServerError RouteNotFound", async () => {
252 const app = await makeFailingApp({})
253 const error = await Effect.runPromise(
254 app.pipe(
255 Effect.provideService(
256 HttpServerRequest.HttpServerRequest,
257 HttpServerRequest.fromWeb(new Request("http://localhost/missing.txt"))
258 ),
259 Effect.flip
260 )
261 )
262​
263 assert.instanceOf(error, HttpServerError.HttpServerError)
264 assert.strictEqual(error.reason._tag, "RouteNotFound")
265 })
266​
267 it("maps non-NotFound platform failures to HttpServerError InternalError", async () => {
268 const statError = permissionDeniedError(filePath)
269 const app = await makeFailingApp({ statError })
270 const error = await Effect.runPromise(
271 app.pipe(
272 Effect.provideService(
273 HttpServerRequest.HttpServerRequest,
274 HttpServerRequest.fromWeb(new Request("http://localhost/file.txt"))
275 ),
276 Effect.flip
277 )
278 )
279​
280 assert.instanceOf(error, HttpServerError.HttpServerError)
281 assert.strictEqual(error.reason._tag, "InternalError")
282 assert.strictEqual(error.reason.cause, statError)
283 })
284​
285 it("layer renders InternalError responses as 500", async () => {
286 const { handler, dispose } = makeLayerHandler({
287 fileResponseError: permissionDeniedError(filePath)
288 })
289 try {
290 const response = await handler(new Request("http://localhost/file.txt"))
291 assert.strictEqual(response.status, 500)
292 } finally {
293 await dispose()
294 }
295 })
296})