Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

compress cache and server bytes

Thiago Araujo da Silva904f18fe9d51
diff --git a/backend/src/server/plugins/swagger.test.ts b/backend/src/server/plugins/swagger.test.ts
new file mode 100644
index 0000000000..b9b40fafe8
--- /dev/null
+++ b/backend/src/server/plugins/swagger.test.ts
@@ -0,0 +1,164 @@
+import { brotliDecompressSync, gunzipSync } from "node:zlib";
+
+import fastifyEtag from "@fastify/etag";
+import Fastify, { FastifyInstance } from "fastify";
+import { beforeAll, describe, expect, test } from "vitest";
+import { z } from "zod";
+
+import { serializerCompiler, validatorCompiler, ZodTypeProvider } from "./fastify-zod";
+import { fastifySwagger } from "./swagger";
+
+const buildServer = async () => {
+ const app = Fastify({ logger: false }).withTypeProvider<ZodTypeProvider>();
+ app.setValidatorCompiler(validatorCompiler);
+ app.setSerializerCompiler(serializerCompiler);
+
+ await app.register(fastifyEtag);
+ await app.register(fastifySwagger);
+
+ for (let i = 0; i < 40; i += 1) {
+ app.route({
+ method: "GET",
+ url: `/api/v1/things-${i}/:id`,
+ schema: {
+ hide: false,
+ operationId: `getThing${i}`,
+ tags: ["Things"],
+ params: z.object({ id: z.string().uuid() }),
+ response: {
+ 200: z.object({
+ id: z.string().uuid(),
+ name: z.string().max(64).describe("The name of the thing")
+ })
+ }
+ },
+ handler: async () => ({ id: "00000000-0000-0000-0000-000000000000", name: "thing" })
+ });
+ }
+
+ await app.ready();
+ app.swagger();
+ return app;
+};
+
+describe("OpenAPI spec routes", () => {
+ let app: FastifyInstance;
+
+ beforeAll(async () => {
+ app = await buildServer();
+ return async () => {
+ await app.close();
+ };
+ });
+
+ const getSpec = (headers: Record<string, string> = {}, url = "/api/docs/json") =>
+ app.inject({ method: "GET", url, headers });
+
+ test("serves the spec uncompressed when the client advertises no encoding", async () => {
+ const res = await getSpec();
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers["content-type"]).toBe("application/json; charset=utf-8");
+ expect(res.headers["content-encoding"]).toBeUndefined();
+ expect((JSON.parse(res.body) as { paths: Record<string, unknown> }).paths).toHaveProperty("/api/v1/things-0/{id}");
+ });
+
+ test("marks the response cacheable and varying on the encoding", async () => {
+ const res = await getSpec();
+
+ expect(res.headers["cache-control"]).toBe("public, max-age=600");
+ expect(res.headers.vary).toBe("accept-encoding");
+ });
+
+ test("compresses with brotli when the client names it", async () => {
+ const identity = await getSpec();
+ const res = await getSpec({ "accept-encoding": "br, gzip" });
+
+ expect(res.headers["content-encoding"]).toBe("br");
+ expect(brotliDecompressSync(res.rawPayload).toString("utf8")).toBe(identity.body);
+ expect(res.rawPayload.byteLength).toBeLessThan(identity.rawPayload.byteLength);
+ });
+
+ test("compresses with gzip when brotli is not offered", async () => {
+ const identity = await getSpec();
+ const res = await getSpec({ "accept-encoding": "gzip, deflate" });
+
+ expect(res.headers["content-encoding"]).toBe("gzip");
+ expect(gunzipSync(res.rawPayload).toString("utf8")).toBe(identity.body);
+ expect(Number(res.headers["content-length"])).toBe(res.rawPayload.byteLength);
+ });
+
+ test("does not infer brotli support from a wildcard", async () => {
+ const res = await getSpec({ "accept-encoding": "*" });
+
+ expect(res.headers["content-encoding"]).toBe("gzip");
+ });
+
+ test("honours an encoding the client rejects with q=0", async () => {
+ const res = await getSpec({ "accept-encoding": "gzip;q=0" });
+
+ expect(res.headers["content-encoding"]).toBeUndefined();
+ });
+
+ test("answers a conditional request for the same encoding with 304", async () => {
+ const gzipped = await getSpec({ "accept-encoding": "gzip" });
+ const res = await getSpec({
+ "accept-encoding": "gzip",
+ "if-none-match": gzipped.headers.etag as string
+ });
+
+ expect(res.statusCode).toBe(304);
+ expect(res.body).toBe("");
+ });
+
+ test("does not answer 304 when the client's etag is for a different encoding", async () => {
+ const identity = await getSpec();
+ const res = await getSpec({
+ "accept-encoding": "gzip",
+ "if-none-match": identity.headers.etag as string
+ });
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers["content-encoding"]).toBe("gzip");
+ });
+
+ test("returns identical bytes and etag on every hit", async () => {
+ const first = await getSpec();
+ const second = await getSpec();
+
+ expect(second.rawPayload.equals(first.rawPayload)).toBe(true);
+ expect(second.headers.etag).toBe(first.headers.etag);
+ });
+
+ test("serves the yaml spec the same way", async () => {
+ const res = await getSpec({ "accept-encoding": "br" }, "/api/docs/yaml");
+
+ expect(res.statusCode).toBe(200);
+ expect(res.headers["content-type"]).toBe("application/x-yaml; charset=utf-8");
+ expect(brotliDecompressSync(res.rawPayload).toString("utf8")).toContain("openapi:");
+ });
+
+ test("leaves the Swagger UI routes untouched", async () => {
+ const ui = await app.inject({ method: "GET", url: "/api/docs/" });
+ const asset = await app.inject({ method: "GET", url: "/api/docs/static/swagger-ui.css" });
+
+ expect(ui.statusCode).toBe(200);
+ expect(ui.headers["content-type"]).toContain("text/html");
+ expect(asset.statusCode).toBe(200);
+ });
+
+ test("builds the payload once when a cold server is hit concurrently", async () => {
+ const cold = await buildServer();
+
+ const responses = await Promise.all(
+ Array.from({ length: 25 }, () =>
+ cold.inject({ method: "GET", url: "/api/docs/json", headers: { "accept-encoding": "br" } })
+ )
+ );
+
+ expect(responses.every((res) => res.statusCode === 200)).toBe(true);
+ expect(responses.every((res) => res.rawPayload.equals(responses[0].rawPayload))).toBe(true);
+
+ await cold.close();
+ });
+});
diff --git a/backend/src/server/plugins/swagger.ts b/backend/src/server/plugins/swagger.ts
index a49922f5e0..79597f98e7 100644
--- a/backend/src/server/plugins/swagger.ts
+++ b/backend/src/server/plugins/swagger.ts
@@ -1,9 +1,91 @@
+import { createHash } from "node:crypto";
+import { promisify } from "node:util";
+import { brotliCompress, constants as zlibConstants, gzip } from "node:zlib";
+
import swagger from "@fastify/swagger";
import swaggerUI from "@fastify/swagger-ui";
+import { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
import fp from "fastify-plugin";
import { jsonSchemaTransform } from "./fastify-zod";
+const DOCS_ROUTE_PREFIX = "/api/docs";
+const SPEC_CACHE_MAX_AGE_SECONDS = 600;
+
+const gzipAsync = promisify(gzip);
+const brotliCompressAsync = promisify(brotliCompress);
+
+type SpecFormat = "json" | "yaml";
+type SpecEncoding = "br" | "gzip";
+
+type SpecPayload = {
+ contentType: string;
+ etagBase: string;
+ identity: Buffer;
+ br: Buffer;
+ gzip: Buffer;
+};
+
+const SPEC_FORMAT_BY_ROUTE: Record<string, SpecFormat> = {
+ [`${DOCS_ROUTE_PREFIX}/json`]: "json",
+ [`${DOCS_ROUTE_PREFIX}/yaml`]: "yaml"
+};
+
+const buildSpecPayload = async (fastify: FastifyInstance, format: SpecFormat): Promise<SpecPayload> => {
+ const isYaml = format === "yaml";
+ const body = isYaml ? fastify.swagger({ yaml: true }) : JSON.stringify(fastify.swagger());
+ const contentType = isYaml ? "application/x-yaml; charset=utf-8" : "application/json; charset=utf-8";
+
+ const identity = Buffer.from(body, "utf8");
+
+ const [brotlied, gzipped] = await Promise.all([
+ brotliCompressAsync(identity, {
+ params: {
+ [zlibConstants.BROTLI_PARAM_QUALITY]: 5,
+ [zlibConstants.BROTLI_PARAM_SIZE_HINT]: identity.byteLength
+ }
+ }),
+ gzipAsync(identity)
+ ]);
+
+ fastify.log.info(
+ {
+ format,
+ identityBytes: identity.byteLength,
+ brotliBytes: brotlied.byteLength,
+ gzipBytes: gzipped.byteLength
+ },
+ "Cached OpenAPI spec payload"
+ );
+
+ return {
+ contentType,
+ etagBase: createHash("sha256").update(identity).digest("base64"),
+ identity,
+ br: brotlied,
+ gzip: gzipped
+ };
+};
+
+const pickSpecEncoding = (header: FastifyRequest["headers"]["accept-encoding"]): SpecEncoding | null => {
+ if (!header) return null;
+
+ const weights = new Map<string, number>();
+ for (const directive of (Array.isArray(header) ? header.join(",") : header).split(",")) {
+ const [token, ...params] = directive.trim().split(";");
+
+ if (token) {
+ const quality = params.map((param) => param.trim()).find((param) => param.startsWith("q="));
+ const parsed = quality ? Number(quality.slice(2)) : 1;
+ weights.set(token.toLowerCase(), Number.isNaN(parsed) ? 1 : parsed);
+ }
+ }
+
+ if ((weights.get("br") ?? 0) > 0) return "br";
+ if ((weights.get("gzip") ?? weights.get("*") ?? 0) > 0) return "gzip";
+ return null;
+};
+
export const fastifySwagger = fp(async (fastify) => {
await fastify.register(swagger, {
transform: jsonSchemaTransform,
@@ -40,7 +122,49 @@ export const fastifySwagger = fp(async (fastify) => {
}
});
+ const specPayloads = new Map<SpecFormat, Promise<SpecPayload>>();
+
+ const getSpecPayload = (format: SpecFormat) => {
+ const cached = specPayloads.get(format);
+ if (cached) return cached;
+
+ const pending = buildSpecPayload(fastify, format).catch((err) => {
+ specPayloads.delete(format);
+ throw err;
+ });
+
+ specPayloads.set(format, pending);
+ return pending;
+ };
+
+ const serveSpec = async (req: FastifyRequest, reply: FastifyReply, format: SpecFormat) => {
+ const payload = await getSpecPayload(format);
+ const encoding = pickSpecEncoding(req.headers["accept-encoding"]);
+
+ void reply
+ .header("content-type", payload.contentType)
+ .header("etag", `"${payload.etagBase}${encoding ? `-${encoding}` : ""}"`)
+ .header("cache-control", `public, max-age=${SPEC_CACHE_MAX_AGE_SECONDS}`)
+ .header("vary", "accept-encoding");
+
+ if (encoding) void reply.header("content-encoding", encoding);
+
+ await reply.send(encoding ? payload[encoding] : payload.identity);
+ };
+
await fastify.register(swaggerUI, {
- routePrefix: "/api/docs"
+ routePrefix: DOCS_ROUTE_PREFIX,
+ uiHooks: {
+ preHandler: (req, reply, done) => {
+ const format = SPEC_FORMAT_BY_ROUTE[req.routeOptions.url ?? ""];
+
+ if (!format) {
+ done();
+ return;
+ }
+
+ void serveSpec(req, reply, format).catch((err) => done(err as Error));
+ }
+ }
});
});