From ce0d23e94baf4961faf52f7efbdb78d7f369ae32 Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Wed, 14 Oct 2026 12:13:01 -0400 Subject: [PATCH] test(analytics): add collector, rollup, retention integration suite and e2e smoke - tests/int/analytics.int.spec.ts: envelope validation, bot filtering, rate limiting, sessionization, retroactive attribution, rollup idempotency, retention purges (11 tests) - tests/e2e/analytics.e2e.spec.ts: dev-flag guest pageview lands in the test DB, collector accepts beacons and rejects garbage, dashboard renders for a superuser - playwright.config.ts: enable NEXT_PUBLIC_ANALYTICS_DEV for the e2e webServer --- playwright.config.ts | 3 + tests/e2e/analytics.e2e.spec.ts | 73 +++++++ tests/int/analytics.int.spec.ts | 357 ++++++++++++++++++++++++++++++++ 3 files changed, 433 insertions(+) create mode 100644 tests/e2e/analytics.e2e.spec.ts create mode 100644 tests/int/analytics.int.spec.ts diff --git a/playwright.config.ts b/playwright.config.ts index 95584275..347d630c 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -81,6 +81,9 @@ export default defineConfig({ env: { ...process.env, DATABASE_URI: testDatabaseUri, + // Enable the first-party analytics tracker in the dev server so the + // analytics e2e smoke can assert rows land. + NEXT_PUBLIC_ANALYTICS_DEV: "1", }, }, globalSetup: "./tests/e2e/global-setup.ts", diff --git a/tests/e2e/analytics.e2e.spec.ts b/tests/e2e/analytics.e2e.spec.ts new file mode 100644 index 00000000..f1ffdd48 --- /dev/null +++ b/tests/e2e/analytics.e2e.spec.ts @@ -0,0 +1,73 @@ +import { expect, test } from "@playwright/test"; +import { Client } from "pg"; + +/** + * First-party analytics e2e smoke (Phase 1). + * + * Runs with NEXT_PUBLIC_ANALYTICS_DEV=1 (set in playwright.config.ts), which + * enables the tracker in the dev server. Verifies the three surfaces end to + * end: the client SDK lands a guest pageview row, the collector endpoint + * accepts beacon batches (and rejects garbage), and the admin dashboard + * renders for a superuser. + */ + +async function countDevPageviews(path: string): Promise { + // global-setup points DATABASE_URI at the test database before workers run, + // so read it directly (calling resolveTestDatabaseUri() again would append + // a second _test suffix). + const client = new Client({ connectionString: process.env.DATABASE_URI }); + await client.connect(); + try { + const result = await client.query( + "SELECT COUNT(*)::int AS c FROM analytics_events WHERE type = 'pageview' AND path = $1 AND env = 'dev'", + [path], + ); + return result.rows[0].c as number; + } finally { + await client.end(); + } +} + +test.describe("First-party analytics", () => { + test("the tracker records a guest pageview end to end", async ({ page }) => { + await page.goto("/"); + await expect(page.getByRole("heading", { level: 1 })).toContainText("Polaris Task Force"); + + // The SDK flushes on the first route change, so the row should land fast. + await expect + .poll(() => countDevPageviews("/"), { timeout: 20_000, intervals: [500] }) + .toBeGreaterThan(0); + }); + + test("the collector accepts beacon batches and rejects malformed ones", async ({ request }) => { + const accepted = await request.post("/api/collect", { + data: { + sid: null, + aid: "e2e-smoke", + events: [{ type: "pageview", path: "/e2e-collector-smoke" }], + }, + }); + expect(accepted.status()).toBe(204); + + const rejected = await request.post("/api/collect", { data: { events: [] } }); + expect(rejected.status()).toBe(400); + }); + + test("the admin analytics dashboard renders for a superuser", async ({ page }) => { + await page.goto("/login"); + await page.getByLabel("Username").fill("dev"); + await page.getByLabel("Password").fill("Test123"); + await page.getByRole("button", { name: "Log in" }).click(); + await page.waitForURL((url) => !url.pathname.startsWith("/login"), { timeout: 30_000 }); + + await page.goto("/admin/analytics"); + await expect(page.getByRole("heading", { name: "Usage Analytics" })).toBeVisible({ + timeout: 60_000, + }); + + // The six report tabs render; hop to one to prove tab navigation works. + await expect(page.getByRole("link", { name: "Minigames" })).toBeVisible(); + await page.getByRole("link", { name: "Sessions" }).click(); + await expect(page.getByText(/^Sessions \(/)).toBeVisible(); + }); +}); diff --git a/tests/int/analytics.int.spec.ts b/tests/int/analytics.int.spec.ts new file mode 100644 index 00000000..ae43a127 --- /dev/null +++ b/tests/int/analytics.int.spec.ts @@ -0,0 +1,357 @@ +import { sql } from "@payloadcms/db-postgres"; +import { getPayload, type Payload } from "payload"; +import config from "@/payload.config"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; + +import { + checkCollectRateLimit, + ingestBatch, + isBotUserAgent, + resetCollectRateLimit, + SESSION_IDLE_MS, + type IngestContext, +} from "@/lib/analytics/ingest"; +import { parseCollectEnvelope, MAX_EVENTS_PER_BATCH } from "@/lib/analytics/events"; +import { + isoDay, + purgeOldEvents, + purgeOldSessions, + rollupDay, +} from "@/lib/analytics/rollup"; + +/** + * Collector + rollup + retention integration tests against the real test + * database (the analytics tables are created by the shared DDL module during + * the test bootstrap). Raw SQL helpers go through payload.db.drizzle because + * these are plain tables, not Payload collections. + */ + +let payload: Payload; + +async function execute(fragment: ReturnType): Promise { + await payload.db.drizzle.execute(fragment); +} + +async function rows(fragment: ReturnType): Promise { + const result = (await payload.db.drizzle.execute(fragment)) as unknown as { rows: T[] }; + return result.rows ?? []; +} + +function ctx(overrides: Partial = {}): IngestContext { + return { + ip: "203.0.113.10", + ua: "Mozilla/5.0 (Test Browser)", + referrer: null, + userId: null, + env: "production", + ...overrides, + }; +} + +function envelope(body: Record) { + const parsed = parseCollectEnvelope(body); + if (!parsed.ok) throw new Error(`envelope rejected in test: ${parsed.error}`); + return parsed.envelope; +} + +const createdSessionIds: string[] = []; + +beforeAll(async () => { + payload = await getPayload({ config: await config }); +}); + +afterAll(async () => { + // Leave the shared database tidy for other spec files. + if (createdSessionIds.length > 0) { + await execute(sql`DELETE FROM analytics_events WHERE session_id IN (${sql.join( + createdSessionIds.map((id) => sql`${id}`), + sql`, `, + )})`); + await execute(sql`DELETE FROM analytics_sessions WHERE id IN (${sql.join( + createdSessionIds.map((id) => sql`${id}`), + sql`, `, + )})`); + } +}); + +describe("envelope validation", () => { + it("accepts a well-formed batch and clamps fields", () => { + const result = parseCollectEnvelope({ + sid: "sid-123", + aid: "aid-456", + events: [ + { type: "pageview", path: "/dashboard", ts: Date.now() }, + { type: "click", path: "/dashboard", element: { selector: "button" }, data: { xPct: 10 } }, + ], + }); + expect(result.ok).toBe(true); + if (!result.ok) return; + expect(result.envelope.sid).toBe("sid-123"); + expect(result.envelope.events).toHaveLength(2); + expect(result.envelope.dropped).toBe(0); + }); + + it("rejects empty or oversized batches", () => { + expect(parseCollectEnvelope({ events: [] }).ok).toBe(false); + const big = Array.from({ length: MAX_EVENTS_PER_BATCH + 1 }, () => ({ type: "pageview" })); + expect(parseCollectEnvelope({ events: big }).ok).toBe(false); + expect(parseCollectEnvelope("nope").ok).toBe(false); + }); + + it("drops invalid events but keeps valid ones", () => { + const result = parseCollectEnvelope({ + events: [ + { type: "pageview", path: "/ok" }, + { type: "not-a-real-type", path: "/bad" }, + { type: "click", path: "relative-not-absolute" }, + { type: "custom", data: { huge: "x".repeat(10_000) } }, + { type: "heartbeat", ts: Date.now() + 60 * 60 * 1000 }, + ], + }); + expect(result.ok).toBe(true); + if (!result.ok) return; + // Bad type and future timestamp drop the event; the oversized payload is + // dropped but its event survives, and the relative path is nulled. + expect(result.envelope.events).toHaveLength(3); + expect(result.envelope.dropped).toBe(2); + const click = result.envelope.events.find((e) => e.type === "click"); + expect(click?.path).toBeNull(); + const custom = result.envelope.events.find((e) => e.type === "custom"); + expect(custom?.data).toBeNull(); + }); +}); + +describe("bot filtering and rate limiting", () => { + it("flags known bots by UA", () => { + expect(isBotUserAgent("Mozilla/5.0 (compatible; AhrefsBot/7.0)")).toBe(true); + expect(isBotUserAgent("curl/8.5.0")).toBe(true); + expect(isBotUserAgent("HeadlessChrome/120")).toBe(true); + expect(isBotUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120")).toBe(false); + expect(isBotUserAgent(null)).toBe(false); + }); + + it("rate limits per IP within the window", () => { + resetCollectRateLimit(); + const ip = "198.51.100.7"; + for (let i = 0; i < 120; i += 1) { + expect(checkCollectRateLimit(ip, 1_000_000)).toBe(true); + } + expect(checkCollectRateLimit(ip, 1_000_001)).toBe(false); + // Next window resets the budget. + expect(checkCollectRateLimit(ip, 1_000_000 + 61_000)).toBe(true); + resetCollectRateLimit(); + }); +}); + +describe("ingestBatch sessionization", () => { + it("creates a session on first flush and reuses it while active", async () => { + const first = await ingestBatch( + payload, + envelope({ + sid: null, + aid: "aid-new-session", + events: [ + { type: "pageview", path: "/dashboard", ts: Date.now() }, + { type: "heartbeat", path: "/dashboard", data: { ms: 15000 }, ts: Date.now() }, + ], + }), + ctx(), + ); + expect(first.newSession).toBe(true); + expect(first.stored).toBe(2); + createdSessionIds.push(first.sessionId); + + const second = await ingestBatch( + payload, + envelope({ + sid: first.sessionId, + aid: "aid-new-session", + events: [{ type: "pageview", path: "/logistics", ts: Date.now() }], + }), + ctx(), + ); + expect(second.newSession).toBe(false); + expect(second.sessionId).toBe(first.sessionId); + + const sessions = await rows<{ pageview_count: number; active_ms: string; entry_path: string }>( + sql`SELECT pageview_count, active_ms, entry_path FROM analytics_sessions WHERE id = ${first.sessionId}`, + ); + expect(sessions[0].pageview_count).toBe(2); + expect(Number(sessions[0].active_ms)).toBe(15000); + expect(sessions[0].entry_path).toBe("/dashboard"); + }); + + it("closes an idle-expired session and starts a new one", async () => { + const fresh = await ingestBatch( + payload, + envelope({ sid: null, events: [{ type: "pageview", path: "/wiki" }] }), + ctx(), + ); + createdSessionIds.push(fresh.sessionId); + // Age the session past the idle window. + await execute(sql` + UPDATE analytics_sessions + SET last_activity_at = now() - (${SESSION_IDLE_MS + 60_000}::double precision * interval '1 millisecond') + WHERE id = ${fresh.sessionId} + `); + + const next = await ingestBatch( + payload, + envelope({ sid: fresh.sessionId, events: [{ type: "pageview", path: "/story" }] }), + ctx(), + ); + expect(next.newSession).toBe(true); + expect(next.sessionId).not.toBe(fresh.sessionId); + createdSessionIds.push(next.sessionId); + + const old = await rows<{ ended_at: string | null }>( + sql`SELECT ended_at FROM analytics_sessions WHERE id = ${fresh.sessionId}`, + ); + expect(old[0]?.ended_at).not.toBeNull(); + }); + + it("drops bot traffic without writing anything", async () => { + const result = await ingestBatch( + payload, + envelope({ sid: null, events: [{ type: "pageview", path: "/secret" }] }), + ctx({ ua: "Mozilla/5.0 (compatible; SemrushBot/7~bl; +http://www.semrush.com/bot.html)" }), + ); + expect(result.isBot).toBe(true); + expect(result.stored).toBe(0); + }); + + it("links guest sessions to the user retroactively on login", async () => { + const guest = await ingestBatch( + payload, + envelope({ sid: null, aid: "aid-upgrade", events: [{ type: "pageview", path: "/login" }] }), + ctx(), + ); + createdSessionIds.push(guest.sessionId); + + const authed = await ingestBatch( + payload, + envelope({ + sid: guest.sessionId, + aid: "aid-upgrade", + events: [{ type: "pageview", path: "/dashboard" }], + }), + ctx({ userId: 424242 }), + ); + expect(authed.sessionId).toBe(guest.sessionId); + + const session = await rows<{ user_id: number | null }>( + sql`SELECT user_id FROM analytics_sessions WHERE id = ${guest.sessionId}`, + ); + expect(session[0]?.user_id).toBe(424242); + + const events = await rows<{ path: string; user_id: number | null }>( + sql`SELECT path, user_id FROM analytics_events WHERE session_id = ${guest.sessionId} ORDER BY path`, + ); + expect(events).toHaveLength(2); + expect(events.every((e) => e.user_id === 424242)).toBe(true); + }); +}); + +describe("rollup and retention", () => { + const today = isoDay(new Date()); + let rollupSessionId: string; + + it("computes daily aggregates from raw events (idempotently)", async () => { + // Seed a dedicated session with a mix of event types for today. + const seeded = await ingestBatch( + payload, + envelope({ + sid: null, + events: [ + { type: "pageview", path: "/minigames/flappy", ts: Date.now() }, + { type: "heartbeat", path: "/minigames/flappy", data: { ms: 15000 }, ts: Date.now() }, + { type: "scroll", path: "/minigames/flappy", data: { maxScrollPct: 100, dwellMs: 30000 }, ts: Date.now() }, + { + type: "custom", + path: "/story", + data: { name: "chronicle.read_progress", kind: "beat", ref: "991", progressPct: 40 }, + ts: Date.now(), + }, + { + type: "custom", + path: "/story", + data: { name: "chronicle.read_completed", kind: "beat", ref: "991", timeMs: 61000 }, + ts: Date.now(), + }, + ], + }), + ctx({ userId: 555001 }), + ); + rollupSessionId = seeded.sessionId; + createdSessionIds.push(rollupSessionId); + + const slugToKey = { flappy: "flappy" }; + const first = await rollupDay(payload, today, slugToKey); + const second = await rollupDay(payload, today, slugToKey); + expect(first.pages).toBe(second.pages); + expect(first.users).toBe(second.users); + expect(first.games).toBe(second.games); + + const pages = await rows<{ views: string }>( + sql`SELECT views FROM analytics_daily_pages WHERE day = ${today}::date AND path = '/minigames/flappy'`, + ); + expect(Number(pages[0]?.views ?? 0)).toBeGreaterThanOrEqual(1); + + const users = await rows<{ active_ms: string; sessions: string }>( + sql`SELECT active_ms, sessions FROM analytics_daily_users WHERE day = ${today}::date AND user_id = 555001`, + ); + expect(Number(users[0]?.active_ms)).toBeGreaterThanOrEqual(15000); + expect(Number(users[0]?.sessions)).toBeGreaterThanOrEqual(1); + + const games = await rows<{ sessions: string; avg_session_ms: string }>( + sql`SELECT sessions, avg_session_ms FROM analytics_daily_games WHERE day = ${today}::date AND game_key = 'flappy'`, + ); + expect(Number(games[0]?.sessions)).toBeGreaterThanOrEqual(1); + expect(Number(games[0]?.avg_session_ms)).toBeGreaterThanOrEqual(15000); + + const chronicle = await rows<{ opens: string; completions: string; median_time_ms: string }>( + sql`SELECT opens, completions, median_time_ms FROM analytics_daily_chronicle WHERE day = ${today}::date AND kind = 'beat' AND ref = '991'`, + ); + expect(Number(chronicle[0]?.opens)).toBeGreaterThanOrEqual(1); + expect(Number(chronicle[0]?.completions)).toBeGreaterThanOrEqual(1); + expect(Number(chronicle[0]?.median_time_ms)).toBeGreaterThanOrEqual(61000); + }); + + it("purges raw events and sessions past the retention window only", async () => { + // Seed directly via SQL: the collector validation intentionally rejects + // stale client timestamps, so an old event can only arrive this way. + const oldSessionId = crypto.randomUUID(); + createdSessionIds.push(oldSessionId); + await execute(sql` + INSERT INTO analytics_sessions (id, started_at, last_activity_at, env) + VALUES (${oldSessionId}, now() - interval '95 days', now() - interval '95 days', 'production') + `); + await execute(sql` + INSERT INTO analytics_events (session_id, ts, type, path, env) + VALUES + (${oldSessionId}, now() - interval '94 days', 'pageview', '/old', 'production'), + (${oldSessionId}, now() - interval '1 hour', 'pageview', '/recent', 'production') + `); + + const deletedEvents = await purgeOldEvents(payload, 90); + expect(deletedEvents).toBeGreaterThanOrEqual(1); + + const remaining = await rows<{ path: string }>( + sql`SELECT path FROM analytics_events WHERE session_id = ${oldSessionId}`, + ); + expect(remaining.map((r) => r.path)).toEqual(["/recent"]); + + const deletedSessions = await purgeOldSessions(payload, 90); + expect(deletedSessions).toBeGreaterThanOrEqual(1); + const gone = await rows<{ id: string }>( + sql`SELECT id FROM analytics_sessions WHERE id = ${oldSessionId}`, + ); + expect(gone).toHaveLength(0); + // The explicit session cleanup removed the remaining event too. + const eventsGone = await rows<{ id: string }>( + sql`SELECT id FROM analytics_events WHERE session_id = ${oldSessionId}`, + ); + expect(eventsGone).toHaveLength(0); + createdSessionIds.splice(createdSessionIds.indexOf(oldSessionId), 1); + }); +});