import { createHmac } from "node:crypto"; import { normalizeIp } from "./origins"; import type { AnalyticsEvent, AnalyticsSink } from "./types"; import type { SqliteStore } from "./store"; export function pseudonymizeIp(secret: string, ip: string, showUri: string, timestamp: string): string | undefined { const normalized = normalizeIp(ip); if (!normalized) return undefined; const day = timestamp.slice(0, 10); return createHmac("sha256", secret).update(JSON.stringify([day, showUri, normalized])).digest("hex"); } export function classifyUserAgent(value: string | null): string { if (!value) return "unknown"; const ua = value.toLowerCase(); if (/bot|crawler|spider/.test(ua)) return "bot"; if (/overcast|castbox|podcast/.test(ua)) return "podcast-app"; if (/iphone|ipad|applecoremedia/.test(ua)) return "ios"; if (ua.includes("android")) return "android"; return "other"; } // Listener handling only enqueues bounded, minimized events. Flushes happen out // of band. Events still in memory can be lost on a crash; never claim exact counts. export class BufferedAnalyticsSink implements AnalyticsSink { private pending: AnalyticsEvent[] = []; private timer?: ReturnType; private lastPrune = 0; dropped = 0; constructor(private readonly store: SqliteStore, private readonly retentionDays = 7, private readonly capacity = 10_000) {} async record(event: AnalyticsEvent): Promise { if (this.pending.length >= this.capacity) { this.dropped++; return; } this.pending.push(event); } start(): void { this.flush(); this.timer = setInterval(() => this.flush(), 1000); this.timer.unref(); } flush(now = Date.now()): void { const batch = this.pending.splice(0); try { if (batch.length) this.store.writeEvents(batch); if (!this.lastPrune || now - this.lastPrune >= 3_600_000) { this.store.pruneEvents(new Date(now - this.retentionDays * 86_400_000).toISOString()); this.lastPrune = now; } } catch { this.dropped += batch.length; console.error("analytics batch could not be stored"); } } close(): void { clearInterval(this.timer); this.flush(); } }