remove session recalculate and related queries

This commit is contained in:
Francis Cao committed 2026-07-21 12:33:41 -07:00
1 parent eb9a77ea64
commit 58ee28a55e
5 files changed
+75 -72

No files matched your search

+18 -20
View File
@@ -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
+7 -39
View File
@@ -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),
);
});
-13
View File
@@ -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);
}
+1
View File
@@ -65,3 +65,4 @@ export * from './sessions/getWebsiteSessionStats';
export * from './sessions/getWebsiteSessions';
export * from './sessions/saveSessionData';
export * from './sessions/saveSessionLink';
export * from './sessions/updateSession';
+49
View File
@@ -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;
}