Skip to content

feat: unified cache profile system with SWR + SIE - #54

Merged
vibe-dex merged 1 commit into
mainfrom
feat/cache-profiles
Mar 28, 2026
Merged

vibe-dex merged 1 commit into
mainfrom
feat/cache-profiles

Conversation

@vibe-dex

@vibe-dex vibe-dex commented Mar 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Redesign cache configuration into a single source of truth per profile (product, listing, search, static, private). Each profile defines timing for all 4 layers: edge (CF Cache API), browser (Cache-Control), loader (in-memory SWR), and client (TanStack Router staleTime/gcTime).
  • Add stale-if-error support at both edge and loader levels — serves stale content when origin is down (5xx/429/timeout) instead of propagating errors to users.
  • Edge-level SWR: serves stale content instantly while revalidating in the background via waitUntil, eliminating blocking origin fetches on cache expiry.
  • createCachedLoader now accepts a profile name ("product", "listing", "search") instead of explicit maxAge — sites no longer need hardcoded cache numbers.
  • registerCacheableSections also accepts profile names.
  • Sites override specific profile values via setCacheProfile() from a single config file.

Files changed

File Change
sdk/cacheHeaders.ts New CacheProfileConfig with edge/browser/loader/client timing + stale-if-error. setCacheProfile(), loaderCacheOptions(), edgeCacheConfig().
sdk/cachedLoader.ts Accepts profile name or explicit options. staleIfError logic for error resilience.
sdk/workerEntry.ts Edge SWR + SIE with X-Deco-Stored-At metadata and extended Cache API TTL.
cms/sectionLoaders.ts registerCacheableSections accepts profile names.
routes/cmsRoute.ts Updated to CacheProfileName type.
sdk/index.ts Re-exports new types and functions.

Test plan

  • Verify existing sites still build (no breaking type changes for sites already using profile names)
  • Test edge cache HIT/MISS/STALE-HIT/STALE-ERROR headers on a deployed Worker
  • Verify logged-in users bypass cache (X-Cache: BYPASS, X-Cache-Reason: logged-in)
  • Verify Set-Cookie responses are never cached
  • Test loader SIE: simulate VTEX 500 and verify stale data is returned instead of error

Made with Cursor


Summary by cubic

Unifies caching into named profiles that drive edge, browser, loader, and client timings. Adds stale-if-error and edge-side SWR to keep pages fast and resilient during origin failures.

  • New Features

    • Single source of truth per profile (static, product, listing, search, private, none) with timing for edge, browser, loader, and client.
    • Edge SWR + SIE: serve stale on expiry or on 5xx/429/timeout; background revalidate with waitUntil.
    • Loader SIE: createCachedLoader accepts a profile name or options and falls back to stale on errors.
    • Config APIs: setCacheProfile(), getCacheProfile(), edgeCacheConfig(), loaderCacheOptions(), routeCacheDefaults(), cacheHeaders().
    • registerCacheableSections now accepts profile names; cmsRoute updated to CacheProfileName.
    • Better observability via X-Cache: HIT | STALE-HIT | STALE-ERROR | MISS and X-Cache-Profile.
  • Migration

    • Replace types/functions:
      • CacheProfile → CacheProfileName.
      • setCacheProfileConfig → setCacheProfile.
      • getCacheProfileConfig → getCacheProfile.
      • setRouteCacheDefaults is removed; use setCacheProfile(..., { client: { staleTime, gcTime } }).
    • createCachedLoader(name, loader, options) now also accepts a profile name: createCachedLoader(name, loader, "product").
    • registerCacheableSections({ key: "product" }) can use a profile name; existing explicit { maxAge } still works.

Written for commit 1ff16ee. Summary will update on new commits.

…levels

Redesign cache configuration into a single source of truth per profile
(product, listing, search, static, private). Each profile defines timing
for all 4 layers: edge (CF Cache API), browser (Cache-Control), loader
(in-memory SWR), and client (TanStack Router staleTime/gcTime).

Key changes:
- cacheHeaders.ts: CacheProfileConfig with edge/browser/loader/client
  timing windows including stale-if-error. setCacheProfile() for site
  overrides. loaderCacheOptions() and edgeCacheConfig() derivation fns.
  No backward-compat types — clean single type system.
- cachedLoader.ts: accepts profile name OR explicit options. Adds
  staleIfError — on origin error, falls back to stale entry within the
  SIE window instead of propagating the error.
- workerEntry.ts: edge-level SWR (serve stale + waitUntil revalidate)
  and SIE (serve stale on origin 5xx/429/timeout). Uses extended Cache
  API TTL with X-Deco-Stored-At metadata for age tracking.
- sectionLoaders.ts: registerCacheableSections accepts profile names.
- cmsRoute.ts: updated to CacheProfileName type.

