mirror of
https://github.com/koala73/worldmonitor.git
synced 2026-05-14 11:06:21 +02:00
Egress optimization: - Add s-maxage + stale-while-revalidate to all API endpoints for Vercel CDN caching - Add vercel.json with immutable caching for hashed assets - Add gzip compression to sidecar responses >1KB - Add gzip to Railway RSS responses (4 paths previously uncompressed) - Increase polling intervals: markets/crypto 60s→120s, ETF/macro/stablecoins 60s→180s - Remove hardcoded Railway URL from theater-posture.js (now env-var only) PWA / Service Worker: - Add vite-plugin-pwa with autoUpdate strategy - Cache map tiles (CacheFirst), fonts (StaleWhileRevalidate), static assets - NetworkOnly for all /api/* routes (real-time data must be fresh) - Manual SW registration (web only, skip Tauri) - Add offline fallback page - Replace manual manifest with plugin-generated manifest Polymarket fix: - Route dev proxy through production Vercel (bypasses JA3 blocking) - Add 4th fallback tier: production URL as absolute fallback Desktop/Sidecar: - Dual-backend cache (_upstash-cache.js): Redis cloud + in-memory+file desktop - Settings window OK/Cancel redesign - Runtime config and secret injection improvements
151 lines
4.7 KiB
JavaScript
151 lines
4.7 KiB
JavaScript
import { getCachedJson, setCachedJson, hashString } from './_upstash-cache.js';
|
|
|
|
export const config = {
|
|
runtime: 'edge',
|
|
};
|
|
|
|
const GROQ_API_URL = 'https://api.groq.com/openai/v1/chat/completions';
|
|
const MODEL = 'llama-3.1-8b-instant';
|
|
const CACHE_TTL_SECONDS = 86400;
|
|
const CACHE_VERSION = 'v1';
|
|
|
|
const VALID_LEVELS = ['critical', 'high', 'medium', 'low', 'info'];
|
|
const VALID_CATEGORIES = [
|
|
'conflict', 'protest', 'disaster', 'diplomatic', 'economic',
|
|
'terrorism', 'cyber', 'health', 'environmental', 'military',
|
|
'crime', 'infrastructure', 'tech', 'general',
|
|
];
|
|
|
|
export default async function handler(request) {
|
|
if (request.method !== 'GET') {
|
|
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
|
|
status: 405,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const apiKey = process.env.GROQ_API_KEY;
|
|
if (!apiKey) {
|
|
return new Response(JSON.stringify({ fallback: true, skipped: true, reason: 'GROQ_API_KEY not configured' }), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const url = new URL(request.url);
|
|
const title = url.searchParams.get('title');
|
|
const variant = url.searchParams.get('variant') || 'full';
|
|
|
|
if (!title) {
|
|
return new Response(JSON.stringify({ error: 'title param required' }), {
|
|
status: 400,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const cacheKey = `classify:${CACHE_VERSION}:${hashString(title.toLowerCase() + ':' + variant)}`;
|
|
|
|
try {
|
|
const cached = await getCachedJson(cacheKey);
|
|
if (cached && typeof cached === 'object' && cached.level) {
|
|
return new Response(JSON.stringify({
|
|
level: cached.level,
|
|
category: cached.category,
|
|
confidence: 0.9,
|
|
source: 'llm',
|
|
cached: true,
|
|
}), {
|
|
status: 200,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const isTech = variant === 'tech';
|
|
const systemPrompt = `You classify news headlines into threat level and category. Return ONLY valid JSON, no other text.
|
|
|
|
Levels: critical, high, medium, low, info
|
|
Categories: conflict, protest, disaster, diplomatic, economic, terrorism, cyber, health, environmental, military, crime, infrastructure, tech, general
|
|
|
|
${isTech ? 'Focus: technology, startups, AI, cybersecurity. Most tech news is "low" or "info" unless it involves outages, breaches, or major disruptions.' : 'Focus: geopolitical events, conflicts, disasters, diplomacy. Classify by real-world severity and impact.'}
|
|
|
|
Return: {"level":"...","category":"..."}`;
|
|
|
|
const response = await fetch(GROQ_API_URL, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Authorization': `Bearer ${apiKey}`,
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify({
|
|
model: MODEL,
|
|
messages: [
|
|
{ role: 'system', content: systemPrompt },
|
|
{ role: 'user', content: title },
|
|
],
|
|
temperature: 0,
|
|
max_tokens: 50,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
console.error('[Classify] Groq error:', response.status);
|
|
return new Response(JSON.stringify({ fallback: true }), {
|
|
status: response.status,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const data = await response.json();
|
|
const raw = data.choices?.[0]?.message?.content?.trim();
|
|
if (!raw) {
|
|
return new Response(JSON.stringify({ fallback: true }), {
|
|
status: 500,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
let parsed;
|
|
try {
|
|
parsed = JSON.parse(raw);
|
|
} catch {
|
|
console.warn('[Classify] Invalid JSON from LLM:', raw);
|
|
return new Response(JSON.stringify({ fallback: true }), {
|
|
status: 500,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
const level = VALID_LEVELS.includes(parsed.level) ? parsed.level : null;
|
|
const category = VALID_CATEGORIES.includes(parsed.category) ? parsed.category : null;
|
|
if (!level || !category) {
|
|
return new Response(JSON.stringify({ fallback: true }), {
|
|
status: 500,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
|
|
await setCachedJson(cacheKey, { level, category, timestamp: Date.now() }, CACHE_TTL_SECONDS);
|
|
|
|
return new Response(JSON.stringify({
|
|
level,
|
|
category,
|
|
confidence: 0.9,
|
|
source: 'llm',
|
|
cached: false,
|
|
}), {
|
|
status: 200,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'Cache-Control': 'public, max-age=3600, s-maxage=3600, stale-while-revalidate=600',
|
|
},
|
|
});
|
|
|
|
} catch (error) {
|
|
console.error('[Classify] Error:', error.message);
|
|
return new Response(JSON.stringify({ fallback: true }), {
|
|
status: 500,
|
|
headers: { 'Content-Type': 'application/json' },
|
|
});
|
|
}
|
|
}
|