Repository navigation
feat(db): seed a reproducible local workspace #1081
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+708
−515
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
847c1ea
feat(db): one command for a reproducible local workspace
izadoesdev df451aa
refactor(db): trim the workspace seed generator
izadoesdev ff4725f
fix(db): require loopback before workspace writes and resets
izadoesdev 454b455
fix(db): reject workspace PostgreSQL host overrides
izadoesdev ae13cf1
fix(db): require finite workspace event counts
izadoesdev 43dc59c
fix(db): replace workspace totals and reuse the local user
izadoesdev 1f703be
fix(db): bound workspace analytics fixture generation
izadoesdev 3b60bc0
fix(db): preserve workspace defaults and login guidance
izadoesdev 131bcb3
fix(db): initialize workspace auth after local target validation
izadoesdev File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,162 +1,57 @@ | ||
| import { clickHouse, TABLE_NAMES } from "@databuddy/db/clickhouse"; | ||
| import { clickHouse } from "@databuddy/db/clickhouse"; | ||
| import { generateAnalytics, seedAnalytics } from "@databuddy/db/seed"; | ||
| import { readBooleanEnv } from "@databuddy/env/app"; | ||
| import { z } from "zod"; | ||
|
|
||
| export const runtime = "nodejs"; | ||
| export const dynamic = "force-dynamic"; | ||
|
|
||
| const TEST_KEY_HEADER = "x-e2e-test-key"; | ||
| const PATHS = ["/", "/pricing", "/docs", "/dashboard", "/settings"]; | ||
| const REFERRERS = [null, "https://google.com", "https://github.com"]; | ||
| const seedBody = z.object({ | ||
| eventCount: z.coerce.number().catch(250), | ||
|
coderabbitai[bot] marked this conversation as resolved.
|
||
| websiteId: z.string().min(1), | ||
| }); | ||
|
|
||
| interface SeedBody { | ||
| eventCount?: unknown; | ||
| websiteId?: unknown; | ||
| } | ||
|
|
||
| function isE2EModeEnabled(): boolean { | ||
| return readBooleanEnv("DATABUDDY_E2E_MODE"); | ||
| } | ||
|
|
||
| function notFound(): Response { | ||
| return Response.json({ error: "Not found" }, { status: 404 }); | ||
| function countBy<T>(items: T[], key: (item: T) => string) { | ||
| const counts: Record<string, number> = {}; | ||
| for (const item of items) { | ||
| counts[key(item)] = (counts[key(item)] ?? 0) + 1; | ||
| } | ||
| return counts; | ||
| } | ||
|
|
||
| function assertE2EAccess(request: Request): Response | null { | ||
| if (!isE2EModeEnabled()) { | ||
| return notFound(); | ||
| } | ||
| export async function POST(request: Request): Promise<Response> { | ||
| const key = process.env.DATABUDDY_E2E_TEST_KEY; | ||
| if (!key) { | ||
| return notFound(); | ||
| if (!(readBooleanEnv("DATABUDDY_E2E_MODE") && key)) { | ||
| return Response.json({ error: "Not found" }, { status: 404 }); | ||
| } | ||
| if (request.headers.get(TEST_KEY_HEADER) !== key) { | ||
| if (request.headers.get("x-e2e-test-key") !== key) { | ||
| return Response.json({ error: "Unauthorized" }, { status: 401 }); | ||
| } | ||
| return null; | ||
| } | ||
|
|
||
| function normalizeEventCount(value: unknown): number { | ||
| const parsed = typeof value === "number" ? value : Number(value); | ||
| if (!Number.isFinite(parsed)) { | ||
| return 250; | ||
| } | ||
| return Math.min(Math.max(Math.floor(parsed), 1), 5000); | ||
| } | ||
|
|
||
| function clickHouseDate(date: Date): string { | ||
| return date.toISOString().replace("T", " ").replace("Z", ""); | ||
| } | ||
|
|
||
| function pageTitle(path: string): string { | ||
| return path === "/" ? "Home" : path.slice(1).replaceAll("-", " "); | ||
| } | ||
|
|
||
| export async function POST(request: Request): Promise<Response> { | ||
| const denied = assertE2EAccess(request); | ||
| if (denied) { | ||
| return denied; | ||
| } | ||
|
|
||
| const body = (await request.json().catch(() => ({}))) as SeedBody; | ||
| if (typeof body.websiteId !== "string" || !body.websiteId) { | ||
| const body = seedBody.safeParse(await request.json().catch(() => null)); | ||
| if (!body.success) { | ||
| return Response.json({ error: "websiteId is required" }, { status: 400 }); | ||
| } | ||
| const { eventCount, websiteId } = body.data; | ||
|
|
||
| const eventCount = normalizeEventCount(body.eventCount); | ||
|
|
||
| const now = Date.now(); | ||
| const users = Array.from( | ||
| { length: Math.max(3, Math.ceil(eventCount / 40)) }, | ||
| () => crypto.randomUUID() | ||
| ); | ||
| const sessions = Array.from( | ||
| { length: Math.max(5, Math.ceil(eventCount / 12)) }, | ||
| (_, index) => ({ | ||
| anonymousId: users[index % users.length], | ||
| sessionId: crypto.randomUUID(), | ||
| start: now - (eventCount - index) * 60_000, | ||
| }) | ||
| ); | ||
|
|
||
| const events = Array.from({ length: eventCount }, (_, index) => { | ||
| const session = sessions[index % sessions.length]; | ||
| const path = PATHS[index % PATHS.length]; | ||
| const timestamp = new Date(session.start + index * 30_000); | ||
| return { | ||
| id: crypto.randomUUID(), | ||
| client_id: body.websiteId as string, | ||
| event_name: index % 4 === 0 ? "page_exit" : "screen_view", | ||
| anonymous_id: session.anonymousId, | ||
| time: clickHouseDate(timestamp), | ||
| session_id: session.sessionId, | ||
| session_start_time: clickHouseDate(new Date(session.start)), | ||
| timestamp: clickHouseDate(timestamp), | ||
| referrer: REFERRERS[index % REFERRERS.length], | ||
| url: `https://e2e.databuddy.local${path}`, | ||
| path, | ||
| title: pageTitle(path), | ||
| ip: "127.0.0.1", | ||
| user_agent: "Databuddy E2E", | ||
| browser_name: index % 3 === 0 ? "Firefox" : "Chrome", | ||
| os_name: index % 2 === 0 ? "macOS" : "Linux", | ||
| device_type: index % 5 === 0 ? "mobile" : "desktop", | ||
| country: index % 2 === 0 ? "US" : "DE", | ||
| properties: "{}", | ||
| created_at: clickHouseDate(new Date(now)), | ||
| }; | ||
| const rows = generateAnalytics({ | ||
| clientId: websiteId, | ||
| days: 1, | ||
| domain: "e2e.databuddy.local", | ||
| events: Math.min(Math.max(Math.floor(eventCount), 1), 5000), | ||
| }); | ||
| await seedAnalytics(clickHouse, rows); | ||
|
|
||
| const screenViewEvents = events.filter( | ||
| const screenViews = rows.events.filter( | ||
| (event) => event.event_name === "screen_view" | ||
| ); | ||
| const screenViewsByCountry = screenViewEvents.reduce<Record<string, number>>( | ||
| (acc, event) => { | ||
| acc[event.country] = (acc[event.country] ?? 0) + 1; | ||
| return acc; | ||
| }, | ||
| {} | ||
| ); | ||
| const screenViewsByPath = screenViewEvents.reduce<Record<string, number>>( | ||
| (acc, event) => { | ||
| acc[event.path] = (acc[event.path] ?? 0) + 1; | ||
| return acc; | ||
| }, | ||
| {} | ||
| ); | ||
|
|
||
| const outgoingLinks = sessions | ||
| .slice(0, Math.ceil(eventCount / 20)) | ||
| .map((session) => ({ | ||
| id: crypto.randomUUID(), | ||
| client_id: body.websiteId as string, | ||
| anonymous_id: session.anonymousId, | ||
| session_id: session.sessionId, | ||
| href: "https://github.com/databuddy-analytics/Databuddy", | ||
| text: "Databuddy GitHub", | ||
| properties: "{}", | ||
| timestamp: clickHouseDate(new Date(session.start + 45_000)), | ||
| })); | ||
|
|
||
| await Promise.all([ | ||
| clickHouse.insert({ | ||
| format: "JSONEachRow", | ||
| table: TABLE_NAMES.events, | ||
| values: events, | ||
| }), | ||
| clickHouse.insert({ | ||
| format: "JSONEachRow", | ||
| table: TABLE_NAMES.outgoing_links, | ||
| values: outgoingLinks, | ||
| }), | ||
| ]); | ||
|
|
||
| return Response.json({ | ||
| events: events.length, | ||
| outgoingLinks: outgoingLinks.length, | ||
| screenViews: screenViewEvents.length, | ||
| screenViewsByCountry, | ||
| screenViewsByPath, | ||
| events: rows.events.length, | ||
| outgoingLinks: rows.outgoingLinks.length, | ||
| screenViews: screenViews.length, | ||
| screenViewsByCountry: countBy(screenViews, (event) => event.country), | ||
| screenViewsByPath: countBy(screenViews, (event) => event.path), | ||
| seeded: true, | ||
| websiteId: body.websiteId, | ||
| websiteId, | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| import "@databuddy/test/env"; | ||
| import { afterAll, describe, expect, it } from "bun:test"; | ||
| import { clickHouse } from "@databuddy/db/clickhouse"; | ||
| import { | ||
| deleteAnalytics, | ||
| generateAnalytics, | ||
| seedAnalytics, | ||
| } from "@databuddy/db/seed"; | ||
| import { detectSignals } from "./detection"; | ||
| import { TRAFFIC_METRICS } from "./investigation"; | ||
|
|
||
| const describeIntegration = | ||
| process.env.INSIGHTS_INTEGRATION_TESTS === "true" ? describe : describe.skip; | ||
|
izadoesdev marked this conversation as resolved.
|
||
|
|
||
| const websiteId = `detection-fixture-${crypto.randomUUID()}`; | ||
|
|
||
| describeIntegration("detectSignals on the workspace fixture", () => { | ||
| afterAll(() => deleteAnalytics(clickHouse, websiteId), 30_000); | ||
|
|
||
| it("flags the seeded anomaly", async () => { | ||
| await seedAnalytics( | ||
| clickHouse, | ||
| generateAnalytics({ | ||
| anomaly: true, | ||
| clientId: websiteId, | ||
| domain: "localhost", | ||
| }) | ||
| ); | ||
|
|
||
| const signals = await detectSignals({ | ||
| lookbackDays: 7, | ||
| timezone: "UTC", | ||
| websiteId, | ||
| }); | ||
|
|
||
| const rising = signals | ||
| .filter((signal) => signal.direction === "up") | ||
| .map((signal) => signal.metric); | ||
| expect(rising.some((metric) => TRAFFIC_METRICS.has(metric))).toBe(true); | ||
| expect(rising).toContain("error_count"); | ||
| }, 30_000); | ||
| }); | ||
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.