Skip to content

๐Ÿ“ˆ Open source, privacy-first web analytics โ€” a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Introduce Profiles

Blue Mouse4a21f0caf5f7
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index 5aeb7a373..75ba316d0 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -1158,7 +1158,19 @@ export class AnalyticsController {
ip,
)
- await this.analyticsService.processInteractionSD(psid, errorDTO.pid)
+ const profileId = await this.analyticsService.generateProfileId(
+ errorDTO.pid,
+ userAgent,
+ ip,
+ errorDTO.profileId,
+ )
+
+ await this.analyticsService.recordSession(
+ psid,
+ errorDTO.pid,
+ profileId,
+ false,
+ )
const { city, region, regionCode, country } = getGeoDetails(ip, errorDTO.tz)
@@ -1170,6 +1182,7 @@ export class AnalyticsController {
const transformed = errorEventTransformer(
psid,
+ profileId,
this.analyticsService.getErrorID(errorDTO),
errorDTO.pid,
this.analyticsService.getHostFromOrigin(headers.origin),
@@ -1281,8 +1294,23 @@ export class AnalyticsController {
ip,
)
+ const profileId = await this.analyticsService.generateProfileId(
+ eventsDTO.pid,
+ userAgent,
+ ip,
+ eventsDTO.profileId,
+ )
+
+ await this.analyticsService.recordSession(
+ psid,
+ eventsDTO.pid,
+ profileId,
+ false,
+ )
+
const transformed = customEventTransformer(
psid,
+ profileId,
eventsDTO.pid,
this.analyticsService.getHostFromOrigin(headers.origin),
eventsDTO.ev,
@@ -1354,9 +1382,15 @@ export class AnalyticsController {
)
}
- await this.analyticsService.extendSessionTTL(psid)
+ const profileId = await this.analyticsService.generateProfileId(
+ pid,
+ userAgent,
+ ip,
+ logDTO.profileId,
+ )
- await this.analyticsService.processInteractionSD(psid, pid)
+ await this.analyticsService.extendSessionTTL(psid)
+ await this.analyticsService.updateSessionActivity(psid, pid, profileId)
return {}
}
@@ -1384,7 +1418,14 @@ export class AnalyticsController {
ip,
)
- await this.analyticsService.processInteractionSD(psid, logDTO.pid)
+ const profileId = await this.analyticsService.generateProfileId(
+ logDTO.pid,
+ userAgent,
+ ip,
+ logDTO.profileId,
+ )
+
+ await this.analyticsService.recordSession(psid, logDTO.pid, profileId, true)
if (!unique && logDTO.unique) {
throw new ForbiddenException(
@@ -1399,6 +1440,7 @@ export class AnalyticsController {
const transformed = trafficTransformer(
psid,
+ profileId,
logDTO.pid,
this.analyticsService.getHostFromOrigin(headers.origin),
logDTO.pg,
@@ -1516,7 +1558,13 @@ export class AnalyticsController {
ip,
)
- await this.analyticsService.processInteractionSD(psid, logDTO.pid)
+ const profileId = await this.analyticsService.generateProfileId(
+ logDTO.pid,
+ userAgent,
+ ip,
+ )
+
+ await this.analyticsService.recordSession(psid, logDTO.pid, profileId, true)
const { city, region, regionCode, country } = getGeoDetails(ip)
@@ -1525,6 +1573,7 @@ export class AnalyticsController {
const transformed = trafficTransformer(
psid,
+ profileId,
logDTO.pid,
this.analyticsService.getHostFromOrigin(headers.origin),
null,
@@ -1735,7 +1784,6 @@ export class AnalyticsController {
from,
to,
timeBucket,
- //
} = data
await this.analyticsService.checkProjectAccess(
@@ -1788,12 +1836,7 @@ export class AnalyticsController {
@CurrentUserId() uid: string,
@Headers() headers: { 'x-password'?: string },
) {
- const {
- pid,
- psid,
- timezone = DEFAULT_TIMEZONE,
- //
- } = data
+ const { pid, psid, timezone = DEFAULT_TIMEZONE } = data
await this.analyticsService.checkProjectAccess(
pid,
diff --git a/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 98932cbfa..2e7e85d16 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -17,7 +17,6 @@ import _last from 'lodash/last'
import _replace from 'lodash/replace'
import _some from 'lodash/some'
import _find from 'lodash/find'
-import _now from 'lodash/now'
import _isString from 'lodash/isString'
import _values from 'lodash/values'
import _round from 'lodash/round'
@@ -114,8 +113,6 @@ dayjs.extend(isSameOrBefore)
// 2 minutes
const LIVE_SESSION_THRESHOLD_SECONDS = 120
-const getSessionDurationKey = (psid: string, pid: string) => `sd:${psid}:${pid}`
-
const SOFTWARE_WITH_PATCH_VERSION = ['GameVault']
const GMT_0_TIMEZONES = [
@@ -728,26 +725,6 @@ export class AnalyticsService {
}
}
- async isSessionDurationOpen(sdKey: string): Promise<[string, boolean]> {
- const sd = await redis.get(sdKey)
- return [sd, Boolean(sd)]
- }
-
- // Processes interaction for session duration
- async processInteractionSD(psid: string, pid: string): Promise<void> {
- const sdKey = getSessionDurationKey(psid, pid)
- const [sd, isOpened] = await this.isSessionDurationOpen(sdKey)
- const now = _now()
-
- // the value is START_UNIX_TIMESTAMP:LAST_INTERACTION_UNIX_TIMESTAMP
- if (isOpened) {
- const [start] = _split(sd, ':')
- await redis.set(sdKey, `${start}:${now}`, 'EX', UNIQUE_SESSION_LIFE_TIME)
- } else {
- await redis.set(sdKey, `${now}:${now}`, 'EX', UNIQUE_SESSION_LIFE_TIME)
- }
- }
-
async getPagesArray(
rawPages?: string,
funnelId?: string,
@@ -1139,7 +1116,7 @@ export class AnalyticsService {
userAgent: string,
ip: string,
): Promise<{ exists: boolean; psid: string }> {
- const salt = await this.saltService.getSaltForProject(pid)
+ const salt = await this.saltService.getSaltForSession()
const psid = this.derivePsidFromInputs(pid, userAgent, ip, salt)
const sessionKey = this.getSessionKey(psid)
@@ -1165,6 +1142,162 @@ export class AnalyticsService {
await redis.set(sessionKey, '1', 'EX', UNIQUE_SESSION_LIFE_TIME)
}
+ static readonly PROFILE_PREFIX_ANON = 'anon_'
+ static readonly PROFILE_PREFIX_USER = 'usr_'
+
+ private hashToNumericString(value: string): string {
+ return crypto
+ .createHash('sha256')
+ .update(value)
+ .digest()
+ .readBigUInt64BE(0)
+ .toString()
+ }
+
+ async generateProfileId(
+ pid: string,
+ userAgent: string,
+ ip: string,
+ userSupplied?: string,
+ ): Promise<string> {
+ if (userSupplied) {
+ const cleanId = userSupplied
+ .replace(AnalyticsService.PROFILE_PREFIX_ANON, '')
+ .replace(AnalyticsService.PROFILE_PREFIX_USER, '')
+ const hash = this.hashToNumericString(`${cleanId}${pid}`)
+ return `${AnalyticsService.PROFILE_PREFIX_USER}${hash}`
+ }
+
+ const salt = await this.saltService.getSaltForProfile()
+ const combined = `${userAgent}${ip}${pid}${salt}`
+ const hash = this.hashToNumericString(combined)
+
+ return `${AnalyticsService.PROFILE_PREFIX_ANON}${hash}`
+ }
+
+ isUserSuppliedProfile(profileId: string): boolean {
+ return profileId.startsWith(AnalyticsService.PROFILE_PREFIX_USER)
+ }
+
+ async recordSession(
+ psid: string,
+ pid: string,
+ profileId: string,
+ isPageview: boolean = true,
+ ): Promise<void> {
+ const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+
+ try {
+ await clickhouse.insert({
+ table: 'sessions',
+ format: 'JSONEachRow',
+ values: [
+ {
+ psid,
+ pid,
+ profileId,
+ firstSeen: now,
+ lastSeen: now,
+ pageviews: isPageview ? 1 : 0,
+ events: isPageview ? 0 : 1,
+ },
+ ],
+ clickhouse_settings: { async_insert: 1 },
+ })
+ } catch (error) {
+ console.error('Failed to record session:', error)
+ }
+ }
+
+ async updateSessionActivity(
+ psid: string,
+ pid: string,
+ profileId: string,
+ ): Promise<void> {
+ const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+
+ try {
+ await clickhouse.insert({
+ table: 'sessions',
+ format: 'JSONEachRow',
+ values: [
+ {
+ psid,
+ pid,
+ profileId,
+ firstSeen: now,
+ lastSeen: now,
+ pageviews: 0,
+ events: 0,
+ },
+ ],
+ clickhouse_settings: { async_insert: 1 },
+ })
+ } catch (error) {
+ console.error('Failed to update session activity:', error)
+ }
+ }
+
+ async checkSessionExistsInClickHouse(
+ psid: string,
+ pid: string,
+ ): Promise<boolean> {
+ const cutoff = dayjs
+ .utc()
+ .subtract(UNIQUE_SESSION_LIFE_TIME, 'second')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ try {
+ const query = `
+ SELECT 1
+ FROM sessions FINAL
+ WHERE psid = {psid:UInt64}
+ AND pid = {pid:FixedString(12)}
+ AND lastSeen >= {cutoff:DateTime}
+ LIMIT 1
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { psid, pid, cutoff },
+ })
+ .then(resultSet => resultSet.json())
+
+ return data.length > 0
+ } catch (error) {
+ console.error('Failed to check session existence:', error)
+ return false
+ }
+ }
+
+ async getSessionDurationFromClickHouse(
+ psid: string,
+ pid: string,
+ ): Promise<number | null> {
+ try {
+ const query = `
+ SELECT dateDiff('second', firstSeen, lastSeen) as duration
+ FROM sessions FINAL
+ WHERE psid = {psid:UInt64}
+ AND pid = {pid:FixedString(12)}
+ LIMIT 1
+ `
+
+ const { data } = await clickhouse
+ .query({
+ query,
+ query_params: { psid, pid },
+ })
+ .then(resultSet => resultSet.json<{ duration: number }>())
+
+ return data[0]?.duration ?? null
+ } catch (error) {
+ console.error('Failed to get session duration:', error)
+ return null
+ }
+ }
+
formatFunnel(data: IFunnelCHResponse[], pages: string[]): IFunnel[] {
const funnel = _map(data, (row, index) => {
const value = pages[index]
@@ -1526,8 +1659,8 @@ export class AnalyticsService {
${filtersQuery}
),
duration_avg AS (
- SELECT avg(duration) as sdur
- FROM session_durations
+ SELECT avg(dateDiff('second', firstSeen, lastSeen)) as sdur
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
)
SELECT
@@ -1608,8 +1741,8 @@ export class AnalyticsService {
${filtersQuery}
),
duration_avg AS (
- SELECT avg(duration) as sdur
- FROM session_durations
+ SELECT avg(dateDiff('second', firstSeen, lastSeen)) as sdur
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
AND psid IN (
SELECT DISTINCT psid
@@ -1638,8 +1771,8 @@ export class AnalyticsService {
${filtersQuery}
),
duration_avg AS (
- SELECT avg(duration) as sdur
- FROM session_durations
+ SELECT avg(dateDiff('second', firstSeen, lastSeen)) as sdur
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
AND psid IN (
SELECT DISTINCT psid
@@ -2401,7 +2534,7 @@ export class AnalyticsService {
const baseQuery = `
SELECT
${selector},
- avgOrNull(session_durations.duration) as sdur,
+ avgOrNull(sessions_data.duration) as sdur,
count() as pageviews,
count(DISTINCT psid) as uniques
FROM (
@@ -2418,12 +2551,12 @@ export class AnalyticsService {
SELECT
pid,
psid,
- duration
- FROM session_durations
+ dateDiff('second', firstSeen, lastSeen) as duration
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
- ) as session_durations
- ON subquery.pid = session_durations.pid
- AND subquery.psid = session_durations.psid
+ ) as sessions_data
+ ON subquery.pid = sessions_data.pid
+ AND subquery.psid = sessions_data.psid
GROUP BY ${groupBy}
ORDER BY ${groupBy}
`
@@ -3914,8 +4047,8 @@ export class AnalyticsService {
const querySessionDuration = `
SELECT
- avg(duration) as duration
- FROM session_durations
+ avg(dateDiff('second', firstSeen, lastSeen)) as duration
+ FROM sessions FINAL
WHERE
pid = {pid:FixedString(12)}
AND CAST(psid, 'String') = {psid:String}
@@ -4116,8 +4249,8 @@ export class AnalyticsService {
SELECT
CAST(psid, 'String') AS psidCasted,
pid,
- avg(duration) as avg_duration
- FROM session_durations
+ avg(dateDiff('second', firstSeen, lastSeen)) as avg_duration
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
GROUP BY psidCasted, pid
)
diff --git a/backend/apps/cloud/src/analytics/dto/error.dto.ts b/backend/apps/cloud/src/analytics/dto/error.dto.ts
index 5c992b131..73b0f3493 100644
--- a/backend/apps/cloud/src/analytics/dto/error.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/error.dto.ts
@@ -32,6 +32,15 @@ export class ErrorDto {
})
pid: string
+ @ApiProperty({
+ example: 'user_12345',
+ description:
+ 'Optional profile ID for long-term user tracking. If not provided, one will be auto-generated.',
+ })
+ @IsOptional()
+ @IsString()
+ profileId?: string
+
// Tracking metrics
@ApiProperty({
example: 'Europe/Kiev',
diff --git a/backend/apps/cloud/src/analytics/dto/events.dto.ts b/backend/apps/cloud/src/analytics/dto/events.dto.ts
index cc1656dbf..3d897b4c6 100644
--- a/backend/apps/cloud/src/analytics/dto/events.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/events.dto.ts
@@ -87,6 +87,14 @@ export class EventsDto {
@Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
pid: string
+ @ApiProperty({
+ example: 'user_12345',
+ description:
+ 'Optional profile ID for long-term user tracking. If not provided, one will be auto-generated.',
+ })
+ @IsOptional()
+ profileId?: string
+
@ApiProperty({
example: 'user-subscribed',
description: 'Event name',
diff --git a/backend/apps/cloud/src/analytics/dto/pageviews.dto.ts b/backend/apps/cloud/src/analytics/dto/pageviews.dto.ts
index d29c114c5..cd3b44fb2 100644
--- a/backend/apps/cloud/src/analytics/dto/pageviews.dto.ts
+++ b/backend/apps/cloud/src/analytics/dto/pageviews.dto.ts
@@ -28,6 +28,14 @@ export class PageviewsDto {
@Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
pid: string
+ @ApiProperty({
+ example: 'user_12345',
+ description:
+ 'Optional profile ID for long-term user tracking. If not provided, one will be auto-generated.',
+ })
+ @IsOptional()
+ profileId?: string
+
// Tracking metrics
@ApiProperty({
example: 'Europe/Kiev',
diff --git a/backend/apps/cloud/src/analytics/salt.service.ts b/backend/apps/cloud/src/analytics/salt.service.ts
index 14f8d74d6..e1aeb7397 100644
--- a/backend/apps/cloud/src/analytics/salt.service.ts
+++ b/backend/apps/cloud/src/analytics/salt.service.ts
@@ -3,32 +3,24 @@ import * as bcrypt from 'bcrypt'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
-import { SaltRotation } from '../project/entity/project.entity'
import { redis } from '../common/constants'
-import { ProjectService } from '../project/project.service'
dayjs.extend(utc)
-// Redis keys for global salts (one per rotation period)
const REDIS_SALT_DAILY = 'salt:daily'
-const REDIS_SALT_WEEKLY = 'salt:weekly'
const REDIS_SALT_MONTHLY = 'salt:monthly'
-// Calculate TTL until end of period
-const getTTLUntilEndOfPeriod = (rotation: SaltRotation): number => {
+export type SaltRotationType = 'daily' | 'monthly'
+
+const getTTLUntilEndOfPeriod = (rotation: SaltRotationType): number => {
const now = dayjs.utc()
let endOfPeriod: dayjs.Dayjs
switch (rotation) {
- case SaltRotation.DAILY:
- endOfPeriod = now.endOf('day')
- break
- case SaltRotation.WEEKLY:
- endOfPeriod = now.endOf('week')
- break
- case SaltRotation.MONTHLY:
+ case 'monthly':
endOfPeriod = now.endOf('month')
break
+ case 'daily':
default:
endOfPeriod = now.endOf('day')
}
@@ -36,66 +28,39 @@ const getTTLUntilEndOfPeriod = (rotation: SaltRotation): number => {
return Math.max(1, endOfPeriod.diff(now, 'second'))
}
-// Get Redis key for rotation type
-const getRedisKeyForRotation = (rotation: SaltRotation): string => {
- switch (rotation) {
- case SaltRotation.WEEKLY:
- return REDIS_SALT_WEEKLY
- case SaltRotation.MONTHLY:
- return REDIS_SALT_MONTHLY
- default:
- return REDIS_SALT_DAILY
- }
+const getRedisKeyForRotation = (rotation: SaltRotationType): string => {
+ return rotation === 'monthly' ? REDIS_SALT_MONTHLY : REDIS_SALT_DAILY
}
@Injectable()
export class SaltService {
private readonly logger = new Logger(SaltService.name)
- constructor(private readonly projectService: ProjectService) {}
-
- /**
- * Generate a new salt value
- */
private async generateSalt(): Promise<string> {
return bcrypt.genSalt(10)
}
- /**
- * Get the appropriate global salt based on the project's rotation setting.
- * Since the hash includes project ID, the same global salt produces unique hashes per project.
- */
- async getSaltForProject(pid: string): Promise<string> {
- // Get the project's salt rotation setting
- let rotation = SaltRotation.DAILY
-
- try {
- const project = await this.projectService.getRedisProject(pid)
- if (project?.saltRotation) {
- rotation = project.saltRotation
- }
- } catch {
- // Default to daily if project not found
- }
+ async getSaltForSession(): Promise<string> {
+ return this.getGlobalSalt('daily')
+ }
+
+ async getSaltForProfile(): Promise<string> {
+ return this.getGlobalSalt('monthly')
+ }
- return this.getGlobalSalt(rotation)
+ /** @deprecated Use getSaltForSession() instead */
+ async getSaltForProject(_pid: string): Promise<string> {
+ return this.getSaltForSession()
}
- /**
- * Get or create a global salt for the specified rotation period
- */
- async getGlobalSalt(
- rotation: SaltRotation = SaltRotation.DAILY,
- ): Promise<string> {
+ async getGlobalSalt(rotation: SaltRotationType = 'daily'): Promise<string> {
const redisKey = getRedisKeyForRotation(rotation)
- // Check if salt exists
const existingSalt = await redis.get(redisKey)
if (existingSalt) {
return existingSalt
}
- // Generate new salt and store with TTL
const salt = await this.generateSalt()
const ttl = getTTLUntilEndOfPeriod(rotation)
await redis.set(redisKey, salt, 'EX', ttl)
@@ -105,16 +70,8 @@ export class SaltService {
return salt
}
- /**
- * Regenerate all global salts (called by cron at midnight UTC)
- * This ensures salts exist even if no requests come in at period boundaries
- */
async regenerateExpiredSalts(): Promise<void> {
- const rotations = [
- SaltRotation.DAILY,
- SaltRotation.WEEKLY,
- SaltRotation.MONTHLY,
- ]
+ const rotations: SaltRotationType[] = ['daily', 'monthly']
for (const rotation of rotations) {
const redisKey = getRedisKeyForRotation(rotation)
diff --git a/backend/apps/cloud/src/analytics/utils/transformers.ts b/backend/apps/cloud/src/analytics/utils/transformers.ts
index 22793b9c1..68c1a8cc0 100644
--- a/backend/apps/cloud/src/analytics/utils/transformers.ts
+++ b/backend/apps/cloud/src/analytics/utils/transformers.ts
@@ -25,6 +25,7 @@ const processMetaKV = (
export const trafficTransformer = (
psid: string,
+ profileId: string,
pid: string,
host: string | null,
pg: string | null,
@@ -48,6 +49,7 @@ export const trafficTransformer = (
) => {
return {
psid,
+ profileId,
pid,
host: host || null,
pg: pg || null,
@@ -74,6 +76,7 @@ export const trafficTransformer = (
export const customEventTransformer = (
psid: string,
+ profileId: string,
pid: string,
host: string | null,
ev: string,
@@ -98,6 +101,7 @@ export const customEventTransformer = (
) => {
return {
psid,
+ profileId,
pid,
host: host || null,
ev,
@@ -125,6 +129,7 @@ export const customEventTransformer = (
export const errorEventTransformer = (
psid: string,
+ profileId: string,
eid: string,
pid: string,
host: string | null,
@@ -149,6 +154,7 @@ export const errorEventTransformer = (
) => {
return {
psid,
+ profileId,
eid,
pid,
host: host || null,
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index 9ec1af618..a682606d7 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -9,7 +9,6 @@ import _isEmpty from 'lodash/isEmpty'
import _isNull from 'lodash/isNull'
import _size from 'lodash/size'
import _map from 'lodash/map'
-import _now from 'lodash/now'
import _find from 'lodash/find'
import _includes from 'lodash/includes'
import _toNumber from 'lodash/toNumber'
@@ -43,7 +42,6 @@ import {
ReportFrequency as UserReportFrequency,
} from '../user/entities/user.entity'
import {
- redis,
SEND_WARNING_AT_PERC,
PROJECT_INVITE_EXPIRE,
JWT_REFRESH_TOKEN_LIFETIME,
@@ -688,8 +686,6 @@ export class TaskManagerService {
)
}
- // Ensure global salts exist for all rotation periods (daily/weekly/monthly)
- // Salts auto-expire via Redis TTL, this just ensures they're regenerated if missing
@Cron(CronExpression.EVERY_HOUR)
async regenerateGlobalSalts() {
await this.saltService.regenerateExpiredSalts()
@@ -731,49 +727,6 @@ export class TaskManagerService {
await this.handleSubscriberReports(ReportFrequency.WEEKLY)
}
- @Cron(CronExpression.EVERY_MINUTE)
- async processSessionDuration() {
- const keys = await redis.keys('sd:*')
- const keysToDelete = []
- const toSave = []
- const now = _now()
-
- const promises = _map(keys, async key => {
- const [start, last] = (await redis.get(key)).split(':')
- const duration = now - Number(last)
-
- // storing to the DB if last interaction was more than 1 minute ago
- if (duration > 60000) {
- const [, psid, pid] = key.split(':')
- toSave.push({
- psid,
- pid,
- duration: Math.max(
- 0,
- Math.floor((Number(last) - Number(start)) / 1000),
- ), // convert to seconds, ensure non-negative
- })
- keysToDelete.push(key)
- }
- })
-
- await Promise.allSettled(promises).catch(reason => {
- this.logger.error(
- `[CRON WORKER](processSessionDuration) Error occured: ${reason}`,
- )
- })
-
- if (_size(toSave) > 0) {
- await redis.del(...keysToDelete)
-
- await clickhouse.insert({
- table: 'session_durations',
- values: toSave,
- format: 'JSONEachRow',
- })
- }
- }
-
@Cron(CronExpression.EVERY_30_MINUTES)
async checkIsTelegramChatIdConfirmed() {
const users = await this.userService.find({
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index de8c9c674..3cd89ed28 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -1273,12 +1273,7 @@ export class AnalyticsController {
@CurrentUserId() uid: string,
@Headers() headers: { 'x-password'?: string },
) {
- const {
- pid,
- psid,
- timezone = DEFAULT_TIMEZONE,
- //
- } = data
+ const { pid, psid, timezone = DEFAULT_TIMEZONE } = data
await this.analyticsService.checkProjectAccess(
pid,
@@ -1620,7 +1615,6 @@ export class AnalyticsController {
from,
to,
timeBucket,
- //
} = data
await this.analyticsService.checkProjectAccess(
diff --git a/backend/apps/community/src/analytics/analytics.service.ts b/backend/apps/community/src/analytics/analytics.service.ts
index 68b0b8808..9ce9d0e3e 100644
--- a/backend/apps/community/src/analytics/analytics.service.ts
+++ b/backend/apps/community/src/analytics/analytics.service.ts
@@ -1385,8 +1385,8 @@ export class AnalyticsService {
${filtersQuery}
),
duration_avg AS (
- SELECT avg(duration) as sdur
- FROM session_durations
+ SELECT avg(dateDiff('second', firstSeen, lastSeen)) as sdur
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
)
SELECT
@@ -1467,8 +1467,8 @@ export class AnalyticsService {
${filtersQuery}
),
duration_avg AS (
- SELECT avg(duration) as sdur
- FROM session_durations
+ SELECT avg(dateDiff('second', firstSeen, lastSeen)) as sdur
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
AND psid IN (
SELECT DISTINCT psid
@@ -1497,8 +1497,8 @@ export class AnalyticsService {
${filtersQuery}
),
duration_avg AS (
- SELECT avg(duration) as sdur
- FROM session_durations
+ SELECT avg(dateDiff('second', firstSeen, lastSeen)) as sdur
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
AND psid IN (
SELECT DISTINCT psid
@@ -2199,7 +2199,7 @@ export class AnalyticsService {
const baseQuery = `
SELECT
${selector},
- avgOrNull(session_durations.duration) as sdur,
+ avgOrNull(sessions_data.duration) as sdur,
count() as pageviews,
count(DISTINCT psid) as uniques
FROM (
@@ -2216,12 +2216,12 @@ export class AnalyticsService {
SELECT
pid,
psid,
- duration
- FROM session_durations
+ dateDiff('second', firstSeen, lastSeen) as duration
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
- ) as session_durations
- ON subquery.pid = session_durations.pid
- AND subquery.psid = session_durations.psid
+ ) as sessions_data
+ ON subquery.pid = sessions_data.pid
+ AND subquery.psid = sessions_data.psid
GROUP BY ${groupBy}
ORDER BY ${groupBy}
`
@@ -3601,8 +3601,8 @@ export class AnalyticsService {
const querySessionDuration = `
SELECT
- avg(duration) as duration
- FROM session_durations
+ avg(dateDiff('second', firstSeen, lastSeen)) as duration
+ FROM sessions FINAL
WHERE
pid = {pid:FixedString(12)}
AND CAST(psid, 'String') = {psid:String}
@@ -3803,8 +3803,8 @@ export class AnalyticsService {
SELECT
CAST(psid, 'String') AS psidCasted,
pid,
- avg(duration) as avg_duration
- FROM session_durations
+ avg(dateDiff('second', firstSeen, lastSeen)) as avg_duration
+ FROM sessions FINAL
WHERE pid = {pid:FixedString(12)}
GROUP BY psidCasted, pid
)
diff --git a/backend/apps/community/src/analytics/salt.service.ts b/backend/apps/community/src/analytics/salt.service.ts
index 14f8d74d6..e1aeb7397 100644
--- a/backend/apps/community/src/analytics/salt.service.ts
+++ b/backend/apps/community/src/analytics/salt.service.ts
@@ -3,32 +3,24 @@ import * as bcrypt from 'bcrypt'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
-import { SaltRotation } from '../project/entity/project.entity'
import { redis } from '../common/constants'
-import { ProjectService } from '../project/project.service'
dayjs.extend(utc)
-// Redis keys for global salts (one per rotation period)
const REDIS_SALT_DAILY = 'salt:daily'
-const REDIS_SALT_WEEKLY = 'salt:weekly'
const REDIS_SALT_MONTHLY = 'salt:monthly'
-// Calculate TTL until end of period
-const getTTLUntilEndOfPeriod = (rotation: SaltRotation): number => {
+export type SaltRotationType = 'daily' | 'monthly'
+
+const getTTLUntilEndOfPeriod = (rotation: SaltRotationType): number => {
const now = dayjs.utc()
let endOfPeriod: dayjs.Dayjs
switch (rotation) {
- case SaltRotation.DAILY:
- endOfPeriod = now.endOf('day')
- break
- case SaltRotation.WEEKLY:
- endOfPeriod = now.endOf('week')
- break
- case SaltRotation.MONTHLY:
+ case 'monthly':
endOfPeriod = now.endOf('month')
break
+ case 'daily':
default:
endOfPeriod = now.endOf('day')
}
@@ -36,66 +28,39 @@ const getTTLUntilEndOfPeriod = (rotation: SaltRotation): number => {
return Math.max(1, endOfPeriod.diff(now, 'second'))
}
-// Get Redis key for rotation type
-const getRedisKeyForRotation = (rotation: SaltRotation): string => {
- switch (rotation) {
- case SaltRotation.WEEKLY:
- return REDIS_SALT_WEEKLY
- case SaltRotation.MONTHLY:
- return REDIS_SALT_MONTHLY
- default:
- return REDIS_SALT_DAILY
- }
+const getRedisKeyForRotation = (rotation: SaltRotationType): string => {
+ return rotation === 'monthly' ? REDIS_SALT_MONTHLY : REDIS_SALT_DAILY
}
@Injectable()
export class SaltService {
private readonly logger = new Logger(SaltService.name)
- constructor(private readonly projectService: ProjectService) {}
-
- /**
- * Generate a new salt value
- */
private async generateSalt(): Promise<string> {
return bcrypt.genSalt(10)
}
- /**
- * Get the appropriate global salt based on the project's rotation setting.
- * Since the hash includes project ID, the same global salt produces unique hashes per project.
- */
- async getSaltForProject(pid: string): Promise<string> {
- // Get the project's salt rotation setting
- let rotation = SaltRotation.DAILY
-
- try {
- const project = await this.projectService.getRedisProject(pid)
- if (project?.saltRotation) {
- rotation = project.saltRotation
- }
- } catch {
- // Default to daily if project not found
- }
+ async getSaltForSession(): Promise<string> {
+ return this.getGlobalSalt('daily')
+ }
+
+ async getSaltForProfile(): Promise<string> {
+ return this.getGlobalSalt('monthly')
+ }
- return this.getGlobalSalt(rotation)
+ /** @deprecated Use getSaltForSession() instead */
+ async getSaltForProject(_pid: string): Promise<string> {
+ return this.getSaltForSession()
}
- /**
- * Get or create a global salt for the specified rotation period
- */
- async getGlobalSalt(
- rotation: SaltRotation = SaltRotation.DAILY,
- ): Promise<string> {
+ async getGlobalSalt(rotation: SaltRotationType = 'daily'): Promise<string> {
const redisKey = getRedisKeyForRotation(rotation)
- // Check if salt exists
const existingSalt = await redis.get(redisKey)
if (existingSalt) {
return existingSalt
}
- // Generate new salt and store with TTL
const salt = await this.generateSalt()
const ttl = getTTLUntilEndOfPeriod(rotation)
await redis.set(redisKey, salt, 'EX', ttl)
@@ -105,16 +70,8 @@ export class SaltService {
return salt
}
- /**
- * Regenerate all global salts (called by cron at midnight UTC)
- * This ensures salts exist even if no requests come in at period boundaries
- */
async regenerateExpiredSalts(): Promise<void> {
- const rotations = [
- SaltRotation.DAILY,
- SaltRotation.WEEKLY,
- SaltRotation.MONTHLY,
- ]
+ const rotations: SaltRotationType[] = ['daily', 'monthly']
for (const rotation of rotations) {
const redisKey = getRedisKeyForRotation(rotation)
diff --git a/backend/apps/community/src/task-manager/task-manager.service.ts b/backend/apps/community/src/task-manager/task-manager.service.ts
index fa718d273..e527db22f 100644
--- a/backend/apps/community/src/task-manager/task-manager.service.ts
+++ b/backend/apps/community/src/task-manager/task-manager.service.ts
@@ -1,18 +1,9 @@
import { Injectable } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
-import dayjs from 'dayjs'
-import utc from 'dayjs/plugin/utc'
-import _size from 'lodash/size'
-import _map from 'lodash/map'
-import _now from 'lodash/now'
-import { redis } from '../common/constants'
-import { clickhouse } from '../common/integrations/clickhouse'
import { AppLoggerService } from '../logger/logger.service'
import { SaltService } from '../analytics/salt.service'
-dayjs.extend(utc)
-
@Injectable()
export class TaskManagerService {
constructor(
@@ -20,53 +11,8 @@ export class TaskManagerService {
private readonly saltService: SaltService,
) {}
- // Ensure global salts exist for all rotation periods (daily/weekly/monthly)
- // Salts auto-expire via Redis TTL, this just ensures they're regenerated if missing
@Cron(CronExpression.EVERY_HOUR)
async regenerateGlobalSalts() {
await this.saltService.regenerateExpiredSalts()
}
-
- @Cron(CronExpression.EVERY_MINUTE)
- async processSessionDuration() {
- const keys = await redis.keys('sd:*')
- const keysToDelete = []
- const toSave = []
- const now = _now()
-
- const promises = _map(keys, async key => {
- const [start, last] = (await redis.get(key)).split(':')
- const duration = now - Number(last)
-
- // storing to the DB if last interaction was more than 1 minute ago
- if (duration > 60000) {
- const [, psid, pid] = key.split(':')
- toSave.push({
- psid,
- pid,
- duration: Math.max(
- 0,
- Math.floor((Number(last) - Number(start)) / 1000),
- ), // convert to seconds, ensure non-negative
- })
- keysToDelete.push(key)
- }
- })
-
- await Promise.allSettled(promises).catch(reason => {
- this.logger.error(
- `[CRON WORKER](processSessionDuration) Error occured: ${reason}`,
- )
- })
-
- if (_size(toSave) > 0) {
- await redis.del(...keysToDelete)
-
- await clickhouse.insert({
- table: 'session_durations',
- values: toSave,
- format: 'JSONEachRow',
- })
- }
- }
}
diff --git a/backend/migrations/clickhouse/2025_12_02_profile_id.js b/backend/migrations/clickhouse/2025_12_02_profile_id.js
new file mode 100644
index 000000000..dd33f28a2
--- /dev/null
+++ b/backend/migrations/clickhouse/2025_12_02_profile_id.js
@@ -0,0 +1,48 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ // Add profileId column to analytics table
+ `ALTER TABLE ${dbName}.analytics ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
+
+ // Add profileId column to customEV table
+ `ALTER TABLE ${dbName}.customEV ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
+
+ // Add profileId column to errors table
+ `ALTER TABLE ${dbName}.errors ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
+
+ // Create sessions table with ReplacingMergeTree for tracking session state
+ // ReplacingMergeTree automatically keeps the latest row by lastSeen for each (pid, psid) pair
+ `CREATE TABLE IF NOT EXISTS ${dbName}.sessions
+ (
+ psid UInt64,
+ pid FixedString(12),
+ profileId Nullable(String),
+ firstSeen DateTime('UTC'),
+ lastSeen DateTime('UTC'),
+ pageviews UInt32 DEFAULT 1,
+ events UInt32 DEFAULT 0
+ )
+ ENGINE = ReplacingMergeTree(lastSeen)
+ ORDER BY (pid, psid)
+ PARTITION BY toYYYYMM(firstSeen);`,
+
+ // Migrate data from old session_durations table to new sessions table
+ // We compute firstSeen as (lastSeen - duration) and set lastSeen to now()
+ // profileId is null for historical data (will be populated on new events)
+ `INSERT INTO ${dbName}.sessions (psid, pid, profileId, firstSeen, lastSeen, pageviews, events)
+ SELECT
+ psid,
+ pid,
+ NULL as profileId,
+ subtractSeconds(now(), duration) as firstSeen,
+ now() as lastSeen,
+ 1 as pageviews,
+ 0 as events
+ FROM ${dbName}.session_durations
+ WHERE (pid, psid) NOT IN (SELECT pid, psid FROM ${dbName}.sessions);`,
+
+ // Drop the old session_durations table (commented out for safety - run manually after verifying migration)
+ // `DROP TABLE IF EXISTS ${dbName}.session_durations;`,
+]
+
+queriesRunner(queries)
diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.js
index 8d3b7bf6d..7eba14816 100644
--- a/backend/migrations/clickhouse/initialise_database.js
+++ b/backend/migrations/clickhouse/initialise_database.js
@@ -8,6 +8,7 @@ const CLICKHOUSE_INIT_QUERIES = [
`CREATE TABLE IF NOT EXISTS ${dbName}.analytics
(
psid Nullable(UInt64),
+ profileId Nullable(String),
pid FixedString(12),
host Nullable(String),
pg Nullable(String),
@@ -38,20 +39,11 @@ const CLICKHOUSE_INIT_QUERIES = [
PARTITION BY toYYYYMM(created)
ORDER BY (pid, created);`,
- // Session duration table
- `CREATE TABLE IF NOT EXISTS ${dbName}.session_durations
- (
- psid UInt64,
- pid FixedString(12),
- duration UInt32
- )
- ENGINE = MergeTree()
- ORDER BY (pid, psid);`,
-
// Custom events table
`CREATE TABLE IF NOT EXISTS ${dbName}.customEV
(
psid Nullable(UInt64),
+ profileId Nullable(String),
pid FixedString(12),
host Nullable(String),
ev String,
@@ -114,6 +106,7 @@ const CLICKHOUSE_INIT_QUERIES = [
`CREATE TABLE IF NOT EXISTS ${dbName}.errors
(
psid Nullable(UInt64),
+ profileId Nullable(String),
eid FixedString(32),
pid FixedString(12),
host Nullable(String),
@@ -155,6 +148,21 @@ const CLICKHOUSE_INIT_QUERIES = [
ENGINE = ReplacingMergeTree()
PRIMARY KEY (eid, pid);`,
+ // Sessions table with ReplacingMergeTree for tracking session state
+ `CREATE TABLE IF NOT EXISTS ${dbName}.sessions
+ (
+ psid UInt64,
+ pid FixedString(12),
+ profileId Nullable(String),
+ firstSeen DateTime('UTC'),
+ lastSeen DateTime('UTC'),
+ pageviews UInt32 DEFAULT 1,
+ events UInt32 DEFAULT 0
+ )
+ ENGINE = ReplacingMergeTree(lastSeen)
+ ORDER BY (pid, psid)
+ PARTITION BY toYYYYMM(firstSeen);`,
+
// The CAPTCHA data table
`CREATE TABLE IF NOT EXISTS ${dbName}.captcha
(
diff --git a/backend/migrations/clickhouse/selfhosted_2025_12_02_profile_id.js b/backend/migrations/clickhouse/selfhosted_2025_12_02_profile_id.js
new file mode 100644
index 000000000..981c7d1ed
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_2025_12_02_profile_id.js
@@ -0,0 +1,48 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ // Add profileId column to analytics table
+ `ALTER TABLE ${dbName}.analytics ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
+
+ // Add profileId column to customEV table
+ `ALTER TABLE ${dbName}.customEV ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
+
+ // Add profileId column to errors table
+ `ALTER TABLE ${dbName}.errors ADD COLUMN IF NOT EXISTS profileId Nullable(String) AFTER psid`,
+
+ // Create sessions table with ReplacingMergeTree for tracking session state
+ // ReplacingMergeTree automatically keeps the latest row by lastSeen for each (pid, psid) pair
+ `CREATE TABLE IF NOT EXISTS ${dbName}.sessions
+ (
+ psid UInt64,
+ pid FixedString(12),
+ profileId Nullable(String),
+ firstSeen DateTime('UTC'),
+ lastSeen DateTime('UTC'),
+ pageviews UInt32 DEFAULT 1,
+ events UInt32 DEFAULT 0
+ )
+ ENGINE = ReplacingMergeTree(lastSeen)
+ ORDER BY (pid, psid)
+ PARTITION BY toYYYYMM(firstSeen);`,
+
+ // Migrate data from old session_durations table to new sessions table
+ // We compute firstSeen as (now - duration) and set lastSeen to now()
+ // profileId is null for historical data (will be populated on new events)
+ `INSERT INTO ${dbName}.sessions (psid, pid, profileId, firstSeen, lastSeen, pageviews, events)
+ SELECT
+ psid,
+ pid,
+ NULL as profileId,
+ subtractSeconds(now(), duration) as firstSeen,
+ now() as lastSeen,
+ 1 as pageviews,
+ 0 as events
+ FROM ${dbName}.session_durations
+ WHERE (pid, psid) NOT IN (SELECT pid, psid FROM ${dbName}.sessions);`,
+
+ // Drop the old session_durations table (commented out for safety - run manually after verifying migration)
+ // `DROP TABLE IF EXISTS ${dbName}.session_durations;`,
+]
+
+queriesRunner(queries)