- Fastify + TypeScript service in bridge/ listening on port 3200 - WordPress REST API client with _embed support and data normalization - Redis stale-while-revalidate cache with in-process Map fallback - Domain routing: reads config/domains/<host>.json per Host header - Routes: /homepage, /articles, /articles/:slug, /articles/:slug/related, /categories, /categories/:slug, /trending, /api/tags, /api/media/:id, /api/site-config, /health - /api/posts and /api/categories aliases redirect to canonical routes - Rate limiting via @fastify/rate-limit; CORS via @fastify/cors - Error handling: WP unavailable → serve stale cache or 503 - Domain configs for localhost and newsproject.bitreport.pt Co-Authored-By: Paperclip <[email protected]> Made-with: Cursor
140 lines
3.6 KiB
TypeScript
140 lines
3.6 KiB
TypeScript
import { Redis } from 'ioredis';
|
|
|
|
interface CacheEntry {
|
|
data: unknown;
|
|
stale_at: number;
|
|
expires_at: number;
|
|
}
|
|
|
|
const FRESH_TTL_MS = (parseInt(process.env['CACHE_FRESH_TTL'] ?? '60', 10)) * 1000;
|
|
const STALE_TTL_MS = (parseInt(process.env['CACHE_STALE_TTL'] ?? '300', 10)) * 1000;
|
|
|
|
// In-process fallback map (used when Redis is unavailable or not configured)
|
|
const local_map = new Map<string, CacheEntry>();
|
|
|
|
let redis_client: Redis | null = null;
|
|
|
|
function get_redis(): Redis | null {
|
|
const url = process.env['REDIS_URL'];
|
|
if (!url) return null;
|
|
|
|
if (redis_client) return redis_client;
|
|
|
|
redis_client = new Redis(url, {
|
|
lazyConnect: true,
|
|
enableOfflineQueue: false,
|
|
maxRetriesPerRequest: 1,
|
|
});
|
|
|
|
redis_client.on('error', (err: Error) => {
|
|
// Log but do not crash — fall back to local cache
|
|
console.error('[cache] Redis error, falling back to in-process cache:', err.message);
|
|
});
|
|
|
|
return redis_client;
|
|
}
|
|
|
|
async function read_redis(key: string): Promise<CacheEntry | null> {
|
|
const redis = get_redis();
|
|
if (!redis) return null;
|
|
try {
|
|
const raw = await redis.get(key);
|
|
if (!raw) return null;
|
|
return JSON.parse(raw) as CacheEntry;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
async function write_redis(key: string, entry: CacheEntry): Promise<void> {
|
|
const redis = get_redis();
|
|
if (!redis) return;
|
|
try {
|
|
const ttl_seconds = Math.ceil((entry.expires_at - Date.now()) / 1000);
|
|
if (ttl_seconds <= 0) return;
|
|
await redis.set(key, JSON.stringify(entry), 'EX', ttl_seconds);
|
|
} catch {
|
|
// ignore write failures
|
|
}
|
|
}
|
|
|
|
async function read_local(key: string): Promise<CacheEntry | null> {
|
|
return local_map.get(key) ?? null;
|
|
}
|
|
|
|
function write_local(key: string, entry: CacheEntry): void {
|
|
local_map.set(key, entry);
|
|
}
|
|
|
|
async function get_entry(key: string): Promise<CacheEntry | null> {
|
|
const redis_entry = await read_redis(key);
|
|
if (redis_entry) return redis_entry;
|
|
return read_local(key);
|
|
}
|
|
|
|
async function set_entry(key: string, data: unknown): Promise<void> {
|
|
const now = Date.now();
|
|
const entry: CacheEntry = {
|
|
data,
|
|
stale_at: now + FRESH_TTL_MS,
|
|
expires_at: now + STALE_TTL_MS,
|
|
};
|
|
write_local(key, entry);
|
|
await write_redis(key, entry);
|
|
}
|
|
|
|
/**
|
|
* Stale-while-revalidate cache.
|
|
*
|
|
* - Returns fresh data immediately if available.
|
|
* - Returns stale data and revalidates in the background if TTL exceeded but hard-expiry not reached.
|
|
* - Fetches synchronously if cold or hard-expired.
|
|
* - On fetch error, returns last known stale value (serve from cache) or throws.
|
|
*/
|
|
export async function swr_fetch<T>(
|
|
key: string,
|
|
fetcher: () => Promise<T>,
|
|
): Promise<T> {
|
|
const now = Date.now();
|
|
const entry = await get_entry(key);
|
|
|
|
if (entry && now < entry.stale_at) {
|
|
return entry.data as T;
|
|
}
|
|
|
|
if (entry && now < entry.expires_at) {
|
|
// Revalidate in background; return stale immediately
|
|
revalidate(key, fetcher).catch(() => null);
|
|
return entry.data as T;
|
|
}
|
|
|
|
return revalidate<T>(key, fetcher, entry);
|
|
}
|
|
|
|
async function revalidate<T>(
|
|
key: string,
|
|
fetcher: () => Promise<T>,
|
|
stale_entry?: CacheEntry | null,
|
|
): Promise<T> {
|
|
try {
|
|
const data = await fetcher();
|
|
await set_entry(key, data);
|
|
return data;
|
|
} catch (err) {
|
|
if (stale_entry) {
|
|
// WP is down but we have something in cache — serve it
|
|
return stale_entry.data as T;
|
|
}
|
|
throw err;
|
|
}
|
|
}
|
|
|
|
/** Invalidate a key from all layers. */
|
|
export async function cache_invalidate(key: string): Promise<void> {
|
|
local_map.delete(key);
|
|
const redis = get_redis();
|
|
if (redis) {
|
|
try { await redis.del(key); } catch { /* ignore */ }
|
|
}
|
|
}
|