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!

Saving analytics data into Clickhouse by chunks stored in Redis cache

Blue Mousec09dd3bbd3b2
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index 142975f93..86e95ec76 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -8,24 +8,21 @@ import * as utc from 'dayjs/plugin/utc'
import { v4 as uuidv4 } from 'uuid'
import { hash } from 'blake3'
import {
- Controller, Body, Query, Param, UseGuards, Get, Post, Ip, Headers, Put, Delete, BadRequestException,
- HttpCode, NotFoundException, InternalServerErrorException, NotAcceptableException, NotImplementedException, UnprocessableEntityException,
+ Controller, Body, Query, UseGuards, Get, Post, Ip, Headers, BadRequestException,
+ InternalServerErrorException, NotImplementedException, UnprocessableEntityException,
} from '@nestjs/common'
-import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'
+import { ApiTags } from '@nestjs/swagger'
import { AnalyticsService } from './analytics.service'
import { ProjectService } from '../project/project.service'
import { UserType } from '../user/entities/user.entity'
-import { Pagination } from '../common/pagination/pagination'
-import { Analytics } from './entities/analytics.entity'
-import { UserService } from '../user/user.service'
import { Roles } from '../common/decorators/roles.decorator'
import { RolesGuard } from 'src/common/guards/roles.guard'
import { PageviewsDTO } from './dto/pageviews.dto'
import { AnalyticsGET_DTO } from './dto/getData.dto'
import { AppLoggerService } from '../logger/logger.service'
import {
- clickhouse, isValidPID, getPercentageChange,
+ clickhouse, isValidPID, getPercentageChange, REDIS_LOG_DATA_CACHE_KEY, redis,
} from '../common/constants'
import ct from '../common/countriesTimezones'
@@ -35,7 +32,6 @@ dayjs.extend(utc)
// store them in redis storage and reset every 24 hours
const getSessionKey = (ip: string, ua: string, salt: string = '') => hash(`${ua}${ip}${salt}`).toString('hex')
-// todo: return string, not array
const analyticsDTO = (pid: string, ev: string, pg: string, lc: string, ref: string, sw: number | string, so: string, me: string, ca: string, lt: number | string, tz: string, unique: number): Array<string | number> => {
const cc = tz === 'NULL' ? 'NULL' : ct.getCountryForTimezone(tz)?.id
return [uuidv4(), pid, ev, pg, lc, ref, sw, so, me, ca, lt, cc, unique, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]
@@ -74,7 +70,7 @@ export class AnalyticsController {
let query = `SELECT * FROM analytics WHERE pid='${pid}' `
if (!_isEmpty(from) && !_isEmpty(to)) {
- throw new NotImplementedException('Filter by from/to params is currently not available')
+ throw new NotImplementedException('Filtering by from/to params is currently not available')
if (dayjs.utc(from).isAfter(dayjs.utc(to), 'second')) {
throw new BadRequestException('The timeframe \'from\' parameter cannot be greater than \'to\'')
}
@@ -100,7 +96,7 @@ export class AnalyticsController {
@Get('/birdseye')
@UseGuards(RolesGuard)
- // @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
// returns overall short statistics per project
async getOverallStats(@Query() data): Promise<any> {
this.logger.log({ ...data }, 'GET /birdseye')
@@ -174,17 +170,13 @@ export class AnalyticsController {
dto = analyticsDTO(logDTO.pid, logDTO.ev, logDTO.pg, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
}
- const values = dto.map(getElValue).join(',')
-
- // may be vulnerable to sql injection attack
- // use only validated project IDs gained from redis store and other data
- // todo: refactor; put into redis cache and next upload data chunks from redis into clickhouse
- const query = `INSERT INTO analytics (*) VALUES (${values})`
+ // todo: fix: may be vulnerable to sql injection attack
+ const values = `(${dto.map(getElValue).join(',')})`
try {
- await clickhouse.query(query).toPromise()
+ await redis.rpush(REDIS_LOG_DATA_CACHE_KEY, values)
return
} catch (e) {
- this.logger.log(e)
+ this.logger.error(e)
throw new InternalServerErrorException(`Error error while saving the data: ${e}`)
}
}
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index 3f542dacc..bf3b84ba9 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -99,9 +99,15 @@ export class AnalyticsService {
if (!project.active) throw new BadRequestException('Incoming analytics is disabled for this project')
if (!_isEmpty(project.origins) && !_isEmpty(origin)) {
- const hostname = new URL(origin).hostname
- if (!_includes(project.origins, hostname)) {
- throw new BadRequestException('This origin is prohibited by the project\'s origins policy')
+ if (origin === 'null') {
+ if (!_includes(project.origins, 'null')) {
+ throw new BadRequestException('\'null\' origin is not added to your project\'s whitelist. To send requests from this origin either add it to your origins policy or leave it empty.')
+ }
+ } else {
+ const hostname = new URL(origin).hostname
+ if (!_includes(project.origins, hostname)) {
+ throw new BadRequestException('This origin is prohibited by the project\'s origins policy')
+ }
}
}
diff --git a/src/common/constants.ts b/src/common/constants.ts
index 29c8825ba..043564e8d 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -55,6 +55,8 @@ const isValidPID = (pid: string) => _size(pid) === 12
// redis keys
const getRedisProjectKey = (pid: string) => `pid_${pid}`
+const REDIS_LOG_DATA_CACHE_KEY = 'log_cache'
+
// 3600 sec -> 1 hour
const redisProjectCacheTimeout = 3600
@@ -63,5 +65,5 @@ const UNIQUE_SESSION_LIFE_TIME = 1800
export {
clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,
- redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME,
+ redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME, REDIS_LOG_DATA_CACHE_KEY,
}
diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.ts
index 0506e9a7e..4b1170c0d 100644
--- a/src/task-manager/task-manager.service.ts
+++ b/src/task-manager/task-manager.service.ts
@@ -1,8 +1,10 @@
import { Injectable, HttpService } from '@nestjs/common'
import { Cron, CronExpression } from '@nestjs/schedule'
-// import * as moment from 'moment'
+import * as _isEmpty from 'lodash/isEmpty'
+import * as _join from 'lodash/join'
import { MailerService } from '../mailer/mailer.service'
+import { clickhouse, REDIS_LOG_DATA_CACHE_KEY, redis } from '../common/constants'
@Injectable()
export class TaskManagerService {
@@ -11,8 +13,14 @@ export class TaskManagerService {
private readonly httpService: HttpService
) {}
- // @Cron(CronExpression.EVERY_MINUTE)
- // async someTask(): Promise<void> {
-
- // }
+ @Cron(CronExpression.EVERY_MINUTE)
+ async someTask(): Promise<void> {
+ const data = await redis.lrange(REDIS_LOG_DATA_CACHE_KEY, 0, -1)
+
+ if (!_isEmpty(data)) {
+ await redis.del(REDIS_LOG_DATA_CACHE_KEY)
+ const query = `INSERT INTO analytics (*) VALUES ${_join(data, ',')}`
+ await clickhouse.query(query).toPromise()
+ }
+ }
}