Made-with: Cursor
@vibe-dex
vibe-dex merged commit d0365af into main Mar 28, 2026
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 0.37.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

5 issues found across 6 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/sdk/workerEntry.ts">

<violation number="1" location="src/sdk/workerEntry.ts:877">
P0: Response body is consumed by `dressResponse` before `storeInCache` can clone it. `origin.clone()` will throw because `origin.bodyUsed` is already `true`, and the silent `catch` swallows it — meaning MISS responses are never persisted to the edge cache.</violation>
</file>

<file name="src/cms/sectionLoaders.ts">

<violation number="1" location="src/cms/sectionLoaders.ts:40">
P1: Using `require` in this ESM module can throw `ReferenceError: require is not defined` when profile strings are resolved.</violation>

<violation number="2" location="src/cms/sectionLoaders.ts:42">
P2: This accepts non-cacheable profiles (e.g. `private`/`none`) and converts them into `maxAge: 0`, which still serves stale cached section data instead of disabling cache.</violation>
</file>

<file name="src/sdk/cachedLoader.ts">

<violation number="1" location="src/sdk/cachedLoader.ts:164">
P1: Stale-if-error fallback is applied to every loader exception, which can mask non-retriable app bugs by serving stale data instead of surfacing the failure.</violation>

<violation number="2" location="src/sdk/cachedLoader.ts:165">
P2: SIE window validation uses request-start time instead of failure time, so stale entries can be served beyond the configured staleIfError limit after slow failures.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/sdk/workerEntry.ts
Comment on lines +877 to +878
const toReturn = dressResponse(origin, "MISS");
storeInCache(origin);

@cubic-dev-ai cubic-dev-ai Bot Mar 28, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P0: Response body is consumed by dressResponse before storeInCache can clone it. origin.clone() will throw because origin.bodyUsed is already true, and the silent catch swallows it — meaning MISS responses are never persisted to the edge cache.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/workerEntry.ts, line 877:

<comment>Response body is consumed by `dressResponse` before `storeInCache` can clone it. `origin.clone()` will throw because `origin.bodyUsed` is already `true`, and the silent `catch` swallows it — meaning MISS responses are never persisted to the edge cache.</comment>

<file context>
@@ -800,48 +873,9 @@ export function createDecoWorkerEntry(
-      }
-
+      // Store in Cache API and return
+      const toReturn = dressResponse(origin, "MISS");
+      storeInCache(origin);
       return toReturn;
</file context>
Suggested change
const toReturn = dressResponse(origin, "MISS");
storeInCache(origin);
storeInCache(origin);
const toReturn = dressResponse(origin, "MISS");
Fix with Cubic

Comment thread src/cms/sectionLoaders.ts

