|
| 1 | +import { getClickhouseAdminClient } from "@/lib/clickhouse"; |
| 2 | +import { findRecentSessionReplay } from "@/lib/session-replays"; |
| 3 | +import { getPrismaClientForTenancy } from "@/prisma-client"; |
| 4 | +import { createSmartRouteHandler } from "@/route-handlers/smart-route-handler"; |
| 5 | +import { KnownErrors } from "@stackframe/stack-shared"; |
| 6 | +import { adaptSchema, clientOrHigherAuthTypeSchema, yupArray, yupMixed, yupNumber, yupObject, yupString } from "@stackframe/stack-shared/dist/schema-fields"; |
| 7 | +import { StatusError } from "@stackframe/stack-shared/dist/utils/errors"; |
| 8 | + |
| 9 | +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; |
| 10 | + |
| 11 | +const MAX_EVENTS = 500; |
| 12 | + |
| 13 | +export const POST = createSmartRouteHandler({ |
| 14 | + metadata: { |
| 15 | + summary: "Upload analytics event batch", |
| 16 | + description: "Uploads a batch of auto-captured analytics events ($page-view, $click).", |
| 17 | + tags: ["Analytics Events"], |
| 18 | + hidden: true, |
| 19 | + }, |
| 20 | + request: yupObject({ |
| 21 | + auth: yupObject({ |
| 22 | + type: clientOrHigherAuthTypeSchema, |
| 23 | + tenancy: adaptSchema, |
| 24 | + user: adaptSchema, |
| 25 | + refreshTokenId: adaptSchema, |
| 26 | + }).defined(), |
| 27 | + body: yupObject({ |
| 28 | + session_replay_segment_id: yupString().defined().matches(UUID_RE, "Invalid session_replay_segment_id"), |
| 29 | + batch_id: yupString().defined().matches(UUID_RE, "Invalid batch_id"), |
| 30 | + sent_at_ms: yupNumber().defined().integer().min(0), |
| 31 | + events: yupArray( |
| 32 | + yupObject({ |
| 33 | + event_type: yupString().defined().oneOf(["$page-view", "$click"]), |
| 34 | + event_at_ms: yupNumber().defined().integer().min(0), |
| 35 | + data: yupMixed().defined(), |
| 36 | + }).defined(), |
| 37 | + ).defined().min(1).max(MAX_EVENTS), |
| 38 | + }).defined(), |
| 39 | + }), |
| 40 | + response: yupObject({ |
| 41 | + statusCode: yupNumber().oneOf([200]).defined(), |
| 42 | + bodyType: yupString().oneOf(["json"]).defined(), |
| 43 | + body: yupObject({ |
| 44 | + inserted: yupNumber().defined(), |
| 45 | + }).defined(), |
| 46 | + }), |
| 47 | + async handler({ auth, body }) { |
| 48 | + if (!auth.tenancy.config.apps.installed["analytics"]?.enabled) { |
| 49 | + return { |
| 50 | + statusCode: 200, |
| 51 | + bodyType: "json", |
| 52 | + body: { inserted: 0 }, |
| 53 | + }; |
| 54 | + } |
| 55 | + if (!auth.user) { |
| 56 | + throw new KnownErrors.UserAuthenticationRequired(); |
| 57 | + } |
| 58 | + if (!auth.refreshTokenId) { |
| 59 | + throw new StatusError(StatusError.BadRequest, "A refresh token is required for analytics events"); |
| 60 | + } |
| 61 | + |
| 62 | + const projectId = auth.tenancy.project.id; |
| 63 | + const branchId = auth.tenancy.branchId; |
| 64 | + const userId = auth.user.id; |
| 65 | + const refreshTokenId = auth.refreshTokenId; |
| 66 | + const tenancyId = auth.tenancy.id; |
| 67 | + |
| 68 | + const prisma = await getPrismaClientForTenancy(auth.tenancy); |
| 69 | + const recentSession = await findRecentSessionReplay(prisma, { tenancyId, refreshTokenId }); |
| 70 | + |
| 71 | + const clickhouseClient = getClickhouseAdminClient(); |
| 72 | + |
| 73 | + const rows = body.events.map((event) => ({ |
| 74 | + event_type: event.event_type, |
| 75 | + event_at: new Date(event.event_at_ms), |
| 76 | + data: event.data as Record<string, unknown>, |
| 77 | + project_id: projectId, |
| 78 | + branch_id: branchId, |
| 79 | + user_id: userId, |
| 80 | + team_id: null, |
| 81 | + refresh_token_id: refreshTokenId, |
| 82 | + session_replay_id: recentSession?.id ?? null, |
| 83 | + session_replay_segment_id: body.session_replay_segment_id, |
| 84 | + })); |
| 85 | + |
| 86 | + await clickhouseClient.insert({ |
| 87 | + table: "analytics_internal.events", |
| 88 | + values: rows, |
| 89 | + format: "JSONEachRow", |
| 90 | + clickhouse_settings: { |
| 91 | + date_time_input_format: "best_effort", |
| 92 | + async_insert: 1, |
| 93 | + }, |
| 94 | + }); |
| 95 | + |
| 96 | + return { |
| 97 | + statusCode: 200, |
| 98 | + bodyType: "json", |
| 99 | + body: { inserted: body.events.length }, |
| 100 | + }; |
| 101 | + }, |
| 102 | +}); |
0 commit comments