{"version":3,"file":"field-defs-cache-DcqMO2vU.mjs","names":[],"sources":["../src/bylines/field-defs-cache.ts"],"sourcesContent":["/**\n * Byline field-definitions cache\n *\n * Discussion #1174 / Phase 3. Two-tier cache for the byline custom-field\n * registry, mirroring the `settings/index.ts` pattern.\n *\n * **Tier 1 — per-isolate (globalThis).** Field definitions change rarely\n * but are read on every byline hydration (admin pages, content rendering,\n * API responses). Caching at the isolate level drops the SELECT-from-\n * `_emdash_byline_fields` from once-per-hydration to once-per-isolate-\n * after-bump. The cache holds the resolved *value* behind a reclaimable\n * single-flight lock (see `utils/single-flight-cache.ts`), never an\n * in-flight promise: concurrent cold-isolate readers coalesce onto one\n * query by polling the published value, so a reader whose request is\n * cancelled mid-query can never strand later byline hydrations on the\n * isolate (the workerd never-settling-promise hazard that produced 524s).\n *\n * Stored on globalThis under `Symbol.for(\"emdash:byline-field-defs\")` so\n * Vite SSR chunk duplication can't produce two independent caches (same\n * pattern as `request-cache.ts` and `request-context.ts`).\n *\n * **Tier 2 — per-request.** Wraps both the version read and the defs\n * fetch in `requestCached` so a single page render that hits byline\n * hydration multiple times (e.g. list view + individual byline lookups\n * in a sidebar) pays at most one version read and one defs fetch in\n * total. The defs cache key includes the version, so a (highly\n * unlikely) mid-request bump still produces a self-consistent view —\n * the second call sees a different key and refetches.\n *\n * **Invalidation.** `options.byline_fields_version` is bumped by every\n * `BylineSchemaRegistry` mutation (Phase 2). Each isolate independently\n * reads the persisted version on the next request and compares against\n * its cached version; mismatch triggers a refetch and overwrite. Other\n * isolates see the change within one request after the bump propagates.\n *\n * **Isolated databases bypass the global cache.** Playground and DO\n * preview sessions set `requestContext.dbIsIsolated = true`, signalling\n * the per-request `db` points at an isolated schema that may diverge\n * from the singleton. Schema-derived caches keyed by the singleton's\n * version would silently leak the singleton's defs into the isolated\n * request. We follow the `loader.ts:74` `getTaxonomyNames` precedent:\n * skip both reading from and writing to the global holder when the\n * request is isolated. The per-request cache (`requestCached`) is keyed\n * by the WeakMap'd `EmDashRequestContext`, so it can't cross-pollinate\n * between requests — it stays in play even for isolated DBs.\n *\n * **Why a versioned cache and not a TTL?** The version counter gives\n * deterministic invalidation without the staleness window a TTL would\n * impose. Field-definition changes need to be visible to the next\n * request, not eventually. The cost is one cheap `options` read per\n * request — cheaper than the field-defs fetch it replaces, and cheaper\n * than maintaining a TTL state machine.\n */\n\nimport type { Kysely } from \"kysely\";\n\nimport { after } from \"../after.js\";\nimport type { Database } from \"../database/types.js\";\nimport { requestCached } from \"../request-cache.js\";\nimport { getRequestContext } from \"../request-context.js\";\nimport { BylineSchemaRegistry } from \"../schema/byline-registry.js\";\nimport type { BylineFieldDefinition } from \"../schema/types.js\";\nimport { createInitLock, type InitLock, initWithLock } from \"../utils/init-lock.js\";\n\ninterface FieldDefsHolder {\n\t/** Last resolved defs, valid only when `hasValue` is true. */\n\tvalue: BylineFieldDefinition[] | null;\n\t/** Presence flag, separate from `value` so an empty-array result still caches. */\n\thasValue: boolean;\n\t/** Persisted-version value that `value` was fetched against. */\n\tcachedVersion: number;\n\t/** Reclaimable single-flight lock so a cancelled owner can't wedge readers. */\n\tlock: InitLock;\n}\n\nconst HOLDER_KEY = Symbol.for(\"emdash:byline-field-defs\");\nconst g = globalThis as Record<symbol, unknown>;\nconst holder: FieldDefsHolder =\n\t// eslint-disable-next-line typescript/no-unsafe-type-assertion -- globalThis singleton pattern (see request-cache.ts)\n\t(g[HOLDER_KEY] as FieldDefsHolder | undefined) ??\n\t(() => {\n\t\tconst h: FieldDefsHolder = {\n\t\t\tvalue: null,\n\t\t\thasValue: false,\n\t\t\tcachedVersion: -1,\n\t\t\tlock: createInitLock(),\n\t\t};\n\t\tg[HOLDER_KEY] = h;\n\t\treturn h;\n\t})();\n\nconst REQUEST_CACHE_KEY_VERSION = \"byline-fields-version\";\nconst REQUEST_CACHE_KEY_DEFS_PREFIX = \"byline-field-defs:\";\n\n/**\n * Reclaim window for the single-flight lock: if an owner holds it past\n * this without publishing (e.g. its request was cancelled and the\n * anchored fetch hasn't completed yet), the next reader reclaims and\n * refetches. `listFields` is a single fast SELECT, so this only needs to\n * cover a genuinely slow/stranded query. Mutable solely so tests can\n * shorten it; production never changes it.\n */\nlet reclaimDeadlineMs = 10_000;\n\n/**\n * Read the persisted `options.byline_fields_version` counter. Cached for\n * the duration of the current request via `requestCached`. Returns `0`\n * when the row is missing (matches `BylineSchemaRegistry.getVersion`).\n */\nasync function getBylineFieldsVersion(db: Kysely<Database>): Promise<number> {\n\treturn requestCached(REQUEST_CACHE_KEY_VERSION, () => new BylineSchemaRegistry(db).getVersion());\n}\n\n/**\n * Resolve registered byline custom-field definitions. Two-tier cache:\n * per-request via `requestCached`, then per-isolate via the global\n * holder.\n *\n * The global holder is bypassed for isolated requests (playground / DO\n * preview, which point at a divergent schema) and for dirty versions\n * (odd counter — see `BylineSchemaRegistry`'s class JSDoc — indicates\n * an in-flight or crashed mutation). Both bypass paths still hit the\n * per-request cache, so a single render dedupes within itself.\n *\n * Always returns an array. Empty = no custom fields registered.\n */\nexport async function getBylineFieldDefs(db: Kysely<Database>): Promise<BylineFieldDefinition[]> {\n\tconst isolated = getRequestContext()?.dbIsIsolated === true;\n\tconst version = await getBylineFieldsVersion(db);\n\tconst dirty = version % 2 !== 0;\n\treturn requestCached(`${REQUEST_CACHE_KEY_DEFS_PREFIX}${version}`, async () => {\n\t\tif (isolated || dirty) {\n\t\t\treturn new BylineSchemaRegistry(db).listFields();\n\t\t}\n\t\t// Per-isolate single-flight cache keyed on the persisted version.\n\t\t// Coalesce concurrent cold readers via the lock and read the\n\t\t// published value; never await another request's in-flight promise\n\t\t// (a cancelled owner would otherwise strand every later byline\n\t\t// hydration on the isolate). The fetch is anchored so a cancelled\n\t\t// originator still drives it to completion and populates the cache.\n\t\treturn initWithLock<BylineFieldDefinition[]>(\n\t\t\tholder.lock,\n\t\t\t() => (holder.hasValue && holder.cachedVersion === version ? holder.value : null),\n\t\t\t(isCurrentClaim) =>\n\t\t\t\t(async () => {\n\t\t\t\t\tconst defs = await new BylineSchemaRegistry(db).listFields();\n\t\t\t\t\t// Publish only while still the current claim, and never\n\t\t\t\t\t// regress over a newer version a concurrent reader stored.\n\t\t\t\t\tif (isCurrentClaim() && version >= holder.cachedVersion) {\n\t\t\t\t\t\tholder.value = defs;\n\t\t\t\t\t\tholder.hasValue = true;\n\t\t\t\t\t\tholder.cachedVersion = version;\n\t\t\t\t\t}\n\t\t\t\t\treturn defs;\n\t\t\t\t})(),\n\t\t\t{ deadlineMs: reclaimDeadlineMs, anchor: (promise) => after(() => promise) },\n\t\t);\n\t});\n}\n\n/**\n * Test/internal helper: clear the per-isolate cache. Useful for unit\n * tests that mutate the registry directly and need to force a refetch\n * without going through the full version-bump path.\n *\n * Production code paths should rely on the version counter for\n * invalidation — calling this from a write path would bypass the\n * coordination that lets other isolates see the change.\n */\nexport function resetBylineFieldDefsCacheForTests(): void {\n\tholder.value = null;\n\tholder.hasValue = false;\n\tholder.cachedVersion = -1;\n\tholder.lock.ownerStartedAt = null;\n\tholder.lock.generation = 0;\n\treclaimDeadlineMs = 10_000;\n}\n\n/**\n * Test-only: shorten the single-flight reclaim window so a \"stranded\n * owner\" scenario can be exercised without waiting out the production\n * deadline. Reset by `resetBylineFieldDefsCacheForTests`.\n *\n * @internal\n */\nexport function setBylineFieldDefsReclaimDeadlineForTests(ms: number): void {\n\treclaimDeadlineMs = ms;\n}\n"],"mappings":";;;;;;;;;AA2EA,MAAM,aAAa,OAAO,IAAI,2BAA2B;AACzD,MAAM,IAAI;AACV,MAAM,SAEJ,EAAE,sBACI;CACN,MAAM,IAAqB;EAC1B,OAAO;EACP,UAAU;EACV,eAAe;EACf,MAAM,gBAAgB;EACtB;AACD,GAAE,cAAc;AAChB,QAAO;IACJ;AAEL,MAAM,4BAA4B;AAClC,MAAM,gCAAgC;;;;;;;;;AAUtC,IAAI,oBAAoB;;;;;;AAOxB,eAAe,uBAAuB,IAAuC;AAC5E,QAAO,cAAc,iCAAiC,IAAI,qBAAqB,GAAG,CAAC,YAAY,CAAC;;;;;;;;;;;;;;;AAgBjG,eAAsB,mBAAmB,IAAwD;CAChG,MAAM,WAAW,mBAAmB,EAAE,iBAAiB;CACvD,MAAM,UAAU,MAAM,uBAAuB,GAAG;CAChD,MAAM,QAAQ,UAAU,MAAM;AAC9B,QAAO,cAAc,GAAG,gCAAgC,WAAW,YAAY;AAC9E,MAAI,YAAY,MACf,QAAO,IAAI,qBAAqB,GAAG,CAAC,YAAY;AAQjD,SAAO,aACN,OAAO,YACA,OAAO,YAAY,OAAO,kBAAkB,UAAU,OAAO,QAAQ,OAC3E,oBACC,YAAY;GACZ,MAAM,OAAO,MAAM,IAAI,qBAAqB,GAAG,CAAC,YAAY;AAG5D,OAAI,gBAAgB,IAAI,WAAW,OAAO,eAAe;AACxD,WAAO,QAAQ;AACf,WAAO,WAAW;AAClB,WAAO,gBAAgB;;AAExB,UAAO;MACJ,EACL;GAAE,YAAY;GAAmB,SAAS,YAAY,YAAY,QAAQ;GAAE,CAC5E;GACA"}