@rangojs/router 0.0.0-experimental.14 → 0.0.0-experimental.140

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (460) hide show
  1. package/AGENTS.md +17 -0
  2. package/README.md +432 -7
  3. package/dist/bin/rango.js +2073 -213
  4. package/dist/testing/vitest.js +82 -0
  5. package/dist/vite/index.js +7258 -2714
  6. package/dist/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  7. package/package.json +140 -67
  8. package/skills/api-client/SKILL.md +211 -0
  9. package/skills/breadcrumbs/SKILL.md +329 -0
  10. package/skills/bundle-analysis/SKILL.md +159 -0
  11. package/skills/cache-guide/SKILL.md +487 -0
  12. package/skills/caching/SKILL.md +357 -25
  13. package/skills/comparison/SKILL.md +50 -0
  14. package/skills/comparison/agents/openai.yaml +4 -0
  15. package/skills/comparison/references/framework-comparison.md +837 -0
  16. package/skills/composability/SKILL.md +246 -0
  17. package/skills/css/SKILL.md +76 -0
  18. package/skills/debug-manifest/SKILL.md +16 -10
  19. package/skills/document-cache/SKILL.md +87 -62
  20. package/skills/fonts/SKILL.md +6 -4
  21. package/skills/handler-use/SKILL.md +364 -0
  22. package/skills/hooks/SKILL.md +557 -79
  23. package/skills/host-router/SKILL.md +320 -0
  24. package/skills/i18n/SKILL.md +276 -0
  25. package/skills/intercept/SKILL.md +207 -15
  26. package/skills/layout/SKILL.md +146 -6
  27. package/skills/links/SKILL.md +304 -25
  28. package/skills/loader/SKILL.md +616 -54
  29. package/skills/middleware/SKILL.md +217 -37
  30. package/skills/migrate-nextjs/SKILL.md +611 -0
  31. package/skills/migrate-react-router/SKILL.md +927 -0
  32. package/skills/mime-routes/SKILL.md +42 -11
  33. package/skills/observability/SKILL.md +194 -0
  34. package/skills/parallel/SKILL.md +284 -3
  35. package/skills/ppr/SKILL.md +426 -0
  36. package/skills/prerender/SKILL.md +437 -52
  37. package/skills/rango/SKILL.md +369 -22
  38. package/skills/react-compiler/SKILL.md +168 -0
  39. package/skills/response-routes/SKILL.md +263 -121
  40. package/skills/route/SKILL.md +350 -21
  41. package/skills/router-setup/SKILL.md +246 -33
  42. package/skills/scripts/SKILL.md +179 -0
  43. package/skills/server-actions/SKILL.md +775 -0
  44. package/skills/shell-manifest/SKILL.md +185 -0
  45. package/skills/streams-and-websockets/SKILL.md +283 -0
  46. package/skills/tailwind/SKILL.md +27 -3
  47. package/skills/testing/SKILL.md +126 -222
  48. package/skills/testing/bindings.md +103 -0
  49. package/skills/testing/cache-prerender.md +127 -0
  50. package/skills/testing/client-components.md +124 -0
  51. package/skills/testing/e2e-parity.md +125 -0
  52. package/skills/testing/flight.md +91 -0
  53. package/skills/testing/handles.md +131 -0
  54. package/skills/testing/loader.md +128 -0
  55. package/skills/testing/middleware.md +99 -0
  56. package/skills/testing/render-handler.md +122 -0
  57. package/skills/testing/response-routes.md +95 -0
  58. package/skills/testing/reverse-and-types.md +85 -0
  59. package/skills/testing/server-actions.md +107 -0
  60. package/skills/testing/server-tree.md +128 -0
  61. package/skills/testing/setup.md +123 -0
  62. package/skills/theme/SKILL.md +9 -8
  63. package/skills/typesafety/SKILL.md +532 -103
  64. package/skills/use-cache/SKILL.md +367 -0
  65. package/skills/vercel/SKILL.md +128 -0
  66. package/skills/view-transitions/SKILL.md +337 -0
  67. package/src/__augment-tests__/augment.ts +81 -0
  68. package/src/__augment-tests__/augmented.check.ts +116 -0
  69. package/src/__internal.ts +77 -44
  70. package/src/bin/rango.ts +312 -15
  71. package/src/browser/action-coordinator.ts +114 -0
  72. package/src/browser/action-fence.ts +47 -0
  73. package/src/browser/app-shell.ts +39 -0
  74. package/src/browser/app-version.ts +14 -0
  75. package/src/browser/connection-warmup.ts +134 -0
  76. package/src/browser/cookie-name.ts +140 -0
  77. package/src/browser/event-controller.ts +293 -202
  78. package/src/browser/history-state.ts +101 -0
  79. package/src/browser/index.ts +3 -3
  80. package/src/browser/intercept-utils.ts +52 -0
  81. package/src/browser/invalidate-client-cache.ts +52 -0
  82. package/src/browser/link-interceptor.ts +24 -4
  83. package/src/browser/logging.ts +11 -0
  84. package/src/browser/merge-segment-loaders.ts +20 -12
  85. package/src/browser/navigation-bridge.ts +385 -576
  86. package/src/browser/navigation-client.ts +245 -75
  87. package/src/browser/navigation-store-handle.ts +38 -0
  88. package/src/browser/navigation-store.ts +184 -118
  89. package/src/browser/navigation-transaction.ts +247 -0
  90. package/src/browser/network-error-handler.ts +88 -0
  91. package/src/browser/partial-update.ts +412 -364
  92. package/src/browser/prefetch/cache.ts +359 -0
  93. package/src/browser/prefetch/fetch.ts +452 -0
  94. package/src/browser/prefetch/observer.ts +65 -0
  95. package/src/browser/prefetch/policy.ts +48 -0
  96. package/src/browser/prefetch/queue.ts +209 -0
  97. package/src/browser/prefetch/resource-ready.ts +77 -0
  98. package/src/browser/rango-state.ts +194 -0
  99. package/src/browser/react/Link.tsx +275 -68
  100. package/src/browser/react/NavigationProvider.tsx +265 -109
  101. package/src/browser/react/ScrollRestoration.tsx +10 -6
  102. package/src/browser/react/context.ts +11 -0
  103. package/src/browser/react/filter-segment-order.ts +70 -0
  104. package/src/browser/react/index.ts +0 -48
  105. package/src/browser/react/location-state-shared.ts +272 -60
  106. package/src/browser/react/location-state.ts +90 -20
  107. package/src/browser/react/mount-context.ts +6 -1
  108. package/src/browser/react/nonce-context.ts +23 -0
  109. package/src/browser/react/shallow-equal.ts +27 -0
  110. package/src/browser/react/use-action.ts +35 -66
  111. package/src/browser/react/use-handle.ts +39 -126
  112. package/src/browser/react/use-href.tsx +8 -1
  113. package/src/browser/react/use-link-status.ts +39 -13
  114. package/src/browser/react/use-navigation.ts +53 -69
  115. package/src/browser/react/use-params.ts +75 -0
  116. package/src/browser/react/use-pathname.ts +47 -0
  117. package/src/browser/react/use-reverse.ts +106 -0
  118. package/src/browser/react/use-router.ts +98 -0
  119. package/src/browser/react/use-search-params.ts +51 -0
  120. package/src/browser/react/use-segments.ts +72 -99
  121. package/src/browser/response-adapter.ts +164 -0
  122. package/src/browser/rsc-router.tsx +300 -72
  123. package/src/browser/scroll-restoration.ts +138 -50
  124. package/src/browser/segment-reconciler.ts +243 -0
  125. package/src/browser/segment-structure-assert.ts +17 -1
  126. package/src/browser/server-action-bridge.ts +668 -613
  127. package/src/browser/types.ts +223 -51
  128. package/src/browser/validate-redirect-origin.ts +56 -0
  129. package/src/build/collect-fallback-refs.ts +107 -0
  130. package/src/build/generate-manifest.ts +252 -161
  131. package/src/build/generate-route-types.ts +41 -1038
  132. package/src/build/index.ts +12 -7
  133. package/src/build/prefix-tree-utils.ts +123 -0
  134. package/src/build/route-trie.ts +225 -42
  135. package/src/build/route-types/ast-helpers.ts +25 -0
  136. package/src/build/route-types/ast-route-extraction.ts +105 -0
  137. package/src/build/route-types/codegen.ts +113 -0
  138. package/src/build/route-types/include-resolution.ts +812 -0
  139. package/src/build/route-types/param-extraction.ts +51 -0
  140. package/src/build/route-types/per-module-writer.ts +144 -0
  141. package/src/build/route-types/router-processing.ts +695 -0
  142. package/src/build/route-types/scan-filter.ts +85 -0
  143. package/src/build/route-types/source-scan.ts +216 -0
  144. package/src/build/runtime-discovery.ts +223 -0
  145. package/src/cache/background-task.ts +34 -0
  146. package/src/cache/cache-error.ts +104 -0
  147. package/src/cache/cache-key-utils.ts +60 -0
  148. package/src/cache/cache-policy.ts +199 -0
  149. package/src/cache/cache-runtime.ts +525 -0
  150. package/src/cache/cache-scope.ts +298 -332
  151. package/src/cache/cache-tag.ts +103 -0
  152. package/src/cache/cf/cf-base64.ts +33 -0
  153. package/src/cache/cf/cf-cache-constants.ts +127 -0
  154. package/src/cache/cf/cf-cache-store.ts +2500 -158
  155. package/src/cache/cf/cf-cache-types.ts +349 -0
  156. package/src/cache/cf/cf-kv-utils.ts +46 -0
  157. package/src/cache/cf/cf-tag-marker-memo.ts +105 -0
  158. package/src/cache/cf/index.ts +17 -17
  159. package/src/cache/document-cache.ts +199 -92
  160. package/src/cache/handle-capture.ts +81 -0
  161. package/src/cache/handle-snapshot.ts +111 -0
  162. package/src/cache/index.ts +29 -35
  163. package/src/cache/memory-segment-store.ts +363 -30
  164. package/src/cache/profile-registry.ts +88 -0
  165. package/src/cache/read-through-swr.ts +178 -0
  166. package/src/cache/segment-codec.ts +248 -0
  167. package/src/cache/shell-cache.ts +386 -0
  168. package/src/cache/tag-invalidation.ts +230 -0
  169. package/src/cache/taint.ts +153 -0
  170. package/src/cache/types.ts +156 -211
  171. package/src/cache/vercel/index.ts +11 -0
  172. package/src/cache/vercel/vercel-cache-store.ts +1102 -0
  173. package/src/client.rsc.tsx +43 -21
  174. package/src/client.tsx +131 -347
  175. package/src/cloudflare/index.ts +11 -0
  176. package/src/cloudflare/tracing.ts +109 -0
  177. package/src/component-utils.ts +23 -4
  178. package/src/components/DefaultDocument.tsx +13 -3
  179. package/src/context-var.ts +168 -0
  180. package/src/debug.ts +19 -9
  181. package/src/decode-loader-results.ts +52 -0
  182. package/src/defer.ts +185 -0
  183. package/src/deps/ssr.ts +0 -1
  184. package/src/encode-kv.ts +49 -0
  185. package/src/errors.ts +106 -10
  186. package/src/escape-script.ts +52 -0
  187. package/src/handle.ts +110 -35
  188. package/src/handles/MetaTags.tsx +83 -59
  189. package/src/handles/Scripts.tsx +183 -0
  190. package/src/handles/breadcrumbs.ts +93 -0
  191. package/src/handles/deferred-resolution.ts +127 -0
  192. package/src/handles/is-thenable.ts +18 -0
  193. package/src/handles/meta.ts +44 -53
  194. package/src/handles/script.ts +244 -0
  195. package/src/host/cookie-handler.ts +20 -65
  196. package/src/host/errors.ts +21 -30
  197. package/src/host/index.ts +13 -9
  198. package/src/host/pattern-matcher.ts +50 -79
  199. package/src/host/router.ts +151 -121
  200. package/src/host/testing.ts +45 -32
  201. package/src/host/types.ts +52 -11
  202. package/src/host/utils.ts +2 -2
  203. package/src/href-client.ts +192 -57
  204. package/src/index.rsc.ts +177 -35
  205. package/src/index.ts +255 -71
  206. package/src/internal-debug.ts +9 -2
  207. package/src/loader-store.ts +500 -0
  208. package/src/loader.rsc.ts +31 -99
  209. package/src/loader.ts +30 -12
  210. package/src/missing-id-error.ts +68 -0
  211. package/src/outlet-context.ts +1 -1
  212. package/src/outlet-provider.tsx +41 -0
  213. package/src/prerender/param-hash.ts +16 -14
  214. package/src/prerender/store.ts +121 -21
  215. package/src/prerender.ts +460 -26
  216. package/src/redirect-origin.ts +100 -0
  217. package/src/regex-escape.ts +8 -0
  218. package/src/render-error-thrower.tsx +20 -0
  219. package/src/response-utils.ts +62 -0
  220. package/src/reverse.ts +198 -128
  221. package/src/root-error-boundary.tsx +42 -48
  222. package/src/route-content-wrapper.tsx +22 -77
  223. package/src/route-definition/dsl-helpers.ts +1116 -0
  224. package/src/route-definition/helper-factories.ts +88 -0
  225. package/src/route-definition/helpers-types.ts +505 -0
  226. package/src/route-definition/index.ts +54 -0
  227. package/src/route-definition/redirect.ts +134 -0
  228. package/src/route-definition/resolve-handler-use.ts +160 -0
  229. package/src/route-definition/use-item-types.ts +29 -0
  230. package/src/route-definition.ts +1 -1481
  231. package/src/route-map-builder.ts +82 -144
  232. package/src/route-name.ts +53 -0
  233. package/src/route-types.ts +71 -45
  234. package/src/router/basename.ts +14 -0
  235. package/src/router/content-negotiation.ts +263 -0
  236. package/src/router/debug-manifest.ts +72 -0
  237. package/src/router/error-handling.ts +54 -27
  238. package/src/router/find-match.ts +245 -0
  239. package/src/router/handler-context.ts +377 -125
  240. package/src/router/instrument.ts +350 -0
  241. package/src/router/intercept-resolution.ts +59 -28
  242. package/src/router/lazy-includes.ts +254 -0
  243. package/src/router/loader-resolution.ts +421 -157
  244. package/src/router/logging.ts +106 -6
  245. package/src/router/manifest.ts +131 -57
  246. package/src/router/match-api.ts +167 -246
  247. package/src/router/match-context.ts +4 -24
  248. package/src/router/match-handlers.ts +440 -0
  249. package/src/router/match-middleware/background-revalidation.ts +117 -93
  250. package/src/router/match-middleware/cache-lookup.ts +297 -150
  251. package/src/router/match-middleware/cache-store.ts +123 -51
  252. package/src/router/match-middleware/intercept-resolution.ts +44 -43
  253. package/src/router/match-middleware/segment-resolution.ts +64 -22
  254. package/src/router/match-pipelines.ts +11 -87
  255. package/src/router/match-result.ts +121 -50
  256. package/src/router/metrics.ts +219 -28
  257. package/src/router/middleware-types.ts +93 -0
  258. package/src/router/middleware.ts +505 -441
  259. package/src/router/navigation-snapshot.ts +133 -0
  260. package/src/router/params-util.ts +23 -0
  261. package/src/router/parse-pattern.ts +115 -0
  262. package/src/router/pattern-matching.ts +311 -142
  263. package/src/router/prefetch-cache-ttl.ts +51 -0
  264. package/src/router/prefetch-limits.ts +37 -0
  265. package/src/router/prerender-match.ts +547 -0
  266. package/src/router/preview-match.ts +102 -0
  267. package/src/router/request-classification.ts +278 -0
  268. package/src/router/revalidation.ts +203 -62
  269. package/src/router/route-snapshot.ts +246 -0
  270. package/src/router/router-context.ts +45 -48
  271. package/src/router/router-interfaces.ts +554 -0
  272. package/src/router/router-options.ts +779 -0
  273. package/src/router/router-registry.ts +21 -0
  274. package/src/router/segment-resolution/fresh.ts +772 -0
  275. package/src/router/segment-resolution/helpers.ts +348 -0
  276. package/src/router/segment-resolution/loader-cache.ts +250 -0
  277. package/src/router/segment-resolution/loader-mask.ts +44 -0
  278. package/src/router/segment-resolution/revalidation.ts +1331 -0
  279. package/src/router/segment-resolution/static-store.ts +81 -0
  280. package/src/router/segment-resolution/streamed-handler-telemetry.ts +52 -0
  281. package/src/router/segment-resolution/view-transition-default.ts +56 -0
  282. package/src/router/segment-resolution.ts +25 -1354
  283. package/src/router/segment-wrappers.ts +292 -0
  284. package/src/router/state-cookie-name.ts +33 -0
  285. package/src/router/substitute-pattern-params.ts +75 -0
  286. package/src/router/telemetry-otel.ts +261 -0
  287. package/src/router/telemetry.ts +377 -0
  288. package/src/router/timeout.ts +128 -0
  289. package/src/router/tracing.ts +206 -0
  290. package/src/router/trie-matching.ts +240 -61
  291. package/src/router/types.ts +23 -70
  292. package/src/router/url-params.ts +57 -0
  293. package/src/router.ts +781 -2378
  294. package/src/rsc/full-payload.ts +70 -0
  295. package/src/rsc/handler-context.ts +46 -0
  296. package/src/rsc/handler.ts +905 -1142
  297. package/src/rsc/helpers.ts +275 -19
  298. package/src/rsc/index.ts +2 -25
  299. package/src/rsc/json-route-result.ts +38 -0
  300. package/src/rsc/loader-fetch.ts +305 -0
  301. package/src/rsc/manifest-init.ts +77 -0
  302. package/src/rsc/nonce.ts +14 -0
  303. package/src/rsc/origin-guard.ts +155 -0
  304. package/src/rsc/progressive-enhancement.ts +502 -0
  305. package/src/rsc/redirect-guard.ts +99 -0
  306. package/src/rsc/response-cache-serve.ts +238 -0
  307. package/src/rsc/response-error.ts +104 -0
  308. package/src/rsc/response-route-handler.ts +257 -0
  309. package/src/rsc/rsc-rendering.ts +337 -0
  310. package/src/rsc/runtime-warnings.ts +55 -0
  311. package/src/rsc/server-action.ts +522 -0
  312. package/src/rsc/shell-capture.ts +439 -0
  313. package/src/rsc/ssr-setup.ts +144 -0
  314. package/src/rsc/transition-gate.ts +89 -0
  315. package/src/rsc/types.ts +95 -12
  316. package/src/runtime-env.ts +18 -0
  317. package/src/search-params.ts +99 -82
  318. package/src/segment-content-promise.ts +67 -0
  319. package/src/segment-loader-promise.ts +149 -0
  320. package/src/segment-system.tsx +349 -134
  321. package/src/serialize.ts +243 -0
  322. package/src/server/context.ts +452 -85
  323. package/src/server/cookie-parse.ts +32 -0
  324. package/src/server/cookie-store.ts +310 -0
  325. package/src/server/fetchable-loader-store.ts +11 -6
  326. package/src/server/handle-store.ts +123 -42
  327. package/src/server/live.ts +130 -0
  328. package/src/server/loader-registry.ts +51 -100
  329. package/src/server/request-context.ts +842 -157
  330. package/src/server.ts +15 -8
  331. package/src/ssr/index.tsx +412 -136
  332. package/src/ssr/ssr-root.tsx +228 -0
  333. package/src/static-handler.ts +45 -18
  334. package/src/testing/cache-status.ts +162 -0
  335. package/src/testing/collect-handle.ts +46 -0
  336. package/src/testing/dispatch.ts +701 -0
  337. package/src/testing/dom.entry.ts +22 -0
  338. package/src/testing/e2e/fixture.ts +188 -0
  339. package/src/testing/e2e/index.ts +128 -0
  340. package/src/testing/e2e/matchers.ts +35 -0
  341. package/src/testing/e2e/page-helpers.ts +272 -0
  342. package/src/testing/e2e/parity.ts +387 -0
  343. package/src/testing/e2e/server.ts +195 -0
  344. package/src/testing/flight-matchers.ts +97 -0
  345. package/src/testing/flight-normalize.ts +11 -0
  346. package/src/testing/flight-runtime.d.ts +57 -0
  347. package/src/testing/flight-tree.ts +682 -0
  348. package/src/testing/flight.entry.ts +52 -0
  349. package/src/testing/flight.ts +257 -0
  350. package/src/testing/generated-routes.ts +199 -0
  351. package/src/testing/index.ts +105 -0
  352. package/src/testing/internal/context.ts +371 -0
  353. package/src/testing/internal/flight-client-globals.ts +30 -0
  354. package/src/testing/internal/seed-vars.ts +54 -0
  355. package/src/testing/render-handler.ts +357 -0
  356. package/src/testing/render-route.tsx +584 -0
  357. package/src/testing/run-loader.ts +385 -0
  358. package/src/testing/run-middleware.ts +205 -0
  359. package/src/testing/run-transition-when.ts +164 -0
  360. package/src/testing/vitest-stubs/cloudflare-email.ts +9 -0
  361. package/src/testing/vitest-stubs/cloudflare-workers.ts +21 -0
  362. package/src/testing/vitest-stubs/plugin-rsc.ts +16 -0
  363. package/src/testing/vitest-stubs/version.ts +5 -0
  364. package/src/testing/vitest.ts +305 -0
  365. package/src/theme/ThemeProvider.tsx +40 -72
  366. package/src/theme/ThemeScript.tsx +12 -14
  367. package/src/theme/constants.ts +57 -15
  368. package/src/theme/index.ts +3 -20
  369. package/src/theme/theme-context.ts +5 -35
  370. package/src/theme/theme-script.ts +43 -39
  371. package/src/theme/use-theme.ts +0 -3
  372. package/src/types/boundaries.ts +123 -0
  373. package/src/types/cache-types.ts +207 -0
  374. package/src/types/error-types.ts +132 -0
  375. package/src/types/global-namespace.ts +113 -0
  376. package/src/types/handler-context.ts +839 -0
  377. package/src/types/index.ts +81 -0
  378. package/src/types/loader-types.ts +212 -0
  379. package/src/types/request-scope.ts +112 -0
  380. package/src/types/route-config.ts +138 -0
  381. package/src/types/route-entry.ts +114 -0
  382. package/src/types/segments.ts +271 -0
  383. package/src/types.ts +1 -1795
  384. package/src/urls/include-helper.ts +162 -0
  385. package/src/urls/include-provider.ts +71 -0
  386. package/src/urls/index.ts +43 -0
  387. package/src/urls/path-helper-types.ts +413 -0
  388. package/src/urls/path-helper.ts +275 -0
  389. package/src/urls/pattern-types.ts +124 -0
  390. package/src/urls/response-types.ts +109 -0
  391. package/src/urls/type-extraction.ts +316 -0
  392. package/src/urls/urls-function.ts +80 -0
  393. package/src/urls.ts +1 -1341
  394. package/src/use-loader.tsx +406 -141
  395. package/src/vercel/index.ts +11 -0
  396. package/src/vercel/tracing.ts +88 -0
  397. package/src/vite/debug.ts +185 -0
  398. package/src/vite/discovery/bundle-postprocess.ts +182 -0
  399. package/src/vite/discovery/discover-routers.ts +389 -0
  400. package/src/vite/discovery/discovery-errors.ts +255 -0
  401. package/src/vite/discovery/gate-state.ts +171 -0
  402. package/src/vite/discovery/prerender-collection.ts +467 -0
  403. package/src/vite/discovery/route-types-writer.ts +214 -0
  404. package/src/vite/discovery/self-gen-tracking.ts +73 -0
  405. package/src/vite/discovery/state.ts +161 -0
  406. package/src/vite/discovery/virtual-module-codegen.ts +183 -0
  407. package/src/vite/index.ts +23 -2255
  408. package/src/vite/inject-client-debug.ts +36 -0
  409. package/src/vite/plugin-types.ts +303 -0
  410. package/src/vite/plugins/cjs-to-esm.ts +90 -0
  411. package/src/vite/plugins/client-ref-dedup.ts +120 -0
  412. package/src/vite/plugins/client-ref-hashing.ts +118 -0
  413. package/src/vite/plugins/cloudflare-protocol-loader-hook.d.mts +23 -0
  414. package/src/vite/plugins/cloudflare-protocol-loader-hook.mjs +76 -0
  415. package/src/vite/plugins/cloudflare-protocol-stub.ts +194 -0
  416. package/src/vite/{expose-action-id.ts → plugins/expose-action-id.ts} +88 -110
  417. package/src/vite/{expose-id-utils.ts → plugins/expose-id-utils.ts} +89 -79
  418. package/src/vite/plugins/expose-ids/export-analysis.ts +363 -0
  419. package/src/vite/plugins/expose-ids/handler-transform.ts +130 -0
  420. package/src/vite/plugins/expose-ids/loader-transform.ts +64 -0
  421. package/src/vite/plugins/expose-ids/router-transform.ts +199 -0
  422. package/src/vite/plugins/expose-ids/types.ts +45 -0
  423. package/src/vite/plugins/expose-internal-ids.ts +805 -0
  424. package/src/vite/plugins/performance-tracks.ts +89 -0
  425. package/src/vite/plugins/refresh-cmd.ts +127 -0
  426. package/src/vite/plugins/use-cache-transform.ts +313 -0
  427. package/src/vite/plugins/vercel-output.ts +384 -0
  428. package/src/vite/plugins/version-injector.ts +94 -0
  429. package/src/vite/plugins/version-plugin.ts +263 -0
  430. package/src/vite/plugins/virtual-entries.ts +234 -0
  431. package/src/vite/plugins/virtual-stub-plugin.ts +29 -0
  432. package/src/vite/rango.ts +560 -0
  433. package/src/vite/router-discovery.ts +1638 -0
  434. package/src/vite/{ast-handler-extract.ts → utils/ast-handler-extract.ts} +200 -37
  435. package/src/vite/utils/banner.ts +36 -0
  436. package/src/vite/utils/bundle-analysis.ts +132 -0
  437. package/src/vite/utils/client-chunks.ts +184 -0
  438. package/src/vite/utils/directive-prologue.ts +40 -0
  439. package/src/vite/utils/forward-user-plugins.ts +171 -0
  440. package/src/vite/utils/manifest-utils.ts +15 -0
  441. package/src/vite/utils/package-resolution.ts +89 -0
  442. package/src/vite/utils/prerender-utils.ts +249 -0
  443. package/src/vite/utils/shared-utils.ts +269 -0
  444. package/CLAUDE.md +0 -43
  445. package/dist/vite/index.named-routes.gen.ts +0 -103
  446. package/src/browser/lru-cache.ts +0 -69
  447. package/src/browser/react/use-client-cache.ts +0 -56
  448. package/src/browser/request-controller.ts +0 -164
  449. package/src/browser/shallow.ts +0 -35
  450. package/src/cache/memory-store.ts +0 -253
  451. package/src/handles/index.ts +0 -6
  452. package/src/href-context.ts +0 -33
  453. package/src/network-error-thrower.tsx +0 -21
  454. package/src/router.gen.ts +0 -6
  455. package/src/static-handler.gen.ts +0 -5
  456. package/src/urls.gen.ts +0 -8
  457. package/src/vite/expose-internal-ids.ts +0 -1167
  458. package/src/vite/package-resolution.ts +0 -125
  459. package/src/vite/virtual-entries.ts +0 -114
  460. /package/src/vite/{version.d.ts → plugins/version.d.ts} +0 -0