function resolveSectionCacheConfig(input: CacheableSectionInput): CacheableSectionConfig {
if (typeof input === "string") {
const { getCacheProfile } = require("../sdk/cacheHeaders") as typeof import("../sdk/cacheHeaders");

@cubic-dev-ai cubic-dev-ai Bot Mar 28, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Using require in this ESM module can throw ReferenceError: require is not defined when profile strings are resolved.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/cms/sectionLoaders.ts, line 40:

<comment>Using `require` in this ESM module can throw `ReferenceError: require is not defined` when profile strings are resolved.</comment>

<file context>
@@ -33,6 +33,17 @@ interface CacheableSectionConfig {
+
+function resolveSectionCacheConfig(input: CacheableSectionInput): CacheableSectionConfig {
+  if (typeof input === "string") {
+    const { getCacheProfile } = require("../sdk/cacheHeaders") as typeof import("../sdk/cacheHeaders");
+    const profile = getCacheProfile(input);
+    return { maxAge: profile.loader.fresh };
</file context>
Fix with Cubic

Comment thread src/sdk/cachedLoader.ts
.catch((err) => {
inflightRequests.delete(cacheKey);
// SIE fallback: if we have a stale entry within the error window, return it
if (staleIfError > 0 && entry) {

@cubic-dev-ai cubic-dev-ai Bot Mar 28, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1: Stale-if-error fallback is applied to every loader exception, which can mask non-retriable app bugs by serving stale data instead of surfacing the failure.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/cachedLoader.ts, line 164:

<comment>Stale-if-error fallback is applied to every loader exception, which can mask non-retriable app bugs by serving stale data instead of surfacing the failure.</comment>

<file context>
@@ -140,6 +160,16 @@ export function createCachedLoader<TProps, TResult>(
       .catch((err) => {
         inflightRequests.delete(cacheKey);
+        // SIE fallback: if we have a stale entry within the error window, return it
+        if (staleIfError > 0 && entry) {
+          const age = now - entry.createdAt;
+          if (age < maxAge + staleIfError) {
</file context>
Fix with Cubic

Comment thread src/cms/sectionLoaders.ts
if (typeof input === "string") {
const { getCacheProfile } = require("../sdk/cacheHeaders") as typeof import("../sdk/cacheHeaders");
const profile = getCacheProfile(input);
return { maxAge: profile.loader.fresh };

@cubic-dev-ai cubic-dev-ai Bot Mar 28, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: This accepts non-cacheable profiles (e.g. private/none) and converts them into maxAge: 0, which still serves stale cached section data instead of disabling cache.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/cms/sectionLoaders.ts, line 42:

<comment>This accepts non-cacheable profiles (e.g. `private`/`none`) and converts them into `maxAge: 0`, which still serves stale cached section data instead of disabling cache.</comment>

<file context>
@@ -33,6 +33,17 @@ interface CacheableSectionConfig {
+  if (typeof input === "string") {
+    const { getCacheProfile } = require("../sdk/cacheHeaders") as typeof import("../sdk/cacheHeaders");
+    const profile = getCacheProfile(input);
+    return { maxAge: profile.loader.fresh };
+  }
+  return input;
</file context>
Suggested change
return { maxAge: profile.loader.fresh };
if (profile.loader.fresh <= 0) {
throw new Error(`[SectionLoaders] Cache profile "${input}" is not cacheable for section loaders`);
}
return { maxAge: profile.loader.fresh };
Fix with Cubic

Comment thread src/sdk/cachedLoader.ts
inflightRequests.delete(cacheKey);
// SIE fallback: if we have a stale entry within the error window, return it
if (staleIfError > 0 && entry) {
const age = now - entry.createdAt;

@cubic-dev-ai cubic-dev-ai Bot Mar 28, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: SIE window validation uses request-start time instead of failure time, so stale entries can be served beyond the configured staleIfError limit after slow failures.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At src/sdk/cachedLoader.ts, line 165:

<comment>SIE window validation uses request-start time instead of failure time, so stale entries can be served beyond the configured staleIfError limit after slow failures.</comment>

<file context>
@@ -140,6 +160,16 @@ export function createCachedLoader<TProps, TResult>(
         inflightRequests.delete(cacheKey);
+        // SIE fallback: if we have a stale entry within the error window, return it
+        if (staleIfError > 0 && entry) {
+          const age = now - entry.createdAt;
+          if (age < maxAge + staleIfError) {
+            console.warn(
</file context>
Suggested change
const age = now - entry.createdAt;
const age = Date.now() - entry.createdAt;
Fix with Cubic

hugo-ccabral added a commit that referenced this pull request Aug 18, 2026
…rnings-staging convention (#457)

## Summary

Consolidates the farmrio-storefront Fresh→TanStack migration's staged
learnings (`migration/learnings/`, ~69 completed targets,
coverage-verified against the live ledger) into this skill's reference
docs, per the epic's own consolidation target (`T40`).

22 new numbered gotchas (**#52–#73**), each carrying Severity, Symptom,
Root cause, Fix (with code), a discovery `rg`/`grep` command, and
empirical farmrio evidence (file counts, byte deltas, before/after
numbers, cross-refs). Distributed into the existing topic files rather
than one new dump file, matching this repo's own index-per-topic
convention:

| File | New gotchas | Headline finding |
|---|---|---|
| `async-rendering.md` | #52–54, #73 | Dead 3-arg `ctx` section loaders
— 28-file sweep, one was a site-wide dead cookie-consent banner |
| `hydration-fixes.md` | #55–58 | `DeferredSectionWrapper` skeleton
remount/CLS (cross-ref #448) + a content-refresh-safe `Lazy.tsx` unwrap
pattern |
| `vtex-commerce.md` | #59–64 | CMS multivariate-flag resolver only
recognizes 2 of 7 real resolveTypes — silently drops content (blocker) |
| `css-styling.md` | #65–67 | Theme-conversion DaisyUI slot mismapping +
v5's silent dark-theme bundling |
| `worker-cloudflare.md` | #68–71 | Device-segmented edge-cache
poisoning via SWR revalidation (novel); server-only secrets reachable
from client bundle via the invoke dispatch table (security) |
| `storefront-patterns.md` | #72 | `sitemap.xml` not auto-wired |

`references/migration-learnings-staging.md` (new file) proposes the
index-per-target-file learnings convention as the **starting** pattern
for the next migration's own staging area — citing this epic's own flat
`LEARNINGS.md` (282,249 bytes / 3,875 lines / 103 entries, costing
target sessions 60k+ tokens just to search before it was restructured
mid-epic on 2026-07-30) as the empirical case for adopting it from day
one instead. Linked from `SKILL.md`'s reference index.

Two gotchas (#55, #59) reference upstream PRs/issues already filed from
this same migration:
**[#448](#448
(`DeferredSectionWrapper` fix, open) and
**[#391](#391
(URL param coercion, referenced by #61).

## Codemod / audit-rule proposals for `packages/blocks-cli`

Proposal only (per this migration's own DoD, implementation is a bonus,
not required) — each was hit ≥3 times independently across the farmrio
migration:

1. **Dead-arity section-loader detector** — AST walk for 3-arg `(props,
req, ctx)` loader exports, cross-referenced against
`registerSectionLoaders` calls and each file's real `__resolveType` (not
its file path) in `blocks.gen.json`. Would have caught all 28 candidate
files in gotcha #52 at migration time.
2. **`typeof X === "function"` guard sweep** — flag this pattern on any
value that originates from CMS section resolution (gotcha #54); recurred
independently in 6+ files across the epic.
3. **Controlled-input-missing-`onChange` sweep** — `checked={...}` JSX
prop with no sibling `onChange` (gotcha #58); found and fixed
independently 3 separate times.
4. **`LoadingFallback` wrapper-function → literal-alias codemod** —
rewrite `export function LoadingFallback(props) { return <X
{...props}/>; }` to `export const LoadingFallback = X;` (gotcha #56).
5. **Redirect self-loop lint rule** — flag any `blocks.gen.json`
redirect block where `normalize(from) === normalize(to)` after
case-folding (gotcha #60); found 3 live instances across 2 targets once
the check existed as an ad-hoc script.
6. **Image-dimension backfill from source headers** — generic
migration-time step parsing real JPEG/PNG dimensions from each unique
image URL's own file header and writing `width`/`height` back into CMS
content, instead of leaving every un-dimensioned image to hit the
CLS-safety-net fallback one page at a time (gotcha #67).
7. **`deco-post-cleanup --strict` comment/string-literal awareness** —
several existing audit rules (`deco-cx-runtime-api`,
`style-string-props`, `htmx-residue`) are literal-substring scans with
no AST/JSX awareness, so they false-positive on matches inside comments
or inside a `dangerouslySetInnerHTML` HTML string. Farmrio counts: 7
comment-only false positives on one rule, 4 on another, 4-of-6 on a
third.

## Parity-destined findings

Filed separately against `decocms/parity` (issue, cross-linked from
`migration/learnings/INDEX.md` in farmrio-storefront) rather than
bundled into this PR — covers `--fail-on` requiring `--ci`, `--pages`
not scoping `flows`, a `banner-aspect-ratio` check double-counting
infinite-carousel clones, a `lazy-section-presence` heuristic
incompatible with TanStack's transport, and LLM visual-diff
hallucination on downscaled full-page screenshots.

## Test plan

- [x] Docs-only change — no code paths affected, nothing to typecheck or
build
- [x] Every new gotcha cross-checked against the current `gotchas.md`
numbering (#51 was the prior max, confirmed via `grep -rn "^## #\?[0-9]"
*.md`)
- [x] Every code snippet reproduced from the source learnings files, not
invented — cross-checked against the cited
`migration/learnings/T<ID>.md` file in `deco-sites/farmrio-storefront`

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Consolidates Farm Rio Fresh→TanStack migration learnings into this skill
and adds 22 numbered gotchas (#52–#73). Also documents an
index-per-target-file staging convention to keep future migrations fast
and cheap.

- Adds gotchas across async/rendering, hydration, VTEX commerce,
CSS/DaisyUI, Worker/Cloudflare, and storefront patterns, covering issues
like pre-`#305` 3‑arg loader pitfalls, `DeferredSectionWrapper` CLS,
multivariate resolver gaps, sitemap wiring, cache behavior, and a
client-bundle secret leak. Cross‑refs: `#448` and
`#391`.
- Introduces `references/migration-learnings-staging.md` and links it
from `SKILL.md` to replace flat learnings with an index-per-target
approach.

**Doc updates since review**
- #52: Clarifies that `@decocms/blocks` now supports an optional 3rd
`ctx` arg when registered; positions the fix as a ctx‑free alternative
for pre‑`#305` or unregistered loaders.
- #61: Splits discovery into two valid `rg` commands.
- #63: Corrects variant‑trim filter to use `priceComponentType` (not
`@type`), ensuring installment entries are removed.
- #65: Adds runnable discovery steps (`grep` + `jq`) for DaisyUI slot
mapping.
- #66: Flags the dark‑theme auto‑bundling gotcha as DaisyUI v5‑only.
- #72: Adds a `worker-entry.ts` wiring example for `/sitemap.xml` and
fixes the import path to `@decocms/apps-vtex`.

<sup>Written for commit 919eb12.
Summary will update on new commits.</sup>

<a href="https://cubic.dev/pr/decocms/blocks/pull/457?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

---------

Co-authored-by: hugo-ccabral <[email protected]>
Co-authored-by: Claude Sonnet 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant