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!

- Establish microservice architecture - Create redis BullMQ and RabbitMQ setup - Add new tables and realtions - Implement CRUD for groups - Add logic for sevice of Background task creation as a Prodcuer-Consumer architectural pattern - DTOs and validation

Yehor Dremliuha7da7c85454fc
diff --git a/apps/production/src/app.module.ts b/apps/production/src/app.module.ts
index 73e905b5e..fb940a65a 100644
--- a/apps/production/src/app.module.ts
+++ b/apps/production/src/app.module.ts
@@ -4,6 +4,7 @@ import { ConfigModule } from '@nestjs/config'
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'
@@ -56,9 +57,15 @@ const modules = [
username: process.env.MYSQL_USER,
password: process.env.MYSQL_ROOT_PASSWORD,
database: process.env.MYSQL_DATABASE,
- synchronize: false, // process.env.NODE_ENV !== 'production',
+ synchronize: true, // process.env.NODE_ENV !== 'production',
entities: [`${__dirname}/**/*.entity{.ts,.js}`],
}),
+ BullModule.forRoot({
+ redis: {
+ host: 'localhost',
+ port: 6379,
+ },
+ }),
I18nModule.forRootAsync(getI18nConfig()),
ScheduleModule.forRoot(),
NestjsFormDataModule.config({ isGlobal: true }),
diff --git a/apps/production/src/project/consumers/monitor.consumer.ts b/apps/production/src/project/consumers/monitor.consumer.ts
new file mode 100644
index 000000000..6a7457450
--- /dev/null
+++ b/apps/production/src/project/consumers/monitor.consumer.ts
@@ -0,0 +1,25 @@
+import { Process, Processor } from '@nestjs/bull'
+import { Inject, Logger } from '@nestjs/common'
+import { ClientProxy } from '@nestjs/microservices'
+import { Job } from 'bullmq'
+import { firstValueFrom } from 'rxjs'
+import { CreateMonitorHttpRequestDTO } from '../dto/create-monitor.dto'
+
+@Processor('monitor')
+export class MonitorConsumer {
+ constructor(@Inject('MONITOR_SERVICE') private monitorService: ClientProxy) {}
+
+ private readonly logger = new Logger(MonitorConsumer.name)
+
+ @Process('http-request')
+ async httpRequestProcess(
+ job: Job<CreateMonitorHttpRequestDTO>,
+ ): Promise<any> {
+ this.logger.debug(`Consumer works ${JSON.stringify(job.data)}`)
+ const res = await firstValueFrom(
+ this.monitorService.send('http-request', job.data),
+ )
+ this.logger.debug(`Consumer works ${JSON.stringify(res)}`)
+ return res
+ }
+}
diff --git a/apps/production/src/project/dto/create-monitor-group.dto.ts b/apps/production/src/project/dto/create-monitor-group.dto.ts
new file mode 100644
index 000000000..a0d1a0773
--- /dev/null
+++ b/apps/production/src/project/dto/create-monitor-group.dto.ts
@@ -0,0 +1,6 @@
+import { ApiProperty } from '@nestjs/swagger'
+
+export class CreateMonitorGroupDto {
+ @ApiProperty()
+ name: string
+}
diff --git a/apps/production/src/project/dto/create-monitor.dto.ts b/apps/production/src/project/dto/create-monitor.dto.ts
new file mode 100644
index 000000000..16e89f54d
--- /dev/null
+++ b/apps/production/src/project/dto/create-monitor.dto.ts
@@ -0,0 +1,107 @@
+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
+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,
+}
+
+// DTO for HTTP Options
+class HttpOptions {
+ @IsArray()
+ @IsEnum(HttpMethodEnum, { each: true })
+ method: HttpMethodEnum[]
+
+ @IsOptional()
+ @IsObject()
+ body?: Record<string, unknown>
+
+ @IsOptional()
+ @IsObject()
+ headers?: Record<string, string>
+}
+
+// Main DTO for Monitor Request
+export class CreateMonitorHttpRequestDTO {
+ @ApiProperty()
+ @IsEnum(['HTTP', 'HTTPS'])
+ monitorType: '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()
+ @IsString()
+ groupName: string
+
+ @ApiProperty()
+ @IsOptional()
+ @IsString()
+ description?: string
+
+ @ApiProperty()
+ @ValidateNested()
+ @Type(() => HttpOptions)
+ httpOptions: HttpOptions
+}
diff --git a/apps/production/src/project/dto/monitor-group-id.dto.ts b/apps/production/src/project/dto/monitor-group-id.dto.ts
new file mode 100644
index 000000000..1e09a04f3
--- /dev/null
+++ b/apps/production/src/project/dto/monitor-group-id.dto.ts
@@ -0,0 +1,9 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty, IsUUID } from 'class-validator'
+
+export class MonitorGroupIdDto {
+ @ApiProperty()
+ @IsUUID()
+ @IsNotEmpty()
+ readonly monitorGroupId: string
+}
diff --git a/apps/production/src/project/dto/update-monitor-group.dto.ts b/apps/production/src/project/dto/update-monitor-group.dto.ts
new file mode 100644
index 000000000..a68983d8f
--- /dev/null
+++ b/apps/production/src/project/dto/update-monitor-group.dto.ts
@@ -0,0 +1,6 @@
+import { ApiProperty } from '@nestjs/swagger'
+
+export class UpdateMonitorGroupDto {
+ @ApiProperty()
+ name: string
+}
diff --git a/apps/production/src/project/entity/monitor-group.entity.ts b/apps/production/src/project/entity/monitor-group.entity.ts
new file mode 100644
index 000000000..ca3a3fce3
--- /dev/null
+++ b/apps/production/src/project/entity/monitor-group.entity.ts
@@ -0,0 +1,26 @@
+import {
+ Entity,
+ Column,
+ PrimaryGeneratedColumn,
+ ManyToOne,
+ OneToMany,
+} from 'typeorm'
+import { Project } from './project.entity'
+import { MonitorEntity } from './monitor.entity'
+
+@Entity('monitor_groups')
+export class MonitorGroupEntity {
+ @PrimaryGeneratedColumn('uuid')
+ id: string
+
+ @Column()
+ name: string
+
+ @ManyToOne(() => Project, project => project.monitorsGroups, {
+ onDelete: 'CASCADE',
+ })
+ project: Project
+
+ @OneToMany(() => MonitorEntity, monitor => monitor.id)
+ monitors: MonitorEntity[]
+}
diff --git a/apps/production/src/project/entity/monitor.entity.ts b/apps/production/src/project/entity/monitor.entity.ts
new file mode 100644
index 000000000..eb4e8986e
--- /dev/null
+++ b/apps/production/src/project/entity/monitor.entity.ts
@@ -0,0 +1,53 @@
+import {
+ Entity,
+ Column,
+ PrimaryGeneratedColumn,
+ ManyToOne,
+ CreateDateColumn,
+ UpdateDateColumn,
+} from 'typeorm'
+import { MonitorGroupEntity } from './monitor-group.entity'
+
+@Entity('monitor')
+export class MonitorEntity {
+ @PrimaryGeneratedColumn()
+ id: number
+
+ @Column({ type: 'varchar' })
+ type: string
+
+ @Column({ type: 'varchar' })
+ name: string
+
+ @Column({ type: 'varchar' })
+ url: string
+
+ @Column({ type: 'int' })
+ interval: number
+
+ @Column({ type: 'int' })
+ retries: number
+
+ @Column({ type: 'int' })
+ retryInterval: number
+
+ @Column({ type: 'int' })
+ timeout: number
+
+ @Column({ type: 'json' })
+ acceptedStatusCodes: number[]
+
+ @Column({ type: 'text', nullable: true })
+ description: string | null
+
+ @ManyToOne(() => MonitorGroupEntity, group => group.monitors, {
+ onDelete: 'CASCADE',
+ })
+ group: MonitorGroupEntity
+
+ @CreateDateColumn()
+ createdAt: Date
+
+ @UpdateDateColumn()
+ updatedAt: Date
+}
diff --git a/apps/production/src/project/entity/project.entity.ts b/apps/production/src/project/entity/project.entity.ts
index 240be81c4..7ce11de8f 100644
--- a/apps/production/src/project/entity/project.entity.ts
+++ b/apps/production/src/project/entity/project.entity.ts
@@ -16,6 +16,7 @@ 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 { MonitorGroupEntity } from './monitor-group.entity'
// In case of modifying some properties here add them to the GDPR data export email template
@Entity()
@@ -117,4 +118,7 @@ export class Project {
@OneToMany(() => ProjectViewEntity, projectView => projectView.id)
views: ProjectViewEntity[]
+
+ @OneToMany(() => MonitorGroupEntity, monitorGroup => monitorGroup.id)
+ monitorsGroups: MonitorGroupEntity[]
}
diff --git a/apps/production/src/project/project.controller.ts b/apps/production/src/project/project.controller.ts
index 7500a0a1c..3c26b5d26 100644
--- a/apps/production/src/project/project.controller.ts
+++ b/apps/production/src/project/project.controller.ts
@@ -108,6 +108,12 @@ 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 { TimeFrameQueryEnumDTO } from './dto/get-prediction-query.dto'
+import { CreateMonitorHttpRequestDTO } from './dto/create-monitor.dto'
+import { MonitorEntity } from './entity/monitor.entity'
+import { MonitorGroupEntity } from './entity/monitor-group.entity'
+import { CreateMonitorGroupDto } from './dto/create-monitor-group.dto'
+import { UpdateMonitorGroupDto } from './dto/update-monitor-group.dto'
+import { MonitorGroupIdDto } from './dto/monitor-group-id.dto'
const PROJECTS_MAXIMUM = 50
@@ -2149,4 +2155,229 @@ export class ProjectController {
query.timeframe,
)
}
+
+ // TODO monitor here
+ @ApiOperation({ summary: 'Create monitor group' })
+ @ApiBearerAuth()
+ @ApiOkResponse({ type: MonitorGroupEntity })
+ @Post(':projectId/monitor-groups')
+ @Auth([], true, true)
+ public async createMonitorGroup(
+ @Param() { projectId }: ProjectIdDto,
+ @Body() body: CreateMonitorGroupDto,
+ @CurrentUserId() userId: string,
+ ): Promise<MonitorGroupEntity> {
+ this.logger.debug(`Creating monitor group: ${body.name}`)
+
+ const project = await this.projectService.findProject(projectId, [
+ 'admin',
+ 'share',
+ ])
+
+ 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 monitorGroup =
+ await this.projectService.findMonitorGroupByProjectIdAndName(
+ projectId,
+ body.name,
+ )
+ if (monitorGroup) {
+ throw new ConflictException('Monitor group exists.')
+ }
+
+ return this.projectService.createMonitorGroup(projectId, body)
+ }
+
+ @ApiOperation({ summary: 'Get all monitor groups for a project' })
+ @ApiBearerAuth()
+ @ApiOkResponse({ type: [MonitorGroupEntity] })
+ @Get(':projectId/monitor-groups')
+ @Auth([], true, true)
+ async getMonitorGroups(
+ @Param() { projectId }: ProjectIdDto,
+ @CurrentUserId() userId: string,
+ ): Promise<MonitorGroupEntity[]> {
+ const project = await this.projectService.findProject(projectId, [
+ 'admin',
+ 'share',
+ ])
+
+ 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 monitorGroup =
+ await this.projectService.getMonitorGroupsByProjectId(projectId)
+
+ return monitorGroup
+ }
+
+ @ApiOperation({ summary: 'Get monitor group by ID' })
+ @ApiBearerAuth()
+ @ApiOkResponse({ type: MonitorGroupEntity })
+ @Get(':projectId/monitor-groups/:monitorGroupId')
+ @Auth([], true, true)
+ async getMonitorGroup(
+ @Param() { projectId }: ProjectIdDto,
+ @Param() { monitorGroupId }: MonitorGroupIdDto,
+ @CurrentUserId() userId: string,
+ ): Promise<MonitorGroupEntity> {
+ const project = await this.projectService.findProject(projectId, [
+ 'admin',
+ 'share',
+ ])
+
+ 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 monitorGroup = await this.projectService.findMonitorGroup(
+ projectId,
+ monitorGroupId,
+ )
+ if (!monitorGroup) {
+ throw new NotFoundException('Monitor group not found.')
+ }
+
+ return monitorGroup
+ }
+
+ @ApiOperation({ summary: 'Update monitor group' })
+ @ApiBearerAuth()
+ @ApiOkResponse({ type: MonitorGroupEntity })
+ @Put(':projectId/monitor-groups/:monitorGroupId')
+ @Auth([], true, true)
+ async updateMonitorGroup(
+ @Param() { projectId }: ProjectIdDto,
+ @Param() { monitorGroupId }: MonitorGroupIdDto,
+ @Body() updateMonitorGroupDto: UpdateMonitorGroupDto,
+ @CurrentUserId() userId: string,
+ ): Promise<MonitorGroupEntity> {
+ const project = await this.projectService.findProject(projectId, [
+ 'admin',
+ 'share',
+ ])
+
+ 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)
+
+ return this.projectService.updateMonitorGroup(
+ projectId,
+ monitorGroupId,
+ updateMonitorGroupDto,
+ )
+ }
+
+ @ApiOperation({ summary: 'Delete monitor group' })
+ @ApiBearerAuth()
+ @Delete(':projectId/monitor-groups/:monitorGroupId')
+ @Auth([], true, true)
+ async deleteMonitorGroup(
+ @Param() { projectId }: ProjectIdDto,
+ @Param() { monitorGroupId }: MonitorGroupIdDto,
+ @CurrentUserId() userId: string,
+ ): Promise<void> {
+ const project = await this.projectService.findProject(projectId, [
+ 'admin',
+ 'share',
+ ])
+
+ 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)
+
+ return this.projectService.deleteMonitorGroup(projectId, monitorGroupId)
+ }
+
+ @ApiOperation({ summary: 'Create monitor for the project' })
+ @ApiBearerAuth()
+ @ApiOkResponse({ type: MonitorEntity })
+ @Post(':projectId/monitor-groups/:monitorGroupId/monitor')
+ @Auth([], true, true)
+ public async createMonitor(
+ @Param() { projectId }: ProjectIdDto,
+ @Param() { monitorGroupId }: MonitorGroupIdDto,
+ @Body() body: CreateMonitorHttpRequestDTO,
+ @CurrentUserId() userId: string,
+ ): Promise<void> {
+ // CREATE A MONITOR JOB HERE AS A SEPARATE PARALLEL PROCESS\
+ this.logger.debug(`Request is send: ${'type'}`)
+ this.logger.debug(`projectId: ${projectId}`)
+ this.logger.debug(`monitorGroupId: ${monitorGroupId}`)
+
+ const project = await this.projectService.findProject(projectId, [
+ 'admin',
+ 'share',
+ ])
+
+ 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 monitorGroup = await this.projectService.findMonitorGroup(
+ monitorGroupId,
+ projectId,
+ )
+ this.logger.debug(`monitorGroup: ${JSON.stringify(monitorGroup)}`)
+
+ if (!monitorGroup) {
+ throw new NotFoundException('Monitor group not found.')
+ }
+
+ // Insert Monitor into DB
+
+ // Create a job in service for sending httpRequest
+ await this.projectService.sendHttpRequest(body, 'idsome') // TODO
+ }
}
diff --git a/apps/production/src/project/project.module.ts b/apps/production/src/project/project.module.ts
index d58a14096..972b49d51 100644
--- a/apps/production/src/project/project.module.ts
+++ b/apps/production/src/project/project.module.ts
@@ -2,6 +2,8 @@ import { Module, forwardRef } from '@nestjs/common'
import { TypeOrmModule } from '@nestjs/typeorm'
import { HttpModule } from '@nestjs/axios'
import { ConfigModule, ConfigService } from '@nestjs/config'
+import { ClientsModule, Transport } from '@nestjs/microservices'
+import { BullModule } from '@nestjs/bull'
import { ProjectService } from './project.service'
import { ProjectController } from './project.controller'
@@ -13,6 +15,9 @@ 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 { MonitorGroupEntity } from './entity/monitor-group.entity'
+import { MonitorEntity } from './entity/monitor.entity'
@Module({
imports: [
@@ -23,6 +28,8 @@ import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event
Funnel,
ProjectViewEntity,
ProjectViewCustomEventEntity,
+ MonitorGroupEntity,
+ MonitorEntity,
]),
forwardRef(() => UserModule),
HttpModule.registerAsync({
@@ -32,11 +39,31 @@ import { ProjectViewCustomEventEntity } from './entity/project-view-custom-event
baseURL: configService.get('AI_URL'),
}),
}),
+ 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, ProjectsViewsRepository],
+ providers: [ProjectService, ProjectsViewsRepository, MonitorConsumer],
exports: [ProjectService, ProjectsViewsRepository],
controllers: [ProjectController],
})
diff --git a/apps/production/src/project/project.service.ts b/apps/production/src/project/project.service.ts
index 7442a2eb1..1dd193c30 100644
--- a/apps/production/src/project/project.service.ts
+++ b/apps/production/src/project/project.service.ts
@@ -29,6 +29,8 @@ import { compareSync } from 'bcrypt'
import { firstValueFrom } from 'rxjs'
import { HttpService } from '@nestjs/axios'
import { AxiosError } from 'axios'
+import { InjectQueue } from '@nestjs/bull'
+import { Queue } from 'bullmq'
import { UserService } from '../user/user.service'
import { ActionTokensService } from '../action-tokens/action-tokens.service'
@@ -74,6 +76,11 @@ import { nFormatter } from '../common/utils'
import { browserArgs } from '../og-image/og-image.service'
import { TimeFrameQueryEnum } from './dto/get-prediction-query.dto'
import { AppLoggerService } from '../logger/logger.service'
+import { CreateMonitorHttpRequestDTO } from './dto/create-monitor.dto'
+import { CreateMonitorGroupDto } from './dto/create-monitor-group.dto'
+import { MonitorGroupEntity } from './entity/monitor-group.entity'
+import { UpdateMonitorGroupDto } from './dto/update-monitor-group.dto'
+import { MonitorEntity } from './entity/monitor.entity'
dayjs.extend(utc)
@@ -290,10 +297,15 @@ export class ProjectService {
private readonly projectSubscriberRepository: Repository<ProjectSubscriber>,
@InjectRepository(Funnel)
private readonly funnelRepository: Repository<Funnel>,
+ @InjectRepository(MonitorGroupEntity)
+ private readonly monitorGroupRepository: Repository<MonitorGroupEntity>,
+ @InjectRepository(MonitorEntity)
+ private readonly monitorRepository: Repository<MonitorEntity>,
private readonly actionTokens: ActionTokensService,
private readonly mailerService: MailerService,
private readonly httpService: HttpService,
private readonly logger: AppLoggerService,
+ @InjectQueue('monitor') private monitorQueue: Queue,
) {}
async getRedisProject(pid: string): Promise<Project | null> {
@@ -1374,4 +1386,106 @@ export class ProjectService {
return null
}
}
+
+ // Monitoring
+ async createMonitorGroup(
+ projectId: string,
+ createMonitorGroupDto: CreateMonitorGroupDto,
+ ) {
+ return this.monitorGroupRepository.save({
+ ...createMonitorGroupDto,
+ project: { id: projectId },
+ })
+ }
+
+ // Get all monitor groups for a specific project
+ async getMonitorGroupsByProjectId(
+ projectId: string,
+ ): Promise<MonitorGroupEntity[]> {
+ return this.monitorGroupRepository.find({
+ where: { project: { id: projectId } },
+ })
+ }
+
+ // Get a monitor group by ID
+ async getMonitorGroupById(
+ projectId: string,
+ monitorGroupId: string,
+ ): Promise<MonitorGroupEntity> {
+ return this.monitorGroupRepository.findOne({
+ where: { id: monitorGroupId, project: { id: projectId } },
+ })
+ }
+
+ // Update a monitor group
+ async updateMonitorGroup(
+ projectId: string,
+ monitorGroupId: string,
+ updateMonitorGroupDto: UpdateMonitorGroupDto,
+ ): Promise<any> {
+ await this.monitorGroupRepository.update(
+ { id: monitorGroupId, project: { id: projectId } },
+ updateMonitorGroupDto,
+ )
+ // await this.monitorGroupRepository.update(monitorGroupId, updateMonitorGroupDto)
+ }
+
+ // Delete a monitor group
+ async deleteMonitorGroup(
+ projectId: string,
+ monitorGroupId: string,
+ ): Promise<void> {
+ await this.monitorGroupRepository.delete({
+ id: monitorGroupId,
+ project: { id: projectId },
+ })
+ }
+
+ async findMonitorGroupByProjectIdAndName(
+ projectId: string,
+ name: string,
+ ): Promise<MonitorGroupEntity | undefined> {
+ return this.monitorGroupRepository.findOne({
+ where: {
+ name,
+ project: { id: projectId },
+ },
+ })
+ }
+
+ async findMonitorGroup(
+ id: string,
+ projectId: string,
+ ): Promise<MonitorGroupEntity | undefined> {
+ return this.monitorGroupRepository.findOne({
+ where: {
+ id,
+ project: { id: projectId },
+ },
+ })
+ }
+
+ // Add a monitor to a monitor group
+ async createMonitor(
+ createMonitorHttpRequestDto: CreateMonitorHttpRequestDTO,
+ group: string,
+ ): Promise<MonitorEntity> {
+ const monitor = this.monitorRepository.create({
+ ...createMonitorHttpRequestDto,
+ group: { id: group },
+ })
+
+ return this.monitorRepository.save(monitor)
+ }
+
+ async sendHttpRequest(
+ monitorHttpRequestDto: CreateMonitorHttpRequestDTO,
+ monitorID: string,
+ ) {
+ // TODO crete interface for that stuff
+ await this.monitorQueue.add('http-request', monitorHttpRequestDto, {
+ repeat: { every: monitorHttpRequestDto.interval },
+ jobId: monitorID,
+ })
+ }
}
diff --git a/docker-compose-dev.yml b/docker-compose-dev.yml
index beca87ac0..4bd1946d2 100644
--- a/docker-compose-dev.yml
+++ b/docker-compose-dev.yml
@@ -17,3 +17,13 @@ services:
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes'
ports:
- 3306:3306
+
+ redis-commander:
+ image: rediscommander/redis-commander:latest
+ container_name: redis-commander
+ environment:
+ - REDIS_HOSTS=local:redis:6379
+ ports:
+ - "8081:8081"
+ depends_on:
+ - redis
diff --git a/migrations/mysql/2024_09_08.sql b/migrations/mysql/2024_09_08.sql
new file mode 100644
index 000000000..032b73910
--- /dev/null
+++ b/migrations/mysql/2024_09_08.sql
@@ -0,0 +1,24 @@
+CREATE TABLE IF NOT EXISTS monitor_groups (
+ groupId INT AUTO_INCREMENT PRIMARY KEY,
+ groupName VARCHAR(255) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+
+
+CREATE TABLE IF NOT EXISTS monitor (
+ monitorId INT AUTO_INCREMENT PRIMARY KEY,
+ monitorType VARCHAR(255) NOT NULL,
+ name VARCHAR(255) NOT NULL,
+ url VARCHAR(255) NOT NULL,
+ `interval` INT NOT NULL,
+ retries INT NOT NULL,
+ retryInterval INT NOT NULL,
+ timeout INT NOT NULL,
+ acceptedStatusCodes JSON NOT NULL,
+ description TEXT,
+ groupName VARCHAR(255) NOT NULL,
+ userID INT NOT NULL,
+ createdAt DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6),
+ updatedAt DATETIME(6) NOT NULL DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6),
+ FOREIGN KEY (groupName) REFERENCES monitor_groups(groupName),
+ FOREIGN KEY (userID) REFERENCES users(userId)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
diff --git a/package.json b/package.json
index a03e80449..cbf79c1f3 100644
--- a/package.json
+++ b/package.json
@@ -31,11 +31,13 @@
"@faker-js/faker": "^8.4.1",
"@nestjs-modules/mailer": "^2.0.2",
"@nestjs/axios": "^3.0.2",
+ "@nestjs/bull": "^10.2.0",
"@nestjs/common": "^10.3.10",
"@nestjs/config": "^3.2.3",
"@nestjs/core": "^10.3.10",
"@nestjs/jwt": "^10.2.0",
"@nestjs/mapped-types": "^2.0.5",
+ "@nestjs/microservices": "^10.3.10",
"@nestjs/passport": "^10.0.3",
"@nestjs/platform-express": "^10.3.10",
"@nestjs/schedule": "^4.1.0",
@@ -46,10 +48,14 @@
"@sentry/cli": "^2.32.2",
"@sentry/nestjs": "^8.19.0",
"@sentry/profiling-node": "^8.19.0",
+ "amqp-connection-manager": "^4.1.14",
+ "amqplib": "^0.10.4",
"axios": "^1.7.2",
"bcrypt": "^5.1.1",
"blake3": "^2.1.7",
"body-parser": "^1.20.2",
+ "bull": "^4.16.0",
+ "bullmq": "^5.12.0",
"chalk": "^4.1.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
@@ -65,6 +71,7 @@
"front-matter": "^4.0.2",
"googleapis": "^140.0.1",
"handlebars": "^4.7.8",
+ "install": "^0.13.0",
"ioredis": "^5.4.1",
"ip-range-check": "^0.2.0",
"isbot": "^5.1.13",
@@ -77,6 +84,7 @@
"nestjs-i18n": "^10.4.5",
"nestjs-telegraf": "^2.8.1",
"nodemailer": "^6.9.14",
+ "npm": "^10.8.2",
"otplib": "^12.0.1",
"passport": "^0.7.0",
"passport-headerapikey": "^1.2.2",
@@ -124,7 +132,7 @@
"ts-node": "^10.9.2",
"ts-prune": "^0.10.3",
"tsconfig-paths": "^4.2.0",
- "typescript": "^5.5.3"
+ "typescript": "^5.1.3"
},
"jest": {
"moduleFileExtensions": [