From 58ee28a55ea81d8624370882774795d7a5c521f8 Mon Sep 17 00:00:00 2001 From: Francis Cao Date: Tue, 21 Jul 2026 12:33:41 -0700 Subject: [PATCH] remove session recalculate and related queries --- src/app/api/send/route.ts | 38 +++++++++--------- src/lib/session.test.ts | 46 ++++----------------- src/lib/session.ts | 13 ------ src/queries/sql/index.ts | 1 + src/queries/sql/sessions/updateSession.ts | 49 +++++++++++++++++++++++ 5 files changed, 75 insertions(+), 72 deletions(-) delete mode 100644 src/lib/session.ts create mode 100644 src/queries/sql/sessions/updateSession.ts diff --git a/src/app/api/send/route.ts b/src/app/api/send/route.ts index 7d6f64ec1..cf0c30ffd 100644 --- a/src/app/api/send/route.ts +++ b/src/app/api/send/route.ts @@ -10,9 +10,8 @@ import { fetchWebsite } from '@/lib/load'; import { parseRequest } from '@/lib/request'; import { badRequest, forbidden, json, serverError } from '@/lib/response'; import { anyObjectParam, urlOrPathParam } from '@/lib/schema'; -import { getSessionId } from '@/lib/session'; import { safeDecodeURI, safeDecodeURIComponent } from '@/lib/url'; -import { createSession, saveEvent, saveSessionData, saveSessionLink } from '@/queries/sql'; +import { createSession, saveEvent, saveSessionData, saveSessionLink, updateSession } from '@/queries/sql'; interface Cache { websiteId: string; @@ -130,7 +129,7 @@ export async function POST(request: Request) { } } - // Carried forward in the cache token so repeat identify calls skip the link write + // Carried forward in the cache token so repeat identify calls skip identity writes let sessionLinkId = cache?.sessionLinkId; // Client info @@ -156,7 +155,7 @@ export async function POST(request: Request) { const sessionSalt = getSalt(saltRotation, createdAt); const visitSalt = hash(startOfHour(createdAt).toUTCString()); - const sessionId = getSessionId(sourceId, ip, userAgent, sessionSalt, id); + const sessionId = uuid(sourceId, ip, userAgent, sessionSalt); // Create a session if not found if (!clickhouse.enabled && !cache?.sessionId) { @@ -283,25 +282,24 @@ export async function POST(request: Request) { }); } else if (type === COLLECTION_TYPE.identify) { if (websiteId && id) { - // Persist both memberships so stitched activity can be resolved from - // either the anonymous session or the identified session. - const anonymousSessionId = getSessionId(sourceId, ip, userAgent, sessionSalt); - const linkedSessionIds = [...new Set([anonymousSessionId, sessionId])]; - const newLinkId = hash(...linkedSessionIds, id); + const newLinkId = hash(sessionId, id); if (sessionLinkId !== newLinkId) { - // Best-effort: a link failure must not block the session data write below + // Best-effort: identity link failures must not block the session data write below. try { - await Promise.all( - linkedSessionIds.map(linkedSessionId => - saveSessionLink({ - websiteId, - sessionId: linkedSessionId, - distinctId: id, - createdAt, - }), - ), - ); + await Promise.all([ + saveSessionLink({ + websiteId, + sessionId, + distinctId: id, + createdAt, + }), + updateSession({ + websiteId, + sessionId, + distinctId: id, + }), + ]); sessionLinkId = newLinkId; } catch (e) { // eslint-disable-next-line no-console diff --git a/src/lib/session.test.ts b/src/lib/session.test.ts index 412faa498..154dd5d18 100644 --- a/src/lib/session.test.ts +++ b/src/lib/session.test.ts @@ -1,56 +1,24 @@ import { expect, test } from 'vitest'; import { uuid } from './crypto'; -import { getSessionId } from './session'; const sourceId = '2e2fc91f-77a7-4e5d-a7b1-18a74c67b4e0'; const sessionSalt = 'monthly-session-salt'; -test('keeps identified sessions stable on the same device', () => { - const args = [sourceId, '192.0.2.1', 'Desktop Browser', sessionSalt, 'user-123'] as const; +test('keeps session IDs stable on the same device', () => { + const args = [sourceId, '192.0.2.1', 'Desktop Browser', sessionSalt] as const; - expect(getSessionId(...args)).toBe(getSessionId(...args)); + expect(uuid(...args)).toBe(uuid(...args)); }); -test('creates separate sessions for the same distinct ID on different devices', () => { - const desktopSessionId = getSessionId( - sourceId, - '192.0.2.1', - 'Desktop Browser', - sessionSalt, - 'user-123', - ); - const mobileSessionId = getSessionId( - sourceId, - '198.51.100.2', - 'Mobile Browser', - sessionSalt, - 'user-123', - ); +test('creates separate sessions on different devices', () => { + const desktopSessionId = uuid(sourceId, '192.0.2.1', 'Desktop Browser', sessionSalt); + const mobileSessionId = uuid(sourceId, '198.51.100.2', 'Mobile Browser', sessionSalt); expect(desktopSessionId).not.toBe(mobileSessionId); }); -test('does not merge different identified users on the same device', () => { - const firstUserSessionId = getSessionId( - sourceId, - '192.0.2.1', - 'Desktop Browser', - sessionSalt, - 'user-123', - ); - const secondUserSessionId = getSessionId( - sourceId, - '192.0.2.1', - 'Desktop Browser', - sessionSalt, - 'user-456', - ); - - expect(firstUserSessionId).not.toBe(secondUserSessionId); -}); - test('preserves anonymous session IDs', () => { - expect(getSessionId(sourceId, '192.0.2.1', 'Desktop Browser', sessionSalt)).toBe( + expect(uuid(sourceId, '192.0.2.1', 'Desktop Browser', sessionSalt)).toBe( uuid(sourceId, '192.0.2.1', 'Desktop Browser', sessionSalt), ); }); diff --git a/src/lib/session.ts b/src/lib/session.ts deleted file mode 100644 index fdfe44631..000000000 --- a/src/lib/session.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { uuid } from './crypto'; - -export function getSessionId( - sourceId: string, - ip: string, - userAgent: string, - sessionSalt: string, - distinctId?: string, -) { - return distinctId - ? uuid(sourceId, ip, userAgent, sessionSalt, distinctId) - : uuid(sourceId, ip, userAgent, sessionSalt); -} diff --git a/src/queries/sql/index.ts b/src/queries/sql/index.ts index 2139e58af..4833adfcc 100644 --- a/src/queries/sql/index.ts +++ b/src/queries/sql/index.ts @@ -65,3 +65,4 @@ export * from './sessions/getWebsiteSessionStats'; export * from './sessions/getWebsiteSessions'; export * from './sessions/saveSessionData'; export * from './sessions/saveSessionLink'; +export * from './sessions/updateSession'; diff --git a/src/queries/sql/sessions/updateSession.ts b/src/queries/sql/sessions/updateSession.ts new file mode 100644 index 000000000..6780123d1 --- /dev/null +++ b/src/queries/sql/sessions/updateSession.ts @@ -0,0 +1,49 @@ +import clickhouse from '@/lib/clickhouse'; +import { FIELD_LENGTH } from '@/lib/constants'; +import { CLICKHOUSE, PRISMA, runQuery } from '@/lib/db'; +import { truncateString } from '@/lib/format'; +import prisma from '@/lib/prisma'; + +const FUNCTION_NAME = 'updateSession'; + +export interface UpdateSessionArgs { + websiteId: string; + sessionId: string; + distinctId: string; +} + +export async function updateSession(data: UpdateSessionArgs) { + return runQuery({ + [PRISMA]: () => relationalQuery(data), + [CLICKHOUSE]: () => clickhouseQuery(), + }); +} + +async function relationalQuery({ websiteId, sessionId, distinctId }: UpdateSessionArgs) { + const { writeRawQuery } = prisma; + + await writeRawQuery( + ` + update session + set distinct_id = {{distinctId}} + where website_id = {{websiteId}} + and session_id = {{sessionId}} + and coalesce(distinct_id, '') != {{distinctId}} + `, + { + websiteId, + sessionId, + distinctId: truncateString(distinctId, FIELD_LENGTH.distinctId), + }, + FUNCTION_NAME, + ); +} + +async function clickhouseQuery() { + if (!clickhouse.enabled) { + return; + } + + // ClickHouse session reads fall back to session_link because session rows are event-derived. + return; +}