Skip to content

Commit f37416d

Browse files
juliusmarmingecodex
andcommitted
refactor(server): resolve compression service from context
Co-authored-by: codex <[email protected]>
1 parent 135ed07 commit f37416d

3 files changed

Lines changed: 84 additions & 89 deletions

File tree

‎apps/server/src/http.test.ts‎

Lines changed: 30 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,6 @@ import { describe } from "vite-plus/test";
88
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
99
import { compressHttpResponse, isLoopbackHostname, resolveDevRedirectUrl } from "./http.ts";
1010

11-
const compressionUnavailable = HttpResponseCompression.HttpResponseCompression.of({
12-
gzip: () => {
13-
throw new Error("Unexpected HTTP response compression.");
14-
},
15-
});
16-
1711
describe("http dev routing", () => {
1812
it("treats localhost and loopback addresses as local", () => {
1913
expect(isLoopbackHostname("127.0.0.1")).toBe(true);
@@ -38,15 +32,13 @@ describe("http dev routing", () => {
3832
});
3933
});
4034

41-
describe("http compression", () => {
35+
it.layer(HttpResponseCompression.layerNode)("http compression", (it) => {
4236
it.effect("gzips large JSON responses when the client accepts it", () =>
4337
Effect.gen(function* () {
4438
const body = `{"value":"${"compressible".repeat(1_000)}"}`;
45-
const compression = yield* HttpResponseCompression.HttpResponseCompression;
46-
const response = compressHttpResponse(
39+
const response = yield* compressHttpResponse(
4740
HttpServerResponse.text(body, { contentType: "application/json" }),
4841
"br, gzip, deflate",
49-
compression,
5042
);
5143

5244
expect(response.headers["content-encoding"]).toBe("gzip");
@@ -67,33 +59,37 @@ describe("http compression", () => {
6759
return chunks;
6860
});
6961
expect(NodeZlib.gunzipSync(Buffer.concat(chunks)).toString()).toBe(body);
70-
}).pipe(Effect.provide(HttpResponseCompression.layerNode)),
62+
}),
7163
);
7264

73-
it("keeps the original body when gzip is declined", () => {
74-
const response = compressHttpResponse(
75-
HttpServerResponse.text("x".repeat(2_000), { contentType: "application/json" }),
76-
"gzip;q=0, *;q=1",
77-
compressionUnavailable,
78-
);
65+
it.effect("keeps the original body when gzip is declined", () =>
66+
Effect.gen(function* () {
67+
const response = yield* compressHttpResponse(
68+
HttpServerResponse.text("x".repeat(2_000), { contentType: "application/json" }),
69+
"gzip;q=0, *;q=1",
70+
);
7971

80-
expect(response.headers["content-encoding"]).toBeUndefined();
81-
expect(response.headers["content-length"]).toBe("2000");
82-
expect(response.headers.vary).toBe("Accept-Encoding");
83-
});
72+
expect(response.headers["content-encoding"]).toBeUndefined();
73+
expect(response.headers["content-length"]).toBe("2000");
74+
expect(response.headers.vary).toBe("Accept-Encoding");
75+
}),
76+
);
8477

85-
it("preserves existing Vary semantics", () => {
86-
const makeResponse = (vary: string) =>
87-
compressHttpResponse(
88-
HttpServerResponse.text("x".repeat(2_000), {
89-
contentType: "application/json",
90-
headers: { vary },
91-
}),
92-
undefined,
93-
compressionUnavailable,
94-
);
78+
it.effect("preserves existing Vary semantics", () =>
79+
Effect.gen(function* () {
80+
const makeResponse = (vary: string) =>
81+
compressHttpResponse(
82+
HttpServerResponse.text("x".repeat(2_000), {
83+
contentType: "application/json",
84+
headers: { vary },
85+
}),
86+
undefined,
87+
);
9588

96-
expect(makeResponse("*").headers.vary).toBe("*");
97-
expect(makeResponse("Origin, accept-encoding").headers.vary).toBe("Origin, accept-encoding");
98-
});
89+
expect((yield* makeResponse("*")).headers.vary).toBe("*");
90+
expect((yield* makeResponse("Origin, accept-encoding")).headers.vary).toBe(
91+
"Origin, accept-encoding",
92+
);
93+
}),
94+
);
9995
});

‎apps/server/src/http.ts‎

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ import * as ServerConfig from "./config.ts";
3030
import { ASSET_ROUTE_PREFIX, resolveAsset } from "./assets/AssetAccess.ts";
3131
import * as BrowserTraceCollector from "./observability/BrowserTraceCollector.ts";
3232
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
33-
import * as HttpResponseCompression from "./httpCompression/HttpResponseCompression.ts";
33+
import { HttpResponseCompression } from "./httpCompression/HttpResponseCompression.ts";
3434
import { traceRelayRequest } from "./cloud/traceRelayRequest.ts";
3535
import {
3636
annotateEnvironmentRequest,
@@ -67,11 +67,10 @@ function varyByAcceptEncoding(value: string | undefined): string {
6767
return values.has("*") || values.has("accept-encoding") ? value : `${value}, Accept-Encoding`;
6868
}
6969

70-
export function compressHttpResponse(
70+
export const compressHttpResponse = Effect.fnUntraced(function* (
7171
response: HttpServerResponse.HttpServerResponse,
7272
acceptEncoding: string | undefined,
73-
compression: HttpResponseCompression.HttpResponseCompression["Service"],
74-
): HttpServerResponse.HttpServerResponse {
73+
) {
7574
const body = response.body;
7675
if (
7776
body._tag !== "Uint8Array" ||
@@ -89,6 +88,7 @@ export function compressHttpResponse(
8988
);
9089
if (!acceptsGzip(acceptEncoding)) return variedResponse;
9190

91+
const compression = yield* HttpResponseCompression;
9292
const headers = Headers.set(
9393
Headers.remove(variedResponse.headers, "content-length"),
9494
"content-encoding",
@@ -101,18 +101,13 @@ export function compressHttpResponse(
101101
cookies: response.cookies,
102102
contentType: body.contentType,
103103
});
104-
}
104+
});
105105

106106
export const httpCompressionLayer = HttpRouter.middleware(
107107
(httpEffect) =>
108108
Effect.gen(function* () {
109109
const request = yield* HttpServerRequest.HttpServerRequest;
110-
const compression = yield* HttpResponseCompression.HttpResponseCompression;
111-
return compressHttpResponse(
112-
yield* httpEffect,
113-
request.headers["accept-encoding"],
114-
compression,
115-
);
110+
return yield* compressHttpResponse(yield* httpEffect, request.headers["accept-encoding"]);
116111
}),
117112
{ global: true },
118113
);

‎apps/server/src/httpCompression/HttpResponseCompression.test.ts‎

Lines changed: 48 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -7,48 +7,52 @@ import * as HttpResponseCompression from "./HttpResponseCompression.ts";
77

88
const body = new TextEncoder().encode(`{"value":"${"compressible".repeat(1_000)}"}`);
99

10-
it.effect("creates a raw Node gzip stream", () =>
11-
Effect.gen(function* () {
12-
const compression = yield* HttpResponseCompression.HttpResponseCompression;
13-
const response = compression.gzip(body, {
14-
contentType: "application/json",
15-
});
16-
17-
expect(response.body._tag).toBe("Raw");
18-
if (response.body._tag !== "Raw") throw new Error("Expected a raw response body.");
19-
expect(response.body.body).toBeInstanceOf(NodeStream.Readable);
20-
if (!(response.body.body instanceof NodeStream.Readable)) {
21-
throw new Error("Expected a Node readable.");
22-
}
23-
24-
const rawBody = response.body.body;
25-
const chunks = yield* Effect.promise(async () => {
26-
const chunks: Array<Buffer> = [];
27-
for await (const chunk of rawBody) {
28-
chunks.push(Buffer.from(chunk));
10+
it.layer(HttpResponseCompression.layerNode)("Node HTTP response compression", (it) => {
11+
it.effect("creates a raw gzip stream", () =>
12+
Effect.gen(function* () {
13+
const compression = yield* HttpResponseCompression.HttpResponseCompression;
14+
const response = compression.gzip(body, {
15+
contentType: "application/json",
16+
});
17+
18+
expect(response.body._tag).toBe("Raw");
19+
if (response.body._tag !== "Raw") throw new Error("Expected a raw response body.");
20+
expect(response.body.body).toBeInstanceOf(NodeStream.Readable);
21+
if (!(response.body.body instanceof NodeStream.Readable)) {
22+
throw new Error("Expected a Node readable.");
2923
}
30-
return chunks;
31-
});
32-
expect(NodeZlib.gunzipSync(Buffer.concat(chunks))).toEqual(Buffer.from(body));
33-
}).pipe(Effect.provide(HttpResponseCompression.layerNode)),
34-
);
35-
36-
it.effect("creates a raw Bun gzip stream", () =>
37-
Effect.gen(function* () {
38-
const compression = yield* HttpResponseCompression.HttpResponseCompression;
39-
const response = compression.gzip(body, {
40-
contentType: "application/json",
41-
});
42-
43-
expect(response.body._tag).toBe("Raw");
44-
if (response.body._tag !== "Raw") throw new Error("Expected a raw response body.");
45-
expect(response.body.body).toBeInstanceOf(ReadableStream);
46-
if (!(response.body.body instanceof ReadableStream)) {
47-
throw new Error("Expected a Web readable stream.");
48-
}
49-
50-
const rawBody = response.body.body;
51-
const compressed = yield* Effect.promise(() => new Response(rawBody).arrayBuffer());
52-
expect(NodeZlib.gunzipSync(compressed)).toEqual(Buffer.from(body));
53-
}).pipe(Effect.provide(HttpResponseCompression.layerBun)),
54-
);
24+
25+
const rawBody = response.body.body;
26+
const chunks = yield* Effect.promise(async () => {
27+
const chunks: Array<Buffer> = [];
28+
for await (const chunk of rawBody) {
29+
chunks.push(Buffer.from(chunk));
30+
}
31+
return chunks;
32+
});
33+
expect(NodeZlib.gunzipSync(Buffer.concat(chunks))).toEqual(Buffer.from(body));
34+
}),
35+
);
36+
});
37+
38+
it.layer(HttpResponseCompression.layerBun)("Bun HTTP response compression", (it) => {
39+
it.effect("creates a raw gzip stream", () =>
40+
Effect.gen(function* () {
41+
const compression = yield* HttpResponseCompression.HttpResponseCompression;
42+
const response = compression.gzip(body, {
43+
contentType: "application/json",
44+
});
45+
46+
expect(response.body._tag).toBe("Raw");
47+
if (response.body._tag !== "Raw") throw new Error("Expected a raw response body.");
48+
expect(response.body.body).toBeInstanceOf(ReadableStream);
49+
if (!(response.body.body instanceof ReadableStream)) {
50+
throw new Error("Expected a Web readable stream.");
51+
}
52+
53+
const rawBody = response.body.body;
54+
const compressed = yield* Effect.promise(() => new Response(rawBody).arrayBuffer());
55+
expect(NodeZlib.gunzipSync(compressed)).toEqual(Buffer.from(body));
56+
}),
57+
);
58+
});

0 commit comments

Comments
 (0)