diff --git a/worker/src/lib/util/cache/cacheSettings.ts b/worker/src/lib/util/cache/cacheSettings.ts index f55664754e..b76da07049 100644 --- a/worker/src/lib/util/cache/cacheSettings.ts +++ b/worker/src/lib/util/cache/cacheSettings.ts @@ -15,8 +15,8 @@ export interface CacheSettings { } function buildCacheControl(cacheControl: string): string { - const sMaxAge = cacheControl.match(/s-maxage=(\d+)/)?.[1]; - const maxAge = cacheControl.match(/max-age=(\d+)/)?.[1]; + const sMaxAge = cacheControl.match(/(?:^|[,;\s])s-maxage=(\d+)/)?.[1]; + const maxAge = cacheControl.match(/(?:^|[,;\s])max-age=(\d+)/)?.[1]; if (sMaxAge || maxAge) { let sMaxAgeInSeconds = 0; diff --git a/worker/test/cache/cacheSettings.spec.ts b/worker/test/cache/cacheSettings.spec.ts new file mode 100644 index 0000000000..229c6b758b --- /dev/null +++ b/worker/test/cache/cacheSettings.spec.ts @@ -0,0 +1,39 @@ +import { describe, it, expect } from "vitest"; +import { getCacheSettings } from "../../src/lib/util/cache/cacheSettings"; + +const DEFAULT_CACHE_AGE = 60 * 60 * 24 * 7; // 7 days, matches cacheSettings.ts + +function cacheControlFrom(cacheControlHeader: string): string | undefined { + const result = getCacheSettings( + new Headers({ + "Cache-Control": cacheControlHeader, + "Helicone-Cache-Enabled": "true", + }) + ); + expect(result.error).toBeNull(); + return result.data?.cacheControl; +} + +describe("getCacheSettings Cache-Control directive matching", () => { + it("uses the real max-age when a vendor x-s-maxage prefix is also present", () => { + expect(cacheControlFrom("x-s-maxage=3600, max-age=1800")).toBe( + "public, max-age=1800" + ); + }); + + it("does not invent an s-maxage TTL from x-s-maxage alone", () => { + const cacheControl = cacheControlFrom("x-s-maxage=3600"); + expect(cacheControl).not.toBe("public, max-age=3600"); + expect(cacheControl).toBe(`public, max-age=${DEFAULT_CACHE_AGE}`); + }); + + it("still honors a real s-maxage directive over max-age", () => { + expect(cacheControlFrom("s-maxage=3600, max-age=1800")).toBe( + "public, max-age=3600" + ); + }); + + it("still honors a standalone max-age directive", () => { + expect(cacheControlFrom("max-age=1800")).toBe("public, max-age=1800"); + }); +});