Skip to content

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.

Enhance CoinGecko cache mechanism and add commit Open Graph endpoint

nirholas2d6cdb3b6edd
diff --git a/api/_lib/coingecko.js b/api/_lib/coingecko.js
index ba94cdf51..8707409e8 100644
--- a/api/_lib/coingecko.js
+++ b/api/_lib/coingecko.js
@@ -9,8 +9,17 @@
export const COINGECKO_BASE = 'https://api.coingecko.com/api/v3';
-const _cache = new Map(); // key → { value, expiresAt }
-const MAX_ENTRIES = 256;
+// key → { value, expiresAt, staleUntil }. Entries stay readable past expiresAt
+// (up to staleUntil) so a rate-limited or flaky upstream serves last-good data
+// instead of cascading into a user-facing 502. CoinGecko's free/demo tiers cap
+// at ~30 req/min; broad coin-page crawling saturates that, and without a stale
+// buffer every /coin/:id detail call would 502 during the storm.
+const _cache = new Map();
+const MAX_ENTRIES = 512;
+// How long past freshness a cached value may still be served on an upstream
+// fault. Coin metadata (description, dev/community stats, market cap) tolerates
+// minutes of staleness far better than an outage.
+const STALE_MS = 30 * 60_000;
function headers() {
const h = { accept: 'application/json', 'user-agent': 'three.ws/1.0' };
@@ -28,18 +37,37 @@ export async function geckoFetch(path, { ttlMs = 60_000, timeoutMs = 8000 } = {}
const now = Date.now();
const hit = _cache.get(path);
if (hit && hit.expiresAt > now) return hit.value;
+ // A still-usable stale entry lets us ride out a throttled/failing upstream.
+ const stale = hit && hit.staleUntil > now ? hit.value : null;
- const resp = await fetch(`${COINGECKO_BASE}${path}`, {
- headers: headers(),
- signal: AbortSignal.timeout(timeoutMs),
- });
+ let resp;
+ try {
+ resp = await fetch(`${COINGECKO_BASE}${path}`, {
+ headers: headers(),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (netErr) {
+ // Network failure or timeout — serve stale if we have it, else surface.
+ if (stale !== null) {
+ console.warn(`[coingecko] ${path} fetch failed (${netErr?.name || 'error'}); serving stale`);
+ return stale;
+ }
+ throw netErr;
+ }
if (!resp.ok) {
+ // 404 is a genuine "unknown coin" signal callers must see; never mask it
+ // with stale data. For throttling (429) or upstream trouble (5xx), a
+ // recent value beats an outage — serve it and keep the page alive.
+ if (resp.status !== 404 && stale !== null) {
+ console.warn(`[coingecko] ${path} → ${resp.status}; serving stale`);
+ return stale;
+ }
const err = new Error(`CoinGecko ${resp.status} for ${path}`);
err.status = resp.status;
throw err;
}
const value = await resp.json();
- _cache.set(path, { value, expiresAt: now + ttlMs });
+ _cache.set(path, { value, expiresAt: now + ttlMs, staleUntil: now + ttlMs + STALE_MS });
if (_cache.size > MAX_ENTRIES) _cache.delete(_cache.keys().next().value);
return value;
}
diff --git a/api/_lib/commit-feed-push.js b/api/_lib/commit-feed-push.js
index b47ca2fe8..edade0ea0 100644
--- a/api/_lib/commit-feed-push.js
+++ b/api/_lib/commit-feed-push.js
@@ -15,6 +15,7 @@
import { sql } from './db.js';
const REPO = 'nirholas/three.ws';
+const BASE = 'https://three.ws';
const TELEGRAM_LIMIT = 15; // per run; Bot API allows ~20 msg/min per chat
const TELEGRAM_PACE_MS = 3500;
const LOCK_KEY = 'commit_feed_push_lock';
diff --git a/api/coin/detail.js b/api/coin/detail.js
index e0133dbbf..cac628a69 100644
--- a/api/coin/detail.js
+++ b/api/coin/detail.js
@@ -156,7 +156,7 @@ export default wrap(async (req, res) => {
try {
return json(res, 200, await buildCoinDetail({ id, contract }), {
- 'cache-control': 'public, max-age=30, s-maxage=60, stale-while-revalidate=300',
+ 'cache-control': 'public, max-age=60, s-maxage=180, stale-while-revalidate=900',
});
} catch (err) {
if (err?.status === 404)
diff --git a/api/commit-og.js b/api/commit-og.js
new file mode 100644
index 000000000..c26c5ed31
--- /dev/null
+++ b/api/commit-og.js
@@ -0,0 +1,104 @@
+// api/commit-og.js — social-share landing for a single commit in the
+// auto-posted commit feed (api/_lib/commit-feed-push.js). Its only job is to
+// carry per-commit Open Graph tags so Telegram, X, and iMessage render a
+// branded three.ws poster card for each commit post instead of GitHub's
+// generic repo social card. Humans who click the preview are redirected
+// straight to the commit on GitHub; crawlers read the OG tags and stop.
+//
+// Params (all supplied by the commit-feed cron, but the endpoint is public so
+// every value is validated / escaped):
+// ?sha=<full or short commit sha> the only source of the redirect target
+// ?t=<headline> ?d=<description> ?date=<YYYY-MM-DD> ?author=<login>
+//
+// The poster itself is the existing api/page-og.js renderer, driven with the
+// `commit` section so every commit card shares one accent family.
+
+const REPO = 'nirholas/three.ws';
+const BASE = 'https://three.ws';
+
+// Escape for HTML text nodes and double-quoted attribute values. OG content
+// lives in attributes, so " and ' must both be neutralised.
+function esc(s) {
+ return String(s || '').replace(
+ /[<>&"']/g,
+ (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+function clamp(s, n) {
+ s = String(s || '').trim();
+ return s.length <= n ? s : s.slice(0, n - 1).trimEnd() + '…';
+}
+
+export default function handler(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const q = url.searchParams;
+
+ // The redirect target is derived ONLY from a validated sha, never from a
+ // caller-supplied URL, so this page can't be turned into an open redirect.
+ const rawSha = String(q.get('sha') || '').toLowerCase();
+ const sha = /^[0-9a-f]{7,40}$/.test(rawSha) ? rawSha : '';
+ const commitUrl = sha
+ ? `https://github.com/${REPO}/commit/${sha}`
+ : `https://github.com/${REPO}/commits/main`;
+
+ const headline = clamp(q.get('t') || 'New commit', 60);
+ const body = clamp(q.get('d') || '', 140);
+ const date = clamp(q.get('date') || '', 10);
+ const author = clamp(q.get('author') || '', 40);
+
+ // Branded poster: reuse the generic OG renderer with the commit section.
+ const poster =
+ `${BASE}/api/page-og?s=commit` +
+ `&t=${encodeURIComponent(headline)}` +
+ `&d=${encodeURIComponent(body)}` +
+ `&p=${encodeURIComponent('/changelog')}`;
+
+ const title = esc(headline);
+ const descParts = [body, [date, author].filter(Boolean).join(' · ')].filter(Boolean);
+ const description = esc(descParts.join(' — '));
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/html; charset=utf-8');
+ res.setHeader('cache-control', 'public, max-age=3600, s-maxage=604800, stale-while-revalidate=86400');
+ res.end(`<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>${title} · three.ws</title>
+<meta name="description" content="${description}">
+<meta property="og:type" content="article">
+<meta property="og:site_name" content="three.ws">
+<meta property="og:title" content="${title}">
+<meta property="og:description" content="${description}">
+<meta property="og:url" content="${esc(commitUrl)}">
+<meta property="og:image" content="${esc(poster)}">
+<meta property="og:image:width" content="1200">
+<meta property="og:image:height" content="630">
+<meta name="twitter:card" content="summary_large_image">
+<meta name="twitter:title" content="${title}">
+<meta name="twitter:description" content="${description}">
+<meta name="twitter:image" content="${esc(poster)}">
+<meta http-equiv="refresh" content="0; url=${esc(commitUrl)}">
+<link rel="canonical" href="${esc(commitUrl)}">
+<style>
+ html,body{margin:0;height:100%;background:#050507;color:#ebebf5;
+ font-family:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}
+ main{min-height:100%;display:flex;flex-direction:column;align-items:center;
+ justify-content:center;gap:14px;text-align:center;padding:24px}
+ a{color:#818cf8;font-weight:600;text-decoration:none}
+ a:hover{text-decoration:underline}
+ p{color:rgba(235,235,245,.55);margin:0}
+</style>
+</head>
+<body>
+<main>
+ <h1 style="margin:0;font-size:28px">${title}</h1>
+ <p>Opening the commit on GitHub…</p>
+ <a href="${esc(commitUrl)}">${esc(commitUrl.replace('https://', ''))}</a>
+</main>
+<script>location.replace(${JSON.stringify(commitUrl)});</script>
+</body>
+</html>`);
+}
diff --git a/api/page-og.js b/api/page-og.js
index 95b41e4ef..e4418b22b 100644
--- a/api/page-og.js
+++ b/api/page-og.js
@@ -50,6 +50,7 @@ const SECTIONS = {
blog: { label: 'Blog', accent: '#a78bfa' },
legal: { label: 'Legal', accent: '#94a3b8' },
machine: { label: 'Reference', accent: '#9ca3af' },
+ commit: { label: 'Commit', accent: '#818cf8' },
};
const DEFAULT_SECTION = { label: 'three.ws', accent: '#8b5cf6' };