-
Notifications
You must be signed in to change notification settings - Fork 513
Analytics event tracking #1208
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
Merged
Analytics event tracking #1208
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
a1da657
fix replay pausing issue
BilalG1 39ca118
analytics event tracking
BilalG1 f1fde88
fix test, remove type cast
BilalG1 fa09166
Merge branch 'dev' into analytics-event-tracking
BilalG1 2aadf87
fix light mode replays page height
BilalG1 97055c9
known errors for analytics disabled
BilalG1 f44ad77
Merge branch 'analytics-event-tracking' of https://github.com/stack-a…
BilalG1 73df340
analytics domain override (#1209)
BilalG1 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
98 changes: 98 additions & 0 deletions
98
apps/backend/src/app/api/latest/analytics/events/batch/route.tsx
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,98 @@ | ||
| import { getClickhouseAdminClient } from "@/lib/clickhouse"; | ||
| import { findRecentSessionReplay } from "@/lib/session-replays"; | ||
| import { getPrismaClientForTenancy } from "@/prisma-client"; | ||
| import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler"; | ||
| import { KnownErrors } from "@stackframe/stack-shared"; | ||
| import { adaptSchema, clientOrHigherAuthTypeSchema, yupArray, yupMixed, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields"; | ||
| import { StatusError } from "@stackframe/stack-shared/dist/utils/errors"; | ||
|
|
||
| const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i; | ||
|
|
||
| const MAX_EVENTS = 500; | ||
|
|
||
| export const POST = createSmartRouteHandler({ | ||
| metadata: { | ||
| summary: "Upload analytics event batch", | ||
| description: "Uploads a batch of auto-captured analytics events ($page-view, $click).", | ||
| tags: ["Analytics Events"], | ||
| hidden: true, | ||
| }, | ||
| request: yupObject({ | ||
| auth: yupObject({ | ||
| type: clientOrHigherAuthTypeSchema, | ||
| tenancy: adaptSchema, | ||
| user: adaptSchema, | ||
| refreshTokenId: adaptSchema, | ||
| }).defined(), | ||
| body: yupObject({ | ||
| session_replay_segment_id: yupString().defined().matches(UUID_RE, "Invalid session_replay_segment_id"), | ||
| batch_id: yupString().defined().matches(UUID_RE, "Invalid batch_id"), | ||
| sent_at_ms: yupNumber().defined().integer().min(0), | ||
| events: yupArray( | ||
| yupObject({ | ||
| event_type: yupString().defined().oneOf(["$page-view", "$click"]), | ||
| event_at_ms: yupNumber().defined().integer().min(0), | ||
| data: yupMixed().defined(), | ||
| }).defined(), | ||
| ).defined().min(1).max(MAX_EVENTS), | ||
| }).defined(), | ||
| }), | ||
| response: yupObject({ | ||
| statusCode: yupNumber().oneOf([200]).defined(), | ||
| bodyType: yupString().oneOf(["json"]).defined(), | ||
| body: yupObject({ | ||
| inserted: yupNumber().defined(), | ||
| }).defined(), | ||
| }), | ||
| async handler({ auth, body }) { | ||
| if (!auth.tenancy.config.apps.installed["analytics"]?.enabled) { | ||
| throw new KnownErrors.AnalyticsNotEnabled(); | ||
| } | ||
| if (!auth.user) { | ||
| throw new KnownErrors.UserAuthenticationRequired(); | ||
| } | ||
| if (!auth.refreshTokenId) { | ||
| throw new StatusError(StatusError.BadRequest, "A refresh token is required for analytics events"); | ||
| } | ||
|
BilalG1 marked this conversation as resolved.
|
||
|
|
||
| const projectId = auth.tenancy.project.id; | ||
| const branchId = auth.tenancy.branchId; | ||
| const userId = auth.user.id; | ||
| const refreshTokenId = auth.refreshTokenId; | ||
| const tenancyId = auth.tenancy.id; | ||
|
|
||
| const prisma = await getPrismaClientForTenancy(auth.tenancy); | ||
| const recentSession = await findRecentSessionReplay(prisma, { tenancyId, refreshTokenId }); | ||
|
|
||
| const clickhouseClient = getClickhouseAdminClient(); | ||
|
|
||
| const rows = body.events.map((event) => ({ | ||
| event_type: event.event_type, | ||
| event_at: new Date(event.event_at_ms), | ||
| data: event.data, | ||
| project_id: projectId, | ||
| branch_id: branchId, | ||
| user_id: userId, | ||
| team_id: null, | ||
| refresh_token_id: refreshTokenId, | ||
| session_replay_id: recentSession?.id ?? null, | ||
| session_replay_segment_id: body.session_replay_segment_id, | ||
| })); | ||
|
BilalG1 marked this conversation as resolved.
|
||
|
|
||
| await clickhouseClient.insert({ | ||
| table: "analytics_internal.events", | ||
| values: rows, | ||
| format: "JSONEachRow", | ||
| clickhouse_settings: { | ||
| date_time_input_format: "best_effort", | ||
| async_insert: 1, | ||
| }, | ||
| }); | ||
|
|
||
| return { | ||
| statusCode: 200, | ||
| bodyType: "json", | ||
| body: { inserted: body.events.length }, | ||
| }; | ||
| }, | ||
| }); | ||
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,23 @@ | ||
| import { PrismaClient } from "@/generated/prisma/client"; | ||
| import { PrismaClientWithReplica } from "@/prisma-client"; | ||
|
|
||
| export const SESSION_IDLE_TIMEOUT_MS = 3 * 60 * 1000; | ||
| export const MAX_SESSION_DURATION_MS = 12 * 60 * 60 * 1000; | ||
|
|
||
| export async function findRecentSessionReplay(prisma: PrismaClientWithReplica<PrismaClient>, options: { | ||
| tenancyId: string, | ||
| refreshTokenId: string, | ||
| }) { | ||
| const cutoff = new Date(Date.now() - SESSION_IDLE_TIMEOUT_MS); | ||
| const maxDurationCutoff = new Date(Date.now() - MAX_SESSION_DURATION_MS); | ||
| return await prisma.sessionReplay.findFirst({ | ||
| where: { | ||
| tenancyId: options.tenancyId, | ||
| refreshTokenId: options.refreshTokenId, | ||
| updatedAt: { gte: cutoff }, | ||
| startedAt: { gte: maxDurationCutoff }, | ||
| }, | ||
| orderBy: { updatedAt: "desc" }, | ||
| select: { id: true, startedAt: true, lastEventAt: true }, | ||
| }); | ||
| } |
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
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.