import { applyPublicReadRule, findPublicReadRule, readThroughPublicCache, resolvePublicCacheOptions, type PublicReadRule, } from 'brainerce'; /** * A short cache for the public, static reads that browsers send through the same-origin BFF proxy * (`app/api/store/[...path]/route.ts`). * * Why it exists. Every visitor's browser calls the Brainerce API through this server, so the API * sees ONE source IP for the whole store, and its per-IP rate limit (HTTP 429) is shared by every * shopper. The header, footer, regions and capabilities are the same for everyone, so asking the * API once a minute instead of once per visitor keeps that budget for the requests that differ. * * What it will and will not do, because a shared cache that stores the wrong thing leaks it: * - which reads: exactly the SDK's own allowlist (`findPublicReadRule`), for THIS store's channel * only. Never products, prices, stock, carts, orders, customers or a write. * - whose: anonymous visitors only. A request that carries the customer token cookie goes straight * to the API, so nothing signed-in ever enters, or is served from, this cache. * - what is stored: the status, the body text and the content type. Never a header, so never a * `Set-Cookie` or `Authorization`. * - how it fails: a refresh that fails (network error, 429, 5xx) serves the last good value for a * while; a 404 is remembered briefly; a 401/403/400 is passed on and never stored. * * Per server process: on serverless hosting each instance keeps its own copy, so the saving there * is partial, never wrong. `BRAINERCE_PUBLIC_CACHE=0` turns it off. */ /** What the proxy answers with: enough to rebuild a response, and nothing that could carry identity. */ export interface BffReply { status: number; body: string; contentType: string; /** The API's `Retry-After` on a 429, passed on so the SDK in the browser can wait and retry. */ retryAfter?: string; } /** A query string longer than this is never keyed, so a caller cannot fill the cache with variants. */ const MAX_QUERY_LENGTH = 512; const options = resolvePublicCacheOptions( process.env.BRAINERCE_PUBLIC_CACHE === '0' ? false : undefined ); /** A non-2xx reply travelling through the cache's error path (a 404 is remembered, 429 and 5xx can be stood in for). */ class ReplyError extends Error { readonly statusCode: number; readonly data: BffReply; constructor(reply: BffReply) { super(`backend ${reply.status}`); this.statusCode = reply.status; this.data = reply; } } /** * The cache rule for a proxied request, or `undefined` when it must go straight to the API. * * `pathSegments` is the proxied path as the route sees it (`api/vc//content/HEADER/main`). * Only this store's channel qualifies; a path naming any other channel is not ours to cache. */ export function bffCacheRule( method: string, pathSegments: string, channelId: string, hasCustomerToken: boolean ): PublicReadRule | undefined { if (!options || method !== 'GET' || hasCustomerToken) return undefined; const prefix = `api/vc/${channelId}/`; if (!channelId || !pathSegments.startsWith(prefix)) return undefined; return findPublicReadRule(`/${pathSegments.slice(prefix.length)}`); } /** The cache key, or `null` when the request should not be cached (an oversized query). */ export function bffCacheKey( pathSegments: string, searchParams: URLSearchParams, forwarded: Record ): string | null { // The query the backend will actually receive, in one unambiguous form: the route forwards each // parameter with `set` (a repeated name keeps its LAST value), and `toString()` percent-encodes // `&` and `=`, so `?a=1%26b%3D2` (one parameter) can never share a key with `?a=1&b=2` (two). const effective = new URLSearchParams(); searchParams.forEach((value, key) => effective.set(key, value)); effective.sort(); const query = effective.toString(); if (query.length > MAX_QUERY_LENGTH) return null; // Everything the backend's answer can depend on: the language, the storefront origin the API // checks, and the features this storefront declared. return [ 'bff', pathSegments, query, forwarded['Accept-Language'] ?? '', forwarded['Origin'] ?? '', forwarded['X-Brainerce-Features'] ?? '', ].join('|'); } /** * Answer from the cache, or run `load` once however many callers ask meanwhile. * * `load` must return the reply exactly as the visitor should see it (including the sanitized body * for a 5xx), and must not throw: a transport failure is a 502/504 reply. */ export async function readThroughBff( key: string, rule: PublicReadRule, load: () => Promise ): Promise { if (!options) return load(); try { return await readThroughPublicCache( key, applyPublicReadRule(options, rule), async () => { // Rebuilt field by field: whatever else a reply object carries is never stored or shared. const loaded = await load(); const reply: BffReply = { status: loaded.status, body: loaded.body, contentType: loaded.contentType, ...(loaded.retryAfter ? { retryAfter: loaded.retryAfter } : {}), }; if (reply.status >= 200 && reply.status < 300) return reply; throw new ReplyError(reply); }, (_message, data) => new ReplyError(data as BffReply) ); } catch (error) { if (error instanceof ReplyError) return error.data; throw error; } } /** How long a browser may keep a cacheable reply: the rule's fresh window, capped at the default. */ export function bffBrowserMaxAgeSeconds(rule: PublicReadRule): number { const ttl = options ? applyPublicReadRule(options, rule).ttlMs : 0; return Math.floor(ttl / 1000); }