| 1 | import { accessConfigured, verifyAccess } from "./access"; |
| 2 | import { CAVEATS, collectStats, startOfUtcDay, utcDay } from "./queries"; |
| 3 | import { rollupDaily } from "./rollup"; |
| 4 | import { createRunner } from "./sql"; |
| 5 | import type { Env } from "./types"; |
| 6 | |
| 7 | const DAY_MS = 86_400_000; |
| 8 | const CACHE_SECONDS = 300; |
| 9 | const TREND_METRICS = ["active_installs", "sessions", "turns", "tool_calls"]; |
| 10 | |
| 11 | const cache = new Map<string, { at: number; body: string }>(); |
| 12 | |
| 13 | function reply(body: string, status = 200, cacheable = false): Response { |
| 14 | return new Response(body, { |
| 15 | status, |
| 16 | headers: { |
| 17 | "content-type": "application/json; charset=utf-8", |
| 18 | "cache-control": cacheable ? `private, max-age=${CACHE_SECONDS}` : "no-store", |
| 19 | "x-content-type-options": "nosniff", |
| 20 | }, |
| 21 | }); |
| 22 | } |
| 23 | |
| 24 | function daysParam(url: URL, fallback: number, max: number): number { |
| 25 | const raw = url.searchParams.get("days"); |
| 26 | if (raw === null) return fallback; |
| 27 | const days = Number(raw); |
| 28 | if (!Number.isInteger(days) || days < 1 || days > max) return fallback; |
| 29 | return days; |
| 30 | } |
| 31 | |
| 32 | export async function handleFetch(request: Request, env: Env, now: Date = new Date()): Promise<Response> { |
| 33 | if (request.method !== "GET" && request.method !== "HEAD") return reply("{}", 405); |
| 34 | if (!accessConfigured(env)) return reply(JSON.stringify({ error: "access_not_configured" }), 503); |
| 35 | if (!(await verifyAccess(request, env, fetch, now.getTime()))) return reply(JSON.stringify({ error: "forbidden" }), 403); |
| 36 | |
| 37 | const url = new URL(request.url); |
| 38 | if (url.pathname === "/api/stats") { |
| 39 | const days = daysParam(url, 14, 31); |
| 40 | const cached = cache.get(`stats:${days}`); |
| 41 | if (cached && now.getTime() - cached.at < CACHE_SECONDS * 1000) return reply(cached.body, 200, true); |
| 42 | const runner = createRunner(env); |
| 43 | if (!runner) return reply(JSON.stringify({ error: "no_analytics_source" }), 503); |
| 44 | const to = new Date(startOfUtcDay(now).getTime() + DAY_MS); |
| 45 | const from = new Date(to.getTime() - days * DAY_MS); |
| 46 | try { |
| 47 | const rows = await collectStats(runner, from, to); |
| 48 | const body = JSON.stringify({ |
| 49 | source: runner.source, |
| 50 | generated_at: now.toISOString(), |
| 51 | from: utcDay(from), |
| 52 | to: utcDay(new Date(to.getTime() - DAY_MS)), |
| 53 | rows, |
| 54 | caveats: CAVEATS, |
| 55 | }); |
| 56 | cache.set(`stats:${days}`, { at: now.getTime(), body }); |
| 57 | return reply(body, 200, true); |
| 58 | } catch { |
| 59 | return reply(JSON.stringify({ error: "query_failed" }), 502); |
| 60 | } |
| 61 | } |
| 62 | if (url.pathname === "/api/trend") { |
| 63 | if (!env.DB) return reply(JSON.stringify({ error: "no_rollup_store" }), 503); |
| 64 | const days = daysParam(url, 365, 1100); |
| 65 | const from = utcDay(new Date(startOfUtcDay(now).getTime() - days * DAY_MS)); |
| 66 | const placeholders = TREND_METRICS.map(() => "?").join(","); |
| 67 | const result = await env.DB.prepare( |
| 68 | `SELECT day, metric, dim, key, value FROM daily_totals WHERE dim = 'all' AND day >= ? AND metric IN (${placeholders}) ORDER BY day`, |
| 69 | ) |
| 70 | .bind(from, ...TREND_METRICS) |
| 71 | .all(); |
| 72 | return reply(JSON.stringify({ from, rows: result.results ?? [] }), 200, true); |
| 73 | } |
| 74 | if (!env.ASSETS) return reply(JSON.stringify({ error: "not_found" }), 404); |
| 75 | return env.ASSETS.fetch(request); |
| 76 | } |
| 77 | |
| 78 | export default { |
| 79 | fetch: (request: Request, env: Env) => handleFetch(request, env), |
| 80 | async scheduled(_controller: unknown, env: Env): Promise<void> { |
| 81 | const runner = createRunner(env); |
| 82 | if (!runner || !env.DB) return; |
| 83 | await rollupDaily(runner, env.DB); |
| 84 | }, |
| 85 | }; |
| 86 |