From e91a54b75c33327b1cf20e0a2dd89178c2942087 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 19 Jan 2026 23:41:24 +0000 Subject: [PATCH 1/6] initial commit --- server/src/config/services.ts | 7 + server/src/controllers/incidentController.ts | 12 +- .../db/models/{Incident.js => Incident.ts} | 42 +-- server/src/db/models/index.ts | 3 + .../incidents/IIncidentsRepository.ts | 22 ++ .../incidents/MongoIncidentRepository.ts | 100 +++++++ server/src/repositories/index.ts | 3 + ...{incidentService.js => incidentService.ts} | 252 +++++++----------- .../SuperSimpleQueueHelper.ts | 11 + .../service/infrastructure/statusService.ts | 64 ----- server/src/types/incident.ts | 20 ++ server/src/types/index.ts | 1 + 12 files changed, 295 insertions(+), 242 deletions(-) rename server/src/db/models/{Incident.js => Incident.ts} (55%) create mode 100644 server/src/repositories/incidents/IIncidentsRepository.ts create mode 100644 server/src/repositories/incidents/MongoIncidentRepository.ts rename server/src/service/business/{incidentService.js => incidentService.ts} (55%) create mode 100644 server/src/types/incident.ts diff --git a/server/src/config/services.ts b/server/src/config/services.ts index 9ae5ecb12..cbd58f2e9 100644 --- a/server/src/config/services.ts +++ b/server/src/config/services.ts @@ -84,6 +84,7 @@ import { MongoRecoveryTokensRepository, MongoSettingsRepository, MongoNotificationsRepository, + MongoIncidentRepository, IMonitorsRepository, IChecksRepository, IMonitorStatsRepository, @@ -93,6 +94,7 @@ import { IRecoveryTokensRepository, ISettingsRepository, INotificationsRepository, + IIncidentsRepository, } from "@/repositories/index.js"; export type InitializedSerivces = { @@ -127,6 +129,7 @@ export type InitializedSerivces = { recoveryTokensRepository: IRecoveryTokensRepository; settingsRepository: ISettingsRepository; notificationsRepository: INotificationsRepository; + incidentsRepository: IIncidentsRepository; }; export const initializeServices = async ({ @@ -183,6 +186,7 @@ export const initializeServices = async ({ const recoveryTokensRepository = new MongoRecoveryTokensRepository(); const settingsRepository = new MongoSettingsRepository(); const notificationsRepository = new MongoNotificationsRepository(); + const incidentsRepository = new MongoIncidentRepository(); const networkService = new NetworkService({ axios, got, @@ -205,6 +209,7 @@ export const initializeServices = async ({ logger, errorService, stringService, + incidentsRepository, }); const checkService = new CheckService({ @@ -247,6 +252,7 @@ export const initializeServices = async ({ notificationsService, checkService, buffer: bufferService, + incidentService, }); const superSimpleQueue = await SuperSimpleQueue.create({ @@ -332,6 +338,7 @@ export const initializeServices = async ({ recoveryTokensRepository, settingsRepository, notificationsRepository, + incidentsRepository, }; Object.values(services).forEach((service) => { diff --git a/server/src/controllers/incidentController.ts b/server/src/controllers/incidentController.ts index b17788d80..645149acd 100644 --- a/server/src/controllers/incidentController.ts +++ b/server/src/controllers/incidentController.ts @@ -67,12 +67,12 @@ class IncidentController { resolveIncidentManually = async (req: Request, res: Response, next: NextFunction) => { try { - const resolvedIncident = await this.incidentService.resolveIncidentManually({ - incidentId: req?.params?.incidentId, - userId: req?.user?.id, - teamId: req?.user?.teamId, - comment: req?.body?.comment, - }); + const resolvedIncident = await this.incidentService.resolveIncident( + req?.params?.incidentId, + req?.user?.id, + req?.user?.teamId, + req?.body?.comment + ); return res.status(200).json({ success: true, diff --git a/server/src/db/models/Incident.js b/server/src/db/models/Incident.ts similarity index 55% rename from server/src/db/models/Incident.js rename to server/src/db/models/Incident.ts index a9477301b..8de1c7c2c 100644 --- a/server/src/db/models/Incident.js +++ b/server/src/db/models/Incident.ts @@ -1,16 +1,31 @@ -import mongoose from "mongoose"; +import { Schema, model, type Types } from "mongoose"; +import { IncidentResolutionTypes, type Incident } from "@/types/incident.js"; -const IncidentSchema = mongoose.Schema( +type IncidentDocumentBase = Omit & { + monitorId: Types.ObjectId; + teamId: Types.ObjectId; + resolvedBy?: Types.ObjectId | null; + startTime: Date; + endTime: Date | null; + createdAt: Date; + updatedAt: Date; +}; + +export interface IncidentDocument extends IncidentDocumentBase { + _id: Types.ObjectId; +} + +const IncidentSchema = new Schema( { monitorId: { - type: mongoose.Schema.Types.ObjectId, + type: Schema.Types.ObjectId, ref: "Monitor", required: true, immutable: true, index: true, }, teamId: { - type: mongoose.Schema.Types.ObjectId, + type: Schema.Types.ObjectId, ref: "Team", required: true, immutable: true, @@ -18,8 +33,8 @@ const IncidentSchema = mongoose.Schema( }, startTime: { type: Date, - required: true, immutable: true, + required: true, }, endTime: { type: Date, @@ -36,16 +51,16 @@ const IncidentSchema = mongoose.Schema( }, statusCode: { type: Number, - index: true, default: null, + index: true, }, resolutionType: { type: String, - enum: ["automatic", "manual"], + enum: IncidentResolutionTypes, default: null, }, resolvedBy: { - type: mongoose.Schema.Types.ObjectId, + type: Schema.Types.ObjectId, ref: "User", default: null, }, @@ -53,12 +68,6 @@ const IncidentSchema = mongoose.Schema( type: String, default: null, }, - checks: [ - { - type: mongoose.Schema.Types.ObjectId, - ref: "Check", - }, - ], }, { timestamps: true } ); @@ -71,6 +80,7 @@ IncidentSchema.index({ resolutionType: 1, status: 1 }); IncidentSchema.index({ resolvedBy: 1, status: 1 }); IncidentSchema.index({ createdAt: -1 }); -const Incident = mongoose.model("Incident", IncidentSchema); +const IncidentModel = model("Incident", IncidentSchema); -export default Incident; +export { IncidentModel }; +export default IncidentModel; diff --git a/server/src/db/models/index.ts b/server/src/db/models/index.ts index 18a3a3b19..4b71937bb 100644 --- a/server/src/db/models/index.ts +++ b/server/src/db/models/index.ts @@ -24,3 +24,6 @@ export { default as RecoveryTokenModel } from "@/db/models/RecoveryToken.js"; export * from "@/db/models/Notification.js"; export { default as NotificationModel } from "@/db/models/Notification.js"; + +export * from "@/db/models/Incident.js"; +export { default as IncidentModel } from "@/db/models/Incident.js"; diff --git a/server/src/repositories/incidents/IIncidentsRepository.ts b/server/src/repositories/incidents/IIncidentsRepository.ts new file mode 100644 index 000000000..00235de0d --- /dev/null +++ b/server/src/repositories/incidents/IIncidentsRepository.ts @@ -0,0 +1,22 @@ +import type { Incident } from "@/types/index.js"; +export interface IIncidentsRepository { + // create + create(incident: Partial): Promise; + // fetch + findActiveByIncidentId(incidentId: string, teamId: string): Promise; + findActiveByMonitorId(monitorId: string, teamId: string): Promise; + findByTeamId( + teamId: string, + dateRange: string, + page: number, + rowsPerPage: number, + sortOrder?: string, + status?: string, + monitorId?: string, + resolutionType?: string + ): Promise; + + // update + updateById(incidentId: string, teamId: string, updateData: Partial): Promise; + // delete +} diff --git a/server/src/repositories/incidents/MongoIncidentRepository.ts b/server/src/repositories/incidents/MongoIncidentRepository.ts new file mode 100644 index 000000000..db0048fc7 --- /dev/null +++ b/server/src/repositories/incidents/MongoIncidentRepository.ts @@ -0,0 +1,100 @@ +import { IncidentModel } from "@/db/models/index.js"; +import type { IncidentDocument } from "@/db/models/Incident.js"; +import type { Incident } from "@/types/index.js"; +import type { IIncidentsRepository } from "@/repositories/index.js"; +import mongoose from "mongoose"; +import { AppError } from "@/utils/AppError.js"; + +class MongoIncidentRepository implements IIncidentsRepository { + private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => { + if (!value) { + return ""; + } + return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value); + }; + + private toDateString = (value?: Date | string | null): string => { + if (!value) { + return new Date(0).toISOString(); + } + return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); + }; + + protected toEntity = (doc: IncidentDocument): Incident => { + return { + id: this.toStringId(doc._id), + monitorId: this.toStringId(doc.monitorId), + teamId: this.toStringId(doc.teamId), + startTime: this.toDateString(doc.startTime), + endTime: doc.endTime ? this.toDateString(doc.endTime) : null, + status: doc.status, + message: doc.message ?? null, + statusCode: doc.statusCode ?? null, + resolutionType: doc.resolutionType ?? null, + resolvedBy: doc.resolvedBy ? this.toStringId(doc.resolvedBy) : null, + comment: doc.comment ?? null, + createdAt: this.toDateString(doc.createdAt), + updatedAt: this.toDateString(doc.updatedAt), + }; + }; + + protected mapDocuments = (documents: IncidentDocument[] | IncidentDocument | null): Incident[] => { + if (!documents) { + return []; + } + if (Array.isArray(documents)) { + return documents.map((doc) => this.toEntity(doc)); + } + return [this.toEntity(documents)]; + }; + + async create(incident: Partial): Promise { + const newIncident = await IncidentModel.create(incident); + return this.toEntity(newIncident); + } + + findActiveByIncidentId = async (incidentId: string, teamId: string): Promise => { + const incident = await IncidentModel.findOne({ + _id: new mongoose.Types.ObjectId(incidentId), + teamId: new mongoose.Types.ObjectId(teamId), + status: true, + }); + if (!incident) { + return null; + } + return this.toEntity(incident); + }; + + findActiveByMonitorId = async (monitorId: string, teamId: string): Promise => { + const incident = await IncidentModel.findOne({ + monitorId: new mongoose.Types.ObjectId(monitorId), + teamId: new mongoose.Types.ObjectId(teamId), + status: true, + }); + if (!incident) { + return null; + } + return this.toEntity(incident); + }; + + findByTeamId = async (teamId: string): Promise => { + throw new Error("Method not implemented."); + }; + + updateById = async (incidentId: string, teamId: string, patch: Partial) => { + const updatedIncident = await IncidentModel.findOneAndUpdate( + { _id: new mongoose.Types.ObjectId(incidentId), teamId: new mongoose.Types.ObjectId(teamId) }, + { + $set: { + ...patch, + }, + }, + { new: true, runValidators: true } + ); + if (!updatedIncident) { + throw new AppError({ message: `Failed to update incident with id ${incidentId}`, status: 500 }); + } + return this.toEntity(updatedIncident); + }; +} +export default MongoIncidentRepository; diff --git a/server/src/repositories/index.ts b/server/src/repositories/index.ts index 1a3199081..72dfd2f40 100644 --- a/server/src/repositories/index.ts +++ b/server/src/repositories/index.ts @@ -24,3 +24,6 @@ export { default as MongoSettingsRepository } from "@/repositories/settings/Mong export * from "@/repositories/notifications/INotificationsRepository.js"; export { default as MongoNotificationsRepository } from "@/repositories/notifications/MongoNotificationsRepository.js"; + +export * from "@/repositories/incidents/IIncidentsRepository.js"; +export { default as MongoIncidentRepository } from "@/repositories/incidents/MongoIncidentRepository.js"; diff --git a/server/src/service/business/incidentService.js b/server/src/service/business/incidentService.ts similarity index 55% rename from server/src/service/business/incidentService.js rename to server/src/service/business/incidentService.ts index db89caa68..a96c7923d 100644 --- a/server/src/service/business/incidentService.js +++ b/server/src/service/business/incidentService.ts @@ -1,183 +1,123 @@ const SERVICE_NAME = "incidentService"; +import type { Monitor } from "@/types/monitor.js"; +import { AppError } from "@/utils/AppError.js"; +import type { IIncidentsRepository } from "@/repositories/index.js"; +import type { Incident } from "@/types/index.js"; class IncidentService { static SERVICE_NAME = SERVICE_NAME; - constructor({ db, logger, errorService, stringService }) { + private db: any; + private logger: any; + private errorService: any; + private stringService: any; + private incidentsRepository: IIncidentsRepository; + + constructor({ + db, + logger, + errorService, + stringService, + incidentsRepository, + }: { + db: any; + logger: any; + errorService: any; + stringService: any; + incidentsRepository: IIncidentsRepository; + }) { this.db = db; this.logger = logger; this.errorService = errorService; this.stringService = stringService; + this.incidentsRepository = incidentsRepository; } get serviceName() { return IncidentService.SERVICE_NAME; } - createIncident = async (monitor, check) => { - try { - if (!monitor || !monitor._id) { - throw this.errorService.createBadRequestError("Monitor is required"); - } - - if (!check || !check._id) { - throw this.errorService.createBadRequestError("Check is required"); - } - - const activeIncident = await this.db.incidentModule.getActiveIncidentByMonitor(monitor._id); - + handleIncident = async (monitor: Monitor, code: number): Promise => { + const activeIncident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId); + // Monitor is down, create an incident + if (monitor.status === false) { if (activeIncident) { - await this.db.incidentModule.addCheckToIncident(activeIncident._id, check._id); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "createIncident", - message: `Check added to existing active incident for monitor ${monitor.name}`, - incidentId: activeIncident._id, - monitorId: monitor._id, - }); - return activeIncident; + } else { + const incident = { + monitorId: monitor.id, + teamId: monitor.teamId, + startTime: Date.now().toString(), + status: true, + statusCode: code, + }; + return await this.incidentsRepository.create(incident); } - - const incidentData = { - monitorId: monitor._id, - teamId: monitor.teamId, - type: monitor.type, - startTime: new Date(), - status: true, - message: check.message || null, - statusCode: check.statusCode || null, - checks: [check._id], - }; - - const incident = await this.db.incidentModule.createIncident(incidentData); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "createIncident", - message: `New incident created for monitor ${monitor.name}`, - incidentId: incident._id, - monitorId: monitor._id, - }); - - return incident; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "createIncident", - message: error.message, - monitorId: monitor?._id, - error: error.stack, - }); - throw error; } + + // Monitor is up, resolve active incidents + if (!activeIncident) { + return null; + } + activeIncident.status = false; + activeIncident.endTime = Date.now().toString(); + activeIncident.resolutionType = "automatic"; + return await this.incidentsRepository.updateById(activeIncident.id, activeIncident.teamId, activeIncident); }; - resolveIncident = async (monitor, check) => { - try { - if (!monitor || !monitor._id) { - throw this.errorService.createBadRequestError("Monitor is required"); - } - - const activeIncident = await this.db.incidentModule.getActiveIncidentByMonitor(monitor._id); - - if (!activeIncident) { - this.logger.info({ - service: this.SERVICE_NAME, - method: "resolveIncident", - message: `No active incident found for monitor ${monitor.name}`, - monitorId: monitor._id, - }); - return null; - } - - await this.db.incidentModule.addCheckToIncident(activeIncident._id, check._id); - - const resolvedIncident = await this.db.incidentModule.resolveIncident(activeIncident._id, { - resolutionType: "automatic", - resolvedBy: null, - endTime: new Date(), - }); - - this.logger.info({ - service: this.SERVICE_NAME, - method: "resolveIncident", - message: `Incident automatically resolved for monitor ${monitor.name}`, - incidentId: resolvedIncident._id, - monitorId: monitor._id, - }); - - return resolvedIncident; - } catch (error) { - this.logger.error({ - service: this.SERVICE_NAME, - method: "resolveIncident", - message: error.message, - monitorId: monitor?._id, - error: error.stack, - }); - throw error; - } - }; - - resolveIncidentManually = async ({ incidentId, userId, teamId, comment }) => { + resolveIncident = async (incidentId: string, userId: string, teamId: string, comment?: string) => { try { if (!incidentId) { - throw this.errorService.createBadRequestError("No incident ID in request"); + throw new AppError({ message: "No incident ID in request", service: SERVICE_NAME, method: "resolveIncident" }); } if (!userId) { - throw this.errorService.createBadRequestError("No user ID in request"); + throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "resolveIncident" }); } if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); + throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "resolveIncident" }); } - const incident = await this.db.incidentModule.getIncidentById(incidentId); + const incident = await this.incidentsRepository.findActiveByIncidentId(incidentId, teamId); if (!incident) { - throw this.errorService.createNotFoundError("Incident not found"); - } - - if (!incident.teamId.equals(teamId)) { - throw this.errorService.createAuthorizationError(); + throw new AppError({ message: "Incident not found", service: SERVICE_NAME, method: "resolveIncident" }); } if (incident.status === false) { - throw this.errorService.createBadRequestError("Incident is already resolved"); + throw new AppError({ message: "Incident is already resolved", service: SERVICE_NAME, method: "resolveIncident" }); } - const resolvedIncident = await this.db.incidentModule.resolveIncident(incidentId, { - resolutionType: "manual", - resolvedBy: userId, - comment: comment || null, - endTime: new Date(), - }); + incident.resolutionType = "manual"; + incident.status = false; + incident.resolvedBy = userId; + incident.comment = comment || null; + incident.endTime = Date.now().toString(); - this.logger.info({ - service: this.SERVICE_NAME, + const resolvedIncident = await this.incidentsRepository.updateById(incident.id, teamId, incident); + + this.logger.debug({ + service: SERVICE_NAME, method: "resolveIncidentManually", message: `Incident manually resolved by user`, - incidentId: resolvedIncident._id, - userId, + details: resolvedIncident.id, }); return resolvedIncident; - } catch (error) { + } catch (error: any) { this.logger.error({ - service: this.SERVICE_NAME, - method: "resolveIncidentManually", + service: SERVICE_NAME, + method: "resolveIncident", message: error.message, - incidentId, - error: error.stack, + details: incidentId, + stack: error.stack, }); throw error; } }; - getIncidentsByTeam = async ({ teamId, query }) => { + getIncidentsByTeam = async ({ teamId, query }: { teamId: string; query?: any }) => { try { if (!teamId) { throw this.errorService.createBadRequestError("No team ID in request"); @@ -197,19 +137,19 @@ class IncidentService { }); return result; - } catch (error) { + } catch (error: any) { this.logger.error({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "getIncidentsByTeam", message: error.message, - teamId, - error: error.stack, + details: teamId, + stack: error.stack, }); throw error; } }; - getIncidentSummary = async ({ teamId, query }) => { + getIncidentSummary = async ({ teamId, query }: { teamId: string; query?: any }) => { try { if (!teamId) { throw this.errorService.createBadRequestError("No team ID in request"); @@ -223,19 +163,19 @@ class IncidentService { }); return summary; - } catch (error) { + } catch (error: any) { this.logger.error({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "getIncidentSummary", message: error.message, - teamId, - error: error.stack, + details: teamId, + stack: error.stack, }); throw error; } }; - getIncidentById = async ({ incidentId, teamId }) => { + getIncidentById = async ({ incidentId, teamId }: { incidentId: string; teamId: string }) => { try { if (!incidentId) { throw this.errorService.createBadRequestError("No incident ID in request"); @@ -256,19 +196,19 @@ class IncidentService { } return incident; - } catch (error) { + } catch (error: any) { this.logger.error({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "getIncidentById", message: error.message, - incidentId, - error: error.stack, + details: incidentId, + stack: error.stack, }); throw error; } }; - processIncidentsFromBuffer = async (incidentBufferItems) => { + processIncidentsFromBuffer = async (incidentBufferItems: any[]) => { try { if (!incidentBufferItems || incidentBufferItems.length === 0) { return; @@ -285,16 +225,16 @@ class IncidentService { } } - for (const item of resolveItems) { + for (const item of resolveItems as any[]) { try { - await this.resolveIncident(item.monitor, item.check); - } catch (error) { + await this.resolveIncident(item.monitor); + } catch (error: any) { this.logger.error({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "processIncidentsFromBuffer", message: `Failed to resolve incident from buffer: ${error.message}`, monitorId: item.monitor?._id, - error: error.stack, + stack: error.stack, }); } } @@ -303,11 +243,11 @@ class IncidentService { return; } - const groupedByMonitor = {}; + const groupedByMonitor: Record = {}; for (const item of createItems) { if (!item.monitor || !item.monitor.id || !item.check || !item.check.id) { this.logger.warn({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "processIncidentsFromBuffer", message: "Skipping item with missing monitor or check data", item, @@ -329,7 +269,7 @@ class IncidentService { const activeIncidents = await this.db.incidentModule.getActiveIncidentsByMonitors(monitorIds); - const incidentsCreatedInFlush = {}; + const incidentsCreatedInFlush: Record = {}; const checksToAddToIncidents = []; const newIncidentsToCreate = []; @@ -392,19 +332,19 @@ class IncidentService { } this.logger.info({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "processIncidentsFromBuffer", message: `Processed ${incidentBufferItems.length} incident buffer items`, created: newIncidentsToCreate.length, checksAdded: checksToAddToIncidents.length, resolved: resolveItems.length, }); - } catch (error) { + } catch (error: any) { this.logger.error({ - service: this.SERVICE_NAME, + service: SERVICE_NAME, method: "processIncidentsFromBuffer", message: error.message, - error: error.stack, + stack: error.stack, }); throw error; } diff --git a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts index bbd3a11f0..26d45db22 100644 --- a/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts +++ b/server/src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts @@ -2,6 +2,8 @@ const SERVICE_NAME = "JobQueueHelper"; import type { Monitor } from "@/types/monitor.js"; import { AppError } from "@/utils/AppError.js"; import { INetworkService, INotificationsService, IStatusService } from "@/service/index.js"; +import IncidentService from "@/service/business/incidentService.js"; + class SuperSimpleQueueHelper { static SERVICE_NAME = SERVICE_NAME; @@ -12,6 +14,7 @@ class SuperSimpleQueueHelper { private notificationsService: INotificationsService; private checkService: any; private buffer: any; + private incidentService: IncidentService; constructor({ db, @@ -21,6 +24,7 @@ class SuperSimpleQueueHelper { notificationsService, checkService, buffer, + incidentService, }: { db: any; logger: any; @@ -29,6 +33,7 @@ class SuperSimpleQueueHelper { notificationsService: INotificationsService; checkService: any; buffer: any; + incidentService: IncidentService; }) { this.db = db; this.logger = logger; @@ -37,6 +42,7 @@ class SuperSimpleQueueHelper { this.checkService = checkService; this.buffer = buffer; this.notificationsService = notificationsService; + this.incidentService = incidentService; } get serviceName() { @@ -90,6 +96,11 @@ class SuperSimpleQueueHelper { stack: error.stack, }); }); + + // Step 6. Handle incidents + if (statusChangeResult.statusChanged) { + await this.incidentService.handleIncident(statusChangeResult.monitor, statusChangeResult.code); + } } catch (error: any) { this.logger.warn({ message: error.message, diff --git a/server/src/service/infrastructure/statusService.ts b/server/src/service/infrastructure/statusService.ts index 3d9591c02..3a83dbd28 100755 --- a/server/src/service/infrastructure/statusService.ts +++ b/server/src/service/infrastructure/statusService.ts @@ -218,70 +218,6 @@ export class StatusService implements IStatusService { statusChanged = true; } - if (statusChanged) { - this.logger.info({ - service: SERVICE_NAME, - message: `${monitor.name} went from ${this.getStatusString(prevStatus)} to ${this.getStatusString(newStatus)}`, - prevStatus, - newStatus, - }); - - if (newStatus === false) { - await this.handleIncidentForCheck(check, monitor, "create", "status change to down"); - } else if (prevStatus === false) { - await this.handleIncidentForCheck(check, monitor, "resolve", "status change to up"); - } - } - - if (monitor.status === false && !statusChanged) { - try { - const lastManuallyResolvedIncident = await this.db.incidentModule.getLastManuallyResolvedIncident(monitor.id); - - let calculatedFailureRate = failureRate; - - if (lastManuallyResolvedIncident && lastManuallyResolvedIncident.endTime) { - try { - const checksAfterResolution = await CheckModel.find({ - monitorId: monitor.id, - createdAt: { $gt: lastManuallyResolvedIncident.endTime }, - }) - .sort({ createdAt: 1 }) - .limit(monitor.statusWindowSize) - .select("status") - .lean(); - - if (checksAfterResolution.length > 0) { - const checksStatuses = checksAfterResolution.map((c) => c.status); - const failuresAfterResolution = checksStatuses.filter((s) => s === false).length; - calculatedFailureRate = (failuresAfterResolution / monitor.statusWindow.length) * 100; - } else { - calculatedFailureRate = 0; - } - } catch (checkQueryError: any) { - this.logger.error({ - service: SERVICE_NAME, - method: "updateStatus", - message: `Failed to query checks after manual resolution: ${checkQueryError.message}`, - monitorId: monitor.id, - stack: checkQueryError.stack, - }); - } - } - - if (calculatedFailureRate >= monitor.statusWindowThreshold) { - await this.handleIncidentForCheck(check, monitor, "create", "threshold check without status change"); - } - } catch (error: any) { - this.logger.error({ - service: SERVICE_NAME, - method: "updateStatus", - message: `Error handling threshold check without status change: ${error.message}`, - monitorId: monitor.id, - stack: error.stack, - }); - } - } - monitor.status = newStatus; const updated = await this.monitorsRepository.updateById(monitor.id, monitor.teamId, monitor); diff --git a/server/src/types/incident.ts b/server/src/types/incident.ts new file mode 100644 index 000000000..65186f08c --- /dev/null +++ b/server/src/types/incident.ts @@ -0,0 +1,20 @@ +// export type IncidentResolutionType = "automatic" | "manual" | null; + +export const IncidentResolutionTypes = ["automatic", "manual", null] as const; +export type IncidentResolutionType = (typeof IncidentResolutionTypes)[number]; + +export interface Incident { + id: string; + monitorId: string; + teamId: string; + startTime: string; + endTime: string | null; + status: boolean; + message?: string | null; + statusCode?: number | null; + resolutionType: IncidentResolutionType; + resolvedBy?: string | null; + comment?: string | null; + createdAt: string; + updatedAt: string; +} diff --git a/server/src/types/index.ts b/server/src/types/index.ts index fda48f0c6..e28d75e91 100644 --- a/server/src/types/index.ts +++ b/server/src/types/index.ts @@ -9,3 +9,4 @@ export * from "@/types/recoveryToken.js"; export * from "@/types/settings.js"; export * from "@/types/notification.js"; export * from "@/types/alert.js"; +export * from "@/types/incident.js"; From adb2a383cfd6705473bc40b12de9eeeeb87f6190 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 20 Jan 2026 00:02:27 +0000 Subject: [PATCH 2/6] refactor --- .../incidents/IIncidentsRepository.ts | 3 +- .../incidents/MongoIncidentRepository.ts | 25 ++++++++- .../src/service/business/incidentService.ts | 51 +++++++++++++++---- 3 files changed, 65 insertions(+), 14 deletions(-) diff --git a/server/src/repositories/incidents/IIncidentsRepository.ts b/server/src/repositories/incidents/IIncidentsRepository.ts index 00235de0d..dbdf2b05f 100644 --- a/server/src/repositories/incidents/IIncidentsRepository.ts +++ b/server/src/repositories/incidents/IIncidentsRepository.ts @@ -7,7 +7,8 @@ export interface IIncidentsRepository { findActiveByMonitorId(monitorId: string, teamId: string): Promise; findByTeamId( teamId: string, - dateRange: string, + startDate: Date, + endDate: Date, page: number, rowsPerPage: number, sortOrder?: string, diff --git a/server/src/repositories/incidents/MongoIncidentRepository.ts b/server/src/repositories/incidents/MongoIncidentRepository.ts index db0048fc7..ead783e11 100644 --- a/server/src/repositories/incidents/MongoIncidentRepository.ts +++ b/server/src/repositories/incidents/MongoIncidentRepository.ts @@ -77,8 +77,29 @@ class MongoIncidentRepository implements IIncidentsRepository { return this.toEntity(incident); }; - findByTeamId = async (teamId: string): Promise => { - throw new Error("Method not implemented."); + findByTeamId = async ( + teamId: string, + startDate: Date, + endDate: Date, + page: number, + rowsPerPage: number, + sortOrder?: string, + status?: string, + monitorId?: string, + resolutionType?: string + ): Promise => { + const matchStage: Record = { + teamId: new mongoose.Types.ObjectId(teamId), + ...(status !== undefined && { status: status }), + ...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }), + ...(resolutionType && { resolutionType }), + createdAt: { $gte: startDate, $lte: endDate }, + }; + const incidents = await IncidentModel.find(matchStage) + .sort({ createdAt: sortOrder === "asc" ? 1 : -1 }) + .skip(page * rowsPerPage) + .limit(rowsPerPage); + return this.mapDocuments(incidents); }; updateById = async (incidentId: string, teamId: string, patch: Partial) => { diff --git a/server/src/service/business/incidentService.ts b/server/src/service/business/incidentService.ts index a96c7923d..b2ad444d3 100644 --- a/server/src/service/business/incidentService.ts +++ b/server/src/service/business/incidentService.ts @@ -4,6 +4,15 @@ import { AppError } from "@/utils/AppError.js"; import type { IIncidentsRepository } from "@/repositories/index.js"; import type { Incident } from "@/types/index.js"; +const dateRangeLookup: Record = { + recent: new Date(new Date().setDate(new Date().getDate() - 2)), + hour: new Date(new Date().setHours(new Date().getHours() - 1)), + day: new Date(new Date().setDate(new Date().getDate() - 1)), + week: new Date(new Date().setDate(new Date().getDate() - 7)), + month: new Date(new Date().setMonth(new Date().getMonth() - 1)), + all: undefined, +}; + class IncidentService { static SERVICE_NAME = SERVICE_NAME; @@ -125,18 +134,38 @@ class IncidentService { const { sortOrder, dateRange, page, rowsPerPage, status, monitorId, resolutionType } = query || {}; - const result = await this.db.incidentModule.getIncidentsByTeam({ - teamId, - sortOrder, - dateRange, - page, - rowsPerPage, - status, - monitorId, - resolutionType, - }); + const startDate = dateRangeLookup[dateRange]; - return result; + const endDate = new Date(); + + const parsedPage = Number.isFinite(parseInt(page)) ? parseInt(page) : 0; + const parsedRowsPerPage = Number.isFinite(parseInt(rowsPerPage)) ? parseInt(rowsPerPage) : 20; + const parsedStatus = status === "true" ? "true" : status === "false" ? "false" : undefined; + + const res = await this.incidentsRepository.findByTeamId( + teamId, + startDate, + endDate, + parsedPage, + parsedRowsPerPage, + sortOrder, + parsedStatus, + monitorId, + resolutionType + ); + + // const result = await this.db.incidentModule.getIncidentsByTeam({ + // teamId, + // sortOrder, + // dateRange, + // page, + // rowsPerPage, + // status, + // monitorId, + // resolutionType, + // }); + + return res; } catch (error: any) { this.logger.error({ service: SERVICE_NAME, From 3cf7243c93fd4fc26f1db6f141c640b41a3aaa6d Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 20 Jan 2026 18:56:06 +0000 Subject: [PATCH 3/6] summary --- .../Components/IncidentTable/index.jsx | 9 +- .../Incidents2/hooks/useFetchIncidents.js | 3 +- client/src/Pages/Incidents2/index.jsx | 3 +- server/src/controllers/incidentController.ts | 16 +- .../incidents/IIncidentsRepository.ts | 9 +- .../incidents/MongoIncidentRepository.ts | 166 ++++++++++++++++-- .../src/service/business/incidentService.ts | 49 +++--- server/src/types/incident.ts | 29 +++ server/src/utils/{utils.js => utils.ts} | 6 +- 9 files changed, 237 insertions(+), 53 deletions(-) rename server/src/utils/{utils.js => utils.ts} (74%) diff --git a/client/src/Pages/Incidents2/Components/IncidentTable/index.jsx b/client/src/Pages/Incidents2/Components/IncidentTable/index.jsx index d613e15c7..670da4a81 100644 --- a/client/src/Pages/Incidents2/Components/IncidentTable/index.jsx +++ b/client/src/Pages/Incidents2/Components/IncidentTable/index.jsx @@ -15,6 +15,7 @@ import { useTranslation } from "react-i18next"; import { Button, Typography, useTheme } from "@mui/material"; const IncidentTable = ({ + monitors = [], incidents = [], incidentsCount = 0, isLoading = false, @@ -44,7 +45,11 @@ const IncidentTable = ({ { id: "monitorName", content: t("incidentsTableMonitorName"), - render: (row) => row.monitorName ?? "N/A", + render: (row) => { + console.log(monitors, row); + const monitor = monitors.find((monitor) => monitor.id === row.monitorId); + return monitor ? monitor.name : "N/A"; + }, }, { id: "status", @@ -130,7 +135,7 @@ const IncidentTable = ({ lineHeight: 1.2, }} onClick={() => { - handleResolveIncident(row._id); + handleResolveIncident(row.id); }} > {t("incidentsPage.incidentsTableActionResolveManually")} diff --git a/client/src/Pages/Incidents2/hooks/useFetchIncidents.js b/client/src/Pages/Incidents2/hooks/useFetchIncidents.js index ab22c42e0..54874bae7 100644 --- a/client/src/Pages/Incidents2/hooks/useFetchIncidents.js +++ b/client/src/Pages/Incidents2/hooks/useFetchIncidents.js @@ -45,9 +45,8 @@ const useFetchIncidents = () => { setNetworkError(false); const res = await networkService.getIncidentsByTeam(config); - setIncidents(res.data?.data?.incidents || []); - setIncidentsCount(res.data?.data?.incidentsCount || 0); + setIncidentsCount(res.data?.data?.count || 0); } catch (error) { setNetworkError(true); console.error(t("incidentsPage.errorFetchingIncidents"), error); diff --git a/client/src/Pages/Incidents2/index.jsx b/client/src/Pages/Incidents2/index.jsx index 2f31864bf..4e68279c5 100644 --- a/client/src/Pages/Incidents2/index.jsx +++ b/client/src/Pages/Incidents2/index.jsx @@ -88,7 +88,7 @@ const Incidents2 = () => { useEffect(() => { const lookup = monitors?.reduce((acc, monitor) => { acc[monitor.id] = { - _id: monitor.id, + id: monitor.id, name: monitor.name, type: monitor.type, }; @@ -132,6 +132,7 @@ const Incidents2 = () => { /> { try { - const summary = await this.incidentService.getIncidentSummary({ - teamId: req?.user?.teamId, - query: req?.query, - }); + const teamId = req.user?.teamId; + + if (!teamId) { + throw new AppError({ message: "Team ID is required", service: SERVICE_NAME, status: 400 }); + } + + const limit = req.query.limit ? parseInt(req.query.limit as string, 10) : 10; + + const summary = await this.incidentService.getIncidentSummary(req?.user?.teamId, limit); return res.status(200).json({ success: true, diff --git a/server/src/repositories/incidents/IIncidentsRepository.ts b/server/src/repositories/incidents/IIncidentsRepository.ts index dbdf2b05f..7c2b0179e 100644 --- a/server/src/repositories/incidents/IIncidentsRepository.ts +++ b/server/src/repositories/incidents/IIncidentsRepository.ts @@ -1,4 +1,5 @@ import type { Incident } from "@/types/index.js"; +import type { IncidentSummary } from "@/types/index.js"; export interface IIncidentsRepository { // create create(incident: Partial): Promise; @@ -7,17 +8,19 @@ export interface IIncidentsRepository { findActiveByMonitorId(monitorId: string, teamId: string): Promise; findByTeamId( teamId: string, - startDate: Date, - endDate: Date, + startDate: Date | undefined, page: number, rowsPerPage: number, sortOrder?: string, - status?: string, + status?: boolean, monitorId?: string, resolutionType?: string ): Promise; + findSummaryByTeamId(teamId: string, limit?: number): Promise; + countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise; // update updateById(incidentId: string, teamId: string, updateData: Partial): Promise; // delete + // other } diff --git a/server/src/repositories/incidents/MongoIncidentRepository.ts b/server/src/repositories/incidents/MongoIncidentRepository.ts index ead783e11..10cb47213 100644 --- a/server/src/repositories/incidents/MongoIncidentRepository.ts +++ b/server/src/repositories/incidents/MongoIncidentRepository.ts @@ -1,6 +1,6 @@ import { IncidentModel } from "@/db/models/index.js"; import type { IncidentDocument } from "@/db/models/Incident.js"; -import type { Incident } from "@/types/index.js"; +import type { Incident, IncidentSummary } from "@/types/index.js"; import type { IIncidentsRepository } from "@/repositories/index.js"; import mongoose from "mongoose"; import { AppError } from "@/utils/AppError.js"; @@ -20,6 +20,32 @@ class MongoIncidentRepository implements IIncidentsRepository { return value instanceof Date ? value.toISOString() : new Date(value).toISOString(); }; + private buildMatchStage({ + teamId, + startDate, + status, + monitorId, + resolutionType, + }: { + teamId: string; + startDate: Date | undefined; + status?: boolean; + monitorId?: string; + resolutionType?: string; + }): Record { + const matchStage: Record = { + teamId: new mongoose.Types.ObjectId(teamId), + ...(status !== undefined && { status }), + ...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }), + ...(resolutionType && { resolutionType }), + }; + + if (startDate) { + matchStage.createdAt = { $gte: startDate }; + } + return matchStage; + } + protected toEntity = (doc: IncidentDocument): Incident => { return { id: this.toStringId(doc._id), @@ -79,22 +105,15 @@ class MongoIncidentRepository implements IIncidentsRepository { findByTeamId = async ( teamId: string, - startDate: Date, - endDate: Date, + startDate: Date | undefined, page: number, rowsPerPage: number, sortOrder?: string, - status?: string, + status?: boolean, monitorId?: string, resolutionType?: string ): Promise => { - const matchStage: Record = { - teamId: new mongoose.Types.ObjectId(teamId), - ...(status !== undefined && { status: status }), - ...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }), - ...(resolutionType && { resolutionType }), - createdAt: { $gte: startDate, $lte: endDate }, - }; + const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType }); const incidents = await IncidentModel.find(matchStage) .sort({ createdAt: sortOrder === "asc" ? 1 : -1 }) .skip(page * rowsPerPage) @@ -117,5 +136,130 @@ class MongoIncidentRepository implements IIncidentsRepository { } return this.toEntity(updatedIncident); }; + + countByTeamId = async ( + teamId: string, + startDate: Date | undefined, + status?: boolean, + monitorId?: string, + resolutionType?: string + ): Promise => { + const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType }); + return IncidentModel.countDocuments(matchStage); + }; + + findSummaryByTeamId = async (teamId: string, limit: number): Promise => { + const matchStage = { teamId: new mongoose.Types.ObjectId(teamId) }; + + const counts = await IncidentModel.aggregate([ + { $match: matchStage }, + { + $group: { + _id: "$status", + count: { $sum: 1 }, + manualResolutions: { + $sum: { $cond: [{ $eq: ["$resolutionType", "manual"] }, 1, 0] }, + }, + automaticResolutions: { + $sum: { $cond: [{ $eq: ["$resolutionType", "automatic"] }, 1, 0] }, + }, + }, + }, + ]); + + let total = 0; + let active = 0; + let manual = 0; + let automatic = 0; + + counts.forEach((item) => { + total += item.count; + if (item._id === true) { + active = item.count; + } + manual += item.manualResolutions; + automatic += item.automaticResolutions; + }); + + const resolutionTimeResult = await IncidentModel.aggregate([ + { $match: { ...matchStage, status: false, endTime: { $exists: true, $ne: null } } }, + { $project: { resolutionTime: { $subtract: ["$endTime", "$startTime"] } } }, + { $group: { _id: null, avgResolutionTime: { $avg: "$resolutionTime" } } }, + ]); + const avgResolutionTimeMs = resolutionTimeResult[0]?.avgResolutionTime || 0; + const avgResolutionTimeHours = Math.round((avgResolutionTimeMs / (1000 * 60 * 60) || 0) * 100) / 100; + + const monitorResult = await IncidentModel.aggregate([ + { $match: matchStage }, + { $group: { _id: "$monitorId", count: { $sum: 1 } } }, + { $sort: { count: -1 } }, + { $limit: 1 }, + { + $lookup: { + from: "monitors", + localField: "_id", + foreignField: "_id", + as: "monitor", + }, + }, + { $project: { monitorId: "$_id", count: 1, monitorName: { $arrayElemAt: ["$monitor.name", 0] } } }, + ]); + + const latestLimit = Math.max(1, Number.isFinite(Number(limit)) ? Number(limit) : 10); + const latestIncidents = await IncidentModel.aggregate([ + { $match: matchStage }, + { $sort: { createdAt: -1 } }, + { $limit: latestLimit }, + { + $lookup: { + from: "monitors", + localField: "monitorId", + foreignField: "_id", + as: "monitor", + }, + }, + { + $project: { + _id: 1, + monitorId: 1, + monitorName: { $arrayElemAt: ["$monitor.name", 0] }, + status: 1, + startTime: 1, + endTime: 1, + resolutionType: 1, + message: 1, + statusCode: 1, + createdAt: 1, + }, + }, + ]); + + return { + total, + totalActive: active, + totalManualResolutions: manual, + totalAutomaticResolutions: automatic, + avgResolutionTimeHours, + topMonitor: monitorResult[0] + ? { + monitorId: this.toStringId(monitorResult[0].monitorId), + monitorName: monitorResult[0].monitorName ?? null, + incidentCount: monitorResult[0].count, + } + : null, + latestIncidents: latestIncidents.map((incident) => ({ + id: this.toStringId(incident._id), + monitorId: this.toStringId(incident.monitorId), + monitorName: incident.monitorName ?? null, + status: incident.status, + startTime: this.toDateString(incident.startTime), + endTime: incident.endTime ? this.toDateString(incident.endTime) : null, + resolutionType: incident.resolutionType ?? null, + message: incident.message ?? null, + statusCode: incident.statusCode ?? null, + createdAt: this.toDateString(incident.createdAt), + })), + }; + }; } export default MongoIncidentRepository; diff --git a/server/src/service/business/incidentService.ts b/server/src/service/business/incidentService.ts index b2ad444d3..bc69eeed0 100644 --- a/server/src/service/business/incidentService.ts +++ b/server/src/service/business/incidentService.ts @@ -1,6 +1,7 @@ const SERVICE_NAME = "incidentService"; import type { Monitor } from "@/types/monitor.js"; import { AppError } from "@/utils/AppError.js"; +import { ParseBoolean } from "@/utils/utils.js"; import type { IIncidentsRepository } from "@/repositories/index.js"; import type { Incident } from "@/types/index.js"; @@ -136,16 +137,13 @@ class IncidentService { const startDate = dateRangeLookup[dateRange]; - const endDate = new Date(); - const parsedPage = Number.isFinite(parseInt(page)) ? parseInt(page) : 0; const parsedRowsPerPage = Number.isFinite(parseInt(rowsPerPage)) ? parseInt(rowsPerPage) : 20; - const parsedStatus = status === "true" ? "true" : status === "false" ? "false" : undefined; + const parsedStatus = typeof status === "undefined" ? undefined : ParseBoolean(status); - const res = await this.incidentsRepository.findByTeamId( + const incidents = await this.incidentsRepository.findByTeamId( teamId, startDate, - endDate, parsedPage, parsedRowsPerPage, sortOrder, @@ -154,18 +152,9 @@ class IncidentService { resolutionType ); - // const result = await this.db.incidentModule.getIncidentsByTeam({ - // teamId, - // sortOrder, - // dateRange, - // page, - // rowsPerPage, - // status, - // monitorId, - // resolutionType, - // }); + const count = await this.incidentsRepository.countByTeamId(teamId, startDate, parsedStatus, monitorId, resolutionType); - return res; + return { incidents, count }; } catch (error: any) { this.logger.error({ service: SERVICE_NAME, @@ -178,18 +167,14 @@ class IncidentService { } }; - getIncidentSummary = async ({ teamId, query }: { teamId: string; query?: any }) => { + getIncidentSummary = async (teamId: string, limit?: string) => { try { if (!teamId) { - throw this.errorService.createBadRequestError("No team ID in request"); + throw this.errorService.createBadRequestError(" team ID in request"); } - const { limit } = query || {}; - - const summary = await this.db.incidentModule.getIncidentSummary({ - teamId, - limit, - }); + const parsedLimit = limit && Number.isFinite(parseInt(limit, 10)) ? parseInt(limit, 10) : 10; + const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit); return summary; } catch (error: any) { @@ -256,7 +241,7 @@ class IncidentService { for (const item of resolveItems as any[]) { try { - await this.resolveIncident(item.monitor); + await this.resolveIncidentForMonitor(item.monitor); } catch (error: any) { this.logger.error({ service: SERVICE_NAME, @@ -378,6 +363,20 @@ class IncidentService { throw error; } }; + + private resolveIncidentForMonitor = async (monitor: Monitor) => { + if (!monitor?.id) { + return; + } + const incident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId); + if (!incident) { + return; + } + incident.status = false; + incident.endTime = new Date().toISOString(); + incident.resolutionType = "automatic"; + await this.incidentsRepository.updateById(incident.id, incident.teamId, incident); + }; } export default IncidentService; diff --git a/server/src/types/incident.ts b/server/src/types/incident.ts index 65186f08c..39dfb3d0d 100644 --- a/server/src/types/incident.ts +++ b/server/src/types/incident.ts @@ -18,3 +18,32 @@ export interface Incident { createdAt: string; updatedAt: string; } + +export interface IncidentSummaryTopMonitor { + monitorId: string; + monitorName: string | null; + incidentCount: number; +} + +export interface IncidentSummaryItem { + id: string; + monitorId: string; + monitorName: string | null; + status: boolean; + startTime: string; + endTime: string | null; + resolutionType: IncidentResolutionType; + message: string | null; + statusCode: number | null; + createdAt: string; +} + +export interface IncidentSummary { + total: number; + totalActive: number; + totalManualResolutions: number; + totalAutomaticResolutions: number; + avgResolutionTimeHours: number; + topMonitor: IncidentSummaryTopMonitor | null; + latestIncidents: IncidentSummaryItem[]; +} diff --git a/server/src/utils/utils.js b/server/src/utils/utils.ts similarity index 74% rename from server/src/utils/utils.js rename to server/src/utils/utils.ts index ee4ee1c6d..a82d8734f 100755 --- a/server/src/utils/utils.js +++ b/server/src/utils/utils.ts @@ -1,4 +1,4 @@ -const ParseBoolean = (value) => { +export const ParseBoolean = (value: boolean | string | null | undefined) => { if (value === true || value === "true") { return true; } else if (value === false || value === "false" || value === null || value === undefined) { @@ -6,7 +6,7 @@ const ParseBoolean = (value) => { } }; -const getTokenFromHeaders = (headers) => { +export const getTokenFromHeaders = (headers: Record) => { const authorizationHeader = headers.authorization; if (!authorizationHeader) throw new Error("No auth headers"); @@ -15,5 +15,3 @@ const getTokenFromHeaders = (headers) => { return parts[1]; }; - -export { ParseBoolean, getTokenFromHeaders }; From 7afdcb8ebcf058ba8232c7ba03251b4fe295b640 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 20 Jan 2026 19:01:50 +0000 Subject: [PATCH 4/6] fix query param --- server/src/controllers/incidentController.ts | 2 +- server/src/service/business/incidentService.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/server/src/controllers/incidentController.ts b/server/src/controllers/incidentController.ts index a94474c5a..93783b20c 100644 --- a/server/src/controllers/incidentController.ts +++ b/server/src/controllers/incidentController.ts @@ -19,7 +19,7 @@ class IncidentController { try { const result = await this.incidentService.getIncidentsByTeam({ teamId: req?.user?.teamId, - query: req?.query?.limit, + query: req?.query, }); return res.status(200).json({ diff --git a/server/src/service/business/incidentService.ts b/server/src/service/business/incidentService.ts index bc69eeed0..513f16b1e 100644 --- a/server/src/service/business/incidentService.ts +++ b/server/src/service/business/incidentService.ts @@ -134,7 +134,6 @@ class IncidentService { } const { sortOrder, dateRange, page, rowsPerPage, status, monitorId, resolutionType } = query || {}; - const startDate = dateRangeLookup[dateRange]; const parsedPage = Number.isFinite(parseInt(page)) ? parseInt(page) : 0; From 69d050ff6115a007c074e8fec36953ef2260fef3 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 20 Jan 2026 19:04:30 +0000 Subject: [PATCH 5/6] remove incidents from buffer --- .../src/service/business/incidentService.ts | 156 ------------------ .../service/infrastructure/bufferService.ts | 61 +------ 2 files changed, 1 insertion(+), 216 deletions(-) diff --git a/server/src/service/business/incidentService.ts b/server/src/service/business/incidentService.ts index 513f16b1e..82211bc4e 100644 --- a/server/src/service/business/incidentService.ts +++ b/server/src/service/business/incidentService.ts @@ -220,162 +220,6 @@ class IncidentService { throw error; } }; - - processIncidentsFromBuffer = async (incidentBufferItems: any[]) => { - try { - if (!incidentBufferItems || incidentBufferItems.length === 0) { - return; - } - - const createItems = []; - const resolveItems = []; - - for (const item of incidentBufferItems) { - if (item.action === "resolve") { - resolveItems.push(item); - } else { - createItems.push(item); - } - } - - for (const item of resolveItems as any[]) { - try { - await this.resolveIncidentForMonitor(item.monitor); - } catch (error: any) { - this.logger.error({ - service: SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: `Failed to resolve incident from buffer: ${error.message}`, - monitorId: item.monitor?._id, - stack: error.stack, - }); - } - } - - if (createItems.length === 0) { - return; - } - - const groupedByMonitor: Record = {}; - for (const item of createItems) { - if (!item.monitor || !item.monitor.id || !item.check || !item.check.id) { - this.logger.warn({ - service: SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: "Skipping item with missing monitor or check data", - item, - }); - continue; - } - - const monitorId = item.monitor.id.toString(); - if (!groupedByMonitor[monitorId]) { - groupedByMonitor[monitorId] = []; - } - groupedByMonitor[monitorId].push(item); - } - - const monitorIds = Object.keys(groupedByMonitor); - if (monitorIds.length === 0) { - return; - } - - const activeIncidents = await this.db.incidentModule.getActiveIncidentsByMonitors(monitorIds); - - const incidentsCreatedInFlush: Record = {}; - const checksToAddToIncidents = []; - const newIncidentsToCreate = []; - - for (const [monitorId, items] of Object.entries(groupedByMonitor)) { - const existingIncident = activeIncidents.get(monitorId) || incidentsCreatedInFlush[monitorId]; - - if (existingIncident) { - const incidentId = existingIncident._id ? existingIncident._id.toString() : existingIncident; - for (const item of items) { - checksToAddToIncidents.push({ - incidentId, - checkId: item.check.id.toString(), - }); - } - } else { - const firstItem = items[0]; - const incidentData = { - monitorId: firstItem.monitor.id, - teamId: firstItem.monitor.teamId, - type: firstItem.monitor.type, - startTime: new Date(), - status: true, - message: firstItem.check.message || null, - statusCode: firstItem.check.statusCode || null, - checks: [firstItem.check.id], - }; - - newIncidentsToCreate.push({ - incidentData, - monitorId, - remainingChecks: items.slice(1), // Checks restantes para agregar después - }); - } - } - - if (newIncidentsToCreate.length > 0) { - const incidentDataArray = newIncidentsToCreate.map((item) => item.incidentData); - await this.db.incidentModule.createIncidents(incidentDataArray); - - const createdIncidentsMap = await this.db.incidentModule.getActiveIncidentsByMonitors(newIncidentsToCreate.map((item) => item.monitorId)); - - for (const item of newIncidentsToCreate) { - const createdIncident = createdIncidentsMap.get(item.monitorId); - if (createdIncident && createdIncident._id) { - const incidentId = createdIncident._id.toString(); - incidentsCreatedInFlush[item.monitorId] = incidentId; - - for (const remainingItem of item.remainingChecks) { - checksToAddToIncidents.push({ - incidentId, - checkId: remainingItem.check.id, - }); - } - } - } - } - - if (checksToAddToIncidents.length > 0) { - await this.db.incidentModule.addChecksToIncidentsBatch(checksToAddToIncidents); - } - - this.logger.info({ - service: SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: `Processed ${incidentBufferItems.length} incident buffer items`, - created: newIncidentsToCreate.length, - checksAdded: checksToAddToIncidents.length, - resolved: resolveItems.length, - }); - } catch (error: any) { - this.logger.error({ - service: SERVICE_NAME, - method: "processIncidentsFromBuffer", - message: error.message, - stack: error.stack, - }); - throw error; - } - }; - - private resolveIncidentForMonitor = async (monitor: Monitor) => { - if (!monitor?.id) { - return; - } - const incident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId); - if (!incident) { - return; - } - incident.status = false; - incident.endTime = new Date().toISOString(); - incident.resolutionType = "automatic"; - await this.incidentsRepository.updateById(incident.id, incident.teamId, incident); - }; } export default IncidentService; diff --git a/server/src/service/infrastructure/bufferService.ts b/server/src/service/infrastructure/bufferService.ts index 0363aa362..89cd6a55f 100755 --- a/server/src/service/infrastructure/bufferService.ts +++ b/server/src/service/infrastructure/bufferService.ts @@ -7,21 +7,17 @@ class BufferService { static SERVICE_NAME = SERVICE_NAME; private BUFFER_TIMEOUT: number; private logger: any; - private incidentService: any; private SERVICE_NAME: string; private buffer: any[]; - private incidentBuffer: any[]; private bufferTimer: NodeJS.Timeout | null = null; private checksService: any; - constructor({ logger, incidentService, checkService }: { logger: any; incidentService: any; checkService: any }) { + constructor({ logger, checkService }: { logger: any; checkService: any }) { this.BUFFER_TIMEOUT = config.NODE_ENV === "development" ? 10 : 1000 * 60 * 1; // 1 minute this.logger = logger; - this.incidentService = incidentService; this.checksService = checkService; this.SERVICE_NAME = SERVICE_NAME; this.buffer = []; - this.incidentBuffer = []; this.scheduleNextFlush(); this.logger.info({ message: `Buffer service initialized, flushing every ${this.BUFFER_TIMEOUT / 1000}s`, @@ -47,28 +43,6 @@ class BufferService { } } - addIncidentToBuffer({ monitor, check, action = "create" }: { monitor: any; check: Check; action?: string }) { - try { - if (!monitor || !check) { - this.logger.warn({ - message: "Skipping incident buffer item: missing monitor or check", - service: this.SERVICE_NAME, - method: "addIncidentToBuffer", - }); - return; - } - - this.incidentBuffer.push({ monitor, check, action }); - } catch (error: any) { - this.logger.error({ - message: error.message, - service: this.SERVICE_NAME, - method: "addIncidentToBuffer", - stack: error.stack, - }); - } - } - removeCheckFromBuffer(checkToRemove: Check) { try { if (!checkToRemove) { @@ -141,40 +115,7 @@ class BufferService { }); } - try { - if (this.incidentBuffer.length > 0 && this.incidentService) { - await this.flushIncidentBuffer(); - } - } catch (error: any) { - this.logger.error({ - message: error.message, - service: this.SERVICE_NAME, - method: "flushBuffer", - stack: error.stack, - }); - } - this.buffer = []; - this.incidentBuffer = []; - } - - async flushIncidentBuffer() { - if (!this.incidentService || this.incidentBuffer.length === 0) { - return; - } - - try { - const itemsToProcess = [...this.incidentBuffer]; - await this.incidentService.processIncidentsFromBuffer(itemsToProcess); - } catch (error: any) { - this.logger.error({ - message: `Error flushing incident buffer: ${error.message}`, - service: this.SERVICE_NAME, - method: "flushIncidentBuffer", - stack: error.stack, - }); - throw error; - } } } From f6fd8729c37b9907ccaa3edb6e9a0a9411901531 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 20 Jan 2026 19:22:04 +0000 Subject: [PATCH 6/6] remove dependency --- server/src/config/services.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/src/config/services.ts b/server/src/config/services.ts index cbd58f2e9..74a261d05 100644 --- a/server/src/config/services.ts +++ b/server/src/config/services.ts @@ -222,7 +222,7 @@ export const initializeServices = async ({ checksRepository, }); - const bufferService = new BufferService({ logger, incidentService, checkService }); + const bufferService = new BufferService({ logger, checkService }); const statusService = new StatusService({ db, logger, buffer: bufferService, monitorsRepository });