📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Update uptime with charts
Yehor Dremliuhace055d80b54b
diff --git a/apps/production/src/analytics/analytics.controller.ts b/apps/production/src/analytics/analytics.controller.tsindex d00ed9c64..42dfd5f1a 100644--- a/apps/production/src/analytics/analytics.controller.ts+++ b/apps/production/src/analytics/analytics.controller.ts@@ -9,6 +9,7 @@ import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'import * as dayjsTimezone from 'dayjs/plugin/timezone'import { hash } from 'blake3'+import { ApiOperation, ApiOkResponse } from '@nestjs/swagger'import {Controller,Body,@@ -52,6 +53,7 @@ import { GetCustomEventMetadata } from './dto/get-custom-event-meta.dto'import { GetPagePropertyMetaDTO } from './dto/get-page-property-meta.dto'import { GetUserFlowDTO } from './dto/getUserFlow.dto'import { GetFunnelsDTO } from './dto/getFunnels.dto'+import { ProjectService } from '../project/project.service'import { AppLoggerService } from '../logger/logger.service'import {redis,@@ -79,6 +81,7 @@ import {PerfMeasure,} from './interfaces'import { GetSessionsDto } from './dto/get-sessions.dto'+import {GetMonitorDataDto} from './dto/get-monitor-data.dto'import { GetSessionDto } from './dto/get-session.dto'import { ErrorDTO } from './dto/error.dto'import { GetErrorsDto } from './dto/get-errors.dto'@@ -195,6 +198,7 @@ export class AnalyticsController {private readonly analyticsService: AnalyticsService,private readonly logger: AppLoggerService,private readonly projectsViewsRepository: ProjectsViewsRepository,+ private readonly projectService: ProjectService,) {}@ApiBearerAuth()@@ -1569,6 +1573,105 @@ export class AnalyticsController {}}++ @ApiOperation({ summary: 'Get monitor data' })+ @ApiBearerAuth()+ @ApiOkResponse({ description: 'Monitor data retrieved successfully' })+ @Get(+ 'monitor-data',+ )+ @Auth([], true, true)+ public async getMonitorData(+ @Query() parameters: GetMonitorDataDto,+ @CurrentUserId() userId: string,+ @Headers() headers: { 'x-password'?: string },+ ): Promise<any & { chart: any }> {+ const {+ pid,+ // monitorGroupId,+ monitorId,+ period,+ timeBucket,+ from,+ to,+ timezone,+ } = parameters+++ // TODO: CHECK THAT MONITOR GROUP BELONGS TO THE PROVIDED PID+ this.analyticsService.validatePID(pid)++ if (!_isEmpty(period)) {+ this.analyticsService.validatePeriod(period)+ }++ await this.analyticsService.checkProjectAccess(+ pid,+ userId,+ headers['x-password'],+ )++ await this.analyticsService.checkBillingAccess(pid)++ let newTimebucket = timeBucket+ let allowedTumebucketForPeriodAll++ let diff++ if (period === 'all') {+ const res = await this.analyticsService.getTimeBucketForAllTime(+ pid,+ period,+ timezone,+ )++ diff = res.diff+ // eslint-disable-next-line prefer-destructuring+ newTimebucket = _includes(res.timeBucket, timeBucket)+ ? timeBucket+ : res.timeBucket[0]+ allowedTumebucketForPeriodAll = res.timeBucket+ }++ this.analyticsService.validateTimebucket(newTimebucket)++ const safeTimezone = this.analyticsService.getSafeTimezone(timezone)+ const { groupFrom, groupTo, groupFromUTC, groupToUTC } =+ this.analyticsService.getGroupFromTo(+ from,+ to,+ newTimebucket,+ period,+ safeTimezone,+ diff,+ )+ // TODO change to Uint64; filters.+ let subQuery = 'FROM monitor_responses WHERE monitorID = {monitorId:FixedString(36)} AND created BETWEEN {groupFrom:String} AND {groupTo:String}'+ const paramsData = {+ params: {+ monitorId,+ groupFrom: groupFromUTC,+ groupTo: groupToUTC,+ },+ }++ // RETURN avg(responseTime) as avgResponseTime AS WELL+ // BY GROUPS LIKE 0-100, 100-200, 200-500, 500-1000, etc.+ const result = await this.analyticsService.groupMonitorResponsesByTimeBucket(+ newTimebucket,+ groupFrom,+ groupTo,+ subQuery,+ paramsData,+ safeTimezone,+ )++ return {+ ...result,+ timeBucket: allowedTumebucketForPeriodAll,+ }+ }+@Get('errors')@Auth([], true, true)async getErrors(diff --git a/apps/production/src/analytics/analytics.service.ts b/apps/production/src/analytics/analytics.service.tsindex 17c5c84a1..1a4643798 100644--- a/apps/production/src/analytics/analytics.service.ts+++ b/apps/production/src/analytics/analytics.service.ts@@ -46,6 +46,7 @@ import {UNIQUE_SESSION_LIFE_TIME,REDIS_SESSION_SALT_KEY,TRAFFIC_COLUMNS,+ UPTIME_COLUMNS,ALL_COLUMNS,CAPTCHA_COLUMNS,ERROR_COLUMNS,@@ -277,7 +278,7 @@ const generateParamsQuery = (subQuery: string,customEVFilterApplied: boolean,isPageInclusiveFilterSet: boolean,- type: 'traffic' | 'performance' | 'captcha' | 'errors',+ type: 'traffic' | 'performance' | 'captcha' | 'errors' | 'uptime',measure?: PerfMeasure,): string => {let columns = [`${col} as name`]@@ -310,6 +311,10 @@ const generateParamsQuery = (return `SELECT ${columnsQuery}, count(*) as count ${subQuery} AND ${col} IS NOT NULL GROUP BY ${col}`}+ if (type === 'uptime') {+ return `SELECT ${columnsQuery}, count(*) as count ${subQuery} AND ${col} IS NOT NULL GROUP BY ${col}`+ }+if (customEVFilterApplied) {return `SELECT ${columnsQuery}, count(*) as count ${subQuery} AND ${col} IS NOT NULL GROUP BY ${columnsQuery}`}@@ -1846,7 +1851,7 @@ export class AnalyticsService {subQuery: string,customEVFilterApplied: boolean,paramsData: any,- type: 'traffic' | 'performance' | 'captcha' | 'errors',+ type: 'traffic' | 'performance' | 'captcha' | 'errors' | 'uptime',measure?: PerfMeasure,): Promise<any> {const params = {}@@ -1875,6 +1880,10 @@ export class AnalyticsService {columns = PERFORMANCE_COLUMNS}+ if (type === 'uptime') {+ columns = UPTIME_COLUMNS+ }+const paramsPromises = _map(columns, async col => {const query = generateParamsQuery(col,@@ -2357,6 +2366,29 @@ export class AnalyticsService {return baseQuery}+ generateMonitorResponsesAggregationQuery(timeBucket: TimeBucketType): string {+ const timeBucketFunc = timeBucketConversion[timeBucket]+ const [selector, groupBy] = this.getGroupSubquery(timeBucket)++ const baseQuery = `+ SELECT+ ${selector},+ count() as count+ FROM (+ SELECT region, statusCode,+ ${timeBucketFunc}(created) as tz_created+ FROM monitor_responses+ WHERE+ monitorID = {monitorId:FixedString(36)}+ AND created BETWEEN {groupFrom:String} AND {groupTo:String}+ ) as subquery+ GROUP BY ${groupBy}+ ORDER BY ${groupBy}+ `++ return baseQuery+ }+async groupByTimeBucket(timeBucket: TimeBucketType,from: string,@@ -2768,6 +2800,66 @@ export class AnalyticsService {})}+ async groupMonitorResponsesByTimeBucket(+ timeBucket: TimeBucketType,+ from: string,+ to: string,+ subQuery: string,+ paramsData: any,+ safeTimezone: string,+ ): Promise<object | void> {+ let params: unknown = {}+ let chart: unknown = {}++ const promises = [+ // Params+ (async () => {+ params = await this.generateParams(+ null,+ subQuery,+ false,+ paramsData,+ 'uptime',+ )++ if (!_some(_values(params), val => !_isEmpty(val))) {+ throw new BadRequestException(+ 'There are no uptime details for specified time frame',+ )+ }+ })(),++ // Chart data+ (async () => {+ const { x, format } = this.generateUTCXAxis(timeBucket, from, to)++ const query = this.generateMonitorResponsesAggregationQuery(timeBucket)++ const { data } = await clickhouse+ .query({+ query,+ query_params: paramsData.params,+ })+ // TODO: TYPE+ .then(resultSet => resultSet.json<any>())+ const { count } = this.extractCaptchaChartData(data, x)++ chart = {+ // todo: other stuff+ x: this.shiftToTimezone(x, safeTimezone, format),+ count,+ }+ })(),+ ]++ await Promise.all(promises)++ return Promise.resolve({+ params,+ chart,+ })+ }+extractPerformanceChartData(result, x: string[]): any {const dns = Array(x.length).fill(0)const tls = Array(x.length).fill(0)diff --git a/apps/production/src/analytics/dto/get-monitor-data.dto.ts b/apps/production/src/analytics/dto/get-monitor-data.dto.tsnew file mode 100644index 000000000..b560f1db5--- /dev/null+++ b/apps/production/src/analytics/dto/get-monitor-data.dto.ts@@ -0,0 +1,49 @@+import { ApiProperty } from '@nestjs/swagger'+import { IsNotEmpty } from 'class-validator'+import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'++export enum TimeBucketType {+ MINUTE = 'minute',+ HOUR = 'hour',+ DAY = 'day',+ MONTH = 'month',+ YEAR = 'year',+}++export enum ChartRenderMode {+ PERIODICAL = 'periodical',+ CUMULATIVE = 'cumulative',+}++export class GetMonitorDataDto {+ @ApiProperty()+ @IsNotEmpty()+ pid: string++ @ApiProperty()+ @IsNotEmpty()+ monitorId: string++ @ApiProperty()+ @IsNotEmpty()+ monitorGroupId: string++ @ApiProperty()+ period: string++ @ApiProperty({ enum: TimeBucketType })+ @IsNotEmpty()+ timeBucket: TimeBucketType++ @ApiProperty({ required: false })+ from: string++ @ApiProperty({ required: false })+ to: string++ @ApiProperty({+ description: 'Timezone to display data in',+ default: DEFAULT_TIMEZONE,+ })+ timezone: string+}diff --git a/apps/production/src/common/constants.ts b/apps/production/src/common/constants.tsindex d95ecd9e0..796873225 100644--- a/apps/production/src/common/constants.ts+++ b/apps/production/src/common/constants.ts@@ -114,6 +114,8 @@ const TRAFFIC_COLUMNS = ['ca',]+const UPTIME_COLUMNS = ['region', 'statusCode']+const TRAFFIC_METAKEY_COLUMNS = ['tag:key', 'tag:value']const ERROR_COLUMNS = ['pg', 'dv', 'br', 'os', 'lc', 'cc', 'rg', 'ct']@@ -195,6 +197,7 @@ export {getRedisUserUsageInfoKey,redisUserUsageinfoCacheTimeout,TRAFFIC_COLUMNS,+ UPTIME_COLUMNS,TRAFFIC_METAKEY_COLUMNS,CAPTCHA_COLUMNS,ERROR_COLUMNS,diff --git a/apps/production/src/common/templates/en/uptime-monitoring-failure.html b/apps/production/src/common/templates/en/uptime-monitoring-failure.htmlnew file mode 100644index 000000000..58a03252c--- /dev/null+++ b/apps/production/src/common/templates/en/uptime-monitoring-failure.html@@ -0,0 +1,3 @@+Uptime Monitoring has failed++<!-- TODO status code, result make a template -->\ No newline at end of filediff --git a/apps/production/src/mailer/letter.ts b/apps/production/src/mailer/letter.tsindex 5b01d6581..91a333395 100644--- a/apps/production/src/mailer/letter.ts+++ b/apps/production/src/mailer/letter.ts@@ -20,4 +20,5 @@ export enum LetterTemplate {UsageOverLimit = 'usage-over-limit',DashboardLockedExceedingLimits = 'dashboard-locked-exceeding-limits',DashboardLockedPaymentFailure = 'dashboard-locked-payment-failure',+ UptimeMonitoringFailure = 'uptime-monitoring-failure',}diff --git a/apps/production/src/mailer/mailer.service.ts b/apps/production/src/mailer/mailer.service.tsindex 722d52e73..b0a3ee1c8 100644--- a/apps/production/src/mailer/mailer.service.ts+++ b/apps/production/src/mailer/mailer.service.ts@@ -119,6 +119,12 @@ const metaInfoJson = {'[ACTION REQUIRED] Your Swetrix dashboard has been locked due to a payment issue',},},+ [LetterTemplate.UptimeMonitoringFailure]: {+ subject: {+ en: () =>+ '[ACTION REQUIRED] Your Swetrix uptime has resulted in an error',+ },+ },}interface Params {diff --git a/apps/production/src/project/consumers/monitor.consumer.ts b/apps/production/src/project/consumers/monitor.consumer.tsindex 7607bc532..ddc06519c 100644--- a/apps/production/src/project/consumers/monitor.consumer.ts+++ b/apps/production/src/project/consumers/monitor.consumer.ts@@ -5,10 +5,17 @@ import { Job } from 'bull'import { firstValueFrom } from 'rxjs'import { CreateMonitorHttpRequestDTO } from '../dto/create-monitor.dto'import { clickhouse } from '../../common/integrations/clickhouse'+import { ProjectService } from '../project.service'+import { MailerService } from '../../mailer/mailer.service'+import { LetterTemplate } from '../../mailer/letter'@Processor('monitor')export class MonitorConsumer {- constructor(@Inject('MONITOR_SERVICE') private monitorService: ClientProxy) {}+ constructor(+ @Inject('MONITOR_SERVICE') private monitorService: ClientProxy,+ private readonly projectService: ProjectService,+ private readonly mailerService: MailerService,+ ) {}private readonly logger = new Logger(MonitorConsumer.name)@@ -25,6 +32,20 @@ export class MonitorConsumer {} = await firstValueFrom(this.monitorService.send('http-request', job.data))this.logger.debug(`Consumer works ${JSON.stringify(res)}`)+ const monitor = await this.projectService.getMonitor(job.data.monitorID)++ if (!monitor.acceptedStatusCodes.includes(res.statusCode)) {+ // await this.mailerService.sed(monitor.group.project.admin.email, 'fuck')+ await this.mailerService.sendEmail(+ monitor.group.project.admin.email,+ LetterTemplate.UptimeMonitoringFailure,+ )+ }+ // this.logger.debug(`Monitor ${JSON.stringify(monitor)}`)++ // this.logger.debug(`1`)+ //+try {await clickhouse.insert({table: 'monitor_responses',diff --git a/apps/production/src/project/dto/create-monitor.dto.ts b/apps/production/src/project/dto/create-monitor.dto.tsindex 1ce8de1f2..90df275e7 100644--- a/apps/production/src/project/dto/create-monitor.dto.ts+++ b/apps/production/src/project/dto/create-monitor.dto.ts@@ -96,10 +96,6 @@ export class CreateMonitorHttpRequestDTO {@IsEnum(HttpStatusCodeEnum, { each: true })acceptedStatusCodes: HttpStatusCodeEnum[]- @ApiProperty()- @IsString()- groupName: string-@ApiProperty()@IsOptional()@IsString()diff --git a/apps/production/src/project/interfaces/monitor-data-interfaces.ts b/apps/production/src/project/interfaces/monitor-data-interfaces.tsnew file mode 100644index 000000000..1cd16dd32--- /dev/null+++ b/apps/production/src/project/interfaces/monitor-data-interfaces.ts@@ -0,0 +1,19 @@+export type Region = 'asia' | 'europe' | 'us' | 'auto'++export interface MonitorRecord {+ region: Region+ responseTime: number+ timestamp: number+ statusCode: number+}++export interface RegionMetrics {+ currentResponseTime: number | null+ avgResponseTime24H: number+ uptime24H: number+ uptime30Days: number+}++export interface MonitorData {+ [region: string]: RegionMetrics+}diff --git a/apps/production/src/project/project.service.ts b/apps/production/src/project/project.service.tsindex a2247e408..f6935eff8 100644--- a/apps/production/src/project/project.service.ts+++ b/apps/production/src/project/project.service.ts@@ -1485,6 +1485,7 @@ export class ProjectService {where: {id: monitorId,},+ relations: ['group', 'group.project', 'group.project.admin'],})}@@ -1531,6 +1532,9 @@ export class ProjectService {}async deleteHttpRequest(monitorID: string) {- await this.monitorQueue.remove(monitorID)+ const job = await this.monitorQueue.getJob(monitorID)+ if (job) {+ await job.remove()+ }}}diff --git a/docker-compose-dev.yml b/docker-compose-dev.ymlindex 8e433eebc..3b909a845 100644--- a/docker-compose-dev.yml+++ b/docker-compose-dev.yml@@ -3,7 +3,7 @@ services:redis:image: redis:7.2-alpineports:- - 6379:6379+ - 6378:6379clickhouse:image: clickhouse/clickhouse-server:23.8-alpineenvironment: