Files
supabase/packages/common/telemetry-event.test.ts
Pamela Chia 62d6bf56f8 fix(telemetry): send the live posthog session id on custom events (#53504)
Custom events sent through the telemetry endpoint often carry a session
id the browser's PostHog session has already left: 8.9% of
server-captured events in a recent week had an id more than 24 hours
old, against 0.046% of browser-captured ones. Two things on the client
cause it. The `session_id` in the request body is parsed out of the
PostHog cookie without going through posthog-js, so a custom event never
rotates an expired session. And the `session_id` cookie, which the API
reads for the events it emits itself, was written on each pageview
before posthog-js rotated the session, so the first pageview after an
idle period stored the previous session's id.

**Changed:**
- **Custom events carry the live session id**: I changed
`buildTelemetryEventRequest` to ask posthog-js for the session id the
way a captured event does, so an expired session rotates first. Until
posthog-js has loaded it sends the cookie-parsed id, as before.
- **The `session_id` cookie follows the session**: I moved the write
from the pageview handler to posthog-js's session-change callback, plus
one write when posthog-js loads, so the cookie changes when the session
does.
- **The cookie stays cleared after an opt-out**: when a visitor
withdraws consent, posthog-js resets the session, and the new id would
have been written back over the cleared cookie. I skip the write once
the visitor has opted out, in this tab or another. Unit tests cover this
one: preview builds accept consent by default, so withdrawal can't be
exercised there.
- **Session metrics will step**: custom events now count as session
activity. A long-lived tab that sends events without navigating stays in
one session, so expect fewer, longer sessions from the day this reaches
each app.

**Note:** The API starts reading the body's `session_id` in a companion
change on its side. Either can deploy first: the field is already sent
today and ignored.

## To test

Tested on the PR preview:
- [x] In Studio with the Network tab open, open the user dropdown in the
header. Expect the `telemetry/event` request body's `session_id` to
equal the `session_id` cookie.
- [x] Open the dropdown again right away. Expect the same `session_id`
as in the first request.
- [x] Leave that tab untouched for 35 minutes, then open the user
dropdown again without navigating. Expect a different `session_id` in
the request body than in the first step, and the `session_id` cookie to
equal the new one. Observed after 38 idle minutes.
- [x] Navigate to another Studio page. Expect the `session_id` cookie to
keep the value from the previous step. Observed on an in-app navigation
to the account page.

## Linear
- fixes GROWTH-1509
2026-11-20 16:22:11 +09:00

195 lines
6.8 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { posthogClient } from './posthog-client'
import { sendTelemetryEvent } from './telemetry'
import type { TelemetryEvent } from './telemetry-constants'
import { buildTelemetryEventRequest, setTelemetryFeatureFlags } from './telemetry-event'
const { consent, platform, post } = vi.hoisted(() => ({
consent: { value: true },
platform: { value: undefined as string | undefined },
post: vi.fn(() => Promise.resolve()),
}))
vi.mock('./consent-state', () => ({
hasConsented: () => consent.value,
useConsentState: () => ({ hasAccepted: consent.value }),
}))
vi.mock('./telemetry-utils', () => ({
getSharedTelemetryData: () => ({ page_title: 'Page', session_id: 'cookie-session' }),
getTelemetryCookieOptions: () => ({}),
getTelemetryPlatform: () => platform.value,
}))
vi.mock('./fetchWrappers', () => ({ post }))
vi.mock('./auth', () => ({ useUser: () => null }))
const API_URL = 'https://api.example.com'
beforeEach(() => {
consent.value = true
platform.value = undefined
setTelemetryFeatureFlags({})
post.mockClear()
})
describe('buildTelemetryEventRequest', () => {
it('returns null without consent', () => {
consent.value = false
expect(
buildTelemetryEventRequest(API_URL, {
action: 'explorer_banner_exposed',
groups: { project: 'p', organization: 'o' },
})
).toBeNull()
})
it('sets the Explorer page title for explorer_ events only', () => {
const explorer = buildTelemetryEventRequest(API_URL, {
action: 'explorer_banner_exposed',
groups: { project: 'p', organization: 'o' },
})
const other = buildTelemetryEventRequest(API_URL, {
action: 'kb_search_submitted',
properties: { queryLength: 3, queryWordCount: 1, resultCount: 1, hasResults: true },
})
expect(explorer?.body.page_title).toBe('Explorer')
expect(other?.body.page_title).toBe('Page')
})
it('drops an Unknown project, and all groups when the organization is Unknown too', () => {
const projectOnly = buildTelemetryEventRequest(API_URL, {
action: 'explorer_banner_exposed',
groups: { project: 'Unknown', organization: 'o' },
})
const both = buildTelemetryEventRequest(API_URL, {
action: 'explorer_banner_exposed',
groups: { project: 'Unknown', organization: 'Unknown' },
})
expect(projectOnly?.body.groups).toEqual({ organization: 'o' })
expect(both?.body).not.toHaveProperty('groups')
})
it('targets the platform endpoint and sets keepalive by action', () => {
const click = buildTelemetryEventRequest(API_URL, {
action: 'kb_search_result_clicked',
properties: { resultPath: '/kb/a', resultPosition: 1, resultCount: 1 },
})
const submit = buildTelemetryEventRequest(API_URL, {
action: 'kb_search_submitted',
properties: { queryLength: 3, queryWordCount: 1, resultCount: 1, hasResults: true },
})
expect(click?.url).toBe('https://api.example.com/platform/telemetry/event')
expect(click?.keepalive).toBe(true)
expect(submit?.keepalive).toBe(false)
})
it("adds the app's platform to custom_properties only once it is set", () => {
const event = {
action: 'kb_search_submitted',
properties: { queryLength: 3, queryWordCount: 1, resultCount: 1, hasResults: true },
} as const
const unset = buildTelemetryEventRequest(API_URL, event)
platform.value = 'kb'
const set = buildTelemetryEventRequest(API_URL, event)
expect(unset?.body.custom_properties).toStrictEqual(event.properties)
expect(set?.body.custom_properties).toStrictEqual({ ...event.properties, platform: 'kb' })
})
it('stamps each PostHog flag as $feature/<key>, with the caller winning on the same key', () => {
const properties = {
query: 'abc',
queryLength: 3,
queryWordCount: 1,
resultCount: 1,
hasResults: true,
}
setTelemetryFeatureFlags({ flagA: 'test', flagB: false })
const stamped = buildTelemetryEventRequest(API_URL, {
action: 'kb_search_submitted',
properties,
})
const overridden = buildTelemetryEventRequest(API_URL, {
action: 'kb_search_submitted',
properties: { ...properties, '$feature/flagA': 'control' },
} as TelemetryEvent)
expect(stamped?.body.custom_properties).toStrictEqual({
'$feature/flagA': 'test',
'$feature/flagB': false,
...properties,
})
expect(overridden?.body.custom_properties).toMatchObject({
'$feature/flagA': 'control',
'$feature/flagB': false,
})
})
it('sends the live PostHog session id, and the cookie one until PostHog has loaded', () => {
const event = {
action: 'kb_search_submitted',
properties: {
query: 'abc',
queryLength: 3,
queryWordCount: 1,
resultCount: 1,
hasResults: true,
},
} as const
const refreshSessionId = vi.spyOn(posthogClient, 'refreshSessionId')
refreshSessionId.mockReturnValueOnce('live-session')
const loaded = buildTelemetryEventRequest(API_URL, event)
refreshSessionId.mockReturnValueOnce(undefined)
const notLoaded = buildTelemetryEventRequest(API_URL, event)
expect(loaded?.body).toHaveProperty('session_id', 'live-session')
expect(notLoaded?.body).toHaveProperty('session_id', 'cookie-session')
})
it('builds the same endpoint whether the API URL has a trailing slash or /platform', () => {
const event = {
action: 'kb_search_submitted',
properties: { queryLength: 3, queryWordCount: 1, resultCount: 1, hasResults: true },
} as const
for (const apiUrl of [
'https://api.example.com/',
'https://api.example.com/platform',
'https://api.example.com/platform/',
'https://api.example.com//',
'https://api.example.com/platform//',
]) {
expect(buildTelemetryEventRequest(apiUrl, event)?.url).toBe(
'https://api.example.com/platform/telemetry/event'
)
}
})
})
describe('sendTelemetryEvent', () => {
it('posts the built request with the v2 header and keepalive', async () => {
await sendTelemetryEvent(API_URL, {
action: 'kb_search_result_clicked',
properties: { resultPath: '/kb/a', resultPosition: 2, resultCount: 3 },
})
expect(post).toHaveBeenCalledWith(
'https://api.example.com/platform/telemetry/event',
expect.objectContaining({
action: 'kb_search_result_clicked',
custom_properties: { resultPath: '/kb/a', resultPosition: 2, resultCount: 3 },
}),
{ headers: { Version: '2' }, keepalive: true }
)
})
it('posts nothing without consent', async () => {
consent.value = false
await sendTelemetryEvent(API_URL, {
action: 'kb_search_submitted',
properties: { queryLength: 3, queryWordCount: 1, resultCount: 1, hasResults: true },
})
expect(post).not.toHaveBeenCalled()
})
})