youraitools-api / tree / functions/cache.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
// Edge cache for discovery documents (Cache API, caches.default). Caching only, never limits callers.
// - Aggregates (/.well-known/x402, /openapi.json) fan out to every tool Worker; cached so a crawler hit costs
//   1 Pages invocation instead of ~19. Fresh for 5 min, then stale-while-revalidate (background refresh via
//   waitUntil). A refresh that fails or comes back incomplete never replaces the last good copy.
// - An incomplete aggregate (some tool failed) is only ever served/cached for 30 s, and only when no good copy exists.
// - Per-tool static discovery routes (GET /<tool>/, /.well-known/x402, /openapi.json, favicons, og images):
//   same 5-min SWR. Never cached: anything with a query string, payment/auth headers, non-200 (402!), POST,
//   MCP, previews, verdicts, cards, no-store/private/set-cookie responses.
export const TTL = 300;          // seconds a good copy counts as fresh
export const PARTIAL_TTL = 30;   // seconds an incomplete aggregate counts as fresh
export const KEEP = 86400;       // how long the Cache API keeps a copy (the last-good fallback)

export const STATIC_REST = /^\/(|\.well-known\/x402|openapi\.json|favicon\.ico|favicon\.svg|og\/[a-z]+\.png)$/;
const PAY_HEADERS = ['authorization', 'payment-signature', 'x-payment', 'cookie'];

/** True when a proxied /<tool><rest> request may be served from cache. */
export function cacheableToolRequest(request, rest) {
  if (!['GET', 'HEAD'].includes(request.method)) return false;
  const url = new URL(request.url);
  if (url.search) return false;
  if (!STATIC_REST.test(rest)) return false;
  return !PAY_HEADERS.some((h) => request.headers.has(h));
}

/** True when an upstream response may be stored (200, no payment/cookie/no-store, no Vary beyond Accept(-Encoding)). */
export function storable(res, { acceptInKey = false } = {}) {
  if (res.status !== 200) return false;
  const h = res.headers;
  if (h.has('set-cookie') || h.has('payment-required') || h.has('payment-response') || h.has('x-payment-response')) return false;
  if (/no-store|private|no-cache/i.test(h.get('cache-control') || '')) return false;
  const vary = (h.get('vary') || '').toLowerCase().split(',').map((s) => s.trim()).filter(Boolean);
  return vary.every((v) => v === 'accept-encoding' || (v === 'accept' && acceptInKey));
}

export function cacheKey(url, { accept } = {}) {
  const u = new URL(url);
  const k = new URL(`${u.origin}/__yat-cache/v1${u.pathname}`); // same zone hostname as the request
  if (accept !== undefined) k.searchParams.set('a', String(accept || '').toLowerCase().replace(/\s+/g, '').slice(0, 256));
  return new Request(k.toString(), { method: 'GET' });
}

const store = () => (typeof caches !== 'undefined' && caches?.default ? caches.default : null);

function withHeaders(res, set, { head = false } = {}) {
  const headers = new Headers(res.headers);
  for (const [k, v] of Object.entries(set)) if (v === null) headers.delete(k); else headers.set(k, v);
  return new Response(head ? null : res.body, { status: res.status, statusText: res.statusText, headers });
}

/**
 * Serve key from cache with SWR. produce() -> Promise<{ res: Response, complete: boolean }>.
 * clientCC(complete) -> Cache-Control for the caller (null = keep upstream's).
 */
export async function swr({ key, produce, waitUntil, head = false, clientCC = (c) => (c ? `public, max-age=${TTL}` : `public, max-age=${PARTIAL_TTL}`) }) {
  const cache = store();
  const now = Date.now();
  // Caller-facing Cache-Control: clientCC(complete), else the upstream value (kept in x-yat-cc while stored).
  const out = (res, state, complete, extra = {}) => withHeaders(res, { 'x-yat-cache': state, 'cache-control': clientCC(complete) || res.headers.get('x-yat-cc') || res.headers.get('cache-control'), 'x-yat-stored-at': null, 'x-yat-complete': null, 'x-yat-cc': null, ...extra }, { head });
  if (!cache) { const p = await produce(); return p.storable === false ? p.res : out(p.res, 'BYPASS', p.complete); }

  let hit = null;
  try { hit = await cache.match(key); } catch { hit = null; }
  const put = async (p) => {
    const body = await p.res.clone().arrayBuffer();
    const headers = new Headers(p.res.headers);
    headers.set('x-yat-cc', p.res.headers.get('cache-control') || `public, max-age=${TTL}`);
    headers.set('cache-control', `public, max-age=${KEEP}`);
    headers.set('x-yat-stored-at', String(Date.now()));
    headers.set('x-yat-complete', p.complete ? '1' : '0');
    headers.delete('set-cookie');
    await cache.put(key, new Response(body, { status: 200, headers }));
  };

  if (hit) {
    const complete = hit.headers.get('x-yat-complete') === '1';
    const age = (now - Number(hit.headers.get('x-yat-stored-at') || 0)) / 1000;
    const fresh = age >= 0 && age < (complete ? TTL : PARTIAL_TTL);
    const ageH = { age: String(Math.max(0, Math.floor(age))) };
    if (fresh) return out(hit, 'HIT', complete, ageH);
    // Stale: serve it now, refresh in the background. Never overwrite a good copy with a partial/failed one.
    const refresh = (async () => {
      try {
        const p = await produce();
        if (p.storable !== false && (p.complete || !complete)) await put(p);
      } catch { /* keep last good copy */ }
    })();
    if (typeof waitUntil === 'function') waitUntil(refresh); else await refresh;
    return out(hit, 'STALE', complete, ageH);
  }

  const p = await produce();
  if (p.storable === false) return p.res; // 402s, errors, no-store, HEAD: passed through untouched, never cached
  const w = put(p).catch(() => {});
  if (typeof waitUntil === 'function') waitUntil(w); else await w;
  return out(p.res, 'MISS', p.complete);
}

agentgate-source: code mirror on Cloudflare Pages. All repos