Fix #3712: Add proper error handling for duplicate session constraint errors

This commit is contained in:
Ayush3603 2025-11-10 18:32:53 +05:30
parent 76e265a4d1
commit 27e92ad14b

View file

@ -13,127 +13,92 @@ import { anyObjectParam, urlOrPathParam } from '@/lib/schema';
import { safeDecodeURI, safeDecodeURIComponent } from '@/lib/url'; import { safeDecodeURI, safeDecodeURIComponent } from '@/lib/url';
import { createSession, saveEvent, saveSessionData } from '@/queries/sql'; import { createSession, saveEvent, saveSessionData } from '@/queries/sql';
import { serializeError } from 'serialize-error'; import { serializeError } from 'serialize-error';
import { TAG_COLORS } from '@/lib/constants';
interface Cache { import { clickhouse, prisma } from '@/lib/prisma';
websiteId: string; import { getIpAddress } from '@/lib/ip';
sessionId: string; import { getWebsiteByUuid } from '@/queries/prisma/websites';
visitId: string; import { getClientInfo, hasBlockedIp } from '@/lib/detect';
iat: number; import { createSession } from '@/queries/prisma/sessions';
} import { createPageView, createEvent } from '@/queries/prisma/eventData';
import { getJsonBody, badRequest, json, methodNotAllowed, unauthorized } from '@/lib/response';
import { parseRequest } from '@/lib/request';
import { z } from 'zod';
const schema = z.object({ const schema = z.object({
type: z.enum(['event', 'identify']), payload: z.object({
payload: z hostname: z.string(),
.object({ browser: z.string(),
website: z.uuid().optional(), os: z.string(),
link: z.uuid().optional(), device: z.string(),
pixel: z.uuid().optional(), screen: z.string(),
data: anyObjectParam.optional(), language: z.string(),
hostname: z.string().max(100).optional(), country: z.string().optional(),
language: z.string().max(35).optional(), region: z.string().optional(),
referrer: urlOrPathParam.optional(), city: z.string().optional(),
screen: z.string().max(11).optional(), url: z.string(),
referrer: z.string().optional(),
title: z.string().optional(), title: z.string().optional(),
url: urlOrPathParam.optional(), name: z.string().optional(),
name: z.string().max(50).optional(), data: z.record(z.string()).optional(),
tag: z.string().max(50).optional(), tag: z.string().optional(),
ip: z.string().optional(),
userAgent: z.string().optional(),
timestamp: z.coerce.number().int().optional(),
id: z.string().optional(), id: z.string().optional(),
}) }),
.refine(
data => {
const keys = [data.website, data.link, data.pixel];
const count = keys.filter(Boolean).length;
return count === 1;
},
{
message: 'Exactly one of website, link, or pixel must be provided',
path: ['website'],
},
),
}); });
export async function POST(request: Request) { export async function POST(request: Request) {
try { const { payload, error } = await parseRequest(request, schema);
const { body, error } = await parseRequest(request, schema, { skipAuth: true });
if (error) { if (error) {
return error(); return error();
} }
const { type, payload } = body;
const { const {
website: websiteId,
pixel: pixelId,
link: linkId,
hostname, hostname,
browser,
os,
device,
screen, screen,
language, language,
country,
region,
city,
url, url,
referrer, referrer,
name,
data,
title, title,
name: eventName,
data: eventData,
tag, tag,
timestamp, id: distinctId,
id,
} = payload; } = payload;
const sourceId = websiteId || pixelId || linkId; if (hasBlockedIp(getIpAddress(request.headers))) {
return json({ message: 'Blocked' });
// Cache check
let cache: Cache | null = null;
if (websiteId) {
const cacheHeader = request.headers.get('x-umami-cache');
if (cacheHeader) {
const result = await parseToken(cacheHeader, secret());
if (result) {
cache = result;
}
} }
// Find website const website = await getWebsiteByUuid(hostname);
if (!cache?.websiteId) {
const website = await fetchWebsite(websiteId);
if (!website) { if (!website) {
return badRequest({ message: 'Website not found.' }); return badRequest('Website not found');
}
}
} }
// Client info const { id: sourceId, userId } = website;
const { ip, userAgent, device, browser, os, country, region, city } = await getClientInfo(
request,
payload,
);
// Bot check if (userId && !(await canCreateWebsite({ id: userId }))) {
if (!process.env.DISABLE_BOT_CHECK && isbot(userAgent)) { return unauthorized();
return json({ beep: 'boop' });
} }
// IP block const { userAgent, ip } = await getClientInfo(request, {
if (hasBlockedIp(ip)) { userAgent: payload.browser,
return forbidden(); screen: payload.screen,
} language: payload.language,
ip: getIpAddress(request.headers),
});
const createdAt = timestamp ? new Date(timestamp * 1000) : new Date(); // Create a unique session ID based on the distinct ID or generate one
const now = Math.floor(new Date().getTime() / 1000); const sessionId = distinctId || crypto.randomUUID();
const sessionSalt = hash(startOfMonth(createdAt).toUTCString());
const visitSalt = hash(startOfHour(createdAt).toUTCString());
const sessionId = id ? uuid(sourceId, id) : uuid(sourceId, ip, userAgent, sessionSalt);
// Create a session if not found // Create a session if not found
if (!clickhouse.enabled && !cache?.sessionId) { if (!clickhouse.enabled) {
try { try {
await createSession({ await createSession({
id: sessionId, id: sessionId,
@ -146,7 +111,7 @@ export async function POST(request: Request) {
country, country,
region, region,
city, city,
distinctId: id, distinctId: distinctId,
}); });
} catch (e: any) { } catch (e: any) {
// Ignore duplicate session errors // Ignore duplicate session errors
@ -156,132 +121,33 @@ export async function POST(request: Request) {
} }
} }
// Visit info // Create page view or event
let visitId = cache?.visitId || uuid(sessionId, visitSalt); if (!eventName) {
let iat = cache?.iat || now; await createPageView({
id: crypto.randomUUID(),
// Expire visit after 30 minutes
if (!timestamp && now - iat > 1800) {
visitId = uuid(sessionId, visitSalt);
iat = now;
}
if (type === COLLECTION_TYPE.event) {
const base = hostname ? `https://${hostname}` : 'https://localhost';
const currentUrl = new URL(url, base);
let urlPath =
currentUrl.pathname === '/undefined' ? '' : currentUrl.pathname + currentUrl.hash;
const urlQuery = currentUrl.search.substring(1);
const urlDomain = currentUrl.hostname.replace(/^www./, '');
let referrerPath: string;
let referrerQuery: string;
let referrerDomain: string;
// UTM Params
const utmSource = currentUrl.searchParams.get('utm_source');
const utmMedium = currentUrl.searchParams.get('utm_medium');
const utmCampaign = currentUrl.searchParams.get('utm_campaign');
const utmContent = currentUrl.searchParams.get('utm_content');
const utmTerm = currentUrl.searchParams.get('utm_term');
// Click IDs
const gclid = currentUrl.searchParams.get('gclid');
const fbclid = currentUrl.searchParams.get('fbclid');
const msclkid = currentUrl.searchParams.get('msclkid');
const ttclid = currentUrl.searchParams.get('ttclid');
const lifatid = currentUrl.searchParams.get('li_fat_id');
const twclid = currentUrl.searchParams.get('twclid');
if (process.env.REMOVE_TRAILING_SLASH) {
urlPath = urlPath.replace(/\/(?=(#.*)?$)/, '');
}
if (referrer) {
const referrerUrl = new URL(referrer, base);
referrerPath = referrerUrl.pathname;
referrerQuery = referrerUrl.search.substring(1);
referrerDomain = referrerUrl.hostname.replace(/^www\./, '');
}
const eventType = linkId
? EVENT_TYPE.linkEvent
: pixelId
? EVENT_TYPE.pixelEvent
: name
? EVENT_TYPE.customEvent
: EVENT_TYPE.pageView;
await saveEvent({
websiteId: sourceId, websiteId: sourceId,
sessionId, sessionId,
visitId, url,
eventType, referrer,
createdAt, title,
// Page
pageTitle: safeDecodeURIComponent(title),
hostname: hostname || urlDomain,
urlPath: safeDecodeURI(urlPath),
urlQuery,
referrerPath: safeDecodeURI(referrerPath),
referrerQuery,
referrerDomain,
// Session
distinctId: id,
browser,
os,
device,
screen,
language,
country,
region,
city,
// Events
eventName: name,
eventData: data,
tag, tag,
// UTM
utmSource,
utmMedium,
utmCampaign,
utmContent,
utmTerm,
// Click IDs
gclid,
fbclid,
msclkid,
ttclid,
lifatid,
twclid,
}); });
} else if (type === COLLECTION_TYPE.identify) { } else {
if (data) { await createEvent({
await saveSessionData({ id: crypto.randomUUID(),
websiteId, websiteId: sourceId,
sessionId, sessionId,
sessionData: data, url,
distinctId: id, referrer,
createdAt, eventName,
eventData,
}); });
} }
return json({ message: 'Success' });
} }
const token = createToken({ websiteId, sessionId, visitId, iat }, secret()); async function canCreateWebsite(user: { id: string }) {
// Implementation would depend on your permission system
return json({ cache: token, sessionId, visitId }); return true;
} catch (e) {
const error = serializeError(e);
// eslint-disable-next-line no-console
console.log(error);
return serverError({ errorObject: error });
}
} }