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!

Store session duration into session_durations table

Blue Moused02a43a36322
diff --git a/backend/apps/production/src/task-manager/task-manager.service.ts b/backend/apps/production/src/task-manager/task-manager.service.ts
index d14a0c08a..516c5f304 100644
--- a/backend/apps/production/src/task-manager/task-manager.service.ts
+++ b/backend/apps/production/src/task-manager/task-manager.service.ts
@@ -749,6 +749,7 @@ export class TaskManagerService {
@Cron(CronExpression.EVERY_MINUTE)
async processSessionDuration(): Promise<void> {
const keys = await redis.keys('sd:*')
+ const keysToDelete = []
const toSave = []
const now = _now()
@@ -758,7 +759,13 @@ export class TaskManagerService {
// storing to the DB if last interaction was more than 1 minute ago
if (duration > 60000) {
- toSave.push([key, Number(last) - Number(start)])
+ const [, psid, pid] = key.split(':')
+ toSave.push({
+ psid: _toNumber(psid),
+ pid,
+ duration: Math.floor((Number(last) - Number(start)) / 1000), // convert to seconds
+ })
+ keysToDelete.push(key)
}
})
@@ -769,25 +776,12 @@ export class TaskManagerService {
})
if (_size(toSave) > 0) {
- await redis.del(..._map(toSave, ([key]) => key))
-
- const psids = _map(toSave, ([key]) => key.split(':')[1])
-
- const setSdurQuery = `
- ALTER TABLE
- analytics
- UPDATE sdur = sdur + CASE ${_map(
- toSave,
- ([key, duration]) =>
- `WHEN psid = ${key.split(':')[1]} THEN ${duration / 1000}`, // converting to seconds
- ).join(' ')} END WHERE psid IN ({ psids: Array(String) })
- `
-
- await clickhouse.query({
- query: setSdurQuery,
- query_params: {
- psids,
- },
+ await redis.del(...keysToDelete)
+
+ await clickhouse.insert({
+ table: 'session_durations',
+ values: toSave,
+ format: 'JSONEachRow',
})
}
}