Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: implement direct-insert timeout for usage event logging; add regression test for x402-pay feed degradation
zprv619212e72bc7
diff --git a/.vercelignore b/.vercelignoreindex 51e16e34b..e190bc623 100644--- a/.vercelignore+++ b/.vercelignore@@ -24,7 +24,17 @@ specsexamples/*!examples/skillsexamples/skills/*+# Keep every skill that api/_lib/skill-runtime.js can dynamically import(). The+# import paths are computed from SKILL_MAP, so Vercel's static tracer cannot see+# them; includeFiles bundles them, but ONLY if they survive this upload filter.+# pump-fun-strategy alone is not enough — it invokes pump-fun / pump-fun-trade /+# solana-wallet at runtime (strategy-backtest scan, live trades). Dropping any+# of these reintroduces "Cannot find module .../<skill>/handlers.js" 502s.!examples/skills/pump-fun-strategy+!examples/skills/pump-fun+!examples/skills/pump-fun-trade+!examples/skills/pump-fun-compose+!examples/skills/solana-walletpromptscontractssdkdiff --git a/api/_lib/cache.js b/api/_lib/cache.jsindex 179ba9a12..c0df98452 100644--- a/api/_lib/cache.js+++ b/api/_lib/cache.js@@ -96,8 +96,14 @@ function redisConfigured() {// endpoint whose whole point in calling us was to be fast. Cap every command so a// degraded Redis fails fast into the in-memory fallback instead of stalling the// request. 3s is far longer than a healthy REST GET/SET yet well under any caller's-// budget.-const REDIS_CMD_TIMEOUT_MS = 3_000;+// budget. Tunable per deploy via CACHE_REDIS_CMD_TIMEOUT_MS (resolved + clamped in+// _lib/env.js) so a cache store in a region far from the function region — the+// cause of legitimate "operation aborted due to timeout" SET failures — can be+// given more headroom without a code change. Read per command (a cheap env get) so+// the knob takes effect on the next request, not only on cold start.+function redisCmdTimeoutMs() {+ return env.CACHE_REDIS_CMD_TIMEOUT_MS;+}// Circuit breaker around the Upstash REST call. A degraded store (commands// timing out at REDIS_CMD_TIMEOUT_MS rather than rejecting promptly) otherwise@@ -214,7 +220,7 @@ async function redisCmd(args) {'content-type': 'application/json',},body: JSON.stringify(args),- signal: AbortSignal.timeout(REDIS_CMD_TIMEOUT_MS),+ signal: AbortSignal.timeout(redisCmdTimeoutMs()),});if (!r.ok) throw new Error(`upstash ${r.status}: ${await r.text().catch(() => '')}`);const json = await r.json();diff --git a/api/_lib/env.js b/api/_lib/env.jsindex ae7e621e2..18110b752 100644--- a/api/_lib/env.js+++ b/api/_lib/env.js@@ -224,6 +224,22 @@ export const env = {return pickPair(REDIS_CACHE_SOURCES).token;},+ // Per-command timeout (ms) for the best-effort cache's Upstash REST calls+ // (api/_lib/cache.js). A cache round-trip must be fast or fall back to memory;+ // the cap stops a TCP stall from hanging a fast endpoint until its hard+ // maxDuration. The default (3000) is far longer than a healthy REST GET/SET,+ // but when the cache store sits in a region far from the function region+ // (e.g. Upstash not co-located with iad1) large best-effort SETs can+ // legitimately exceed it and surface as "operation aborted due to timeout".+ // Exposed as an env knob so ops can raise it (region latency) or lower it+ // (fail faster to memory) without a code deploy. Clamped to [500, 30000];+ // anything unparseable falls back to the default.+ get CACHE_REDIS_CMD_TIMEOUT_MS() {+ const n = Number(opt('CACHE_REDIS_CMD_TIMEOUT_MS'));+ if (!Number.isFinite(n)) return 3000;+ return Math.min(30_000, Math.max(500, Math.round(n)));+ },+// ── Upstash quota-burn visibility (api/_lib/redis-usage.js) ──────────────// The free plan ceils at 500k commands/month; when it is exhausted every// critical limiter fails closed and all paid forge + x402 flows 503 (thediff --git a/api/_lib/usage.js b/api/_lib/usage.jsindex 436b62fc2..9acf57df3 100644--- a/api/_lib/usage.js+++ b/api/_lib/usage.js@@ -27,6 +27,15 @@ const BUFFER_MAX = 10_000; // safety cap — drop oldest when exceededconst BUFFER_TTL_S = 7200; // 2h — events should never sit this longconst FLUSH_DEDUP_WINDOW_MS = 60_000; // one QStash flush job per minute+// Per-event budget for the direct-insert fallback (Redis buffer down/absent).+// Far below the 15s default DB budget on purpose: when the buffer is unavailable+// every usage event takes this path, and a slow Neon spell must never hold a+// serverless invocation open for 15s per event — that storm of 15000ms-deadline+// writes was stalling the avatar API. Telemetry is best-effort, so a bounded miss+// beats a wedged request. The batch flusher (flushUsageBuffer) keeps the default+// budget — it owns its own deadline and isn't on the request path.+const DIRECT_INSERT_TIMEOUT_MS = 2_500;+function normalizeEvt(evt) {return {userId: evt.userId ?? null,@@ -48,7 +57,7 @@ function normalizeEvt(evt) {};}-async function insertEvent(evt) {+async function insertEvent(evt, opts) {await withDbRetry(() => sql`insert into usage_events (user_id, api_key_id, client_id, avatar_id, agent_id, kind, tool, status, bytes, latency_ms, meta, provider, model, input_tokens, output_tokens, cost_micro_usd)values (@@ -69,7 +78,7 @@ async function insertEvent(evt) {${evt.outputTokens},${evt.costMicroUsd})- `);+ `, opts);}function triggerFlushJob() {@@ -105,9 +114,11 @@ export function recordEvent(evt) {console.warn('[usage] buffer push failed, falling back to direct insert', err?.message);}}- // Direct-insert fallback when Redis is absent or the push fails.+ // Direct-insert fallback when Redis is absent or the push fails. Bounded by+ // a short per-event timeout so a slow DB can't stall the (already-detached)+ // request work for 15s — the buffer-down path must stay cheap.try {- await insertEvent(normalizeEvt(evt));+ await insertEvent(normalizeEvt(evt), { timeoutMs: DIRECT_INSERT_TIMEOUT_MS });} catch (err) {console.warn('[usage] write failed', err?.message);}diff --git a/tests/api/x402-pay-feed-degraded.test.js b/tests/api/x402-pay-feed-degraded.test.jsnew file mode 100644index 000000000..fdb924fde--- /dev/null+++ b/tests/api/x402-pay-feed-degraded.test.js@@ -0,0 +1,104 @@+// /api/x402-pay?feed=1 — the public activity feed must degrade gracefully when+// Upstash Redis is unavailable (wrong credentials → WRONGPASS, outage, etc).+//+// Regression: a Redis LRANGE that throws used to escape readFeed() to the top of+// the handler and surface as an unhandled 500 (35× `UpstashError: WRONGPASS …+// command was: ["lrange",...]` in prod). The rate-limiter already degraded, but+// the feed read did not. The endpoint MUST return 200 with a (possibly empty,+// in-memory) feed when Redis is down — never 500.+//+// We mock getRedis() to return a client whose lrange rejects exactly the way a+// bad-password Upstash client does, and assert the GET still answers 200.++import { describe, it, expect, vi, beforeEach } from 'vitest';++// Auth/rate-limit/db are not exercised on the GET feed path, but the module+// imports them at load time — stub them so the import is side-effect free.+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: async () => null,+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ x402PayIp: vi.fn(async () => ({ success: true })),+ x402PayGlobal: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '127.0.0.1',+}));++const warnMock = vi.fn();+vi.mock('../../api/_lib/usage.js', () => ({+ logger: () => ({ info: vi.fn(), warn: warnMock, error: vi.fn() }),+ recordEvent: vi.fn(),+}));+vi.mock('../../api/_lib/db.js', () => ({ sql: vi.fn(async () => []) }));++// A Redis client that is present (so readFeed takes the Redis branch) but whose+// every command rejects the way a WRONGPASS-authenticated Upstash client does.+const lrangeMock = vi.fn(async () => {+ throw new Error('WRONGPASS invalid or missing auth token, command was: ["lrange","x402:pay:feed","0","49"]');+});+vi.mock('../../api/_lib/redis.js', () => ({+ getRedis: () => ({+ lrange: (...a) => lrangeMock(...a),+ lpush: async () => { throw new Error('WRONGPASS'); },+ ltrim: async () => { throw new Error('WRONGPASS'); },+ get: async () => { throw new Error('WRONGPASS'); },+ set: async () => { throw new Error('WRONGPASS'); },+ }),+}));++const { default: handler } = await import('../../api/x402-pay.js');++function makeGet(url) {+ return {+ url,+ method: 'GET',+ headers: { host: 'x' },+ query: {},+ on() { return this; },+ };+}+function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },+ getHeader(k) { return this._h[k.toLowerCase()]; },+ end(b) { this._body = b; },+ };+}+async function call(url) {+ const res = makeRes();+ await handler(makeGet(url), res);+ let body = null;+ try { body = JSON.parse(res._body); } catch {}+ return { res, body };+}++beforeEach(() => {+ warnMock.mockReset();+ lrangeMock.mockClear();+});++describe('GET /api/x402-pay?feed=1 with Redis down', () => {+ it('returns 200 with a degraded (empty/stale) feed, never a 500', async () => {+ const { res, body } = await call('/api/x402-pay?feed=1');+ expect(res.statusCode).toBe(200);+ expect(body).toBeTruthy();+ expect(Array.isArray(body.items)).toBe(true);+ // The Redis read was attempted (and failed) — proving we exercised the+ // degraded path rather than skipping Redis entirely.+ expect(lrangeMock).toHaveBeenCalled();+ // The failure is logged as a warning, not thrown as an unhandled 500.+ expect(warnMock).toHaveBeenCalledWith('feed_read_failed', expect.any(Object));+ });++ it('honours the limit param while degraded', async () => {+ const { res, body } = await call('/api/x402-pay?feed=1&limit=5');+ expect(res.statusCode).toBe(200);+ expect(Array.isArray(body.items)).toBe(true);+ expect(body.items.length).toBeLessThanOrEqual(5);+ });+});