@@ -1,4 +1,4 @@
1
- /// <reference path="../../vite/version.d.ts" />
1
+ /// <reference path="../../vite/plugins/version.d.ts" />
2
2
 
3
3
  // Extend CacheStorage with Cloudflare's default cache property
4
4
  declare global {
@@ -10,14 +10,21 @@ declare global {
10
10
  /**
11
11
  * Cloudflare Edge Cache Store
12
12
  *
13
- * Production cache store using Cloudflare's Cache API.
14
- * Handles SWR atomically - get() checks staleness and marks REVALIDATING in one operation.
13
+ * Production cache store using Cloudflare's Cache API (L1) with optional
14
+ * KV persistence (L2).
15
+ *
16
+ * L1 (Cache API): Per-colo, fast, ephemeral. Handles SWR atomically.
17
+ * L2 (KV): Global, persistent, ~50ms reads. Auto-warms cold colos.
18
+ *
19
+ * Read flow: L1 hit → serve | L1 miss → L2 hit → serve + promote to L1 | both miss → render
20
+ * Write flow: L1 write + L2 write (both via waitUntil)
15
21
  *
16
22
  * Features:
17
23
  * - Extended TTL for SWR window (max-age = ttl + swr)
18
24
  * - Staleness via x-edge-cache-stale-at header
19
- * - Atomic REVALIDATING status for thundering herd prevention
25
+ * - Atomic REVALIDATING status for thundering herd prevention (L1 only)
20
26
  * - Non-blocking writes via waitUntil
27
+ * - KV L2 for cross-colo cache persistence
21
28
  */
22
29
 
23
30
  import type {
@@ -25,121 +32,209 @@ import type {
25
32
  CachedEntryData,
26
33
  CacheDefaults,
27
34
  CacheGetResult,
35
+ CacheItemResult,
36
+ CacheItemOptions,
37
+ ShellCacheEntry,
28
38
  } from "../types.js";
29
39
  import {
30
- getRequestContext,
40
+ _getRequestContext,
31
41
  type RequestContext,
32
42
  } from "../../server/request-context.js";
33
43
  import { VERSION } from "@rangojs/router:version";
44
+ import {
45
+ isPerClientSignalHeader,
46
+ stripPerClientSignals,
47
+ } from "../../browser/cookie-name.js";
48
+ import {
49
+ resolveTtl,
50
+ resolveSwrWindow,
51
+ DEFAULT_FUNCTION_TTL,
52
+ } from "../cache-policy.js";
53
+ import { reportCacheError, reportingAsync } from "../cache-error.js";
54
+ import type { CacheErrorCategory } from "../cache-error.js";
55
+ import { bufferToBase64, base64ToBuffer } from "./cf-base64.js";
56
+ import {
57
+ KV_MAX_KEY_BYTES,
58
+ KV_MIN_EXPIRATION_TTL,
59
+ kvKeyByteLength,
60
+ remainingCacheControl,
61
+ } from "./cf-kv-utils.js";
62
+ import {
63
+ TAG_MARKER_CACHE_PREFIX,
64
+ TAG_MARKER_ABSENT,
65
+ getTagMarkerMemo,
66
+ getTagMarkerInflight,
67
+ } from "./cf-tag-marker-memo.js";
34
68
 
35
69
  // ============================================================================
36
70
  // Constants
37
71
  // ============================================================================
72
+ //
73
+ // Header names, KV prefixes, and timeout/interval defaults live in
74
+ // cf-cache-constants.ts so collaborator modules can share them without a
75
+ // circular import back to this class. They are re-exported below so existing
76
+ // import paths (`../cf-cache-store`, `./cf-cache-store.js`) still resolve.
77
+ import {
78
+ CACHE_STALE_AT_HEADER,
79
+ CACHE_STATUS_HEADER,
80
+ CACHE_TAGS_HEADER,
81
+ CACHE_TAGGED_AT_HEADER,
82
+ TAG_MARKER_PREFIX,
83
+ CACHE_REVALIDATING_AT_HEADER,
84
+ CACHE_EXPIRES_AT_HEADER,
85
+ CACHE_ORIG_CC_HEADER,
86
+ MAX_REVALIDATION_INTERVAL,
87
+ EDGE_LOOKUP_TIMEOUT_MS,
88
+ EDGE_READ_TIMEOUT_MS,
89
+ KV_READ_TIMEOUT_MS,
90
+ } from "./cf-cache-constants.js";
38
91
 
39
- /** Header storing timestamp when entry becomes stale */
40
- export const CACHE_STALE_AT_HEADER = "x-edge-cache-stale-at";
92
+ // Re-export the public constants so consumers/tests importing them from
93
+ // cf-cache-store keep working after the move.
94
+ export {
95
+ CACHE_STALE_AT_HEADER,
96
+ CACHE_STATUS_HEADER,
97
+ CACHE_TAGS_HEADER,
98
+ CACHE_TAGGED_AT_HEADER,
99
+ TAG_MARKER_PREFIX,
100
+ CACHE_REVALIDATING_AT_HEADER,
101
+ MAX_REVALIDATION_INTERVAL,
102
+ EDGE_LOOKUP_TIMEOUT_MS,
103
+ EDGE_READ_TIMEOUT_MS,
104
+ KV_READ_TIMEOUT_MS,
105
+ };
41
106
 
42
- /** Header storing cache status: HIT | REVALIDATING */
43
- export const CACHE_STATUS_HEADER = "x-edge-cache-status";
107
+ // The tag-marker prefix/sentinel and per-request memo helpers (with their
108
+ // module-singleton WeakMaps) live in cf-tag-marker-memo.ts; imported above.
44
109
 
45
110
  /**
46
- * Maximum age in seconds for REVALIDATING status before allowing new revalidation.
47
- * After this period, a stale entry in REVALIDATING status will trigger revalidation again.
48
- * @internal
111
+ * Per-request memo of the derived cache-key base URL.
112
+ *
113
+ * deriveBaseUrl() is a pure function of the live request URL, but keyToRequest
114
+ * calls it on EVERY cache operation (each segment/item get/set/delete, each
115
+ * KV->L1 promote, each tag-marker read), so a page composed of many cached
116
+ * entries re-parses the same request.url and re-runs the host validation tens
117
+ * of times. Keying by the request-context object collapses that to one derive
118
+ * per request. Keyed by ctx alone (not by store) because the derived value
119
+ * depends only on the request URL, not on which store asked.
120
+ */
121
+ const derivedBaseUrlMemo = new WeakMap<object, string>();
122
+
123
+ // Pure KV helpers (key byte-length limits, expirationTtl floor, stale-path
124
+ // Cache-Control recompute) live in cf-kv-utils.ts; imported above.
125
+
126
+ /**
127
+ * Stores (by namespace) already warned about tag machinery configured without a
128
+ * KV namespace, so the warning fires once per process rather than per request
129
+ * (CFCacheStore is constructed per request).
130
+ */
131
+ const warnedNoKvReadInvalidation = new Set<string>();
132
+
133
+ /**
134
+ * Stores (by namespace) already warned about a tagInvalidationTtl below KV's
135
+ * expirationTtl floor, so the floor warning fires once per process rather than
136
+ * once per request (CFCacheStore is constructed per request).
49
137
  */
50
- export const MAX_REVALIDATION_INTERVAL = 30;
138
+ const warnedTagInvalidationTtlFloor = new Set<string>();
51
139
 
52
140
  // ============================================================================
53
141
  // Types
54
142
  // ============================================================================
143
+ //
144
+ // The shared public types (KVNamespace, CFCacheReadDebugEvent, CFCacheDebug,
145
+ // CFCacheStoreOptions) live in cf-cache-types.ts; imported and re-exported below
146
+ // so existing import paths still resolve. The private KV envelope interfaces
147
+ // stay here with the methods that read/write them.
148
+ import type {
149
+ KVNamespace,
150
+ CFCacheReadDebugEvent,
151
+ CFCacheDebug,
152
+ CFCacheStoreOptions,
153
+ } from "./cf-cache-types.js";
154
+ export type {
155
+ KVNamespace,
156
+ CFCacheReadDebugEvent,
157
+ CFCacheDebug,
158
+ CFCacheStoreOptions,
159
+ };
55
160
 
56
161
  /**
57
- * Cloudflare Workers ExecutionContext (subset we need)
162
+ * KV envelope for segment cache entries.
163
+ * @internal
58
164
  */
59
- export interface ExecutionContext {
60
- waitUntil(promise: Promise<any>): void;
61
- passThroughOnException(): void;
165
+ interface KVSegmentEnvelope {
166
+ /** Cached segment data */
167
+ d: CachedEntryData;
168
+ /** When entry becomes stale (ms epoch) */
169
+ s: number;
170
+ /** When entry hard-expires (ms epoch) */
171
+ e: number;
62
172
  }
63
173
 
64
- export interface CFCacheStoreOptions<TEnv = unknown> {
65
- /**
66
- * Cache namespace. If not provided, uses caches.default (recommended).
67
- * Only set this if you need isolated cache storage.
68
- */
69
- namespace?: string;
70
-
71
- /**
72
- * Base URL for cache keys.
73
- *
74
- * If not provided, derives from request hostname via requestContext:
75
- * - Production domains → uses `https://{hostname}/`
76
- * - Dev/preview (localhost, workers.dev, pages.dev) → uses internal fallback URL
77
- */
78
- baseUrl?: string;
79
-
80
- /** Default cache options */
81
- defaults?: CacheDefaults;
82
-
83
- /**
84
- * Cloudflare ExecutionContext for non-blocking cache writes.
85
- * Pass the `ctx` from your worker's fetch handler.
86
- *
87
- * @example
88
- * ```typescript
89
- * new CFCacheStore({ ctx: env.ctx })
90
- * ```
91
- */
92
- ctx: ExecutionContext;
93
-
94
- /**
95
- * Cache version string override. When this changes, all cached entries are
96
- * effectively invalidated (new keys won't match old entries).
97
- *
98
- * Defaults to the auto-generated VERSION from `rsc-router:version` virtual module.
99
- * Only set this if you need a custom versioning strategy.
100
- */
101
- version?: string;
174
+ /**
175
+ * KV envelope for function cache entries ("use cache").
176
+ * @internal
177
+ */
178
+ interface KVItemEnvelope {
179
+ /** RSC-serialized return value */
180
+ v: string;
181
+ /** RSC-encoded handle data (see handle-snapshot.ts encodeHandles) */
182
+ h?: string;
183
+ /** When entry becomes stale (ms epoch) */
184
+ s: number;
185
+ /** When entry hard-expires (ms epoch) */
186
+ e: number;
187
+ /** Cache tags (for distributed tag invalidation) */
188
+ t?: string[];
189
+ /** Timestamp when tags were attached (ms epoch) */
190
+ ta?: number;
191
+ }
102
192
 
103
- /**
104
- * Custom key generator applied to all cache operations.
105
- * Receives the full RequestContext (including env) and the default-generated key.
106
- * Return value becomes the final cache key (unless route overrides with `key` option).
107
- *
108
- * @example Using headers for user segmentation
109
- * ```typescript
110
- * keyGenerator: (ctx, defaultKey) => {
111
- * const segment = ctx.request.headers.get('x-user-segment') || 'default';
112
- * return `${segment}:${defaultKey}`;
113
- * }
114
- * ```
115
- *
116
- * @example Using env bindings for multi-region
117
- * ```typescript
118
- * keyGenerator: (ctx, defaultKey) => {
119
- * const region = ctx.env.REGION || 'us';
120
- * return `${region}:${defaultKey}`;
121
- * }
122
- * ```
123
- *
124
- * @example Using cookies for locale-aware caching
125
- * ```typescript
126
- * keyGenerator: (ctx, defaultKey) => {
127
- * const locale = ctx.cookie('locale') || 'en';
128
- * return `${locale}:${defaultKey}`;
129
- * }
130
- * ```
131
- */
132
- keyGenerator?: (
133
- ctx: RequestContext<TEnv>,
134
- defaultKey: string,
135
- ) => string | Promise<string>;
193
+ /**
194
+ * KV envelope for PPR shell cache entries.
195
+ * @internal
196
+ */
197
+ interface KVShellEnvelope {
198
+ /** base64-encoded prelude bytes */
199
+ p: string;
200
+ /** postponed state JSON, or null (DATA variant — no holes) */
201
+ po: string | null;
202
+ /** React.version captured at prerender time */
203
+ rv: string;
204
+ /** createdAt (ms epoch) */
205
+ c: number;
206
+ /** When entry becomes stale (ms epoch) */
207
+ s: number;
208
+ /** When entry hard-expires (ms epoch) */
209
+ e: number;
210
+ /** Cache tags (for distributed tag invalidation) */
211
+ t?: string[];
212
+ /** Timestamp when tags were attached (ms epoch) */
213
+ ta?: number;
136
214
  }
137
215
 
138
216
  /**
139
- * Cache status values for the x-edge-cache-status header.
217
+ * KV envelope for document cache entries.
140
218
  * @internal
141
219
  */
142
- export type CacheStatus = "HIT" | "REVALIDATING";
220
+ interface KVResponseEnvelope {
221
+ /** Response body as base64-encoded string (safe for binary payloads) */
222
+ b: string;
223
+ /** HTTP status code */
224
+ st: number;
225
+ /** HTTP status text */
226
+ stx: string;
227
+ /** Serialized headers as key-value pairs (client-facing; no internal headers) */
228
+ hd: [string, string][];
229
+ /** When entry becomes stale (ms epoch) */
230
+ s: number;
231
+ /** When entry hard-expires (ms epoch) */
232
+ e: number;
233
+ /** Cache tags (for distributed tag invalidation) */
234
+ t?: string[];
235
+ /** Timestamp when tags were attached (ms epoch) */
236
+ ta?: number;
237
+ }
143
238
 
144
239
  // ============================================================================
145
240
  // CFCacheStore Implementation
@@ -153,9 +248,17 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
153
248
  ) => string | Promise<string>;
154
249
 
155
250
  private readonly namespace?: string;
156
- private readonly baseUrl: string;
251
+ private readonly explicitBaseUrl?: string;
157
252
  private readonly waitUntil?: (fn: () => Promise<void>) => void;
158
253
  private readonly version?: string;
254
+ private readonly edgeLookupTimeoutMs: number;
255
+ private readonly edgeReadTimeoutMs: number;
256
+ private readonly kvReadTimeoutMs: number;
257
+ private readonly debug?: (event: CFCacheReadDebugEvent) => void;
258
+ private readonly kv?: KVNamespace;
259
+ private readonly onRevalidateTag?: (tags: string[]) => Promise<void>;
260
+ private readonly tagInvalidationTtl?: number;
261
+ private readonly tagCacheTtl: number;
159
262
 
160
263
  constructor(options: CFCacheStoreOptions<TEnv>) {
161
264
  if (!options.ctx) {
@@ -167,45 +270,192 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
167
270
  }
168
271
 
169
272
  this.namespace = options.namespace;
170
- this.baseUrl = options.baseUrl ?? this.deriveBaseUrl();
273
+ // Base URL is resolved lazily per cache operation (see resolveBaseUrl).
274
+ // The store is constructed before the per-request context ALS is entered
275
+ // (the cache factory runs ahead of runWithRequestContext in the handler),
276
+ // so deriving the host here would always miss the request and fall back to
277
+ // the internal host. Only the explicit override can be captured eagerly.
278
+ this.explicitBaseUrl = options.baseUrl;
171
279
  this.defaults = options.defaults;
172
280
  this.version = options.version ?? VERSION;
281
+ // Coalesce only finite numbers to the override; a non-finite value (NaN from
282
+ // `Number(env.UNSET)`, or Infinity) would otherwise sail past `?? DEFAULT`
283
+ // (which only replaces null/undefined) into setTimeout, where NaN/Infinity
284
+ // are spec-coerced to ~1ms and silently turn the budget into a near-100%
285
+ // false-miss on that tier. A genuine finite 0 or negative still passes
286
+ // through and disables the budget per the documented `<= 0` contract.
287
+ const finiteBudget = (
288
+ value: number | undefined,
289
+ fallback: number,
290
+ ): number =>
291
+ typeof value === "number" && Number.isFinite(value) ? value : fallback;
292
+ this.edgeLookupTimeoutMs = finiteBudget(
293
+ options.edgeLookupTimeoutMs,
294
+ EDGE_LOOKUP_TIMEOUT_MS,
295
+ );
296
+ this.edgeReadTimeoutMs = finiteBudget(
297
+ options.edgeReadTimeoutMs,
298
+ EDGE_READ_TIMEOUT_MS,
299
+ );
300
+ this.kvReadTimeoutMs = finiteBudget(
301
+ options.kvReadTimeoutMs,
302
+ KV_READ_TIMEOUT_MS,
303
+ );
304
+ this.debug =
305
+ options.debug === true
306
+ ? (event) =>
307
+ console.log(`[CFCacheStore:debug] ${JSON.stringify(event)}`)
308
+ : typeof options.debug === "function"
309
+ ? options.debug
310
+ : undefined;
173
311
  this.keyGenerator = options.keyGenerator;
174
312
  this.waitUntil = (fn) => options.ctx.waitUntil(fn());
313
+ this.kv = options.kv;
314
+ this.onRevalidateTag = options.onRevalidateTag;
315
+ // tagInvalidationTtl feeds KV's expirationTtl, which CF rejects below
316
+ // KV_MIN_EXPIRATION_TTL (60s) -- a too-small finite value would make EVERY
317
+ // marker write throw and break ALL invalidation. Floor it (and warn once);
318
+ // a non-finite/non-positive value falls back to the no-expiry default
319
+ // (markers persist) rather than silently sailing a NaN into expirationTtl.
320
+ this.tagInvalidationTtl = this.sanitizeTagInvalidationTtl(
321
+ options.tagInvalidationTtl,
322
+ );
323
+ // tagCacheTtl gates the L1 marker cache via `> 0`. A non-finite value (NaN
324
+ // from `Number(env.UNSET)`) is not null/undefined, so `?? 0` would let it
325
+ // through and silently disable the cache while reading as "configured".
326
+ // finiteBudget coerces non-finite/null/undefined to 0; the `> 0` guard then
327
+ // collapses a finite non-positive value to the documented 0 = disabled.
328
+ const tagCacheTtl = finiteBudget(options.tagCacheTtl, 0);
329
+ this.tagCacheTtl = tagCacheTtl > 0 ? tagCacheTtl : 0;
330
+
331
+ // Read-side tag invalidation requires KV: isGloballyInvalidated() compares an
332
+ // entry's taggedAt against the per-tag KV marker and short-circuits to "not
333
+ // invalidated" when no KV namespace is configured. A consumer who wires the
334
+ // tag machinery (tagCacheTtl for L1 markers, or onRevalidateTag for CDN purge)
335
+ // but omits kv gets only the purge fired - marker writes are skipped without
336
+ // kv - yet every tagged read still serves stale data with no other signal.
337
+ // Surface that misconfiguration.
338
+ if (!this.kv && (this.tagCacheTtl > 0 || this.onRevalidateTag)) {
339
+ const id = this.namespace ?? "default";
340
+ if (!warnedNoKvReadInvalidation.has(id)) {
341
+ warnedNoKvReadInvalidation.add(id);
342
+ console.warn(
343
+ `[CFCacheStore] tagCacheTtl/onRevalidateTag is configured without a KV ` +
344
+ `namespace, so tag invalidation has NO read-side effect: tagged reads ` +
345
+ `are never treated as invalidated and serve stale data. Configure ` +
346
+ `{ kv } for distributed tag invalidation.`,
347
+ );
348
+ }
349
+ }
350
+ }
351
+
352
+ /**
353
+ * Validate a consumer-supplied tagInvalidationTtl against CF KV's expirationTtl
354
+ * floor. A finite value below KV_MIN_EXPIRATION_TTL is raised to it (with a
355
+ * one-time warning) so invalidation keeps working instead of every marker
356
+ * write throwing; a non-finite or non-positive value returns undefined (the
357
+ * no-expiry default). The warning still notes the sizing rule: the TTL must
358
+ * exceed the largest entry TTL+SWR or invalidated entries can resurrect.
359
+ * @internal
360
+ */
361
+ private sanitizeTagInvalidationTtl(
362
+ value: number | undefined,
363
+ ): number | undefined {
364
+ if (value == null) return undefined;
365
+ if (!Number.isFinite(value) || value <= 0) return undefined;
366
+ if (value < KV_MIN_EXPIRATION_TTL) {
367
+ const id = this.namespace ?? "default";
368
+ if (!warnedTagInvalidationTtlFloor.has(id)) {
369
+ warnedTagInvalidationTtlFloor.add(id);
370
+ console.warn(
371
+ `[CFCacheStore] tagInvalidationTtl ${value} is below Cloudflare KV's ` +
372
+ `${KV_MIN_EXPIRATION_TTL}s expirationTtl floor; raising to ` +
373
+ `${KV_MIN_EXPIRATION_TTL}. It must still exceed your largest entry ` +
374
+ `TTL+SWR or invalidated entries can resurrect when the marker expires.`,
375
+ );
376
+ }
377
+ return KV_MIN_EXPIRATION_TTL;
378
+ }
379
+ return value;
380
+ }
381
+
382
+ /**
383
+ * Emit a debug event if `debug` is enabled. Swallows sink errors so a faulty
384
+ * debug callback can never break a cache read.
385
+ * @internal
386
+ */
387
+ private emitDebug(event: CFCacheReadDebugEvent): void {
388
+ if (!this.debug) return;
389
+ try {
390
+ this.debug(event);
391
+ } catch {
392
+ // A broken debug sink must not affect the request.
393
+ }
394
+ }
395
+
396
+ /**
397
+ * Resolve the cache-key base URL for the current cache operation.
398
+ * Prefers an explicit `baseUrl` option; otherwise derives it from the live
399
+ * request. Called per operation (from keyToRequest), which runs inside the
400
+ * request-context ALS, so deriveBaseUrl sees the request and can use the
401
+ * production host instead of the internal fallback.
402
+ * @internal
403
+ */
404
+ private resolveBaseUrl(): string {
405
+ return this.explicitBaseUrl ?? this.deriveBaseUrl();
175
406
  }
176
407
 
177
408
  /**
178
409
  * Derive base URL from request hostname via requestContext.
179
- * Uses internal fallback for dev/preview environments.
410
+ * Uses internal fallback for dev/preview environments and untrusted hostnames.
411
+ * Must run inside the request context (invoked lazily via resolveBaseUrl).
180
412
  * @internal
181
413
  */
182
414
  private deriveBaseUrl(): string {
183
- const fallback = "https://rsc-cache.internal.com/";
415
+ const fallback = "https://rsc-dummy-host-1.com/";
184
416
 
185
- const ctx = getRequestContext();
417
+ const ctx = _getRequestContext();
186
418
  if (!ctx?.request) {
187
419
  return fallback;
188
420
  }
189
421
 
190
- try {
191
- const url = new URL(ctx.request.url);
192
- const hostname = url.hostname;
422
+ // The result is deterministic per request, but keyToRequest calls this on
423
+ // every cache operation; memoize per request context (see derivedBaseUrlMemo).
424
+ const memoized = derivedBaseUrlMemo.get(ctx);
425
+ if (memoized !== undefined) {
426
+ return memoized;
427
+ }
193
428
 
194
- // Use fallback for dev/preview environments
195
- if (
196
- hostname === "localhost" ||
197
- hostname === "127.0.0.1" ||
198
- hostname.endsWith(".workers.dev") ||
199
- hostname.endsWith(".pages.dev")
200
- ) {
429
+ const derived = ((): string => {
430
+ try {
431
+ const url = new URL(ctx.request.url);
432
+ const hostname = url.hostname;
433
+
434
+ // Use fallback for dev/preview environments
435
+ if (
436
+ hostname === "localhost" ||
437
+ hostname === "127.0.0.1" ||
438
+ hostname.endsWith(".workers.dev") ||
439
+ hostname.endsWith(".pages.dev")
440
+ ) {
441
+ return fallback;
442
+ }
443
+
444
+ // Validate hostname: must be a valid domain (alphanumeric, hyphens, dots)
445
+ // to prevent host header injection into cache keys
446
+ if (!/^[a-zA-Z0-9.-]+$/.test(hostname) || hostname.length > 253) {
447
+ return fallback;
448
+ }
449
+
450
+ // Use actual hostname for production
451
+ return `https://${hostname}/`;
452
+ } catch {
201
453
  return fallback;
202
454
  }
455
+ })();
203
456
 
204
- // Use actual hostname for production
205
- return `https://${hostname}/`;
206
- } catch {
207
- return fallback;
208
- }
457
+ derivedBaseUrlMemo.set(ctx, derived);
458
+ return derived;
209
459
  }
210
460
 
211
461
  /**
@@ -219,6 +469,297 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
219
469
  return caches.default;
220
470
  }
221
471
 
472
+ /**
473
+ * Race an async cache read against a latency budget. Shared by all three read
474
+ * tiers (L1 match, L1 body, L2/KV) so the timeout policy lives in one place:
475
+ * on timeout it returns `{ value: undefined, timedOut: true }` and logs
476
+ * `${label} exceeded ${budgetMs}ms; treating as miss`; the abandoned read is
477
+ * left to settle in the background (late rejection swallowed) rather than
478
+ * aborted, since the underlying CF primitives expose no cancellation. A budget
479
+ * <= 0 disables the bound and awaits the read directly. `read` is a thunk so
480
+ * the disabled path and the raced path start the read identically.
481
+ * @internal
482
+ */
483
+ private async readWithTimeout<T>(
484
+ read: () => Promise<T>,
485
+ budgetMs: number,
486
+ label: string,
487
+ ): Promise<{ value: T | undefined; timedOut: boolean }> {
488
+ if (budgetMs <= 0) return { value: await read(), timedOut: false };
489
+
490
+ let timer: ReturnType<typeof setTimeout> | undefined;
491
+ const timeout = new Promise<{ timedOut: true }>((resolve) => {
492
+ timer = setTimeout(() => resolve({ timedOut: true }), budgetMs);
493
+ });
494
+ try {
495
+ const readPromise = read();
496
+ // The losing branch keeps running; ensure a late rejection can't surface
497
+ // as an unhandled rejection once we've stopped awaiting it.
498
+ readPromise.catch(() => {});
499
+ const result = await Promise.race([
500
+ readPromise.then((value) => ({ timedOut: false as const, value })),
501
+ timeout,
502
+ ]);
503
+ if (result.timedOut) {
504
+ console.warn(
505
+ `[CFCacheStore] ${label} exceeded ${budgetMs}ms; treating as miss`,
506
+ );
507
+ return { value: undefined, timedOut: true };
508
+ }
509
+ return { value: result.value, timedOut: false };
510
+ } finally {
511
+ if (timer) clearTimeout(timer);
512
+ }
513
+ }
514
+
515
+ /**
516
+ * Read from the L1 edge cache under the edgeLookupTimeoutMs budget. A `match`
517
+ * slower than the budget is abandoned and reported as a miss
518
+ * (`{ response: undefined, timedOut: true }`) so a degraded colo cannot stall
519
+ * the request; callers fall through to their normal miss path (L2/KV or
520
+ * render). The `timedOut` flag lets callers distinguish an abandoned slow
521
+ * match from a genuine miss for debug reporting; `error` is set when the
522
+ * `match` itself rejected (a transient L1 infra error) so the caller can
523
+ * report it as cache-read while still degrading to L2/KV -- distinct from a
524
+ * genuine miss (no entry), which sets neither flag.
525
+ * @internal
526
+ */
527
+ private async matchWithTimeout(
528
+ cache: Cache,
529
+ request: Request,
530
+ ): Promise<{
531
+ response: Response | undefined;
532
+ timedOut: boolean;
533
+ error?: unknown;
534
+ }> {
535
+ let matchError: unknown;
536
+ const { value, timedOut } = await this.readWithTimeout(
537
+ // A fast match rejection is caught at the thunk and reported as a miss
538
+ // (response undefined), so the caller falls through to L2/KV rather than
539
+ // escaping to the outer catch -- symmetric with the body-read thunk. The
540
+ // error is captured (not swallowed) so the caller can surface it via
541
+ // onError as a cache-read degradation.
542
+ () =>
543
+ cache.match(request).catch((e) => {
544
+ matchError = e;
545
+ return undefined;
546
+ }),
547
+ this.edgeLookupTimeoutMs,
548
+ "edge cache lookup",
549
+ );
550
+ return { response: value, timedOut, error: matchError };
551
+ }
552
+
553
+ /**
554
+ * Read and JSON-parse a matched L1 Response's body under the edgeReadTimeoutMs
555
+ * budget. CF resolves `match()` with a lazily-streamed body, so the latency
556
+ * tail surfaces here -- after matchWithTimeout has already passed -- not in the
557
+ * match itself. On timeout `undefined` is returned so the caller falls through
558
+ * to L2/KV or render.
559
+ * @internal
560
+ */
561
+ private async readJsonWithTimeout<T>(
562
+ response: Response,
563
+ ): Promise<{ value: T | undefined; errored: boolean; error?: unknown }> {
564
+ // A FAST json() rejection (a corrupt body, or a foreign 200 non-JSON
565
+ // response that collided on this key) is caught at the thunk and turned into
566
+ // a miss, so the caller falls through to L2/KV exactly like a body-timeout
567
+ // -- instead of escaping to get()/getItem()'s outer catch, which returns
568
+ // null WITHOUT ever consulting KV. The catch lives here, not in
569
+ // readWithTimeout, so the L2/KV tier keeps propagating a genuine kv.get
570
+ // rejection to its own error sink. The `errored` flag lets the caller emit a
571
+ // distinct "body-error" debug outcome rather than masquerading as a timeout.
572
+ // On a TIMEOUT the json() promise is still pending, so the catch has not
573
+ // fired: errored stays false and the outcome is correctly a body-timeout. A
574
+ // late rejection after the timeout only mutates the closure flag, which the
575
+ // already-returned object no longer reads.
576
+ let errored = false;
577
+ let error: unknown;
578
+ const { value } = await this.readWithTimeout<T | undefined>(
579
+ () =>
580
+ (response.json() as Promise<T>).catch((e) => {
581
+ errored = true;
582
+ error = e;
583
+ return undefined;
584
+ }),
585
+ this.edgeReadTimeoutMs,
586
+ "edge cache body read",
587
+ );
588
+ return { value, errored, error };
589
+ }
590
+
591
+ /**
592
+ * Self-heal a corrupt L1 entry, then return the fall-through result. Reports
593
+ * the corruption as cache-corrupt (so an onError consumer sees it distinctly
594
+ * from a transient outage), runs the caller's L2/KV fall-through, and evicts
595
+ * the faulty per-colo entry ONLY when that fall-through found no good copy.
596
+ *
597
+ * The conditional evict is the load-bearing detail: when KV DOES serve a copy,
598
+ * kvGet* has already scheduled a same-key promote (`cache.put`); an eager
599
+ * `cache.delete` here would race that put with no CF Cache API ordering
600
+ * guarantee and could clobber the freshly-restored entry. So in that case we
601
+ * lean on #558's heal-by-overwrite (the non-suppressed fall-through promotes /
602
+ * a fresh render re-`set`s over the bad entry) and skip the delete. Only when
603
+ * this request's fall-through found no copy (=== null) is the eager evict
604
+ * scheduled -- useful then, since nothing else will overwrite the poison entry.
605
+ * A null fall-through can also be a KV-read TIMEOUT rather than a genuine miss:
606
+ * a concurrent request that read KV successfully may be promoting the same key,
607
+ * and this evict could race it. That is benign -- the worst case is one wasted
608
+ * colo-local promote, never a wrong served value, and the next read self-heals
609
+ * -- so we accept it rather than suppressing the evict on a timeout (which
610
+ * would strand the poison entry when KV really is empty). The evict is
611
+ * non-blocking (waitUntil) so it never adds latency to the degraded read.
612
+ * @internal
613
+ */
614
+ private async healCorruptL1<T>(
615
+ cache: Cache,
616
+ request: Request,
617
+ error: unknown,
618
+ label: string,
619
+ fallThrough: () => Promise<T | null>,
620
+ ): Promise<T | null> {
621
+ reportCacheError(
622
+ error ?? new Error("corrupt/partial L1 body"),
623
+ "cache-corrupt",
624
+ `[CFCacheStore] ${label}: corrupt L1 body`,
625
+ );
626
+ const result = await fallThrough();
627
+ if (result === null) {
628
+ const evict = (): Promise<void> =>
629
+ reportingAsync(
630
+ () => cache.delete(request),
631
+ "cache-delete",
632
+ `[CFCacheStore] ${label}: evict corrupt L1`,
633
+ );
634
+ if (this.waitUntil) this.waitUntil(evict);
635
+ else void evict();
636
+ }
637
+ return result;
638
+ }
639
+
640
+ /**
641
+ * Re-put a stale L1 entry marked REVALIDATING, so concurrent requests serve it
642
+ * without each triggering a revalidation. Shared by get()/getItem().
643
+ *
644
+ * The write is NON-BLOCKING (waitUntil) and best-effort by design:
645
+ * - It runs in waitUntil, so it never adds the put latency to the served stale
646
+ * read and a put failure can never turn that good read into a miss. The put
647
+ * is still initiated synchronously (this.waitUntil invokes its callback
648
+ * immediately), so concurrent readers see the marker land at the same time an
649
+ * awaited write would -- awaiting only blocks the current request.
650
+ * - The background revalidation's fresh set() is gated behind a full re-render,
651
+ * so it lands well after this put; a stale-clobbers-fresh race would require
652
+ * this single put to be slower than that entire render+set, and self-heals
653
+ * within MAX_REVALIDATION_INTERVAL.
654
+ *
655
+ * Cache-Control is recomputed to the REMAINING ttl from the stored hard-expiry
656
+ * deadline (see remainingCacheControl), not copied from the original
657
+ * full-window header -- copying it would restart CF retention on every re-arm
658
+ * and pin a perpetually-failing entry past hard-expiry. A legacy/tampered entry
659
+ * without a valid deadline floors to max-age=1 and self-heals via KV.
660
+ * @internal
661
+ */
662
+ private markRevalidating(
663
+ cache: Cache,
664
+ request: Request,
665
+ sourceHeaders: Headers,
666
+ status: number,
667
+ body: string,
668
+ ): void {
669
+ const reputNow = Date.now();
670
+ const headers = new Headers(sourceHeaders);
671
+ headers.set(CACHE_STATUS_HEADER, "REVALIDATING");
672
+ headers.set(CACHE_REVALIDATING_AT_HEADER, String(reputNow));
673
+ headers.set("Cache-Control", remainingCacheControl(headers, reputNow));
674
+ const markerResponse = new Response(body, { status, headers });
675
+ const write = async (): Promise<void> => {
676
+ try {
677
+ await cache.put(request, markerResponse);
678
+ } catch {
679
+ // Best-effort: a failed marker write must not affect the served read;
680
+ // the entry simply re-arms on the next stale read.
681
+ }
682
+ };
683
+ if (this.waitUntil) this.waitUntil(write);
684
+ else void write();
685
+ }
686
+
687
+ /**
688
+ * Document-tier counterpart of markRevalidating for getResponse's herd guard.
689
+ * The segment/item tiers JSON-parse the body, so they re-put with a string
690
+ * body; document bodies are streamed verbatim, so we re-put with a CLONED
691
+ * response body (`response.clone()`) supplied by the caller -- the original
692
+ * body still streams to the client while the marker carries the clone. Same
693
+ * REVALIDATING status header, same revalidating-at stamp, same
694
+ * remainingCacheControl re-put math as markRevalidating, so the document tier
695
+ * suppresses concurrent revalidation for the identical MAX_REVALIDATION_INTERVAL
696
+ * window the segment tier does. Best-effort and non-blocking: a failed marker
697
+ * write must not affect the served stale read.
698
+ * @internal
699
+ */
700
+ private markResponseRevalidating(
701
+ cache: Cache,
702
+ request: Request,
703
+ clonedResponse: Response,
704
+ ): void {
705
+ const reputNow = Date.now();
706
+ const headers = new Headers(clonedResponse.headers);
707
+ headers.set(CACHE_STATUS_HEADER, "REVALIDATING");
708
+ headers.set(CACHE_REVALIDATING_AT_HEADER, String(reputNow));
709
+ headers.set("Cache-Control", remainingCacheControl(headers, reputNow));
710
+ const markerResponse = new Response(clonedResponse.body, {
711
+ status: clonedResponse.status,
712
+ statusText: clonedResponse.statusText,
713
+ headers,
714
+ });
715
+ const write = async (): Promise<void> => {
716
+ try {
717
+ await cache.put(request, markerResponse);
718
+ } catch {
719
+ // Best-effort: see markRevalidating.
720
+ }
721
+ };
722
+ if (this.waitUntil) this.waitUntil(write);
723
+ else void write();
724
+ }
725
+
726
+ // ============================================================================
727
+ // Segment Cache Methods
728
+ // ============================================================================
729
+
730
+ /**
731
+ * Guard the segment tier against a `keyGenerator` that returns a key colliding
732
+ * with a reserved tag-marker namespace: `__tag__/` (the KV marker key) or
733
+ * `__tagmarker__/` (the L1 Cache API marker request). The item/doc tiers are
734
+ * internally prefixed (`fn:`/`doc:`) so only the bare segment key can collide;
735
+ * a collision would let a segment write clobber - or a segment read/delete
736
+ * evict - a live tag marker, silently breaking invalidation. Report loudly
737
+ * (so a misconfigured keyGenerator surfaces immediately) and treat the segment
738
+ * operation as a miss/no-op rather than corrupting the marker namespace.
739
+ * @internal
740
+ */
741
+ private isReservedSegmentKey(
742
+ key: string,
743
+ category: CacheErrorCategory,
744
+ ): boolean {
745
+ const reserved = key.startsWith(TAG_MARKER_PREFIX)
746
+ ? TAG_MARKER_PREFIX
747
+ : key.startsWith(TAG_MARKER_CACHE_PREFIX)
748
+ ? TAG_MARKER_CACHE_PREFIX
749
+ : null;
750
+ if (!reserved) return false;
751
+ reportCacheError(
752
+ new Error(
753
+ `segment key "${key}" collides with the reserved "${reserved}" ` +
754
+ `tag-marker namespace; the operation is ignored. Fix the store ` +
755
+ `keyGenerator so it does not produce keys with this prefix.`,
756
+ ),
757
+ category,
758
+ "[CFCacheStore] reserved key",
759
+ );
760
+ return true;
761
+ }
762
+
222
763
  /**
223
764
  * Get cached entry data by key.
224
765
  *
@@ -227,51 +768,223 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
227
768
  * - If already REVALIDATING (and recent), returns shouldRevalidate: false
228
769
  * - If fresh, returns shouldRevalidate: false
229
770
  *
230
- * The atomic mark prevents thundering herd - only first request triggers revalidation.
771
+ * On L1 miss, falls back to KV (L2) if configured.
772
+ * KV hits are promoted to L1 in the background.
231
773
  */
232
774
  async get(key: string): Promise<CacheGetResult | null> {
775
+ if (this.isReservedSegmentKey(key, "cache-read")) return null;
233
776
  try {
234
777
  const cache = await this.getCache();
235
778
  const request = this.keyToRequest(key);
236
- const response = await cache.match(request);
779
+ const matchStart = Date.now();
780
+ const {
781
+ response,
782
+ timedOut,
783
+ error: matchError,
784
+ } = await this.matchWithTimeout(cache, request);
785
+ const matchMs = Date.now() - matchStart;
237
786
 
238
787
  if (!response) {
788
+ // A transient L1 match error (matchError set) is reported as cache-read
789
+ // but, like a genuine miss or an abandoned slow match (timedOut), still
790
+ // degrades to L2/KV rather than failing the read.
791
+ if (matchError)
792
+ reportCacheError(
793
+ matchError,
794
+ "cache-read",
795
+ "[CFCacheStore] get L1 match",
796
+ );
797
+ if (this.debug)
798
+ this.emitDebug({
799
+ op: "get",
800
+ key,
801
+ // A match REJECTION (matchError) is distinct from a genuine absence:
802
+ // surface it as match-error so debug agrees with the cache-read
803
+ // already routed to onError, instead of masquerading as l1-miss.
804
+ outcome: matchError
805
+ ? "match-error"
806
+ : timedOut
807
+ ? "match-timeout"
808
+ : "l1-miss",
809
+ matchMs,
810
+ });
811
+ return this.kvGetSegment(key);
812
+ }
813
+
814
+ // A non-200 entry (a cached error response, or a foreign response that
815
+ // landed on this key) is not valid segment data; treat it as a miss
816
+ // rather than JSON-parsing garbage and serving it as a hit.
817
+ if (response.status !== 200) {
818
+ if (this.debug)
819
+ this.emitDebug({
820
+ op: "get",
821
+ key,
822
+ outcome: "non-200",
823
+ status: response.status,
824
+ matchMs,
825
+ });
826
+ // Degraded fall-through: suppress revalidation so a broken L1 entry hit
827
+ // concurrently serves KV-stale, not a herd. See kvGetSegment.
828
+ return this.kvGetSegment(key, { suppressRevalidate: true });
829
+ }
830
+
831
+ // Tag invalidation: an entry whose tags were invalidated after it was
832
+ // cached is treated as a miss, so the next render re-populates it. We
833
+ // return null (re-render locally) rather than falling through to KV. In
834
+ // the common case the L1 entry and its KV twin were written together with
835
+ // the same taggedAt, so kvGetSegment's own tag check would miss too and a
836
+ // fall-through is pure cost. The tiers CAN diverge -- another colo may have
837
+ // already re-rendered and written a fresher KV envelope -- in which case a
838
+ // fall-through could serve that copy instead of re-rendering here.
839
+ // Capturing that cross-colo optimization is a deferred follow-up, not a
840
+ // correctness gap: this colo's next read after its own re-render self-heals.
841
+ const tagInfo = this.readTagInfo(response.headers);
842
+ // Measure the marker-resolution tail (memo -> L1 marker cache -> KV) only
843
+ // when debug is on, so the hot path pays nothing. It is the serial read
844
+ // that sits between matchMs and bodyReadMs for a tagged entry.
845
+ const markerStart = this.debug ? Date.now() : 0;
846
+ const invalidated = await this.isGloballyInvalidated(
847
+ tagInfo.tags,
848
+ tagInfo.taggedAt,
849
+ );
850
+ const markerMs = this.debug ? Date.now() - markerStart : undefined;
851
+ if (invalidated) {
852
+ if (this.debug)
853
+ this.emitDebug({
854
+ op: "get",
855
+ key,
856
+ outcome: "tag-invalidated",
857
+ status: response.status,
858
+ matchMs,
859
+ markerMs,
860
+ });
239
861
  return null;
240
862
  }
241
863
 
242
864
  // Read status headers
243
865
  const status = response.headers.get(CACHE_STATUS_HEADER);
244
- const age = Number(response.headers.get("age") ?? "0");
245
866
  const staleAt = Number(
246
867
  response.headers.get(CACHE_STALE_AT_HEADER) ?? "0",
247
868
  );
869
+ const revalidatingAt = Number(
870
+ response.headers.get(CACHE_REVALIDATING_AT_HEADER) ?? "0",
871
+ );
248
872
 
249
- const isStale = staleAt > 0 && Date.now() > staleAt;
873
+ const now = Date.now();
874
+ const isStale = staleAt > 0 && now > staleAt;
875
+ // Recency comes from our explicit revalidating-at stamp, not CF's `Age`
876
+ // header (see CACHE_REVALIDATING_AT_HEADER). An absent/zero stamp counts
877
+ // as "not recent" so a dropped revalidation re-arms instead of pinning.
250
878
  const isRevalidating =
251
- status === "REVALIDATING" && age < MAX_REVALIDATION_INTERVAL;
879
+ status === "REVALIDATING" &&
880
+ revalidatingAt > 0 &&
881
+ now - revalidatingAt < MAX_REVALIDATION_INTERVAL * 1000;
882
+
883
+ // Single emitter for the post-header L1 outcomes. Undefined (so the event
884
+ // object is never allocated) when debug is off; the informational-only
885
+ // `age` header is read lazily inside for the same reason.
886
+ const debugRead = this.debug
887
+ ? (
888
+ outcome: CFCacheReadDebugEvent["outcome"],
889
+ bodyReadMs: number,
890
+ shouldRevalidate?: boolean,
891
+ ) =>
892
+ this.emitDebug({
893
+ op: "get",
894
+ key,
895
+ outcome,
896
+ status: response.status,
897
+ cacheStatus: status,
898
+ staleAt,
899
+ revalidatingAt,
900
+ ageHeader: response.headers.get("age"),
901
+ isStale,
902
+ isRevalidating,
903
+ shouldRevalidate,
904
+ matchMs,
905
+ markerMs,
906
+ bodyReadMs,
907
+ })
908
+ : undefined;
252
909
 
253
910
  // Case 1: Fresh or already being revalidated - just return data
254
911
  if (!isStale || isRevalidating) {
255
- const data = (await response.json()) as CachedEntryData;
912
+ const bodyStart = Date.now();
913
+ const {
914
+ value: data,
915
+ errored,
916
+ error,
917
+ } = await this.readJsonWithTimeout<CachedEntryData>(response);
918
+ const bodyReadMs = Date.now() - bodyStart;
919
+ if (data === undefined) {
920
+ debugRead?.(errored ? "body-error" : "body-timeout", bodyReadMs);
921
+ // A body-ERROR (corrupt/foreign body) self-heals via healCorruptL1:
922
+ // report cache-corrupt, fall through to L2/KV (which overwrites the
923
+ // bad entry), and evict only if KV had no good copy to promote. A
924
+ // body-TIMEOUT is a degraded read of a likely-valid entry: leave it
925
+ // intact and suppress revalidation so a stalling colo cannot herd.
926
+ if (errored)
927
+ return this.healCorruptL1(cache, request, error, "get", () =>
928
+ this.kvGetSegment(key, { suppressRevalidate: false }),
929
+ );
930
+ return this.kvGetSegment(key, { suppressRevalidate: true });
931
+ }
932
+ debugRead?.(
933
+ isRevalidating ? "l1-revalidating-guarded" : "l1-fresh",
934
+ bodyReadMs,
935
+ false,
936
+ );
256
937
  return { data, shouldRevalidate: false };
257
938
  }
258
939
 
259
- // Case 2: Stale and needs revalidation - atomically mark REVALIDATING
260
- const [b1, b2] = response.body!.tee();
261
-
262
- const headers = new Headers(response.headers);
263
- headers.set(CACHE_STATUS_HEADER, "REVALIDATING");
940
+ // Case 2: Stale and needs revalidation.
941
+ // Read the body under the edge-read budget BEFORE writing the REVALIDATING
942
+ // marker. CF can resolve match() fast but stall the body stream; the prior
943
+ // approach teed the stream and awaited cache.put(b1) first, which blocked
944
+ // on that same stalled stream so the read budget could never fire on a
945
+ // stale hit. Reading first bounds the stall and lets us skip marking an
946
+ // entry we could not even read.
947
+ const bodyStart = Date.now();
948
+ const {
949
+ value: data,
950
+ errored,
951
+ error,
952
+ } = await this.readJsonWithTimeout<CachedEntryData>(response);
953
+ const bodyReadMs = Date.now() - bodyStart;
954
+ if (data === undefined) {
955
+ debugRead?.(errored ? "body-error" : "body-timeout", bodyReadMs);
956
+ // Heal + conditionally evict a body-error, suppress a body-timeout; see
957
+ // Case 1.
958
+ if (errored)
959
+ return this.healCorruptL1(
960
+ cache,
961
+ request,
962
+ error,
963
+ "get(revalidating)",
964
+ () => this.kvGetSegment(key, { suppressRevalidate: false }),
965
+ );
966
+ return this.kvGetSegment(key, { suppressRevalidate: true });
967
+ }
264
968
 
265
- // Blocking write - must complete before returning to prevent race
266
- await cache.put(
969
+ // Mark REVALIDATING so concurrent requests don't all revalidate, then
970
+ // return the stale data. The marker write is non-blocking and best-effort
971
+ // (see markRevalidating) -- it must not add latency to, or fail, the served
972
+ // stale read.
973
+ this.markRevalidating(
974
+ cache,
267
975
  request,
268
- new Response(b1, { status: response.status, headers }),
976
+ response.headers,
977
+ response.status,
978
+ JSON.stringify(data),
269
979
  );
270
980
 
271
- const data = (await new Response(b2).json()) as CachedEntryData;
981
+ debugRead?.("l1-stale-revalidate", bodyReadMs, true);
272
982
  return { data, shouldRevalidate: true };
273
983
  } catch (error) {
274
- console.error("[CFCacheStore] get failed:", error);
984
+ // reportCacheError logs and routes to onError (cache-read); the debug
985
+ // emit is the separate wrangler-tail signal. Keep both observability paths.
986
+ reportCacheError(error, "cache-read", "[CFCacheStore] get");
987
+ if (this.debug) this.emitDebug({ op: "get", key, outcome: "error" });
275
988
  return null;
276
989
  }
277
990
  }
@@ -279,6 +992,7 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
279
992
  /**
280
993
  * Store entry data with TTL and optional SWR window.
281
994
  * Uses waitUntil for non-blocking write when available.
995
+ * When KV is configured, also persists to L2.
282
996
  */
283
997
  async set(
284
998
  key: string,
@@ -286,49 +1000,94 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
286
1000
  ttl: number,
287
1001
  swr?: number,
288
1002
  ): Promise<void> {
1003
+ if (this.isReservedSegmentKey(key, "cache-write")) return;
289
1004
  try {
290
1005
  const cache = await this.getCache();
291
1006
  const request = this.keyToRequest(key);
292
1007
 
293
1008
  // Extended TTL covers SWR window
294
- const swrWindow = swr ?? this.defaults?.swr ?? 0;
1009
+ const swrWindow = resolveSwrWindow(swr, this.defaults);
295
1010
  const totalTtl = ttl + swrWindow;
296
1011
  const staleAt = Date.now() + ttl * 1000;
297
1012
 
298
- const response = new Response(JSON.stringify(data), {
1013
+ // Stamp the tag timestamp at write time and carry it (with the tags)
1014
+ // into both the L1 body and the KV envelope so reads can run the
1015
+ // invalidation check.
1016
+ const taggedAt =
1017
+ Array.isArray(data.tags) && data.tags.length > 0
1018
+ ? Date.now()
1019
+ : undefined;
1020
+ const dataToStore: CachedEntryData = taggedAt
1021
+ ? { ...data, taggedAt }
1022
+ : data;
1023
+
1024
+ const body = JSON.stringify(dataToStore);
1025
+ const response = new Response(body, {
299
1026
  headers: {
300
1027
  "Content-Type": "application/json",
301
1028
  "Cache-Control": `public, max-age=${totalTtl}`,
302
1029
  [CACHE_STALE_AT_HEADER]: String(staleAt),
1030
+ // Absolute hard-expiry deadline so a stale-path re-put can recompute a
1031
+ // shrinking max-age instead of restarting retention (see
1032
+ // remainingCacheControl / CACHE_EXPIRES_AT_HEADER).
1033
+ [CACHE_EXPIRES_AT_HEADER]: String(staleAt + swrWindow * 1000),
303
1034
  [CACHE_STATUS_HEADER]: "HIT",
1035
+ ...this.tagHeaderEntries(dataToStore.tags, taggedAt),
304
1036
  },
305
1037
  });
306
1038
 
307
1039
  const putPromise = cache.put(request, response);
308
1040
 
309
1041
  if (this.waitUntil) {
310
- // Non-blocking write
311
- this.waitUntil(async () => {
312
- await putPromise;
313
- });
1042
+ // Non-blocking write. These store-level background tasks intentionally
1043
+ // omit the reportingAsync ctx argument: the store is a request-agnostic
1044
+ // singleton and this.waitUntil is the execution context's, not a single
1045
+ // request's, so a failure is reported console-loud only (it cannot be
1046
+ // attributed to one request's onError). The request-scoped tag verbs
1047
+ // (revalidateTag / stale-revalidation) DO thread their captured ctx.
1048
+ this.waitUntil(() =>
1049
+ reportingAsync(
1050
+ () => putPromise,
1051
+ "cache-write",
1052
+ "[CFCacheStore] L1 write",
1053
+ ),
1054
+ );
314
1055
  } else {
315
1056
  // Blocking fallback
316
1057
  await putPromise;
317
1058
  }
1059
+
1060
+ // L2: persist to KV
1061
+ this.kvSetSegment(key, dataToStore, staleAt, totalTtl, swrWindow);
318
1062
  } catch (error) {
319
- console.error("[CFCacheStore] set failed:", error);
1063
+ reportCacheError(error, "cache-write", "[CFCacheStore] set");
320
1064
  }
321
1065
  }
322
1066
 
323
1067
  /**
324
- * Delete a cached entry
1068
+ * Delete a cached entry from L1 and L2.
325
1069
  */
326
1070
  async delete(key: string): Promise<boolean> {
1071
+ if (this.isReservedSegmentKey(key, "cache-delete")) return false;
327
1072
  try {
328
1073
  const cache = await this.getCache();
329
- return await cache.delete(this.keyToRequest(key));
1074
+ const result = await cache.delete(this.keyToRequest(key));
1075
+
1076
+ // L2: delete from KV
1077
+ if (this.kv && this.waitUntil) {
1078
+ const kvKey = this.toKVKey(key);
1079
+ this.waitUntil(() =>
1080
+ reportingAsync(
1081
+ () => this.kv!.delete(kvKey),
1082
+ "cache-delete",
1083
+ "[CFCacheStore] delete L2",
1084
+ ),
1085
+ );
1086
+ }
1087
+
1088
+ return result;
330
1089
  } catch (error) {
331
- console.error("[CFCacheStore] delete failed:", error);
1090
+ reportCacheError(error, "cache-delete", "[CFCacheStore] delete");
332
1091
  return false;
333
1092
  }
334
1093
  }
@@ -340,6 +1099,7 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
340
1099
  /**
341
1100
  * Get a cached Response by key (for document-level caching).
342
1101
  * Returns the response and whether it should be revalidated (SWR).
1102
+ * Falls back to KV (L2) on L1 miss.
343
1103
  */
344
1104
  async getResponse(
345
1105
  key: string,
@@ -347,50 +1107,173 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
347
1107
  try {
348
1108
  const cache = await this.getCache();
349
1109
  const request = this.keyToRequest(`doc:${key}`);
350
- const response = await cache.match(request);
1110
+ // The document path is outside the debug surface (op is only get/getItem),
1111
+ // so the match-timeout flag is not surfaced as an event here -- though
1112
+ // matchWithTimeout still warns on a slow match. A miss or timeout falls
1113
+ // through to the KV document path and then render.
1114
+ const { response, error: matchError } = await this.matchWithTimeout(
1115
+ cache,
1116
+ request,
1117
+ );
351
1118
 
352
1119
  if (!response || response.status !== 200) {
1120
+ // A transient L1 match rejection (matchError set; only ever set when
1121
+ // response is undefined) is surfaced as cache-read before degrading to
1122
+ // L2/KV -- matching get()/getItem(). A genuine miss or a non-200 hit
1123
+ // carries no matchError and reports nothing.
1124
+ if (matchError)
1125
+ reportCacheError(
1126
+ matchError,
1127
+ "cache-read",
1128
+ "[CFCacheStore] getResponse L1 match",
1129
+ );
1130
+ return this.kvGetResponse(key);
1131
+ }
1132
+
1133
+ // Tag invalidation check (treat invalidated entry as a miss).
1134
+ const tagInfo = this.readTagInfo(response.headers);
1135
+ if (await this.isGloballyInvalidated(tagInfo.tags, tagInfo.taggedAt)) {
353
1136
  return null;
354
1137
  }
355
1138
 
356
1139
  // Check staleness
357
1140
  const staleAt = Number(response.headers.get(CACHE_STALE_AT_HEADER) || 0);
358
- const isStale = staleAt > 0 && Date.now() > staleAt;
1141
+ const now = Date.now();
1142
+ const isStale = staleAt > 0 && now > staleAt;
1143
+
1144
+ // Thundering-herd guard, mirroring the segment (get) and item (getItem)
1145
+ // tiers. Without it, every concurrent stale reader returned
1146
+ // shouldRevalidate=true and document-cache.ts scheduled a fresh render for
1147
+ // each one. Recency comes from our own revalidating-at stamp, not CF's Age
1148
+ // header (see CACHE_REVALIDATING_AT_HEADER); an absent/zero stamp counts as
1149
+ // "not recent" so a dropped revalidation re-arms instead of pinning.
1150
+ const status = response.headers.get(CACHE_STATUS_HEADER);
1151
+ const revalidatingAt = Number(
1152
+ response.headers.get(CACHE_REVALIDATING_AT_HEADER) ?? "0",
1153
+ );
1154
+ const isRevalidating =
1155
+ status === "REVALIDATING" &&
1156
+ revalidatingAt > 0 &&
1157
+ now - revalidatingAt < MAX_REVALIDATION_INTERVAL * 1000;
359
1158
 
1159
+ // L1 document bodies are streamed through verbatim - unlike the segment/
1160
+ // item tiers (which JSON-parse and so structurally detect corruption) and
1161
+ // the KV doc tier (validated in kvGetResponse, KV being the real partial-
1162
+ // read vector). Integrity here relies on the Cache API: cache.put stores a
1163
+ // response atomically or fails, so a truncated body is not served back. We
1164
+ // deliberately do NOT buffer+hash the body to re-verify it: that would
1165
+ // defeat streaming the document and add a full read to every cache hit.
1166
+
1167
+ if (isStale && !isRevalidating) {
1168
+ // First stale reader within the window: mark REVALIDATING (non-blocking,
1169
+ // best-effort) so concurrent readers below see the guard and suppress,
1170
+ // then return shouldRevalidate=true so this caller revalidates. Clone the
1171
+ // matched response for the marker since its original body must still
1172
+ // stream to the client.
1173
+ this.markResponseRevalidating(cache, request, response.clone());
1174
+ return {
1175
+ response: this.toClientResponse(response),
1176
+ shouldRevalidate: true,
1177
+ };
1178
+ }
1179
+
1180
+ // Fresh, or stale-but-already-REVALIDATING: serve without scheduling a
1181
+ // (re-)revalidation. A recent marker already has a render in flight.
360
1182
  return {
361
- response,
362
- shouldRevalidate: isStale,
1183
+ response: this.toClientResponse(response),
1184
+ shouldRevalidate: false,
363
1185
  };
364
1186
  } catch (error) {
365
- console.error("[CFCacheStore] getResponse failed:", error);
1187
+ reportCacheError(error, "cache-read", "[CFCacheStore] getResponse");
366
1188
  return null;
367
1189
  }
368
1190
  }
369
1191
 
1192
+ /**
1193
+ * Strip internal edge headers and restore the author's Cache-Control before a
1194
+ * cached document Response is served to a client. L1 entries carry the
1195
+ * internal staleness/status headers and a rewritten Cache-Control; none of
1196
+ * those should reach the browser or an upstream CDN.
1197
+ */
1198
+ private toClientResponse(response: Response): Response {
1199
+ const headers = new Headers(response.headers);
1200
+ const originalCacheControl = headers.get(CACHE_ORIG_CC_HEADER);
1201
+ if (originalCacheControl !== null) {
1202
+ headers.set("Cache-Control", originalCacheControl);
1203
+ } else {
1204
+ headers.delete("Cache-Control");
1205
+ }
1206
+ headers.delete(CACHE_ORIG_CC_HEADER);
1207
+ headers.delete(CACHE_STALE_AT_HEADER);
1208
+ headers.delete(CACHE_STATUS_HEADER);
1209
+ headers.delete(CACHE_TAGS_HEADER);
1210
+ headers.delete(CACHE_TAGGED_AT_HEADER);
1211
+ // Internal stale-path bookkeeping (hard-expiry deadline + REVALIDATING
1212
+ // stamp). Carried on doc L1 entries for the herd guard; never serve them.
1213
+ headers.delete(CACHE_EXPIRES_AT_HEADER);
1214
+ headers.delete(CACHE_REVALIDATING_AT_HEADER);
1215
+ // Finding #3 (read side): strip per-client signals a pre-fix or
1216
+ // pinned-version L1 entry may carry. See the read-side note in the design doc.
1217
+ stripPerClientSignals(headers);
1218
+ return new Response(response.body, {
1219
+ status: response.status,
1220
+ statusText: response.statusText,
1221
+ headers,
1222
+ });
1223
+ }
1224
+
370
1225
  /**
371
1226
  * Store a Response with TTL and optional SWR window (for document-level caching).
1227
+ * When KV is configured, also persists to L2.
372
1228
  */
373
1229
  async putResponse(
374
1230
  key: string,
375
1231
  response: Response,
376
1232
  ttl: number,
377
1233
  swr?: number,
1234
+ tags?: string[],
378
1235
  ): Promise<void> {
379
1236
  try {
380
1237
  const cache = await this.getCache();
381
1238
  const request = this.keyToRequest(`doc:${key}`);
382
1239
 
383
1240
  // Extended TTL covers SWR window
384
- const swrWindow = swr ?? this.defaults?.swr ?? 0;
1241
+ const swrWindow = resolveSwrWindow(swr, this.defaults);
385
1242
  const totalTtl = ttl + swrWindow;
386
1243
  const staleAt = Date.now() + ttl * 1000;
1244
+ const taggedAt =
1245
+ Array.isArray(tags) && tags.length > 0 ? Date.now() : undefined;
387
1246
 
388
- // Clone and add cache headers
1247
+ // Clone body for potential KV write before consuming it for L1
1248
+ const [l1Body, kvBody] = this.kv
1249
+ ? response.body
1250
+ ? response.body.tee()
1251
+ : [null, null]
1252
+ : [response.body, null];
1253
+
1254
+ // Clone and add cache headers. The author's Cache-Control is stashed and
1255
+ // replaced with a long max-age so the CF Cache API holds the entry across
1256
+ // the SWR window; getResponse restores the original before serving.
389
1257
  const headers = new Headers(response.headers);
1258
+ // Finding #3: never persist a per-client signal in the shared L1 entry
1259
+ // (the platform's Set-Cookie rejection is unverified and ignores the
1260
+ // directive anyway). See stripPerClientSignals.
1261
+ stripPerClientSignals(headers);
1262
+ const originalCacheControl = response.headers.get("Cache-Control");
1263
+ if (originalCacheControl !== null) {
1264
+ headers.set(CACHE_ORIG_CC_HEADER, originalCacheControl);
1265
+ }
390
1266
  headers.set("Cache-Control", `public, max-age=${totalTtl}`);
391
1267
  headers.set(CACHE_STALE_AT_HEADER, String(staleAt));
1268
+ // Absolute hard-expiry deadline so a stale-path REVALIDATING re-put can
1269
+ // recompute a shrinking max-age (remainingCacheControl) instead of
1270
+ // restarting retention. Mirrors set()/setItem(). Stripped by
1271
+ // toClientResponse before serving.
1272
+ headers.set(CACHE_EXPIRES_AT_HEADER, String(staleAt + swrWindow * 1000));
1273
+ // Internal tag headers (stripped by toClientResponse before serving).
1274
+ this.setTagHeaders(headers, tags, taggedAt);
392
1275
 
393
- const toCache = new Response(response.body, {
1276
+ const toCache = new Response(l1Body, {
394
1277
  status: response.status,
395
1278
  statusText: response.statusText,
396
1279
  headers,
@@ -400,29 +1283,1488 @@ export class CFCacheStore<TEnv = unknown> implements SegmentCacheStore<TEnv> {
400
1283
 
401
1284
  if (this.waitUntil) {
402
1285
  // Non-blocking write
403
- this.waitUntil(async () => {
404
- await putPromise;
405
- });
1286
+ this.waitUntil(() =>
1287
+ reportingAsync(
1288
+ () => putPromise,
1289
+ "cache-write",
1290
+ "[CFCacheStore] L1 write",
1291
+ ),
1292
+ );
406
1293
  } else {
407
1294
  // Blocking fallback
408
1295
  await putPromise;
409
1296
  }
1297
+
1298
+ // L2: persist to KV (KV requires expirationTtl >= 60s)
1299
+ if (this.kv && this.waitUntil && totalTtl >= 60) {
1300
+ const kvKey = this.toDocKVKey(key);
1301
+ // Finding #3: never persist a per-client signal in the KV envelope.
1302
+ const headersArray: [string, string][] = [];
1303
+ response.headers.forEach((v, k) => {
1304
+ if (isPerClientSignalHeader(k)) return;
1305
+ headersArray.push([k, v]);
1306
+ });
1307
+ // Read body as ArrayBuffer and encode to base64 to preserve binary payloads
1308
+ const bodyBuf = kvBody
1309
+ ? await new Response(kvBody).arrayBuffer()
1310
+ : new ArrayBuffer(0);
1311
+ const bodyBase64 = bufferToBase64(bodyBuf);
1312
+
1313
+ this.waitUntil(() =>
1314
+ reportingAsync(
1315
+ () => {
1316
+ const envelope: KVResponseEnvelope = {
1317
+ b: bodyBase64,
1318
+ st: response.status,
1319
+ stx: response.statusText,
1320
+ hd: headersArray,
1321
+ s: staleAt,
1322
+ e: staleAt + swrWindow * 1000,
1323
+ t: tags,
1324
+ ta: taggedAt,
1325
+ };
1326
+ return this.kv!.put(kvKey, JSON.stringify(envelope), {
1327
+ expirationTtl: totalTtl,
1328
+ });
1329
+ },
1330
+ "cache-write",
1331
+ "[CFCacheStore] kvPutResponse",
1332
+ ),
1333
+ );
1334
+ }
410
1335
  } catch (error) {
411
- console.error("[CFCacheStore] putResponse failed:", error);
1336
+ reportCacheError(error, "cache-write", "[CFCacheStore] putResponse");
412
1337
  }
413
1338
  }
414
1339
 
1340
+ // ============================================================================
1341
+ // Function Cache Methods (for "use cache" directive)
1342
+ // ============================================================================
1343
+
415
1344
  /**
416
- * Convert string key to Request object for CF Cache API.
417
- * Includes version in URL if specified (for cache invalidation on code changes).
418
- * @internal
1345
+ * Get a cached function result by key.
1346
+ * Follows the same SWR pattern as get() for segment caching.
1347
+ * Falls back to KV (L2) on L1 miss.
419
1348
  */
420
- private keyToRequest(key: string): Request {
421
- const encodedKey = encodeURIComponent(key);
422
- // Include version in URL path to invalidate cache when version changes
423
- const versionPath = this.version ? `v/${this.version}/` : "";
424
- return new Request(`${this.baseUrl}${versionPath}${encodedKey}`, {
425
- method: "GET",
426
- });
1349
+ async getItem(key: string): Promise<CacheItemResult | null> {
1350
+ try {
1351
+ const cache = await this.getCache();
1352
+ const request = this.keyToRequest(`fn:${key}`);
1353
+ const matchStart = Date.now();
1354
+ const {
1355
+ response,
1356
+ timedOut,
1357
+ error: matchError,
1358
+ } = await this.matchWithTimeout(cache, request);
1359
+ const matchMs = Date.now() - matchStart;
1360
+
1361
+ if (!response) {
1362
+ // Transient match error reported cache-read; still degrades to L2/KV.
1363
+ if (matchError)
1364
+ reportCacheError(
1365
+ matchError,
1366
+ "cache-read",
1367
+ "[CFCacheStore] getItem L1 match",
1368
+ );
1369
+ if (this.debug)
1370
+ this.emitDebug({
1371
+ op: "getItem",
1372
+ key,
1373
+ // match-error (rejection) vs l1-miss (absence); see get().
1374
+ outcome: matchError
1375
+ ? "match-error"
1376
+ : timedOut
1377
+ ? "match-timeout"
1378
+ : "l1-miss",
1379
+ matchMs,
1380
+ });
1381
+ return this.kvGetItem(key);
1382
+ }
1383
+
1384
+ // Non-200 entry is not a valid cached function result; treat as a miss.
1385
+ if (response.status !== 200) {
1386
+ if (this.debug)
1387
+ this.emitDebug({
1388
+ op: "getItem",
1389
+ key,
1390
+ outcome: "non-200",
1391
+ status: response.status,
1392
+ matchMs,
1393
+ });
1394
+ // Degraded fall-through: suppress revalidation so a broken L1 entry hit
1395
+ // concurrently serves KV-stale instead of spawning a herd (see get()).
1396
+ return this.kvGetItem(key, { suppressRevalidate: true });
1397
+ }
1398
+
1399
+ // Tag invalidation check (treat invalidated entry as a miss). Measure the
1400
+ // marker-resolution tail only under debug (see get()).
1401
+ const tagInfo = this.readTagInfo(response.headers);
1402
+ const markerStart = this.debug ? Date.now() : 0;
1403
+ const invalidated = await this.isGloballyInvalidated(
1404
+ tagInfo.tags,
1405
+ tagInfo.taggedAt,
1406
+ );
1407
+ const markerMs = this.debug ? Date.now() - markerStart : undefined;
1408
+ if (invalidated) {
1409
+ if (this.debug)
1410
+ this.emitDebug({
1411
+ op: "getItem",
1412
+ key,
1413
+ outcome: "tag-invalidated",
1414
+ status: response.status,
1415
+ matchMs,
1416
+ markerMs,
1417
+ });
1418
+ return null;
1419
+ }
1420
+
1421
+ const staleAt = Number(
1422
+ response.headers.get(CACHE_STALE_AT_HEADER) ?? "0",
1423
+ );
1424
+ const status = response.headers.get(CACHE_STATUS_HEADER);
1425
+ const revalidatingAt = Number(
1426
+ response.headers.get(CACHE_REVALIDATING_AT_HEADER) ?? "0",
1427
+ );
1428
+
1429
+ const now = Date.now();
1430
+ const isStale = staleAt > 0 && now > staleAt;
1431
+ // Recency from our explicit stamp, not CF's `Age` header (see get()).
1432
+ const isRevalidating =
1433
+ status === "REVALIDATING" &&
1434
+ revalidatingAt > 0 &&
1435
+ now - revalidatingAt < MAX_REVALIDATION_INTERVAL * 1000;
1436
+
1437
+ // Single emitter for the post-header L1 outcomes (see get()). Undefined
1438
+ // when debug is off, so the event object is never allocated on the hot
1439
+ // path; the informational-only `age` header is read lazily inside.
1440
+ const debugRead = this.debug
1441
+ ? (
1442
+ outcome: CFCacheReadDebugEvent["outcome"],
1443
+ bodyReadMs: number,
1444
+ shouldRevalidate?: boolean,
1445
+ ) =>
1446
+ this.emitDebug({
1447
+ op: "getItem",
1448
+ key,
1449
+ outcome,
1450
+ status: response.status,
1451
+ cacheStatus: status,
1452
+ staleAt,
1453
+ revalidatingAt,
1454
+ ageHeader: response.headers.get("age"),
1455
+ isStale,
1456
+ isRevalidating,
1457
+ shouldRevalidate,
1458
+ matchMs,
1459
+ markerMs,
1460
+ bodyReadMs,
1461
+ })
1462
+ : undefined;
1463
+
1464
+ const bodyStart = Date.now();
1465
+ const {
1466
+ value: data,
1467
+ errored,
1468
+ error,
1469
+ } = await this.readJsonWithTimeout<{
1470
+ value: string;
1471
+ handles?: string;
1472
+ }>(response);
1473
+ const bodyReadMs = Date.now() - bodyStart;
1474
+ if (data === undefined) {
1475
+ debugRead?.(errored ? "body-error" : "body-timeout", bodyReadMs);
1476
+ // Heal + conditionally evict a body-error, suppress a body-timeout; see
1477
+ // get().
1478
+ if (errored)
1479
+ return this.healCorruptL1(cache, request, error, "getItem", () =>
1480
+ this.kvGetItem(key, { suppressRevalidate: false }),
1481
+ );
1482
+ return this.kvGetItem(key, { suppressRevalidate: true });
1483
+ }
1484
+
1485
+ if (!isStale || isRevalidating) {
1486
+ debugRead?.(
1487
+ isRevalidating ? "l1-revalidating-guarded" : "l1-fresh",
1488
+ bodyReadMs,
1489
+ false,
1490
+ );
1491
+ return {
1492
+ value: data.value,
1493
+ handles: data.handles,
1494
+ shouldRevalidate: false,
1495
+ tags: tagInfo.tags,
1496
+ };
1497
+ }
1498
+
1499
+ // Stale and needs revalidation -- mark REVALIDATING (non-blocking,
1500
+ // best-effort, remaining-ttl) and return the stale value. See get() /
1501
+ // markRevalidating for the full rationale.
1502
+ this.markRevalidating(
1503
+ cache,
1504
+ request,
1505
+ response.headers,
1506
+ 200,
1507
+ JSON.stringify(data),
1508
+ );
1509
+
1510
+ debugRead?.("l1-stale-revalidate", bodyReadMs, true);
1511
+ return {
1512
+ value: data.value,
1513
+ handles: data.handles,
1514
+ shouldRevalidate: true,
1515
+ tags: tagInfo.tags,
1516
+ };
1517
+ } catch (error) {
1518
+ reportCacheError(error, "cache-read", "[CFCacheStore] getItem");
1519
+ if (this.debug) this.emitDebug({ op: "getItem", key, outcome: "error" });
1520
+ return null;
1521
+ }
1522
+ }
1523
+
1524
+ /**
1525
+ * Store a function result with TTL and optional SWR window.
1526
+ * When KV is configured, also persists to L2.
1527
+ */
1528
+ async setItem(
1529
+ key: string,
1530
+ value: string,
1531
+ options?: CacheItemOptions,
1532
+ ): Promise<void> {
1533
+ try {
1534
+ const cache = await this.getCache();
1535
+ const request = this.keyToRequest(`fn:${key}`);
1536
+
1537
+ const ttl = resolveTtl(options?.ttl, this.defaults, DEFAULT_FUNCTION_TTL);
1538
+ const swrWindow = resolveSwrWindow(options?.swr, this.defaults);
1539
+ const totalTtl = ttl + swrWindow;
1540
+ const staleAt = Date.now() + ttl * 1000;
1541
+
1542
+ const tags = options?.tags;
1543
+ const taggedAt =
1544
+ Array.isArray(tags) && tags.length > 0 ? Date.now() : undefined;
1545
+
1546
+ const body = JSON.stringify({ value, handles: options?.handles });
1547
+ const response = new Response(body, {
1548
+ headers: {
1549
+ "Content-Type": "application/json",
1550
+ "Cache-Control": `public, max-age=${totalTtl}`,
1551
+ [CACHE_STALE_AT_HEADER]: String(staleAt),
1552
+ // Absolute hard-expiry deadline; see set() / remainingCacheControl.
1553
+ [CACHE_EXPIRES_AT_HEADER]: String(staleAt + swrWindow * 1000),
1554
+ [CACHE_STATUS_HEADER]: "HIT",
1555
+ ...this.tagHeaderEntries(tags, taggedAt),
1556
+ },
1557
+ });
1558
+
1559
+ const putPromise = cache.put(request, response);
1560
+
1561
+ if (this.waitUntil) {
1562
+ this.waitUntil(() =>
1563
+ reportingAsync(
1564
+ () => putPromise,
1565
+ "cache-write",
1566
+ "[CFCacheStore] L1 write",
1567
+ ),
1568
+ );
1569
+ } else {
1570
+ await putPromise;
1571
+ }
1572
+
1573
+ // L2: persist to KV (KV requires expirationTtl >= 60s)
1574
+ if (this.kv && this.waitUntil && totalTtl >= 60) {
1575
+ const kvKey = this.toKVKey(`fn:${key}`);
1576
+ this.waitUntil(() =>
1577
+ reportingAsync(
1578
+ () => {
1579
+ const envelope: KVItemEnvelope = {
1580
+ v: value,
1581
+ h: options?.handles,
1582
+ s: staleAt,
1583
+ e: staleAt + swrWindow * 1000,
1584
+ t: tags,
1585
+ ta: taggedAt,
1586
+ };
1587
+ return this.kv!.put(kvKey, JSON.stringify(envelope), {
1588
+ expirationTtl: totalTtl,
1589
+ });
1590
+ },
1591
+ "cache-write",
1592
+ "[CFCacheStore] kvSetItem",
1593
+ ),
1594
+ );
1595
+ }
1596
+ } catch (error) {
1597
+ reportCacheError(error, "cache-write", "[CFCacheStore] setItem");
1598
+ }
1599
+ }
1600
+
1601
+ // ============================================================================
1602
+ // Shell Cache Methods (PPR shell resume) — KV-only in v1
1603
+ // ============================================================================
1604
+ //
1605
+ // Unlike the segment/item/document tiers, the shell family has NO Cache-API L1
1606
+ // tier: the prelude bytes + postponed blob are large and version-coupled, and a
1607
+ // per-colo L1 for them is a deliberate follow-up (see the PPR shell-resume
1608
+ // design doc). Shell entries live only in KV (the global tier), so the family
1609
+ // requires a configured KV namespace; without one, getShell/putShell no-op and
1610
+ // the shell-cache middleware fails open to a full HTML render. Tag invalidation
1611
+ // still applies: shell entries carry tags/taggedAt and are checked against the
1612
+ // same KV markers isGloballyInvalidated() reads for every other tier.
1613
+
1614
+ /**
1615
+ * Get a cached PPR shell entry by key from KV (no L1). Applies the KV read
1616
+ * budget, corrupt-entry eviction, hard-expiry, and tag invalidation exactly
1617
+ * like kvGetItem, minus the L1 promote. SWR is a plain staleness flag — KV has
1618
+ * no REVALIDATING herd guard, so the shell-cache middleware's module-level
1619
+ * in-flight set is the recapture stampede guard.
1620
+ */
1621
+ async getShell(
1622
+ key: string,
1623
+ ): Promise<{ entry: ShellCacheEntry; shouldRevalidate?: boolean } | null> {
1624
+ if (!this.kv) return null;
1625
+ try {
1626
+ const kvKey = this.toKVKey(`shell:${key}`);
1627
+ const { value: envelope, timedOut } =
1628
+ await this.kvGetOrEvict<KVShellEnvelope>(
1629
+ kvKey,
1630
+ (e) =>
1631
+ typeof e.p === "string" &&
1632
+ (e.po === null || typeof e.po === "string") &&
1633
+ typeof e.rv === "string" &&
1634
+ typeof e.e === "number" &&
1635
+ typeof e.s === "number",
1636
+ "getShell",
1637
+ );
1638
+ // A timeout, a missing key, or an already-evicted corrupt entry is a miss.
1639
+ if (timedOut || !envelope) return null;
1640
+
1641
+ const now = Date.now();
1642
+ if (now > envelope.e) return null;
1643
+
1644
+ if (await this.isGloballyInvalidated(envelope.t, envelope.ta)) {
1645
+ return null;
1646
+ }
1647
+
1648
+ const shouldRevalidate = envelope.s > 0 && now > envelope.s;
1649
+ return {
1650
+ entry: {
1651
+ prelude: envelope.p,
1652
+ postponed: envelope.po,
1653
+ reactVersion: envelope.rv,
1654
+ createdAt: envelope.c,
1655
+ },
1656
+ shouldRevalidate,
1657
+ };
1658
+ } catch (error) {
1659
+ reportCacheError(error, "cache-read", "[CFCacheStore] getShell");
1660
+ return null;
1661
+ }
1662
+ }
1663
+
1664
+ /**
1665
+ * Store a PPR shell entry in KV with TTL and optional SWR window. Non-blocking
1666
+ * (waitUntil) like the other KV writes. The tags/taggedAt ride in the envelope
1667
+ * so isGloballyInvalidated() can invalidate the shell via the shared KV markers.
1668
+ */
1669
+ async putShell(
1670
+ key: string,
1671
+ entry: ShellCacheEntry,
1672
+ ttlSeconds?: number,
1673
+ swrSeconds?: number,
1674
+ tags?: string[],
1675
+ ): Promise<void> {
1676
+ // KV-only tier: needs a KV namespace and waitUntil (writes are non-blocking).
1677
+ if (!this.kv || !this.waitUntil) return;
1678
+ try {
1679
+ const ttl = resolveTtl(ttlSeconds, this.defaults, DEFAULT_FUNCTION_TTL);
1680
+ const swrWindow = resolveSwrWindow(swrSeconds, this.defaults);
1681
+ const totalTtl = ttl + swrWindow;
1682
+ // KV requires expirationTtl >= 60s; skip a shorter-lived shell rather than
1683
+ // letting kv.put reject inside waitUntil (mirrors setItem/kvSetSegment).
1684
+ if (totalTtl < 60) return;
1685
+
1686
+ const staleAt = Date.now() + ttl * 1000;
1687
+ const taggedAt =
1688
+ Array.isArray(tags) && tags.length > 0 ? Date.now() : undefined;
1689
+
1690
+ const kvKey = this.toKVKey(`shell:${key}`);
1691
+ // A key over the KV limit makes kv.put reject deep inside waitUntil; report
1692
+ // and skip the doomed write (mirrors kvSetSegment).
1693
+ const kvKeyBytes = kvKeyByteLength(kvKey);
1694
+ if (kvKeyBytes > KV_MAX_KEY_BYTES) {
1695
+ reportCacheError(
1696
+ new Error(
1697
+ `shell cache key produces a ${kvKeyBytes}-byte KV key, over the ` +
1698
+ `${KV_MAX_KEY_BYTES}-byte limit; the shell was not persisted.`,
1699
+ ),
1700
+ "cache-write",
1701
+ "[CFCacheStore] putShell",
1702
+ );
1703
+ return;
1704
+ }
1705
+
1706
+ this.waitUntil(() =>
1707
+ reportingAsync(
1708
+ () => {
1709
+ const envelope: KVShellEnvelope = {
1710
+ p: entry.prelude,
1711
+ po: entry.postponed,
1712
+ rv: entry.reactVersion,
1713
+ c: entry.createdAt,
1714
+ s: staleAt,
1715
+ e: staleAt + swrWindow * 1000,
1716
+ t: tags,
1717
+ ta: taggedAt,
1718
+ };
1719
+ return this.kv!.put(kvKey, JSON.stringify(envelope), {
1720
+ expirationTtl: totalTtl,
1721
+ });
1722
+ },
1723
+ "cache-write",
1724
+ "[CFCacheStore] putShell",
1725
+ ),
1726
+ );
1727
+ } catch (error) {
1728
+ reportCacheError(error, "cache-write", "[CFCacheStore] putShell");
1729
+ }
1730
+ }
1731
+
1732
+ // ============================================================================
1733
+ // Key Helpers
1734
+ // ============================================================================
1735
+
1736
+ /**
1737
+ * Convert string key to Request object for CF Cache API.
1738
+ * Includes version in URL if specified (for cache invalidation on code changes).
1739
+ * @internal
1740
+ */
1741
+ private keyToRequest(key: string): Request {
1742
+ const encodedKey = encodeURIComponent(key);
1743
+ // Include version in URL path to invalidate cache when version changes
1744
+ const versionPath = this.version ? `v/${this.version}/` : "";
1745
+ return new Request(`${this.resolveBaseUrl()}${versionPath}${encodedKey}`, {
1746
+ method: "GET",
1747
+ });
1748
+ }
1749
+
1750
+ /**
1751
+ * Convert string key to KV key string.
1752
+ * Uses same version prefix as Cache API for consistent invalidation.
1753
+ * @internal
1754
+ */
1755
+ private toKVKey(key: string): string {
1756
+ const versionPath = this.version ? `v/${this.version}/` : "";
1757
+ return `${versionPath}${key}`;
1758
+ }
1759
+
1760
+ /**
1761
+ * Host token for the current request, used to namespace the document KV key.
1762
+ * Derived from the same resolveBaseUrl() that namespaces the L1 (Cache API)
1763
+ * tier, so a doc entry's KV twin lands under the identical host bucket.
1764
+ * Falls back to "_" if the base URL cannot be parsed (it always carries a
1765
+ * trailing-slash origin, so parsing succeeds in practice).
1766
+ * @internal
1767
+ */
1768
+ private docKVHost(): string {
1769
+ try {
1770
+ return new URL(this.resolveBaseUrl()).host || "_";
1771
+ } catch {
1772
+ return "_";
1773
+ }
1774
+ }
1775
+
1776
+ /**
1777
+ * Convert a document key to its host-namespaced KV key. The L1 tier already
1778
+ * namespaces document entries by host via keyToRequest/resolveBaseUrl, but the
1779
+ * KV fallback keyed only on `doc:{key}`, so two hosts serving the same path
1780
+ * could collide on the KV tier (one host serving another's cached document).
1781
+ * Prefixing the host closes that cross-host collision. Deterministic per
1782
+ * (host, key). Segment/fn/tag-marker KV keys keep toKVKey unchanged: tag
1783
+ * markers are intentionally global (invalidation must cross hosts), and the
1784
+ * document tier is the one with a request-host context here.
1785
+ * @internal
1786
+ */
1787
+ private toDocKVKey(key: string): string {
1788
+ return this.toKVKey(`h/${this.docKVHost()}/doc:${key}`);
1789
+ }
1790
+
1791
+ /**
1792
+ * Best-effort delete of a single KV key, reporting (not swallowing) a delete
1793
+ * failure as cache-delete. Used by the corrupt-entry self-heal paths.
1794
+ * @internal
1795
+ */
1796
+ private async evictKvKey(kvKey: string, label: string): Promise<void> {
1797
+ try {
1798
+ await this.kv!.delete(kvKey);
1799
+ } catch (error) {
1800
+ reportCacheError(
1801
+ error,
1802
+ "cache-delete",
1803
+ `[CFCacheStore] ${label}: evict failed`,
1804
+ );
1805
+ }
1806
+ }
1807
+
1808
+ /**
1809
+ * Schedule a corrupt-entry KV eviction as a NON-BLOCKING background task
1810
+ * (waitUntil) instead of awaiting it on the request path. The corrupt read has
1811
+ * already resolved to a miss; awaiting an unbounded kv.delete here would re-add
1812
+ * exactly the multi-second stall the read budgets exist to prevent when the KV
1813
+ * namespace is degraded. evictKvKey never rejects (it reports its own failure),
1814
+ * so the fire-and-forget fallback is safe when no waitUntil is available.
1815
+ * @internal
1816
+ */
1817
+ private scheduleKvEvict(kvKey: string, label: string): void {
1818
+ const evict = (): Promise<void> => this.evictKvKey(kvKey, label);
1819
+ if (this.waitUntil) this.waitUntil(evict);
1820
+ else void evict();
1821
+ }
1822
+
1823
+ /**
1824
+ * KV-get a JSON envelope, EVICTING the key only when it is genuinely corrupt.
1825
+ *
1826
+ * Reads as { type: "text" }, NOT { type: "json" }, on purpose: the "json" form
1827
+ * fuses the network read and the JSON parse, so a transient KV outage (5xx/429/
1828
+ * network blip) is indistinguishable from a malformed body and would delete a
1829
+ * still-good cross-colo entry - a self-inflicted miss storm. Reading text lets a
1830
+ * transient read error propagate to the caller's outer catch (reported
1831
+ * cache-read, the entry left intact); only a JSON.parse failure on a body that
1832
+ * WAS successfully read - or an envelope that parses but fails `validate`
1833
+ * (fields missing from a truncated write) - is true corruption that evicts +
1834
+ * reports cache-corrupt. A MISSING key (kv.get -> null) is a normal miss.
1835
+ * @internal
1836
+ */
1837
+ private async kvGetOrEvict<T>(
1838
+ kvKey: string,
1839
+ validate: (envelope: T) => boolean,
1840
+ label: string,
1841
+ ): Promise<{ value: T | null; timedOut: boolean }> {
1842
+ // Bound the read with the KV latency budget (inherited from #558) so a
1843
+ // degraded namespace cannot pin the request. readWithTimeout reports
1844
+ // timedOut on budget expiry; a transient read REJECTION (5xx/429/network)
1845
+ // instead propagates out to the caller's outer catch (reported cache-read,
1846
+ // the entry left intact) -- deliberately NOT caught as corruption.
1847
+ const { value: raw, timedOut } = await this.readWithTimeout<unknown>(
1848
+ () => this.kv!.get(kvKey, { type: "text" }),
1849
+ this.kvReadTimeoutMs,
1850
+ "KV read",
1851
+ );
1852
+ if (timedOut) return { value: null, timedOut: true };
1853
+ if (raw == null) return { value: null, timedOut: false }; // missing = miss
1854
+
1855
+ // Real CF KV with { type: "text" } returns a string: parse + structurally
1856
+ // validate it; a parse/validate failure on a successfully-read body is the
1857
+ // only true corruption (evict + cache-corrupt). A KV binding that already
1858
+ // returns a parsed object (some shims/tests) is used as-is.
1859
+ let envelope: T;
1860
+ if (typeof raw === "string") {
1861
+ try {
1862
+ envelope = JSON.parse(raw) as T;
1863
+ } catch (error) {
1864
+ reportCacheError(
1865
+ error,
1866
+ "cache-corrupt",
1867
+ `[CFCacheStore] ${label}: corrupt JSON in KV, evicting`,
1868
+ );
1869
+ this.scheduleKvEvict(kvKey, label);
1870
+ return { value: null, timedOut: false };
1871
+ }
1872
+ } else {
1873
+ envelope = raw as T;
1874
+ }
1875
+
1876
+ // A body that parses to null or a primitive ('null', '42', 'true', '"x"')
1877
+ // is not a valid envelope. Guard it BEFORE validate(): the property-reading
1878
+ // validators throw on a null/primitive rather than returning false, which
1879
+ // would escape to the caller's outer catch as a transient cache-read and
1880
+ // leave the bad key un-evicted (re-failing every read until its KV TTL). The
1881
+ // typeof check short-circuits validate() so it only ever runs on an object.
1882
+ if (
1883
+ envelope == null ||
1884
+ typeof envelope !== "object" ||
1885
+ !validate(envelope)
1886
+ ) {
1887
+ reportCacheError(
1888
+ new Error("malformed/partial KV envelope"),
1889
+ "cache-corrupt",
1890
+ `[CFCacheStore] ${label}: malformed envelope, evicting`,
1891
+ );
1892
+ this.scheduleKvEvict(kvKey, label);
1893
+ return { value: null, timedOut: false };
1894
+ }
1895
+ return { value: envelope, timedOut: false };
1896
+ }
1897
+
1898
+ // ============================================================================
1899
+ // Tag Invalidation (single-store: markers live in this.kv)
1900
+ // ============================================================================
1901
+
1902
+ /** KV key for a tag's invalidation marker. */
1903
+ private tagMarkerKey(tag: string): string {
1904
+ return this.toKVKey(`${TAG_MARKER_PREFIX}${tag}`);
1905
+ }
1906
+
1907
+ /**
1908
+ * Header entries carrying an entry's tags (JSON-encoded, comma-safe) and the
1909
+ * timestamp they were attached. Returns an empty object when there are no
1910
+ * tags so untagged entries stay header-free and skip the invalidation check.
1911
+ */
1912
+ private tagHeaderEntries(
1913
+ tags: string[] | undefined,
1914
+ taggedAt: number | undefined,
1915
+ ): Record<string, string> {
1916
+ if (!Array.isArray(tags) || tags.length === 0 || !taggedAt) return {};
1917
+ return {
1918
+ // encodeURIComponent so the value is pure ASCII: HTTP header values are
1919
+ // ByteStrings, but JSON.stringify leaves codepoints > U+00FF (emoji/CJK)
1920
+ // verbatim, which makes new Response({ headers }) throw and the outer
1921
+ // try/catch silently drop the whole entry from cache. Decoded in
1922
+ // readTagInfo. The L1 marker Cache-Tag path encodes for the same reason.
1923
+ [CACHE_TAGS_HEADER]: encodeURIComponent(JSON.stringify(tags)),
1924
+ [CACHE_TAGGED_AT_HEADER]: String(taggedAt),
1925
+ };
1926
+ }
1927
+
1928
+ /**
1929
+ * Merge the internal tag headers onto an existing Headers instance. The
1930
+ * from-scratch paths spread tagHeaderEntries() into an object-literal init;
1931
+ * the document put/promote paths build a Headers first, so they .set() each
1932
+ * entry instead.
1933
+ */
1934
+ private setTagHeaders(
1935
+ headers: Headers,
1936
+ tags: string[] | undefined,
1937
+ taggedAt: number | undefined,
1938
+ ): void {
1939
+ for (const [name, value] of Object.entries(
1940
+ this.tagHeaderEntries(tags, taggedAt),
1941
+ )) {
1942
+ headers.set(name, value);
1943
+ }
1944
+ }
1945
+
1946
+ /** Read an entry's tags/taggedAt back from its headers. */
1947
+ private readTagInfo(headers: Headers): {
1948
+ tags?: string[];
1949
+ taggedAt?: number;
1950
+ } {
1951
+ const rawTags = headers.get(CACHE_TAGS_HEADER);
1952
+ const rawTaggedAt = headers.get(CACHE_TAGGED_AT_HEADER);
1953
+ if (!rawTags || !rawTaggedAt) return {};
1954
+ try {
1955
+ const taggedAt = Number(rawTaggedAt);
1956
+ // A corrupt/non-numeric tagged-at header yields NaN. isGloballyInvalidated
1957
+ // short-circuits on a falsy taggedAt (NaN is falsy), so returning
1958
+ // { taggedAt: NaN } would make the entry permanently NON-invalidatable -
1959
+ // a revalidateTag could never evict it. Treat a non-finite stamp the same
1960
+ // as the missing-header case (untagged): drop both tags and taggedAt so the
1961
+ // entry is re-rendered/re-tagged rather than silently un-invalidatable.
1962
+ if (!Number.isFinite(taggedAt)) return {};
1963
+ return {
1964
+ tags: JSON.parse(decodeURIComponent(rawTags)) as string[],
1965
+ taggedAt,
1966
+ };
1967
+ } catch {
1968
+ return {};
1969
+ }
1970
+ }
1971
+
1972
+ /**
1973
+ * Whether an entry tagged at `taggedAt` with `tags` has been invalidated since.
1974
+ * Reads the per-tag invalidation markers from KV and returns true if any tag's
1975
+ * latest invalidation is at or after taggedAt (>= so a same-millisecond
1976
+ * invalidate wins, favouring freshness over staleness). Fails open: KV errors
1977
+ * never turn a hit into a wrongful miss-storm beyond this single read.
1978
+ */
1979
+ private async isGloballyInvalidated(
1980
+ tags: string[] | undefined,
1981
+ taggedAt: number | undefined,
1982
+ ): Promise<boolean> {
1983
+ // Array.isArray (not just truthiness): a non-array tags value - direct store
1984
+ // misuse like setItem(k, v, { tags: "products" }), or a skewed KV envelope -
1985
+ // must fail safe to "not invalidated" rather than throwing `.map` on every
1986
+ // read (which the outer catch would mis-report as a transient cache-read).
1987
+ if (!this.kv || !Array.isArray(tags) || tags.length === 0 || !taggedAt)
1988
+ return false;
1989
+ const ctx = _getRequestContext();
1990
+ const memo = ctx ? getTagMarkerMemo(ctx, this) : undefined;
1991
+ const inflight = ctx ? getTagMarkerInflight(ctx, this) : undefined;
1992
+ try {
1993
+ const markers = await Promise.all(
1994
+ tags.map((tag) => this.readTagMarker(tag, memo, inflight)),
1995
+ );
1996
+ for (const marker of markers) {
1997
+ if (marker != null && marker >= taggedAt) return true;
1998
+ }
1999
+ return false;
2000
+ } catch (error) {
2001
+ reportCacheError(
2002
+ error,
2003
+ "cache-read",
2004
+ "[CFCacheStore] tag invalidation check",
2005
+ );
2006
+ return false;
2007
+ }
2008
+ }
2009
+
2010
+ /** Synthetic Cache API request for a tag's L1-cached invalidation marker. */
2011
+ private tagMarkerRequest(tag: string): Request {
2012
+ return this.keyToRequest(`${TAG_MARKER_CACHE_PREFIX}${tag}`);
2013
+ }
2014
+
2015
+ /**
2016
+ * Read a tag's latest invalidation timestamp (or null if never invalidated)
2017
+ * through the cascade: per-request memo -> per-colo L1 cache (only when
2018
+ * tagCacheTtl > 0) -> KV (the global truth). The memo is always consulted
2019
+ * first so it stays authoritative within a request (read-your-own-writes),
2020
+ * and every KV/L1 result is written back into the memo. A Cache API miss
2021
+ * always falls through to KV; absence is represented by a cached sentinel,
2022
+ * never by a miss.
2023
+ *
2024
+ * Concurrent reads of the same tag within a request share one in-flight read
2025
+ * (the resolved-value memo only collapses sequential reads; parallel segment
2026
+ * loading would otherwise issue one KV read per concurrent reader).
2027
+ * @internal
2028
+ */
2029
+ private async readTagMarker(
2030
+ tag: string,
2031
+ memo: Map<string, number | null> | undefined,
2032
+ inflight: Map<string, Promise<number | null>> | undefined,
2033
+ ): Promise<number | null> {
2034
+ if (memo && memo.has(tag)) return memo.get(tag) ?? null;
2035
+
2036
+ // Collapse concurrent (not-yet-resolved) reads of this tag onto one promise.
2037
+ if (inflight) {
2038
+ const pending = inflight.get(tag);
2039
+ if (pending) return pending;
2040
+ const read = this.fetchTagMarker(tag, memo);
2041
+ inflight.set(tag, read);
2042
+ try {
2043
+ return await read;
2044
+ } finally {
2045
+ // Resolved values now live in the memo; drop the in-flight entry.
2046
+ inflight.delete(tag);
2047
+ }
2048
+ }
2049
+
2050
+ return this.fetchTagMarker(tag, memo);
2051
+ }
2052
+
2053
+ /**
2054
+ * Uncached body of readTagMarker: L1 (per-colo Cache API, opt-in via
2055
+ * tagCacheTtl) -> KV. Writes the resolved value back into the memo.
2056
+ * @internal
2057
+ */
2058
+ private async fetchTagMarker(
2059
+ tag: string,
2060
+ memo: Map<string, number | null> | undefined,
2061
+ ): Promise<number | null> {
2062
+ // Write the resolved marker into the memo WITHOUT clobbering a value a
2063
+ // concurrent invalidateTags() wrote during our await. The router resolves
2064
+ // sibling slots in parallel, so a slot's updateTag() can land the
2065
+ // authoritative invalidatedAt into the memo while this read is still in
2066
+ // flight; overwriting it with our (pre-invalidation) read result would break
2067
+ // read-your-own-writes for the rest of the request. If the tag was memoized
2068
+ // mid-read, that value wins and is returned. Without a memo, the read result
2069
+ // stands as-is.
2070
+ const memoize = (read: number | null): number | null => {
2071
+ if (memo && memo.has(tag)) return memo.get(tag) ?? null;
2072
+ memo?.set(tag, read);
2073
+ return read;
2074
+ };
2075
+
2076
+ // L1 (per-colo) marker cache - opt-in via tagCacheTtl. Bounded by the same
2077
+ // edge budgets as data reads (inherited from #558) so a degraded colo cannot
2078
+ // stall a tagged read; a miss, timeout, or error all fall through to KV.
2079
+ if (this.tagCacheTtl > 0) {
2080
+ try {
2081
+ const cache = await this.getCache();
2082
+ const { response: hit, error: matchError } =
2083
+ await this.matchWithTimeout(cache, this.tagMarkerRequest(tag));
2084
+ // A transient match REJECTION is captured (not thrown) by
2085
+ // matchWithTimeout; surface it as cache-read like the data read paths
2086
+ // before falling through to KV, rather than silently dropping it.
2087
+ if (matchError)
2088
+ reportCacheError(
2089
+ matchError,
2090
+ "cache-read",
2091
+ "[CFCacheStore] tag marker L1 match",
2092
+ );
2093
+ if (hit) {
2094
+ const { value: body } = await this.readWithTimeout(
2095
+ () => hit.text(),
2096
+ this.edgeReadTimeoutMs,
2097
+ "tag marker L1 body read",
2098
+ );
2099
+ if (body !== undefined) {
2100
+ const value = body === TAG_MARKER_ABSENT ? null : Number(body);
2101
+ return memoize(value);
2102
+ }
2103
+ }
2104
+ } catch {
2105
+ // Fall through to KV on any L1 read error.
2106
+ }
2107
+ }
2108
+
2109
+ // KV (global truth), bounded by the KV budget. On TIMEOUT fail OPEN: treat
2110
+ // the marker as absent (-> entry not invalidated -> served) so a degraded
2111
+ // namespace cannot pin every tagged read behind a slow global lookup. A
2112
+ // transient REJECTION instead propagates to isGloballyInvalidated's catch
2113
+ // (reported cache-read), which also fails open. Either way one slow tag
2114
+ // never amplifies into a per-segment stall.
2115
+ const { value: raw, timedOut } = await this.readWithTimeout<string | null>(
2116
+ () => this.kv!.get(this.tagMarkerKey(tag), { type: "text" }),
2117
+ this.kvReadTimeoutMs,
2118
+ "tag marker KV read",
2119
+ );
2120
+ if (timedOut) {
2121
+ // Memoize the fail-open result so the rest of this request is consistent
2122
+ // (and does not re-pay the timeout per segment sharing the tag).
2123
+ return memoize(null);
2124
+ }
2125
+ const value = raw != null ? Number(raw) : null;
2126
+ const resolved = memoize(value);
2127
+
2128
+ // Populate L1 for subsequent reads in this colo (non-blocking). Use the
2129
+ // resolved (memo-aware) value so a marker invalidated mid-read is not
2130
+ // re-cached stale into this colo's L1.
2131
+ if (this.tagCacheTtl > 0) {
2132
+ const put = () => this.putTagMarkerL1(tag, resolved);
2133
+ if (this.waitUntil) this.waitUntil(put);
2134
+ else void put();
2135
+ }
2136
+ return resolved;
2137
+ }
2138
+
2139
+ /**
2140
+ * Cloudflare Cache-Tags written on a tag's L1 marker entry, namespaced per
2141
+ * store so purges never collide with other Cache-Tags in the zone. Three
2142
+ * tiers, broad to specific:
2143
+ * rg:{ns} - everything this store cached (deploy/nuclear reset)
2144
+ * rg:{ns}:lk - all tag-lookup markers
2145
+ * rg:{ns}:lk:{tag} - this tag's lookup (the normal updateTag purge target)
2146
+ * The tag value is encodeURIComponent'd so commas/spaces can't corrupt the
2147
+ * comma-delimited Cache-Tag header.
2148
+ * @internal
2149
+ */
2150
+ private lookupCacheTags(tag: string): string[] {
2151
+ const ns = this.namespace ?? "default";
2152
+ return [`rg:${ns}`, `rg:${ns}:lk`, this.lookupPurgeTag(tag)];
2153
+ }
2154
+
2155
+ /** The specific Cache-Tag a consumer purges to evict tag `tag`'s lookup. */
2156
+ private lookupPurgeTag(tag: string): string {
2157
+ const ns = this.namespace ?? "default";
2158
+ return `rg:${ns}:lk:${encodeURIComponent(tag)}`;
2159
+ }
2160
+
2161
+ /**
2162
+ * Write a tag marker value into the per-colo L1 Cache API with tagCacheTtl.
2163
+ * `null` is stored as the TAG_MARKER_ABSENT sentinel so "no marker yet" is
2164
+ * cacheable (most tags are never invalidated - that is where the read savings
2165
+ * come from). The entry also carries a namespaced Cache-Tag so an external
2166
+ * purge-by-tag (via onRevalidateTag) can evict it across colos promptly,
2167
+ * rather than waiting out tagCacheTtl. Best-effort.
2168
+ * @internal
2169
+ */
2170
+ private async putTagMarkerL1(
2171
+ tag: string,
2172
+ value: number | null,
2173
+ opts?: { critical?: boolean },
2174
+ ): Promise<void> {
2175
+ if (this.tagCacheTtl <= 0) return;
2176
+ try {
2177
+ const cache = await this.getCache();
2178
+ const body = value != null ? String(value) : TAG_MARKER_ABSENT;
2179
+ await cache.put(
2180
+ this.tagMarkerRequest(tag),
2181
+ new Response(body, {
2182
+ headers: {
2183
+ "Cache-Control": `public, max-age=${this.tagCacheTtl}`,
2184
+ "Cache-Tag": this.lookupCacheTags(tag).join(","),
2185
+ },
2186
+ }),
2187
+ );
2188
+ } catch (error) {
2189
+ // The read-path populate is best-effort: a failed populate just means the
2190
+ // next read consults KV. The invalidation WRITE-THROUGH (critical) is not
2191
+ // - silently swallowing it would leave this colo's stale marker (often the
2192
+ // ABSENT sentinel) authoritative for tagCacheTtl while updateTag reports
2193
+ // success. Surface it, and best-effort delete the L1 marker so the next
2194
+ // read re-reads KV, which already holds the fresh marker (written before
2195
+ // this write-through in invalidateTags).
2196
+ if (opts?.critical) {
2197
+ reportCacheError(
2198
+ error,
2199
+ "cache-invalidate",
2200
+ "[CFCacheStore] tag marker L1 write-through",
2201
+ );
2202
+ await reportingAsync(
2203
+ async () => {
2204
+ const cache = await this.getCache();
2205
+ await cache.delete(this.tagMarkerRequest(tag));
2206
+ },
2207
+ "cache-delete",
2208
+ "[CFCacheStore] tag marker L1 evict after failed write-through",
2209
+ );
2210
+ }
2211
+ }
2212
+ }
2213
+
2214
+ /**
2215
+ * Invalidate every entry tagged with any of `tags`. Receives the whole batch
2216
+ * from one updateTag()/revalidateTag() call so the eager-purge hook fires
2217
+ * ONCE (one CDN purge request, not one per tag). For each tag: records the KV
2218
+ * marker (the durable cross-colo truth that reads compare taggedAt against),
2219
+ * writes the fresh marker straight into this colo's L1 (write-through, NOT
2220
+ * delete - a delete would let the next read re-read a not-yet-converged KV
2221
+ * value and re-arm the stale window), and memoizes it for same-request
2222
+ * read-your-own-writes. Finally fires onRevalidateTag with the namespaced
2223
+ * lookup Cache-Tags so a consumer purge evicts the cached lookups in other
2224
+ * colos promptly (otherwise they converge within tagCacheTtl).
2225
+ *
2226
+ * Durable-write integrity: the in-memory write-through (memo + L1) for a tag
2227
+ * runs ONLY after that tag's KV marker write is confirmed. If any KV write
2228
+ * fails (transient error, or an over-512-byte key), this rejects with the
2229
+ * failed tags so an awaiting updateTag() surfaces the failure instead of
2230
+ * silently reporting success while other requests/colos serve stale data. The
2231
+ * eager purge still fires for the whole batch first (it is additive).
2232
+ */
2233
+ async invalidateTags(tags: string[]): Promise<void> {
2234
+ if (tags.length === 0) return;
2235
+ const invalidatedAt = Date.now();
2236
+ const ctx = _getRequestContext();
2237
+ const memo = ctx ? getTagMarkerMemo(ctx, this) : undefined;
2238
+
2239
+ if (!this.kv && !this.onRevalidateTag) {
2240
+ console.warn(
2241
+ `[CFCacheStore] invalidateTags had no effect: configure a KV namespace ` +
2242
+ `for distributed invalidation, or an onRevalidateTag hook.`,
2243
+ );
2244
+ }
2245
+
2246
+ const failedTags = new Set<string>();
2247
+ const errors: unknown[] = [];
2248
+ if (this.kv) {
2249
+ await Promise.all(
2250
+ tags.map(async (tag) => {
2251
+ const markerKey = this.tagMarkerKey(tag);
2252
+ const markerKeyBytes = kvKeyByteLength(markerKey);
2253
+ if (markerKeyBytes > KV_MAX_KEY_BYTES) {
2254
+ failedTags.add(tag);
2255
+ errors.push(
2256
+ new Error(
2257
+ `tag "${tag}" produces a ${markerKeyBytes}-byte KV ` +
2258
+ `marker key, over the ${KV_MAX_KEY_BYTES}-byte limit`,
2259
+ ),
2260
+ );
2261
+ return;
2262
+ }
2263
+ try {
2264
+ await this.kv!.put(markerKey, String(invalidatedAt), {
2265
+ ...(this.tagInvalidationTtl
2266
+ ? { expirationTtl: this.tagInvalidationTtl }
2267
+ : {}),
2268
+ });
2269
+ } catch (error) {
2270
+ failedTags.add(tag);
2271
+ errors.push(error);
2272
+ }
2273
+ }),
2274
+ );
2275
+ }
2276
+
2277
+ // Write-through memo + L1 only for tags with a confirmed durable marker, and
2278
+ // only when KV is configured. Markers are read exclusively through
2279
+ // isGloballyInvalidated(), which short-circuits to "not invalidated" when
2280
+ // !this.kv; writing memo/L1 markers without KV would be dead state no read
2281
+ // path ever consults. The onRevalidateTag purge below still fires regardless
2282
+ // (it is additive and external to the marker cascade). The memo write is
2283
+ // synchronous (read-your-own-writes); the L1 Cache API writes are
2284
+ // independent, so fan them out in parallel rather than awaiting each.
2285
+ if (this.kv) {
2286
+ const l1Writes: Promise<void>[] = [];
2287
+ for (const tag of tags) {
2288
+ if (failedTags.has(tag)) continue;
2289
+ memo?.set(tag, invalidatedAt);
2290
+ if (this.tagCacheTtl > 0) {
2291
+ l1Writes.push(
2292
+ this.putTagMarkerL1(tag, invalidatedAt, { critical: true }),
2293
+ );
2294
+ }
2295
+ }
2296
+ if (l1Writes.length > 0) await Promise.all(l1Writes);
2297
+ }
2298
+
2299
+ // One batched eager purge of the lookup markers for the whole call. Fired
2300
+ // regardless of KV write outcome (it is additive and uses pure string ops).
2301
+ if (this.onRevalidateTag) {
2302
+ try {
2303
+ await this.onRevalidateTag(tags.map((tag) => this.lookupPurgeTag(tag)));
2304
+ } catch (error) {
2305
+ reportCacheError(
2306
+ error,
2307
+ "cache-invalidate",
2308
+ "[CFCacheStore] onRevalidateTag hook",
2309
+ );
2310
+ }
2311
+ }
2312
+
2313
+ if (failedTags.size > 0) {
2314
+ const err = new Error(
2315
+ `[CFCacheStore] ${failedTags.size}/${tags.length} tag marker write(s) ` +
2316
+ `failed: ${[...failedTags].join(", ")}. Those tags may still serve ` +
2317
+ `stale data across requests/colos; retry the invalidation.`,
2318
+ );
2319
+ (err as Error & { cause?: unknown }).cause = errors[0];
2320
+ throw err;
2321
+ }
2322
+ }
2323
+
2324
+ // ============================================================================
2325
+ // KV L2 Helpers
2326
+ // ============================================================================
2327
+
2328
+ /**
2329
+ * KV fallback for segment cache reads.
2330
+ * Returns null if KV is not configured, entry is missing, or expired.
2331
+ * Promotes hits to L1 via waitUntil.
2332
+ * @internal
2333
+ */
2334
+ private async kvGetSegment(
2335
+ key: string,
2336
+ opts?: { suppressRevalidate?: boolean },
2337
+ ): Promise<CacheGetResult | null> {
2338
+ if (!this.kv) return null;
2339
+
2340
+ try {
2341
+ const kvKey = this.toKVKey(key);
2342
+ const { value: envelope, timedOut } =
2343
+ await this.kvGetOrEvict<KVSegmentEnvelope>(
2344
+ kvKey,
2345
+ (e) =>
2346
+ typeof e.e === "number" && typeof e.s === "number" && e.d != null,
2347
+ "kvGetSegment",
2348
+ );
2349
+ if (timedOut) {
2350
+ // Abandoned slow KV read: no envelope, so no promote-to-L1. Distinct
2351
+ // from a genuine kv-miss so the degradation is visible on wrangler tail.
2352
+ if (this.debug)
2353
+ this.emitDebug({ op: "get", key, outcome: "kv-timeout" });
2354
+ return null;
2355
+ }
2356
+ if (!envelope) {
2357
+ // Missing key, or a corrupt entry already evicted + reported by
2358
+ // kvGetOrEvict. Either way a miss.
2359
+ if (this.debug) this.emitDebug({ op: "get", key, outcome: "kv-miss" });
2360
+ return null;
2361
+ }
2362
+
2363
+ const now = Date.now();
2364
+
2365
+ // Hard-expired — treat as miss
2366
+ if (now > envelope.e) {
2367
+ if (this.debug) this.emitDebug({ op: "get", key, outcome: "kv-miss" });
2368
+ return null;
2369
+ }
2370
+
2371
+ // Tag invalidation check (also covers the KV tier, not just L1).
2372
+ if (
2373
+ await this.isGloballyInvalidated(envelope.d.tags, envelope.d.taggedAt)
2374
+ ) {
2375
+ if (this.debug)
2376
+ this.emitDebug({ op: "get", key, outcome: "tag-invalidated" });
2377
+ return null;
2378
+ }
2379
+
2380
+ // When this is a degraded L1 fall-through (body-timeout / non-200), the
2381
+ // caller asks us to suppress revalidation: KV has no REVALIDATING herd
2382
+ // guard, so N concurrent degraded reads would otherwise each spawn a
2383
+ // render exactly when the colo is already struggling. We still serve the
2384
+ // stale data and still promote to L1; only the revalidation is withheld.
2385
+ const stale = now > envelope.s;
2386
+ const shouldRevalidate = stale && !opts?.suppressRevalidate;
2387
+
2388
+ // Promote to L1 in background
2389
+ this.promoteSegmentToL1(key, envelope);
2390
+
2391
+ if (this.debug)
2392
+ this.emitDebug({
2393
+ op: "get",
2394
+ key,
2395
+ outcome: !stale
2396
+ ? "kv-fresh"
2397
+ : opts?.suppressRevalidate
2398
+ ? "kv-stale-suppressed"
2399
+ : "kv-stale",
2400
+ shouldRevalidate,
2401
+ });
2402
+ return { data: envelope.d, shouldRevalidate };
2403
+ } catch (error) {
2404
+ reportCacheError(error, "cache-read", "[CFCacheStore] kvGetSegment");
2405
+ if (this.debug) this.emitDebug({ op: "get", key, outcome: "error" });
2406
+ return null;
2407
+ }
2408
+ }
2409
+
2410
+ /**
2411
+ * Write segment data to KV.
2412
+ * @internal
2413
+ */
2414
+ private kvSetSegment(
2415
+ key: string,
2416
+ data: CachedEntryData,
2417
+ staleAt: number,
2418
+ totalTtl: number,
2419
+ swrWindow: number,
2420
+ ): void {
2421
+ // KV requires expirationTtl >= 60s. Skip write for short-lived entries.
2422
+ if (!this.kv || !this.waitUntil || totalTtl < 60) return;
2423
+
2424
+ const kvKey = this.toKVKey(key);
2425
+
2426
+ // Reject an oversized data-segment KV key the same way tag-marker keys are
2427
+ // rejected in invalidateTags(). A key over KV_MAX_KEY_BYTES makes kv.put()
2428
+ // fail, so the segment silently never lands in L2 (KV) and every cold-colo
2429
+ // or TTL-expired read re-renders instead of serving stale. Segment keys can
2430
+ // grow with user-controlled inputs (e.g. a route's search params), so report
2431
+ // a clear, actionable error and skip the doomed write rather than letting it
2432
+ // reject deep inside waitUntil as an opaque cache-write failure.
2433
+ const kvKeyBytes = kvKeyByteLength(kvKey);
2434
+ if (kvKeyBytes > KV_MAX_KEY_BYTES) {
2435
+ reportCacheError(
2436
+ new Error(
2437
+ `cache segment key produces a ${kvKeyBytes}-byte KV key, over the ` +
2438
+ `${KV_MAX_KEY_BYTES}-byte limit; the segment was not persisted to KV (L2). ` +
2439
+ `Reduce the cache-key inputs (e.g. large search params on this route).`,
2440
+ ),
2441
+ "cache-write",
2442
+ "[CFCacheStore] kvSetSegment",
2443
+ );
2444
+ return;
2445
+ }
2446
+
2447
+ const expiresAt = staleAt + swrWindow * 1000;
2448
+
2449
+ this.waitUntil(() =>
2450
+ reportingAsync(
2451
+ () => {
2452
+ const envelope: KVSegmentEnvelope = {
2453
+ d: data,
2454
+ s: staleAt,
2455
+ e: expiresAt,
2456
+ };
2457
+ return this.kv!.put(kvKey, JSON.stringify(envelope), {
2458
+ expirationTtl: totalTtl,
2459
+ });
2460
+ },
2461
+ "cache-write",
2462
+ "[CFCacheStore] kvSetSegment",
2463
+ ),
2464
+ );
2465
+ }
2466
+
2467
+ /**
2468
+ * Promote segment data from KV to L1 Cache API.
2469
+ * @internal
2470
+ */
2471
+ private promoteSegmentToL1(key: string, envelope: KVSegmentEnvelope): void {
2472
+ if (!this.waitUntil) return;
2473
+
2474
+ this.waitUntil(() =>
2475
+ reportingAsync(
2476
+ async () => {
2477
+ const now = Date.now();
2478
+ const remainingTtl = Math.max(
2479
+ 1,
2480
+ Math.floor((envelope.e - now) / 1000),
2481
+ );
2482
+ const cache = await this.getCache();
2483
+ const request = this.keyToRequest(key);
2484
+
2485
+ const response = new Response(JSON.stringify(envelope.d), {
2486
+ headers: {
2487
+ "Content-Type": "application/json",
2488
+ "Cache-Control": `public, max-age=${remainingTtl}`,
2489
+ [CACHE_STALE_AT_HEADER]: String(envelope.s),
2490
+ // Carry the hard-expiry deadline so a promoted entry that later
2491
+ // goes stale re-puts with the correct remaining ttl (see set()).
2492
+ [CACHE_EXPIRES_AT_HEADER]: String(envelope.e),
2493
+ [CACHE_STATUS_HEADER]: "HIT",
2494
+ // Preserve tags across KV->L1 promotion so the promoted entry
2495
+ // stays tag-invalidatable.
2496
+ ...this.tagHeaderEntries(envelope.d.tags, envelope.d.taggedAt),
2497
+ },
2498
+ });
2499
+
2500
+ await cache.put(request, response);
2501
+ },
2502
+ "cache-write",
2503
+ "[CFCacheStore] promoteSegmentToL1",
2504
+ ),
2505
+ );
2506
+ }
2507
+
2508
+ /**
2509
+ * KV fallback for function cache reads.
2510
+ * @internal
2511
+ */
2512
+ private async kvGetItem(
2513
+ key: string,
2514
+ opts?: { suppressRevalidate?: boolean },
2515
+ ): Promise<CacheItemResult | null> {
2516
+ if (!this.kv) return null;
2517
+
2518
+ try {
2519
+ const kvKey = this.toKVKey(`fn:${key}`);
2520
+ const { value: envelope, timedOut } =
2521
+ await this.kvGetOrEvict<KVItemEnvelope>(
2522
+ kvKey,
2523
+ (e) =>
2524
+ typeof e.v === "string" &&
2525
+ typeof e.e === "number" &&
2526
+ typeof e.s === "number",
2527
+ "kvGetItem",
2528
+ );
2529
+ if (timedOut) {
2530
+ if (this.debug)
2531
+ this.emitDebug({ op: "getItem", key, outcome: "kv-timeout" });
2532
+ return null;
2533
+ }
2534
+ if (!envelope) {
2535
+ if (this.debug)
2536
+ this.emitDebug({ op: "getItem", key, outcome: "kv-miss" });
2537
+ return null;
2538
+ }
2539
+
2540
+ const now = Date.now();
2541
+
2542
+ if (now > envelope.e) {
2543
+ if (this.debug)
2544
+ this.emitDebug({ op: "getItem", key, outcome: "kv-miss" });
2545
+ return null;
2546
+ }
2547
+
2548
+ // Tag invalidation check (also covers the KV tier, not just L1).
2549
+ if (await this.isGloballyInvalidated(envelope.t, envelope.ta)) {
2550
+ if (this.debug)
2551
+ this.emitDebug({ op: "getItem", key, outcome: "tag-invalidated" });
2552
+ return null;
2553
+ }
2554
+
2555
+ // Degraded fall-through suppresses revalidation (no KV herd guard); see
2556
+ // kvGetSegment. Still serves stale and still promotes.
2557
+ const stale = now > envelope.s;
2558
+ const shouldRevalidate = stale && !opts?.suppressRevalidate;
2559
+
2560
+ // Promote to L1
2561
+ this.promoteItemToL1(key, envelope);
2562
+
2563
+ if (this.debug)
2564
+ this.emitDebug({
2565
+ op: "getItem",
2566
+ key,
2567
+ outcome: !stale
2568
+ ? "kv-fresh"
2569
+ : opts?.suppressRevalidate
2570
+ ? "kv-stale-suppressed"
2571
+ : "kv-stale",
2572
+ shouldRevalidate,
2573
+ });
2574
+ return {
2575
+ value: envelope.v,
2576
+ handles: envelope.h,
2577
+ shouldRevalidate,
2578
+ tags: envelope.t,
2579
+ };
2580
+ } catch (error) {
2581
+ reportCacheError(error, "cache-read", "[CFCacheStore] kvGetItem");
2582
+ if (this.debug) this.emitDebug({ op: "getItem", key, outcome: "error" });
2583
+ return null;
2584
+ }
2585
+ }
2586
+
2587
+ /**
2588
+ * Promote function cache data from KV to L1.
2589
+ * @internal
2590
+ */
2591
+ private promoteItemToL1(key: string, envelope: KVItemEnvelope): void {
2592
+ if (!this.waitUntil) return;
2593
+
2594
+ this.waitUntil(() =>
2595
+ reportingAsync(
2596
+ async () => {
2597
+ const now = Date.now();
2598
+ const remainingTtl = Math.max(
2599
+ 1,
2600
+ Math.floor((envelope.e - now) / 1000),
2601
+ );
2602
+ const cache = await this.getCache();
2603
+ const request = this.keyToRequest(`fn:${key}`);
2604
+
2605
+ const body = JSON.stringify({
2606
+ value: envelope.v,
2607
+ handles: envelope.h,
2608
+ });
2609
+ const response = new Response(body, {
2610
+ headers: {
2611
+ "Content-Type": "application/json",
2612
+ "Cache-Control": `public, max-age=${remainingTtl}`,
2613
+ [CACHE_STALE_AT_HEADER]: String(envelope.s),
2614
+ // Carry the hard-expiry deadline; see promoteSegmentToL1 / set().
2615
+ [CACHE_EXPIRES_AT_HEADER]: String(envelope.e),
2616
+ [CACHE_STATUS_HEADER]: "HIT",
2617
+ // Preserve tags across KV->L1 promotion (the item tier previously
2618
+ // dropped them, permanently disabling tag invalidation here).
2619
+ ...this.tagHeaderEntries(envelope.t, envelope.ta),
2620
+ },
2621
+ });
2622
+
2623
+ await cache.put(request, response);
2624
+ },
2625
+ "cache-write",
2626
+ "[CFCacheStore] promoteItemToL1",
2627
+ ),
2628
+ );
2629
+ }
2630
+
2631
+ /**
2632
+ * KV fallback for document cache reads.
2633
+ * @internal
2634
+ */
2635
+ private async kvGetResponse(
2636
+ key: string,
2637
+ ): Promise<{ response: Response; shouldRevalidate: boolean } | null> {
2638
+ if (!this.kv) return null;
2639
+
2640
+ try {
2641
+ const kvKey = this.toDocKVKey(key);
2642
+ // The document path is debug-silent (op is only get/getItem): a KV-read
2643
+ // timeout here is bounded for resilience parity (kvGetOrEvict applies the
2644
+ // budget) but emits no kv-timeout event, so its absence from the debug
2645
+ // stream is expected. A null envelope is a miss -- missing key, a budget
2646
+ // timeout, or a corrupt entry already evicted + reported by kvGetOrEvict.
2647
+ const { value: envelope } = await this.kvGetOrEvict<KVResponseEnvelope>(
2648
+ kvKey,
2649
+ (e) =>
2650
+ typeof e.b === "string" &&
2651
+ typeof e.st === "number" &&
2652
+ typeof e.e === "number" &&
2653
+ typeof e.s === "number" &&
2654
+ // stx is optional but, if present, must be a string (feeds Response).
2655
+ (e.stx === undefined || typeof e.stx === "string") &&
2656
+ // hd must be an array of [name, value] string tuples; a malformed
2657
+ // shape would otherwise throw in `new Headers(hd)`. Validate it here
2658
+ // so a faulty envelope is a fail-open MISS, never a thrown read.
2659
+ Array.isArray(e.hd) &&
2660
+ e.hd.every(
2661
+ (entry) =>
2662
+ Array.isArray(entry) &&
2663
+ entry.length === 2 &&
2664
+ typeof entry[0] === "string" &&
2665
+ typeof entry[1] === "string",
2666
+ ),
2667
+ "kvGetResponse",
2668
+ );
2669
+ if (!envelope) return null;
2670
+
2671
+ const now = Date.now();
2672
+
2673
+ if (now > envelope.e) return null;
2674
+
2675
+ // Tag invalidation check (also covers the KV tier, not just L1).
2676
+ if (await this.isGloballyInvalidated(envelope.t, envelope.ta)) {
2677
+ return null;
2678
+ }
2679
+
2680
+ const shouldRevalidate = now > envelope.s;
2681
+
2682
+ // Reconstruct Response: decode base64 -> binary, rebuild headers/status.
2683
+ // Corrupt/partial base64 throws in atob; malformed `hd` or an out-of-range
2684
+ // `st` throws in new Headers/new Response. Any of these is a faulty entry,
2685
+ // so evict it and miss rather than re-failing every read until TTL.
2686
+ let response: Response;
2687
+ try {
2688
+ // Finding #3 (read side): strip per-client signals a stale envelope may
2689
+ // carry. Inside the try so a malformed `hd` evicts (not throws through);
2690
+ // mutates `hd` in place so promoteResponseToL1 re-seeds from it too.
2691
+ envelope.hd = envelope.hd.filter(
2692
+ ([name]) => !isPerClientSignalHeader(name),
2693
+ );
2694
+ const bodyBuffer = base64ToBuffer(envelope.b);
2695
+ const headers = new Headers(envelope.hd);
2696
+ response = new Response(bodyBuffer, {
2697
+ status: envelope.st,
2698
+ statusText: envelope.stx,
2699
+ headers,
2700
+ });
2701
+ } catch (error) {
2702
+ reportCacheError(
2703
+ error,
2704
+ "cache-corrupt",
2705
+ "[CFCacheStore] kvGetResponse: corrupt response envelope, evicting",
2706
+ );
2707
+ this.scheduleKvEvict(kvKey, "kvGetResponse");
2708
+ return null;
2709
+ }
2710
+
2711
+ // Promote to L1
2712
+ this.promoteResponseToL1(key, envelope);
2713
+
2714
+ return { response, shouldRevalidate };
2715
+ } catch (error) {
2716
+ reportCacheError(error, "cache-read", "[CFCacheStore] kvGetResponse");
2717
+ return null;
2718
+ }
2719
+ }
2720
+
2721
+ /**
2722
+ * Promote document cache data from KV to L1.
2723
+ * @internal
2724
+ */
2725
+ private promoteResponseToL1(key: string, envelope: KVResponseEnvelope): void {
2726
+ if (!this.waitUntil) return;
2727
+
2728
+ this.waitUntil(() =>
2729
+ reportingAsync(
2730
+ async () => {
2731
+ const now = Date.now();
2732
+ const remainingTtl = Math.max(
2733
+ 1,
2734
+ Math.floor((envelope.e - now) / 1000),
2735
+ );
2736
+ const cache = await this.getCache();
2737
+ const request = this.keyToRequest(`doc:${key}`);
2738
+
2739
+ const headers = new Headers(envelope.hd);
2740
+ const originalCacheControl = headers.get("Cache-Control");
2741
+ if (originalCacheControl !== null) {
2742
+ headers.set(CACHE_ORIG_CC_HEADER, originalCacheControl);
2743
+ }
2744
+ headers.set("Cache-Control", `public, max-age=${remainingTtl}`);
2745
+ headers.set(CACHE_STALE_AT_HEADER, String(envelope.s));
2746
+ // Carry the hard-expiry deadline so the document herd guard's
2747
+ // markResponseRevalidating re-put can compute the remaining window
2748
+ // (matches promoteSegmentToL1/promoteItemToL1); without it a stale
2749
+ // re-put would floor to max-age=1 and churn the KV-promoted twin.
2750
+ headers.set(CACHE_EXPIRES_AT_HEADER, String(envelope.e));
2751
+ // Re-attach the internal tag headers (envelope.hd is client-facing
2752
+ // and intentionally excludes them) so the promoted entry stays
2753
+ // invalidatable.
2754
+ this.setTagHeaders(headers, envelope.t, envelope.ta);
2755
+
2756
+ const bodyBuffer = base64ToBuffer(envelope.b);
2757
+ const response = new Response(bodyBuffer, {
2758
+ status: envelope.st,
2759
+ statusText: envelope.stx,
2760
+ headers,
2761
+ });
2762
+
2763
+ await cache.put(request, response);
2764
+ },
2765
+ "cache-write",
2766
+ "[CFCacheStore] promoteResponseToL1",
2767
+ ),
2768
+ );
427
2769
  }
428
2770
  }