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!

Implemented basic limitations for account plans

Blue Mouse35eb1db11a6d
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index 4808b0c8b..640eef01e 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -9,7 +9,7 @@ import { v4 as uuidv4 } from 'uuid'
import { hash } from 'blake3'
import {
Controller, Body, Query, UseGuards, Get, Post, Headers, BadRequestException,
- InternalServerErrorException, NotImplementedException, UnprocessableEntityException,
+ InternalServerErrorException, NotImplementedException, UnprocessableEntityException, PreconditionFailedException,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import * as UAParser from 'ua-parser-js'
@@ -71,7 +71,7 @@ export class AnalyticsController {
if (!_isEmpty(from) && !_isEmpty(to)) {
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\'')
+ throw new PreconditionFailedException('The timeframe \'from\' parameter cannot be greater than \'to\'')
}
if (dayjs.utc(to).isAfter(dayjs.utc(), 'second')) {
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index e82966fba..fd565967d 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -7,15 +7,17 @@ import * as _map from 'lodash/map'
import * as _keys from 'lodash/keys'
import * as dayjs from 'dayjs'
import * as utc from 'dayjs/plugin/utc'
-// import { OpUnitType } from 'dayjs/index'
-import { ForbiddenException, Injectable, BadRequestException, InternalServerErrorException } from '@nestjs/common'
+import {
+ Injectable, BadRequestException, InternalServerErrorException, ForbiddenException,
+} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
-import { Pagination, PaginationOptionsInterface } from '../common/pagination'
+import { ACCOUNT_PLANS } from '../user/entities/user.entity'
import {
redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout,
- UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange,
+ UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisProjectCountKey,
+ redisProjectCountCacheTimeout,
} from '../common/constants'
import { Analytics } from './entities/analytics.entity'
import { PageviewsDTO } from './dto/pageviews.dto'
@@ -32,22 +34,6 @@ export class AnalyticsService {
private readonly projectService: ProjectService,
) { }
- // async paginate(options: PaginationOptionsInterface, where: Record<string, unknown> | undefined): Promise<Pagination<Analytics>> {
- // const [results, total] = await this.analyticsRepository.findAndCount({
- // take: options.take || 10,
- // skip: options.skip || 0,
- // where: where,
- // order: {
- // name: 'ASC',
- // }
- // })
-
- // return new Pagination<Analytics>({
- // results,
- // total,
- // })
- // }
-
count(): Promise<number> {
return this.analyticsRepository.count()
}
@@ -86,7 +72,7 @@ export class AnalyticsService {
const pidKey = getRedisProjectKey(pid)
let project = await redis.get(pidKey)
if (_isEmpty(project)) {
- project = await this.projectService.findOne(pid)
+ project = await this.projectService.findOneWithRelations(pid)
if (_isEmpty(project)) throw new BadRequestException('The provided Project ID (pid) is incorrect')
await redis.set(pidKey, JSON.stringify(project), 'EX', redisProjectCacheTimeout)
} else {
@@ -99,6 +85,33 @@ export class AnalyticsService {
if (!project.active) throw new BadRequestException('Incoming analytics is disabled for this project')
+ const countKey = getRedisProjectCountKey(pid)
+ let count = await redis.get(countKey)
+ if (_isEmpty(count)) {
+ const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
+ const monthStart = dayjs.utc().startOf('month').format('YYYY-MM-DD HH:mm:ss')
+ const count_query = `SELECT COUNT() FROM analytics WHERE pid='${pid}' AND created BETWEEN '${monthStart}' AND '${now}'`
+ const result = await clickhouse.query(count_query).toPromise()
+
+ const pageviews = result[0]['count()']
+ count = pageviews
+
+ await redis.set(countKey, `${pageviews}`, 'EX', redisProjectCountCacheTimeout)
+ } else {
+ try {
+ count = Number(count)
+ } catch (e) {
+ console.error(e)
+ throw new InternalServerErrorException('Error while processing project')
+ }
+ }
+
+ const maxCount = ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0
+
+ if (count >= maxCount) {
+ throw new ForbiddenException('You have exceeded the available monthly request limit for your account. Please upgrade your account plan if you need more requests.')
+ }
+
if (!_isEmpty(project.origins) && !_isEmpty(origin)) {
if (origin === 'null') {
if (!_includes(project.origins, 'null')) {
diff --git a/src/common/constants.ts b/src/common/constants.ts
index 7261d1d35..530a35221 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -58,12 +58,16 @@ const isValidPID = (pid: string) => _size(pid) === 12
// redis keys
const getRedisProjectKey = (pid: string) => `pid_${pid}`
+const getRedisProjectCountKey = (pid: string) => `pid_c_${pid}`
const REDIS_LOG_DATA_CACHE_KEY = 'log_cache'
// 3600 sec -> 1 hour
const redisProjectCacheTimeout = 3600
+// 15 minutes
+const redisProjectCountCacheTimeout = 900
+
// 30 minues -> the amount of time analytics requests within one session are counted as non-unique
const UNIQUE_SESSION_LIFE_TIME = 1800
@@ -73,5 +77,5 @@ const GDPR_EXPORT_TIMEFRAME = 14
export {
clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,
redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME, REDIS_LOG_DATA_CACHE_KEY,
- GDPR_EXPORT_TIMEFRAME,
+ GDPR_EXPORT_TIMEFRAME, getRedisProjectCountKey, redisProjectCountCacheTimeout,
}
diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.ts
index 9d86d3237..f3399999e 100644
--- a/src/user/entities/user.entity.ts
+++ b/src/user/entities/user.entity.ts
@@ -2,25 +2,30 @@ import { Entity, Column, PrimaryGeneratedColumn, OneToMany, BeforeUpdate } from
import { ActionToken } from 'src/action-tokens/action-token.entity'
import { Project } from 'src/project/entity/project.entity'
-const FREE_PLAN = {
- code: 'free',
- displayName: 'Free plan',
- monthlyUsageLimit: 5000,
- stripePriceID: '',
+export const ACCOUNT_PLANS = {
+ free: {
+ displayName: 'Free plan',
+ monthlyUsageLimit: 3000,
+ },
+ freelancer: {
+ displayName: 'Freelancer plan',
+ monthlyUsageLimit: 100000,
+ },
+ startup: {
+ displayName: 'Startup plan',
+ monthlyUsageLimit: 500000,
+ },
+ enterprise: {
+ displayName: 'Enterprise plan',
+ monthlyUsageLimit: 1000000,
+ },
}
-const BASIC_PLAN = {
- code: 'free',
- displayName: 'Free plan',
- monthlyUsageLimit: 5000,
- stripePriceID: '',
-}
-
-const ENTERPRISE_PLAN = {
- code: 'free',
- displayName: 'Free plan',
- monthlyUsageLimit: 5000,
- stripePriceID: '',
+export enum PlanCode {
+ free = 'free',
+ freelancer = 'freelancer',
+ startup = 'startup',
+ enterprise = 'enterprise',
}
export enum UserType {
@@ -48,6 +53,13 @@ export class User {
})
roles: UserType[]
+ @Column({
+ type: 'enum',
+ enum: PlanCode,
+ default: PlanCode.free,
+ })
+ planCode: PlanCode
+
@Column('varchar', { length: 254, unique: true })
email: string