youraitools-api / tree / test/cache.test.js ยท raw (this view has old GitHub links rewritten for the mirror; raw is byte-exact)
import test from 'node:test';
import assert from 'node:assert/strict';
import { onRequest } from '../functions/[[path]].js';
import { TOOLS, SERVICES } from '../functions/tools.js';

// In-memory stand-in for caches.default (GET keys by URL).
function fakeCache() {
  const m = new Map();
  return { m, async match(req) { const e = m.get(req.url); return e ? new Response(e.body, { status: e.status, headers: e.headers }) : undefined; },
    async put(req, res) { m.set(req.url, { body: await res.arrayBuffer(), status: res.status, headers: [...res.headers] }); } };
}
function setup({ fail = new Set() } = {}) {
  const log = []; const cache = fakeCache(); globalThis.caches = { default: cache };
  const svc = (name) => ({ async fetch(req) {
    const u = new URL(req.url); log.push(`${name} ${req.method} ${u.pathname}${u.search}`);
    if (fail.has(name)) return new Response('boom', { status: 503 });
    const base = `https://${req.headers.get('x-forwarded-host')}${req.headers.get('x-forwarded-prefix')}`;
    if (u.pathname === '/.well-known/x402') return Response.json({ version: 1, resources: [`${base}/v1/x`] }, { headers: { 'cache-control': 'public, max-age=300' } });
    if (u.pathname === '/openapi.json') return Response.json({ openapi: '3.1.0', servers: [{ url: base }], paths: { '/v1/x': { get: {} } } });
    if (u.pathname === '/' && !u.search) return /text\/html/.test(req.headers.get('accept') || '') ? new Response('<h1>html</h1>', { headers: { 'content-type': 'text/html', vary: 'Accept' } }) : Response.json({ name }, { headers: { vary: 'Accept' } });
    if (u.pathname === '/health') return Response.json({ ok: true }, { headers: { 'cache-control': 'no-store' } });
    return new Response('{}', { status: 402, headers: { 'content-type': 'application/json', 'PAYMENT-REQUIRED': `pr-${log.length}` } });
  } });
  const env = { PUBLIC_HOST: 'api.youraitools.co' };
  for (const t of [...TOOLS, ...SERVICES]) env[t.binding] = svc(t.prefix);
  const pending = [];
  const call = (path, init = {}) => onRequest({ request: new Request(`https://api.youraitools.co${path}`, init), env, waitUntil: (p) => pending.push(p) });
  return { log, cache, call, pending, settle: () => Promise.all(pending.splice(0)) };
}
const N = TOOLS.length + SERVICES.length;

test('aggregate /.well-known/x402 and /openapi.json: MISS fans out once, then HIT with 0 Worker calls', async () => {
  const s = setup();
  for (const p of ['/.well-known/x402', '/openapi.json']) {
    s.log.length = 0;
    const a = await s.call(p); const ab = await a.text(); await s.settle();
    assert.equal(a.headers.get('x-yat-cache'), 'MISS'); assert.equal(s.log.length, N);
    assert.equal(a.headers.get('cache-control'), 'public, max-age=300');
    const b = await s.call(p); const bb = await b.text();
    assert.equal(b.headers.get('x-yat-cache'), 'HIT'); assert.equal(s.log.length, N, 'no extra Worker calls');
    assert.equal(bb, ab); assert.equal(b.headers.get('cache-control'), 'public, max-age=300');
    assert.equal(b.headers.get('content-type'), 'application/json; charset=utf-8'); assert.equal(b.headers.get('access-control-allow-origin'), '*');
    assert.equal(b.headers.get('x-yat-stored-at'), null);
  }
  const h = await s.call('/.well-known/x402', { method: 'HEAD' });
  assert.equal(h.headers.get('x-yat-cache'), 'HIT'); assert.equal(h.body, null);
});

test('stale copy is served while a background refresh replaces it', async () => {
  const s = setup();
  await (await s.call('/.well-known/x402')).text(); await s.settle();
  const [k, e] = [...s.cache.m.entries()][0];
  e.headers = e.headers.map(([n, v]) => [n, n === 'x-yat-stored-at' ? String(Date.now() - 301000) : v]);
  s.log.length = 0;
  const r = await s.call('/.well-known/x402');
  assert.equal(r.headers.get('x-yat-cache'), 'STALE');
  await s.settle(); assert.equal(s.log.length, N);
  assert.ok(Date.now() - Number(new Map(s.cache.m.get(k).headers).get('x-yat-stored-at')) < 5000);
  assert.equal((await s.call('/.well-known/x402')).headers.get('x-yat-cache'), 'HIT');
});

