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!

Remove uptime monitoring

Blue Mouse23050ceab446
diff --git a/backend/.env.example b/backend/.env.example
index 5f7cce1d5..f132be595 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -89,8 +89,5 @@ IS_PRIMARY_NODE=true
# Generic
EMAIL_ACTION_ENCRYPTION_KEY=
-# Uptime monitoring
-MONITOR_QUEUE_URL=amqp://localhost:5672
-
# Swetrix Enterprise (Cloud)
SWETRIX_LICENSE_KEY=
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index f824bd515..306181fb7 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -7,12 +7,7 @@ import _map from 'lodash/map'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import dayjsTimezone from 'dayjs/plugin/timezone'
-import {
- ApiOperation,
- ApiOkResponse,
- ApiBearerAuth,
- ApiTags,
-} from '@nestjs/swagger'
+import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
import {
Controller,
Body,
@@ -76,7 +71,6 @@ 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'
@@ -88,7 +82,6 @@ import {
performanceTransformer,
trafficTransformer,
} from './utils/transformers'
-import { GetUptimeBirdseyeDto } from './dto/get-uptime-birdseye.dto'
import {
MAX_METRICS_IN_VIEW,
ProjectViewCustomEventDto,
@@ -159,38 +152,6 @@ const getPIDsArray = (pids, pid) => {
return pids
}
-const getMonitorIdsArray = (monitorIds, monitorId) => {
- const idsEmpty = _isEmpty(monitorIds)
- const idEmpty = _isEmpty(monitorId)
- if (idsEmpty && idEmpty)
- throw new BadRequestException(
- 'An array of Monitor IDs (monitorIds) or a Monitor ID (monitorId) has to be provided',
- )
- else if (!idsEmpty && !idEmpty)
- throw new BadRequestException(
- 'Please provide either an array of Monitor IDs (monitorIds) or a Monitor ID (monitorId), but not both',
- )
- else if (!idEmpty) {
- monitorIds = JSON.stringify([monitorId])
- }
-
- try {
- monitorIds = JSON.parse(monitorIds)
- } catch (e) {
- throw new UnprocessableEntityException(
- "Cannot process the provided array of Monitor ID's",
- )
- }
-
- if (!_isArray(monitorIds)) {
- throw new UnprocessableEntityException(
- "An array of Monitor ID's has to be provided as a 'monitorIds' param",
- )
- }
-
- return monitorIds
-}
-
const getEIDsArray = (eids, eid) => {
const eidsEmpty = _isEmpty(eids)
const eidEmpty = _isEmpty(eid)
@@ -1637,136 +1598,6 @@ export class AnalyticsController {
}
}
- @Get('monitor-data/birdseye')
- @Auth([], true, true)
- async getUptimeBirdseye(
- @Query() parameters: GetUptimeBirdseyeDto,
- @CurrentUserId() uid: string,
- @Headers() headers: { 'x-password'?: string },
- ) {
- const {
- pid,
- monitorId,
- monitorIds,
- period,
- from,
- to,
- timezone = DEFAULT_TIMEZONE,
- } = parameters
-
- await this.analyticsService.checkProjectAccess(
- pid,
- uid,
- headers['x-password'],
- )
-
- await this.analyticsService.checkBillingAccess(pid)
-
- const idsArray = getMonitorIdsArray(monitorIds, monitorId)
-
- const validationPromises = _map(idsArray, async currentId => {
- await this.analyticsService.checkUptimeAccess(pid, currentId)
- })
-
- await Promise.all(validationPromises)
-
- return this.analyticsService.getUptimeSummary(
- idsArray,
- period,
- from,
- to,
- timezone,
- )
- }
-
- @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,
- monitorId,
- period,
- timeBucket,
- from,
- to,
- timezone = DEFAULT_TIMEZONE,
- } = parameters
-
- await this.analyticsService.checkProjectAccess(
- pid,
- userId,
- headers['x-password'],
- )
-
- await this.analyticsService.checkBillingAccess(pid)
-
- await this.analyticsService.checkUptimeAccess(pid, monitorId)
-
- 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
- }
-
- const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
- const { groupFrom, groupTo, groupFromUTC, groupToUTC } =
- this.analyticsService.getGroupFromTo(
- from,
- to,
- newTimebucket,
- period,
- safeTimezone,
- diff,
- )
- const subQuery =
- 'FROM monitor_responses WHERE monitorId = {monitorId:UInt64} 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/backend/apps/cloud/src/analytics/analytics.service.ts b/backend/apps/cloud/src/analytics/analytics.service.ts
index 3bac6f31f..049b6d16c 100644
--- a/backend/apps/cloud/src/analytics/analytics.service.ts
+++ b/backend/apps/cloud/src/analytics/analytics.service.ts
@@ -36,7 +36,6 @@ import {
HttpStatus,
UnprocessableEntityException,
PreconditionFailedException,
- ForbiddenException,
} from '@nestjs/common'
import { isbot } from 'isbot'
@@ -46,7 +45,6 @@ import {
UNIQUE_SESSION_LIFE_TIME,
REDIS_SESSION_SALT_KEY,
TRAFFIC_COLUMNS,
- UPTIME_COLUMNS,
ALL_COLUMNS,
CAPTCHA_COLUMNS,
ERROR_COLUMNS,
@@ -98,7 +96,6 @@ import {
PropertiesCHResponse,
IPageProperty,
ICustomEvent,
- BirdseyeCHUptimeResponse,
} from './interfaces'
import { ErrorDto } from './dto/error.dto'
import { GetPagePropertyMetaDto } from './dto/get-page-property-meta.dto'
@@ -247,7 +244,7 @@ const generateParamsQuery = (
subQuery: string,
customEVFilterApplied: boolean,
isPageInclusiveFilterSet: boolean,
- type: 'traffic' | 'performance' | 'captcha' | 'errors' | 'uptime',
+ type: 'traffic' | 'performance' | 'captcha' | 'errors',
measure?: PerfMeasure,
): string => {
let columns = [`${col} as name`]
@@ -287,10 +284,6 @@ 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}`
}
@@ -380,14 +373,6 @@ export class AnalyticsService {
}
}
- async checkUptimeAccess(pid: string, monitorId: number) {
- const monitor = await this.projectService.findMonitorById(monitorId, pid)
-
- if (!monitor) {
- throw new ForbiddenException('You are not allowed to view this project')
- }
- }
-
checkOrigin(project: Project, origin: string): void {
// For some reasons the project.origins sometimes may look like [''], let's filter it out
// TODO: Properly validate the origins on project update
@@ -1413,171 +1398,6 @@ export class AnalyticsService {
return result
}
- async getUptimeSummary(
- monitorIds: number[],
- period?: string,
- from?: string,
- to?: string,
- timezone?: string,
- ): Promise<IOverallCaptcha> {
- // eslint-disable-next-line
- let _from: string
- // eslint-disable-next-line
- let _to: string
-
- if (_isEmpty(period) || ['today', 'yesterday', 'custom'].includes(period)) {
- const safeTimezone = this.getSafeTimezone(timezone)
-
- const { groupFrom, groupTo } = this.getGroupFromTo(
- from,
- to,
- ['today', 'yesterday'].includes(period) ? TimeBucketType.HOUR : null,
- period,
- safeTimezone,
- )
-
- _from = groupFrom
- _to = groupTo
- }
-
- const result = {}
-
- const promises = monitorIds.map(async monitorId => {
- try {
- if (period === 'all') {
- const queryAll = `
- SELECT
- coalesce(divide(avg(responseTime), 1000), 0) as avg,
- coalesce(divide(max(responseTime), 1000), 0) as max,
- coalesce(divide(min(responseTime), 1000), 0) as min
- FROM
- monitor_responses
- WHERE
- monitorId={monitorId:UInt64}
- `
-
- const { data } = await clickhouse
- .query({
- query: queryAll,
- query_params: { monitorId },
- })
- .then(resultSet => resultSet.json<BirdseyeCHUptimeResponse>())
-
- result[monitorId] = {
- current: {
- avg: data[0].avg || 0,
- min: data[0].min || 0,
- max: data[0].max || 0,
- },
- previous: {
- avg: 0,
- min: 0,
- max: 0,
- },
- avgChange: data[0].avg || 0,
- minChange: data[0].min || 0,
- maxChange: data[0].max || 0,
- }
- return
- }
-
- let now: string
- let periodFormatted: string
- let periodSubtracted: string
-
- if (_from && _to) {
- // diff may be 0 (when selecting data for 1 day), so let's make it 1 to grab some data for the prev day as well
- const diff = dayjs(_to).diff(dayjs(_from), 'days') || 1
-
- now = _to
- periodFormatted = _from
- periodSubtracted = dayjs(_from)
- .subtract(diff, 'days')
- .format('YYYY-MM-DD HH:mm:ss')
- } else {
- const amountToSubtract = parseInt(period, 10)
- const unit = _replace(period, /[0-9]/g, '') as dayjs.ManipulateType
-
- now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')
- const periodRaw = dayjs.utc().subtract(amountToSubtract, unit)
- periodFormatted = periodRaw.format('YYYY-MM-DD HH:mm:ss')
- periodSubtracted = periodRaw
- .subtract(amountToSubtract, unit)
- .format('YYYY-MM-DD HH:mm:ss')
- }
-
- const queryCurrent = `
- SELECT
- 1 AS sortOrder,
- coalesce(divide(avg(responseTime), 1000), 0) as avg,
- coalesce(divide(max(responseTime), 1000), 0) as max,
- coalesce(divide(min(responseTime), 1000), 0) as min
- FROM
- monitor_responses
- WHERE
- monitorId={monitorId:UInt64}
- AND created BETWEEN {periodFormatted:String} AND {now:String}
- `
-
- const queryPrevious = `
- SELECT
- 2 AS sortOrder,
- coalesce(divide(avg(responseTime), 1000), 0) as avg,
- coalesce(divide(max(responseTime), 1000), 0) as max,
- coalesce(divide(min(responseTime), 1000), 0) as min
- FROM
- monitor_responses
- WHERE
- monitorId={monitorId:UInt64}
- AND created BETWEEN {periodSubtracted:String} AND {periodFormatted:String}
- `
-
- const query = `${queryCurrent} UNION ALL ${queryPrevious}`
-
- let { data } = await clickhouse
- .query({
- query,
- query_params: {
- monitorId,
- periodFormatted,
- periodSubtracted,
- now,
- },
- })
- .then(resultSet => resultSet.json<BirdseyeCHUptimeResponse>())
-
- data = _sortBy(data, 'sortOrder')
-
- const currentPeriod = data[0]
- const previousPeriod = data[1]
-
- result[monitorId] = {
- current: {
- avg: currentPeriod.avg || 0,
- min: currentPeriod.min || 0,
- max: currentPeriod.max || 0,
- },
- previous: {
- avg: previousPeriod.avg || 0,
- min: previousPeriod.min || 0,
- max: previousPeriod.max || 0,
- },
- avgChange: currentPeriod.avg - previousPeriod.avg,
- minChange: currentPeriod.min - previousPeriod.min,
- maxChange: currentPeriod.max - previousPeriod.max,
- }
- } catch {
- throw new InternalServerErrorException(
- "Can't process the provided PID. Please, try again later.",
- )
- }
- })
-
- await Promise.all(promises)
-
- return result
- }
-
convertSummaryToObsoleteFormat(summary: IOverall): any {
const result = {}
@@ -2124,7 +1944,7 @@ export class AnalyticsService {
subQuery: string,
customEVFilterApplied: boolean,
paramsData: any,
- type: 'traffic' | 'performance' | 'captcha' | 'errors' | 'uptime',
+ type: 'traffic' | 'performance' | 'captcha' | 'errors',
measure?: PerfMeasure,
) {
// We need this to display all the pageview related data (e.g. country, browser) when user applies an inclusive filter on the Page column
@@ -2153,10 +1973,6 @@ export class AnalyticsService {
columns = PERFORMANCE_COLUMNS
}
- if (type === 'uptime') {
- columns = UPTIME_COLUMNS
- }
-
// Build a single query combining all metrics
const withClauses = columns.map(col => {
const baseQuery = generateParamsQuery(
@@ -2699,29 +2515,6 @@ export class AnalyticsService {
return baseQuery
}
- generateMonitorResponsesAggregationQuery(timeBucket: TimeBucketType): string {
- const timeBucketFunc = timeBucketConversion[timeBucket]
- const [selector, groupBy] = this.getGroupSubquery(timeBucket)
-
- const baseQuery = `
- SELECT
- ${selector},
- round(divide(avg(responseTime), 1000), 2) as avgResponseTime
- FROM (
- SELECT responseTime,
- ${timeBucketFunc}(created) as tz_created
- FROM monitor_responses
- WHERE
- monitorId = {monitorId:UInt64}
- AND created BETWEEN {groupFrom:String} AND {groupTo:String}
- ) as subquery
- GROUP BY ${groupBy}
- ORDER BY ${groupBy}
- `
-
- return baseQuery
- }
-
async groupByTimeBucket(
timeBucket: TimeBucketType,
from: string,
@@ -2987,24 +2780,6 @@ export class AnalyticsService {
}
}
- extractUptimeChartData(result, x: string[]): any {
- const avgResponseTime = Array(x.length).fill(0)
-
- for (let row = 0; row < _size(result); ++row) {
- const dateString = this.generateDateString(result[row])
-
- const index = x.indexOf(dateString)
-
- if (index !== -1) {
- avgResponseTime[index] = result[row].avgResponseTime
- }
- }
-
- return {
- avgResponseTime,
- }
- }
-
async groupCaptchaByTimeBucket(
timeBucket: TimeBucketType,
from: string,
@@ -3139,64 +2914,6 @@ export class AnalyticsService {
})
}
- async groupMonitorResponsesByTimeBucket(
- timeBucket: TimeBucketType,
- from: string,
- to: string,
- subQuery: string,
- paramsData: any,
- safeTimezone: string,
- ): Promise<object | void> {
- const 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,
- })
- .then(resultSet => resultSet.json<any>())
- const { avgResponseTime } = this.extractUptimeChartData(data, x)
-
- chart = {
- x: this.shiftToTimezone(x, safeTimezone, format),
- avgResponseTime,
- }
- })(),
- ]
-
- 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/backend/apps/cloud/src/analytics/dto/get-monitor-data.dto.ts b/backend/apps/cloud/src/analytics/dto/get-monitor-data.dto.ts
deleted file mode 100644
index 3d3b19f24..000000000
--- a/backend/apps/cloud/src/analytics/dto/get-monitor-data.dto.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsEnum, IsNotEmpty, IsOptional, Matches } from 'class-validator'
-import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'
-import { TimeBucketType } from './getData.dto'
-import { ValidatePeriod } from '../decorators/validate-period.decorator'
-import { PID_REGEX } from '../../common/constants'
-
-export class GetMonitorDataDto {
- @ApiProperty({
- example: 'aUn1quEid-3',
- required: true,
- description: 'The project ID',
- })
- @IsNotEmpty()
- @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
- pid: string
-
- @ApiProperty()
- @IsNotEmpty()
- monitorId: number
-
- @ApiProperty({ required: false })
- @IsOptional()
- @ValidatePeriod()
- period?: string
-
- @ApiProperty({ enum: TimeBucketType })
- @IsNotEmpty()
- @IsEnum(TimeBucketType, { message: 'The provided timebucket is incorrect' })
- 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/backend/apps/cloud/src/analytics/dto/get-uptime-birdseye.dto.ts b/backend/apps/cloud/src/analytics/dto/get-uptime-birdseye.dto.ts
deleted file mode 100644
index 8c623f386..000000000
--- a/backend/apps/cloud/src/analytics/dto/get-uptime-birdseye.dto.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { ApiProperty } from '@nestjs/swagger'
-import { IsNotEmpty, IsOptional, Matches } from 'class-validator'
-import { DEFAULT_TIMEZONE } from '../../user/entities/user.entity'
-import { ValidatePeriod } from '../decorators/validate-period.decorator'
-import { PID_REGEX } from '../../common/constants'
-
-export class GetUptimeBirdseyeDto {
- @ApiProperty({
- example: 'aUn1quEid-3',
- required: true,
- description: 'The project ID',
- })
- @IsNotEmpty()
- @Matches(PID_REGEX, { message: 'The provided Project ID (pid) is incorrect' })
- pid: string
-
- @ApiProperty({ required: false })
- @IsOptional()
- monitorId?: number
-
- @ApiProperty({ required: false, isArray: true })
- @IsOptional()
- monitorIds?: number[] | string[]
-
- @ApiProperty({ required: false })
- @IsOptional()
- @ValidatePeriod()
- period?: string
-
- @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/backend/apps/cloud/src/analytics/interfaces/index.ts b/backend/apps/cloud/src/analytics/interfaces/index.ts
index 5f752aa35..b097687df 100644
--- a/backend/apps/cloud/src/analytics/interfaces/index.ts
+++ b/backend/apps/cloud/src/analytics/interfaces/index.ts
@@ -22,12 +22,6 @@ export interface BirdseyeCHResponse {
sdur: number
}
-export interface BirdseyeCHUptimeResponse {
- avg: number
- min: number
- max: number
-}
-
export interface PerformanceCHResponse {
year: number
month: number
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.ts
index c8bcdfb6a..a11a3f683 100644
--- a/backend/apps/cloud/src/app.module.ts
+++ b/backend/apps/cloud/src/app.module.ts
@@ -1,4 +1,3 @@
-import _toNumber from 'lodash/toNumber'
import { Module } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { ConfigModule } from '@nestjs/config'
@@ -7,7 +6,6 @@ import { SentryModule, SentryGlobalFilter } from '@sentry/nestjs/setup'
import { ScheduleModule } from '@nestjs/schedule'
import { NestjsFormDataModule } from 'nestjs-form-data'
import { MailerModule as NodeMailerModule } from '@nestjs-modules/mailer'
-import { BullModule } from '@nestjs/bull'
import { I18nModule } from 'nestjs-i18n'
import { UserModule } from './user/user.module'
@@ -66,14 +64,6 @@ const modules = [
synchronize: false, // process.env.NODE_ENV !== 'production',
entities: [`${__dirname}/**/*.entity{.ts,.js}`],
}),
- BullModule.forRoot({
- redis: {
- host: process.env.REDIS_HOST,
- port: _toNumber(process.env.REDIS_PORT),
- username: process.env.REDIS_USER,
- password: process.env.REDIS_PASSWORD,
- },
- }),
I18nModule.forRootAsync(getI18nConfig()),
ScheduleModule.forRoot(),
NestjsFormDataModule.config({ isGlobal: true }),
diff --git a/backend/apps/cloud/src/common/constants.ts b/backend/apps/cloud/src/common/constants.ts
index 99026aca6..e9272c122 100644
--- a/backend/apps/cloud/src/common/constants.ts
+++ b/backend/apps/cloud/src/common/constants.ts
@@ -114,8 +114,6 @@ const TRAFFIC_COLUMNS = [
'co',
]
-const UPTIME_COLUMNS = ['region', 'statusCode']
-
const TRAFFIC_METAKEY_COLUMNS = ['tag:key', 'tag:value']
const ERROR_COLUMNS = [
@@ -208,7 +206,6 @@ export {
getRedisUserUsageInfoKey,
redisUserUsageinfoCacheTimeout,
TRAFFIC_COLUMNS,
- UPTIME_COLUMNS,
TRAFFIC_METAKEY_COLUMNS,
CAPTCHA_COLUMNS,
ERROR_COLUMNS,
diff --git a/backend/apps/cloud/src/common/templates/en/uptime-monitoring-failure.html b/backend/apps/cloud/src/common/templates/en/uptime-monitoring-failure.html
deleted file mode 100644
index 75156e4bf..000000000
--- a/backend/apps/cloud/src/common/templates/en/uptime-monitoring-failure.html
+++ /dev/null
@@ -1,3 +0,0 @@
-Hello,
-
-We have just detected that the monitor {{monitorName}} of the {{projectName}} project is down.
diff --git a/backend/apps/cloud/src/mailer/letter.ts b/backend/apps/cloud/src/mailer/letter.ts
index 0937c8e5b..23513699c 100644
--- a/backend/apps/cloud/src/mailer/letter.ts
+++ b/backend/apps/cloud/src/mailer/letter.ts
@@ -20,6 +20,5 @@ export enum LetterTemplate {
UsageOverLimit = 'usage-over-limit',
DashboardLockedExceedingLimits = 'dashboard-locked-exceeding-limits',
DashboardLockedPaymentFailure = 'dashboard-locked-payment-failure',
- UptimeMonitoringFailure = 'uptime-monitoring-failure',
OrganisationInvitation = 'organisation-invitation',
}
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index 95f387c3c..2519e6e43 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -124,11 +124,6 @@ const metaInfoJson = {
'[ACTION REQUIRED] Your Swetrix dashboard has been locked due to a payment issue',
},
},
- [LetterTemplate.UptimeMonitoringFailure]: {
- subject: {
- en: (p: Params) => `Monitor "${p.monitorName}" is down`,
- },
- },
}
interface Params {
diff --git a/backend/apps/cloud/src/project/consumers/monitor.consumer.ts b/backend/apps/cloud/src/project/consumers/monitor.consumer.ts
deleted file mode 100644
index 609988570..000000000
--- a/backend/apps/cloud/src/project/consumers/monitor.consumer.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import { Process, Processor } from '@nestjs/bull'
-import { Inject, InternalServerErrorException, Logger } from '@nestjs/common'
-import { ClientProxy } from '@nestjs/microservices'
-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,
- private readonly projectService: ProjectService,
- private readonly mailerService: MailerService,
- ) {}
-
- private readonly logger = new Logger(MonitorConsumer.name)
-
- @Process('http-request')
- async httpRequestProcess(
- job: Job<CreateMonitorHttpRequestDTO & { monitorId: number }>,
- ): Promise<any> {
- const res: {
- responseTime: number
- statusCode: number
- timestamp: number
- region: string
- } = await firstValueFrom(this.monitorService.send('http-request', job.data))
-
- // const monitor = await this.projectService.getMonitor(job.data.monitorId)
-
- // TODO: Don't send emails yet as we need to configure a system when we can send only 1 email on downtime and on uptime, not on every failed request
- // if (!monitor.acceptedStatusCodes.includes(res.statusCode)) {
- // try {
- // await this.mailerService.sendEmail(
- // monitor.project.admin.email,
- // LetterTemplate.UptimeMonitoringFailure,
- // {
- // projectName: monitor.project.name,
- // monitorName: monitor.name,
- // },
- // )
- // } catch (reason) {
- // console.error('Monitor failure: sendEmail action failed')
- // console.error(reason)
- // }
- // }
-
- try {
- await clickhouse.insert({
- table: 'monitor_responses',
- format: 'JSONEachRow',
- values: [
- {
- monitorId: job.data.monitorId,
- region: res.region,
- responseTime: res.responseTime,
- timestamp: res.timestamp,
- statusCode: res.statusCode,
- },
- ],
- })
- } catch (e) {
- this.logger.error(e)
- throw new InternalServerErrorException(
- 'Error occurred while saving the monitor data',
- )
- }
- }
-}
diff --git a/backend/apps/cloud/src/project/dto/create-monitor.dto.ts b/backend/apps/cloud/src/project/dto/create-monitor.dto.ts
deleted file mode 100644
index e230ff4c9..000000000
--- a/backend/apps/cloud/src/project/dto/create-monitor.dto.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import {
- IsEnum,
- IsString,
- IsUrl,
- IsNumber,
- IsArray,
- ValidateNested,
- IsOptional,
- IsObject,
-} from 'class-validator'
-import { Type } from 'class-transformer'
-import { ApiProperty } from '@nestjs/swagger'
-
-// Enums for HTTP Methods and Status Codes
-export enum HttpMethodEnum {
- GET = 'GET',
- POST = 'POST',
- PUT = 'PUT',
- PATCH = 'PATCH',
- DELETE = 'DELETE',
- HEAD = 'HEAD',
- OPTIONS = 'OPTIONS',
-}
-
-export enum HttpStatusCodeEnum {
- OK = 200,
- CREATED = 201,
- ACCEPTED = 202,
- NO_CONTENT = 204,
- MOVED_PERMANENTLY = 301,
- FOUND = 302,
- NOT_MODIFIED = 304,
- BAD_REQUEST = 400,
- UNAUTHORIZED = 401,
- FORBIDDEN = 403,
- NOT_FOUND = 404,
- INTERNAL_SERVER_ERROR = 500,
- NOT_IMPLEMENTED = 501,
- BAD_GATEWAY = 502,
- SERVICE_UNAVAILABLE = 503,
- GATEWAY_TIMEOUT = 504,
-}
-
-export enum HttpType {
- HTTP = 'HTTP',
- HTTPS = 'HTTPS',
-}
-
-// DTO for HTTP Options
-export class HttpOptions {
- @IsArray()
- @IsEnum(HttpMethodEnum)
- method: HttpMethodEnum
-
- @IsOptional()
- @IsObject()
- body?: Record<string, unknown>
-
- @IsOptional()
- @IsObject()
- headers?: Record<string, string>
-}
-
-// Main DTO for Monitor Request
-export class CreateMonitorHttpRequestDTO {
- @ApiProperty()
- @IsEnum(HttpType)
- type: HttpType
-
- @ApiProperty()
- @IsString()
- name: string
-
- @ApiProperty()
- @IsUrl()
- url: string
-
- @ApiProperty()
- @IsNumber()
- interval: number
-
- @ApiProperty()
- @IsNumber()
- retries: number
-
- @ApiProperty()
- @IsNumber()
- retryInterval: number
-
- @ApiProperty()
- @IsNumber()
- timeout: number
-
- @ApiProperty()
- @IsArray()
- @IsEnum(HttpStatusCodeEnum, { each: true })
- acceptedStatusCodes: HttpStatusCodeEnum[]
-
- @ApiProperty()
- @IsOptional()
- @IsString()
- description?: string
-
- @ApiProperty()
- @ValidateNested()
- @Type(() => HttpOptions)
- httpOptions: HttpOptions
-}
diff --git a/backend/apps/cloud/src/project/dto/update-monitor.dto.ts b/backend/apps/cloud/src/project/dto/update-monitor.dto.ts
deleted file mode 100644
index 1d1c4d891..000000000
--- a/backend/apps/cloud/src/project/dto/update-monitor.dto.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import {
- IsEnum,
- IsOptional,
- IsString,
- ValidateNested,
- IsUrl,
- IsNumber,
- IsArray,
-} from 'class-validator'
-
-import { ApiProperty } from '@nestjs/swagger'
-import { HttpStatusCodeEnum, HttpOptions } from './create-monitor.dto'
-
-export class UpdateMonitorHttpRequestDTO {
- @ApiProperty()
- @IsEnum(['HTTP', 'HTTPS'])
- type: 'HTTP' | 'HTTPS'
-
- @ApiProperty()
- @IsString()
- name: string
-
- @ApiProperty()
- @IsUrl()
- url: string
-
- @ApiProperty()
- @IsNumber()
- interval: number
-
- @ApiProperty()
- @IsNumber()
- retries: number
-
- @ApiProperty()
- @IsNumber()
- retryInterval: number
-
- @ApiProperty()
- @IsNumber()
- timeout: number
-
- @ApiProperty()
- @IsArray()
- @IsEnum(HttpStatusCodeEnum, { each: true })
- acceptedStatusCodes: HttpStatusCodeEnum[]
-
- @ApiProperty()
- @IsOptional()
- @IsString()
- description?: string
-
- @ApiProperty()
- @ValidateNested()
- httpOptions: HttpOptions
-}
diff --git a/backend/apps/cloud/src/project/entity/monitor.entity.ts b/backend/apps/cloud/src/project/entity/monitor.entity.ts
deleted file mode 100644
index 6935d6989..000000000
--- a/backend/apps/cloud/src/project/entity/monitor.entity.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import {
- Entity,
- Column,
- PrimaryGeneratedColumn,
- ManyToOne,
- CreateDateColumn,
- UpdateDateColumn,
-} from 'typeorm'
-import { ApiProperty } from '@nestjs/swagger'
-import { Project } from './project.entity'
-
-@Entity('monitor')
-export class MonitorEntity {
- @ApiProperty()
- @PrimaryGeneratedColumn('increment', { type: 'bigint' })
- id: number
-
- @ApiProperty()
- @Column({ type: 'varchar' })
- type: string
-
- @ApiProperty()
- @Column({ type: 'varchar' })
- name: string
-
- @ApiProperty()
- @Column({ type: 'varchar' })
- url: string
-
- @ApiProperty()
- @Column({ type: 'int' })
- interval: number
-
- @ApiProperty()
- @Column({ type: 'int' })
- retries: number
-
- @ApiProperty()
- @Column({ type: 'int' })
- retryInterval: number
-
- @ApiProperty()
- @Column({ type: 'int' })
- timeout: number
-
- @ApiProperty()
- @Column({ type: 'json' })
- acceptedStatusCodes: number[]
-
- @ApiProperty()
- @Column({ type: 'text', nullable: true })
- description: string | null
-
- @ManyToOne(() => Project, entity => entity.monitors, {
- onDelete: 'CASCADE',
- })
- project: Project
-
- @ApiProperty()
- @CreateDateColumn()
- createdAt: Date
-
- @ApiProperty()
- @UpdateDateColumn()
- updatedAt: Date
-
- @ApiProperty()
- @Column({ type: 'json', nullable: true })
- httpOptions: {
- method: string
- body?: Record<string, unknown>
- headers?: Record<string, string>
- }
-}
diff --git a/backend/apps/cloud/src/project/entity/project.entity.ts b/backend/apps/cloud/src/project/entity/project.entity.ts
index 819795784..47b7b217e 100644
--- a/backend/apps/cloud/src/project/entity/project.entity.ts
+++ b/backend/apps/cloud/src/project/entity/project.entity.ts
@@ -16,7 +16,6 @@ import { ProjectSubscriber } from './project-subscriber.entity'
import { Funnel } from './funnel.entity'
import { CAPTCHA_SECRET_KEY_LENGTH } from '../../common/constants'
import { ProjectViewEntity } from './project-view.entity'
-import { MonitorEntity } from './monitor.entity'
import { Organisation } from '../../organisation/entity/organisation.entity'
export enum BotsProtectionLevel {
@@ -133,9 +132,6 @@ export class Project {
@OneToMany(() => ProjectViewEntity, projectView => projectView.id)
views: ProjectViewEntity[]
- @OneToMany(() => MonitorEntity, monitor => monitor.id)
- monitors: MonitorEntity[]
-
@ManyToOne(() => Organisation, org => org.projects, { nullable: true })
organisation: Organisation | null
}
diff --git a/backend/apps/cloud/src/project/interfaces/http-request-options.interface.ts b/backend/apps/cloud/src/project/interfaces/http-request-options.interface.ts
deleted file mode 100644
index 3e1869a95..000000000
--- a/backend/apps/cloud/src/project/interfaces/http-request-options.interface.ts
+++ /dev/null
@@ -1,14 +0,0 @@
-export interface HttpRequestOptions {
- type: string
- url: string
- interval: number
- retries: number
- retryInterval: number
- timeout: number
- acceptedStatusCodes: number[]
- httpOptions: {
- method: string
- body?: Record<string, unknown>
- headers?: Record<string, string>
- }
-}
diff --git a/backend/apps/cloud/src/project/interfaces/monitor-data-interfaces.ts b/backend/apps/cloud/src/project/interfaces/monitor-data-interfaces.ts
deleted file mode 100644
index 1cd16dd32..000000000
--- a/backend/apps/cloud/src/project/interfaces/monitor-data-interfaces.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-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/backend/apps/cloud/src/project/project.controller.ts b/backend/apps/cloud/src/project/project.controller.ts
index 19c246484..5a4d34ff2 100644
--- a/backend/apps/cloud/src/project/project.controller.ts
+++ b/backend/apps/cloud/src/project/project.controller.ts
@@ -33,7 +33,6 @@ import {
ApiOkResponse,
ApiNoContentResponse,
} from '@nestjs/swagger'
-import { Equal } from 'typeorm'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _trim from 'lodash/trim'
@@ -107,9 +106,6 @@ import { ProjectIdDto } from './dto/project-id.dto'
import { CreateProjectViewDto } from './dto/create-project-view.dto'
import { UpdateProjectViewDto } from './dto/update-project-view.dto'
import { ProjectViewIdsDto } from './dto/project-view-ids.dto'
-import { CreateMonitorHttpRequestDTO } from './dto/create-monitor.dto'
-import { MonitorEntity } from './entity/monitor.entity'
-import { UpdateMonitorHttpRequestDTO } from './dto/update-monitor.dto'
import { BulkAddUsersDto } from './dto/bulk-add-users.dto'
import { BulkAddUsersResponse } from './interfaces/bulk-add-users'
import { OrganisationService } from '../organisation/organisation.service'
@@ -2224,178 +2220,4 @@ export class ProjectController {
await this.projectsViewsRepository.deleteProjectView(params.viewId)
}
-
- @ApiOperation({ summary: 'Get monitors for a project' })
- @ApiBearerAuth()
- @ApiOkResponse({ type: MonitorEntity })
- @Get(':projectId/monitors')
- @Auth([], true, true)
- public async getProjectMonitors(
- @Param() { projectId }: ProjectIdDto,
- @CurrentUserId() userId: string,
- @Query('take') take: number | undefined,
- @Query('skip') skip: number | undefined,
- @Headers() headers: { 'x-password'?: string },
- ): Promise<Pagination<MonitorEntity>> {
- this.logger.log({ userId, take, skip }, 'GET /project/:projectId/monitors')
-
- const project = await this.projectService.getFullProject(projectId)
-
- if (!project) {
- throw new NotFoundException('Project not found.')
- }
-
- this.projectService.allowedToView(project, userId, headers['x-password'])
-
- const result = await this.projectService.paginateMonitors(
- {
- take,
- skip,
- },
- { project: Equal(project.id) },
- )
-
- // @ts-expect-error
- result.results = _map(result.results, monitor => ({
- ..._omit(monitor, ['project']),
- projectId: monitor.project.id,
- }))
-
- return result
- }
-
- @ApiOperation({ summary: 'Create monitor for the project' })
- @ApiBearerAuth()
- @ApiOkResponse({ type: MonitorEntity })
- @Post(':projectId/monitor')
- @Auth([], true, true)
- public async createMonitor(
- @Param() { projectId }: ProjectIdDto,
- @Body() body: CreateMonitorHttpRequestDTO,
- @CurrentUserId() userId: string,
- ): Promise<MonitorEntity> {
- const project = await this.projectService.getFullProject(projectId)
-
- if (!project) {
- throw new NotFoundException('Project not found.')
- }
-
- const user = await this.userService.findUserV2(userId, ['roles'])
-
- if (!user) {
- throw new NotFoundException('User not found.')
- }
-
- this.projectService.allowedToManage(project, userId, user.roles)
-
- const monitor = await this.projectService.createMonitor(body, projectId)
-
- // Create a job in service for sending httpRequest
- await this.projectService.sendHttpRequest(monitor.id, {
- ...monitor,
- timeout: monitor.timeout * 1000,
- })
-
- return monitor
- }
-
- @ApiOperation({ summary: 'Get monitor for the project' })
- @ApiBearerAuth()
- @ApiOkResponse({ type: MonitorEntity })
- @Get(':projectId/monitor/:monitorId')
- @Auth([], true, true)
- public async getMonitor(
- @Param() { projectId }: ProjectIdDto,
- @Param('monitorId') monitorId: number,
- @CurrentUserId() userId: string,
- ): Promise<MonitorEntity> {
- const project = await this.projectService.getFullProject(projectId)
-
- if (!project) {
- throw new NotFoundException('Project not found.')
- }
-
- this.projectService.allowedToManage(project, userId)
-
- const monitor = await this.projectService.getMonitor(monitorId)
-
- if (!monitor) {
- throw new NotFoundException('Monitor not found.')
- }
-
- return monitor
- }
-
- @ApiOperation({ summary: 'Update monitor for the project' })
- @ApiBearerAuth()
- @ApiOkResponse({ type: MonitorEntity })
- @Patch(':projectId/monitor/:monitorId')
- @Auth([], true, true)
- public async updateMonitor(
- @Param() { projectId }: ProjectIdDto,
- @Param('monitorId') monitorId: number,
- @Body() body: UpdateMonitorHttpRequestDTO,
- @CurrentUserId() userId: string,
- ): Promise<void> {
- const project = await this.projectService.getFullProject(projectId)
-
- if (!project) {
- throw new NotFoundException('Project not found.')
- }
-
- const user = await this.userService.findUserV2(userId, ['roles'])
-
- if (!user) {
- throw new NotFoundException('User not found.')
- }
-
- this.projectService.allowedToManage(project, userId, user.roles)
-
- const monitor = await this.projectService.getMonitor(monitorId)
-
- if (!monitor) {
- throw new NotFoundException('Monitor not found.')
- }
-
- const updatedMonitor = await this.projectService.updateMonitor(
- monitorId,
- body,
- )
-
- await this.projectService.updateHttpRequest(monitor.id, monitor)
- return updatedMonitor
- }
-
- @ApiOperation({ summary: 'Delete monitor from the project' })
- @ApiBearerAuth()
- @ApiOkResponse({ description: 'Monitor deleted successfully' })
- @Delete(':projectId/monitor/:monitorId')
- @Auth([], true, true)
- public async deleteMonitor(
- @Param() { projectId }: ProjectIdDto,
- @Param('monitorId') monitorId: number,
- @CurrentUserId() userId: string,
- ): Promise<void> {
- const project = await this.projectService.getFullProject(projectId)
-
- if (!project) {
- throw new NotFoundException('Project not found.')
- }
- const user = await this.userService.findUserV2(userId, ['roles'])
-
- if (!user) {
- throw new NotFoundException('User not found.')
- }
-
- this.projectService.allowedToManage(project, userId, user.roles)
-
- const monitor = await this.projectService.getMonitor(monitorId)
-
- if (!monitor) {
- throw new NotFoundException('Monitor not found.')
- }
-
- this.projectService.deleteMonitor(monitorId)
- this.projectService.deleteHttpRequest(monitorId)
- }
}
diff --git a/backend/apps/cloud/src/project/project.module.ts b/backend/apps/cloud/src/project/project.module.ts
index ec67dae55..bb827e70a 100644
--- a/backend/apps/cloud/src/project/project.module.ts
+++ b/backend/apps/cloud/src/project/project.module.ts
@@ -1,7 +1,5 @@
import { Module, forwardRef } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
-import { ClientsModule, Transport } from '@nestjs/microservices'
-import { BullModule } from '@nestjs/bull'
import { ProjectService } from './project.service'
import { ProjectController } from './project.controller'
@@ -13,8 +11,6 @@ import { Project, ProjectSubscriber, Funnel, ProjectShare } from './entity'
import { ProjectsViewsRepository } from './repositories/projects-views.repository'
import { ProjectViewEntity } from './entity/project-view.entity'
import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event.entity'
-import { MonitorConsumer } from './consumers/monitor.consumer'
-import { MonitorEntity } from './entity/monitor.entity'
import { OrganisationModule } from '../organisation/organisation.module'
import { ProjectExtraService } from './project-extra.service'
@@ -27,40 +23,14 @@ import { ProjectExtraService } from './project-extra.service'
Funnel,
ProjectViewEntity,
ProjectViewCustomEventEntity,
- MonitorEntity,
]),
forwardRef(() => UserModule),
forwardRef(() => OrganisationModule),
- ClientsModule.register([
- {
- name: 'MONITOR_SERVICE',
- transport: Transport.RMQ,
- options: {
- urls: [process.env.MONITOR_QUEUE_URL],
- queue: 'monitor_queue',
- queueOptions: {
- durable: false,
- },
- },
- },
- ]),
- BullModule.registerQueue({
- name: 'monitor',
- defaultJobOptions: {
- removeOnComplete: true,
- removeOnFail: 25,
- },
- }),
AppLoggerModule,
ActionTokensModule,
MailerModule,
],
- providers: [
- ProjectService,
- ProjectExtraService,
- ProjectsViewsRepository,
- MonitorConsumer,
- ],
+ providers: [ProjectService, ProjectExtraService, ProjectsViewsRepository],
exports: [ProjectService, ProjectExtraService, ProjectsViewsRepository],
controllers: [ProjectController],
})
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index d67f1cdf2..5a05a2fed 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -34,8 +34,6 @@ import _reduce from 'lodash/reduce'
import dayjs from 'dayjs'
import utc from 'dayjs/plugin/utc'
import { compareSync } from 'bcrypt'
-import { InjectQueue } from '@nestjs/bull'
-import { Queue } from 'bullmq'
import { UserService } from '../user/user.service'
import { ActionTokensService } from '../action-tokens/action-tokens.service'
@@ -82,10 +80,6 @@ import { ReportFrequency } from './enums'
import { nFormatter } from '../common/utils'
import { browserArgs } from '../og-image/og-image.service'
import { CreateProjectViewDto } from './dto/create-project-view.dto'
-import { CreateMonitorHttpRequestDTO } from './dto/create-monitor.dto'
-import { MonitorEntity } from './entity/monitor.entity'
-import { UpdateMonitorHttpRequestDTO } from './dto/update-monitor.dto'
-import { HttpRequestOptions } from './interfaces/http-request-options.interface'
import { Organisation } from '../organisation/entity/organisation.entity'
import { OrganisationRole } from '../organisation/entity/organisation-member.entity'
@@ -315,12 +309,9 @@ export class ProjectService {
private readonly projectSubscriberRepository: Repository<ProjectSubscriber>,
@InjectRepository(Funnel)
private readonly funnelRepository: Repository<Funnel>,
- @InjectRepository(MonitorEntity)
- private readonly monitorRepository: Repository<MonitorEntity>,
private readonly actionTokens: ActionTokensService,
private readonly mailerService: MailerService,
private readonly userService: UserService,
- @InjectQueue('monitor') private monitorQueue: Queue,
) {}
async getRedisProject(pid: string): Promise<Project | null> {
@@ -1567,152 +1558,6 @@ export class ProjectService {
)
}
- async findMonitorById(
- id: number,
- projectId: string,
- options?: Omit<FindOneOptions<MonitorEntity>, 'where'>,
- ): Promise<MonitorEntity | undefined> {
- return this.monitorRepository.findOne({
- where: {
- id,
- project: {
- id: projectId,
- },
- },
- ...options,
- })
- }
-
- async createMonitor(
- {
- type,
- name,
- url,
- interval,
- retries,
- retryInterval,
- timeout,
- acceptedStatusCodes,
- description,
- httpOptions,
- }: CreateMonitorHttpRequestDTO,
- projectId: string,
- ): Promise<MonitorEntity> {
- const monitor = this.monitorRepository.create({
- type,
- name,
- url,
- interval,
- retries,
- retryInterval,
- timeout,
- acceptedStatusCodes,
- description,
- httpOptions,
- project: { id: projectId },
- })
-
- return this.monitorRepository.save(monitor)
- }
-
- async getMonitor(monitorId: number) {
- return this.monitorRepository.findOne({
- where: {
- id: monitorId,
- },
- relations: ['project'],
- })
- }
-
- async paginateMonitors(
- options: PaginationOptionsInterface,
- where: FindManyOptions<MonitorEntity>['where'],
- ): Promise<Pagination<MonitorEntity>> {
- const [results, total] = await this.monitorRepository.findAndCount({
- take: options.take || 100,
- skip: options.skip || 0,
- where,
- order: {
- name: 'ASC',
- },
- relations: ['project'],
- })
-
- return new Pagination<MonitorEntity>({
- results,
- total,
- })
- }
-
- async updateMonitor(
- monitorId: number,
- {
- type,
- name,
- url,
- interval,
- retries,
- retryInterval,
- timeout,
- acceptedStatusCodes,
- description,
- httpOptions,
- }: UpdateMonitorHttpRequestDTO,
- ): Promise<void> {
- await this.monitorRepository.update(
- { id: monitorId },
- {
- type,
- name,
- url,
- interval,
- retries,
- retryInterval,
- timeout,
- acceptedStatusCodes,
- description,
- httpOptions,
- },
- )
- }
-
- async deleteMonitor(monitorId: number) {
- return this.monitorRepository.delete(monitorId)
- }
-
- async sendHttpRequest(
- monitorId: number,
- monitorHttpRequestDto: HttpRequestOptions,
- ) {
- await this.monitorQueue.add(
- 'http-request',
- { ...monitorHttpRequestDto, monitorId },
- {
- repeat: { every: monitorHttpRequestDto.interval * 1000 },
- jobId: monitorId.toString(),
- },
- )
- }
-
- async updateHttpRequest(
- monitorId: number,
- updatedHttpRequestDto: HttpRequestOptions,
- ): Promise<void> {
- await this.deleteHttpRequest(monitorId)
-
- await this.sendHttpRequest(monitorId, {
- ...updatedHttpRequestDto,
- timeout: updatedHttpRequestDto.timeout * 1000,
- })
- }
-
- async deleteHttpRequest(monitorId: number) {
- const job = await this.monitorQueue.getJob(monitorId.toString())
- if (job) {
- await job.remove()
- }
- }
-
async addProjectToOrganisation(organisationId: string, projectId: string) {
const project = await this.findOne({
where: { id: projectId },
diff --git a/backend/meta/kill_all_jobs_rmq.js b/backend/meta/kill_all_jobs_rmq.js
deleted file mode 100644
index c80c10caa..000000000
--- a/backend/meta/kill_all_jobs_rmq.js
+++ /dev/null
@@ -1,49 +0,0 @@
-/* eslint-disable @typescript-eslint/no-require-imports */
-const { Queue } = require('bullmq')
-require('dotenv').config()
-
-async function cleanAllJobs(queueName) {
- const queue = new Queue(queueName, {
- connection: {
- host: process.env.REDIS_HOST,
- port: process.env.REDIS_PORT,
- // Add other Redis connection options if needed
- },
- })
-
- try {
- // Clean all completed jobs
- await queue.clean(0, 1000, 'completed')
- console.log('Completed jobs cleaned')
-
- // Clean all waiting jobs
- await queue.clean(0, 1000, 'wait')
- console.log('Waiting jobs cleaned')
-
- // Clean all active jobs
- await queue.clean(0, 1000, 'active')
- console.log('Active jobs cleaned')
-
- // Clean all delayed jobs
- await queue.clean(0, 1000, 'delayed')
- console.log('Delayed jobs cleaned')
-
- // Clean all failed jobs
- await queue.clean(0, 1000, 'failed')
- console.log('Failed jobs cleaned')
-
- // Drain the queue (remove all jobs)
- await queue.drain()
- console.log('Queue drained')
-
- // Obliterate the queue (remove all data and jobs associated with the queue)
- await queue.obliterate({ force: true })
- console.log('Queue obliterated')
- } catch (error) {
- console.error('Error cleaning jobs:', error)
- } finally {
- await queue.close()
- }
-}
-
-cleanAllJobs('monitor')
diff --git a/backend/migrations/clickhouse/2025_02_08.js b/backend/migrations/clickhouse/2025_02_08.js
new file mode 100644
index 000000000..284f92ed3
--- /dev/null
+++ b/backend/migrations/clickhouse/2025_02_08.js
@@ -0,0 +1,8 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ // Remove uptime
+ `DROP TABLE IF EXISTS ${dbName}.monitor_responses`,
+]
+
+queriesRunner(queries)
diff --git a/backend/migrations/clickhouse/initialise_database.js b/backend/migrations/clickhouse/initialise_database.js
index ea423e774..af00f76c9 100644
--- a/backend/migrations/clickhouse/initialise_database.js
+++ b/backend/migrations/clickhouse/initialise_database.js
@@ -158,19 +158,6 @@ const CLICKHOUSE_INIT_QUERIES = [
ENGINE = MergeTree()
PARTITION BY toYYYYMM(created)
ORDER BY (pid, created);`,
-
- `CREATE TABLE IF NOT EXISTS ${dbName}.monitor_responses
- (
- monitorId UInt64,
- region LowCardinality(Nullable(String)),
- responseTime UInt32,
- timestamp UInt32,
- statusCode UInt32,
- created DateTime('UTC') DEFAULT now()
- )
- ENGINE = MergeTree()
- PARTITION BY toYYYYMM(created)
- ORDER BY (monitorId, created);`,
]
const initialiseDatabase = async () => {
diff --git a/backend/migrations/mysql/2025_02_08.sql b/backend/migrations/mysql/2025_02_08.sql
new file mode 100644
index 000000000..e3bbca4a0
--- /dev/null
+++ b/backend/migrations/mysql/2025_02_08.sql
@@ -0,0 +1,2 @@
+DROP TABLE IF EXISTS monitor;
+DROP TABLE IF EXISTS monitor_groups;
diff --git a/backend/package-lock.json b/backend/package-lock.json
index 27cd2f51d..4d9a22952 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -11,7 +11,6 @@
"@faker-js/faker": "^9.2.0",
"@nestjs-modules/mailer": "^2.0.2",
"@nestjs/axios": "^3.1.2",
- "@nestjs/bull": "^10.2.2",
"@nestjs/common": "^10.4.7",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.4.7",
@@ -34,8 +33,6 @@
"axios": "^1.7.7",
"bcrypt": "^5.1.1",
"body-parser": "^1.20.3",
- "bull": "^4.16.4",
- "bullmq": "^5.25.6",
"chalk": "^4.1.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
@@ -973,84 +970,6 @@
"resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.15.0.tgz",
"integrity": "sha512-HZpPoABogPvjeJOdzCOSJsXeL/SMCBgBZMVC3X3d7YYp2gf31MfxhUoYUNwf1ERPJOnQc0wkFn9trqI6ZEdZuA=="
},
- "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.3.tgz",
- "integrity": "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.3.tgz",
- "integrity": "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "darwin"
- ]
- },
- "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.3.tgz",
- "integrity": "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw==",
- "cpu": [
- "arm"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.3.tgz",
- "integrity": "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg==",
- "cpu": [
- "arm64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.3.tgz",
- "integrity": "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "linux"
- ]
- },
- "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.3.tgz",
- "integrity": "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ==",
- "cpu": [
- "x64"
- ],
- "license": "MIT",
- "optional": true,
- "os": [
- "win32"
- ]
- },
"node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.5",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.5.tgz",
@@ -1151,34 +1070,6 @@
"rxjs": "^6.0.0 || ^7.0.0"
}
},
- "node_modules/@nestjs/bull": {
- "version": "10.2.2",
- "resolved": "https://registry.npmjs.org/@nestjs/bull/-/bull-10.2.2.tgz",
- "integrity": "sha512-5UW1X82C03EUm4DH/Cj+zeN2YdcfWUJnNji4tIXHMJplYKLKQA3QXIiwtttLBDO0omYx5WL0MyteRc69CDjoNg==",
- "license": "MIT",
- "dependencies": {
- "@nestjs/bull-shared": "^10.2.2",
- "tslib": "2.8.0"
- },
- "peerDependencies": {
- "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
- "@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0",
- "bull": "^3.3 || ^4.0.0"
- }
- },
- "node_modules/@nestjs/bull-shared": {
- "version": "10.2.2",
- "resolved": "https://registry.npmjs.org/@nestjs/bull-shared/-/bull-shared-10.2.2.tgz",
- "integrity": "sha512-bMIEILYYovQWfdz6fCSTgqb/zuKyGmNSc7guB56MiZVW84JloUHb8330nNh3VWaamJKGtUzawbEoG2VR3uVeOg==",
- "license": "MIT",
- "dependencies": {
- "tslib": "2.8.0"
- },
- "peerDependencies": {
- "@nestjs/common": "^8.0.0 || ^9.0.0 || ^10.0.0",
- "@nestjs/core": "^8.0.0 || ^9.0.0 || ^10.0.0"
- }
- },
"node_modules/@nestjs/cli": {
"version": "10.4.7",
"resolved": "https://registry.npmjs.org/@nestjs/cli/-/cli-10.4.7.tgz",
@@ -5126,59 +5017,6 @@
"resolved": "https://registry.npmjs.org/buffer-more-ints/-/buffer-more-ints-1.0.0.tgz",
"integrity": "sha512-EMetuGFz5SLsT0QTnXzINh4Ksr+oo4i+UGTXEshiGCQWnsgSs7ZhJ8fzlwQ+OzEMs0MpDAMr1hxnblp5a4vcHg=="
},
- "node_modules/bull": {
- "version": "4.16.4",
- "resolved": "https://registry.npmjs.org/bull/-/bull-4.16.4.tgz",
- "integrity": "sha512-CF+nGsJyfsCC9MJL8hFxqXzbwq+jGBXhaz1j15G+5N/XtKIPFUUy5O1mfWWKbKunfuH/x+UV4NYRQDHSkjCOgA==",
- "license": "MIT",
- "dependencies": {
- "cron-parser": "^4.2.1",
- "get-port": "^5.1.1",
- "ioredis": "^5.3.2",
- "lodash": "^4.17.21",
- "msgpackr": "^1.11.2",
- "semver": "^7.5.2",
- "uuid": "^8.3.0"
- },
- "engines": {
- "node": ">=12"
- }
- },
- "node_modules/bull/node_modules/uuid": {
- "version": "8.3.2",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
- "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
- "bin": {
- "uuid": "dist/bin/uuid"
- }
- },
- "node_modules/bullmq": {
- "version": "5.25.6",
- "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.25.6.tgz",
- "integrity": "sha512-jxpa/DB02V20CqBAgyqpQazT630CJm0r4fky8EchH3mcJAomRtKXLS6tRA0J8tb29BDGlr/LXhlUuZwdBJBSdA==",
- "license": "MIT",
- "dependencies": {
- "cron-parser": "^4.6.0",
- "ioredis": "^5.4.1",
- "msgpackr": "^1.11.2",
- "node-abort-controller": "^3.1.1",
- "semver": "^7.5.4",
- "tslib": "^2.0.0",
- "uuid": "^9.0.0"
- }
- },
- "node_modules/bullmq/node_modules/uuid": {
- "version": "9.0.1",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
- "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
- "funding": [
- "https://github.com/sponsors/broofa",
- "https://github.com/sponsors/ctavan"
- ],
- "bin": {
- "uuid": "dist/bin/uuid"
- }
- },
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
@@ -5862,17 +5700,6 @@
"luxon": "~3.4.0"
}
},
- "node_modules/cron-parser": {
- "version": "4.9.0",
- "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-4.9.0.tgz",
- "integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==",
- "dependencies": {
- "luxon": "^3.2.1"
- },
- "engines": {
- "node": ">=12.0.0"
- }
- },
"node_modules/cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
@@ -7878,6 +7705,7 @@
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/get-port/-/get-port-5.1.1.tgz",
"integrity": "sha512-g/Q1aTSDOxFpchXC4i8ZWvxA1lnPqx/JHqcpIw0/LX9T8x/GBbi6YnlN5nhaKIFkT8oFsscUKgDJYxfwfS6QsQ==",
+ "optional": true,
"engines": {
"node": ">=8"
},
@@ -10290,37 +10118,6 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT"
},
- "node_modules/msgpackr": {
- "version": "1.11.2",
- "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.11.2.tgz",
- "integrity": "sha512-F9UngXRlPyWCDEASDpTf6c9uNhGPTqnTeLVt7bN+bU1eajoR/8V9ys2BRaV5C/e5ihE6sJ9uPIKaYt6bFuO32g==",
- "license": "MIT",
- "optionalDependencies": {
- "msgpackr-extract": "^3.0.2"
- }
- },
- "node_modules/msgpackr-extract": {
- "version": "3.0.3",
- "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.3.tgz",
- "integrity": "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA==",
- "hasInstallScript": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "node-gyp-build-optional-packages": "5.2.2"
- },
- "bin": {
- "download-msgpackr-prebuilds": "bin/download-prebuilds.js"
- },
- "optionalDependencies": {
- "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3",
- "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3",
- "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3",
- "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3",
- "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3",
- "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3"
- }
- },
"node_modules/multer": {
"version": "1.4.4-lts.1",
"resolved": "https://registry.npmjs.org/multer/-/multer-1.4.4-lts.1.tgz",
@@ -10584,7 +10381,8 @@
"node_modules/node-abort-controller": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz",
- "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ=="
+ "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==",
+ "dev": true
},
"node_modules/node-addon-api": {
"version": "5.1.0",
@@ -10619,21 +10417,6 @@
}
}
},
- "node_modules/node-gyp-build-optional-packages": {
- "version": "5.2.2",
- "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz",
- "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "detect-libc": "^2.0.1"
- },
- "bin": {
- "node-gyp-build-optional-packages": "bin.js",
- "node-gyp-build-optional-packages-optional": "optional.js",
- "node-gyp-build-optional-packages-test": "build-test.js"
- }
- },
"node_modules/node-releases": {
"version": "2.0.18",
"resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.18.tgz",
diff --git a/backend/package.json b/backend/package.json
index 26f4803b8..18e366a1f 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -29,7 +29,6 @@
"@faker-js/faker": "^9.2.0",
"@nestjs-modules/mailer": "^2.0.2",
"@nestjs/axios": "^3.1.2",
- "@nestjs/bull": "^10.2.2",
"@nestjs/common": "^10.4.7",
"@nestjs/config": "^3.3.0",
"@nestjs/core": "^10.4.7",
@@ -52,8 +51,6 @@
"axios": "^1.7.7",
"bcrypt": "^5.1.1",
"body-parser": "^1.20.3",
- "bull": "^4.16.4",
- "bullmq": "^5.25.6",
"chalk": "^4.1.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
diff --git a/web/app/App.tsx b/web/app/App.tsx
index 68a130020..9ca511d26 100644
--- a/web/app/App.tsx
+++ b/web/app/App.tsx
@@ -93,7 +93,6 @@ const App = ({ ssrTheme, ssrAuthenticated }: AppProps) => {
!_endsWith(pathname, '/subscribers/invite') &&
!_endsWith(pathname, '/subscribers/invite') &&
!_includes(pathname, '/alerts/') &&
- !_includes(pathname, '/uptime/') &&
!_includes(pathname, '/settings/')
const routesWithOutHeader = [
diff --git a/web/app/api/index.ts b/web/app/api/index.ts
index 43eafbafb..730305e6b 100644
--- a/web/app/api/index.ts
+++ b/web/app/api/index.ts
@@ -9,14 +9,13 @@ import _isArray from 'lodash/isArray'
import { authActions } from '~/lib/reducers/auth'
import { getAccessToken, removeAccessToken, setAccessToken } from '~/utils/accessToken'
import { getRefreshToken, removeRefreshToken } from '~/utils/refreshToken'
-import { DEFAULT_ALERTS_TAKE, API_URL, DEFAULT_MONITORS_TAKE } from '~/lib/constants'
+import { DEFAULT_ALERTS_TAKE, API_URL } from '~/lib/constants'
import { User, FeatureFlag } from '~/lib/models/User'
import { Auth } from '~/lib/models/Auth'
import { Project, Overall, LiveStats, Funnel } from '~/lib/models/Project'
import { Alerts } from '~/lib/models/Alerts'
import { Subscriber } from '~/lib/models/Subscriber'
import { Filter, ProjectViewCustomEvent } from '~/pages/Project/View/interfaces/traffic'
-import { Monitor, MonitorOverall } from '~/lib/models/Uptime'
import { Role } from '~/lib/models/Organisation'
import { logout } from '~/utils/auth'
@@ -1094,105 +1093,6 @@ export const deleteAlert = (id: string) =>
throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
})
-export interface CreateMonitor extends Omit<Monitor, 'id' | 'createdAt' | 'updatedAt'> {}
-
-export const getProjectMonitors = (projectId: string, take: number = DEFAULT_MONITORS_TAKE, skip: number = 0) =>
- api
- .get(`project/${projectId}/monitors?take=${take}&skip=${skip}`)
- .then(
- (
- response,
- ): {
- results: Monitor[]
- total: number
- page_total: number
- } => response.data,
- )
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getProjectMonitor = (projectId: string, monitorId: string) =>
- api
- .get(`/project/${projectId}/monitor/${monitorId}`)
- .then((response): Monitor => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getMonitorOverallStats = (
- pid: string,
- monitorIds: string[],
- period: string,
- from = '',
- to = '',
- timezone = 'Etc/GMT',
- password?: string,
-) =>
- api
- .get(
- `log/monitor-data/birdseye?pid=${pid}&monitorIds=[${_map(monitorIds, (pid) => `"${pid}"`).join(
- ',',
- )}]&period=${period}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response): MonitorOverall => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const getMonitorStats = (
- pid: string,
- monitorId: string,
- period: string = '1d',
- timeBucket: string = 'hour',
- from: string = '',
- to: string = '',
- timezone: string = '',
- password: string | undefined = '',
-) =>
- api
- .get(
- `log/monitor-data?pid=${pid}&monitorId=${monitorId}&timeBucket=${timeBucket}&period=${period}&from=${from}&to=${to}&timezone=${timezone}`,
- {
- headers: {
- 'x-password': password,
- },
- },
- )
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const createMonitor = (pid: string, data: CreateMonitor) =>
- api
- .post(`project/${pid}/monitor`, data)
- .then((response): Monitor => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const updateMonitor = (pid: string, id: string, data: Partial<Monitor>) =>
- api
- .patch(`project/${pid}/monitor/${id}`, data)
- .then((response): Monitor => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
-export const deleteMonitor = (pid: string, id: string) =>
- api
- .delete(`project/${pid}/monitor/${id}`)
- .then((response) => response.data)
- .catch((error) => {
- throw _isEmpty(error.response.data?.message) ? error.response.data : error.response.data.message
- })
-
export const reGenerateCaptchaSecretKey = (pid: string) =>
api
.post(`project/secret-gen/${pid}`)
diff --git a/web/app/lib/constants/index.ts b/web/app/lib/constants/index.ts
index 25d94fd1a..347488bd4 100644
--- a/web/app/lib/constants/index.ts
+++ b/web/app/lib/constants/index.ts
@@ -196,7 +196,6 @@ export const FILTERS_PERIOD_PAIRS = ['1d', '7d', '4w', '3M', '12M', 'custom', 'c
export const ERROR_PERIOD_PAIRS = ['1h', '1d', '7d', '4w', '3M', '12M']
export const FUNNELS_PERIOD_PAIRS = ['1h', '1d', '7d', '4w', '3M', '12M', 'custom']
-export const UPTIME_PERIOD_PAIRS = ['1h', '1d', '7d', '4w', '3M', '12M', 'custom']
export const tbPeriodPairsCompare = (
t: Function,
@@ -447,7 +446,6 @@ const PRODUCTION_PROJECT_TABS = {
sessions: 'sessions',
errors: 'errors',
alerts: 'alerts',
- uptime: 'uptime',
} as const
export const PROJECT_TABS = (
@@ -481,7 +479,6 @@ export const INVITATION_EXPIRES_IN = 48 // hours
export const ENTRIES_PER_PAGE_DASHBOARD = 11
export const DEFAULT_ALERTS_TAKE = 100
-export const DEFAULT_MONITORS_TAKE = 100
const EUR = {
symbol: '€',
@@ -552,7 +549,6 @@ export const PLAN_LIMITS = {
},
},
maxAlerts: 0,
- maxMonitors: 0,
},
free: {
index: 0, // 'downgrade' or 'upgrade' logic depends on this
@@ -574,7 +570,6 @@ export const PLAN_LIMITS = {
},
},
maxAlerts: 1,
- maxMonitors: 1,
},
trial: {
index: 0, // 'downgrade' or 'upgrade' logic depends on this
@@ -596,7 +591,6 @@ export const PLAN_LIMITS = {
},
},
maxAlerts: 50,
- maxMonitors: 20,
},
hobby: {
index: 1, // 'downgrade' or 'upgrade' logic depends on this
@@ -620,7 +614,6 @@ export const PLAN_LIMITS = {
pid: 813694, // Plan ID
ypid: 813695, // Plan ID - Yearly billing
maxAlerts: 50,
- maxMonitors: 20,
},
freelancer: {
index: 2, // 'downgrade' or 'upgrade' logic depends on this
@@ -644,7 +637,6 @@ export const PLAN_LIMITS = {
pid: 752316, // Plan ID
ypid: 776469, // Plan ID - Yearly billing
maxAlerts: 50,
- maxMonitors: 20,
},
'200k': {
index: 3, // 'downgrade' or 'upgrade' logic depends on this
@@ -668,7 +660,6 @@ export const PLAN_LIMITS = {
pid: 854654, // Plan ID
ypid: 854655, // Plan ID - Yearly billing
maxAlerts: 50,
- maxMonitors: 20,
},
'500k': {
index: 4, // 'downgrade' or 'upgrade' logic depends on this
@@ -692,7 +683,6 @@ export const PLAN_LIMITS = {
pid: 854656, // Plan ID
ypid: 854657, // Plan ID - Yearly billing
maxAlerts: 50,
- maxMonitors: 20,
},
startup: {
index: 5, // 'downgrade' or 'upgrade' logic depends on this
@@ -716,7 +706,6 @@ export const PLAN_LIMITS = {
pid: 752317,
ypid: 776470,
maxAlerts: 50,
- maxMonitors: 20,
},
'2m': {
index: 6, // 'downgrade' or 'upgrade' logic depends on this
@@ -740,7 +729,6 @@ export const PLAN_LIMITS = {
pid: 854663,
ypid: 854664,
maxAlerts: 50,
- maxMonitors: 20,
},
enterprise: {
index: 7, // 'downgrade' or 'upgrade' logic depends on this
@@ -764,7 +752,6 @@ export const PLAN_LIMITS = {
pid: 752318,
ypid: 776471,
maxAlerts: 50,
- maxMonitors: 20,
},
'10m': {
index: 8, // 'downgrade' or 'upgrade' logic depends on this
@@ -788,7 +775,6 @@ export const PLAN_LIMITS = {
pid: 854665,
ypid: 854666,
maxAlerts: 50,
- maxMonitors: 20,
},
}
diff --git a/web/app/lib/models/Uptime.ts b/web/app/lib/models/Uptime.ts
deleted file mode 100644
index 11a99acbe..000000000
--- a/web/app/lib/models/Uptime.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-export interface Monitor {
- id: string
- type: string
- name: string
- url: string
- interval: number
- retries: number
- retryInterval: number
- timeout: number
- acceptedStatusCodes: number[]
- description: string | null
- projectId: string
- createdAt: Date
- updatedAt: Date
- httpOptions: {
- method: string[]
- body?: Record<string, unknown>
- headers?: Record<string, string>
- }
-}
-
-interface MonitorOverallPeriodStats {
- avg: number
- min: number
- max: number
-}
-
-export interface MonitorOverallObject {
- current: MonitorOverallPeriodStats
- previous: MonitorOverallPeriodStats
- avgChange: number
- minChange: number
- maxChange: number
-}
-
-export interface MonitorOverall {
- [key: string]: MonitorOverallObject
-}
diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsx
index 8224ce790..97b82ac7d 100644
--- a/web/app/pages/Project/View/ViewProject.helpers.tsx
+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx
@@ -1167,131 +1167,6 @@ const getSettingsFunnels = (funnel: AnalyticsFunnel[], totalPageviews: number, t
}
}
-const getSettingsUptime = (
- chart: any,
- timeBucket: string,
- timeFormat: string,
- rotateXAxis: boolean,
- chartType: string,
-): ChartOptions => {
- const xAxisSize = _size(chart.x)
-
- const columns = getColumns(chart, { avgResponseTime: true }, {})
-
- let regionStart
-
- if (xAxisSize > 1) {
- regionStart = dayjs(chart.x[xAxisSize - 2]).toDate()
- } else {
- regionStart = dayjs(chart.x[xAxisSize - 1]).toDate()
- }
-
- return {
- data: {
- x: 'x',
- columns,
- types: {
- avgResponseTime: chartType === chartTypes.line ? area() : bar(),
- },
- colors: {
- avgResponseTime: '#709775',
- },
- regions: {
- avgResponseTime: [
- {
- // @ts-expect-error
- start: regionStart,
- style: {
- dasharray: '6 2',
- },
- },
- ],
- },
- },
- transition: {
- duration: 500,
- },
- resize: {
- auto: true,
- timer: false,
- },
- axis: {
- x: {
- clipPath: false,
- tick: {
- fit: true,
- rotate: rotateXAxis ? 45 : 0,
- // @ts-expect-error
- format:
- timeFormat === TimeFormat['24-hour']
- ? (x: string) => d3.timeFormat(tbsFormatMapper24h[timeBucket])(x)
- : (x: string) => d3.timeFormat(tbsFormatMapper[timeBucket])(x),
- },
- localtime: timeFormat === TimeFormat['24-hour'],
- type: 'timeseries',
- },
- y: {
- tick: {
- // @ts-expect-error
- format: (d: string) => getStringFromTime(getTimeFromSeconds(d), true),
- },
- show: true,
- inner: true,
- },
- },
- tooltip: {
- contents: (item: any, _: any, __: any, color: any) => {
- return `<ul class='bg-gray-50 dark:text-gray-50 dark:bg-slate-800 rounded-md ring-1 ring-black/10 px-3 py-1'>
- <li class='font-semibold'>${
- timeFormat === TimeFormat['24-hour']
- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(item[0].x)
- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(item[0].x)
- }</li>
- <hr class='border-gray-200 dark:border-gray-600' />
- ${_map(
- item,
- (el: { id: string; index: number; name: string; value: string; x: Date }) => `
- <li class='flex justify-between'>
- <div class='flex justify-items-start'>
- <div class='w-3 h-3 rounded-xs mt-1.5 mr-2' style=background-color:${color(el.id)}></div>
- <span>${el.name}</span>
- </div>
- <span class='pl-4'>${getStringFromTime(getTimeFromSeconds(el.value), true)}</span>
- </li>
- `,
- ).join('')}`
- },
- },
- point:
- chartType === chartTypes.bar
- ? {}
- : {
- focus: {
- only: xAxisSize > 1,
- },
- pattern: ['circle'],
- r: 2,
- },
- legend: {
- item: {
- tile: {
- type: 'circle',
- width: 10,
- r: 3,
- },
- },
- hide: ['uniqueCompare', 'totalCompare', 'bounceCompare', 'sessionDurationCompare'],
- },
- area: {
- linearGradient: true,
- },
- bar: {
- linearGradient: true,
- },
- bindto: '#avgResponseUptimeChart',
- }
-}
-
const perfomanceChartCompare = [
'dnsCompare',
'tlsCompare',
@@ -1625,5 +1500,4 @@ export {
SHORTCUTS_TIMEBUCKETS_LISTENERS,
CHART_MEASURES_MAPPING_PERF,
getSettingsError,
- getSettingsUptime,
}
diff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsx
index 2e456f228..ba4a35dda 100644
--- a/web/app/pages/Project/View/ViewProject.tsx
+++ b/web/app/pages/Project/View/ViewProject.tsx
@@ -14,7 +14,7 @@ import { ClientOnly } from 'remix-utils/client-only'
import useSize from '~/hooks/useSize'
import { useNavigate, Link, useSearchParams, useLoaderData } from '@remix-run/react'
import bb from 'billboard.js'
-import { MagnifyingGlassIcon, ChevronLeftIcon, GlobeAltIcon, ClockIcon } from '@heroicons/react/24/outline'
+import { MagnifyingGlassIcon, ChevronLeftIcon, GlobeAltIcon } from '@heroicons/react/24/outline'
import {
BugIcon,
GaugeIcon,
@@ -161,7 +161,6 @@ import LiveVisitorsDropdown from './components/LiveVisitorsDropdown'
import CountryDropdown from './components/CountryDropdown'
import { MetricCard, MetricCards, PerformanceMetricCards } from './components/MetricCards'
import ProjectAlertsView from '../Alerts/View'
-import Uptime from '../uptime/View'
import UTMDropdown from './components/UTMDropdown'
import TBPeriodSelector from './components/TBPeriodSelector'
import { Session } from './interfaces/session'
@@ -881,11 +880,6 @@ const ViewProject = () => {
label: t('dashboard.alerts'),
icon: BellRingIcon,
},
- ['79eF2Z9rNNvv', 'STEzHcB1rALV'].includes(id) && {
- id: PROJECT_TABS.uptime,
- label: t('dashboard.uptime'),
- icon: ClockIcon,
- },
...adminTabs,
].filter((x) => !!x)
@@ -2956,7 +2950,7 @@ const ViewProject = () => {
)
}
- if (!project.isDataExists && !_includes([PROJECT_TABS.errors, PROJECT_TABS.uptime], activeTab) && !analyticsLoading) {
+ if (!project.isDataExists && activeTab !== PROJECT_TABS.errors && !analyticsLoading) {
return (
<>
{!embedded && <Header ssrTheme={ssrTheme} authenticated={authenticated} />}
@@ -3063,7 +3057,6 @@ const ViewProject = () => {
>
<TabsSelector />
{activeTab !== PROJECT_TABS.alerts &&
- activeTab !== PROJECT_TABS.uptime &&
(activeTab !== PROJECT_TABS.sessions || !activePSID) &&
(activeFunnel || activeTab !== PROJECT_TABS.funnels) && (
<>
@@ -4052,7 +4045,6 @@ const ViewProject = () => {
{activeTab === PROJECT_TABS.alerts && project.role === 'owner' && authenticated && (
<ProjectAlertsView projectId={id} />
)}
- {activeTab === PROJECT_TABS.uptime && <Uptime />}
{analyticsLoading && (activeTab === PROJECT_TABS.traffic || activeTab === PROJECT_TABS.performance) && (
<Loader />
)}
diff --git a/web/app/pages/Project/View/components/MetricCards.tsx b/web/app/pages/Project/View/components/MetricCards.tsx
index fb61c54b6..008d24070 100644
--- a/web/app/pages/Project/View/components/MetricCards.tsx
+++ b/web/app/pages/Project/View/components/MetricCards.tsx
@@ -10,7 +10,6 @@ import { nFormatter, getStringFromTime, getTimeFromSeconds } from '~/utils/gener
import { OverallObject, OverallPerformanceObject } from '~/lib/models/Project'
import { ChevronDownIcon, ChevronUpIcon, XMarkIcon } from '@heroicons/react/24/outline'
import { Badge } from '~/ui/Badge'
-import { MonitorOverallObject } from '~/lib/models/Uptime'
interface MetricCardProps {
label: string
@@ -228,46 +227,6 @@ export const MetricCards = memo(({ overall, overallCompare, activePeriodCompare
)
})
-interface MetricCardsUptimeProps {
- overall: MonitorOverallObject
-}
-
-export const MetricCardsUptime = memo(({ overall }: MetricCardsUptimeProps) => {
- const { t } = useTranslation()
-
- return (
- <>
- <MetricCard
- label={t('monitor.metrics.avg')}
- value={overall.current.avg}
- change={overall.avgChange}
- goodChangeDirection='up'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
- }
- />
- <MetricCard
- label={t('monitor.metrics.min')}
- value={overall.current.min}
- change={overall.minChange}
- goodChangeDirection='up'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
- }
- />
- <MetricCard
- label={t('monitor.metrics.max')}
- value={overall.current.max}
- change={overall.maxChange}
- goodChangeDirection='up'
- valueMapper={(value, type) =>
- `${type === 'badge' && value > 0 ? '+' : ''}${getStringFromTime(getTimeFromSeconds(value), true)}`
- }
- />
- </>
- )
-})
-
interface PerformanceMetricCardsProps {
overall: Partial<OverallPerformanceObject>
overallCompare?: Partial<OverallPerformanceObject>
@@ -326,5 +285,4 @@ export const PerformanceMetricCards = memo(
)
MetricCards.displayName = 'MetricCards'
-MetricCardsUptime.displayName = 'MetricCardsUptime'
PerformanceMetricCards.displayName = 'PerformanceMetricCards'
diff --git a/web/app/pages/Project/uptime/Settings.tsx b/web/app/pages/Project/uptime/Settings.tsx
deleted file mode 100644
index 91046233f..000000000
--- a/web/app/pages/Project/uptime/Settings.tsx
+++ /dev/null
@@ -1,528 +0,0 @@
-import React, { ChangeEvent, ChangeEventHandler, useEffect, useId, useState } from 'react'
-import { Link, useNavigate } from '@remix-run/react'
-import { useTranslation } from 'react-i18next'
-import { ExclamationTriangleIcon, XCircleIcon } from '@heroicons/react/24/outline'
-
-import _isEmpty from 'lodash/isEmpty'
-import _size from 'lodash/size'
-import _join from 'lodash/join'
-import _split from 'lodash/split'
-import _includes from 'lodash/includes'
-import _isNaN from 'lodash/isNaN'
-import _map from 'lodash/map'
-import _keys from 'lodash/keys'
-import { clsx as cx } from 'clsx'
-import Input from '~/ui/Input'
-import Button from '~/ui/Button'
-import Modal from '~/ui/Modal'
-import { PROJECT_TABS } from '~/lib/constants'
-import { createMonitor, updateMonitor, deleteMonitor, CreateMonitor, getProjectMonitor } from '~/api'
-import { withAuthentication, auth } from '~/hoc/protected'
-import routes from '~/utils/routes'
-import { Monitor } from '~/lib/models/Uptime'
-import { useSelector } from 'react-redux'
-import { toast } from 'sonner'
-import { StateType } from '~/lib/store'
-import { useRequiredParams } from '~/hooks/useRequiredParams'
-import Select from '~/ui/Select'
-import { formatTime } from '~/utils/date'
-import { isValidUrl } from '~/utils/validator'
-import Loader from '~/ui/Loader'
-
-const MONITOR_TYPES = ['HTTP']
-
-const INTERVALS_IN_SECONDS = [
- 30, // 30 seconds
- 60, // 1 minute
- 120, // 2 minutes
- 180, // 3 minutes
- 300, // 5 minutes
- 600, // 10 minutes
- 900, // 15 minutes
- 1200, // 20 minutes
- 1800, // 30 minutes
- 2700, // 45 minutes
- 3600, // 1 hour
- 7200, // 2 hours
- 10800, // 3 hours
- 21600, // 6 hours
- 43200, // 12 hours
- 57600, // 16 hours
- 72000, // 20 hours
- 86400, // 24 hours
-]
-
-const INTERVALS_ALLOWED_DATALIST = [30, 60, 300, 1800, 3600, 21600, 86400]
-
-const getIntervalDisplayName = (interval: number, language: string, style: Intl.RelativeTimeFormatStyle = 'short') => {
- let displayName
-
- if (interval < 60) {
- displayName = formatTime(interval, 'second', language, style)
- } else if (interval < 3600) {
- displayName = formatTime(interval / 60, 'minute', language, style)
- } else {
- displayName = formatTime(interval / 3600, 'hour', language, style)
- }
-
- return displayName
-}
-
-interface IntervalSelectorProps {
- value?: number
- onChange: ChangeEventHandler<HTMLInputElement>
- label: string
- hint: string
- name: string
-}
-
-const IntervalSelector = ({ value, onChange, label, hint, name }: IntervalSelectorProps) => {
- const id = useId()
- const {
- i18n: { language },
- } = useTranslation('common')
-
- const handleChange = (ev: ChangeEvent<HTMLInputElement>) => {
- const { value, name } = ev.target
-
- onChange({
- target: {
- name,
- // @ts-expect-error
- value: INTERVALS_IN_SECONDS[Number(value)],
- },
- })
- }
-
- return (
- <div className='mt-4'>
- <Input
- list={id}
- name={name}
- label={label}
- hint={hint}
- hintPosition='top'
- type='range'
- min='0'
- max={INTERVALS_IN_SECONDS.length - 1}
- value={value ? INTERVALS_IN_SECONDS.indexOf(Number(value)) : 4}
- classes={{
- input: 'arrows-handle mt-4 h-2 w-full rounded-full bg-gray-200 dark:bg-slate-600',
- }}
- onChange={handleChange}
- />
- <datalist
- style={{
- writingMode: 'vertical-lr',
- }}
- className='flex w-full flex-col justify-between'
- id={id}
- >
- {_map(INTERVALS_IN_SECONDS, (interval, index) => {
- if (!_includes(INTERVALS_ALLOWED_DATALIST, interval)) {
- return <option key={interval} value={index} />
- }
-
- const displayName = getIntervalDisplayName(interval, language)
-
- return (
- <option
- className='mt-4 text-sm text-gray-700 lg:mt-0 lg:-rotate-90 lg:text-center dark:text-gray-200'
- key={interval}
- value={index}
- label={displayName}
- />
- )
- })}
- </datalist>
- </div>
- )
-}
-
-const MAX_RETRIES = 100
-
-interface UptimeSettingsProps {
- isSettings?: boolean
-}
-
-const UptimeSettings = ({ isSettings }: UptimeSettingsProps) => {
- const { loading: authLoading } = useSelector((state: StateType) => state.auth)
-
- const navigate = useNavigate()
- const { id, pid } = useRequiredParams<{ id: string; pid: string }>()
- const {
- t,
- i18n: { language },
- } = useTranslation('common')
- const [form, setForm] = useState<
- Partial<Omit<Monitor, 'acceptedStatusCodes'>> & {
- acceptedStatusCodes: string
- }
- >({
- type: 'HTTP',
- projectId: pid,
- name: '',
- url: '',
- interval: 60,
- retries: 3,
- retryInterval: 60,
- timeout: 30,
- acceptedStatusCodes: '200',
- description: '',
- })
- const [validated, setValidated] = useState(false)
- const [errors, setErrors] = useState<{
- [key: string]: string
- }>({})
- const [beenSubmitted, setBeenSubmitted] = useState(false)
- const [showModal, setShowModal] = useState(false)
-
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [error, setError] = useState<string | null>(null)
-
- const loadMonitor = async (projectId: string, monitorId: string) => {
- if (!isSettings) {
- setIsLoading(false)
- return
- }
-
- if (isLoading) {
- return
- }
-
- setIsLoading(true)
-
- try {
- const result = await getProjectMonitor(projectId, monitorId)
- setForm({
- ...result,
- acceptedStatusCodes: _join(result.acceptedStatusCodes, ','),
- })
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
- }
-
- useEffect(() => {
- if (authLoading) {
- return
- }
-
- loadMonitor(pid, id)
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [authLoading, pid, id])
-
- const validate = () => {
- const allErrors: {
- [key: string]: string
- } = {}
-
- if (_isEmpty(form.name) || _size(form.name) < 3) {
- allErrors.name = t('alert.noNameError')
- }
-
- if (_isEmpty(form.url)) {
- allErrors.url = t('apiNotifications.inputCannotBeEmpty')
- }
-
- if (!isValidUrl(form.url!)) {
- allErrors.url = t('monitor.error.urlInvalid')
- }
-
- const retries = Number(form.retries)
-
- if (_isNaN(retries)) {
- allErrors.retries = t('apiNotifications.enterACorrectNumber')
- }
-
- if (retries <= 0) {
- allErrors.retries = t('apiNotifications.numberCantBeNegative')
- }
-
- if (retries > MAX_RETRIES) {
- allErrors.retries = t('apiNotifications.numberCantBeBigger', {
- max: MAX_RETRIES,
- })
- }
-
- const acceptedStatusCodes = _split(form.acceptedStatusCodes, ',')
-
- if (_isEmpty(acceptedStatusCodes)) {
- allErrors.acceptedStatusCodes = t('apiNotifications.inputCannotBeEmpty')
- }
-
- if (
- acceptedStatusCodes.some((statusCode) => {
- const trimmedStatusCode = Number(statusCode.trim())
- return _isNaN(trimmedStatusCode) || trimmedStatusCode < 100 || trimmedStatusCode > 599
- })
- ) {
- allErrors.acceptedStatusCodes = t('monitor.error.acceptedStatusCodesNotValid')
- }
-
- const valid = _isEmpty(_keys(allErrors))
-
- setErrors(allErrors)
- setValidated(valid)
- }
-
- const onSubmit = (data: Partial<Monitor>) => {
- if (isSettings) {
- updateMonitor(pid, id, data)
- .then((res) => {
- navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)
- toast.success(t('monitor.monitorUpdated'))
- })
- .catch((err) => {
- toast.error(err.message || err || 'Something went wrong')
- })
- } else {
- createMonitor(pid, data as CreateMonitor)
- .then((res) => {
- navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)
- toast.success(t('monitor.monitorCreated'))
- })
- .catch((err) => {
- toast.error(err.message || err || 'Something went wrong')
- })
- }
- }
-
- const onDelete = () => {
- if (!id) {
- toast.error('Something went wrong')
- return
- }
-
- deleteMonitor(pid, id)
- .then(() => {
- navigate(`/projects/${pid}?tab=${PROJECT_TABS.uptime}`)
- toast.success(t('monitor.monitorDeleted'))
- })
- .catch((err) => {
- toast.error(err.message || err || 'Something went wrong')
- })
- }
-
- useEffect(() => {
- validate()
- }, [form]) // eslint-disable-line
-
- const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
- const { target } = event
-
- setForm((prevForm) => ({
- ...prevForm,
- [target.name]: target.value,
- }))
- }
-
- const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
- e.preventDefault()
- e.stopPropagation()
- setBeenSubmitted(true)
-
- if (validated) {
- onSubmit({
- ...form,
- acceptedStatusCodes: _map(_split(form.acceptedStatusCodes, ','), (code) => parseInt(code, 10)),
- })
- }
- }
-
- const title = isSettings
- ? t('monitor.settingsOf', {
- name: form.name,
- })
- : t('monitor.create')
-
- if (isLoading || isLoading === null) {
- return (
- <div className='min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900'>
- <Loader />
- </div>
- )
- }
-
- if (error && !isLoading) {
- return (
- <div className='min-h-page bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>
- <div className='mx-auto max-w-max'>
- <main className='sm:flex'>
- <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
- <div className='sm:ml-6'>
- <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
- <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 sm:text-5xl dark:text-gray-50'>
- {t('apiNotifications.somethingWentWrong')}
- </h1>
- <p className='mt-4 text-2xl font-medium tracking-tight text-gray-700 dark:text-gray-200'>
- {t('apiNotifications.errorCode', { error })}
- </p>
- </div>
- <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
- <button
- type='button'
- onClick={() => window.location.reload()}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'
- >
- {t('dashboard.reloadPage')}
- </button>
- <Link
- to={routes.contact}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
- >
- {t('notFoundPage.support')}
- </Link>
- </div>
- </div>
- </main>
- </div>
- </div>
- )
- }
-
- return (
- <div
- className={cx('min-h-min-footer flex flex-col bg-gray-50 px-4 py-6 sm:px-6 lg:px-8 dark:bg-slate-900', {
- 'pb-40': isSettings,
- })}
- >
- <form className='mx-auto w-full max-w-7xl' onSubmit={handleSubmit}>
- <h2 className='mt-2 text-3xl font-bold text-gray-900 dark:text-gray-50'>{title}</h2>
- <Input
- name='name'
- label={t('monitor.form.name')}
- value={form.name || ''}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.name : null}
- />
- <div className='mt-4'>
- <Select
- id='type'
- label={t('monitor.form.type')}
- items={MONITOR_TYPES}
- title={form.type}
- onSelect={(item) => {
- setForm((prev) => ({
- ...prev,
- type: item,
- }))
- }}
- capitalise
- />
- </div>
- <Input
- name='url'
- label={t('monitor.form.url')}
- value={form.url || ''}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.url : null}
- />
- <IntervalSelector
- name='interval'
- label={t('monitor.form.interval')}
- hint={t('monitor.form.intervalHint', {
- intervalTranslated: getIntervalDisplayName(Number(form.interval), language, 'long'),
- })}
- value={form.interval}
- onChange={handleInput}
- />
- <Input
- name='retries'
- label={t('monitor.form.retries')}
- hint={t('monitor.form.retriesHint', { retries: form.retries || 'N/A' })}
- value={form.retries}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.retries : null}
- />
- <IntervalSelector
- name='retryInterval'
- label={t('monitor.form.retryInterval')}
- hint={t('monitor.form.retryIntervalHint', {
- retryIntervalTranslated: getIntervalDisplayName(Number(form.retryInterval), language, 'long'),
- })}
- value={form.retryInterval}
- onChange={handleInput}
- />
- <Input
- name='timeout'
- label={t('monitor.form.timeout')}
- hint={t('monitor.form.timeoutHint', { x: form.timeout || 'N/A' })}
- value={form.timeout || ''}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.timeout : null}
- />
- <Input
- name='acceptedStatusCodes'
- label={t('monitor.form.acceptedStatusCodes')}
- value={form.acceptedStatusCodes || ''}
- className='mt-4'
- onChange={handleInput}
- error={beenSubmitted ? errors.acceptedStatusCodes : null}
- />
-
- {isSettings ? (
- <div className='mt-5 flex items-center justify-between'>
- <Button onClick={() => setShowModal(true)} danger semiSmall>
- <>
- <ExclamationTriangleIcon className='mr-1 h-5 w-5' />
- {t('monitor.delete')}
- </>
- </Button>
- <div className='flex items-center justify-between'>
- <Button
- className='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- as={Link}
- // @ts-expect-error
- to={`/projects/${pid}?tab=${PROJECT_TABS.uptime}`}
- secondary
- regular
- >
- {t('common.cancel')}
- </Button>
- <Button type='submit' primary regular>
- {t('common.save')}
- </Button>
- </div>
- </div>
- ) : (
- <div className='mt-5 flex items-center justify-between'>
- <Button
- className='mr-2 border-indigo-100 dark:border-slate-700/50 dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700'
- as={Link}
- // @ts-expect-error
- to={`/projects/${pid}?tab=${PROJECT_TABS.uptime}`}
- secondary
- regular
- >
- {t('common.cancel')}
- </Button>
- <Button type='submit' primary regular>
- {t('common.save')}
- </Button>
- </div>
- )}
- </form>
- <Modal
- onClose={() => setShowModal(false)}
- onSubmit={onDelete}
- submitText={t('monitor.delete')}
- closeText={t('common.close')}
- title={t('monitor.qDelete')}
- message={t('monitor.deleteHint')}
- submitType='danger'
- type='error'
- isOpened={showModal}
- />
- </div>
- )
-}
-
-export default withAuthentication(UptimeSettings, auth.authenticated)
diff --git a/web/app/pages/Project/uptime/View.tsx b/web/app/pages/Project/uptime/View.tsx
deleted file mode 100644
index 96fff06b7..000000000
--- a/web/app/pages/Project/uptime/View.tsx
+++ /dev/null
@@ -1,505 +0,0 @@
-import React, { useCallback, useEffect, useMemo, useState } from 'react'
-import bb from 'billboard.js'
-import cx from 'clsx'
-import _map from 'lodash/map'
-import _isEmpty from 'lodash/isEmpty'
-import _includes from 'lodash/includes'
-import _replace from 'lodash/replace'
-import _filter from 'lodash/filter'
-import { Link, useNavigate } from '@remix-run/react'
-import { useTranslation } from 'react-i18next'
-import { useSelector } from 'react-redux'
-import {
- CurrencyDollarIcon,
- AdjustmentsVerticalIcon,
- PlusCircleIcon,
- ClockIcon,
- ChevronLeftIcon,
- XCircleIcon,
-} from '@heroicons/react/24/outline'
-import { toast } from 'sonner'
-
-import routes from '~/utils/routes'
-import Button from '~/ui/Button'
-import Modal from '~/ui/Modal'
-import PaidFeature from '~/modals/PaidFeature'
-import { DEFAULT_MONITORS_TAKE, PLAN_LIMITS, tbPeriodPairs, UPTIME_PERIOD_PAIRS } from '~/lib/constants'
-import { deleteMonitor as deleteMonitorApi, getMonitorOverallStats, getMonitorStats, getProjectMonitors } from '~/api'
-import { StateType } from '~/lib/store'
-import { Monitor, MonitorOverallObject } from '~/lib/models/Uptime'
-import { useViewProjectContext } from '../View/ViewProject'
-import { getFormatDate, getSettingsUptime } from '../View/ViewProject.helpers'
-import TBPeriodSelector from '../View/components/TBPeriodSelector'
-import { MetricCardsUptime } from '../View/components/MetricCards'
-import NoMonitorEvents from './components/NoMonitorDetails'
-import Loader from '~/ui/Loader'
-import Pagination from '~/ui/Pagination'
-import { RotateCw, Trash2Icon } from 'lucide-react'
-
-interface MonitorCardProps {
- monitor: Monitor
- deleteMonitor: (id: string) => void
- onClick: (monitor: Monitor) => void
- allowedToManage: boolean
-}
-
-const MonitorCard = ({ monitor, deleteMonitor, onClick, allowedToManage }: MonitorCardProps) => {
- const { t } = useTranslation()
- const [showDeleteModal, setShowDeleteModal] = useState(false)
-
- return (
- <>
- <div onClick={() => onClick(monitor)} role='button' tabIndex={0}>
- <li className='min-h-[120px] cursor-pointer overflow-hidden rounded-xl border border-gray-200 bg-gray-50 hover:bg-gray-100 dark:border-slate-800/25 dark:bg-[#162032] dark:hover:bg-slate-800'>
- <div className='px-4 py-4'>
- <div className='flex justify-between'>
- <div>
- <p className='flex items-center gap-x-2 text-lg text-slate-900 dark:text-gray-50'>
- <span className='font-semibold'>{monitor.name}</span>
- {/* <Separator />
- <span>{queryMetric}</span> */}
- </p>
- </div>
- {allowedToManage && (
- <div className='flex gap-2'>
- <Link
- to={_replace(_replace(routes.uptime_settings, ':pid', monitor.projectId), ':id', monitor.id)}
- onClick={(e) => {
- e.stopPropagation()
- }}
- >
- <AdjustmentsVerticalIcon
- role='button'
- aria-label={t('common.settings')}
- className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500'
- />
- </Link>
- <Trash2Icon
- onClick={(e) => {
- e.stopPropagation()
- setShowDeleteModal(true)
- }}
- role='button'
- aria-label={t('common.delete')}
- className='h-6 w-6 text-gray-800 hover:text-gray-900 dark:text-slate-400 dark:hover:text-slate-500'
- strokeWidth={1.5}
- />
- </div>
- )}
- </div>
- </div>
- </li>
- </div>
- <Modal
- onClose={() => setShowDeleteModal(false)}
- onSubmit={() => deleteMonitor(monitor.id)}
- submitText={t('monitor.delete')}
- closeText={t('common.close')}
- title={t('monitor.qDelete')}
- message={t('monitor.deleteHint')}
- submitType='danger'
- type='error'
- isOpened={showDeleteModal}
- />
- </>
- )
-}
-
-interface AddMonitorProps {
- handleNewMonitor: () => void
- isLimitReached: boolean
-}
-
-const AddMonitor = ({ handleNewMonitor, isLimitReached }: AddMonitorProps) => {
- const { t } = useTranslation()
-
- return (
- <li
- onClick={handleNewMonitor}
- className='group flex h-auto min-h-[120px] cursor-pointer items-center justify-center rounded-lg border-2 border-dashed border-gray-300 hover:border-gray-400 dark:border-gray-500 dark:hover:border-gray-600'
- >
- <div>
- {isLimitReached ? (
- <CurrencyDollarIcon className='mx-auto h-12 w-12 text-gray-400 group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
- ) : (
- <PlusCircleIcon className='mx-auto h-12 w-12 text-gray-400 group-hover:text-gray-500 dark:text-gray-200 group-hover:dark:text-gray-400' />
- )}
- <span className='mt-2 block text-sm font-semibold text-gray-900 dark:text-gray-50 group-hover:dark:text-gray-400'>
- {t('monitor.create')}
- </span>
- </div>
- </li>
- )
-}
-
-const Uptime = () => {
- const {
- projectId,
- isLoading: isProjectLoading,
- dateRange,
- timeBucket,
- period,
- timezone,
- projectPassword,
- refCalendar,
- setDateRange,
- updatePeriod,
- setPeriodPairs,
- activePeriod,
- periodPairs,
- size,
- timeFormat,
- allowedToManage,
- } = useViewProjectContext()
- const {
- t,
- i18n: { language },
- } = useTranslation()
- const { user, authenticated } = useSelector((state: StateType) => state.auth)
- const [isPaidFeatureOpened, setIsPaidFeatureOpened] = useState(false)
- const [activeMonitor, setActiveMonitor] = useState<{
- monitor: Monitor
- overall?: MonitorOverallObject
- isFailed?: boolean
- } | null>(null)
- const [isMonitorLoading, setIsMonitorLoading] = useState(false)
- const navigate = useNavigate()
-
- const rotateXAxis = useMemo(() => size.width > 0 && size.width < 500, [size])
-
- const [isLoading, setIsLoading] = useState<boolean | null>(null)
- const [total, setTotal] = useState(0)
- const [monitors, setMonitors] = useState<Monitor[]>([])
- const [page, setPage] = useState(1)
- const [error, setError] = useState<string | null>(null)
-
- const limits = PLAN_LIMITS[user?.planCode] || PLAN_LIMITS.trial
- const isLimitReached = authenticated && total >= limits?.maxMonitors
-
- const pageAmount = Math.ceil(total / DEFAULT_MONITORS_TAKE)
-
- const loadMonitors = async (take: number, skip: number, search?: string) => {
- if (isLoading) {
- return
- }
- setIsLoading(true)
-
- try {
- const result = await getProjectMonitors(projectId, take, skip)
- setMonitors(result.results)
- setTotal(result.total)
- } catch (reason: any) {
- setError(reason)
- } finally {
- setIsLoading(false)
- }
- }
-
- useEffect(() => {
- loadMonitors(DEFAULT_MONITORS_TAKE, (page - 1) * DEFAULT_MONITORS_TAKE)
-
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [page])
-
- const handleNewMonitor = () => {
- if (isLimitReached) {
- setIsPaidFeatureOpened(true)
- return
- }
-
- navigate(_replace(routes.create_uptime, ':pid', projectId))
- }
-
- const allowedPeriodPairs = useMemo(
- () => _filter(periodPairs, (el) => _includes(UPTIME_PERIOD_PAIRS, el.period)),
- [periodPairs],
- )
-
- const onDelete = async (id: string) => {
- try {
- await deleteMonitorApi(projectId, id)
- toast.success(t('monitor.monitorDeleted'))
- } catch (reason: any) {
- toast.error(reason?.response?.data?.message || reason?.message || 'Something went wrong')
- }
- }
-
- const bbDataNames = useMemo(
- () => ({
- avgResponseTime: t('monitor.metrics.avg'),
- }),
- [t],
- )
-
- const loadMonitorData = useCallback(
- async (monitor: Monitor) => {
- if (isMonitorLoading || !projectId || isProjectLoading) {
- return
- }
-
- setIsMonitorLoading(true)
-
- try {
- let overallStats
- let monitorStats
- let from
- let to
-
- if (dateRange) {
- from = getFormatDate(dateRange[0])
- to = getFormatDate(dateRange[1])
- }
-
- if (period === 'custom' && dateRange) {
- // eslint-disable-next-line no-extra-semi, @typescript-eslint/no-extra-semi
- ;[overallStats, monitorStats] = await Promise.all([
- getMonitorOverallStats(projectId, [monitor.id], period, from, to, timezone, projectPassword),
- getMonitorStats(projectId, monitor.id, period, timeBucket, from, to, timezone, projectPassword),
- ])
- } else {
- // eslint-disable-next-line no-extra-semi, @typescript-eslint/no-extra-semi
- ;[overallStats, monitorStats] = await Promise.all([
- getMonitorOverallStats(projectId, [monitor.id], period, '', '', timezone, projectPassword),
- getMonitorStats(projectId, monitor.id, period, timeBucket, '', '', timezone, projectPassword),
- ])
- }
-
- setActiveMonitor({
- monitor,
- overall: overallStats[monitor.id],
- isFailed: false,
- })
-
- const { chart } = monitorStats
-
- setTimeout(() => {
- // todo: chart type
- const bbSettings = getSettingsUptime(chart, timeBucket, timeFormat, rotateXAxis, 'line')
-
- const generate = bb.generate(bbSettings)
- generate.data.names(bbDataNames)
- }, 100)
-
- setIsMonitorLoading(false)
- } catch (reason) {
- setActiveMonitor({
- monitor,
- isFailed: true,
- })
- setIsMonitorLoading(false)
-
- console.error('[ERROR](loadMonitorData) Loading monitor data failed')
- console.error(reason)
- }
- },
- [
- projectPassword,
- timezone,
- period,
- dateRange,
- isProjectLoading,
- isMonitorLoading,
- projectId,
- timeBucket,
- rotateXAxis,
- bbDataNames,
- timeFormat,
- ],
- )
-
- useEffect(() => {
- if (activeMonitor) {
- loadMonitorData(activeMonitor.monitor)
- }
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [period, dateRange, timeBucket])
-
- if (error && isLoading === false) {
- return (
- <div className='bg-gray-50 px-4 py-16 sm:px-6 sm:py-24 md:grid md:place-items-center lg:px-8 dark:bg-slate-900'>
- <div className='mx-auto max-w-max'>
- <main className='sm:flex'>
- <XCircleIcon className='h-12 w-12 text-red-400' aria-hidden='true' />
- <div className='sm:ml-6'>
- <div className='max-w-prose sm:border-l sm:border-gray-200 sm:pl-6'>
- <h1 className='text-4xl font-extrabold tracking-tight text-gray-900 sm:text-5xl dark:text-gray-50'>
- {t('apiNotifications.somethingWentWrong')}
- </h1>
- <p className='mt-4 text-2xl font-medium tracking-tight text-gray-700 dark:text-gray-200'>
- {t('apiNotifications.errorCode', { error })}
- </p>
- </div>
- <div className='mt-8 flex space-x-3 sm:border-l sm:border-transparent sm:pl-6'>
- <button
- type='button'
- onClick={() => window.location.reload()}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden'
- >
- {t('dashboard.reloadPage')}
- </button>
- <Link
- to={routes.contact}
- className='inline-flex items-center rounded-md border border-transparent bg-indigo-100 px-4 py-2 text-sm font-medium text-indigo-700 hover:bg-indigo-200 focus:ring-2 focus:ring-indigo-500 focus:ring-offset-2 focus:outline-hidden dark:bg-slate-800 dark:text-gray-50 dark:hover:bg-slate-700 dark:focus:ring-gray-50'
- >
- {t('notFoundPage.support')}
- </Link>
- </div>
- </div>
- </main>
- </div>
- </div>
- )
- }
-
- if (isLoading || isLoading === null) {
- return (
- <div className='mt-4'>
- <Loader />
- </div>
- )
- }
-
- if (activeMonitor) {
- return (
- <>
- <div className='mt-2 flex flex-col items-center justify-between lg:flex-row lg:items-start'>
- <div className='flex flex-wrap items-center space-x-5'>
- <h2 className='text-xl font-bold break-words break-all text-gray-900 dark:text-gray-50'>
- {activeMonitor.monitor.name}
- </h2>
- </div>
- <div className='mx-auto mt-3 flex w-full max-w-[420px] flex-wrap items-center justify-center gap-y-1 space-x-2 sm:mx-0 sm:w-auto sm:max-w-none sm:flex-nowrap sm:justify-between lg:mt-0'>
- <button
- type='button'
- title={t('project.refreshStats')}
- onClick={() => loadMonitorData(activeMonitor.monitor)}
- className={cx(
- 'hover: relative rounded-md bg-gray-50 p-2 text-sm font-medium hover:bg-white focus:z-10 focus:border-indigo-500 focus:ring-1 focus:ring-indigo-500 focus:outline-hidden dark:bg-slate-900 dark:hover:bg-slate-800 focus:dark:border-gray-200 focus:dark:ring-gray-200',
- {
- 'cursor-not-allowed opacity-50': isProjectLoading || isMonitorLoading,
- },
- )}
- >
- <RotateCw className='h-5 w-5 text-gray-700 dark:text-gray-50' />
- </button>
- <TBPeriodSelector
- activePeriod={activePeriod}
- items={allowedPeriodPairs}
- title={activePeriod?.label}
- onSelect={(pair) => {
- if (pair.isCustomDate) {
- setTimeout(() => {
- refCalendar.current.openCalendar()
- }, 100)
- } else {
- setPeriodPairs(tbPeriodPairs(t, undefined, undefined, language))
- setDateRange(null)
- updatePeriod(pair)
- }
- }}
- />
- </div>
- </div>
- <button
- type='button'
- onClick={() => setActiveMonitor(null)}
- className='mx-auto mt-2 mb-4 flex items-center text-base font-normal text-gray-900 underline decoration-dashed hover:decoration-solid lg:mx-0 lg:mt-0 dark:text-gray-100'
- >
- <ChevronLeftIcon className='h-4 w-4' />
- {t('monitor.backToMonitors')}
- </button>
- {activeMonitor.isFailed ? (
- <>
- <NoMonitorEvents />
- {isMonitorLoading && (
- <div className='static mt-4 !bg-transparent' id='loader'>
- <div className='loader-head dark:!bg-slate-800'>
- <div className='first dark:!bg-slate-600' />
- <div className='second dark:!bg-slate-600' />
- </div>
- </div>
- )}
- </>
- ) : (
- <div className='pt-2'>
- <div className='mb-5 flex flex-wrap justify-center gap-5 lg:justify-start'>
- <MetricCardsUptime overall={activeMonitor.overall!} />
- </div>
- <div className='mt-5 h-80 md:mt-0 [&_svg]:!overflow-visible' id='avgResponseUptimeChart' />
- {isMonitorLoading && (
- <div className='static mt-4 !bg-transparent' id='loader'>
- <div className='loader-head dark:!bg-slate-800'>
- <div className='first dark:!bg-slate-600' />
- <div className='second dark:!bg-slate-600' />
- </div>
- </div>
- )}
- </div>
- )}
- </>
- )
- }
-
- return (
- <div>
- <div className='mt-4'>
- {_isEmpty(monitors) ? (
- <div className='mt-5 rounded-xl bg-gray-700 p-5'>
- <div className='flex items-center text-gray-50'>
- <ClockIcon className='mr-2 h-8 w-8' />
- <p className='text-3xl font-bold'>{t('dashboard.uptime')}</p>
- </div>
- <p className='mt-2 text-lg whitespace-pre-wrap text-gray-100'>{t('dashboard.uptimeDesc')}</p>
- {authenticated ? (
- <Button
- onClick={handleNewMonitor}
- className='mt-6 rounded-md border border-transparent bg-white px-3 py-2 text-base font-medium text-gray-700 hover:bg-indigo-50 md:px-4'
- secondary
- large
- >
- <>
- {isLimitReached && <CurrencyDollarIcon className='mr-1 h-5 w-5' />}
- {t('monitor.create')}
- </>
- </Button>
- ) : (
- <Link
- to={routes.signup}
- className='mt-6 inline-block rounded-md border border-transparent bg-white px-3 py-2 text-base font-medium text-gray-700 select-none hover:bg-indigo-50'
- aria-label={t('titles.signup')}
- >
- {t('common.getStarted')}
- </Link>
- )}
- </div>
- ) : (
- <ul className='mt-4 grid grid-cols-1 gap-x-6 gap-y-3 lg:grid-cols-3 lg:gap-y-6'>
- {_map(monitors, (monitor) => (
- <MonitorCard
- allowedToManage={allowedToManage}
- key={monitor.id}
- monitor={monitor}
- deleteMonitor={onDelete}
- onClick={loadMonitorData}
- />
- ))}
- <AddMonitor handleNewMonitor={handleNewMonitor} isLimitReached={isLimitReached} />
- </ul>
- )}
- {pageAmount > 1 ? (
- <Pagination
- className='mt-4'
- page={page}
- pageAmount={pageAmount}
- setPage={setPage}
- total={total}
- pageSize={DEFAULT_MONITORS_TAKE}
- />
- ) : null}
- </div>
- <PaidFeature isOpened={isPaidFeatureOpened} onClose={() => setIsPaidFeatureOpened(false)} />
- </div>
- )
-}
-
-export default Uptime
diff --git a/web/app/pages/Project/uptime/components/NoMonitorDetails.tsx b/web/app/pages/Project/uptime/components/NoMonitorDetails.tsx
deleted file mode 100644
index d90dae6ea..000000000
--- a/web/app/pages/Project/uptime/components/NoMonitorDetails.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import React from 'react'
-import { useTranslation } from 'react-i18next'
-
-const NoMonitorEvents = () => {
- const { t } = useTranslation('common')
-
- return (
- <div className='mt-5 flex flex-col py-6 sm:px-6 lg:px-8'>
- <div className='mx-auto w-full max-w-7xl text-gray-900 dark:text-gray-50'>
- <h2 className='my-3 text-center text-4xl leading-tight'>{t('monitor.noEvents')}</h2>
- <h2 className='mb-8 text-center text-2xl leading-snug'>{t('monitor.noEventsDesc')}</h2>
- </div>
- </div>
- )
-}
-
-export default NoMonitorEvents
diff --git a/web/app/routes/projects.$pid.uptime.create.tsx b/web/app/routes/projects.$pid.uptime.create.tsx
deleted file mode 100644
index 76439768b..000000000
--- a/web/app/routes/projects.$pid.uptime.create.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import UptimeSettings from '~/pages/Project/uptime/Settings'
-
-export default function Settings() {
- return <UptimeSettings />
-}
diff --git a/web/app/routes/projects.$pid.uptime.settings.$id.tsx b/web/app/routes/projects.$pid.uptime.settings.$id.tsx
deleted file mode 100644
index b6a3afdde..000000000
--- a/web/app/routes/projects.$pid.uptime.settings.$id.tsx
+++ /dev/null
@@ -1,5 +0,0 @@
-import UptimeSettings from '~/pages/Project/uptime/Settings'
-
-export default function Index() {
- return <UptimeSettings isSettings />
-}
diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.ts
index 025270bf3..979e8f3f3 100644
--- a/web/app/utils/routes.ts
+++ b/web/app/utils/routes.ts
@@ -28,8 +28,6 @@ const routes = Object.freeze({
about: '/about',
create_alert: '/projects/:pid/alerts/create',
alert_settings: '/projects/:pid/alerts/settings/:id',
- create_uptime: '/projects/:pid/uptime/create',
- uptime_settings: '/projects/:pid/uptime/settings/:id',
press: '/press',
transfer_confirm: '/project/transfer/confirm',
transfer_reject: '/project/transfer/cancel',
diff --git a/web/app/utils/server.ts b/web/app/utils/server.ts
index 93a273e65..bff2daf69 100644
--- a/web/app/utils/server.ts
+++ b/web/app/utils/server.ts
@@ -265,7 +265,7 @@ export const getPageMeta = (t: typeof i18next.t, url?: string, _pathname?: strin
// organisation, project_settings, captcha_settings, project, captcha titles are set dynamically
- // todo: create_alert, alert_settings, project_protected_password, create_monitor, monitor_settings,
+ // todo: create_alert, alert_settings, project_protected_password
result.prefixLessTitle = result.title
result.title += ` ${TITLE_SUFFIX}`
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index f574d5c59..b19e450dd 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -699,7 +699,6 @@
"pageviewsAsc": "Least pageviews",
"noProjectsForCriteria": "No projects found for the selected criteria",
"lastVisitDesc": "Recently visited first",
- "uptime": "Uptime",
"captcha": "CAPTCHA",
"newProject": "New project",
"newFunnel": "New funnel",
@@ -748,7 +747,6 @@
"alerts": "Alerts",
"alertsDesc": "Automated alerts is a powerful tool that allows you to run automated tasks when specific events occur.\nWe can automatically monitor your project for traffic spikes and notify you via Telegram.",
"funnelsDesc": "Funnels is a powerful tool that allows you to track the conversion rate of your users through a series of steps.\nThe analysis provided by the marketing funnel gives you the ability to discover potential problems, improve your website, and boost your conversion rate.",
- "uptimeDesc": "Swetrix uptime is a powerful tool that allows you to monitor the uptime of your websites.\nThe analysis provided by the uptime gives you the ability to discover potential problems before your customers notice them.",
"frontend": "Frontend",
"backend": "Backend",
"network": "Network",
@@ -767,43 +765,6 @@
"median": "Median",
"xPercentile": "{{x}}th percentile"
},
- "monitor": {
- "create": "Create a monitor",
- "settingsOf": "Settings of {{name}}",
- "delete": "Delete monitor",
- "monitorCreated": "Uptime monitor created",
- "monitorUpdated": "Uptime monitor has been updated",
- "monitorDeleted": "Uptime monitor deleted",
- "qDelete": "Delete the monitor?",
- "deleteHint": "This action is irreversible.\nThe uptime monitor and all the data related to it will be deleted from our servers.",
- "noEvents": "No monitor events found",
- "noEventsDesc": "No events have been recorded for the specified period, please try a different period.",
- "form": {
- "name": "Monitor name",
- "type": "Monitor type",
- "url": "URL to monitor",
- "interval": "Monitor interval",
- "intervalHint": "We will check the URL every {{intervalTranslated}}",
- "retries": "Monitor retries",
- "retriesHint": "We will retry the URL {{retries}} times before marking it as failed",
- "retryInterval": "Monitor retry interval",
- "retryIntervalHint": "We will retry the URL every {{retryIntervalTranslated}}",
- "timeout": "Monitor timeout",
- "timeoutHint": "We will cancel the request to the URL if it takes longer than {{x}} seconds and mark it as failed",
- "acceptedStatusCodes": "Monitor accepted status codes (comma-separated)",
- "description": "Monitor description"
- },
- "error": {
- "urlInvalid": "Please enter a valid URL",
- "acceptedStatusCodesNotValid": "Some of the values provided are not valid HTTP status codes"
- },
- "backToMonitors": "Back to monitors list",
- "metrics": {
- "avg": "Avg. response time",
- "min": "Min. response time",
- "max": "Max. response time"
- }
- },
"alert": {
"create": "Create an alert",
"customEvent": "Custom event name",