test('incomplete aggregate: 30 s TTL when nothing good exists; never replaces a good copy', async () => {
  const fail = new Set();
  const s = setup({ fail });
  fail.add('solverdict');
  const p = await s.call('/.well-known/x402'); const pj = await p.json(); await s.settle();
  assert.equal(p.headers.get('cache-control'), 'public, max-age=30'); assert.equal(p.headers.get('x-yat-partial'), 'solverdict');
  assert.ok(pj.tools.find((t) => t.name && t.error));
  // good copy arrives once the partial is stale
  fail.clear();
  const [k, e] = [...s.cache.m.entries()][0];
  e.headers = e.headers.map(([n, v]) => [n, n === 'x-yat-stored-at' ? String(Date.now() - 31000) : v]);
  assert.equal((await s.call('/.well-known/x402')).headers.get('x-yat-cache'), 'STALE'); await s.settle();
  const good = await s.call('/.well-known/x402'); assert.equal(good.headers.get('x-yat-cache'), 'HIT'); assert.equal(good.headers.get('cache-control'), 'public, max-age=300');
  const goodBody = await good.text(); assert.ok(!/"error"/.test(goodBody));
  // later refresh fails partially: last good copy is kept
  fail.add('payguard');
  const e2 = s.cache.m.get(k); e2.headers = e2.headers.map(([n, v]) => [n, n === 'x-yat-stored-at' ? String(Date.now() - 301000) : v]);
  const st = await s.call('/.well-known/x402'); assert.equal(st.headers.get('x-yat-cache'), 'STALE'); assert.equal(await st.text(), goodBody); await s.settle();
  assert.equal(new Map(s.cache.m.get(k).headers).get('x-yat-complete'), '1');
  assert.equal(await (await s.call('/.well-known/x402')).text(), goodBody);
});

test('per-tool discovery routes are cached; 402/paid, previews, queries, payment headers and POST never are', async () => {
  const s = setup();
  for (const p of ['/agentready/.well-known/x402', '/agentready/openapi.json', '/solverdict/.well-known/x402']) {
    s.log.length = 0;
    const a = await s.call(p); await a.text(); await s.settle();
    const b = await s.call(p);
    assert.equal(a.headers.get('x-yat-cache'), 'MISS'); assert.equal(b.headers.get('x-yat-cache'), 'HIT'); assert.equal(s.log.length, 1, p);
    assert.match(b.headers.get('cache-control'), /^public, max-age=300$/);
  }
  // landing keyed by Accept
  const html = await s.call('/payguard/', { headers: { accept: 'text/html' } }); assert.equal(await html.text(), '<h1>html</h1>'); await s.settle();
  const js = await s.call('/payguard', { headers: { accept: 'application/json' } }); assert.deepEqual(await js.json(), { name: 'payguard' }); await s.settle();
  assert.equal((await s.call('/payguard/', { headers: { accept: 'text/html' } })).headers.get('x-yat-cache'), 'HIT');
  assert.equal(await (await s.call('/payguard/', { headers: { accept: 'application/json' } })).text(), '{"name":"payguard"}');
  // never cached
  for (const [p, init] of [['/agentready/v1/audit', {}], ['/solverdict/v1/lite', { method: 'POST', body: '{}' }], ['/agentready/.well-known/x402?x=1', {}],
    ['/agentready/.well-known/x402', { headers: { 'PAYMENT-SIGNATURE': 'sig' } }], ['/agentready/.well-known/x402', { headers: { authorization: 'Bearer k' } }], ['/payguard/health', {}], ['/payguard/mcp', { method: 'POST', body: '{}' }]]) {
    s.log.length = 0;
    const a = await s.call(p, init); const b = await s.call(p, init); await s.settle();
    assert.equal(s.log.length, 2, `${p} must hit the Worker every time`);
    assert.equal(a.headers.get('x-yat-cache'), null); assert.equal(b.headers.get('x-yat-cache'), null);
  }
  const p1 = await s.call('/agentready/v1/audit'); const p2 = await s.call('/agentready/v1/audit');
  assert.equal(p1.status, 402); assert.notEqual(p1.headers.get('PAYMENT-REQUIRED'), p2.headers.get('PAYMENT-REQUIRED'), 'fresh 402 each time');
  assert.equal(p1.headers.get('cache-control'), null, '402 headers untouched');
  for (const k of s.cache.m.keys()) assert.ok(!/\/v1\/|mcp|health|x=1/.test(k.replace('https://api.youraitools.co/__yat-cache/v1/', '').replace(/\?a=.*/, '')), k);
});

test('no Cache API available: everything still works (BYPASS)', async () => {
  const s = setup(); globalThis.caches = undefined;
  const r = await s.call('/.well-known/x402'); assert.equal(r.status, 200); assert.equal(r.headers.get('x-yat-cache'), 'BYPASS');
  const p = await s.call('/agentready/v1/audit'); assert.equal(p.status, 402);
});

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