reorg to domain and api
This commit is contained in:
1 parent
0fb210e9e1
commit
d022f7d849
190 files changed
+643
-830
No files matched your search
@@ -0,0 +1,11 @@
|
||||
import type { Settings, SettingsUpdate } from "@/domain/app-settings/app-settings.type.js";
|
||||
export interface ISettingsRepository {
|
||||
// create
|
||||
create(settings: Partial<Settings>): Promise<Settings>;
|
||||
// fetch
|
||||
findSingleton(): Promise<Settings | null>;
|
||||
// update
|
||||
update(settings: SettingsUpdate): Promise<Settings>;
|
||||
// delete
|
||||
deleteLegacy: () => Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { Settings, SettingsThresholds } from "@/domain/app-settings/app-settings.type.js";
|
||||
|
||||
interface AppSettingsDocument extends Omit<Settings, "id" | "createdAt" | "updatedAt"> {
|
||||
_id: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const thresholdsSchema = new Schema<SettingsThresholds>(
|
||||
{
|
||||
cpu: { type: Number },
|
||||
memory: { type: Number },
|
||||
disk: { type: Number },
|
||||
temperature: { type: Number },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const AppSettingsSchema = new Schema<AppSettingsDocument>(
|
||||
{
|
||||
checkTTL: { type: Number, default: 30 },
|
||||
language: { type: String, default: "gb" },
|
||||
jwtSecret: { type: String },
|
||||
pagespeedApiKey: { type: String },
|
||||
systemEmailHost: { type: String },
|
||||
systemEmailPort: { type: Number },
|
||||
systemEmailAddress: { type: String },
|
||||
systemEmailDisplayName: { type: String },
|
||||
systemEmailPassword: { type: String },
|
||||
systemEmailUser: { type: String },
|
||||
systemEmailConnectionHost: { type: String, default: "localhost" },
|
||||
systemEmailTLSServername: { type: String },
|
||||
systemEmailSecure: { type: Boolean, default: false },
|
||||
systemEmailPool: { type: Boolean, default: false },
|
||||
systemEmailIgnoreTLS: { type: Boolean, default: false },
|
||||
systemEmailRequireTLS: { type: Boolean, default: false },
|
||||
systemEmailRejectUnauthorized: { type: Boolean, default: true },
|
||||
showURL: { type: Boolean, default: false },
|
||||
singleton: { type: Boolean, required: true, unique: true, default: true },
|
||||
version: { type: Number, default: 1 },
|
||||
globalThresholds: { type: thresholdsSchema },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
const AppSettingsModel = model<AppSettingsDocument>("AppSettings", AppSettingsSchema);
|
||||
|
||||
export type { AppSettingsDocument };
|
||||
export { AppSettingsModel };
|
||||
export default AppSettingsModel;
|
||||
@@ -0,0 +1,99 @@
|
||||
import mongoose, { type UpdateQuery } from "mongoose";
|
||||
import { ISettingsRepository } from "@/domain/app-settings/app-settings-repository.interface.js";
|
||||
import type { Settings, SettingsUpdate } from "@/domain/app-settings/app-settings.type.js";
|
||||
import { AppSettingsModel, type AppSettingsDocument } from "@/domain/app-settings/app-settings.model.js";
|
||||
|
||||
class MongoSettingsRepository implements ISettingsRepository {
|
||||
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: AppSettingsDocument): Settings => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
checkTTL: doc.checkTTL,
|
||||
language: doc.language,
|
||||
jwtSecret: doc.jwtSecret ?? undefined,
|
||||
pagespeedApiKey: doc.pagespeedApiKey ?? undefined,
|
||||
systemEmailHost: doc.systemEmailHost ?? undefined,
|
||||
systemEmailPort: doc.systemEmailPort ?? undefined,
|
||||
systemEmailAddress: doc.systemEmailAddress ?? undefined,
|
||||
systemEmailPassword: doc.systemEmailPassword ?? undefined,
|
||||
systemEmailUser: doc.systemEmailUser ?? undefined,
|
||||
systemEmailConnectionHost: doc.systemEmailConnectionHost ?? undefined,
|
||||
systemEmailTLSServername: doc.systemEmailTLSServername ?? undefined,
|
||||
systemEmailSecure: doc.systemEmailSecure ?? false,
|
||||
systemEmailPool: doc.systemEmailPool ?? false,
|
||||
systemEmailIgnoreTLS: doc.systemEmailIgnoreTLS ?? false,
|
||||
systemEmailRequireTLS: doc.systemEmailRequireTLS ?? false,
|
||||
systemEmailRejectUnauthorized: doc.systemEmailRejectUnauthorized ?? true,
|
||||
showURL: doc.showURL ?? false,
|
||||
singleton: doc.singleton,
|
||||
version: doc.version ?? 1,
|
||||
globalThresholds: doc.globalThresholds ?? undefined,
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (settings: Partial<Settings>) => {
|
||||
const newSettings = await AppSettingsModel.create(settings);
|
||||
return this.toEntity(newSettings);
|
||||
};
|
||||
|
||||
findSingleton = async () => {
|
||||
const settings = await AppSettingsModel.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
|
||||
if (!settings) {
|
||||
return null;
|
||||
}
|
||||
return this.toEntity(settings);
|
||||
};
|
||||
|
||||
update = async (settings: SettingsUpdate) => {
|
||||
const $set: Record<string, unknown> = {};
|
||||
const $unset: Record<string, string> = {};
|
||||
|
||||
// Iterate through settings and separate into $set and $unset
|
||||
Object.entries(settings).forEach(([key, value]) => {
|
||||
if (value === undefined || value === null) {
|
||||
$unset[key] = "";
|
||||
} else {
|
||||
$set[key] = value;
|
||||
}
|
||||
});
|
||||
|
||||
const update: UpdateQuery<AppSettingsDocument> = {
|
||||
...(Object.keys($set).length > 0 && { $set }),
|
||||
...(Object.keys($unset).length > 0 && { $unset }),
|
||||
};
|
||||
|
||||
await AppSettingsModel.findOneAndUpdate({}, update, {
|
||||
upsert: true,
|
||||
});
|
||||
|
||||
const updatedSettings = await AppSettingsModel.findOneAndUpdate({}, update, {
|
||||
upsert: true,
|
||||
new: true,
|
||||
projection: "-__v -_id -createdAt -updatedAt -singleton",
|
||||
});
|
||||
|
||||
return this.toEntity(updatedSettings);
|
||||
};
|
||||
|
||||
deleteLegacy = async () => {
|
||||
const res = await AppSettingsModel.deleteMany({ version: { $exists: false } });
|
||||
return res.deletedCount > 0;
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoSettingsRepository;
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
import { ISettingsRepository } from "@/domain/app-settings/app-settings-repository.interface.js";
|
||||
import { Settings, SettingsUpdate, type DbType, type QueueMode, type QueueType } from "@/domain/app-settings/app-settings.type.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { ValidatedEnv } from "@/config/envValidation.js";
|
||||
import type { StringValue } from "ms";
|
||||
const SERVICE_NAME = "SettingsService";
|
||||
|
||||
export type EnvConfig = {
|
||||
jwtSecret: string;
|
||||
jwtTTL: StringValue;
|
||||
nodeEnv: string;
|
||||
logLevel: string;
|
||||
clientHost: string;
|
||||
dbConnectionString: string;
|
||||
dbType: DbType;
|
||||
queueType: QueueType;
|
||||
queueMode: QueueMode;
|
||||
statusPageThemesEnabled: boolean;
|
||||
};
|
||||
|
||||
export interface ISettingsService {
|
||||
readonly serviceName: string;
|
||||
loadSettings(): EnvConfig;
|
||||
getSettings(): EnvConfig;
|
||||
areStatusPageThemesEnabled(): boolean;
|
||||
getDBSettings(): Promise<Settings>;
|
||||
updateDbSettings(newSettings: SettingsUpdate): Promise<Settings>;
|
||||
}
|
||||
|
||||
export class SettingsService implements ISettingsService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private settings: EnvConfig;
|
||||
private settingsRepository: ISettingsRepository | null = null;
|
||||
|
||||
constructor(env: ValidatedEnv) {
|
||||
this.settings = {
|
||||
jwtSecret: env.JWT_SECRET,
|
||||
jwtTTL: env.TOKEN_TTL as StringValue,
|
||||
nodeEnv: env.NODE_ENV,
|
||||
logLevel: env.LOG_LEVEL,
|
||||
clientHost: env.CLIENT_HOST,
|
||||
dbConnectionString: env.DB_CONNECTION_STRING,
|
||||
dbType: env.DB_TYPE,
|
||||
queueType: env.QUEUE_TYPE,
|
||||
queueMode: env.QUEUE_MODE,
|
||||
statusPageThemesEnabled: env.STATUS_PAGE_THEMES_ENABLED,
|
||||
};
|
||||
}
|
||||
|
||||
setRepository(settingsRepository: ISettingsRepository) {
|
||||
this.settingsRepository = settingsRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return SettingsService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
loadSettings() {
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
getSettings() {
|
||||
return this.settings;
|
||||
}
|
||||
|
||||
areStatusPageThemesEnabled() {
|
||||
return this.settings.statusPageThemesEnabled;
|
||||
}
|
||||
|
||||
private getRepository(): ISettingsRepository {
|
||||
if (!this.settingsRepository) {
|
||||
throw new AppError({
|
||||
message: "Settings repository not initialized. Call setRepository() after DB connect.",
|
||||
status: 500,
|
||||
service: SERVICE_NAME,
|
||||
});
|
||||
}
|
||||
return this.settingsRepository;
|
||||
}
|
||||
|
||||
updateDbSettings = async (newSettings: SettingsUpdate) => {
|
||||
return await this.getRepository().update(newSettings);
|
||||
};
|
||||
|
||||
getDBSettings = async () => {
|
||||
const repo = this.getRepository();
|
||||
// Remove any old settings
|
||||
await repo.deleteLegacy();
|
||||
|
||||
let settings = await repo.findSingleton();
|
||||
if (settings === null) {
|
||||
await repo.create({});
|
||||
settings = await repo.findSingleton();
|
||||
}
|
||||
|
||||
if (!settings) {
|
||||
throw new AppError({ message: "Settings not found", status: 500 });
|
||||
}
|
||||
|
||||
return settings;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
export const DbTypes = ["mongodb"] as const;
|
||||
export type DbType = (typeof DbTypes)[number];
|
||||
|
||||
export const QueueTypes = ["lessSimpleQueue", "superSimpleQueue"] as const;
|
||||
export type QueueType = (typeof QueueTypes)[number];
|
||||
|
||||
export const QueueModes = ["primary", "worker"] as const;
|
||||
export type QueueMode = (typeof QueueModes)[number];
|
||||
|
||||
export interface SettingsThresholds {
|
||||
cpu?: number;
|
||||
memory?: number;
|
||||
disk?: number;
|
||||
temperature?: number;
|
||||
}
|
||||
|
||||
export type SettingsUpdate = {
|
||||
[K in keyof Settings]?: Settings[K] | null;
|
||||
};
|
||||
|
||||
export interface Settings {
|
||||
id: string;
|
||||
checkTTL: number;
|
||||
language: string;
|
||||
jwtSecret?: string;
|
||||
pagespeedApiKey?: string;
|
||||
systemEmailHost?: string;
|
||||
systemEmailPort?: number;
|
||||
systemEmailAddress?: string;
|
||||
systemEmailDisplayName?: string;
|
||||
systemEmailPassword?: string;
|
||||
systemEmailUser?: string;
|
||||
systemEmailConnectionHost?: string;
|
||||
systemEmailTLSServername?: string;
|
||||
systemEmailSecure: boolean;
|
||||
systemEmailPool: boolean;
|
||||
systemEmailIgnoreTLS: boolean;
|
||||
systemEmailRequireTLS: boolean;
|
||||
systemEmailRejectUnauthorized: boolean;
|
||||
showURL: boolean;
|
||||
singleton: boolean;
|
||||
version: number;
|
||||
globalThresholds?: SettingsThresholds;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export type EmailTransportConfig = Pick<
|
||||
Settings,
|
||||
| "systemEmailHost"
|
||||
| "systemEmailPort"
|
||||
| "systemEmailAddress"
|
||||
| "systemEmailDisplayName"
|
||||
| "systemEmailPassword"
|
||||
| "systemEmailUser"
|
||||
| "systemEmailConnectionHost"
|
||||
| "systemEmailTLSServername"
|
||||
| "systemEmailSecure"
|
||||
| "systemEmailPool"
|
||||
| "systemEmailIgnoreTLS"
|
||||
| "systemEmailRequireTLS"
|
||||
| "systemEmailRejectUnauthorized"
|
||||
>;
|
||||
@@ -0,0 +1,294 @@
|
||||
import { Schema, model, Types } from "mongoose";
|
||||
import { MonitorTypes, type MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import type {
|
||||
Check,
|
||||
CheckAudits,
|
||||
CheckCaptureInfo,
|
||||
CheckCpuInfo,
|
||||
CheckDiskInfo,
|
||||
CheckErrorInfo,
|
||||
CheckHostInfo,
|
||||
CheckMemoryInfo,
|
||||
CheckMetadata,
|
||||
CheckNetworkInterfaceInfo,
|
||||
GotTimings,
|
||||
ILighthouseAudit,
|
||||
} from "@/domain/checks/check.type.js";
|
||||
|
||||
type CheckMetadataDocument = Omit<CheckMetadata, "monitorId" | "teamId"> & {
|
||||
monitorId: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
type: MonitorType;
|
||||
};
|
||||
|
||||
type CheckDocumentBase = Omit<Check, "id" | "metadata" | "createdAt" | "updatedAt"> & {
|
||||
metadata: CheckMetadataDocument;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
interface CheckDocument extends CheckDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
const timingPhasesSchema = new Schema<GotTimings["phases"]>(
|
||||
{
|
||||
wait: { type: Number, default: 0 },
|
||||
dns: { type: Number, default: 0 },
|
||||
tcp: { type: Number, default: 0 },
|
||||
tls: { type: Number, default: 0 },
|
||||
request: { type: Number, default: 0 },
|
||||
firstByte: { type: Number, default: 0 },
|
||||
download: { type: Number, default: 0 },
|
||||
total: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const timingsSchema = new Schema<GotTimings>(
|
||||
{
|
||||
start: { type: Number, default: 0 },
|
||||
socket: { type: Number, default: 0 },
|
||||
lookup: { type: Number, default: 0 },
|
||||
connect: { type: Number, default: 0 },
|
||||
secureConnect: { type: Number, default: 0 },
|
||||
upload: { type: Number, default: 0 },
|
||||
response: { type: Number, default: 0 },
|
||||
end: { type: Number, default: 0 },
|
||||
phases: {
|
||||
type: timingPhasesSchema,
|
||||
default: () => ({}),
|
||||
},
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const cpuSchema = new Schema<CheckCpuInfo>(
|
||||
{
|
||||
physical_core: { type: Number, default: 0 },
|
||||
logical_core: { type: Number, default: 0 },
|
||||
frequency: { type: Number, default: 0 },
|
||||
current_frequency: { type: Number, default: 0 },
|
||||
temperature: { type: [Number], default: [] },
|
||||
free_percent: { type: Number, default: 0 },
|
||||
usage_percent: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const memorySchema = new Schema<CheckMemoryInfo>(
|
||||
{
|
||||
total_bytes: { type: Number, default: 0 },
|
||||
available_bytes: { type: Number, default: 0 },
|
||||
used_bytes: { type: Number, default: 0 },
|
||||
usage_percent: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const diskSchema = new Schema<CheckDiskInfo>(
|
||||
{
|
||||
device: { type: String, default: "" },
|
||||
mountpoint: { type: String, default: "" },
|
||||
total_bytes: { type: Number, default: 0 },
|
||||
free_bytes: { type: Number, default: 0 },
|
||||
used_bytes: { type: Number, default: 0 },
|
||||
usage_percent: { type: Number, default: 0 },
|
||||
total_inodes: { type: Number, default: 0 },
|
||||
free_inodes: { type: Number, default: 0 },
|
||||
used_inodes: { type: Number, default: 0 },
|
||||
inodes_usage_percent: { type: Number, default: 0 },
|
||||
read_bytes: { type: Number, default: 0 },
|
||||
write_bytes: { type: Number, default: 0 },
|
||||
read_time: { type: Number, default: 0 },
|
||||
write_time: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const hostSchema = new Schema<CheckHostInfo>(
|
||||
{
|
||||
os: { type: String, default: "" },
|
||||
platform: { type: String, default: "" },
|
||||
kernel_version: { type: String, default: "" },
|
||||
pretty_name: { type: String, default: "" },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const errorSchema = new Schema<CheckErrorInfo>(
|
||||
{
|
||||
metric: { type: [String], default: [] },
|
||||
err: { type: String, default: "" },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const captureSchema = new Schema<CheckCaptureInfo>(
|
||||
{
|
||||
version: { type: String, default: "" },
|
||||
mode: { type: String, default: "" },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const networkInterfaceSchema = new Schema<CheckNetworkInterfaceInfo>(
|
||||
{
|
||||
name: { type: String, default: "" },
|
||||
bytes_sent: { type: Number, default: 0 },
|
||||
bytes_recv: { type: Number, default: 0 },
|
||||
packets_sent: { type: Number, default: 0 },
|
||||
packets_recv: { type: Number, default: 0 },
|
||||
err_in: { type: Number, default: 0 },
|
||||
err_out: { type: Number, default: 0 },
|
||||
drop_in: { type: Number, default: 0 },
|
||||
drop_out: { type: Number, default: 0 },
|
||||
fifo_in: { type: Number, default: 0 },
|
||||
fifo_out: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const lighthouseAuditSchema = new Schema<ILighthouseAudit>(
|
||||
{
|
||||
id: { type: String },
|
||||
title: { type: String },
|
||||
score: { type: Number },
|
||||
displayValue: { type: String },
|
||||
numericValue: { type: Number },
|
||||
numericUnit: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const auditsSchema = new Schema<CheckAudits>(
|
||||
{
|
||||
cls: { type: lighthouseAuditSchema, default: undefined },
|
||||
si: { type: lighthouseAuditSchema, default: undefined },
|
||||
fcp: { type: lighthouseAuditSchema, default: undefined },
|
||||
lcp: { type: lighthouseAuditSchema, default: undefined },
|
||||
tbt: { type: lighthouseAuditSchema, default: undefined },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const metadataSchema = new Schema<CheckMetadataDocument>(
|
||||
{
|
||||
monitorId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Monitor",
|
||||
required: true,
|
||||
immutable: true,
|
||||
index: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
required: true,
|
||||
immutable: true,
|
||||
index: true,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: MonitorTypes,
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const CheckSchema = new Schema<CheckDocument>(
|
||||
{
|
||||
metadata: {
|
||||
type: metadataSchema,
|
||||
required: true,
|
||||
},
|
||||
status: {
|
||||
type: Boolean,
|
||||
index: true,
|
||||
},
|
||||
responseTime: {
|
||||
type: Number,
|
||||
},
|
||||
timings: {
|
||||
type: timingsSchema,
|
||||
default: undefined,
|
||||
},
|
||||
statusCode: {
|
||||
type: Number,
|
||||
index: true,
|
||||
},
|
||||
message: {
|
||||
type: String,
|
||||
},
|
||||
|
||||
cpu: {
|
||||
type: cpuSchema,
|
||||
default: () => ({}),
|
||||
},
|
||||
memory: {
|
||||
type: memorySchema,
|
||||
default: () => ({}),
|
||||
},
|
||||
disk: {
|
||||
type: [diskSchema],
|
||||
default: () => [],
|
||||
},
|
||||
host: {
|
||||
type: hostSchema,
|
||||
default: () => ({}),
|
||||
},
|
||||
errors: {
|
||||
type: [errorSchema],
|
||||
default: () => [],
|
||||
},
|
||||
capture: {
|
||||
type: captureSchema,
|
||||
default: () => ({}),
|
||||
},
|
||||
net: {
|
||||
type: [networkInterfaceSchema],
|
||||
default: () => [],
|
||||
},
|
||||
accessibility: {
|
||||
type: Number,
|
||||
},
|
||||
bestPractices: {
|
||||
type: Number,
|
||||
},
|
||||
seo: {
|
||||
type: Number,
|
||||
},
|
||||
performance: {
|
||||
type: Number,
|
||||
},
|
||||
audits: {
|
||||
type: auditsSchema,
|
||||
default: undefined,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
strict: false,
|
||||
suppressReservedKeysWarning: true,
|
||||
timeseries: {
|
||||
timeField: "createdAt",
|
||||
metaField: "metadata",
|
||||
granularity: "seconds",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
CheckSchema.index({ "metadata.monitorId": 1, createdAt: -1 });
|
||||
CheckSchema.index({ "metadata.monitorId": 1, createdAt: 1 });
|
||||
CheckSchema.index({ createdAt: 1 });
|
||||
CheckSchema.index({ "metadata.teamId": 1, createdAt: -1 });
|
||||
CheckSchema.index({ "metadata.monitorId": 1, "metadata.type": 1, createdAt: -1 });
|
||||
CheckSchema.index({ "metadata.teamId": 1, status: 1, createdAt: -1 });
|
||||
|
||||
const CheckModel = model<CheckDocument>("Check", CheckSchema);
|
||||
|
||||
export type { CheckDocument, CheckMetadataDocument };
|
||||
export { CheckModel };
|
||||
export default CheckModel;
|
||||
@@ -0,0 +1,51 @@
|
||||
import type {
|
||||
Check,
|
||||
ChecksQueryResult,
|
||||
ChecksSummary,
|
||||
HardwareChecksResult,
|
||||
PageSpeedChecksResult,
|
||||
UptimeChecksResult,
|
||||
} from "@/domain/checks/check.type.js";
|
||||
import type { MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import type { LatestChecksMap } from "@/domain/checks/check.repository.mongo.js";
|
||||
|
||||
export interface IChecksRepository {
|
||||
// create
|
||||
create(check: Check): Promise<Check>;
|
||||
createChecks(checks: Check[]): Promise<Check[]>;
|
||||
|
||||
// single fetch
|
||||
// collection fetch
|
||||
findByMonitorId(
|
||||
monitorId: string,
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
filter: string | undefined,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
status: boolean | undefined
|
||||
): Promise<ChecksQueryResult>;
|
||||
findByTeamId(
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
filter: string | undefined,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
teamId: string
|
||||
): Promise<ChecksQueryResult>;
|
||||
findLatestByMonitorIds(monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap>;
|
||||
findByDateRangeAndMonitorId(
|
||||
monitorId: string,
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
dateString: string,
|
||||
options?: { type?: MonitorType }
|
||||
): Promise<UptimeChecksResult | HardwareChecksResult | PageSpeedChecksResult>;
|
||||
findSummaryByTeamId(teamId: string, dateRange: string): Promise<ChecksSummary>;
|
||||
// update
|
||||
//delete
|
||||
deleteByMonitorId(monitorId: string): Promise<number>;
|
||||
deleteByTeamId(teamId: string): Promise<number>;
|
||||
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
|
||||
deleteOlderThan(date: Date): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,791 @@
|
||||
import { IChecksRepository } from "@/domain/checks/check.repository.interface.js";
|
||||
import type {
|
||||
Check,
|
||||
CheckAudits,
|
||||
CheckCaptureInfo,
|
||||
CheckCpuInfo,
|
||||
CheckDiskInfo,
|
||||
CheckErrorInfo,
|
||||
CheckHostInfo,
|
||||
CheckMemoryInfo,
|
||||
CheckMetadata,
|
||||
CheckNetworkInterfaceInfo,
|
||||
GotTimings,
|
||||
} from "@/domain/checks/check.type.js";
|
||||
import type { MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import { CheckModel, type CheckDocument } from "@/domain/checks/check.model.js";
|
||||
import mongoose from "mongoose";
|
||||
import { getDateForRange } from "@/utils/dataUtils.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
|
||||
const SERVICE_NAME = "StatusService";
|
||||
|
||||
export type LatestChecksMap = Record<string, Check[]>;
|
||||
type DateRange = { start: Date; end: Date };
|
||||
type HardwareUpChecks = { totalChecks: number };
|
||||
|
||||
class MongoChecksRepository implements IChecksRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private logger: ILogger;
|
||||
constructor(logger: ILogger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
private toEntity = (doc: CheckDocument): Check => {
|
||||
const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value);
|
||||
};
|
||||
|
||||
const toDateString = (value?: Date | string | null): string => {
|
||||
if (!value) {
|
||||
return new Date(0).toISOString();
|
||||
}
|
||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||
};
|
||||
|
||||
const mapTimings = (timings?: GotTimings): GotTimings => {
|
||||
const phases = timings?.phases ?? {
|
||||
wait: 0,
|
||||
dns: 0,
|
||||
tcp: 0,
|
||||
tls: 0,
|
||||
request: 0,
|
||||
firstByte: 0,
|
||||
download: 0,
|
||||
total: 0,
|
||||
};
|
||||
|
||||
return {
|
||||
start: timings?.start ?? 0,
|
||||
socket: timings?.socket ?? 0,
|
||||
lookup: timings?.lookup ?? 0,
|
||||
connect: timings?.connect ?? 0,
|
||||
secureConnect: timings?.secureConnect ?? 0,
|
||||
upload: timings?.upload ?? 0,
|
||||
response: timings?.response ?? 0,
|
||||
end: timings?.end ?? 0,
|
||||
phases,
|
||||
};
|
||||
};
|
||||
|
||||
const mapCpu = (cpu?: CheckCpuInfo): CheckCpuInfo => ({
|
||||
physical_core: cpu?.physical_core ?? 0,
|
||||
logical_core: cpu?.logical_core ?? 0,
|
||||
frequency: cpu?.frequency ?? 0,
|
||||
temperature: cpu?.temperature ?? [],
|
||||
free_percent: cpu?.free_percent ?? 0,
|
||||
usage_percent: cpu?.usage_percent ?? 0,
|
||||
});
|
||||
|
||||
const mapMemory = (memory?: CheckMemoryInfo): CheckMemoryInfo => ({
|
||||
total_bytes: memory?.total_bytes ?? 0,
|
||||
available_bytes: memory?.available_bytes ?? 0,
|
||||
used_bytes: memory?.used_bytes ?? 0,
|
||||
usage_percent: memory?.usage_percent ?? 0,
|
||||
});
|
||||
|
||||
const mapHost = (host?: CheckHostInfo): CheckHostInfo => ({
|
||||
os: host?.os ?? "",
|
||||
platform: host?.platform ?? "",
|
||||
kernel_version: host?.kernel_version ?? "",
|
||||
});
|
||||
|
||||
const mapCapture = (capture?: CheckCaptureInfo): CheckCaptureInfo => ({
|
||||
version: capture?.version ?? "",
|
||||
mode: capture?.mode ?? "",
|
||||
});
|
||||
|
||||
const mapDisks = (disks?: CheckDiskInfo[]): CheckDiskInfo[] =>
|
||||
(disks ?? []).map((disk) => ({
|
||||
device: disk?.device ?? "",
|
||||
mountpoint: disk?.mountpoint ?? "",
|
||||
total_bytes: disk?.total_bytes ?? 0,
|
||||
free_bytes: disk?.free_bytes ?? 0,
|
||||
used_bytes: disk?.used_bytes ?? 0,
|
||||
usage_percent: disk?.usage_percent ?? 0,
|
||||
total_inodes: disk?.total_inodes ?? 0,
|
||||
free_inodes: disk?.free_inodes ?? 0,
|
||||
used_inodes: disk?.used_inodes ?? 0,
|
||||
inodes_usage_percent: disk?.inodes_usage_percent ?? 0,
|
||||
read_bytes: disk?.read_bytes ?? 0,
|
||||
write_bytes: disk?.write_bytes ?? 0,
|
||||
read_time: disk?.read_time ?? 0,
|
||||
write_time: disk?.write_time ?? 0,
|
||||
}));
|
||||
|
||||
const mapErrors = (errors?: CheckErrorInfo[]): CheckErrorInfo[] =>
|
||||
(errors ?? []).map((error) => ({
|
||||
metric: error?.metric ?? [],
|
||||
err: error?.err ?? "",
|
||||
}));
|
||||
|
||||
const mapNet = (net?: CheckNetworkInterfaceInfo[]): CheckNetworkInterfaceInfo[] =>
|
||||
(net ?? []).map((iface) => ({
|
||||
name: iface?.name ?? "",
|
||||
bytes_sent: iface?.bytes_sent ?? 0,
|
||||
bytes_recv: iface?.bytes_recv ?? 0,
|
||||
packets_sent: iface?.packets_sent ?? 0,
|
||||
packets_recv: iface?.packets_recv ?? 0,
|
||||
err_in: iface?.err_in ?? 0,
|
||||
err_out: iface?.err_out ?? 0,
|
||||
drop_in: iface?.drop_in ?? 0,
|
||||
drop_out: iface?.drop_out ?? 0,
|
||||
fifo_in: iface?.fifo_in ?? 0,
|
||||
fifo_out: iface?.fifo_out ?? 0,
|
||||
}));
|
||||
|
||||
const mapAudits = (audits?: CheckAudits): CheckAudits | undefined => {
|
||||
if (!audits) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
cls: audits.cls,
|
||||
si: audits.si,
|
||||
fcp: audits.fcp,
|
||||
lcp: audits.lcp,
|
||||
tbt: audits.tbt,
|
||||
};
|
||||
};
|
||||
|
||||
const mapMetadata = (metadata: CheckDocument["metadata"]): CheckMetadata => ({
|
||||
monitorId: toStringId(metadata.monitorId),
|
||||
teamId: toStringId(metadata.teamId),
|
||||
type: metadata.type,
|
||||
});
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
metadata: mapMetadata(doc.metadata),
|
||||
status: doc.status ?? false,
|
||||
responseTime: doc.responseTime ?? 0,
|
||||
timings: mapTimings(doc.timings),
|
||||
statusCode: doc.statusCode ?? 0,
|
||||
message: doc.message ?? "",
|
||||
cpu: mapCpu(doc.cpu),
|
||||
memory: mapMemory(doc.memory),
|
||||
disk: mapDisks(doc.disk),
|
||||
host: mapHost(doc.host),
|
||||
errors: mapErrors(doc.errors),
|
||||
capture: mapCapture(doc.capture),
|
||||
net: mapNet(doc.net),
|
||||
accessibility: doc.accessibility,
|
||||
bestPractices: doc.bestPractices,
|
||||
seo: doc.seo,
|
||||
performance: doc.performance,
|
||||
audits: mapAudits(doc.audits),
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: CheckDocument[]): Check[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
private toDocument = (check: Partial<Check>): CheckDocument => {
|
||||
// Map id to _id for MongoDB storage
|
||||
const { id, metadata, ...rest } = check;
|
||||
if (!metadata || !metadata.monitorId || !metadata.teamId) {
|
||||
throw new Error(`Check must have valid metadata with monitorId and teamId. Got: ${JSON.stringify({ id, metadata })}`);
|
||||
}
|
||||
return {
|
||||
_id: id ? new mongoose.Types.ObjectId(id) : new mongoose.Types.ObjectId(),
|
||||
metadata: {
|
||||
monitorId: new mongoose.Types.ObjectId(metadata.monitorId),
|
||||
teamId: new mongoose.Types.ObjectId(metadata.teamId),
|
||||
type: metadata.type,
|
||||
},
|
||||
...rest,
|
||||
} as unknown as CheckDocument;
|
||||
};
|
||||
|
||||
create = async (check: Check) => {
|
||||
const savedCheck = await CheckModel.create(check);
|
||||
return this.toEntity(savedCheck);
|
||||
};
|
||||
|
||||
createChecks = async (checks: Check[]) => {
|
||||
const docs = checks.map((check) => this.toDocument(check));
|
||||
const inserted = await CheckModel.insertMany(docs);
|
||||
return this.mapDocuments(inserted as unknown as CheckDocument[]);
|
||||
};
|
||||
|
||||
findByMonitorId = async (
|
||||
monitorId: string,
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
filter: string | undefined,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
status: boolean | undefined
|
||||
) => {
|
||||
// Match
|
||||
const matchStage: Record<string, unknown> = {
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
...(typeof status !== "undefined" && { status }),
|
||||
...(getDateForRange(dateRange) && {
|
||||
createdAt: {
|
||||
$gte: getDateForRange(dateRange),
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
if (filter !== undefined) {
|
||||
switch (filter) {
|
||||
case "all":
|
||||
break;
|
||||
case "up":
|
||||
matchStage.status = true;
|
||||
break;
|
||||
case "down":
|
||||
matchStage.status = false;
|
||||
break;
|
||||
case "resolve":
|
||||
matchStage.status = false;
|
||||
matchStage.statusCode = 5000;
|
||||
break;
|
||||
default:
|
||||
this.logger.warn({
|
||||
message: "invalid filter",
|
||||
service: SERVICE_NAME,
|
||||
method: "getChecks",
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//Sort
|
||||
const convertedSortOrder = sortOrder === "asc" ? 1 : -1;
|
||||
|
||||
// Pagination
|
||||
let skip = 0;
|
||||
if (page && rowsPerPage) {
|
||||
skip = page * rowsPerPage;
|
||||
}
|
||||
|
||||
const [checksCount, checks] = await Promise.all([
|
||||
CheckModel.countDocuments(matchStage),
|
||||
CheckModel.find(matchStage).sort({ createdAt: convertedSortOrder }).skip(skip).limit(rowsPerPage).lean() as Promise<CheckDocument[]>,
|
||||
]);
|
||||
|
||||
return { checksCount, checks: this.mapDocuments(checks) };
|
||||
};
|
||||
|
||||
findByTeamId = async (sortOrder: string, dateRange: string, filter: string, page: number, rowsPerPage: number, teamId: string) => {
|
||||
const matchStage: Record<string, unknown> = {
|
||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||
...(getDateForRange(dateRange) && {
|
||||
createdAt: {
|
||||
$gte: getDateForRange(dateRange),
|
||||
},
|
||||
}),
|
||||
};
|
||||
// Add filter to match stage
|
||||
if (filter !== undefined) {
|
||||
switch (filter) {
|
||||
case "all":
|
||||
break;
|
||||
case "up":
|
||||
matchStage.status = true;
|
||||
break;
|
||||
case "down":
|
||||
matchStage.status = false;
|
||||
break;
|
||||
case "resolve":
|
||||
matchStage.status = false;
|
||||
matchStage.statusCode = 5000;
|
||||
break;
|
||||
default:
|
||||
this.logger.warn({
|
||||
message: "invalid filter",
|
||||
service: SERVICE_NAME,
|
||||
method: "getChecksByTeam",
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const parsedSortOrder = sortOrder === "asc" ? 1 : -1;
|
||||
|
||||
// pagination
|
||||
let skip = 0;
|
||||
if (page && rowsPerPage) {
|
||||
skip = page * rowsPerPage;
|
||||
}
|
||||
|
||||
const [checksCount, checks] = await Promise.all([
|
||||
CheckModel.countDocuments(matchStage),
|
||||
CheckModel.find(matchStage).sort({ createdAt: parsedSortOrder }).skip(skip).limit(rowsPerPage).lean() as Promise<CheckDocument[]>,
|
||||
]);
|
||||
|
||||
return { checksCount, checks: this.mapDocuments(checks) };
|
||||
};
|
||||
|
||||
findLatestByMonitorIds = async (monitorIds: string[], options?: { limitPerMonitor?: number }): Promise<LatestChecksMap> => {
|
||||
if (monitorIds.length === 0) {
|
||||
return {};
|
||||
}
|
||||
const limitPerMonitor = options?.limitPerMonitor ?? 25;
|
||||
const dateFilter = new Date(Date.now() - 24 * 60 * 60 * 1000);
|
||||
const results = await Promise.all(
|
||||
monitorIds.map(async (monitorId) => {
|
||||
const docs = await CheckModel.find({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
createdAt: { $gte: dateFilter },
|
||||
})
|
||||
.sort({ createdAt: -1 })
|
||||
.limit(limitPerMonitor)
|
||||
.lean();
|
||||
return { monitorId, docs };
|
||||
})
|
||||
);
|
||||
|
||||
const mapped = results.reduce<LatestChecksMap>((acc, { monitorId, docs }) => {
|
||||
acc[monitorId] = docs.map((doc: CheckDocument) => this.toEntity(doc));
|
||||
return acc;
|
||||
}, {});
|
||||
return mapped;
|
||||
};
|
||||
|
||||
findByDateRangeAndMonitorId = async (monitorId: string, startDate: Date, endDate: Date, dateString: string, options?: { type?: MonitorType }) => {
|
||||
const monitorObjectId = new mongoose.Types.ObjectId(monitorId);
|
||||
if (options?.type === "hardware") {
|
||||
return this.findHardwareDateRangeChecks(monitorObjectId, startDate, endDate, dateString);
|
||||
}
|
||||
if (options?.type === "pagespeed") {
|
||||
return this.findPageSpeedDateRangeChecks(monitorObjectId, startDate, endDate, dateString);
|
||||
}
|
||||
return this.findUptimeDateRangeChecks(options?.type ?? "http", monitorObjectId, startDate, endDate, dateString);
|
||||
};
|
||||
|
||||
findSummaryByTeamId = async (teamId: string, dateRange: string) => {
|
||||
const baseMatch = {
|
||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||
...(getDateForRange(dateRange) && {
|
||||
createdAt: {
|
||||
$gte: getDateForRange(dateRange),
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const [totalResult, downResult] = await Promise.all([
|
||||
CheckModel.countDocuments(baseMatch),
|
||||
CheckModel.countDocuments({ ...baseMatch, status: false }),
|
||||
]);
|
||||
|
||||
return {
|
||||
totalChecks: totalResult,
|
||||
downChecks: downResult,
|
||||
};
|
||||
};
|
||||
|
||||
deleteByMonitorId = async (monitorId: string): Promise<number> => {
|
||||
const result = await CheckModel.deleteMany({ "metadata.monitorId": new mongoose.Types.ObjectId(monitorId) });
|
||||
return result.deletedCount;
|
||||
};
|
||||
|
||||
deleteByTeamId = async (teamId: string) => {
|
||||
const deleteResult = await CheckModel.deleteMany({ "metadata.teamId": teamId });
|
||||
return deleteResult.deletedCount;
|
||||
};
|
||||
|
||||
deleteByMonitorIdsNotIn = async (monitorIds: string[]): Promise<number> => {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const result = await CheckModel.deleteMany({ "metadata.monitorId": { $nin: objectIds } });
|
||||
return result.deletedCount ?? 0;
|
||||
};
|
||||
|
||||
deleteOlderThan = async (cutoffDate: Date, batchDays: number = 30): Promise<number> => {
|
||||
// Find the oldest check that is older than the cutoff
|
||||
const oldest = await CheckModel.findOne({ createdAt: { $lt: cutoffDate } })
|
||||
.sort({ createdAt: 1 })
|
||||
.select({ createdAt: 1 });
|
||||
if (!oldest?.createdAt) return 0;
|
||||
|
||||
let totalDeleted = 0;
|
||||
let batchStart = new Date(oldest.createdAt);
|
||||
const batchMs = batchDays * 24 * 60 * 60 * 1000;
|
||||
|
||||
// Delete in 30 day chunks until we reach the cutoff
|
||||
while (batchStart < cutoffDate) {
|
||||
// Advance startTime by batchMs to get to the end of last batch
|
||||
const nextStart = batchStart.getTime() + batchMs;
|
||||
const batchEnd = new Date(Math.min(nextStart, cutoffDate.getTime()));
|
||||
const result = await CheckModel.deleteMany({
|
||||
createdAt: { $gte: batchStart, $lt: batchEnd },
|
||||
});
|
||||
totalDeleted += result.deletedCount ?? 0;
|
||||
batchStart = batchEnd;
|
||||
}
|
||||
|
||||
return totalDeleted;
|
||||
};
|
||||
private findUptimeDateRangeChecks = async (
|
||||
monitorType: Exclude<MonitorType, "hardware" | "pagespeed">,
|
||||
monitorObjectId: mongoose.Types.ObjectId,
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
dateString: string
|
||||
) => {
|
||||
const matchStage = {
|
||||
"metadata.monitorId": monitorObjectId,
|
||||
createdAt: { $gte: startDate, $lte: endDate },
|
||||
};
|
||||
const [result] = await CheckModel.aggregate([
|
||||
{ $match: matchStage },
|
||||
{ $sort: { createdAt: 1 } },
|
||||
{
|
||||
$facet: {
|
||||
uptimePercentage: [
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
upChecks: { $sum: { $cond: [{ $eq: ["$status", true] }, 1, 0] } },
|
||||
totalChecks: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
percentage: {
|
||||
$cond: [{ $eq: ["$totalChecks", 0] }, 0, { $divide: ["$upChecks", "$totalChecks"] }],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
groupedAvgResponseTime: [
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
},
|
||||
},
|
||||
],
|
||||
groupedChecks: [
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
$dateToString: { format: dateString, date: "$createdAt" },
|
||||
},
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
totalChecks: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: 1 } },
|
||||
{ $project: { bucketDate: "$_id", avgResponseTime: 1, totalChecks: 1, _id: 0 } },
|
||||
],
|
||||
groupedUpChecks: [
|
||||
{ $match: { status: true } },
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
$dateToString: { format: dateString, date: "$createdAt" },
|
||||
},
|
||||
totalChecks: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: 1 } },
|
||||
{ $project: { bucketDate: "$_id", avgResponseTime: 1, totalChecks: 1, _id: 0 } },
|
||||
],
|
||||
groupedDownChecks: [
|
||||
{ $match: { status: false } },
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
$dateToString: { format: dateString, date: "$createdAt" },
|
||||
},
|
||||
totalChecks: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: 1 } },
|
||||
{ $project: { bucketDate: "$_id", avgResponseTime: 1, totalChecks: 1, _id: 0 } },
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const uptimePercentage = result?.uptimePercentage?.[0]?.percentage ?? 0;
|
||||
const avgResponseTime = result?.groupedAvgResponseTime?.[0]?.avgResponseTime ?? 0;
|
||||
|
||||
return {
|
||||
monitorType,
|
||||
groupedChecks: result?.groupedChecks ?? [],
|
||||
groupedUpChecks: result?.groupedUpChecks ?? [],
|
||||
groupedDownChecks: result?.groupedDownChecks ?? [],
|
||||
uptimePercentage,
|
||||
avgResponseTime,
|
||||
};
|
||||
};
|
||||
|
||||
private findHardwareDateRangeChecks = async (monitorObjectId: mongoose.Types.ObjectId, startDate: Date, endDate: Date, dateString: string) => {
|
||||
const monitorId = monitorObjectId.toHexString();
|
||||
const dates = { start: startDate, end: endDate };
|
||||
const [aggregateDataDoc, upChecksDoc, hardwareMetrics] = await Promise.all([
|
||||
this.getHardwareTotalChecks(monitorId, dates),
|
||||
this.getHardwareUpChecks(monitorId, dates),
|
||||
this.getHardwareStats(monitorId, dates, dateString),
|
||||
]);
|
||||
|
||||
const aggregateData = {
|
||||
totalChecks: aggregateDataDoc ?? 0,
|
||||
};
|
||||
|
||||
const upChecks = {
|
||||
totalChecks: upChecksDoc?.totalChecks ?? 0,
|
||||
};
|
||||
|
||||
const checks = (hardwareMetrics ?? []).map((metric) => ({
|
||||
bucketDate: metric._id,
|
||||
avgCpuUsage: metric.avgCpuUsage ?? 0,
|
||||
avgMemoryUsage: metric.avgMemoryUsage ?? 0,
|
||||
avgTemperature: metric.avgTemperature ?? [],
|
||||
disks: (metric.disks ?? []).map((disk: { [key: string]: number | string | undefined }) => ({
|
||||
name: disk?.name ?? "",
|
||||
readSpeed: disk?.readSpeed ?? 0,
|
||||
writeSpeed: disk?.writeSpeed ?? 0,
|
||||
totalBytes: disk?.totalBytes ?? 0,
|
||||
freeBytes: disk?.freeBytes ?? 0,
|
||||
usagePercent: disk?.usagePercent ?? 0,
|
||||
})),
|
||||
net: (metric.net ?? []).map((iface: { [key: string]: number | string | undefined }) => ({
|
||||
name: iface?.name ?? "",
|
||||
bytesSentPerSecond: iface?.bytesSentPerSecond ?? 0,
|
||||
deltaBytesRecv: iface?.deltaBytesRecv ?? 0,
|
||||
deltaPacketsSent: iface?.deltaPacketsSent ?? 0,
|
||||
deltaPacketsRecv: iface?.deltaPacketsRecv ?? 0,
|
||||
deltaErrIn: iface?.deltaErrIn ?? 0,
|
||||
deltaErrOut: iface?.deltaErrOut ?? 0,
|
||||
deltaDropIn: iface?.deltaDropIn ?? 0,
|
||||
deltaDropOut: iface?.deltaDropOut ?? 0,
|
||||
deltaFifoIn: iface?.deltaFifoIn ?? 0,
|
||||
deltaFifoOut: iface?.deltaFifoOut ?? 0,
|
||||
})),
|
||||
}));
|
||||
|
||||
return {
|
||||
monitorType: "hardware" as const,
|
||||
aggregateData,
|
||||
upChecks,
|
||||
checks,
|
||||
};
|
||||
};
|
||||
|
||||
private findPageSpeedDateRangeChecks = async (monitorObjectId: mongoose.Types.ObjectId, startDate: Date, endDate: Date, dateString: string) => {
|
||||
const matchStage = {
|
||||
"metadata.monitorId": monitorObjectId,
|
||||
createdAt: { $gte: startDate, $lte: endDate },
|
||||
};
|
||||
|
||||
const [result] = await CheckModel.aggregate([
|
||||
{ $match: matchStage },
|
||||
{ $sort: { createdAt: 1 } },
|
||||
{
|
||||
$facet: {
|
||||
groupedChecks: [
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
$dateToString: { format: dateString, date: "$createdAt" },
|
||||
},
|
||||
avgPerformance: { $avg: "$performance" },
|
||||
avgAccessibility: { $avg: "$accessibility" },
|
||||
avgBestPractices: { $avg: "$bestPractices" },
|
||||
avgSeo: { $avg: "$seo" },
|
||||
totalChecks: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: 1 } },
|
||||
{
|
||||
$project: {
|
||||
bucketDate: "$_id",
|
||||
performance: "$avgPerformance",
|
||||
accessibility: "$avgAccessibility",
|
||||
bestPractices: "$avgBestPractices",
|
||||
seo: "$avgSeo",
|
||||
totalChecks: 1,
|
||||
_id: 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
return {
|
||||
monitorType: "pagespeed" as const,
|
||||
groupedChecks: result?.groupedChecks ?? [],
|
||||
};
|
||||
};
|
||||
|
||||
private getHardwareTotalChecks = async (monitorId: string, dates: DateRange): Promise<number> => {
|
||||
return await CheckModel.countDocuments({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
"metadata.type": "hardware",
|
||||
createdAt: { $gte: dates.start, $lte: dates.end },
|
||||
});
|
||||
};
|
||||
|
||||
private getHardwareUpChecks = async (monitorId: string, dates: DateRange): Promise<HardwareUpChecks> => {
|
||||
const count = await CheckModel.countDocuments({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
"metadata.type": "hardware",
|
||||
createdAt: { $gte: dates.start, $lte: dates.end },
|
||||
status: true,
|
||||
});
|
||||
return { totalChecks: count };
|
||||
};
|
||||
|
||||
private getHardwareStats = async (monitorId: string, dates: DateRange, dateString: string) => {
|
||||
return await CheckModel.aggregate([
|
||||
{
|
||||
$match: {
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
"metadata.type": "hardware",
|
||||
createdAt: { $gte: dates.start, $lte: dates.end },
|
||||
},
|
||||
},
|
||||
{ $sort: { createdAt: 1 } },
|
||||
{
|
||||
$group: {
|
||||
_id: { $dateToString: { format: dateString, date: "$createdAt" } },
|
||||
avgCpuUsage: { $avg: "$cpu.usage_percent" },
|
||||
avgMemoryUsage: { $avg: "$memory.usage_percent" },
|
||||
avgTemperatures: { $push: { $ifNull: ["$cpu.temperature", [0]] } },
|
||||
disks: { $push: "$disk" },
|
||||
net: { $push: "$net" },
|
||||
createdAts: { $push: "$createdAt" },
|
||||
sampleDoc: { $first: "$$ROOT" },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
_id: 1,
|
||||
avgCpuUsage: 1,
|
||||
avgMemoryUsage: 1,
|
||||
avgTemperature: {
|
||||
$map: {
|
||||
input: { $range: [0, { $size: { $ifNull: [{ $arrayElemAt: ["$avgTemperatures", 0] }, [0]] } }] },
|
||||
as: "idx",
|
||||
in: { $avg: { $map: { input: "$avgTemperatures", as: "t", in: { $arrayElemAt: ["$$t", "$$idx"] } } } },
|
||||
},
|
||||
},
|
||||
disks: {
|
||||
$map: {
|
||||
input: { $range: [0, { $size: { $ifNull: ["$sampleDoc.disk", []] } }] },
|
||||
as: "dIdx",
|
||||
in: {
|
||||
name: { $concat: ["disk", { $toString: "$$dIdx" }] },
|
||||
readSpeed: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.read_bytes", "$$dIdx"] } } } },
|
||||
writeSpeed: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.write_bytes", "$$dIdx"] } } } },
|
||||
totalBytes: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.total_bytes", "$$dIdx"] } } } },
|
||||
freeBytes: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.free_bytes", "$$dIdx"] } } } },
|
||||
usagePercent: { $avg: { $map: { input: "$disks", as: "dA", in: { $arrayElemAt: ["$$dA.usage_percent", "$$dIdx"] } } } },
|
||||
},
|
||||
},
|
||||
},
|
||||
net: {
|
||||
$map: {
|
||||
input: { $range: [0, { $size: { $ifNull: ["$sampleDoc.net", []] } }] },
|
||||
as: "nIdx",
|
||||
in: {
|
||||
name: { $arrayElemAt: ["$sampleDoc.net.name", "$$nIdx"] },
|
||||
bytesSentPerSecond: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.bytes_sent" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.bytes_sent" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaBytesRecv: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.bytes_recv" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.bytes_recv" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaPacketsSent: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.packets_sent" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.packets_sent" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaPacketsRecv: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.packets_recv" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.packets_recv" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaErrIn: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.err_in" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.err_in" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaErrOut: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.err_out" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.err_out" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaDropIn: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.drop_in" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.drop_in" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
deltaDropOut: {
|
||||
$let: {
|
||||
vars: {
|
||||
tDiff: { $divide: [{ $subtract: [{ $last: "$createdAts" }, { $first: "$createdAts" }] }, 1000] },
|
||||
f: { $arrayElemAt: [{ $map: { input: { $first: "$net" }, as: "i", in: "$$i.drop_out" } }, "$$nIdx"] },
|
||||
l: { $arrayElemAt: [{ $map: { input: { $last: "$net" }, as: "i", in: "$$i.drop_out" } }, "$$nIdx"] },
|
||||
},
|
||||
in: { $cond: [{ $gt: ["$$tDiff", 0] }, { $divide: [{ $subtract: ["$$l", "$$f"] }, "$$tDiff"] }, 0] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: 1 } },
|
||||
]);
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoChecksRepository;
|
||||
@@ -0,0 +1,213 @@
|
||||
import { Types } from "mongoose";
|
||||
import { IChecksRepository } from "@/domain/checks/check.repository.interface.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { Check, CheckErrorInfo, ChecksQueryResult, ChecksSummary, ILighthouseAudit } from "@/domain/checks/check.type.js";
|
||||
import type { MonitorPayloadMap, MonitorStatusResponse } from "@/types/network.js";
|
||||
import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
|
||||
const SERVICE_NAME = "checkService";
|
||||
|
||||
export interface ICheckService {
|
||||
createChecks(checks: Check[]): Promise<Check[]>;
|
||||
buildCheck(statusResponse: MonitorStatusResponse<MonitorPayloadMap[keyof MonitorPayloadMap]>): Check | undefined;
|
||||
getChecksByMonitor(params: {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
sortOrder: string;
|
||||
dateRange: string;
|
||||
page: number;
|
||||
rowsPerPage: number;
|
||||
filter?: string;
|
||||
status?: boolean;
|
||||
}): Promise<ChecksQueryResult>;
|
||||
getChecksByTeam(params: {
|
||||
teamId: string;
|
||||
sortOrder: string;
|
||||
dateRange: string;
|
||||
page: number;
|
||||
rowsPerPage: number;
|
||||
filter?: string;
|
||||
}): Promise<ChecksQueryResult>;
|
||||
getChecksSummaryByTeamId(params: { teamId: string; dateRange: string }): Promise<ChecksSummary>;
|
||||
deleteChecks(params: { monitorId: string; teamId: string }): Promise<number>;
|
||||
deleteChecksByTeamId(params: { teamId: string }): Promise<number>;
|
||||
deleteOlderThan(date: Date): Promise<number>;
|
||||
}
|
||||
|
||||
export class CheckService implements ICheckService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private checksRepository: IChecksRepository;
|
||||
private logger: ILogger;
|
||||
constructor(monitorsRepository: IMonitorsRepository, logger: ILogger, checksRepository: IChecksRepository) {
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.logger = logger;
|
||||
this.checksRepository = checksRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return CheckService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
createChecks = async (checks: Check[]) => {
|
||||
return this.checksRepository.createChecks(checks);
|
||||
};
|
||||
|
||||
buildCheck = (statusResponse: MonitorStatusResponse<MonitorPayloadMap[keyof MonitorPayloadMap]>): Check | undefined => {
|
||||
const { monitorId, teamId, type, status, responseTime, code, message, payload, timings } = statusResponse;
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const check: Check = {
|
||||
id: new Types.ObjectId().toString(),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
metadata: {
|
||||
monitorId,
|
||||
teamId,
|
||||
type,
|
||||
},
|
||||
status,
|
||||
statusCode: code,
|
||||
responseTime: responseTime || 0,
|
||||
timings: timings,
|
||||
message,
|
||||
};
|
||||
|
||||
if (type === "pagespeed") {
|
||||
const pageSpeedPayload = payload as PageSpeedStatusPayload | undefined;
|
||||
if (!pageSpeedPayload) {
|
||||
this.logger.warn({
|
||||
message: "Failed to build check",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildCheck",
|
||||
});
|
||||
return undefined;
|
||||
}
|
||||
const categories = pageSpeedPayload.lighthouseResult?.categories ?? {};
|
||||
const audits = pageSpeedPayload.lighthouseResult?.audits ?? {};
|
||||
const mapAudit = (audit: ILighthouseAudit | undefined) => {
|
||||
if (!audit || typeof audit !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
id: audit.id,
|
||||
title: audit.title,
|
||||
score: typeof audit.score === "number" ? audit.score : (audit.score ?? null),
|
||||
displayValue: audit.displayValue,
|
||||
numericValue: typeof audit.numericValue === "number" ? audit.numericValue : undefined,
|
||||
numericUnit: audit.numericUnit,
|
||||
};
|
||||
};
|
||||
check.accessibility = (categories.accessibility?.score || 0) * 100;
|
||||
check.bestPractices = (categories["best-practices"]?.score || 0) * 100;
|
||||
check.seo = (categories.seo?.score || 0) * 100;
|
||||
check.performance = (categories.performance?.score || 0) * 100;
|
||||
check.audits = {
|
||||
cls: mapAudit(audits["cumulative-layout-shift"]),
|
||||
si: mapAudit(audits["speed-index"]),
|
||||
fcp: mapAudit(audits["first-contentful-paint"]),
|
||||
lcp: mapAudit(audits["largest-contentful-paint"]),
|
||||
tbt: mapAudit(audits["total-blocking-time"]),
|
||||
};
|
||||
}
|
||||
|
||||
if (type === "hardware") {
|
||||
const hardwarePayload = payload as HardwareStatusPayload | undefined;
|
||||
const { cpu, memory, disk, host, net } = hardwarePayload?.data ?? {};
|
||||
const errorsSource = Array.isArray(hardwarePayload?.errors)
|
||||
? hardwarePayload.errors
|
||||
: (hardwarePayload?.errors as { errors?: CheckErrorInfo[] } | undefined)?.errors;
|
||||
check.cpu = cpu;
|
||||
check.memory = memory;
|
||||
check.disk = disk;
|
||||
check.host = host;
|
||||
check.errors = errorsSource;
|
||||
check.capture = hardwarePayload?.capture;
|
||||
check.net = net;
|
||||
}
|
||||
return check;
|
||||
};
|
||||
|
||||
getChecksByMonitor = async ({
|
||||
monitorId,
|
||||
teamId,
|
||||
sortOrder,
|
||||
dateRange,
|
||||
filter,
|
||||
page,
|
||||
rowsPerPage,
|
||||
status,
|
||||
}: {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
sortOrder: string;
|
||||
dateRange: string;
|
||||
page: number;
|
||||
rowsPerPage: number;
|
||||
status?: boolean;
|
||||
filter?: string;
|
||||
}) => {
|
||||
if (!monitorId) {
|
||||
throw new AppError({ message: "No monitor ID in request", service: SERVICE_NAME, method: "getChecksByMonitor", status: 400 });
|
||||
}
|
||||
if (!teamId) {
|
||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getChecksByMonitor", status: 400 });
|
||||
}
|
||||
|
||||
// For verification, throws an error if monitor doesn't belong to team
|
||||
await this.monitorsRepository.findById(monitorId, teamId);
|
||||
|
||||
const parsedPage = page ?? 0;
|
||||
const parsedRowsPerPage = rowsPerPage ?? 5;
|
||||
|
||||
const result = await this.checksRepository.findByMonitorId(monitorId, sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, status);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
getChecksByTeam = async ({
|
||||
teamId,
|
||||
sortOrder,
|
||||
dateRange,
|
||||
filter,
|
||||
page,
|
||||
rowsPerPage,
|
||||
}: {
|
||||
teamId: string;
|
||||
sortOrder: string;
|
||||
dateRange: string;
|
||||
page: number;
|
||||
rowsPerPage: number;
|
||||
filter?: string;
|
||||
}) => {
|
||||
const parsedPage = page ?? 0;
|
||||
const parsedRowsPerPage = rowsPerPage ?? 5;
|
||||
|
||||
const checkData = await this.checksRepository.findByTeamId(sortOrder, dateRange, filter, parsedPage, parsedRowsPerPage, teamId);
|
||||
return checkData;
|
||||
};
|
||||
|
||||
getChecksSummaryByTeamId = async ({ teamId, dateRange }: { teamId: string; dateRange: string }) => {
|
||||
const summary = await this.checksRepository.findSummaryByTeamId(teamId, dateRange);
|
||||
return summary;
|
||||
};
|
||||
|
||||
deleteChecks = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => {
|
||||
await this.monitorsRepository.findById(monitorId, teamId);
|
||||
|
||||
const deletedCount = await this.checksRepository.deleteByMonitorId(monitorId);
|
||||
return deletedCount;
|
||||
};
|
||||
deleteChecksByTeamId = async ({ teamId }: { teamId: string }) => {
|
||||
const deletedCount = await this.checksRepository.deleteByTeamId(teamId);
|
||||
return deletedCount;
|
||||
};
|
||||
|
||||
deleteOlderThan = async (date: Date) => {
|
||||
const deletedCount = await this.checksRepository.deleteOlderThan(date);
|
||||
return deletedCount;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import type { MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import type { Response } from "got";
|
||||
|
||||
export const CHECK_TTL_SENTINEL = 366;
|
||||
|
||||
export type GotTimings = Response["timings"];
|
||||
|
||||
export interface CheckMetadata {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
type: MonitorType;
|
||||
}
|
||||
|
||||
export interface CheckCpuInfo {
|
||||
physical_core?: number;
|
||||
logical_core?: number;
|
||||
frequency?: number;
|
||||
current_frequency?: number;
|
||||
temperature?: number[];
|
||||
free_percent?: number;
|
||||
usage_percent?: number;
|
||||
}
|
||||
|
||||
export interface CheckMemoryInfo {
|
||||
total_bytes?: number;
|
||||
available_bytes?: number;
|
||||
used_bytes?: number;
|
||||
usage_percent?: number;
|
||||
}
|
||||
|
||||
export interface CheckHostInfo {
|
||||
os?: string;
|
||||
platform?: string;
|
||||
kernel_version?: string;
|
||||
pretty_name?: string;
|
||||
}
|
||||
|
||||
export interface CheckCaptureInfo {
|
||||
version?: string;
|
||||
mode?: string;
|
||||
}
|
||||
|
||||
export interface CheckDiskInfo {
|
||||
device?: string;
|
||||
mountpoint?: string;
|
||||
total_bytes?: number;
|
||||
free_bytes?: number;
|
||||
used_bytes?: number;
|
||||
usage_percent?: number;
|
||||
total_inodes?: number;
|
||||
free_inodes?: number;
|
||||
used_inodes?: number;
|
||||
inodes_usage_percent?: number;
|
||||
read_bytes?: number;
|
||||
write_bytes?: number;
|
||||
read_time?: number;
|
||||
write_time?: number;
|
||||
}
|
||||
|
||||
export interface CheckErrorInfo {
|
||||
metric: string[];
|
||||
err: string;
|
||||
}
|
||||
|
||||
export interface CheckNetworkInterfaceInfo {
|
||||
name: string;
|
||||
bytes_sent: number;
|
||||
bytes_recv: number;
|
||||
packets_sent: number;
|
||||
packets_recv: number;
|
||||
err_in: number;
|
||||
err_out: number;
|
||||
drop_in: number;
|
||||
drop_out: number;
|
||||
fifo_in: number;
|
||||
fifo_out: number;
|
||||
}
|
||||
|
||||
export interface CheckAudits {
|
||||
cls?: ILighthouseAudit;
|
||||
si?: ILighthouseAudit;
|
||||
fcp?: ILighthouseAudit;
|
||||
lcp?: ILighthouseAudit;
|
||||
tbt?: ILighthouseAudit;
|
||||
}
|
||||
|
||||
export interface ILighthouseAudit {
|
||||
id?: string;
|
||||
title?: string;
|
||||
score?: number | null;
|
||||
displayValue?: string;
|
||||
numericValue?: number;
|
||||
numericUnit?: string;
|
||||
}
|
||||
|
||||
export interface Check {
|
||||
id: string;
|
||||
metadata: CheckMetadata;
|
||||
status: boolean;
|
||||
responseTime: number;
|
||||
timings?: GotTimings;
|
||||
statusCode: number;
|
||||
message: string;
|
||||
cpu?: CheckCpuInfo;
|
||||
memory?: CheckMemoryInfo;
|
||||
disk?: CheckDiskInfo[];
|
||||
host?: CheckHostInfo;
|
||||
errors?: CheckErrorInfo[];
|
||||
capture?: CheckCaptureInfo;
|
||||
net?: CheckNetworkInterfaceInfo[];
|
||||
accessibility?: number;
|
||||
bestPractices?: number;
|
||||
seo?: number;
|
||||
performance?: number;
|
||||
audits?: CheckAudits;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
export interface ChecksQueryResult {
|
||||
checksCount: number;
|
||||
checks: Check[];
|
||||
}
|
||||
|
||||
export interface PageSpeedChecksResult {
|
||||
monitorType: "pagespeed";
|
||||
groupedChecks: PageSpeedGroupedCheck[];
|
||||
}
|
||||
|
||||
export interface HardwareChecksResult {
|
||||
monitorType: "hardware";
|
||||
aggregateData: {
|
||||
totalChecks: number;
|
||||
};
|
||||
upChecks: {
|
||||
totalChecks: number;
|
||||
};
|
||||
checks: Array<{
|
||||
bucketDate: string;
|
||||
avgCpuUsage: number;
|
||||
avgMemoryUsage: number;
|
||||
avgTemperature: number[];
|
||||
disks: Array<{
|
||||
name: string;
|
||||
readSpeed: number;
|
||||
writeSpeed: number;
|
||||
totalBytes: number;
|
||||
freeBytes: number;
|
||||
usagePercent: number;
|
||||
}>;
|
||||
net: Array<{
|
||||
name: string;
|
||||
bytesSentPerSecond: number;
|
||||
deltaBytesRecv: number;
|
||||
deltaPacketsSent: number;
|
||||
deltaPacketsRecv: number;
|
||||
deltaErrIn: number;
|
||||
deltaErrOut: number;
|
||||
deltaDropIn: number;
|
||||
deltaDropOut: number;
|
||||
deltaFifoIn: number;
|
||||
deltaFifoOut: number;
|
||||
}>;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface GroupedCheck {
|
||||
bucketDate: string;
|
||||
avgResponseTime: number;
|
||||
totalChecks: number;
|
||||
}
|
||||
|
||||
export interface PageSpeedGroupedCheck {
|
||||
bucketDate: string;
|
||||
performance: number;
|
||||
accessibility: number;
|
||||
bestPractices: number;
|
||||
seo: number;
|
||||
totalChecks: number;
|
||||
}
|
||||
|
||||
export interface UptimeChecksResult {
|
||||
monitorType: Exclude<MonitorType, "hardware" | "pagespeed">;
|
||||
groupedChecks: GroupedCheck[];
|
||||
groupedUpChecks: GroupedCheck[];
|
||||
groupedDownChecks: GroupedCheck[];
|
||||
uptimePercentage: number;
|
||||
avgResponseTime: number;
|
||||
}
|
||||
|
||||
export interface ChecksSummary {
|
||||
totalChecks: number;
|
||||
downChecks: number;
|
||||
}
|
||||
|
||||
export interface HasResponseTime {
|
||||
responseTime: number;
|
||||
}
|
||||
|
||||
export type NormalizedCheck<T extends HasResponseTime = Check> = T & {
|
||||
originalResponseTime: number;
|
||||
};
|
||||
|
||||
export type NormalizedUptimeCheck<T extends GroupedCheck = GroupedCheck> = T & {
|
||||
originalAvgResponseTime: number;
|
||||
};
|
||||
|
||||
export type CheckSnapshot = Omit<Check, "metadata" | "updatedAt">;
|
||||
@@ -0,0 +1,145 @@
|
||||
import v8 from "v8";
|
||||
import os from "os";
|
||||
import { IDb } from "@/db/db.interface.js";
|
||||
import { Mongoose } from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
const SERVICE_NAME = "diagnosticService";
|
||||
|
||||
export interface CollectionDiagnostics {
|
||||
name: string;
|
||||
documentCount: number;
|
||||
storageSize: number;
|
||||
totalIndexSize: number;
|
||||
totalSize: number;
|
||||
bucketCount?: number;
|
||||
}
|
||||
|
||||
export interface MongoDiagnostics {
|
||||
readyState: number;
|
||||
host: string;
|
||||
port: number;
|
||||
dbName: string;
|
||||
totalSize: number;
|
||||
collections: CollectionDiagnostics[];
|
||||
}
|
||||
|
||||
export interface Diagnostics {
|
||||
osStats: { totalMemoryBytes: number };
|
||||
cpuUsage: { usagePercentage: number };
|
||||
v8HeapStats: {
|
||||
totalHeapSizeBytes: number;
|
||||
usedHeapSizeBytes: number;
|
||||
heapSizeLimitBytes: number;
|
||||
};
|
||||
eventLoopDelayMs: number;
|
||||
uptimeMs: number;
|
||||
mongoStats: MongoDiagnostics;
|
||||
}
|
||||
|
||||
export interface IDiagnosticService {
|
||||
getSystemStats(): Promise<Diagnostics>;
|
||||
}
|
||||
|
||||
export class DiagnosticService implements IDiagnosticService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
constructor(private db: IDb<Mongoose>) {
|
||||
/**
|
||||
* Performance Observer for monitoring system performance metrics.
|
||||
* Clears performance marks after each measurement to prevent memory leaks.
|
||||
*/
|
||||
const obs = new PerformanceObserver((items) => {
|
||||
items.getEntries();
|
||||
performance.clearMarks();
|
||||
});
|
||||
obs.observe({ entryTypes: ["measure"] });
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return DiagnosticService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
private getCPUUsagePercentage = async (): Promise<number> => {
|
||||
const startUsage = process.cpuUsage();
|
||||
const timingPeriod = 1000; // measured in ms
|
||||
await new Promise((resolve) => setTimeout(resolve, timingPeriod));
|
||||
const endUsage = process.cpuUsage(startUsage);
|
||||
return ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100;
|
||||
};
|
||||
|
||||
private getMongoDBStats = async (): Promise<MongoDiagnostics> => {
|
||||
const mongo = await this.db.getConnection();
|
||||
const db = mongo.connection.db;
|
||||
if (!db) {
|
||||
throw new AppError({ message: "Database connection is not available", service: SERVICE_NAME, method: "getMongoDBStats" });
|
||||
}
|
||||
|
||||
const dbStats = await db.stats();
|
||||
const rawCollections = await db.collections();
|
||||
|
||||
const collections: CollectionDiagnostics[] = await Promise.all(
|
||||
rawCollections
|
||||
.filter((collection) => !collection.collectionName.startsWith("system"))
|
||||
.map(async (collection) => {
|
||||
const stats = await db.command({ collStats: collection.collectionName });
|
||||
const documentCount = await db.collection(collection.collectionName).countDocuments({});
|
||||
const entry: CollectionDiagnostics = {
|
||||
name: collection.collectionName,
|
||||
documentCount,
|
||||
storageSize: stats.storageSize ?? 0,
|
||||
totalIndexSize: stats.totalIndexSize ?? 0,
|
||||
totalSize: stats.totalSize ?? (stats.storageSize ?? 0) + (stats.totalIndexSize ?? 0),
|
||||
};
|
||||
if (stats.timeseries?.bucketCount !== undefined) {
|
||||
entry.bucketCount = stats.timeseries.bucketCount;
|
||||
}
|
||||
return entry;
|
||||
})
|
||||
);
|
||||
|
||||
return {
|
||||
readyState: mongo.connection.readyState,
|
||||
host: mongo.connection.host,
|
||||
port: mongo.connection.port,
|
||||
dbName: mongo.connection.name,
|
||||
totalSize: dbStats.totalSize ?? (dbStats.storageSize ?? 0) + (dbStats.indexSize ?? 0),
|
||||
collections,
|
||||
};
|
||||
};
|
||||
|
||||
getSystemStats = async (): Promise<Diagnostics> => {
|
||||
const osStats = { totalMemoryBytes: os.totalmem() };
|
||||
|
||||
const cpuUsage = { usagePercentage: await this.getCPUUsagePercentage() };
|
||||
|
||||
const heapStats = v8.getHeapStatistics();
|
||||
const v8HeapStats = {
|
||||
totalHeapSizeBytes: heapStats.total_heap_size,
|
||||
usedHeapSizeBytes: heapStats.used_heap_size,
|
||||
heapSizeLimitBytes: heapStats.heap_size_limit,
|
||||
};
|
||||
|
||||
let eventLoopDelayMs = 0;
|
||||
performance.mark("start");
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
performance.mark("end");
|
||||
performance.measure("eventLoopDelay", "start", "end");
|
||||
const entries = performance.getEntriesByName("eventLoopDelay");
|
||||
if (entries.length > 0 && entries[0] !== undefined) {
|
||||
eventLoopDelayMs = entries[0].duration;
|
||||
}
|
||||
|
||||
const uptimeMs = process.uptime() * 1000;
|
||||
const mongoStats = await this.getMongoDBStats();
|
||||
|
||||
return {
|
||||
osStats,
|
||||
cpuUsage,
|
||||
v8HeapStats,
|
||||
eventLoopDelayMs,
|
||||
uptimeMs,
|
||||
mongoStats,
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import { DLQItemTypes, DLQItemStatuses, type DLQItem } from "@/domain/dlq/dlq.type.js";
|
||||
|
||||
export interface DLQItemDocument extends Omit<DLQItem, "id" | "monitorId" | "teamId" | "nextRetryAt" | "createdAt" | "updatedAt"> {
|
||||
_id: Types.ObjectId;
|
||||
monitorId: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
nextRetryAt: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const DLQItemSchema = new Schema<DLQItemDocument>(
|
||||
{
|
||||
type: {
|
||||
type: String,
|
||||
enum: DLQItemTypes,
|
||||
required: true,
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: DLQItemStatuses,
|
||||
default: "pending",
|
||||
},
|
||||
payload: {
|
||||
type: Schema.Types.Mixed,
|
||||
required: true,
|
||||
},
|
||||
monitorId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Monitor",
|
||||
required: true,
|
||||
immutable: true,
|
||||
index: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
required: true,
|
||||
immutable: true,
|
||||
index: true,
|
||||
},
|
||||
retryCount: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
maxRetries: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
},
|
||||
lastError: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
nextRetryAt: {
|
||||
type: Date,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
DLQItemSchema.index({ status: 1, nextRetryAt: 1 });
|
||||
DLQItemSchema.index({ teamId: 1, status: 1 });
|
||||
DLQItemSchema.index({ createdAt: 1 });
|
||||
|
||||
const DLQItemModel = model<DLQItemDocument>("DLQItem", DLQItemSchema);
|
||||
|
||||
export { DLQItemModel };
|
||||
export default DLQItemModel;
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { DLQItem, DLQItemStatus, DLQItemType } from "@/domain/dlq/dlq.type.js";
|
||||
|
||||
export interface DLQQueryFilters {
|
||||
type?: DLQItemType;
|
||||
status?: DLQItemStatus;
|
||||
page: number;
|
||||
rowsPerPage: number;
|
||||
}
|
||||
|
||||
export interface DLQStatusCount {
|
||||
status: DLQItemStatus;
|
||||
type: DLQItemType;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface IDLQRepository {
|
||||
// create
|
||||
create(item: Partial<DLQItem>): Promise<DLQItem>;
|
||||
// fetch
|
||||
findById(id: string): Promise<DLQItem | null>;
|
||||
findByTeamId(teamId: string, filters: DLQQueryFilters): Promise<DLQItem[]>;
|
||||
findRetryable(limit: number): Promise<DLQItem[]>;
|
||||
countByTeamId(teamId: string): Promise<number>;
|
||||
countByTeamIdGrouped(teamId: string): Promise<DLQStatusCount[]>;
|
||||
// update
|
||||
updateById(id: string, patch: Partial<DLQItem>): Promise<DLQItem>;
|
||||
// delete
|
||||
deleteById(id: string, teamId: string): Promise<number>;
|
||||
deleteOlderThan(date: Date): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import { DLQItemModel } from "@/domain/dlq/dlq.model.js";
|
||||
import type { DLQItemDocument } from "@/domain/dlq/dlq.model.js";
|
||||
import type { DLQItem } from "@/domain/dlq/dlq.type.js";
|
||||
import type { IDLQRepository, DLQQueryFilters, DLQStatusCount } from "@/domain/dlq/dlq.repository.interface.js";
|
||||
import mongoose from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
class MongoDLQRepository implements IDLQRepository {
|
||||
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: DLQItemDocument): DLQItem => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
type: doc.type,
|
||||
status: doc.status,
|
||||
payload: doc.payload,
|
||||
monitorId: this.toStringId(doc.monitorId),
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
retryCount: doc.retryCount,
|
||||
maxRetries: doc.maxRetries,
|
||||
lastError: doc.lastError,
|
||||
nextRetryAt: this.toDateString(doc.nextRetryAt),
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
protected mapDocuments = (documents: DLQItemDocument[] | DLQItemDocument | null): DLQItem[] => {
|
||||
if (!documents) {
|
||||
return [];
|
||||
}
|
||||
if (Array.isArray(documents)) {
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
}
|
||||
return [this.toEntity(documents)];
|
||||
};
|
||||
|
||||
async create(item: Partial<DLQItem>): Promise<DLQItem> {
|
||||
const newItem = await DLQItemModel.create(item);
|
||||
return this.toEntity(newItem);
|
||||
}
|
||||
|
||||
findById = async (id: string): Promise<DLQItem | null> => {
|
||||
const item = await DLQItemModel.findById(new mongoose.Types.ObjectId(id));
|
||||
return item ? this.toEntity(item) : null;
|
||||
};
|
||||
|
||||
findByTeamId = async (teamId: string, filters: DLQQueryFilters): Promise<DLQItem[]> => {
|
||||
const query: Record<string, unknown> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
};
|
||||
if (filters.type) {
|
||||
query.type = filters.type;
|
||||
}
|
||||
if (filters.status) {
|
||||
query.status = filters.status;
|
||||
}
|
||||
|
||||
const items = await DLQItemModel.find(query)
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(filters.page * filters.rowsPerPage)
|
||||
.limit(filters.rowsPerPage);
|
||||
return this.mapDocuments(items);
|
||||
};
|
||||
|
||||
findRetryable = async (limit: number): Promise<DLQItem[]> => {
|
||||
const items = await DLQItemModel.find({
|
||||
status: { $in: ["pending", "retrying"] },
|
||||
nextRetryAt: { $lte: new Date() },
|
||||
})
|
||||
.sort({ nextRetryAt: 1 })
|
||||
.limit(limit);
|
||||
return this.mapDocuments(items);
|
||||
};
|
||||
|
||||
countByTeamId = async (teamId: string): Promise<number> => {
|
||||
return DLQItemModel.countDocuments({
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
};
|
||||
|
||||
countByTeamIdGrouped = async (teamId: string): Promise<DLQStatusCount[]> => {
|
||||
const results = await DLQItemModel.aggregate([
|
||||
{ $match: { teamId: new mongoose.Types.ObjectId(teamId) } },
|
||||
{
|
||||
$group: {
|
||||
_id: { status: "$status", type: "$type" },
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
]);
|
||||
return results.map((r) => ({
|
||||
status: r._id.status,
|
||||
type: r._id.type,
|
||||
count: r.count,
|
||||
}));
|
||||
};
|
||||
|
||||
updateById = async (id: string, patch: Partial<DLQItem>): Promise<DLQItem> => {
|
||||
const updated = await DLQItemModel.findOneAndUpdate(
|
||||
{ _id: new mongoose.Types.ObjectId(id) },
|
||||
{ $set: { ...patch } },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updated) {
|
||||
throw new AppError({ message: `DLQ item with id ${id} not found`, status: 404 });
|
||||
}
|
||||
return this.toEntity(updated);
|
||||
};
|
||||
|
||||
deleteById = async (id: string, teamId: string): Promise<number> => {
|
||||
const result = await DLQItemModel.deleteOne({
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
return result.deletedCount || 0;
|
||||
};
|
||||
|
||||
deleteOlderThan = async (date: Date): Promise<number> => {
|
||||
const result = await DLQItemModel.deleteMany({
|
||||
createdAt: { $lt: date },
|
||||
});
|
||||
return result.deletedCount || 0;
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoDLQRepository;
|
||||
@@ -0,0 +1,20 @@
|
||||
export const DLQItemTypes = ["notification", "incident_create", "incident_resolve"] as const;
|
||||
export type DLQItemType = (typeof DLQItemTypes)[number];
|
||||
|
||||
export const DLQItemStatuses = ["pending", "retrying", "failed"] as const;
|
||||
export type DLQItemStatus = (typeof DLQItemStatuses)[number];
|
||||
|
||||
export interface DLQItem {
|
||||
id: string;
|
||||
type: DLQItemType;
|
||||
status: DLQItemStatus;
|
||||
payload: Record<string, unknown>;
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
retryCount: number;
|
||||
maxRetries: number;
|
||||
lastError: string;
|
||||
nextRetryAt: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { Schema, model, Types } from "mongoose";
|
||||
import { MonitorTypes, type MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
import type { GeoCheck, GeoCheckLocation, GeoCheckMetadata, GeoCheckResult, GeoCheckTimings } from "@/domain/geo-checks/geo-check.type.js";
|
||||
|
||||
type GeoCheckMetadataDocument = Omit<GeoCheckMetadata, "monitorId" | "teamId"> & {
|
||||
monitorId: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
type: MonitorType;
|
||||
};
|
||||
|
||||
type GeoCheckDocumentBase = Omit<GeoCheck, "id" | "metadata" | "expiry" | "createdAt" | "updatedAt" | "results"> & {
|
||||
metadata: GeoCheckMetadataDocument;
|
||||
results: GeoCheckResult[];
|
||||
expiry: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
__v: number;
|
||||
};
|
||||
|
||||
export interface GeoCheckDocument extends GeoCheckDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
const geoCheckMetadataSchema = new Schema<GeoCheckMetadataDocument>(
|
||||
{
|
||||
monitorId: { type: Schema.Types.ObjectId, required: true, index: true },
|
||||
teamId: { type: Schema.Types.ObjectId, required: true, index: true },
|
||||
type: { type: String, required: true, enum: MonitorTypes },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const geoCheckTimingsSchema = new Schema<GeoCheckTimings>(
|
||||
{
|
||||
total: { type: Number, default: 0 },
|
||||
dns: { type: Number, default: 0 },
|
||||
tcp: { type: Number, default: 0 },
|
||||
tls: { type: Number, default: 0 },
|
||||
firstByte: { type: Number, default: 0 },
|
||||
download: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const geoCheckLocationSchema = new Schema<GeoCheckLocation>(
|
||||
{
|
||||
continent: { type: String, required: true },
|
||||
region: { type: String, default: "" },
|
||||
country: { type: String, default: "" },
|
||||
state: { type: String, default: "" },
|
||||
city: { type: String, default: "" },
|
||||
longitude: { type: Number, default: 0 },
|
||||
latitude: { type: Number, default: 0 },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const geoCheckResultSchema = new Schema<GeoCheckResult>(
|
||||
{
|
||||
location: {
|
||||
type: geoCheckLocationSchema,
|
||||
required: true,
|
||||
},
|
||||
status: {
|
||||
type: Boolean,
|
||||
required: true,
|
||||
},
|
||||
statusCode: {
|
||||
type: Number,
|
||||
required: true,
|
||||
},
|
||||
timings: {
|
||||
type: geoCheckTimingsSchema,
|
||||
required: true,
|
||||
},
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const GeoCheckSchema = new Schema<GeoCheckDocument>(
|
||||
{
|
||||
metadata: {
|
||||
type: geoCheckMetadataSchema,
|
||||
required: true,
|
||||
},
|
||||
results: {
|
||||
type: [geoCheckResultSchema],
|
||||
required: true,
|
||||
default: [],
|
||||
},
|
||||
expiry: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
strict: false,
|
||||
timeseries: {
|
||||
timeField: "createdAt",
|
||||
metaField: "metadata",
|
||||
granularity: "seconds",
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
GeoCheckSchema.index({ "metadata.monitorId": 1, createdAt: -1 });
|
||||
GeoCheckSchema.index({ "metadata.monitorId": 1, createdAt: 1 });
|
||||
GeoCheckSchema.index({ "metadata.teamId": 1, createdAt: -1 });
|
||||
GeoCheckSchema.index({ createdAt: 1 });
|
||||
|
||||
const GeoCheckModel = model<GeoCheckDocument>("GeoCheck", GeoCheckSchema);
|
||||
|
||||
export type { GeoCheckMetadataDocument };
|
||||
export { GeoCheckModel };
|
||||
export default GeoCheckModel;
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { GeoCheck, GroupedGeoCheck } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import type { GeoContinent, FlatGeoCheck } from "@/domain/geo-checks/geo-check.type.js";
|
||||
|
||||
export interface GeoChecksQueryResult {
|
||||
geoChecksCount: number;
|
||||
geoChecks: GeoCheck[];
|
||||
}
|
||||
|
||||
export interface FlatGeoChecksQueryResult {
|
||||
geoChecksCount: number;
|
||||
geoChecks: FlatGeoCheck[];
|
||||
}
|
||||
|
||||
export interface IGeoChecksRepository {
|
||||
createGeoChecks(geoChecks: Omit<GeoCheck, "id" | "__v" | "createdAt" | "updatedAt">[]): Promise<GeoCheck[]>;
|
||||
findByMonitorId(
|
||||
monitorId: string,
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
continents?: GeoContinent[]
|
||||
): Promise<FlatGeoChecksQueryResult>;
|
||||
findByMonitorIdAndDateRange(monitorId: string, startDate: Date, endDate: Date): Promise<GeoCheck[]>;
|
||||
findGroupedByMonitorIdAndDateRange(
|
||||
monitorId: string,
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
dateFormat: string,
|
||||
continents?: GeoContinent[]
|
||||
): Promise<GroupedGeoCheck[]>;
|
||||
deleteByMonitorId(monitorId: string): Promise<number>;
|
||||
deleteByTeamId(teamId: string): Promise<number>;
|
||||
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
import { IGeoChecksRepository } from "./geo-check.repository.interface.js";
|
||||
import type { GeoCheck, GeoCheckMetadata, GeoCheckResult, GroupedGeoCheck, GeoContinent, FlatGeoCheck } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import type { FlatGeoChecksQueryResult } from "./geo-check.repository.interface.js";
|
||||
import { GeoCheckMetadataDocument, GeoCheckModel, type GeoCheckDocument } from "@/domain/geo-checks/geo-check.model.js";
|
||||
import mongoose, { PipelineStage } from "mongoose";
|
||||
import { getDateForRange } from "@/utils/dataUtils.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
|
||||
const SERVICE_NAME = "GeoChecksRepository";
|
||||
|
||||
class MongoGeoChecksRepository implements IGeoChecksRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private logger: ILogger;
|
||||
constructor(logger: ILogger) {
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
private toEntity = (doc: GeoCheckDocument): GeoCheck => {
|
||||
const toStringId = (value: mongoose.Types.ObjectId | string | undefined | null): string => {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value);
|
||||
};
|
||||
|
||||
const toDateString = (value?: Date | string | null): string => {
|
||||
if (!value) {
|
||||
return new Date(0).toISOString();
|
||||
}
|
||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||
};
|
||||
|
||||
const mapMetadata = (metadata: GeoCheckMetadataDocument): GeoCheckMetadata => ({
|
||||
monitorId: toStringId(metadata.monitorId),
|
||||
teamId: toStringId(metadata.teamId),
|
||||
type: metadata.type,
|
||||
});
|
||||
|
||||
const mapResults = (results: GeoCheckResult[]): GeoCheckResult[] => {
|
||||
if (!results || !Array.isArray(results)) {
|
||||
return [];
|
||||
}
|
||||
return results.map((result) => ({
|
||||
location: {
|
||||
continent: result.location?.continent ?? "",
|
||||
region: result.location?.region ?? "",
|
||||
country: result.location?.country ?? "",
|
||||
state: result.location?.state ?? "",
|
||||
city: result.location?.city ?? "",
|
||||
longitude: result.location?.longitude ?? 0,
|
||||
latitude: result.location?.latitude ?? 0,
|
||||
},
|
||||
status: result.status ?? false,
|
||||
statusCode: result.statusCode ?? 0,
|
||||
timings: {
|
||||
total: result.timings?.total ?? 0,
|
||||
dns: result.timings?.dns ?? 0,
|
||||
tcp: result.timings?.tcp ?? 0,
|
||||
tls: result.timings?.tls ?? 0,
|
||||
firstByte: result.timings?.firstByte ?? 0,
|
||||
download: result.timings?.download ?? 0,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
metadata: mapMetadata(doc.metadata),
|
||||
results: mapResults(doc.results),
|
||||
expiry: toDateString(doc.expiry),
|
||||
__v: doc.__v ?? 0,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
createGeoChecks = async (geoChecks: Omit<GeoCheck, "id" | "__v" | "createdAt" | "updatedAt">[]): Promise<GeoCheck[]> => {
|
||||
try {
|
||||
const docs = await GeoCheckModel.insertMany(
|
||||
geoChecks.map((geoCheck) => ({
|
||||
metadata: {
|
||||
monitorId: new mongoose.Types.ObjectId(geoCheck.metadata.monitorId),
|
||||
teamId: new mongoose.Types.ObjectId(geoCheck.metadata.teamId),
|
||||
type: geoCheck.metadata.type,
|
||||
},
|
||||
results: geoCheck.results,
|
||||
expiry: new Date(geoCheck.expiry),
|
||||
}))
|
||||
);
|
||||
return docs.map((doc) => this.toEntity(doc));
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: error instanceof Error ? `Failed to createGeoChecks: ${error.message}` : "Failed to createGeoChecks",
|
||||
service: SERVICE_NAME,
|
||||
method: "createGeoChecks",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
findByMonitorId = async (
|
||||
monitorId: string,
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
continents?: GeoContinent[]
|
||||
): Promise<FlatGeoChecksQueryResult> => {
|
||||
try {
|
||||
const matchStage: Record<string, unknown> = {
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
...(getDateForRange(dateRange) && {
|
||||
createdAt: {
|
||||
$gte: getDateForRange(dateRange),
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const convertedSortOrder = sortOrder === "asc" ? 1 : -1;
|
||||
|
||||
let skip = 0;
|
||||
if (page && rowsPerPage) {
|
||||
skip = page * rowsPerPage;
|
||||
}
|
||||
|
||||
// Common pipeline stages for both paths
|
||||
const pipeline: PipelineStage[] = [
|
||||
{ $match: matchStage },
|
||||
{ $unwind: "$results" },
|
||||
// Filter by continent if specified
|
||||
...(continents && continents.length > 0
|
||||
? [
|
||||
{
|
||||
$match: {
|
||||
"results.location.continent": { $in: continents },
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Project to flat structure
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
monitorId: "$metadata.monitorId",
|
||||
teamId: "$metadata.teamId",
|
||||
type: "$metadata.type",
|
||||
location: "$results.location",
|
||||
status: "$results.status",
|
||||
statusCode: "$results.statusCode",
|
||||
timings: "$results.timings",
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
},
|
||||
},
|
||||
{ $sort: { createdAt: convertedSortOrder } },
|
||||
{ $skip: skip },
|
||||
{ $limit: rowsPerPage },
|
||||
];
|
||||
|
||||
// Count pipeline
|
||||
const countPipeline: PipelineStage[] = [
|
||||
{ $match: matchStage },
|
||||
{ $unwind: "$results" },
|
||||
...(continents && continents.length > 0
|
||||
? [
|
||||
{
|
||||
$match: {
|
||||
"results.location.continent": { $in: continents },
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
{ $count: "count" },
|
||||
];
|
||||
|
||||
const [countResult, dataResults] = await Promise.all([GeoCheckModel.aggregate(countPipeline), GeoCheckModel.aggregate(pipeline)]);
|
||||
|
||||
const geoChecksCount = countResult[0]?.count || 0;
|
||||
const geoChecks: FlatGeoCheck[] = dataResults.map((doc) => ({
|
||||
id: `${doc.monitorId.toString()}-${new Date(doc.createdAt).getTime()}-${doc.location.continent}-${doc.location.city}-${Math.random().toString(36).substring(2, 15)}`,
|
||||
monitorId: doc.monitorId.toString(),
|
||||
teamId: doc.teamId.toString(),
|
||||
type: doc.type,
|
||||
location: doc.location,
|
||||
status: doc.status,
|
||||
statusCode: doc.statusCode,
|
||||
timings: doc.timings,
|
||||
createdAt: new Date(doc.createdAt).toISOString(),
|
||||
updatedAt: new Date(doc.updatedAt).toISOString(),
|
||||
}));
|
||||
|
||||
return { geoChecksCount, geoChecks };
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: error instanceof Error ? `Error finding geo checks by monitor ID: ${error.message}` : "Error finding geo checks by monitor ID",
|
||||
service: SERVICE_NAME,
|
||||
method: "findByMonitorId",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
findByMonitorIdAndDateRange = async (monitorId: string, startDate: Date, endDate: Date): Promise<GeoCheck[]> => {
|
||||
try {
|
||||
const docs = await GeoCheckModel.find({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
createdAt: {
|
||||
$gte: startDate,
|
||||
$lte: endDate,
|
||||
},
|
||||
}).sort({ createdAt: -1 });
|
||||
return docs.map(this.toEntity);
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message:
|
||||
error instanceof Error
|
||||
? `Error finding geo checks by monitor ID and date range: ${error.message}`
|
||||
: "Error finding geo checks by monitor ID and date range",
|
||||
service: SERVICE_NAME,
|
||||
method: "findByMonitorIdAndDateRange",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
findGroupedByMonitorIdAndDateRange = async (
|
||||
monitorId: string,
|
||||
startDate: Date,
|
||||
endDate: Date,
|
||||
dateFormat: string,
|
||||
continents?: GeoContinent[]
|
||||
): Promise<GroupedGeoCheck[]> => {
|
||||
try {
|
||||
const pipeline: PipelineStage[] = [
|
||||
// Match geo checks for this monitor in date range
|
||||
{
|
||||
$match: {
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
createdAt: {
|
||||
$gte: startDate,
|
||||
$lte: endDate,
|
||||
},
|
||||
},
|
||||
},
|
||||
// Unwind the results array to process each location separately
|
||||
{
|
||||
$unwind: "$results",
|
||||
},
|
||||
// Filter by continent if specified
|
||||
...(continents && continents.length > 0
|
||||
? [
|
||||
{
|
||||
$match: {
|
||||
"results.location.continent": { $in: continents },
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
// Group by date bucket and continent
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
bucketDate: {
|
||||
$dateToString: {
|
||||
format: dateFormat,
|
||||
date: "$createdAt",
|
||||
},
|
||||
},
|
||||
continent: "$results.location.continent",
|
||||
},
|
||||
avgResponseTime: { $avg: "$results.timings.total" },
|
||||
totalChecks: { $sum: 1 },
|
||||
upChecks: {
|
||||
$sum: {
|
||||
$cond: ["$results.status", 1, 0],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
// Calculate uptime percentage
|
||||
{
|
||||
$project: {
|
||||
_id: 0,
|
||||
bucketDate: "$_id.bucketDate",
|
||||
continent: "$_id.continent",
|
||||
avgResponseTime: { $round: ["$avgResponseTime", 2] },
|
||||
totalChecks: 1,
|
||||
uptimePercentage: {
|
||||
$round: [
|
||||
{
|
||||
$multiply: [
|
||||
{
|
||||
$divide: ["$upChecks", "$totalChecks"],
|
||||
},
|
||||
100,
|
||||
],
|
||||
},
|
||||
2,
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
// Sort by date and continent
|
||||
{
|
||||
$sort: {
|
||||
bucketDate: 1,
|
||||
continent: 1,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const results = await GeoCheckModel.aggregate(pipeline);
|
||||
return results as GroupedGeoCheck[];
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: error instanceof Error ? `Error finding grouped geo checks: ${error.message}` : "Error finding grouped geo checks",
|
||||
service: SERVICE_NAME,
|
||||
method: "findGroupedByMonitorIdAndDateRange",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
deleteByMonitorId = async (monitorId: string): Promise<number> => {
|
||||
try {
|
||||
const result = await GeoCheckModel.deleteMany({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
});
|
||||
return result.deletedCount || 0;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: error instanceof Error ? `Error deleting geo checks by monitor ID: ${error.message}` : "Error deleting geo checks by monitor ID",
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteByMonitorId",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
deleteByTeamId = async (teamId: string): Promise<number> => {
|
||||
try {
|
||||
const result = await GeoCheckModel.deleteMany({
|
||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
return result.deletedCount || 0;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: error instanceof Error ? `Error deleting geo checks by team ID: ${error.message}` : "Error deleting geo checks by team ID",
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteByTeamId",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
deleteByMonitorIdsNotIn = async (monitorIds: string[]): Promise<number> => {
|
||||
try {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const result = await GeoCheckModel.deleteMany({ "metadata.monitorId": { $nin: objectIds } });
|
||||
return result.deletedCount || 0;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: error instanceof Error ? `Error deleting orphaned geo checks: ${error.message}` : "Error deleting orphaned geo checks",
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteByMonitorIdsNotIn",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export { MongoGeoChecksRepository };
|
||||
export default MongoGeoChecksRepository;
|
||||
@@ -0,0 +1,201 @@
|
||||
import type { GeoCheck } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import type { Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import type { GeoCheckResult, GeoContinent } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import { Types } from "mongoose";
|
||||
import type { FlatGeoChecksQueryResult, IGeoChecksRepository } from "@/domain/geo-checks/geo-check.repository.interface.js";
|
||||
import type { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { IGlobalPingService } from "@/service/globalPingService.js";
|
||||
import type { ILogger } from "@/utils/logger.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
const SERVICE_NAME = "GeoChecksService";
|
||||
|
||||
export interface IGeoChecksService {
|
||||
readonly serviceName: string;
|
||||
buildGeoCheck(monitor: Monitor): Promise<GeoCheck | null>;
|
||||
createGeoChecks(geoChecks: GeoCheck[]): Promise<GeoCheck[]>;
|
||||
getGeoChecksByMonitor(args: {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
sortOrder: string;
|
||||
dateRange: string;
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
continent?: GeoContinent | GeoContinent[];
|
||||
}): Promise<FlatGeoChecksQueryResult>;
|
||||
}
|
||||
|
||||
export class GeoChecksService implements IGeoChecksService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private logger: ILogger;
|
||||
private geoChecksRepository: IGeoChecksRepository;
|
||||
private globalPingService: IGlobalPingService;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
|
||||
constructor({
|
||||
logger,
|
||||
geoChecksRepository,
|
||||
globalPingService,
|
||||
monitorsRepository,
|
||||
}: {
|
||||
logger: ILogger;
|
||||
geoChecksRepository: IGeoChecksRepository;
|
||||
globalPingService: IGlobalPingService;
|
||||
monitorsRepository: IMonitorsRepository;
|
||||
}) {
|
||||
this.logger = logger;
|
||||
this.geoChecksRepository = geoChecksRepository;
|
||||
this.globalPingService = globalPingService;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return GeoChecksService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
async buildGeoCheck(monitor: Monitor): Promise<GeoCheck | null> {
|
||||
try {
|
||||
if (!monitor.url) {
|
||||
this.logger.warn({
|
||||
message: "Monitor missing URL for geo check",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildGeoCheck",
|
||||
details: { monitorId: monitor.id },
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!monitor.geoCheckLocations || monitor.geoCheckLocations.length === 0) {
|
||||
this.logger.warn({
|
||||
message: "Monitor missing geo check locations",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildGeoCheck",
|
||||
details: { monitorId: monitor.id },
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Step 1: Create measurement request
|
||||
const measurementId = await this.globalPingService.createMeasurement(monitor.type, monitor.url, monitor.geoCheckLocations);
|
||||
|
||||
if (!measurementId) {
|
||||
// GlobalPing API is down, skip this check
|
||||
this.logger.debug({
|
||||
message: "Skipping geo check due to API unavailability",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildGeoCheck",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Step 2: Poll for results
|
||||
const results = await this.globalPingService.pollForResults(measurementId, undefined, monitor.customUpCodes ?? []);
|
||||
|
||||
if (results.length === 0) {
|
||||
// No successful results (all locations timed out or failed)
|
||||
this.logger.debug({
|
||||
message: "No successful geo check results",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildGeoCheck",
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
// Step 3: Build GeoCheck document
|
||||
const geoCheck = this.createGeoCheckDocument(monitor, results);
|
||||
|
||||
this.logger.debug({
|
||||
message: `Geo check completed for monitor ${monitor.id}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "buildGeoCheck",
|
||||
});
|
||||
|
||||
return geoCheck;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
message: "Error executing geo check",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildGeoCheck",
|
||||
details: { monitorId: monitor.id, error: error instanceof Error ? error.message : "Unknown error" },
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private createGeoCheckDocument(monitor: Monitor, results: GeoCheckResult[]): GeoCheck {
|
||||
const now = new Date();
|
||||
const ttl = 90 * 24 * 60 * 60 * 1000; // 90 days in ms
|
||||
const expiryDate = new Date(now.getTime() + ttl);
|
||||
|
||||
return {
|
||||
id: new Types.ObjectId().toString(),
|
||||
metadata: {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
type: monitor.type,
|
||||
},
|
||||
results,
|
||||
expiry: expiryDate.toISOString(),
|
||||
__v: 0,
|
||||
createdAt: now.toISOString(),
|
||||
updatedAt: now.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
createGeoChecks = async (geoChecks: GeoCheck[]) => {
|
||||
return this.geoChecksRepository.createGeoChecks(geoChecks);
|
||||
};
|
||||
|
||||
getGeoChecksByMonitor = async ({
|
||||
monitorId,
|
||||
teamId,
|
||||
sortOrder,
|
||||
dateRange,
|
||||
page,
|
||||
rowsPerPage,
|
||||
continent,
|
||||
}: {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
sortOrder: string;
|
||||
dateRange: string;
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
continent: GeoContinent | GeoContinent[];
|
||||
}) => {
|
||||
if (!monitorId) {
|
||||
throw new AppError({
|
||||
message: "No monitor ID in request",
|
||||
service: SERVICE_NAME,
|
||||
method: "getGeoChecksByMonitor",
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
if (!teamId) {
|
||||
throw new AppError({
|
||||
message: "No team ID in request",
|
||||
service: SERVICE_NAME,
|
||||
method: "getGeoChecksByMonitor",
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
|
||||
if (!monitor) {
|
||||
throw new AppError({
|
||||
message: `Monitor with ID ${monitorId} not found.`,
|
||||
service: SERVICE_NAME,
|
||||
method: "getGeoChecksByMonitor",
|
||||
status: 404,
|
||||
});
|
||||
}
|
||||
|
||||
const continents = continent ? (Array.isArray(continent) ? continent : [continent]) : undefined;
|
||||
const parsedPage = page || 0;
|
||||
const parsedRowsPerPage = rowsPerPage || 5;
|
||||
const result = await this.geoChecksRepository.findByMonitorId(monitorId, sortOrder, dateRange, parsedPage, parsedRowsPerPage, continents);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import type { MonitorType } from "@/domain/monitors/monitor.types.js";
|
||||
|
||||
export const GeoContinents = ["EU", "NA", "AS", "SA", "AF", "OC"] as const;
|
||||
export type GeoContinent = (typeof GeoContinents)[number];
|
||||
|
||||
export interface GeoCheckMetadata {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
type: MonitorType;
|
||||
}
|
||||
|
||||
export interface GeoCheckTimings {
|
||||
total: number;
|
||||
dns: number;
|
||||
tcp: number;
|
||||
tls: number;
|
||||
firstByte: number;
|
||||
download: number;
|
||||
}
|
||||
|
||||
export interface GeoCheckLocation {
|
||||
continent: GeoContinent;
|
||||
region: string;
|
||||
country: string;
|
||||
state: string;
|
||||
city: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
}
|
||||
|
||||
export interface GeoCheckResult {
|
||||
location: GeoCheckLocation;
|
||||
status: boolean;
|
||||
statusCode: number;
|
||||
timings: GeoCheckTimings;
|
||||
}
|
||||
|
||||
export interface GeoCheck {
|
||||
id: string;
|
||||
metadata: GeoCheckMetadata;
|
||||
results: GeoCheckResult[];
|
||||
expiry: string;
|
||||
__v: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface FlatGeoCheck {
|
||||
id: string;
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
type: string;
|
||||
location: GeoCheckLocation;
|
||||
status: boolean;
|
||||
statusCode: number;
|
||||
timings: GeoCheckTimings;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface GroupedGeoCheck {
|
||||
bucketDate: string;
|
||||
continent: GeoContinent;
|
||||
avgResponseTime: number;
|
||||
totalChecks: number;
|
||||
uptimePercentage: number;
|
||||
}
|
||||
|
||||
export interface GeoChecksResult {
|
||||
monitorType: Exclude<MonitorType, "hardware" | "pagespeed">;
|
||||
groupedGeoChecks: GroupedGeoCheck[];
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import { IncidentResolutionTypes, type Incident } from "@/domain/incidents/incident.type.js";
|
||||
|
||||
type IncidentDocumentBase = Omit<Incident, "id" | "monitorId" | "teamId" | "resolvedBy" | "startTime" | "endTime" | "createdAt" | "updatedAt"> & {
|
||||
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<IncidentDocument>(
|
||||
{
|
||||
monitorId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Monitor",
|
||||
required: true,
|
||||
immutable: true,
|
||||
index: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
required: true,
|
||||
immutable: true,
|
||||
index: true,
|
||||
},
|
||||
startTime: {
|
||||
type: Date,
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
endTime: {
|
||||
type: Date,
|
||||
default: null,
|
||||
},
|
||||
status: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
index: true,
|
||||
},
|
||||
message: {
|
||||
type: String,
|
||||
default: null,
|
||||
},
|
||||
statusCode: {
|
||||
type: Number,
|
||||
default: null,
|
||||
index: true,
|
||||
},
|
||||
resolutionType: {
|
||||
type: String,
|
||||
enum: IncidentResolutionTypes,
|
||||
default: null,
|
||||
},
|
||||
resolvedBy: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
default: null,
|
||||
},
|
||||
resolvedByEmail: {
|
||||
type: String,
|
||||
default: null,
|
||||
},
|
||||
comment: {
|
||||
type: String,
|
||||
default: null,
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
IncidentSchema.index({ monitorId: 1, status: 1 });
|
||||
IncidentSchema.index({ teamId: 1, status: 1 });
|
||||
IncidentSchema.index({ teamId: 1, startTime: -1 });
|
||||
IncidentSchema.index({ status: 1, startTime: -1 });
|
||||
IncidentSchema.index({ resolutionType: 1, status: 1 });
|
||||
IncidentSchema.index({ resolvedBy: 1, status: 1 });
|
||||
IncidentSchema.index({ createdAt: -1 });
|
||||
|
||||
const IncidentModel = model<IncidentDocument>("Incident", IncidentSchema);
|
||||
|
||||
export { IncidentModel };
|
||||
export default IncidentModel;
|
||||
@@ -0,0 +1,29 @@
|
||||
import type { Incident } from "@/domain/incidents/incident.type.js";
|
||||
import type { IncidentSummary } from "@/domain/incidents/incident.type.js";
|
||||
export interface IIncidentsRepository {
|
||||
// create
|
||||
create(incident: Partial<Incident>): Promise<Incident>;
|
||||
// fetch
|
||||
findById(incidentId: string, teamId: string): Promise<Incident>;
|
||||
findActiveByIncidentId(incidentId: string, teamId: string): Promise<Incident | null>;
|
||||
findActiveByMonitorId(monitorId: string, teamId: string): Promise<Incident | null>;
|
||||
findByTeamId(
|
||||
teamId: string,
|
||||
startDate: Date | undefined,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
sortOrder?: string,
|
||||
status?: boolean,
|
||||
monitorId?: string,
|
||||
resolutionType?: string
|
||||
): Promise<Incident[]>;
|
||||
findSummaryByTeamId(teamId: string, limit?: number): Promise<IncidentSummary>;
|
||||
countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise<number>;
|
||||
|
||||
// update
|
||||
updateById(incidentId: string, teamId: string, updateData: Partial<Incident>): Promise<Incident>;
|
||||
// delete
|
||||
deleteByMonitorId(monitorId: string, teamId: string): Promise<number>;
|
||||
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
|
||||
// other
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
import { IncidentModel } from "@/domain/incidents/incident.model.js";
|
||||
import type { IncidentDocument } from "@/domain/incidents/incident.model.js";
|
||||
import type { Incident, IncidentSummary } from "@/domain/incidents/incident.type.js";
|
||||
import type { IIncidentsRepository } from "@/domain/incidents/incident.repository.interface.js";
|
||||
import mongoose from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
class MongoIncidentsRepository 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();
|
||||
};
|
||||
|
||||
private buildMatchStage({
|
||||
teamId,
|
||||
startDate,
|
||||
status,
|
||||
monitorId,
|
||||
resolutionType,
|
||||
}: {
|
||||
teamId: string;
|
||||
startDate: Date | undefined;
|
||||
status?: boolean;
|
||||
monitorId?: string;
|
||||
resolutionType?: string;
|
||||
}): Record<string, unknown> {
|
||||
const matchStage: Record<string, unknown> = {
|
||||
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),
|
||||
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,
|
||||
resolvedByEmail: doc.resolvedByEmail ?? 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<Incident>): Promise<Incident> {
|
||||
const newIncident = await IncidentModel.create(incident);
|
||||
return this.toEntity(newIncident);
|
||||
}
|
||||
|
||||
findById = async (incidentId: string, teamId: string): Promise<Incident> => {
|
||||
const incident = await IncidentModel.findOne({
|
||||
_id: new mongoose.Types.ObjectId(incidentId),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
if (!incident) {
|
||||
throw new AppError({ message: `Incident with id ${incidentId} not found`, status: 404 });
|
||||
}
|
||||
return this.toEntity(incident);
|
||||
};
|
||||
|
||||
findActiveByIncidentId = async (incidentId: string, teamId: string): Promise<Incident | null> => {
|
||||
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<Incident | null> => {
|
||||
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,
|
||||
startDate: Date | undefined,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
sortOrder?: string,
|
||||
status?: boolean,
|
||||
monitorId?: string,
|
||||
resolutionType?: string
|
||||
): Promise<Incident[]> => {
|
||||
const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType });
|
||||
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<Incident>) => {
|
||||
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);
|
||||
};
|
||||
|
||||
countByTeamId = async (
|
||||
teamId: string,
|
||||
startDate: Date | undefined,
|
||||
status?: boolean,
|
||||
monitorId?: string,
|
||||
resolutionType?: string
|
||||
): Promise<number> => {
|
||||
const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType });
|
||||
return IncidentModel.countDocuments(matchStage);
|
||||
};
|
||||
|
||||
findSummaryByTeamId = async (teamId: string, limit: number): Promise<IncidentSummary> => {
|
||||
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),
|
||||
})),
|
||||
};
|
||||
};
|
||||
|
||||
deleteByMonitorId = async (monitorId: string, teamId: string) => {
|
||||
const result = await IncidentModel.deleteMany({
|
||||
monitorId: new mongoose.Types.ObjectId(monitorId),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
return result.deletedCount || 0;
|
||||
};
|
||||
|
||||
deleteByMonitorIdsNotIn = async (monitorIds: string[]): Promise<number> => {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const result = await IncidentModel.deleteMany({ monitorId: { $nin: objectIds } });
|
||||
return result.deletedCount ?? 0;
|
||||
};
|
||||
}
|
||||
export default MongoIncidentsRepository;
|
||||
@@ -0,0 +1,266 @@
|
||||
const SERVICE_NAME = "incidentService";
|
||||
import type { Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import type { MonitorStatusResponse } from "@/types/network.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { getDateForRange } from "@/utils/dataUtils.js";
|
||||
import type { IIncidentsRepository } from "@/domain/incidents/incident.repository.interface.js";
|
||||
import type { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { IUsersRepository } from "@/domain/users/user.repository.interface.js";
|
||||
import type { Incident, IncidentSummary } from "@/domain/incidents/incident.type.js";
|
||||
import type { User } from "@/domain/users/user.type.js";
|
||||
import type { MonitorActionDecision } from "@/service/job-queues/job-queue.helper.js";
|
||||
import type { INotificationMessageBuilder } from "@/domain/notifications/notification.message-builder.js";
|
||||
import type { ILogger } from "@/utils/logger.js";
|
||||
|
||||
export interface IIncidentService {
|
||||
handleIncident(
|
||||
monitor: Monitor,
|
||||
code: number,
|
||||
decision: MonitorActionDecision,
|
||||
monitorStatusResponse?: MonitorStatusResponse
|
||||
): Promise<Incident | null>;
|
||||
resolveIncident(incidentId: string, userId: string, teamId: string, comment?: string, userEmail?: string): Promise<Incident>;
|
||||
getIncidentsByTeam(
|
||||
teamId: string,
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
status: boolean | undefined,
|
||||
monitorId: string | undefined,
|
||||
resolutionType: string | undefined
|
||||
): Promise<{ incidents: Incident[]; count: number }>;
|
||||
getIncidentSummary(teamId: string, limit?: number): Promise<IncidentSummary>;
|
||||
getIncidentById(incidentId: string, teamId: string): Promise<{ incident: Incident; monitor: Monitor; user: User | null }>;
|
||||
}
|
||||
|
||||
export class IncidentService implements IIncidentService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private logger: ILogger;
|
||||
private incidentsRepository: IIncidentsRepository;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private usersRepository: IUsersRepository;
|
||||
private notificationMessageBuilder: INotificationMessageBuilder;
|
||||
|
||||
constructor(
|
||||
logger: ILogger,
|
||||
incidentsRepository: IIncidentsRepository,
|
||||
monitorsRepository: IMonitorsRepository,
|
||||
usersRepository: IUsersRepository,
|
||||
notificationMessageBuilder: INotificationMessageBuilder
|
||||
) {
|
||||
this.logger = logger;
|
||||
this.incidentsRepository = incidentsRepository;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.usersRepository = usersRepository;
|
||||
this.notificationMessageBuilder = notificationMessageBuilder;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return IncidentService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
handleIncident = async (
|
||||
monitor: Monitor,
|
||||
code: number,
|
||||
decision: MonitorActionDecision,
|
||||
monitorStatusResponse?: MonitorStatusResponse
|
||||
): Promise<Incident | null> => {
|
||||
if (!decision.shouldCreateIncident && !decision.shouldResolveIncident) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const activeIncident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId);
|
||||
|
||||
if (decision.shouldCreateIncident) {
|
||||
if (activeIncident) {
|
||||
return activeIncident;
|
||||
} else {
|
||||
let statusCode = code;
|
||||
let message: string | undefined;
|
||||
|
||||
// For threshold breaches, use 9999 status code and build descriptive message
|
||||
if (decision.incidentReason === "threshold_breach") {
|
||||
statusCode = 9999;
|
||||
message = this.buildThresholdBreachMessage(monitor, monitorStatusResponse);
|
||||
}
|
||||
|
||||
const incident = {
|
||||
monitorId: monitor.id,
|
||||
teamId: monitor.teamId,
|
||||
startTime: Date.now().toString(),
|
||||
status: true,
|
||||
statusCode,
|
||||
message,
|
||||
};
|
||||
return await this.incidentsRepository.create(incident);
|
||||
}
|
||||
}
|
||||
|
||||
if (!decision.shouldResolveIncident || !activeIncident) {
|
||||
return null;
|
||||
}
|
||||
|
||||
activeIncident.status = false;
|
||||
activeIncident.endTime = Date.now().toString();
|
||||
activeIncident.resolutionType = "automatic";
|
||||
return await this.incidentsRepository.updateById(activeIncident.id, activeIncident.teamId, activeIncident);
|
||||
};
|
||||
|
||||
private buildThresholdBreachMessage(monitor: Monitor, monitorStatusResponse?: MonitorStatusResponse): string {
|
||||
if (!monitorStatusResponse) {
|
||||
return "Threshold breach detected";
|
||||
}
|
||||
|
||||
const breaches = this.notificationMessageBuilder.extractThresholdBreaches(monitor, monitorStatusResponse);
|
||||
|
||||
if (breaches.length === 0) {
|
||||
return "Threshold breach detected";
|
||||
}
|
||||
|
||||
return breaches.map((b) => `${b.metric.toUpperCase()}: ${b.formattedValue} (threshold: ${b.threshold}${b.unit})`).join(", ");
|
||||
}
|
||||
|
||||
resolveIncident = async (incidentId: string, userId: string, teamId: string, comment?: string, userEmail?: string) => {
|
||||
try {
|
||||
if (!incidentId) {
|
||||
throw new AppError({ message: "No incident ID in request", service: SERVICE_NAME, method: "resolveIncident" });
|
||||
}
|
||||
|
||||
if (!userId) {
|
||||
throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "resolveIncident" });
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "resolveIncident" });
|
||||
}
|
||||
|
||||
const incident = await this.incidentsRepository.findActiveByIncidentId(incidentId, teamId);
|
||||
|
||||
if (!incident) {
|
||||
throw new AppError({ message: "Incident not found", service: SERVICE_NAME, method: "resolveIncident" });
|
||||
}
|
||||
|
||||
if (incident.status === false) {
|
||||
throw new AppError({ message: "Incident is already resolved", service: SERVICE_NAME, method: "resolveIncident" });
|
||||
}
|
||||
|
||||
incident.resolutionType = "manual";
|
||||
incident.status = false;
|
||||
incident.resolvedBy = userId;
|
||||
incident.resolvedByEmail = userEmail || null;
|
||||
incident.comment = comment || null;
|
||||
incident.endTime = Date.now().toString();
|
||||
|
||||
const resolvedIncident = await this.incidentsRepository.updateById(incident.id, teamId, incident);
|
||||
|
||||
this.logger.debug({
|
||||
service: SERVICE_NAME,
|
||||
method: "resolveIncidentManually",
|
||||
message: `Incident manually resolved by user`,
|
||||
details: { incidentId: resolvedIncident.id },
|
||||
});
|
||||
|
||||
return resolvedIncident;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
service: SERVICE_NAME,
|
||||
method: "resolveIncident",
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
details: { id: incidentId },
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
getIncidentsByTeam = async (
|
||||
teamId: string,
|
||||
sortOrder: string,
|
||||
dateRange: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
status: boolean | undefined,
|
||||
monitorId: string | undefined,
|
||||
resolutionType: string | undefined
|
||||
) => {
|
||||
try {
|
||||
if (!teamId) {
|
||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentsByTeam", status: 400 });
|
||||
}
|
||||
|
||||
const startDate = getDateForRange(dateRange);
|
||||
|
||||
const parsedPage = page ?? 0;
|
||||
const parsedRowsPerPage = rowsPerPage ?? 20;
|
||||
|
||||
const incidents = await this.incidentsRepository.findByTeamId(
|
||||
teamId,
|
||||
startDate,
|
||||
parsedPage,
|
||||
parsedRowsPerPage,
|
||||
sortOrder,
|
||||
status,
|
||||
monitorId,
|
||||
resolutionType
|
||||
);
|
||||
|
||||
const count = await this.incidentsRepository.countByTeamId(teamId, startDate, status, monitorId, resolutionType);
|
||||
|
||||
return { incidents, count };
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
service: SERVICE_NAME,
|
||||
method: "getIncidentsByTeam",
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
details: { teamId },
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
getIncidentSummary = async (teamId: string, limit?: number) => {
|
||||
try {
|
||||
if (!teamId) {
|
||||
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentSummary", status: 400 });
|
||||
}
|
||||
|
||||
const parsedLimit = limit ?? 10;
|
||||
const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit);
|
||||
|
||||
return summary;
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
service: SERVICE_NAME,
|
||||
method: "getIncidentSummary",
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
details: { teamId },
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
getIncidentById = async (incidentId: string, teamId: string) => {
|
||||
try {
|
||||
const incident = await this.incidentsRepository.findById(incidentId, teamId);
|
||||
const monitor = await this.monitorsRepository.findById(incident.monitorId, teamId);
|
||||
let user = null;
|
||||
if (incident.resolvedBy) {
|
||||
user = await this.usersRepository.findById(incident.resolvedBy);
|
||||
}
|
||||
return { incident, monitor, user };
|
||||
} catch (error: unknown) {
|
||||
this.logger.error({
|
||||
service: SERVICE_NAME,
|
||||
method: "getIncidentById",
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
details: { incidentId },
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// 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;
|
||||
resolvedByEmail?: string | null;
|
||||
comment?: string | null;
|
||||
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[];
|
||||
}
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { Invite } from "@/domain/invites/invite.type.js";
|
||||
|
||||
type InviteDocumentBase = Omit<Invite, "id" | "teamId" | "createdAt" | "updatedAt" | "expiry"> & {
|
||||
teamId: Types.ObjectId;
|
||||
expiry: Date;
|
||||
};
|
||||
|
||||
interface InviteDocument extends InviteDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const InviteSchema = new Schema<InviteDocument>(
|
||||
{
|
||||
email: { type: String, required: true, unique: true },
|
||||
teamId: { type: Schema.Types.ObjectId, ref: "Team", immutable: true, required: true },
|
||||
role: { type: [String], required: true, default: ["user"] },
|
||||
token: { type: String, required: true },
|
||||
expiry: { type: Date, default: Date.now, expires: 3600 },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
const InviteModel = model<InviteDocument>("Invite", InviteSchema);
|
||||
|
||||
export type { InviteDocument };
|
||||
export { InviteModel };
|
||||
export default InviteModel;
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Invite } from "@/domain/invites/invite.type.js";
|
||||
|
||||
export interface IInvitesRepository {
|
||||
// create
|
||||
create(invite: Partial<Invite>): Promise<Invite>;
|
||||
// fetch
|
||||
findByToken(token: string): Promise<Invite>;
|
||||
findByTokenAndDelete(token: string): Promise<Invite>;
|
||||
// update
|
||||
|
||||
// delete
|
||||
// other
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { IInvitesRepository } from "@/domain/invites/invite.repository.interface.js";
|
||||
import type { Invite } from "@/domain/invites/invite.type.js";
|
||||
import { type InviteDocument, InviteModel } from "@/domain/invites/invite.model.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import mongoose from "mongoose";
|
||||
import crypto from "crypto";
|
||||
|
||||
class MongoInvitesRepository implements IInvitesRepository {
|
||||
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: InviteDocument): Invite => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
email: doc.email,
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
role: doc.role ?? [],
|
||||
token: doc.token,
|
||||
expiry: this.toDateString(doc.expiry),
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (invite: Partial<Invite>) => {
|
||||
await InviteModel.deleteMany({ email: invite.email });
|
||||
invite.token = crypto.randomBytes(32).toString("hex");
|
||||
const inviteToken = await InviteModel.create(invite);
|
||||
return this.toEntity(inviteToken);
|
||||
};
|
||||
|
||||
findByToken = async (token: string) => {
|
||||
const invite = await InviteModel.findOne({
|
||||
token,
|
||||
});
|
||||
if (invite === null) {
|
||||
throw new AppError({ message: "Invite not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(invite);
|
||||
};
|
||||
|
||||
findByTokenAndDelete = async (token: string) => {
|
||||
const invite = await InviteModel.findOneAndDelete({
|
||||
token,
|
||||
});
|
||||
if (invite === null) {
|
||||
throw new AppError({ message: "Invite not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(invite);
|
||||
};
|
||||
}
|
||||
export default MongoInvitesRepository;
|
||||
@@ -0,0 +1,117 @@
|
||||
import type { Invite } from "@/domain/invites/invite.type.js";
|
||||
import type { UserRole } from "@/domain/users/user.type.js";
|
||||
import { canManageRole } from "@/domain/users/user.type.js";
|
||||
import type { IInvitesRepository } from "@/domain/invites/invite.repository.interface.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { ISettingsService } from "../app-settings/app-settings.service.js";
|
||||
import { IEmailService } from "@/service/emailService.js";
|
||||
|
||||
const SERVICE_NAME = "inviteService";
|
||||
|
||||
export interface IInviteService {
|
||||
getInviteToken(params: { invite: Partial<Invite>; teamId: string; userRoles: UserRole[] }): Promise<Invite>;
|
||||
sendInviteEmail(params: { invite: Partial<Invite>; firstName: string; userRoles: UserRole[] }): Promise<void>;
|
||||
verifyInviteToken(params: { inviteToken: string }): Promise<Invite>;
|
||||
}
|
||||
|
||||
export class InviteService implements IInviteService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private settingsService: ISettingsService;
|
||||
private emailService: IEmailService;
|
||||
private invitesRepository: IInvitesRepository;
|
||||
|
||||
constructor({
|
||||
invitesRepository,
|
||||
settingsService,
|
||||
emailService,
|
||||
}: {
|
||||
invitesRepository: IInvitesRepository;
|
||||
settingsService: ISettingsService;
|
||||
emailService: IEmailService;
|
||||
}) {
|
||||
this.invitesRepository = invitesRepository;
|
||||
this.settingsService = settingsService;
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return InviteService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
getInviteToken = async ({ invite, teamId, userRoles }: { invite: Partial<Invite>; teamId: string; userRoles: UserRole[] }) => {
|
||||
invite.teamId = teamId;
|
||||
|
||||
const inviteRoles = invite.role ?? [];
|
||||
|
||||
for (const targetRole of inviteRoles) {
|
||||
const canManage = userRoles.some((actorRole) => canManageRole(actorRole, targetRole));
|
||||
if (!canManage) {
|
||||
throw new AppError({
|
||||
message: "You do not have permission to create this invite",
|
||||
service: SERVICE_NAME,
|
||||
method: "getInviteToken",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const inviteToken = await this.invitesRepository.create(invite);
|
||||
return inviteToken;
|
||||
};
|
||||
|
||||
sendInviteEmail = async ({ invite, firstName, userRoles }: { invite: Partial<Invite>; firstName: string; userRoles: UserRole[] }) => {
|
||||
const inviteRoles = invite.role ?? [];
|
||||
if (!invite.email) {
|
||||
throw new AppError({
|
||||
message: "Invite email is required to send an invite",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendInviteEmail",
|
||||
status: 400,
|
||||
});
|
||||
}
|
||||
|
||||
for (const targetRole of inviteRoles) {
|
||||
const canManage = userRoles.some((actorRole) => canManageRole(actorRole, targetRole));
|
||||
if (!canManage) {
|
||||
throw new AppError({
|
||||
message: "You do not have permission to create this invite",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendInviteEmail",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const inviteToken = await this.invitesRepository.create(invite);
|
||||
const { clientHost } = this.settingsService.getSettings();
|
||||
|
||||
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
|
||||
name: firstName,
|
||||
link: `${clientHost}/register/${inviteToken.token}`,
|
||||
});
|
||||
|
||||
if (!html) {
|
||||
throw new AppError({
|
||||
message: "Failed to build invite e-mail... Please verify your settings.",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendInviteEmail",
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
|
||||
const result = await this.emailService.sendEmail(invite.email, "Welcome to Uptime Monitor", html);
|
||||
if (!result) {
|
||||
throw new AppError({
|
||||
message: "Failed to send invite e-mail... Please verify your settings.",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendInviteEmail",
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
verifyInviteToken = async ({ inviteToken }: { inviteToken: string }) => {
|
||||
return await this.invitesRepository.findByToken(inviteToken);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { UserRole } from "@/domain/users/user.type.js";
|
||||
|
||||
export interface Invite {
|
||||
id: string;
|
||||
email: string;
|
||||
teamId: string;
|
||||
role: UserRole[];
|
||||
token: string;
|
||||
expiry: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import { DurationUnits, type MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
|
||||
type MaintenanceWindowDocumentBase = Omit<MaintenanceWindow, "id" | "monitorIds" | "teamId" | "start" | "end" | "createdAt" | "updatedAt"> & {
|
||||
monitorIds: Types.ObjectId[];
|
||||
teamId: Types.ObjectId;
|
||||
start: Date;
|
||||
end: Date;
|
||||
expiry?: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
interface MaintenanceWindowDocument extends MaintenanceWindowDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
const MaintenanceWindowSchema = new Schema<MaintenanceWindowDocument>(
|
||||
{
|
||||
monitorIds: {
|
||||
type: [Schema.Types.ObjectId],
|
||||
ref: "Monitor",
|
||||
index: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
},
|
||||
active: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
},
|
||||
duration: {
|
||||
type: Number,
|
||||
},
|
||||
durationUnit: {
|
||||
type: String,
|
||||
enum: DurationUnits,
|
||||
},
|
||||
repeat: {
|
||||
type: Number,
|
||||
},
|
||||
start: {
|
||||
type: Date,
|
||||
},
|
||||
end: {
|
||||
type: Date,
|
||||
},
|
||||
expiry: {
|
||||
type: Date,
|
||||
index: { expires: "0s" },
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
const MaintenanceWindowModel = model<MaintenanceWindowDocument>("MaintenanceWindow", MaintenanceWindowSchema);
|
||||
|
||||
export type { MaintenanceWindowDocument };
|
||||
export { MaintenanceWindowModel };
|
||||
export default MaintenanceWindowModel;
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
export interface IMaintenanceWindowsRepository {
|
||||
// create
|
||||
create(data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow>;
|
||||
// fetch
|
||||
findById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
||||
findByMonitorId(monitorId: string, teamId: string): Promise<MaintenanceWindow[]>;
|
||||
findByMonitorIds(monitorIds: string[], teamId: string, excludeId?: string): Promise<MaintenanceWindow[]>;
|
||||
findByTeamId(teamId: string, page: number, rowsPerPage: number, field?: string, order?: string, active?: boolean): Promise<MaintenanceWindow[]>;
|
||||
|
||||
// update
|
||||
updateById(id: string, teamId: string, data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow>;
|
||||
// delete
|
||||
deleteById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
||||
// other
|
||||
countByTeamId(teamId: string, active?: boolean): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
import { type MaintenanceWindowDocument, MaintenanceWindowModel } from "@/domain/maintenance-windows/maintenance-window.model.js";
|
||||
import { IMaintenanceWindowsRepository } from "./maintenance-window.repository.interface.js";
|
||||
import mongoose, { SortOrder } from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository {
|
||||
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();
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: MaintenanceWindowDocument[]): MaintenanceWindow[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
private toEntity = (doc: MaintenanceWindowDocument): MaintenanceWindow => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
monitorIds: doc.monitorIds.map(this.toStringId),
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
active: doc.active,
|
||||
name: doc.name,
|
||||
duration: doc.duration,
|
||||
durationUnit: doc.durationUnit,
|
||||
repeat: doc.repeat,
|
||||
start: this.toDateString(doc.start),
|
||||
end: this.toDateString(doc.end),
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow> => {
|
||||
const maintenanceWindow = new MaintenanceWindowModel(data);
|
||||
|
||||
// If the maintenance window is a one time window, set the expiry to the end date
|
||||
if (maintenanceWindow.repeat === 0) {
|
||||
maintenanceWindow.expiry = maintenanceWindow.end;
|
||||
}
|
||||
const result = await maintenanceWindow.save();
|
||||
return this.toEntity(result);
|
||||
};
|
||||
|
||||
findById = async (id: string, teamId: string): Promise<MaintenanceWindow> => {
|
||||
const maintenanceWindow = await MaintenanceWindowModel.findOne({
|
||||
_id: id,
|
||||
teamId: teamId,
|
||||
});
|
||||
if (!maintenanceWindow) {
|
||||
throw new AppError({ message: "Maintenance Window not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(maintenanceWindow);
|
||||
};
|
||||
|
||||
findByMonitorIds = async (monitorIds: string[], teamId: string, excludeId?: string): Promise<MaintenanceWindow[]> => {
|
||||
const query: Record<string, unknown> = {
|
||||
monitorIds: { $in: monitorIds },
|
||||
teamId,
|
||||
};
|
||||
if (excludeId) {
|
||||
query._id = { $ne: new mongoose.Types.ObjectId(excludeId) };
|
||||
}
|
||||
const maintenanceWindows = await MaintenanceWindowModel.find(query);
|
||||
return this.mapDocuments(maintenanceWindows);
|
||||
};
|
||||
|
||||
findByMonitorId = async (monitorId: string, teamId: string): Promise<MaintenanceWindow[]> => {
|
||||
const maintenanceWindows = await MaintenanceWindowModel.find({
|
||||
monitorIds: monitorId,
|
||||
teamId: teamId,
|
||||
});
|
||||
return this.mapDocuments(maintenanceWindows);
|
||||
};
|
||||
|
||||
findByTeamId = async (
|
||||
teamId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
field?: string,
|
||||
order?: string,
|
||||
active?: boolean
|
||||
): Promise<MaintenanceWindow[]> => {
|
||||
const maintenanceQuery: Record<string, unknown> = { teamId };
|
||||
|
||||
if (active !== undefined) maintenanceQuery.active = active;
|
||||
|
||||
// Pagination
|
||||
let skip = 0;
|
||||
if (page && rowsPerPage) {
|
||||
skip = page * rowsPerPage;
|
||||
}
|
||||
|
||||
// Sorting
|
||||
const sort: Record<string, SortOrder> = {};
|
||||
if (field !== undefined && order !== undefined) {
|
||||
sort[field] = order === "asc" ? 1 : -1;
|
||||
}
|
||||
|
||||
const maintenanceWindows = await MaintenanceWindowModel.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
|
||||
return this.mapDocuments(maintenanceWindows);
|
||||
};
|
||||
|
||||
updateById = async (id: string, teamId: string, data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow> => {
|
||||
const updated = await MaintenanceWindowModel.findOneAndUpdate(
|
||||
{
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
},
|
||||
{ $set: data },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updated) {
|
||||
throw new AppError({ message: "Maintenance window not found or could not be updated", status: 404 });
|
||||
}
|
||||
|
||||
return this.toEntity(updated);
|
||||
};
|
||||
|
||||
deleteById = async (id: string, teamId: string): Promise<MaintenanceWindow> => {
|
||||
const deleted = await MaintenanceWindowModel.findOneAndDelete({
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
if (!deleted) {
|
||||
throw new AppError({ message: "Maintenance window not found or could not be deleted", status: 404 });
|
||||
}
|
||||
|
||||
return this.toEntity(deleted);
|
||||
};
|
||||
countByTeamId = async (teamId: string, active?: boolean) => {
|
||||
const maintenanceQuery: Record<string, unknown> = { teamId };
|
||||
|
||||
if (active !== undefined) maintenanceQuery.active = active;
|
||||
|
||||
return await MaintenanceWindowModel.countDocuments(maintenanceQuery);
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoMaintenanceWindowsRepository;
|
||||
@@ -0,0 +1,218 @@
|
||||
import { IMaintenanceWindowsRepository } from "@/domain/maintenance-windows/maintenance-window.repository.interface.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { DurationUnit, MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { isWindowActive } from "@/utils/maintenanceWindow.js";
|
||||
|
||||
const SERVICE_NAME = "maintenanceWindowService";
|
||||
|
||||
export interface IMaintenanceWindowService {
|
||||
createMaintenanceWindow(params: {
|
||||
teamId: string;
|
||||
monitorIDs: string[];
|
||||
name: string;
|
||||
active: boolean;
|
||||
duration: number;
|
||||
durationUnit: DurationUnit;
|
||||
repeat: number;
|
||||
start: string;
|
||||
end: string;
|
||||
}): Promise<void>;
|
||||
getMaintenanceWindowById(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||
getMaintenanceWindowsByTeamId(params: {
|
||||
teamId: string;
|
||||
active?: boolean;
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
field?: string;
|
||||
order?: string;
|
||||
}): Promise<{ maintenanceWindows: MaintenanceWindow[]; maintenanceWindowCount: number }>;
|
||||
getMaintenanceWindowsByMonitorId(params: { monitorId: string; teamId: string }): Promise<MaintenanceWindow[]>;
|
||||
deleteMaintenanceWindow(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||
editMaintenanceWindow(params: {
|
||||
id: string;
|
||||
teamId: string;
|
||||
body: Partial<Omit<MaintenanceWindow, "monitorIds">> & { monitors?: string[] };
|
||||
}): Promise<MaintenanceWindow>;
|
||||
}
|
||||
|
||||
export class MaintenanceWindowService implements IMaintenanceWindowService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private maintenanceWindowsRepository: IMaintenanceWindowsRepository;
|
||||
|
||||
constructor({
|
||||
monitorsRepository,
|
||||
maintenanceWindowsRepository,
|
||||
}: {
|
||||
monitorsRepository: IMonitorsRepository;
|
||||
maintenanceWindowsRepository: IMaintenanceWindowsRepository;
|
||||
}) {
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.maintenanceWindowsRepository = maintenanceWindowsRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return MaintenanceWindowService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
private flipMonitorsLeavingMaintenance = async (monitorIds: string[], teamId: string, excludeWindowId: string, now: Date): Promise<void> => {
|
||||
if (monitorIds.length === 0) return;
|
||||
|
||||
const otherWindows = await this.maintenanceWindowsRepository.findByMonitorIds(monitorIds, teamId, excludeWindowId);
|
||||
const stillCovered = new Set<string>();
|
||||
for (const otherWindow of otherWindows) {
|
||||
if (!isWindowActive(otherWindow, now)) continue;
|
||||
for (const monitorId of otherWindow.monitorIds) {
|
||||
if (monitorIds.includes(monitorId)) stillCovered.add(monitorId);
|
||||
}
|
||||
}
|
||||
|
||||
const toInitializing = monitorIds.filter((monitorId) => !stillCovered.has(monitorId));
|
||||
if (toInitializing.length > 0) {
|
||||
await this.monitorsRepository.updateByIds(toInitializing, teamId, { status: "initializing" }, ["paused"]);
|
||||
}
|
||||
};
|
||||
|
||||
createMaintenanceWindow = async ({
|
||||
teamId,
|
||||
monitorIDs,
|
||||
name,
|
||||
active,
|
||||
duration,
|
||||
durationUnit,
|
||||
repeat,
|
||||
start,
|
||||
end,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorIDs: string[];
|
||||
name: string;
|
||||
active: boolean;
|
||||
duration: number;
|
||||
durationUnit: DurationUnit;
|
||||
repeat: number;
|
||||
start: string;
|
||||
end: string;
|
||||
}) => {
|
||||
const monitors = await this.monitorsRepository.findByIds(monitorIDs);
|
||||
|
||||
const unauthorizedMonitors = monitors.filter((monitor) => monitor.teamId !== teamId);
|
||||
|
||||
if (unauthorizedMonitors.length > 0) {
|
||||
throw new AppError({
|
||||
message: "Unauthorized to create maintenance window for one or more monitors",
|
||||
service: SERVICE_NAME,
|
||||
method: "createMaintenanceWindow",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const created = await this.maintenanceWindowsRepository.create({
|
||||
teamId,
|
||||
monitorIds: monitorIDs,
|
||||
name: name,
|
||||
active: active,
|
||||
duration: duration,
|
||||
durationUnit: durationUnit,
|
||||
repeat: repeat,
|
||||
start: start,
|
||||
end: end,
|
||||
});
|
||||
|
||||
if (isWindowActive(created)) {
|
||||
await this.monitorsRepository.updateByIds(created.monitorIds, teamId, { status: "maintenance" }, ["paused"]);
|
||||
}
|
||||
};
|
||||
|
||||
getMaintenanceWindowById = async ({ id, teamId }: { id: string; teamId: string }) => {
|
||||
return await this.maintenanceWindowsRepository.findById(id, teamId);
|
||||
};
|
||||
|
||||
getMaintenanceWindowsByTeamId = async ({
|
||||
teamId,
|
||||
active,
|
||||
page,
|
||||
rowsPerPage,
|
||||
field,
|
||||
order,
|
||||
}: {
|
||||
teamId: string;
|
||||
active?: boolean;
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
field?: string;
|
||||
order?: string;
|
||||
}) => {
|
||||
page = page ?? 0;
|
||||
rowsPerPage = rowsPerPage ?? 10;
|
||||
|
||||
const maintenanceWindows = await this.maintenanceWindowsRepository.findByTeamId(teamId, page, rowsPerPage, field, order, active);
|
||||
const maintenanceWindowCount = await this.maintenanceWindowsRepository.countByTeamId(teamId, active);
|
||||
return { maintenanceWindows, maintenanceWindowCount };
|
||||
};
|
||||
|
||||
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => {
|
||||
return await this.maintenanceWindowsRepository.findByMonitorId(monitorId, teamId);
|
||||
};
|
||||
|
||||
deleteMaintenanceWindow = async ({ id, teamId }: { id: string; teamId: string }) => {
|
||||
const deleted = await this.maintenanceWindowsRepository.deleteById(id, teamId);
|
||||
|
||||
const now = new Date();
|
||||
if (isWindowActive(deleted, now)) {
|
||||
await this.flipMonitorsLeavingMaintenance(deleted.monitorIds, teamId, deleted.id, now);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
};
|
||||
|
||||
editMaintenanceWindow = async ({
|
||||
id,
|
||||
teamId,
|
||||
body,
|
||||
}: {
|
||||
id: string;
|
||||
teamId: string;
|
||||
body: Partial<Omit<MaintenanceWindow, "monitorIds">> & { monitors?: string[] };
|
||||
}) => {
|
||||
const existing = await this.maintenanceWindowsRepository.findById(id, teamId);
|
||||
|
||||
const { monitors, ...rest } = body;
|
||||
const update: Partial<MaintenanceWindow> = rest;
|
||||
|
||||
if (monitors !== undefined) {
|
||||
const monitorDocs = await this.monitorsRepository.findByIds(monitors);
|
||||
const unauthorizedMonitors = monitorDocs.filter((monitor) => monitor.teamId !== teamId);
|
||||
if (unauthorizedMonitors.length > 0) {
|
||||
throw new AppError({
|
||||
message: "Unauthorized to edit maintenance window for one or more monitors",
|
||||
service: SERVICE_NAME,
|
||||
method: "editMaintenanceWindow",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
update.monitorIds = monitors;
|
||||
}
|
||||
|
||||
const updated = await this.maintenanceWindowsRepository.updateById(id, teamId, update);
|
||||
|
||||
const now = new Date();
|
||||
const wasActive = isWindowActive(existing, now);
|
||||
const isActive = isWindowActive(updated, now);
|
||||
|
||||
const enteringMaintenance = isActive ? updated.monitorIds.filter((monitorId) => !wasActive || !existing.monitorIds.includes(monitorId)) : [];
|
||||
|
||||
const leavingCandidates = wasActive ? existing.monitorIds.filter((monitorId) => !isActive || !updated.monitorIds.includes(monitorId)) : [];
|
||||
|
||||
if (enteringMaintenance.length > 0) {
|
||||
await this.monitorsRepository.updateByIds(enteringMaintenance, teamId, { status: "maintenance" }, ["paused"]);
|
||||
}
|
||||
|
||||
if (leavingCandidates.length > 0) {
|
||||
await this.flipMonitorsLeavingMaintenance(leavingCandidates, teamId, existing.id, now);
|
||||
}
|
||||
|
||||
return updated;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export const DurationUnits = ["seconds", "minutes", "hours", "days"] as const;
|
||||
export type DurationUnit = (typeof DurationUnits)[number];
|
||||
|
||||
export interface MaintenanceWindow {
|
||||
id: string;
|
||||
monitorIds: string[];
|
||||
teamId: string;
|
||||
active: boolean;
|
||||
name: string;
|
||||
duration: number;
|
||||
durationUnit: DurationUnit;
|
||||
repeat: number;
|
||||
start: string;
|
||||
end: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
const MigrationSchema = new mongoose.Schema(
|
||||
{
|
||||
name: { type: String, required: true, unique: true },
|
||||
status: { type: String, enum: ["completed", "failed"], default: "completed" },
|
||||
completedAt: { type: Date },
|
||||
error: { type: String },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
export default mongoose.model("Migration", MigrationSchema);
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { MonitorStats as MonitorStatsEntity } from "@/domain/monitor-stats/monitor-stats.type.js";
|
||||
|
||||
type MonitorStatsDocumentBase = Omit<MonitorStatsEntity, "id" | "monitorId" | "createdAt" | "updatedAt"> & {
|
||||
monitorId: Types.ObjectId;
|
||||
};
|
||||
|
||||
interface MonitorStatsDocument extends MonitorStatsDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const MonitorStatsSchema = new Schema<MonitorStatsDocument>(
|
||||
{
|
||||
monitorId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Monitor",
|
||||
unique: true,
|
||||
required: true,
|
||||
},
|
||||
avgResponseTime: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
maxResponseTime: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
totalChecks: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
totalUpChecks: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
totalDownChecks: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
uptimePercentage: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
lastCheckTimestamp: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
lastResponseTime: {
|
||||
type: Number,
|
||||
default: 0,
|
||||
},
|
||||
timeOfLastFailure: {
|
||||
type: Number,
|
||||
default: undefined,
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
const MonitorStatsModel = model<MonitorStatsDocument>("MonitorStats", MonitorStatsSchema);
|
||||
|
||||
export type { MonitorStatsDocument };
|
||||
export { MonitorStatsModel };
|
||||
export default MonitorStatsModel;
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { CheckResultInput, MonitorStats } from "@/domain/monitor-stats/monitor-stats.type.js";
|
||||
|
||||
export interface IMonitorStatsRepository {
|
||||
// create
|
||||
create(data: Omit<MonitorStats, "id" | "createdAt" | "updatedAt">): Promise<MonitorStats>;
|
||||
// single fetch
|
||||
findByMonitorId(monitorId: string): Promise<MonitorStats>;
|
||||
// Upsert must be atomic to prevent race conditions
|
||||
updateByMonitorId(monitorId: string, result: CheckResultInput): Promise<MonitorStats>;
|
||||
// delete
|
||||
deleteByMonitorId(monitorId: string): Promise<MonitorStats>;
|
||||
deleteByMonitorIds(monitorIds: string[]): Promise<number>;
|
||||
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
|
||||
// other
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { type MonitorStatsDocument, MonitorStatsModel } from "@/domain/monitor-stats/monitor-stats.model.js";
|
||||
import type { CheckResultInput, MonitorStats } from "@/domain/monitor-stats/monitor-stats.type.js";
|
||||
import { IMonitorStatsRepository } from "@/domain/monitor-stats/monitor-stats.repository.interface.js";
|
||||
import mongoose from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
class MongoMonitorStatsRepository implements IMonitorStatsRepository {
|
||||
private toEntity = (doc: MonitorStatsDocument): MonitorStats => {
|
||||
const toStringId = (value: unknown): string => {
|
||||
if (value instanceof mongoose.Types.ObjectId) {
|
||||
return value.toString();
|
||||
}
|
||||
return value?.toString() ?? "";
|
||||
};
|
||||
|
||||
const toDateString = (value: Date | string): string => {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
};
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
monitorId: toStringId(doc.monitorId),
|
||||
avgResponseTime: doc.avgResponseTime,
|
||||
maxResponseTime: doc.maxResponseTime,
|
||||
totalChecks: doc.totalChecks,
|
||||
totalUpChecks: doc.totalUpChecks,
|
||||
totalDownChecks: doc.totalDownChecks,
|
||||
uptimePercentage: doc.uptimePercentage,
|
||||
lastCheckTimestamp: doc.lastCheckTimestamp,
|
||||
lastResponseTime: doc.lastResponseTime,
|
||||
timeOfLastFailure: doc.timeOfLastFailure,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (data: Omit<MonitorStats, "id" | "createdAt" | "updatedAt">): Promise<MonitorStats> => {
|
||||
const created = await MonitorStatsModel.create(data);
|
||||
return this.toEntity(created);
|
||||
};
|
||||
|
||||
findByMonitorId = async (monitorId: string): Promise<MonitorStats> => {
|
||||
const monitorStats = await MonitorStatsModel.findOne({ monitorId: new mongoose.Types.ObjectId(monitorId) });
|
||||
if (!monitorStats) {
|
||||
throw new AppError({ message: "Monitor stats not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(monitorStats);
|
||||
};
|
||||
|
||||
updateByMonitorId = async (monitorId: string, result: CheckResultInput): Promise<MonitorStats> => {
|
||||
const { status, responseTime, now } = result;
|
||||
const objectId = new mongoose.Types.ObjectId(monitorId);
|
||||
const upDelta = status ? 1 : 0;
|
||||
const downDelta = status ? 0 : 1;
|
||||
const pipeline = [
|
||||
{
|
||||
$set: {
|
||||
monitorId: objectId,
|
||||
totalChecks: { $add: [{ $ifNull: ["$totalChecks", 0] }, 1] },
|
||||
totalUpChecks: { $add: [{ $ifNull: ["$totalUpChecks", 0] }, upDelta] },
|
||||
totalDownChecks: { $add: [{ $ifNull: ["$totalDownChecks", 0] }, downDelta] },
|
||||
avgResponseTime: {
|
||||
$divide: [
|
||||
{
|
||||
$add: [{ $multiply: [{ $ifNull: ["$avgResponseTime", 0] }, { $ifNull: ["$totalChecks", 0] }] }, responseTime],
|
||||
},
|
||||
{ $add: [{ $ifNull: ["$totalChecks", 0] }, 1] },
|
||||
],
|
||||
},
|
||||
uptimePercentage: {
|
||||
$divide: [{ $add: [{ $ifNull: ["$totalUpChecks", 0] }, upDelta] }, { $add: [{ $ifNull: ["$totalChecks", 0] }, 1] }],
|
||||
},
|
||||
maxResponseTime: { $max: [{ $ifNull: ["$maxResponseTime", 0] }, responseTime] },
|
||||
lastResponseTime: responseTime,
|
||||
lastCheckTimestamp: now,
|
||||
timeOfLastFailure: status
|
||||
? {
|
||||
$cond: [{ $eq: [{ $ifNull: ["$timeOfLastFailure", 0] }, 0] }, now, "$timeOfLastFailure"],
|
||||
}
|
||||
: 0,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const updated = await MonitorStatsModel.findOneAndUpdate({ monitorId: objectId }, pipeline, {
|
||||
upsert: true,
|
||||
new: true,
|
||||
setDefaultsOnInsert: true,
|
||||
});
|
||||
if (!updated) {
|
||||
throw new AppError({ message: "Failed to apply check result to monitor stats", status: 500 });
|
||||
}
|
||||
return this.toEntity(updated);
|
||||
};
|
||||
|
||||
deleteByMonitorId = async (monitorId: string) => {
|
||||
const deleted = await MonitorStatsModel.findOneAndDelete({ monitorId: new mongoose.Types.ObjectId(monitorId) });
|
||||
if (!deleted) {
|
||||
throw new AppError({ message: "Monitor stats not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(deleted);
|
||||
};
|
||||
|
||||
deleteByMonitorIds = async (monitorIds: string[]): Promise<number> => {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const result = await MonitorStatsModel.deleteMany({ monitorId: { $in: objectIds } });
|
||||
return result.deletedCount ?? 0;
|
||||
};
|
||||
|
||||
deleteByMonitorIdsNotIn = async (monitorIds: string[]): Promise<number> => {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const result = await MonitorStatsModel.deleteMany({ monitorId: { $nin: objectIds } });
|
||||
return result.deletedCount ?? 0;
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoMonitorStatsRepository;
|
||||
@@ -0,0 +1,21 @@
|
||||
export interface CheckResultInput {
|
||||
status: boolean;
|
||||
responseTime: number;
|
||||
now: number;
|
||||
}
|
||||
|
||||
export interface MonitorStats {
|
||||
id: string;
|
||||
monitorId: string;
|
||||
avgResponseTime: number;
|
||||
maxResponseTime: number;
|
||||
totalChecks: number;
|
||||
totalUpChecks: number;
|
||||
totalDownChecks: number;
|
||||
uptimePercentage: number;
|
||||
lastCheckTimestamp: number;
|
||||
lastResponseTime: number;
|
||||
timeOfLastFailure?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
import { Schema, model, Types } from "mongoose";
|
||||
import type { Monitor, MonitorMatchMethod, CheckSnapshot } from "@/domain/monitors/monitor.types.js";
|
||||
import { DnsRecordTypes, MonitorTypes, MonitorStatuses, PageSpeedStrategies } from "@/domain/monitors/monitor.types.js";
|
||||
import type {
|
||||
CheckAudits,
|
||||
CheckCaptureInfo,
|
||||
CheckCpuInfo,
|
||||
CheckDiskInfo,
|
||||
CheckErrorInfo,
|
||||
CheckHostInfo,
|
||||
CheckMemoryInfo,
|
||||
CheckNetworkInterfaceInfo,
|
||||
GotTimings,
|
||||
ILighthouseAudit,
|
||||
} from "@/domain/checks/check.type.js";
|
||||
|
||||
type CheckSnapshotDocument = Omit<CheckSnapshot, "createdAt"> & { createdAt: Date };
|
||||
|
||||
type MonitorDocumentBase = Omit<
|
||||
Monitor,
|
||||
"id" | "userId" | "teamId" | "notifications" | "tags" | "selectedDisks" | "statusWindow" | "recentChecks" | "createdAt" | "updatedAt"
|
||||
> & {
|
||||
statusWindow: boolean[];
|
||||
recentChecks: CheckSnapshotDocument[];
|
||||
notifications: Types.ObjectId[];
|
||||
tags: Types.ObjectId[];
|
||||
selectedDisks: string[];
|
||||
matchMethod?: MonitorMatchMethod;
|
||||
};
|
||||
|
||||
interface MonitorDocument extends MonitorDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
userId: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const snapshotTimingPhasesSchema = new Schema<GotTimings["phases"]>(
|
||||
{
|
||||
wait: { type: Number },
|
||||
dns: { type: Number },
|
||||
tcp: { type: Number },
|
||||
tls: { type: Number },
|
||||
request: { type: Number },
|
||||
firstByte: { type: Number },
|
||||
download: { type: Number },
|
||||
total: { type: Number },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotTimingsSchema = new Schema<GotTimings>(
|
||||
{
|
||||
start: { type: Number },
|
||||
socket: { type: Number },
|
||||
lookup: { type: Number },
|
||||
connect: { type: Number },
|
||||
secureConnect: { type: Number },
|
||||
upload: { type: Number },
|
||||
response: { type: Number },
|
||||
end: { type: Number },
|
||||
phases: { type: snapshotTimingPhasesSchema },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotCpuSchema = new Schema<CheckCpuInfo>(
|
||||
{
|
||||
physical_core: { type: Number },
|
||||
logical_core: { type: Number },
|
||||
frequency: { type: Number },
|
||||
current_frequency: { type: Number },
|
||||
temperature: { type: [Number] },
|
||||
free_percent: { type: Number },
|
||||
usage_percent: { type: Number },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotMemorySchema = new Schema<CheckMemoryInfo>(
|
||||
{
|
||||
total_bytes: { type: Number },
|
||||
available_bytes: { type: Number },
|
||||
used_bytes: { type: Number },
|
||||
usage_percent: { type: Number },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotDiskSchema = new Schema<CheckDiskInfo>(
|
||||
{
|
||||
device: { type: String },
|
||||
mountpoint: { type: String },
|
||||
total_bytes: { type: Number },
|
||||
free_bytes: { type: Number },
|
||||
used_bytes: { type: Number },
|
||||
usage_percent: { type: Number },
|
||||
total_inodes: { type: Number },
|
||||
free_inodes: { type: Number },
|
||||
used_inodes: { type: Number },
|
||||
inodes_usage_percent: { type: Number },
|
||||
read_bytes: { type: Number },
|
||||
write_bytes: { type: Number },
|
||||
read_time: { type: Number },
|
||||
write_time: { type: Number },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotHostSchema = new Schema<CheckHostInfo>(
|
||||
{
|
||||
os: { type: String },
|
||||
platform: { type: String },
|
||||
kernel_version: { type: String },
|
||||
pretty_name: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotErrorSchema = new Schema<CheckErrorInfo>(
|
||||
{
|
||||
metric: { type: [String] },
|
||||
err: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotCaptureSchema = new Schema<CheckCaptureInfo>(
|
||||
{
|
||||
version: { type: String },
|
||||
mode: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotNetworkInterfaceSchema = new Schema<CheckNetworkInterfaceInfo>(
|
||||
{
|
||||
name: { type: String },
|
||||
bytes_sent: { type: Number },
|
||||
bytes_recv: { type: Number },
|
||||
packets_sent: { type: Number },
|
||||
packets_recv: { type: Number },
|
||||
err_in: { type: Number },
|
||||
err_out: { type: Number },
|
||||
drop_in: { type: Number },
|
||||
drop_out: { type: Number },
|
||||
fifo_in: { type: Number },
|
||||
fifo_out: { type: Number },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotLighthouseAuditSchema = new Schema<ILighthouseAudit>(
|
||||
{
|
||||
id: { type: String },
|
||||
title: { type: String },
|
||||
score: { type: Number },
|
||||
displayValue: { type: String },
|
||||
numericValue: { type: Number },
|
||||
numericUnit: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const snapshotAuditsSchema = new Schema<CheckAudits>(
|
||||
{
|
||||
cls: { type: snapshotLighthouseAuditSchema },
|
||||
si: { type: snapshotLighthouseAuditSchema },
|
||||
fcp: { type: snapshotLighthouseAuditSchema },
|
||||
lcp: { type: snapshotLighthouseAuditSchema },
|
||||
tbt: { type: snapshotLighthouseAuditSchema },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const checkSnapshotSchema = new Schema<CheckSnapshotDocument>(
|
||||
{
|
||||
id: { type: String, required: true },
|
||||
status: { type: Boolean, required: true },
|
||||
responseTime: { type: Number },
|
||||
timings: { type: snapshotTimingsSchema },
|
||||
statusCode: { type: Number },
|
||||
message: { type: String },
|
||||
cpu: { type: snapshotCpuSchema },
|
||||
memory: { type: snapshotMemorySchema },
|
||||
disk: { type: [snapshotDiskSchema] },
|
||||
host: { type: snapshotHostSchema },
|
||||
errors: { type: [snapshotErrorSchema] },
|
||||
capture: { type: snapshotCaptureSchema },
|
||||
net: { type: [snapshotNetworkInterfaceSchema] },
|
||||
accessibility: { type: Number },
|
||||
bestPractices: { type: Number },
|
||||
seo: { type: Number },
|
||||
performance: { type: Number },
|
||||
audits: { type: snapshotAuditsSchema },
|
||||
createdAt: { type: Date, required: true },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const MonitorSchema = new Schema<MonitorDocument>(
|
||||
{
|
||||
userId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
description: {
|
||||
type: String,
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: MonitorStatuses,
|
||||
default: "initializing",
|
||||
},
|
||||
statusWindow: {
|
||||
type: [Boolean],
|
||||
default: [],
|
||||
},
|
||||
statusWindowSize: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
},
|
||||
statusWindowThreshold: {
|
||||
type: Number,
|
||||
default: 60,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
required: true,
|
||||
enum: MonitorTypes,
|
||||
},
|
||||
ignoreTlsErrors: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
useAdvancedMatching: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
jsonPath: {
|
||||
type: String,
|
||||
},
|
||||
expectedValue: {
|
||||
type: String,
|
||||
},
|
||||
matchMethod: {
|
||||
type: String,
|
||||
enum: ["equal", "include", "regex", ""],
|
||||
},
|
||||
url: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
port: {
|
||||
type: Number,
|
||||
},
|
||||
isActive: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
interval: {
|
||||
type: Number,
|
||||
default: 60000,
|
||||
},
|
||||
uptimePercentage: {
|
||||
type: Number,
|
||||
default: undefined,
|
||||
},
|
||||
notifications: [
|
||||
{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Notification",
|
||||
},
|
||||
],
|
||||
tags: [
|
||||
{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Tag",
|
||||
},
|
||||
],
|
||||
customUpCodes: {
|
||||
type: [Number],
|
||||
default: [],
|
||||
},
|
||||
secret: {
|
||||
type: String,
|
||||
},
|
||||
cpuAlertThreshold: {
|
||||
type: Number,
|
||||
default: 100,
|
||||
},
|
||||
cpuAlertCounter: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
},
|
||||
memoryAlertThreshold: {
|
||||
type: Number,
|
||||
default: 100,
|
||||
},
|
||||
memoryAlertCounter: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
},
|
||||
diskAlertThreshold: {
|
||||
type: Number,
|
||||
default: 100,
|
||||
},
|
||||
diskAlertCounter: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
},
|
||||
tempAlertThreshold: {
|
||||
type: Number,
|
||||
default: 100,
|
||||
},
|
||||
tempAlertCounter: {
|
||||
type: Number,
|
||||
default: 5,
|
||||
},
|
||||
selectedDisks: {
|
||||
type: [String],
|
||||
default: [],
|
||||
},
|
||||
gameId: {
|
||||
type: String,
|
||||
},
|
||||
grpcServiceName: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
strategy: {
|
||||
type: String,
|
||||
enum: PageSpeedStrategies,
|
||||
},
|
||||
group: {
|
||||
type: String,
|
||||
trim: true,
|
||||
maxLength: 50,
|
||||
default: null,
|
||||
set(value: string | null) {
|
||||
return value && value.trim() ? value.trim() : null;
|
||||
},
|
||||
},
|
||||
geoCheckEnabled: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
geoCheckLocations: {
|
||||
type: [String],
|
||||
default: [],
|
||||
},
|
||||
geoCheckInterval: {
|
||||
type: Number,
|
||||
default: 300000,
|
||||
},
|
||||
dnsServer: {
|
||||
type: String,
|
||||
},
|
||||
dnsRecordType: {
|
||||
type: String,
|
||||
enum: DnsRecordTypes,
|
||||
},
|
||||
recentChecks: {
|
||||
type: [checkSnapshotSchema],
|
||||
default: [],
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
MonitorSchema.index({ teamId: 1, type: 1 });
|
||||
|
||||
const MonitorModel = model<MonitorDocument>("Monitor", MonitorSchema);
|
||||
|
||||
export type { MonitorDocument, CheckSnapshotDocument };
|
||||
export { MonitorModel };
|
||||
export default MonitorModel;
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { MonitorType, Monitor, MonitorStatus, MonitorsSummary, CheckSnapshot } from "@/domain/monitors/monitor.types.js";
|
||||
|
||||
export interface TeamQueryConfig {
|
||||
limit?: number;
|
||||
type?: MonitorType | MonitorType[];
|
||||
tags?: string | string[];
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
filter?: string;
|
||||
field?: string;
|
||||
order?: "asc" | "desc";
|
||||
}
|
||||
|
||||
export interface SummaryConfig {
|
||||
type?: MonitorType | MonitorType[];
|
||||
tags?: string | string[];
|
||||
}
|
||||
|
||||
export interface IMonitorsRepository {
|
||||
// create
|
||||
create(monitor: Monitor, teamId: string, userId: string): Promise<Monitor | null>;
|
||||
createMonitors(monitors: Monitor[]): Promise<Monitor[]>;
|
||||
// single fetch
|
||||
findById(monitorId: string, teamId: string): Promise<Monitor>;
|
||||
|
||||
// collection fetch
|
||||
findAll(): Promise<Monitor[] | null>;
|
||||
findByTeamId(teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null>;
|
||||
findByTeamIdWithStats(teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null>;
|
||||
findByIds(monitorIds: string[]): Promise<Monitor[]>;
|
||||
findByIdsWithChecks(monitorIds: string[], checksCount?: number): Promise<Monitor[]>;
|
||||
|
||||
// update
|
||||
updateById(monitorId: string, teamId: string, updates: Partial<Monitor>): Promise<Monitor>;
|
||||
updateByIds(monitorIds: string[], teamId: string, updates: Partial<Monitor>, excludeStatuses?: MonitorStatus[]): Promise<number>;
|
||||
updateStatusWindowAndChecks(
|
||||
monitorId: string,
|
||||
teamId: string,
|
||||
status: boolean,
|
||||
checkSnapshot: CheckSnapshot,
|
||||
windowSize: number,
|
||||
maxRecentChecks: number,
|
||||
statusPatch?: Partial<Monitor>
|
||||
): Promise<Monitor>;
|
||||
togglePauseById(monitorId: string, teamId: string): Promise<Monitor>;
|
||||
bulkTogglePause(monitorIds: string[], teamId: string, pause: boolean): Promise<Monitor[]>;
|
||||
// delete
|
||||
deleteById(monitorId: string, teamId: string): Promise<Monitor>;
|
||||
deleteByTeamId(teamId: string): Promise<{ monitors: Monitor[]; deletedCount: number }>;
|
||||
|
||||
// counts
|
||||
findMonitorCountByTeamIdAndType(teamId: string, config: TeamQueryConfig): Promise<number>;
|
||||
|
||||
// other
|
||||
findMonitorsSummaryByTeamId(teamId: string, config?: SummaryConfig): Promise<MonitorsSummary>;
|
||||
findGroupsByTeamId(teamId: string): Promise<string[]>;
|
||||
removeNotificationFromMonitors(notificationId: string): Promise<void>;
|
||||
removeTagFromMonitors(tagId: string): Promise<void>;
|
||||
updateNotifications(teamId: string, monitorIds: string[], notificationIds: string[], action: "add" | "remove" | "set"): Promise<number>;
|
||||
deleteByTeamIdsNotIn(teamIds: string[]): Promise<number>;
|
||||
findAllMonitorIds(): Promise<string[]>;
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
import { MonitorModel } from "@/domain/monitors/monitor.model.js";
|
||||
import type { MonitorDocument, CheckSnapshotDocument } from "@/domain/monitors/monitor.model.js";
|
||||
import type { CheckSnapshot } from "@/domain/checks/check.type.js";
|
||||
import type { Monitor, MonitorStatus, MonitorsSummary } from "@/domain/monitors/monitor.types.js";
|
||||
import mongoose, { type FilterQuery, type PipelineStage } from "mongoose";
|
||||
import { MongoBulkWriteError } from "mongodb";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { IMonitorsRepository, TeamQueryConfig, SummaryConfig } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
class MongoMonitorsRepository implements IMonitorsRepository {
|
||||
create = async (monitor: Monitor, teamId: string, userId: string) => {
|
||||
const monitorModel = new MonitorModel({ ...monitor, teamId, userId });
|
||||
const saved = await monitorModel.save();
|
||||
return this.toEntity(saved);
|
||||
};
|
||||
|
||||
createMonitors = async (monitors: Monitor[]): Promise<Monitor[]> => {
|
||||
if (!monitors.length) {
|
||||
return [];
|
||||
}
|
||||
const payload = monitors.map((monitor) => ({ ...monitor, notifications: undefined }));
|
||||
try {
|
||||
const inserted = await MonitorModel.insertMany(payload, { ordered: false });
|
||||
return this.mapDocuments(inserted);
|
||||
} catch (error: unknown) {
|
||||
if (error instanceof MongoBulkWriteError && "insertedDocs" in error && Array.isArray(error.insertedDocs) && error.insertedDocs.length > 0) {
|
||||
return this.mapDocuments(error.insertedDocs);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
findById = async (monitorId: string, teamId: string): Promise<Monitor> => {
|
||||
const match: { _id: string; teamId: string } = { _id: monitorId, teamId };
|
||||
const monitor = await MonitorModel.findOne(match);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found`, status: 404 });
|
||||
}
|
||||
return this.toEntity(monitor);
|
||||
};
|
||||
|
||||
findAll = async (): Promise<Monitor[]> => {
|
||||
const monitors = await MonitorModel.find();
|
||||
return this.mapDocuments(monitors);
|
||||
};
|
||||
|
||||
findByTeamId = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null> => {
|
||||
const { page = 0, rowsPerPage = 0, filter, field = "createdAt", order = "desc", type, tags } = config ?? {};
|
||||
|
||||
const query: Record<string, unknown> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
};
|
||||
|
||||
if (type !== undefined) {
|
||||
query.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
if (tags !== undefined) {
|
||||
query.tags = Array.isArray(tags) ? { $in: tags } : tags;
|
||||
}
|
||||
|
||||
if (filter !== undefined) {
|
||||
switch (field) {
|
||||
case "name":
|
||||
query.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
|
||||
break;
|
||||
case "isActive":
|
||||
query.isActive = filter === "true";
|
||||
break;
|
||||
case "status":
|
||||
query.status = filter;
|
||||
break;
|
||||
case "type":
|
||||
query.type = filter;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const sort = { [field]: order === "asc" ? 1 : -1 } as const;
|
||||
const skip = Math.max(page, 0) * rowsPerPage;
|
||||
|
||||
const documents = await MonitorModel.find(query).sort(sort).skip(skip).limit(rowsPerPage);
|
||||
|
||||
return this.mapDocuments(documents);
|
||||
};
|
||||
|
||||
findByTeamIdWithStats = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[] | null> => {
|
||||
const { page = 0, rowsPerPage = 0, filter, field = "createdAt", order = "desc", type, tags } = config ?? {};
|
||||
|
||||
const query: Record<string, unknown> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
};
|
||||
|
||||
if (type !== undefined) {
|
||||
query.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
if (tags !== undefined) {
|
||||
query.tags = Array.isArray(tags) ? { $in: tags } : tags;
|
||||
}
|
||||
|
||||
if (filter !== undefined) {
|
||||
switch (field) {
|
||||
case "name":
|
||||
query.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
|
||||
break;
|
||||
case "isActive":
|
||||
query.isActive = filter === "true";
|
||||
break;
|
||||
case "status":
|
||||
query.status = filter;
|
||||
break;
|
||||
case "type":
|
||||
query.type = filter;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const sort = { [field]: order === "asc" ? 1 : -1 } as const;
|
||||
const skip = Math.max(page, 0) * rowsPerPage;
|
||||
|
||||
const pipeline: PipelineStage[] = [
|
||||
{ $match: query },
|
||||
{ $sort: sort },
|
||||
...(rowsPerPage ? [{ $skip: skip }, { $limit: rowsPerPage }] : []),
|
||||
{
|
||||
$lookup: {
|
||||
from: "monitorstats",
|
||||
localField: "_id",
|
||||
foreignField: "monitorId",
|
||||
as: "stats",
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
uptimePercentage: { $arrayElemAt: ["$stats.uptimePercentage", 0] },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
stats: 0,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const documents = await MonitorModel.aggregate(pipeline);
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
findByIds = async (monitorIds: string[]): Promise<Monitor[]> => {
|
||||
if (!monitorIds.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
|
||||
const pipeline: PipelineStage[] = [
|
||||
{ $match: { _id: { $in: objectIds } } },
|
||||
{
|
||||
$lookup: {
|
||||
from: "monitorstats",
|
||||
localField: "_id",
|
||||
foreignField: "monitorId",
|
||||
as: "stats",
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
uptimePercentage: { $arrayElemAt: ["$stats.uptimePercentage", 0] },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
stats: 0,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const documents = await MonitorModel.aggregate(pipeline);
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
findByIdsWithChecks = async (monitorIds: string[], checksCount: number = 25): Promise<Monitor[]> => {
|
||||
if (!monitorIds.length) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
|
||||
const pipeline: PipelineStage[] = [
|
||||
{ $match: { _id: { $in: objectIds } } },
|
||||
{
|
||||
$lookup: {
|
||||
from: "checks",
|
||||
let: { monitorId: "$_id" },
|
||||
pipeline: [{ $match: { $expr: { $eq: ["$metadata.monitorId", "$$monitorId"] } } }, { $sort: { createdAt: -1 } }, { $limit: checksCount }],
|
||||
as: "checks",
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: "maintenancewindows",
|
||||
let: { monitorId: "$_id" },
|
||||
pipeline: [{ $match: { $expr: { $in: ["$$monitorId", { $ifNull: ["$monitorIds", []] }] } } }],
|
||||
as: "maintenanceWindows",
|
||||
},
|
||||
},
|
||||
{
|
||||
$lookup: {
|
||||
from: "monitorstats",
|
||||
localField: "_id",
|
||||
foreignField: "monitorId",
|
||||
as: "stats",
|
||||
},
|
||||
},
|
||||
{
|
||||
$addFields: {
|
||||
isMaintenance: {
|
||||
$reduce: {
|
||||
input: "$maintenanceWindows",
|
||||
initialValue: false,
|
||||
in: {
|
||||
$or: [
|
||||
"$$value",
|
||||
{
|
||||
$and: [{ $eq: ["$$this.active", true] }, { $lte: ["$$this.start", "$$NOW"] }, { $gte: ["$$this.end", "$$NOW"] }],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
uptimePercentage: { $arrayElemAt: ["$stats.uptimePercentage", 0] },
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
maintenanceWindows: 0,
|
||||
stats: 0,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const documents = await MonitorModel.aggregate(pipeline);
|
||||
return documents.map((doc) => this.toEntityWithChecks(doc));
|
||||
};
|
||||
|
||||
findMonitorCountByTeamIdAndType = async (teamId: string, config?: TeamQueryConfig): Promise<number> => {
|
||||
const { type, tags } = config ?? {};
|
||||
|
||||
const query: FilterQuery<MonitorDocument> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
};
|
||||
|
||||
if (type !== undefined) {
|
||||
query.type = Array.isArray(type) ? { $in: type } : type;
|
||||
}
|
||||
|
||||
if (tags !== undefined) {
|
||||
query.tags = Array.isArray(tags) ? { $in: tags } : tags;
|
||||
}
|
||||
|
||||
const count = await MonitorModel.countDocuments(query);
|
||||
return count;
|
||||
};
|
||||
|
||||
updateById = async (monitorId: string, teamId: string, patch: Partial<Monitor>) => {
|
||||
const updatedMonitor = await MonitorModel.findOneAndUpdate(
|
||||
{ _id: monitorId, teamId },
|
||||
{
|
||||
$set: {
|
||||
...patch,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updatedMonitor) {
|
||||
throw new AppError({ message: `Failed to update monitor with id ${monitorId}`, status: 500 });
|
||||
}
|
||||
return this.toEntity(updatedMonitor);
|
||||
};
|
||||
|
||||
updateByIds = async (monitorIds: string[], teamId: string, updates: Partial<Monitor>, excludeStatuses?: MonitorStatus[]) => {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const filter: Record<string, unknown> = { _id: { $in: objectIds }, teamId };
|
||||
if (excludeStatuses && excludeStatuses.length > 0) {
|
||||
filter.status = { $nin: excludeStatuses };
|
||||
}
|
||||
const updated = await MonitorModel.updateMany(filter, { $set: updates }, { runValidators: true });
|
||||
return updated.modifiedCount;
|
||||
};
|
||||
|
||||
updateStatusWindowAndChecks = async (
|
||||
monitorId: string,
|
||||
teamId: string,
|
||||
status: boolean,
|
||||
checkSnapshot: CheckSnapshot,
|
||||
windowSize: number,
|
||||
maxRecentChecks: number,
|
||||
statusPatch?: Partial<Monitor>
|
||||
): Promise<Monitor> => {
|
||||
const updatedMonitor = await MonitorModel.findOneAndUpdate(
|
||||
{ _id: monitorId, teamId },
|
||||
{
|
||||
$push: {
|
||||
statusWindow: { $each: [status], $slice: -windowSize },
|
||||
recentChecks: { $each: [checkSnapshot], $slice: -maxRecentChecks },
|
||||
},
|
||||
...(statusPatch && { $set: statusPatch }),
|
||||
},
|
||||
{ returnDocument: "after" }
|
||||
);
|
||||
|
||||
if (!updatedMonitor) {
|
||||
throw new AppError({ message: `Failed to update status and checks for monitor with id ${monitorId}`, status: 500 });
|
||||
}
|
||||
return this.toEntity(updatedMonitor);
|
||||
};
|
||||
|
||||
togglePauseById = async (monitorId: string, teamId: string) => {
|
||||
const monitor = await MonitorModel.findOneAndUpdate(
|
||||
{ _id: monitorId, teamId },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
isActive: { $not: "$isActive" },
|
||||
status: {
|
||||
$cond: {
|
||||
if: { $eq: ["$status", "paused"] },
|
||||
then: "initializing",
|
||||
else: "paused",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
{ new: true }
|
||||
);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found for the given team.`, status: 404 });
|
||||
}
|
||||
return this.toEntity(monitor);
|
||||
};
|
||||
|
||||
bulkTogglePause = async (monitorIds: string[], teamId: string, pause: boolean): Promise<Monitor[]> => {
|
||||
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const filter = {
|
||||
_id: { $in: objectIds },
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
isActive: pause, // Only pause if active (true), only resume if inactive (false)
|
||||
};
|
||||
const nextStatus = pause ? "paused" : "initializing";
|
||||
|
||||
const eligible = await MonitorModel.find(filter);
|
||||
if (eligible.length === 0) return [];
|
||||
|
||||
const now = new Date();
|
||||
await MonitorModel.updateMany(
|
||||
{ _id: { $in: eligible.map((doc) => doc._id) } },
|
||||
{ $set: { isActive: !pause, status: nextStatus, updatedAt: now } },
|
||||
{ timestamps: false }
|
||||
);
|
||||
|
||||
eligible.forEach((doc) => {
|
||||
doc.isActive = !pause;
|
||||
doc.status = nextStatus;
|
||||
doc.updatedAt = now;
|
||||
});
|
||||
|
||||
return this.mapDocuments(eligible);
|
||||
};
|
||||
|
||||
deleteById = async (monitorId: string, teamId: string) => {
|
||||
const deletedMonitor = await MonitorModel.findOneAndDelete({ _id: monitorId, teamId });
|
||||
|
||||
if (!deletedMonitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found for the given team.`, status: 404 });
|
||||
}
|
||||
|
||||
return this.toEntity(deletedMonitor);
|
||||
};
|
||||
|
||||
deleteByTeamId = async (teamId: string) => {
|
||||
const monitors = await MonitorModel.find({ teamId });
|
||||
const { deletedCount } = await MonitorModel.deleteMany({ teamId });
|
||||
|
||||
return { monitors: this.mapDocuments(monitors), deletedCount };
|
||||
};
|
||||
|
||||
findMonitorsSummaryByTeamId = async (teamId: string, config?: SummaryConfig): Promise<MonitorsSummary> => {
|
||||
const match: FilterQuery<MonitorDocument> = { teamId: new mongoose.Types.ObjectId(teamId) };
|
||||
if (config?.type !== undefined) {
|
||||
match.type = Array.isArray(config.type) ? { $in: config.type } : config.type;
|
||||
}
|
||||
if (config?.tags !== undefined) {
|
||||
const tagIds = (Array.isArray(config.tags) ? config.tags : [config.tags]).map((tag) => new mongoose.Types.ObjectId(tag));
|
||||
match.tags = { $in: tagIds };
|
||||
}
|
||||
const pipeline = [
|
||||
{ $match: match },
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
totalMonitors: { $sum: 1 },
|
||||
upMonitors: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ["$status", "up"] }, 1, 0],
|
||||
},
|
||||
},
|
||||
downMonitors: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ["$status", "down"] }, 1, 0],
|
||||
},
|
||||
},
|
||||
pausedMonitors: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ["$status", "paused"] }, 1, 0],
|
||||
},
|
||||
},
|
||||
initializingMonitors: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ["$status", "initializing"] }, 1, 0],
|
||||
},
|
||||
},
|
||||
maintenanceMonitors: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ["$status", "maintenance"] }, 1, 0],
|
||||
},
|
||||
},
|
||||
breachedMonitors: {
|
||||
$sum: {
|
||||
$cond: [{ $eq: ["$status", "breached"] }, 1, 0],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $project: { _id: 0 } },
|
||||
];
|
||||
|
||||
const [summary] = await MonitorModel.aggregate(pipeline);
|
||||
return (
|
||||
summary ?? {
|
||||
totalMonitors: 0,
|
||||
upMonitors: 0,
|
||||
downMonitors: 0,
|
||||
pausedMonitors: 0,
|
||||
initializingMonitors: 0,
|
||||
maintenanceMonitors: 0,
|
||||
breachedMonitors: 0,
|
||||
}
|
||||
);
|
||||
};
|
||||
|
||||
findGroupsByTeamId = async (teamId: string): Promise<string[]> => {
|
||||
const groups = await MonitorModel.distinct("group", {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
group: { $nin: [null, ""] },
|
||||
});
|
||||
return groups.sort();
|
||||
};
|
||||
|
||||
removeNotificationFromMonitors = async (notificationId: string): Promise<void> => {
|
||||
await MonitorModel.updateMany({ notifications: notificationId }, { $pull: { notifications: notificationId } });
|
||||
};
|
||||
|
||||
removeTagFromMonitors = async (tagId: string): Promise<void> => {
|
||||
await MonitorModel.updateMany({ tags: tagId }, { $pull: { tags: tagId } });
|
||||
};
|
||||
|
||||
updateNotifications = async (
|
||||
teamId: string,
|
||||
monitorIds: string[],
|
||||
notificationIds: string[],
|
||||
action: "add" | "remove" | "set"
|
||||
): Promise<number> => {
|
||||
let objectIds;
|
||||
let notificationObjectIds;
|
||||
try {
|
||||
objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
notificationObjectIds = notificationIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
} catch {
|
||||
throw new AppError({ message: "One or more monitor or notification IDs are invalid", status: 400 });
|
||||
}
|
||||
const filter = { _id: { $in: objectIds }, teamId: new mongoose.Types.ObjectId(teamId) };
|
||||
|
||||
let update;
|
||||
switch (action) {
|
||||
case "add":
|
||||
update = { $addToSet: { notifications: { $each: notificationObjectIds } } };
|
||||
break;
|
||||
case "remove":
|
||||
update = { $pull: { notifications: { $in: notificationObjectIds } } };
|
||||
break;
|
||||
case "set":
|
||||
update = { $set: { notifications: notificationObjectIds } };
|
||||
break;
|
||||
default:
|
||||
throw new AppError({ message: `Invalid action: ${action}`, status: 400 });
|
||||
}
|
||||
|
||||
const result = await MonitorModel.updateMany(filter, update);
|
||||
return result.modifiedCount;
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: MonitorDocument[]): Monitor[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
private toEntity = (doc: MonitorDocument): Monitor => {
|
||||
const toStringId = (value: unknown): string => {
|
||||
if (value instanceof mongoose.Types.ObjectId) {
|
||||
return value.toString();
|
||||
}
|
||||
return value?.toString() ?? "";
|
||||
};
|
||||
|
||||
const toDateString = (value: Date | string): string => {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
};
|
||||
|
||||
const notificationIds = (doc.notifications ?? []).map((notification) => toStringId(notification));
|
||||
const tagIds = (doc.tags ?? []).map((tag) => toStringId(tag));
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
userId: toStringId(doc.userId),
|
||||
teamId: toStringId(doc.teamId),
|
||||
name: doc.name,
|
||||
description: doc.description ?? undefined,
|
||||
status: doc.status ?? "initializing",
|
||||
statusWindow: doc.statusWindow ?? [],
|
||||
statusWindowSize: doc.statusWindowSize,
|
||||
statusWindowThreshold: doc.statusWindowThreshold,
|
||||
type: doc.type,
|
||||
ignoreTlsErrors: doc.ignoreTlsErrors,
|
||||
useAdvancedMatching: doc.useAdvancedMatching ?? false,
|
||||
jsonPath: doc.jsonPath ?? undefined,
|
||||
expectedValue: doc.expectedValue ?? undefined,
|
||||
matchMethod: doc.matchMethod ?? undefined,
|
||||
url: doc.url,
|
||||
port: doc.port ?? undefined,
|
||||
isActive: doc.isActive,
|
||||
interval: doc.interval,
|
||||
uptimePercentage: doc.uptimePercentage ?? undefined,
|
||||
notifications: notificationIds,
|
||||
tags: tagIds,
|
||||
customUpCodes: doc.customUpCodes ?? [],
|
||||
secret: doc.secret ?? undefined,
|
||||
cpuAlertThreshold: doc.cpuAlertThreshold,
|
||||
cpuAlertCounter: doc.cpuAlertCounter,
|
||||
memoryAlertThreshold: doc.memoryAlertThreshold,
|
||||
memoryAlertCounter: doc.memoryAlertCounter,
|
||||
diskAlertThreshold: doc.diskAlertThreshold,
|
||||
diskAlertCounter: doc.diskAlertCounter,
|
||||
tempAlertThreshold: doc.tempAlertThreshold,
|
||||
tempAlertCounter: doc.tempAlertCounter,
|
||||
selectedDisks: doc.selectedDisks ?? [],
|
||||
gameId: doc.gameId ?? undefined,
|
||||
grpcServiceName: doc.grpcServiceName ?? undefined,
|
||||
strategy: doc.strategy ?? undefined,
|
||||
group: doc.group ?? null,
|
||||
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => this.toCheckSnapshot(check)),
|
||||
geoCheckEnabled: doc.geoCheckEnabled ?? false,
|
||||
geoCheckLocations: doc.geoCheckLocations ?? [],
|
||||
geoCheckInterval: doc.geoCheckInterval ?? 300000,
|
||||
dnsServer: doc.dnsServer ?? undefined,
|
||||
dnsRecordType: doc.dnsRecordType ?? undefined,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
private toEntityWithChecks = (doc: MonitorDocument): Monitor => {
|
||||
const toStringId = (value: unknown): string => {
|
||||
if (value instanceof mongoose.Types.ObjectId) {
|
||||
return value.toString();
|
||||
}
|
||||
return value?.toString() ?? "";
|
||||
};
|
||||
|
||||
const toDateString = (value: Date | string): string => {
|
||||
if (!value) return "";
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
};
|
||||
|
||||
const notificationIds = (doc.notifications ?? []).map((notification: unknown) => toStringId(notification));
|
||||
const tagIds = (doc.tags ?? []).map((tag: unknown) => toStringId(tag));
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
userId: toStringId(doc.userId),
|
||||
teamId: toStringId(doc.teamId),
|
||||
name: doc.name,
|
||||
description: doc.description ?? undefined,
|
||||
status: doc.status ?? "initializing",
|
||||
statusWindow: doc.statusWindow ?? [],
|
||||
statusWindowSize: doc.statusWindowSize,
|
||||
statusWindowThreshold: doc.statusWindowThreshold,
|
||||
type: doc.type,
|
||||
ignoreTlsErrors: doc.ignoreTlsErrors,
|
||||
useAdvancedMatching: doc.useAdvancedMatching ?? false,
|
||||
jsonPath: doc.jsonPath ?? undefined,
|
||||
expectedValue: doc.expectedValue ?? undefined,
|
||||
matchMethod: doc.matchMethod ?? undefined,
|
||||
url: doc.url,
|
||||
port: doc.port ?? undefined,
|
||||
isActive: doc.isActive,
|
||||
interval: doc.interval,
|
||||
uptimePercentage: doc.uptimePercentage ?? undefined,
|
||||
notifications: notificationIds,
|
||||
tags: tagIds,
|
||||
customUpCodes: doc.customUpCodes ?? [],
|
||||
secret: doc.secret ?? undefined,
|
||||
cpuAlertThreshold: doc.cpuAlertThreshold,
|
||||
cpuAlertCounter: doc.cpuAlertCounter,
|
||||
memoryAlertThreshold: doc.memoryAlertThreshold,
|
||||
memoryAlertCounter: doc.memoryAlertCounter,
|
||||
diskAlertThreshold: doc.diskAlertThreshold,
|
||||
diskAlertCounter: doc.diskAlertCounter,
|
||||
tempAlertThreshold: doc.tempAlertThreshold,
|
||||
tempAlertCounter: doc.tempAlertCounter,
|
||||
selectedDisks: doc.selectedDisks ?? [],
|
||||
gameId: doc.gameId ?? undefined,
|
||||
grpcServiceName: doc.grpcServiceName ?? undefined,
|
||||
strategy: doc.strategy ?? undefined,
|
||||
group: doc.group ?? null,
|
||||
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => this.toCheckSnapshot(check)),
|
||||
geoCheckEnabled: doc.geoCheckEnabled ?? false,
|
||||
geoCheckLocations: doc.geoCheckLocations ?? [],
|
||||
geoCheckInterval: doc.geoCheckInterval ?? 300000,
|
||||
dnsServer: doc.dnsServer ?? undefined,
|
||||
dnsRecordType: doc.dnsRecordType ?? undefined,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
private toCheckSnapshot = (doc: CheckSnapshotDocument): CheckSnapshot => {
|
||||
const toDateString = (value: Date | string): string => {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
};
|
||||
|
||||
return {
|
||||
id: doc.id,
|
||||
status: doc.status,
|
||||
responseTime: doc.responseTime,
|
||||
timings: doc.timings,
|
||||
statusCode: doc.statusCode,
|
||||
message: doc.message,
|
||||
cpu: doc.cpu,
|
||||
memory: doc.memory,
|
||||
disk: doc.disk,
|
||||
host: doc.host,
|
||||
errors: doc.errors,
|
||||
capture: doc.capture,
|
||||
net: doc.net,
|
||||
accessibility: doc.accessibility,
|
||||
bestPractices: doc.bestPractices,
|
||||
seo: doc.seo,
|
||||
performance: doc.performance,
|
||||
audits: doc.audits,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
};
|
||||
};
|
||||
|
||||
deleteByTeamIdsNotIn = async (teamIds: string[]): Promise<number> => {
|
||||
const objectIds = teamIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const result = await MonitorModel.deleteMany({ teamId: { $nin: objectIds } });
|
||||
return result.deletedCount ?? 0;
|
||||
};
|
||||
|
||||
findAllMonitorIds = async (): Promise<string[]> => {
|
||||
const monitors = await MonitorModel.find({}, { _id: 1 }).lean();
|
||||
return monitors.map((doc) => doc._id.toString());
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoMonitorsRepository;
|
||||
@@ -0,0 +1,606 @@
|
||||
import { NormalizeData, NormalizeDataUptimeDetails } from "@/utils/dataUtils.js";
|
||||
import { type Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import type {
|
||||
MonitorType,
|
||||
MonitorsWithChecksByTeamIdResult,
|
||||
UptimeDetailsResult,
|
||||
HardwareDetailsResult,
|
||||
PageSpeedDetailsResult,
|
||||
GamesMap,
|
||||
GroupedGeoCheckResult,
|
||||
} from "@/domain/monitors/monitor.types.js";
|
||||
import { supportsGeoCheck, supportsUptimeDetails } from "@/domain/monitors/monitor.types.js";
|
||||
import type { UptimeChecksResult, HardwareChecksResult, PageSpeedChecksResult } from "@/domain/checks/check.type.js";
|
||||
import type { GeoContinent } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import type { IChecksRepository } from "@/domain/checks/check.repository.interface.js";
|
||||
import type { IGeoChecksRepository } from "@/domain/geo-checks/geo-check.repository.interface.js";
|
||||
import type { IIncidentsRepository } from "@/domain/incidents/incident.repository.interface.js";
|
||||
import type { IMonitorStatsRepository } from "@/domain/monitor-stats/monitor-stats.repository.interface.js";
|
||||
import type { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js";
|
||||
import demoMonitorsData from "@/utils/demoMonitors.json" with { type: "json" };
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import type { ImportedMonitor } from "@/api/validation/monitorValidation.js";
|
||||
import { IJobQueue } from "@/service/job-queues/job-queue.interface.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
|
||||
const SERVICE_NAME = "MonitorService";
|
||||
type DateRangeKey = "recent" | "day" | "week" | "month" | "all";
|
||||
|
||||
const isUptimeChecksResult = (result: UptimeChecksResult | HardwareChecksResult | PageSpeedChecksResult): result is UptimeChecksResult =>
|
||||
supportsUptimeDetails(result.monitorType);
|
||||
|
||||
export interface IMonitorService {
|
||||
readonly serviceName: string;
|
||||
|
||||
// create
|
||||
createMonitor(teamId: string, userId: string, body: Partial<Monitor>): Promise<void>;
|
||||
createMonitors(monitors: Array<Monitor>): Promise<Monitor[] | null>;
|
||||
addDemoMonitors(args: { userId: string; teamId: string }): Promise<Monitor[]>;
|
||||
|
||||
// read
|
||||
getUptimeDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<UptimeDetailsResult>;
|
||||
getHardwareDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<HardwareDetailsResult>;
|
||||
getPageSpeedDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<PageSpeedDetailsResult>;
|
||||
getGeoChecksByMonitorId(args: {
|
||||
teamId: string;
|
||||
monitorId: string;
|
||||
dateRange: string;
|
||||
continents?: GeoContinent[];
|
||||
}): Promise<GroupedGeoCheckResult>;
|
||||
getMonitorById(args: { teamId: string; monitorId: string }): Promise<Monitor>;
|
||||
getMonitorsByTeamId(args: {
|
||||
teamId: string;
|
||||
limit?: number;
|
||||
type?: MonitorType | MonitorType[];
|
||||
tags?: string | string[];
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
filter?: string;
|
||||
field?: string;
|
||||
order?: "asc" | "desc";
|
||||
}): Promise<Monitor[] | null>;
|
||||
getMonitorsWithChecksByTeamId(args: {
|
||||
teamId: string;
|
||||
limit?: number;
|
||||
type?: MonitorType | MonitorType[];
|
||||
tags?: string | string[];
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
filter?: string;
|
||||
field?: string;
|
||||
order?: "asc" | "desc";
|
||||
}): Promise<MonitorsWithChecksByTeamIdResult>;
|
||||
getAllGames(): GamesMap;
|
||||
getGroupsByTeamId(args: { teamId: string }): Promise<string[]>;
|
||||
|
||||
// update
|
||||
editMonitor(args: { teamId: string; monitorId: string; body: Partial<Monitor> }): Promise<Monitor>;
|
||||
pauseMonitor(args: { teamId: string; monitorId: string }): Promise<Monitor>;
|
||||
bulkPauseMonitors(args: { teamId: string; monitorIds: string[]; pause: boolean }): Promise<{ monitors: Monitor[]; failedCount: number }>;
|
||||
|
||||
// delete
|
||||
deleteMonitor(args: { teamId: string; monitorId: string }): Promise<Monitor>;
|
||||
deleteAllMonitors(args: { teamId: string }): Promise<number>;
|
||||
|
||||
// notifications
|
||||
updateNotifications(args: { teamId: string; monitorIds: string[]; notificationIds: string[]; action: "add" | "remove" | "set" }): Promise<number>;
|
||||
|
||||
// other
|
||||
exportMonitorsToJSON(args: { teamId: string }): Promise<Monitor[]>;
|
||||
importMonitorsFromJSON(args: { teamId: string; userId: string; monitors: ImportedMonitor[] }): Promise<{ imported: number; errors: string[] }>;
|
||||
}
|
||||
|
||||
export class MonitorService implements IMonitorService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private jobQueue: IJobQueue;
|
||||
private logger: ILogger;
|
||||
private games: GamesMap;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private checksRepository: IChecksRepository;
|
||||
private geoChecksRepository: IGeoChecksRepository;
|
||||
private monitorStatsRepository: IMonitorStatsRepository;
|
||||
private statusPagesRepository: IStatusPagesRepository;
|
||||
private incidentsRepository: IIncidentsRepository;
|
||||
|
||||
constructor({
|
||||
jobQueue,
|
||||
logger,
|
||||
games,
|
||||
monitorsRepository,
|
||||
checksRepository,
|
||||
geoChecksRepository,
|
||||
monitorStatsRepository,
|
||||
statusPagesRepository,
|
||||
incidentsRepository,
|
||||
}: {
|
||||
jobQueue: IJobQueue;
|
||||
logger: ILogger;
|
||||
games: GamesMap;
|
||||
monitorsRepository: IMonitorsRepository;
|
||||
checksRepository: IChecksRepository;
|
||||
geoChecksRepository: IGeoChecksRepository;
|
||||
monitorStatsRepository: IMonitorStatsRepository;
|
||||
statusPagesRepository: IStatusPagesRepository;
|
||||
incidentsRepository: IIncidentsRepository;
|
||||
}) {
|
||||
this.jobQueue = jobQueue;
|
||||
this.logger = logger;
|
||||
this.games = games;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.checksRepository = checksRepository;
|
||||
this.geoChecksRepository = geoChecksRepository;
|
||||
this.monitorStatsRepository = monitorStatsRepository;
|
||||
this.statusPagesRepository = statusPagesRepository;
|
||||
this.incidentsRepository = incidentsRepository;
|
||||
}
|
||||
|
||||
get serviceName(): string {
|
||||
return MonitorService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
private getDateRange = (dateRange: DateRangeKey) => {
|
||||
const startDates = {
|
||||
recent: new Date(new Date().setHours(new Date().getHours() - 2)),
|
||||
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: new Date(0),
|
||||
};
|
||||
return {
|
||||
start: startDates[dateRange],
|
||||
end: new Date(),
|
||||
};
|
||||
};
|
||||
|
||||
private getDateFormat = (dateRange: DateRangeKey): string => {
|
||||
const formatLookup = {
|
||||
recent: "%Y-%m-%dT%H:%M:00Z",
|
||||
day: "%Y-%m-%dT%H:00:00Z",
|
||||
week: "%Y-%m-%dT00:00:00Z",
|
||||
month: "%Y-%m-%dT00:00:00Z",
|
||||
all: "%Y-%m-%dT00:00:00Z",
|
||||
};
|
||||
return formatLookup[dateRange];
|
||||
};
|
||||
|
||||
createMonitor = async (teamId: string, userId: string, body: Monitor): Promise<void> => {
|
||||
const monitor = await this.monitorsRepository.create(body, teamId, userId);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: "Failed to create monitor", status: 500, service: SERVICE_NAME, method: "createMonitor" });
|
||||
}
|
||||
|
||||
this.jobQueue.addJob(monitor.id, monitor);
|
||||
};
|
||||
|
||||
createMonitors = async (monitors: Array<Monitor>): Promise<Monitor[] | null> => {
|
||||
const createdMonitors = await this.monitorsRepository.createMonitors(monitors);
|
||||
if (!createdMonitors || createdMonitors.length === 0) {
|
||||
throw new AppError({ message: "Failed to create monitors", status: 500, service: SERVICE_NAME, method: "createMonitors" });
|
||||
}
|
||||
|
||||
await Promise.all(createdMonitors.map((monitor) => this.jobQueue.addJob(monitor.id, monitor)));
|
||||
return createdMonitors;
|
||||
};
|
||||
|
||||
addDemoMonitors = async ({ userId, teamId }: { userId: string; teamId: string }): Promise<Monitor[]> => {
|
||||
const monitors = demoMonitorsData.map((monitor) => ({
|
||||
userId,
|
||||
teamId,
|
||||
name: monitor.name,
|
||||
description: monitor.name,
|
||||
type: "http" as const,
|
||||
url: monitor.url,
|
||||
interval: 60000,
|
||||
}));
|
||||
const demoMonitors = await this.monitorsRepository.createMonitors(monitors as unknown as Monitor[]);
|
||||
|
||||
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor.id, monitor)));
|
||||
return demoMonitors;
|
||||
};
|
||||
|
||||
getUptimeDetailsById = async ({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorId: string;
|
||||
dateRange: string;
|
||||
}): Promise<UptimeDetailsResult> => {
|
||||
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
|
||||
}
|
||||
const rangeKey = dateRange as DateRangeKey;
|
||||
const { start, end } = this.getDateRange(rangeKey);
|
||||
const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), {
|
||||
type: monitor.type,
|
||||
});
|
||||
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
|
||||
|
||||
if (!isUptimeChecksResult(checksData)) {
|
||||
throw new AppError({ message: `${monitor.type} monitors are not supported for uptime details`, status: 400 });
|
||||
}
|
||||
|
||||
return {
|
||||
monitorData: {
|
||||
monitor,
|
||||
groupedChecks: NormalizeDataUptimeDetails(checksData.groupedChecks, 10, 100),
|
||||
groupedUpChecks: NormalizeDataUptimeDetails(checksData.groupedUpChecks, 10, 100),
|
||||
groupedDownChecks: NormalizeDataUptimeDetails(checksData.groupedDownChecks, 10, 100),
|
||||
groupedAvgResponseTime: checksData.avgResponseTime,
|
||||
groupedUptimePercentage: checksData.uptimePercentage,
|
||||
},
|
||||
monitorStats,
|
||||
};
|
||||
};
|
||||
|
||||
getHardwareDetailsById = async ({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorId: string;
|
||||
dateRange: string;
|
||||
}): Promise<HardwareDetailsResult> => {
|
||||
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
|
||||
}
|
||||
if (monitor.type !== "hardware") {
|
||||
throw new AppError({ message: `${monitor.type} monitors are not supported for hardware details`, status: 400 });
|
||||
}
|
||||
|
||||
const rangeKey = dateRange as DateRangeKey;
|
||||
const { start, end } = this.getDateRange(rangeKey);
|
||||
const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), {
|
||||
type: monitor.type,
|
||||
});
|
||||
|
||||
if (checksData.monitorType !== "hardware") {
|
||||
throw new AppError({ message: "Unable to load hardware stats for this monitor", status: 500 });
|
||||
}
|
||||
|
||||
const stats = {
|
||||
aggregateData: checksData.aggregateData,
|
||||
upChecks: checksData.upChecks,
|
||||
checks: checksData.checks,
|
||||
};
|
||||
|
||||
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
|
||||
|
||||
return {
|
||||
monitor,
|
||||
stats,
|
||||
monitorStats,
|
||||
};
|
||||
};
|
||||
|
||||
getPageSpeedDetailsById = async ({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorId: string;
|
||||
dateRange: string;
|
||||
}): Promise<PageSpeedDetailsResult> => {
|
||||
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
|
||||
}
|
||||
if (monitor.type !== "pagespeed") {
|
||||
throw new AppError({ message: `${monitor.type} monitors are not supported for pagespeed details`, status: 400 });
|
||||
}
|
||||
|
||||
const rangeKey = dateRange as DateRangeKey;
|
||||
const { start, end } = this.getDateRange(rangeKey);
|
||||
const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), {
|
||||
type: monitor.type,
|
||||
});
|
||||
|
||||
if (checksData.monitorType !== "pagespeed") {
|
||||
throw new AppError({ message: "Unable to load pagespeed stats for this monitor", status: 500 });
|
||||
}
|
||||
|
||||
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
|
||||
|
||||
return {
|
||||
monitorData: {
|
||||
monitor,
|
||||
groupedChecks: checksData.groupedChecks,
|
||||
},
|
||||
monitorStats,
|
||||
};
|
||||
};
|
||||
|
||||
getGeoChecksByMonitorId = async ({
|
||||
teamId,
|
||||
monitorId,
|
||||
dateRange,
|
||||
continents,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorId: string;
|
||||
dateRange: string;
|
||||
continents?: GeoContinent[];
|
||||
}): Promise<GroupedGeoCheckResult> => {
|
||||
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
|
||||
if (!monitor) {
|
||||
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
|
||||
}
|
||||
|
||||
if (!supportsGeoCheck(monitor.type) || !monitor.geoCheckEnabled) {
|
||||
return { groupedGeoChecks: [] };
|
||||
}
|
||||
|
||||
const rangeKey = dateRange as DateRangeKey;
|
||||
const { start, end } = this.getDateRange(rangeKey);
|
||||
const groupedGeoChecks = await this.geoChecksRepository.findGroupedByMonitorIdAndDateRange(
|
||||
monitor.id,
|
||||
start,
|
||||
end,
|
||||
this.getDateFormat(rangeKey),
|
||||
continents
|
||||
);
|
||||
|
||||
return { groupedGeoChecks };
|
||||
};
|
||||
|
||||
getMonitorById = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
|
||||
return await this.monitorsRepository.findById(monitorId, teamId);
|
||||
};
|
||||
|
||||
getMonitorsByTeamId = async ({
|
||||
teamId,
|
||||
type,
|
||||
tags,
|
||||
filter,
|
||||
}: {
|
||||
teamId: string;
|
||||
type?: MonitorType | MonitorType[];
|
||||
tags?: string | string[];
|
||||
filter?: string;
|
||||
}): Promise<Monitor[] | null> => {
|
||||
return await this.monitorsRepository.findByTeamId(teamId, { type, tags, filter });
|
||||
};
|
||||
|
||||
getMonitorsWithChecksByTeamId = async ({
|
||||
teamId,
|
||||
limit,
|
||||
type,
|
||||
tags,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
}: {
|
||||
teamId: string;
|
||||
limit?: number;
|
||||
type?: MonitorType | MonitorType[];
|
||||
tags?: string | string[];
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
filter?: string;
|
||||
field?: string;
|
||||
order?: "asc" | "desc";
|
||||
}): Promise<MonitorsWithChecksByTeamIdResult> => {
|
||||
const summary = await this.monitorsRepository.findMonitorsSummaryByTeamId(teamId, { type, tags });
|
||||
const count = await this.monitorsRepository.findMonitorCountByTeamIdAndType(teamId, { type, tags, filter });
|
||||
const monitors = await this.monitorsRepository.findByTeamIdWithStats(teamId, {
|
||||
limit,
|
||||
type,
|
||||
tags,
|
||||
page,
|
||||
rowsPerPage,
|
||||
filter,
|
||||
field,
|
||||
order,
|
||||
});
|
||||
|
||||
const monitorsList = (monitors ?? []) as Monitor[];
|
||||
const snapshotTypes: MonitorType[] = ["hardware"];
|
||||
const requestedTypes = Array.isArray(type) ? type : type ? [type] : [];
|
||||
const snapshotOnlyRequest =
|
||||
requestedTypes.length > 0 && requestedTypes.every((requestedType) => snapshotTypes.includes(requestedType as MonitorType));
|
||||
|
||||
const monitorsWithChecks = monitorsList.map((monitor: Monitor) => {
|
||||
const rawChecks = monitor.recentChecks ?? [];
|
||||
const isSnapshotType = snapshotOnlyRequest || snapshotTypes.includes(monitor.type);
|
||||
const checks = isSnapshotType ? rawChecks.slice(0, 1) : NormalizeData(rawChecks, 10, 100);
|
||||
monitor.recentChecks = checks;
|
||||
return monitor;
|
||||
});
|
||||
return { summary: summary ?? null, count, monitors: monitorsWithChecks };
|
||||
};
|
||||
|
||||
getAllGames = (): GamesMap => {
|
||||
return this.games;
|
||||
};
|
||||
|
||||
getGroupsByTeamId = async ({ teamId }: { teamId: string }): Promise<string[]> => {
|
||||
return await this.monitorsRepository.findGroupsByTeamId(teamId);
|
||||
};
|
||||
|
||||
editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: Partial<Monitor> }) => {
|
||||
const editedMonitor = await this.monitorsRepository.updateById(monitorId, teamId, body);
|
||||
await this.jobQueue.updateJob(editedMonitor);
|
||||
return editedMonitor;
|
||||
};
|
||||
|
||||
updateNotifications = async ({
|
||||
teamId,
|
||||
monitorIds,
|
||||
notificationIds,
|
||||
action,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorIds: string[];
|
||||
notificationIds: string[];
|
||||
action: "add" | "remove" | "set";
|
||||
}): Promise<number> => {
|
||||
const modifiedCount = await this.monitorsRepository.updateNotifications(teamId, monitorIds, notificationIds, action);
|
||||
|
||||
// If notifications were updated, we should update the jobs in the queue
|
||||
if (modifiedCount > 0) {
|
||||
const monitors = await this.monitorsRepository.findByIds(monitorIds);
|
||||
await Promise.all(monitors.map((monitor) => this.jobQueue.updateJob(monitor)));
|
||||
}
|
||||
|
||||
return modifiedCount;
|
||||
};
|
||||
|
||||
pauseMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
|
||||
const monitor = await this.monitorsRepository.togglePauseById(monitorId, teamId);
|
||||
if (monitor.isActive) {
|
||||
await this.jobQueue.resumeJob(monitor);
|
||||
} else {
|
||||
await this.jobQueue.pauseJob(monitor);
|
||||
}
|
||||
return monitor;
|
||||
};
|
||||
|
||||
bulkPauseMonitors = async ({
|
||||
teamId,
|
||||
monitorIds,
|
||||
pause,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorIds: string[];
|
||||
pause: boolean;
|
||||
}): Promise<{ monitors: Monitor[]; failedCount: number }> => {
|
||||
const monitors = await this.monitorsRepository.bulkTogglePause(monitorIds, teamId, pause);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
monitors.map(async (monitor) => {
|
||||
if (monitor.isActive) {
|
||||
await this.jobQueue.resumeJob(monitor);
|
||||
} else {
|
||||
await this.jobQueue.pauseJob(monitor);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
let failedCount = 0;
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === "rejected") {
|
||||
failedCount++;
|
||||
this.logger.error({
|
||||
message: `Failed to sync job queue for monitor ${monitors[index]?.id || "unknown"} during bulk ${pause ? "pause" : "resume"}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "bulkPauseMonitors",
|
||||
stack: result.reason instanceof Error ? result.reason.stack : undefined,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
return { monitors, failedCount };
|
||||
};
|
||||
|
||||
deleteMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
|
||||
const monitor = await this.monitorsRepository.deleteById(monitorId, teamId);
|
||||
await this.monitorStatsRepository.deleteByMonitorId(monitor.id).catch((err: unknown) => {
|
||||
this.logger.warn({
|
||||
message: `Error deleting monitor stats for monitor ${monitor.id} with name ${monitor.name}`,
|
||||
service: SERVICE_NAME,
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
});
|
||||
await this.checksRepository.deleteByMonitorId(monitor.id).catch((err: unknown) => {
|
||||
this.logger.warn({
|
||||
message: `Error deleting checks for monitor ${monitor.id} with name ${monitor.name}`,
|
||||
service: SERVICE_NAME,
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
});
|
||||
await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id).catch((err: unknown) => {
|
||||
this.logger.warn({
|
||||
message: `Error removing monitor ${monitor.id} with name ${monitor.name} from status pages`,
|
||||
service: SERVICE_NAME,
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
await this.incidentsRepository.deleteByMonitorId(monitor.id, teamId).catch((err: unknown) => {
|
||||
this.logger.warn({
|
||||
message: `Error deleting incidents for monitor ${monitor.id} with name ${monitor.name}`,
|
||||
service: SERVICE_NAME,
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
await this.geoChecksRepository.deleteByMonitorId(monitor.id).catch((err: unknown) => {
|
||||
this.logger.warn({
|
||||
message: `Error deleting geo checks for monitor ${monitor.id} with name ${monitor.name}`,
|
||||
service: SERVICE_NAME,
|
||||
stack: err instanceof Error ? err.stack : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
await this.jobQueue.deleteJob(monitor);
|
||||
return monitor;
|
||||
};
|
||||
|
||||
deleteAllMonitors = async ({ teamId }: { teamId: string }): Promise<number> => {
|
||||
const { monitors, deletedCount } = await this.monitorsRepository.deleteByTeamId(teamId);
|
||||
await Promise.all(
|
||||
monitors.map(async (monitor) => {
|
||||
try {
|
||||
await this.jobQueue.deleteJob(monitor);
|
||||
await this.checksRepository.deleteByMonitorId(monitor.id);
|
||||
await this.geoChecksRepository.deleteByMonitorId(monitor.id);
|
||||
await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id);
|
||||
await this.monitorStatsRepository.deleteByMonitorId(monitor.id);
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
message: `Error deleting associated records for monitor ${monitor.id} with name ${monitor.name}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteAllMonitors",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
return deletedCount;
|
||||
};
|
||||
|
||||
exportMonitorsToJSON = async ({ teamId }: { teamId: string }): Promise<Monitor[]> => {
|
||||
const monitors = await this.monitorsRepository.findByTeamId(teamId, {});
|
||||
|
||||
if (!monitors || monitors.length === 0) {
|
||||
throw new AppError({ message: "No monitors found to export.", service: SERVICE_NAME, method: "exportMonitorsToJSON", status: 400 });
|
||||
}
|
||||
|
||||
return monitors;
|
||||
};
|
||||
|
||||
importMonitorsFromJSON = async ({
|
||||
teamId,
|
||||
userId,
|
||||
monitors,
|
||||
}: {
|
||||
teamId: string;
|
||||
userId: string;
|
||||
monitors: ImportedMonitor[];
|
||||
}): Promise<{ imported: number; errors: string[] }> => {
|
||||
const errors: string[] = [];
|
||||
|
||||
const cleanedMonitors: Monitor[] = monitors.map((monitor) => ({
|
||||
...monitor,
|
||||
id: "",
|
||||
teamId,
|
||||
userId,
|
||||
recentChecks: [],
|
||||
createdAt: "",
|
||||
updatedAt: "",
|
||||
}));
|
||||
|
||||
const createdMonitors = await this.createMonitors(cleanedMonitors);
|
||||
|
||||
return { imported: createdMonitors!.length, errors };
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import type { CheckSnapshot } from "@/domain/checks/check.type.js";
|
||||
export type { CheckSnapshot } from "@/domain/checks/check.type.js";
|
||||
import type { GeoContinent, GroupedGeoCheck } from "@/domain/geo-checks/geo-check.type.js";
|
||||
export type { GeoContinent } from "@/domain/geo-checks/geo-check.type.js";
|
||||
import http from "node:http";
|
||||
|
||||
export const HttpStatusCodes = Object.keys(http.STATUS_CODES).map(Number);
|
||||
export const HttpStatusCodeSet = new Set(HttpStatusCodes);
|
||||
export type HttpStatusCode = number;
|
||||
|
||||
export const MonitorTypes = ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"] as const;
|
||||
export type MonitorType = (typeof MonitorTypes)[number];
|
||||
|
||||
export const PageSpeedStrategies = ["desktop", "mobile"] as const;
|
||||
export type PageSpeedStrategy = (typeof PageSpeedStrategies)[number];
|
||||
export const DefaultPageSpeedStrategy: PageSpeedStrategy = "desktop";
|
||||
|
||||
export const GeoCheckSupportedTypes: readonly MonitorType[] = ["http", "ping"] as const;
|
||||
export const supportsGeoCheck = (type: MonitorType): boolean => GeoCheckSupportedTypes.includes(type);
|
||||
|
||||
export const UptimeDetailsSupportedTypes = [
|
||||
"http",
|
||||
"ping",
|
||||
"docker",
|
||||
"port",
|
||||
"game",
|
||||
"grpc",
|
||||
"websocket",
|
||||
"dns",
|
||||
] as const satisfies readonly MonitorType[];
|
||||
export type UptimeDetailsSupportedType = (typeof UptimeDetailsSupportedTypes)[number];
|
||||
export const supportsUptimeDetails = (type: MonitorType): type is UptimeDetailsSupportedType => UptimeDetailsSupportedTypes.some((t) => t === type);
|
||||
|
||||
export const MonitorStatuses = ["up", "down", "paused", "initializing", "maintenance", "breached"] as const;
|
||||
export type MonitorStatus = (typeof MonitorStatuses)[number];
|
||||
|
||||
export const MonitorMatchMethods = ["equal", "include", "regex"] as const;
|
||||
export type MonitorMatchMethod = (typeof MonitorMatchMethods)[number] | "";
|
||||
|
||||
export const DnsRecordTypes = ["A", "AAAA", "CNAME", "MX", "TXT", "NS"] as const;
|
||||
export type DnsRecordType = (typeof DnsRecordTypes)[number];
|
||||
|
||||
export const MAX_RECENT_CHECKS = 50;
|
||||
|
||||
export interface Monitor {
|
||||
id: string;
|
||||
userId: string;
|
||||
teamId: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
status: MonitorStatus;
|
||||
statusWindow: boolean[];
|
||||
statusWindowSize: number;
|
||||
statusWindowThreshold: number;
|
||||
type: MonitorType;
|
||||
ignoreTlsErrors: boolean;
|
||||
useAdvancedMatching: boolean;
|
||||
jsonPath?: string;
|
||||
expectedValue?: string;
|
||||
matchMethod?: MonitorMatchMethod;
|
||||
url: string;
|
||||
port?: number;
|
||||
isActive: boolean;
|
||||
interval: number;
|
||||
uptimePercentage?: number;
|
||||
notifications: string[];
|
||||
tags: string[];
|
||||
customUpCodes: HttpStatusCode[];
|
||||
secret?: string;
|
||||
cpuAlertThreshold: number;
|
||||
cpuAlertCounter: number;
|
||||
memoryAlertThreshold: number;
|
||||
memoryAlertCounter: number;
|
||||
diskAlertThreshold: number;
|
||||
diskAlertCounter: number;
|
||||
tempAlertThreshold: number;
|
||||
tempAlertCounter: number;
|
||||
selectedDisks: string[];
|
||||
gameId?: string;
|
||||
grpcServiceName?: string;
|
||||
strategy?: PageSpeedStrategy;
|
||||
group: string | null;
|
||||
geoCheckEnabled?: boolean;
|
||||
geoCheckLocations?: GeoContinent[];
|
||||
geoCheckInterval?: number;
|
||||
dnsServer?: string;
|
||||
dnsRecordType?: DnsRecordType;
|
||||
recentChecks: CheckSnapshot[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface MonitorsSummary {
|
||||
totalMonitors: number;
|
||||
upMonitors: number;
|
||||
downMonitors: number;
|
||||
pausedMonitors: number;
|
||||
initializingMonitors: number;
|
||||
maintenanceMonitors: number;
|
||||
breachedMonitors: number;
|
||||
}
|
||||
|
||||
export interface MonitorsWithChecksByTeamIdResult {
|
||||
summary: MonitorsSummary | null;
|
||||
count: number;
|
||||
monitors: Monitor[];
|
||||
}
|
||||
|
||||
export interface GroupedGeoCheckResult {
|
||||
groupedGeoChecks: GroupedGeoCheck[];
|
||||
}
|
||||
|
||||
export interface UptimeDetailsResult {
|
||||
monitorData: {
|
||||
monitor: Monitor;
|
||||
groupedChecks: import("../checks/check.type.js").GroupedCheck[];
|
||||
groupedUpChecks: import("../checks/check.type.js").GroupedCheck[];
|
||||
groupedDownChecks: import("../checks/check.type.js").GroupedCheck[];
|
||||
groupedAvgResponseTime: number;
|
||||
groupedUptimePercentage: number;
|
||||
};
|
||||
monitorStats: import("../monitor-stats/monitor-stats.type.js").MonitorStats | null;
|
||||
}
|
||||
|
||||
export interface HardwareDiskStats {
|
||||
name: string;
|
||||
readSpeed: number;
|
||||
writeSpeed: number;
|
||||
totalBytes: number;
|
||||
freeBytes: number;
|
||||
usagePercent: number;
|
||||
}
|
||||
|
||||
export interface HardwareNetStats {
|
||||
name: string;
|
||||
bytesSentPerSecond: number;
|
||||
deltaBytesRecv: number;
|
||||
deltaPacketsSent: number;
|
||||
deltaPacketsRecv: number;
|
||||
deltaErrIn: number;
|
||||
deltaErrOut: number;
|
||||
deltaDropIn: number;
|
||||
deltaDropOut: number;
|
||||
deltaFifoIn: number;
|
||||
deltaFifoOut: number;
|
||||
}
|
||||
|
||||
export interface HardwareCheckStats {
|
||||
bucketDate: string;
|
||||
avgCpuUsage: number;
|
||||
avgMemoryUsage: number;
|
||||
avgTemperature: number[];
|
||||
disks: HardwareDiskStats[];
|
||||
net: HardwareNetStats[];
|
||||
}
|
||||
|
||||
export interface HardwareStats {
|
||||
aggregateData: {
|
||||
totalChecks: number;
|
||||
};
|
||||
upChecks: {
|
||||
totalChecks: number;
|
||||
};
|
||||
checks: HardwareCheckStats[];
|
||||
}
|
||||
|
||||
export interface HardwareDetailsResult {
|
||||
monitor: Monitor;
|
||||
stats: HardwareStats;
|
||||
monitorStats: import("../monitor-stats/monitor-stats.type.js").MonitorStats | null;
|
||||
}
|
||||
|
||||
export interface PageSpeedDetailsResult {
|
||||
monitorData: {
|
||||
monitor: Monitor;
|
||||
groupedChecks: import("../checks/check.type.js").PageSpeedGroupedCheck[];
|
||||
};
|
||||
monitorStats: import("../monitor-stats/monitor-stats.type.js").MonitorStats | null;
|
||||
}
|
||||
|
||||
export interface Game {
|
||||
name: string;
|
||||
release_year?: number;
|
||||
options?: {
|
||||
port?: number;
|
||||
port_query?: number;
|
||||
protocol?: string;
|
||||
};
|
||||
extra?: {
|
||||
old_id?: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type GamesMap = Record<string, Game>;
|
||||
@@ -0,0 +1,275 @@
|
||||
import type { Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import type { HardwareStatusPayload, MonitorStatusResponse } from "@/types/network.js";
|
||||
import type { MonitorActionDecision } from "@/service/job-queues/job-queue.helper.js";
|
||||
import type {
|
||||
NotificationMessage,
|
||||
NotificationType,
|
||||
NotificationSeverity,
|
||||
ThresholdBreach,
|
||||
NotificationContent,
|
||||
} from "@/domain/notifications/notification.type.js";
|
||||
|
||||
export interface INotificationMessageBuilder {
|
||||
buildMessage(
|
||||
monitor: Monitor,
|
||||
monitorStatusResponse: MonitorStatusResponse,
|
||||
decision: MonitorActionDecision,
|
||||
clientHost: string
|
||||
): NotificationMessage;
|
||||
extractThresholdBreaches(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): ThresholdBreach[];
|
||||
}
|
||||
|
||||
const SERVICE_NAME = "NotificationMessageBuilder";
|
||||
|
||||
export class NotificationMessageBuilder implements INotificationMessageBuilder {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
buildMessage(
|
||||
monitor: Monitor,
|
||||
monitorStatusResponse: MonitorStatusResponse,
|
||||
decision: MonitorActionDecision,
|
||||
clientHost: string
|
||||
): NotificationMessage {
|
||||
const type = this.determineNotificationType(decision, monitor);
|
||||
const severity = this.determineSeverity(type);
|
||||
const content = this.buildContent(type, monitor, monitorStatusResponse);
|
||||
|
||||
return {
|
||||
type,
|
||||
severity,
|
||||
monitor: {
|
||||
id: monitor.id,
|
||||
name: monitor.name,
|
||||
url: monitor.url,
|
||||
type: monitor.type,
|
||||
status: monitor.status,
|
||||
},
|
||||
content,
|
||||
clientHost,
|
||||
metadata: {
|
||||
teamId: monitor.teamId,
|
||||
notificationReason: decision.notificationReason || "status_change",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private determineNotificationType(decision: MonitorActionDecision, monitor: Monitor): NotificationType {
|
||||
// Down status has highest priority (critical)
|
||||
if (monitor.status === "down") {
|
||||
return "monitor_down";
|
||||
}
|
||||
|
||||
// Threshold breach (only if not down)
|
||||
if (decision.notificationReason === "threshold_breach") {
|
||||
return "threshold_breach";
|
||||
}
|
||||
|
||||
// Recovery from threshold breach (only for hardware monitors)
|
||||
if (decision.notificationReason === "status_change" && monitor.status === "up" && monitor.type === "hardware") {
|
||||
return "threshold_resolved";
|
||||
}
|
||||
|
||||
// Standard recovery (up)
|
||||
if (monitor.status === "up") {
|
||||
return "monitor_up";
|
||||
}
|
||||
|
||||
// Default to monitor_up for any other case
|
||||
return "monitor_up";
|
||||
}
|
||||
|
||||
private determineSeverity(type: NotificationType): NotificationSeverity {
|
||||
switch (type) {
|
||||
case "monitor_down":
|
||||
return "critical";
|
||||
case "threshold_breach":
|
||||
return "warning";
|
||||
case "monitor_up":
|
||||
case "threshold_resolved":
|
||||
return "success";
|
||||
case "test":
|
||||
return "info";
|
||||
default:
|
||||
return "info";
|
||||
}
|
||||
}
|
||||
|
||||
private buildContent(type: NotificationType, monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): NotificationContent {
|
||||
switch (type) {
|
||||
case "monitor_down":
|
||||
return this.buildMonitorDownContent(monitor, monitorStatusResponse);
|
||||
case "monitor_up":
|
||||
return this.buildMonitorUpContent(monitor);
|
||||
case "threshold_breach":
|
||||
return this.buildThresholdBreachContent(monitor, monitorStatusResponse as MonitorStatusResponse<HardwareStatusPayload>);
|
||||
case "threshold_resolved":
|
||||
return this.buildThresholdResolvedContent(monitor);
|
||||
default:
|
||||
return this.buildDefaultContent(monitor);
|
||||
}
|
||||
}
|
||||
|
||||
private buildMonitorDownContent(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse): NotificationContent {
|
||||
const title = `Monitor Down: ${monitor.name}`;
|
||||
const summary = `Monitor "${monitor.name}" is currently down and unreachable.`;
|
||||
const details = [`URL: ${monitor.url}`, `Status: Down`, `Type: ${monitor.type}`];
|
||||
|
||||
// Add response code if available
|
||||
if (monitorStatusResponse.code) {
|
||||
details.push(`Response Code: ${monitorStatusResponse.code}`);
|
||||
}
|
||||
|
||||
// Add error message if available
|
||||
if (monitorStatusResponse.message) {
|
||||
details.push(`Error: ${monitorStatusResponse.message}`);
|
||||
}
|
||||
|
||||
return {
|
||||
title,
|
||||
summary,
|
||||
details,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
private buildMonitorUpContent(monitor: Monitor): NotificationContent {
|
||||
const title = `Monitor Recovered: ${monitor.name}`;
|
||||
const summary = `Monitor "${monitor.name}" is back up and operational.`;
|
||||
const details = [`URL: ${monitor.url}`, `Status: Up`, `Type: ${monitor.type}`];
|
||||
|
||||
return {
|
||||
title,
|
||||
summary,
|
||||
details,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
private buildThresholdBreachContent(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse<HardwareStatusPayload>): NotificationContent {
|
||||
const title = `Threshold Exceeded: ${monitor.name}`;
|
||||
const summary = `Monitor "${monitor.name}" has exceeded one or more thresholds.`;
|
||||
const details = [`URL: ${monitor.url}`, `Status: Threshold exceeded`, `Type: ${monitor.type}`];
|
||||
|
||||
const thresholds = this.extractThresholdBreaches(monitor, monitorStatusResponse);
|
||||
|
||||
return {
|
||||
title,
|
||||
summary,
|
||||
details,
|
||||
thresholds,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
private buildThresholdResolvedContent(monitor: Monitor): NotificationContent {
|
||||
const title = `Thresholds Resolved: ${monitor.name}`;
|
||||
const summary = `Monitor "${monitor.name}" thresholds have returned to normal.`;
|
||||
const details = [`URL: ${monitor.url}`, `Status: Up`, `Type: ${monitor.type}`];
|
||||
|
||||
return {
|
||||
title,
|
||||
summary,
|
||||
details,
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
private buildDefaultContent(monitor: Monitor): NotificationContent {
|
||||
return {
|
||||
title: `Monitor: ${monitor.name}`,
|
||||
summary: `Status update for monitor "${monitor.name}".`,
|
||||
details: [`URL: ${monitor.url}`, `Status: ${monitor.status}`, `Type: ${monitor.type}`],
|
||||
timestamp: new Date(),
|
||||
};
|
||||
}
|
||||
|
||||
public extractThresholdBreaches(monitor: Monitor, monitorStatusResponse: MonitorStatusResponse<HardwareStatusPayload>): ThresholdBreach[] {
|
||||
const breaches: ThresholdBreach[] = [];
|
||||
|
||||
// Check if this is a hardware monitor with threshold data
|
||||
if (monitor.type !== "hardware" || !monitorStatusResponse.payload || typeof monitorStatusResponse.payload === "string") {
|
||||
return breaches;
|
||||
}
|
||||
|
||||
// Cast to HardwareStatusPayload type
|
||||
const payload = monitorStatusResponse.payload;
|
||||
const hardware = payload.data;
|
||||
|
||||
if (!hardware) {
|
||||
return breaches;
|
||||
}
|
||||
|
||||
// Note: usage_percent values in hardware payload are decimals (0-1)
|
||||
if (monitor.cpuAlertThreshold !== undefined && monitor.cpuAlertThreshold !== null && hardware.cpu?.usage_percent !== undefined) {
|
||||
const cpuUsageDecimal = hardware.cpu.usage_percent;
|
||||
const cpuPercent = cpuUsageDecimal * 100;
|
||||
const threshold = monitor.cpuAlertThreshold;
|
||||
if (cpuPercent > threshold) {
|
||||
breaches.push({
|
||||
metric: "cpu",
|
||||
currentValue: cpuPercent,
|
||||
threshold,
|
||||
unit: "%",
|
||||
formattedValue: `${cpuPercent.toFixed(1)}%`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Memory threshold breach
|
||||
if (monitor.memoryAlertThreshold !== undefined && monitor.memoryAlertThreshold !== null && hardware.memory?.usage_percent !== undefined) {
|
||||
const memoryUsageDecimal = hardware.memory.usage_percent;
|
||||
const memoryPercent = memoryUsageDecimal * 100;
|
||||
const threshold = monitor.memoryAlertThreshold;
|
||||
if (memoryPercent > threshold) {
|
||||
breaches.push({
|
||||
metric: "memory",
|
||||
currentValue: memoryPercent,
|
||||
threshold,
|
||||
unit: "%",
|
||||
formattedValue: `${memoryPercent.toFixed(1)}%`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Disk threshold breach
|
||||
if (monitor.diskAlertThreshold !== undefined && monitor.diskAlertThreshold !== null && Array.isArray(hardware.disk)) {
|
||||
// Find the highest disk usage
|
||||
let maxDiskUsageDecimal = 0;
|
||||
for (const disk of hardware.disk) {
|
||||
if (disk.usage_percent !== undefined && disk.usage_percent > maxDiskUsageDecimal) {
|
||||
maxDiskUsageDecimal = disk.usage_percent;
|
||||
}
|
||||
}
|
||||
const maxDiskPercent = maxDiskUsageDecimal * 100;
|
||||
const threshold = monitor.diskAlertThreshold;
|
||||
if (maxDiskPercent > threshold) {
|
||||
breaches.push({
|
||||
metric: "disk",
|
||||
currentValue: maxDiskPercent,
|
||||
threshold,
|
||||
unit: "%",
|
||||
formattedValue: `${maxDiskPercent.toFixed(1)}%`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Temperature threshold breach
|
||||
if (monitor.tempAlertThreshold !== undefined && monitor.tempAlertThreshold !== null && hardware.cpu?.temperature) {
|
||||
// Temperature is an array in cpu.temperature
|
||||
const temps = Array.isArray(hardware.cpu.temperature) ? hardware.cpu.temperature : [hardware.cpu.temperature];
|
||||
const maxTemp = Math.max(...temps.filter((t: number) => !isNaN(t)));
|
||||
const threshold = monitor.tempAlertThreshold;
|
||||
if (maxTemp >= threshold) {
|
||||
breaches.push({
|
||||
metric: "temp",
|
||||
currentValue: maxTemp,
|
||||
threshold,
|
||||
unit: "°C",
|
||||
formattedValue: `${maxTemp.toFixed(1)}°C`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return breaches;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { Notification, NotificationChannel } from "@/domain/notifications/notification.type.js";
|
||||
|
||||
interface NotificationDocument extends Omit<Notification, "id" | "userId" | "teamId" | "createdAt" | "updatedAt"> {
|
||||
_id: Types.ObjectId;
|
||||
userId: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const NotificationSchema = new Schema<NotificationDocument>(
|
||||
{
|
||||
userId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
enum: [
|
||||
"email",
|
||||
"slack",
|
||||
"discord",
|
||||
"webhook",
|
||||
"pager_duty",
|
||||
"matrix",
|
||||
"teams",
|
||||
"telegram",
|
||||
"pushover",
|
||||
"twilio",
|
||||
"ntfy",
|
||||
] as NotificationChannel[],
|
||||
required: true,
|
||||
},
|
||||
notificationName: {
|
||||
type: String,
|
||||
required: true,
|
||||
},
|
||||
address: { type: String },
|
||||
phone: { type: String },
|
||||
homeserverUrl: { type: String },
|
||||
roomId: { type: String },
|
||||
accessToken: { type: String },
|
||||
accountSid: { type: String },
|
||||
twilioPhoneNumber: { type: String },
|
||||
topic: { type: String },
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
const NotificationModel = model<NotificationDocument>("Notification", NotificationSchema);
|
||||
|
||||
export type { NotificationDocument };
|
||||
export { NotificationModel };
|
||||
export default NotificationModel;
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
export interface INotificationsRepository {
|
||||
// create
|
||||
create(notificationData: Partial<Notification>): Promise<Notification>;
|
||||
// fetch
|
||||
findById(id: string, teamId: string): Promise<Notification>;
|
||||
findNotificationsByIds(ids: string[]): Promise<Notification[]>;
|
||||
findByTeamId(teamId: string): Promise<Notification[]>;
|
||||
// update
|
||||
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
|
||||
// delete
|
||||
deleteById(id: string, teamId: string): Promise<Notification>;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import mongoose from "mongoose";
|
||||
import { NotificationModel, type NotificationDocument } from "@/domain/notifications/notification.model.js";
|
||||
import { INotificationsRepository } from "@/domain/notifications/notification.repository.interface.js";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
class MongoNotificationsRepository implements INotificationsRepository {
|
||||
private mapDocuments = (documents: NotificationDocument[]): Notification[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
private toEntity = (doc: NotificationDocument): Notification => {
|
||||
const toStringId = (value: mongoose.Types.ObjectId | string): string => {
|
||||
return value instanceof mongoose.Types.ObjectId ? value.toString() : value;
|
||||
};
|
||||
|
||||
const toDateString = (value: Date | string): string => {
|
||||
return value instanceof Date ? value.toISOString() : value;
|
||||
};
|
||||
|
||||
return {
|
||||
id: toStringId(doc._id),
|
||||
userId: toStringId(doc.userId),
|
||||
teamId: toStringId(doc.teamId),
|
||||
type: doc.type,
|
||||
notificationName: doc.notificationName,
|
||||
address: doc.address ?? undefined,
|
||||
phone: doc.phone ?? undefined,
|
||||
homeserverUrl: doc.homeserverUrl ?? undefined,
|
||||
roomId: doc.roomId ?? undefined,
|
||||
accessToken: doc.accessToken ?? undefined,
|
||||
accountSid: doc.accountSid ?? undefined,
|
||||
twilioPhoneNumber: doc.twilioPhoneNumber ?? undefined,
|
||||
topic: doc.topic ?? undefined,
|
||||
createdAt: toDateString(doc.createdAt),
|
||||
updatedAt: toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (notificationData: Partial<Notification>) => {
|
||||
const notification = await NotificationModel.create({ ...notificationData });
|
||||
if (!notification) {
|
||||
throw new AppError({ message: "Failed to create notification", status: 500 });
|
||||
}
|
||||
return this.toEntity(notification);
|
||||
};
|
||||
|
||||
findById = async (id: string, teamId: string): Promise<Notification> => {
|
||||
const notification = await NotificationModel.findOne({
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
if (!notification) {
|
||||
throw new AppError({ message: "Notification not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(notification);
|
||||
};
|
||||
|
||||
findNotificationsByIds = async (ids: string[]) => {
|
||||
const mongoIds = ids.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const documents = await NotificationModel.find({ _id: { $in: mongoIds } });
|
||||
return this.mapDocuments(documents);
|
||||
};
|
||||
|
||||
findByTeamId = async (teamId: string): Promise<Notification[]> => {
|
||||
const documents = await NotificationModel.find({ teamId });
|
||||
return this.mapDocuments(documents);
|
||||
};
|
||||
|
||||
updateById = async (id: string, teamId: string, patch: Partial<Notification>): Promise<Notification> => {
|
||||
const notification = await NotificationModel.findOneAndUpdate(
|
||||
{
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
},
|
||||
{ $set: patch },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!notification) {
|
||||
throw new AppError({ message: "Notification not found or could not be updated", status: 404 });
|
||||
}
|
||||
return this.toEntity(notification);
|
||||
};
|
||||
|
||||
deleteById = async (id: string, teamId: string): Promise<Notification> => {
|
||||
const deleted = await NotificationModel.findOneAndDelete({
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
if (!deleted) {
|
||||
throw new AppError({ message: "Notification not found or could not be deleted", status: 404 });
|
||||
}
|
||||
return this.toEntity(deleted);
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoNotificationsRepository;
|
||||
@@ -0,0 +1,231 @@
|
||||
import type { Monitor } from "@/domain/monitors/monitor.types.js";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import type { MonitorStatusResponse } from "@/types/network.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import { INotificationsRepository } from "@/domain/notifications/notification.repository.interface.js";
|
||||
import { INotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { MonitorActionDecision } from "@/service/job-queues/job-queue.helper.js";
|
||||
import type { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
import type { INotificationMessageBuilder } from "@/domain/notifications/notification.message-builder.js";
|
||||
|
||||
export interface INotificationsService {
|
||||
createNotification: (notificationData: Partial<Notification>, userId: string, teamId: string) => Promise<Notification>;
|
||||
findById: (id: string, teamId: string) => Promise<Notification>;
|
||||
findNotificationsByTeamId: (teamId: string) => Promise<Notification[]>;
|
||||
updateById(id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification>;
|
||||
deleteById: (id: string, teamId: string) => Promise<Notification>;
|
||||
handleNotifications: (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => Promise<boolean>;
|
||||
|
||||
sendTestNotification: (notification: Partial<Notification>) => Promise<boolean>;
|
||||
testAllNotifications: (notificationIds: string[]) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const SERVICE_NAME = "NotificationsService";
|
||||
|
||||
export class NotificationsService implements INotificationsService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private notificationsRepository: INotificationsRepository;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private webhookProvider: INotificationProvider;
|
||||
private emailProvider: INotificationProvider;
|
||||
private slackProvider: INotificationProvider;
|
||||
private discordProvider: INotificationProvider;
|
||||
private pagerDutyProvider: INotificationProvider;
|
||||
private matrixProvider: INotificationProvider;
|
||||
private teamsProvider: INotificationProvider;
|
||||
private telegramProvider: INotificationProvider;
|
||||
private pushoverProvider: INotificationProvider;
|
||||
private twilioProvider: INotificationProvider;
|
||||
private ntfyProvider: INotificationProvider;
|
||||
private logger: ILogger;
|
||||
private settingsService: ISettingsService;
|
||||
private notificationMessageBuilder: INotificationMessageBuilder;
|
||||
|
||||
constructor(
|
||||
notificationsRepository: INotificationsRepository,
|
||||
monitorsRepository: IMonitorsRepository,
|
||||
webhookProvider: INotificationProvider,
|
||||
emailProvider: INotificationProvider,
|
||||
slackProvider: INotificationProvider,
|
||||
discordProvider: INotificationProvider,
|
||||
pagerDutyProvider: INotificationProvider,
|
||||
matrixProvider: INotificationProvider,
|
||||
teamsProvider: INotificationProvider,
|
||||
telegramProvider: INotificationProvider,
|
||||
pushoverProvider: INotificationProvider,
|
||||
twilioProvider: INotificationProvider,
|
||||
ntfyProvider: INotificationProvider,
|
||||
settingsService: ISettingsService,
|
||||
logger: ILogger,
|
||||
notificationMessageBuilder: INotificationMessageBuilder
|
||||
) {
|
||||
this.notificationsRepository = notificationsRepository;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.webhookProvider = webhookProvider;
|
||||
this.emailProvider = emailProvider;
|
||||
this.slackProvider = slackProvider;
|
||||
this.discordProvider = discordProvider;
|
||||
this.pagerDutyProvider = pagerDutyProvider;
|
||||
this.matrixProvider = matrixProvider;
|
||||
this.teamsProvider = teamsProvider;
|
||||
this.telegramProvider = telegramProvider;
|
||||
this.pushoverProvider = pushoverProvider;
|
||||
this.twilioProvider = twilioProvider;
|
||||
this.ntfyProvider = ntfyProvider;
|
||||
this.settingsService = settingsService;
|
||||
this.logger = logger;
|
||||
this.notificationMessageBuilder = notificationMessageBuilder;
|
||||
}
|
||||
|
||||
private send = async (
|
||||
notification: Notification,
|
||||
monitor: Monitor,
|
||||
monitorStatusResponse: MonitorStatusResponse,
|
||||
decision: MonitorActionDecision,
|
||||
notificationMessage: NotificationMessage | undefined
|
||||
): Promise<boolean> => {
|
||||
if (!notificationMessage) {
|
||||
this.logger.warn({
|
||||
message: "Notification message not provided",
|
||||
service: SERVICE_NAME,
|
||||
method: "send",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Route to provider based on notification type
|
||||
switch (notification.type) {
|
||||
case "webhook":
|
||||
return await this.webhookProvider.sendMessage!(notification, notificationMessage);
|
||||
case "slack":
|
||||
return await this.slackProvider.sendMessage!(notification, notificationMessage);
|
||||
case "matrix":
|
||||
return await this.matrixProvider.sendMessage!(notification, notificationMessage);
|
||||
case "pager_duty":
|
||||
return await this.pagerDutyProvider.sendMessage!(notification, notificationMessage);
|
||||
case "discord":
|
||||
return await this.discordProvider.sendMessage!(notification, notificationMessage);
|
||||
case "email":
|
||||
return await this.emailProvider.sendMessage!(notification, notificationMessage);
|
||||
case "teams":
|
||||
return await this.teamsProvider.sendMessage!(notification, notificationMessage);
|
||||
case "telegram":
|
||||
return await this.telegramProvider.sendMessage!(notification, notificationMessage);
|
||||
case "pushover":
|
||||
return await this.pushoverProvider.sendMessage!(notification, notificationMessage);
|
||||
case "twilio":
|
||||
return await this.twilioProvider.sendMessage!(notification, notificationMessage);
|
||||
case "ntfy":
|
||||
return await this.ntfyProvider.sendMessage!(notification, notificationMessage);
|
||||
default:
|
||||
this.logger.warn({
|
||||
message: `Unknown notification type: ${notification.type}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "send",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
private sendNotifications = async (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => {
|
||||
const notificationIds = monitor.notifications ?? [];
|
||||
const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds);
|
||||
|
||||
// Build notification message once for all notifications
|
||||
const settings = this.settingsService.getSettings();
|
||||
const clientHost = settings.clientHost || "Host not defined";
|
||||
const notificationMessage = this.notificationMessageBuilder.buildMessage(monitor, monitorStatusResponse, decision, clientHost);
|
||||
|
||||
const tasks = notifications.map((notification) => this.send(notification, monitor, monitorStatusResponse, decision, notificationMessage));
|
||||
|
||||
const outcomes = await Promise.all(tasks);
|
||||
const succeeded = outcomes.filter(Boolean).length;
|
||||
const failed = outcomes.length - succeeded;
|
||||
if (failed > 0) {
|
||||
this.logger.warn({
|
||||
message: `Notification send completed with ${succeeded} success, ${failed} failure(s)`,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendNotifications",
|
||||
});
|
||||
}
|
||||
// Return true if all notifications succeeded
|
||||
return succeeded === notifications.length;
|
||||
};
|
||||
|
||||
handleNotifications = async (monitor: Monitor, monitorStatusResponse: MonitorStatusResponse, decision: MonitorActionDecision) => {
|
||||
if (!decision.shouldSendNotification) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Send notifications based on decision
|
||||
return await this.sendNotifications(monitor, monitorStatusResponse, decision);
|
||||
};
|
||||
|
||||
sendTestNotification = async (notification: Partial<Notification>) => {
|
||||
switch (notification.type) {
|
||||
case "email":
|
||||
return await this.emailProvider.sendTestAlert(notification);
|
||||
case "slack":
|
||||
return await this.slackProvider.sendTestAlert(notification);
|
||||
case "discord":
|
||||
return await this.discordProvider.sendTestAlert(notification);
|
||||
case "pager_duty":
|
||||
return await this.pagerDutyProvider.sendTestAlert(notification);
|
||||
case "matrix":
|
||||
return await this.matrixProvider.sendTestAlert(notification);
|
||||
case "webhook":
|
||||
return await this.webhookProvider.sendTestAlert(notification);
|
||||
case "teams":
|
||||
return await this.teamsProvider.sendTestAlert(notification);
|
||||
case "telegram":
|
||||
return await this.telegramProvider.sendTestAlert(notification);
|
||||
case "pushover":
|
||||
return await this.pushoverProvider.sendTestAlert(notification);
|
||||
case "twilio":
|
||||
return await this.twilioProvider.sendTestAlert(notification);
|
||||
case "ntfy":
|
||||
return await this.ntfyProvider.sendTestAlert(notification);
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
testAllNotifications = async (notificationIds: string[]) => {
|
||||
const notifications = await this.notificationsRepository.findNotificationsByIds(notificationIds);
|
||||
const tasks = notifications.map((notification) => this.sendTestNotification(notification));
|
||||
const outcomes = await Promise.all(tasks);
|
||||
const succeeded = outcomes.filter(Boolean).length;
|
||||
const failed = outcomes.length - succeeded;
|
||||
if (failed > 0) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
createNotification = async (notificationData: Partial<Notification>, userId: string, teamId: string): Promise<Notification> => {
|
||||
notificationData.userId = userId;
|
||||
notificationData.teamId = teamId;
|
||||
return await this.notificationsRepository.create(notificationData);
|
||||
};
|
||||
|
||||
findById = async (id: string, teamId: string): Promise<Notification> => {
|
||||
return await this.notificationsRepository.findById(id, teamId);
|
||||
};
|
||||
|
||||
findNotificationsByTeamId = async (teamId: string): Promise<Notification[]> => {
|
||||
return await this.notificationsRepository.findByTeamId(teamId);
|
||||
};
|
||||
|
||||
updateById = async (id: string, teamId: string, updateData: Partial<Notification>): Promise<Notification> => {
|
||||
return await this.notificationsRepository.updateById(id, teamId, updateData);
|
||||
};
|
||||
|
||||
deleteById = async (id: string, teamId: string): Promise<Notification> => {
|
||||
await this.monitorsRepository.removeNotificationFromMonitors(id);
|
||||
const deleted = await this.notificationsRepository.deleteById(id, teamId);
|
||||
return deleted;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
export const NotificationChannels = [
|
||||
"email",
|
||||
"slack",
|
||||
"discord",
|
||||
"webhook",
|
||||
"pager_duty",
|
||||
"matrix",
|
||||
"teams",
|
||||
"telegram",
|
||||
"pushover",
|
||||
"twilio",
|
||||
"ntfy",
|
||||
] as const;
|
||||
export type NotificationChannel = (typeof NotificationChannels)[number];
|
||||
|
||||
export interface Notification {
|
||||
id: string;
|
||||
userId: string;
|
||||
teamId: string;
|
||||
type: NotificationChannel;
|
||||
notificationName: string;
|
||||
address?: string;
|
||||
phone?: string;
|
||||
homeserverUrl?: string;
|
||||
roomId?: string;
|
||||
accessToken?: string;
|
||||
accountSid?: string;
|
||||
twilioPhoneNumber?: string;
|
||||
topic?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface AlertPagerDutyPayload {
|
||||
routing_key?: string;
|
||||
dedup_key?: string;
|
||||
event_action?: "trigger" | "resolve";
|
||||
payload: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface AlertMatrixPayload {
|
||||
plainText: string;
|
||||
htmlText: string;
|
||||
}
|
||||
|
||||
export interface DiscordEmbedField {
|
||||
name: string;
|
||||
value: string;
|
||||
inline?: boolean;
|
||||
}
|
||||
|
||||
export interface AlertDiscordPayload {
|
||||
title: string;
|
||||
description: string;
|
||||
color: number;
|
||||
fields: DiscordEmbedField[];
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified notification message types for cross-provider consistency
|
||||
* Part of notification system unification effort
|
||||
*/
|
||||
|
||||
export type NotificationType = "monitor_down" | "monitor_up" | "threshold_breach" | "threshold_resolved" | "test";
|
||||
|
||||
export type NotificationSeverity = "critical" | "warning" | "info" | "success";
|
||||
|
||||
export interface MonitorInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
url: string;
|
||||
type: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface ThresholdBreach {
|
||||
metric: "cpu" | "memory" | "disk" | "temp";
|
||||
currentValue: number;
|
||||
threshold: number;
|
||||
unit: string;
|
||||
formattedValue: string; // e.g., "85%" or "72°C"
|
||||
}
|
||||
|
||||
export interface IncidentInfo {
|
||||
id: string;
|
||||
url: string;
|
||||
createdAt: Date;
|
||||
resolvedAt?: Date;
|
||||
duration?: string;
|
||||
}
|
||||
|
||||
export interface NotificationContent {
|
||||
title: string;
|
||||
summary: string;
|
||||
details?: string[];
|
||||
thresholds?: ThresholdBreach[];
|
||||
incident?: IncidentInfo;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export interface NotificationMessage {
|
||||
type: NotificationType;
|
||||
severity: NotificationSeverity;
|
||||
monitor: MonitorInfo;
|
||||
content: NotificationContent;
|
||||
clientHost: string;
|
||||
metadata: {
|
||||
teamId: string;
|
||||
notificationReason: string;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
import type { OptionsOfJSONResponseBody } from "got";
|
||||
|
||||
export const DEFAULT_NOTIFICATION_TIMEOUT_MS = 30_000;
|
||||
export interface INotificationProvider {
|
||||
sendMessage: (notification: Notification, message: NotificationMessage) => Promise<boolean>;
|
||||
sendTestAlert(notification: Partial<Notification>): Promise<boolean>;
|
||||
}
|
||||
|
||||
export abstract class NotificationProvider implements INotificationProvider {
|
||||
protected readonly logger: ILogger;
|
||||
protected readonly timeoutMs: number;
|
||||
|
||||
constructor(logger: ILogger, timeoutMs: number = DEFAULT_NOTIFICATION_TIMEOUT_MS) {
|
||||
this.logger = logger;
|
||||
this.timeoutMs = timeoutMs;
|
||||
}
|
||||
|
||||
protected gotRequestOptions(): Pick<OptionsOfJSONResponseBody, "timeout" | "retry"> {
|
||||
return {
|
||||
timeout: { request: this.timeoutMs },
|
||||
retry: { limit: 0 },
|
||||
};
|
||||
}
|
||||
|
||||
abstract sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean>;
|
||||
abstract sendTestAlert(notification: Partial<Notification>): Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
const SERVICE_NAME = "DiscordProvider";
|
||||
import type { AlertDiscordPayload, DiscordEmbedField, Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import type { NotificationMessage, NotificationSeverity } from "@/domain/notifications/notification.type.js";
|
||||
import got from "got";
|
||||
|
||||
export class DiscordProvider extends NotificationProvider {
|
||||
sendTestAlert = async (notification: Partial<Notification>) => {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: { content: getTestMessage() },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "Discord test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
this.logger.warn({
|
||||
message: "Discord notification missing webhook URL",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const embed = this.buildDiscordEmbed(message);
|
||||
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: { embeds: [embed] },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "Discord notification failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private buildDiscordEmbed(message: NotificationMessage): AlertDiscordPayload {
|
||||
const colorMap: Record<NotificationSeverity, number> = {
|
||||
critical: 0xdc2626, // red-600
|
||||
warning: 0xf59e0b, // amber-500
|
||||
info: 0x3b82f6, // blue-500
|
||||
success: 0x10b981, // green-500
|
||||
};
|
||||
|
||||
const color = colorMap[message.severity] ?? colorMap.info;
|
||||
|
||||
const fields: Array<DiscordEmbedField> = [];
|
||||
|
||||
// Add monitor details
|
||||
fields.push({
|
||||
name: "Monitor",
|
||||
value: message.monitor.name,
|
||||
inline: true,
|
||||
});
|
||||
|
||||
fields.push({
|
||||
name: "Type",
|
||||
value: message.monitor.type.toUpperCase(),
|
||||
inline: true,
|
||||
});
|
||||
|
||||
fields.push({
|
||||
name: "Status",
|
||||
value: message.monitor.status.charAt(0).toUpperCase() + message.monitor.status.slice(1),
|
||||
inline: true,
|
||||
});
|
||||
|
||||
// Add monitor URL
|
||||
fields.push({
|
||||
name: "URL",
|
||||
value: message.monitor.url,
|
||||
inline: false,
|
||||
});
|
||||
|
||||
// Add threshold breaches if present
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
const thresholdLines = message.content.thresholds
|
||||
.map((t) => `• **${t.metric.toUpperCase()}**: ${t.formattedValue} (threshold: ${t.threshold}${t.unit})`)
|
||||
.join("\n");
|
||||
|
||||
fields.push({
|
||||
name: "Threshold Breaches",
|
||||
value: thresholdLines,
|
||||
inline: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Add details if present
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
const detailsText = message.content.details.join("\n");
|
||||
fields.push({
|
||||
name: "Details",
|
||||
value: detailsText,
|
||||
inline: false,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
title: message.content.title,
|
||||
description: message.content.summary,
|
||||
color,
|
||||
fields,
|
||||
timestamp: message.content.timestamp.toISOString(),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
const SERVICE_NAME = "EmailProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import { buildTestEmail } from "@/domain/notifications/providers/utils.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import type { ILogger } from "@/utils/logger.js";
|
||||
import { IEmailService } from "@/service/emailService.js";
|
||||
export class EmailProvider extends NotificationProvider {
|
||||
private emailService: IEmailService;
|
||||
|
||||
constructor(emailService: IEmailService, logger: ILogger) {
|
||||
super(logger);
|
||||
this.emailService = emailService;
|
||||
}
|
||||
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
const subject = "Test notification";
|
||||
const html = await buildTestEmail(this.emailService);
|
||||
|
||||
if (!notification.address) {
|
||||
this.logger.warn({
|
||||
message: "Missing address",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!html) {
|
||||
this.logger.warn({
|
||||
message: "Failed to build test email content",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const messageId = await this.emailService.sendEmail(notification.address, subject, html);
|
||||
if (!messageId) {
|
||||
this.logger.warn({
|
||||
message: "Email test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const subject = this.buildSubject(message);
|
||||
const html = await this.buildEmailFromMessage(message);
|
||||
|
||||
if (!html) {
|
||||
this.logger.warn({
|
||||
message: "Failed to build email content",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
const messageId = await this.emailService.sendEmail(notification.address, subject, html);
|
||||
if (!messageId) {
|
||||
this.logger.warn({
|
||||
message: "Email notification failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private buildSubject(message: NotificationMessage): string {
|
||||
switch (message.type) {
|
||||
case "monitor_down":
|
||||
return `Monitor ${message.monitor.name} is down`;
|
||||
case "monitor_up":
|
||||
return `Monitor ${message.monitor.name} is back up`;
|
||||
case "threshold_breach":
|
||||
return `Monitor ${message.monitor.name} threshold exceeded`;
|
||||
case "threshold_resolved":
|
||||
return `Monitor ${message.monitor.name} thresholds resolved`;
|
||||
default:
|
||||
return `Alert: ${message.monitor.name}`;
|
||||
}
|
||||
}
|
||||
|
||||
private async buildEmailFromMessage(message: NotificationMessage): Promise<string | undefined> {
|
||||
const context = {
|
||||
title: message.content.title,
|
||||
summary: message.content.summary,
|
||||
monitorName: message.monitor.name,
|
||||
monitorUrl: message.monitor.url,
|
||||
monitorType: message.monitor.type,
|
||||
monitorStatus: message.monitor.status,
|
||||
headerColor: this.getColorForSeverity(message.severity),
|
||||
thresholds: message.content.thresholds,
|
||||
details: message.content.details,
|
||||
incidentUrl: message.content.incident?.url,
|
||||
};
|
||||
|
||||
this.logger.info({
|
||||
message: "[DEBUG] Building email from message",
|
||||
service: SERVICE_NAME,
|
||||
method: "buildEmailFromMessage",
|
||||
details: { context },
|
||||
});
|
||||
|
||||
const html = await this.emailService.buildEmail("unifiedNotificationTemplate", context);
|
||||
|
||||
return html;
|
||||
}
|
||||
|
||||
private getColorForSeverity(severity: string): string {
|
||||
const colorMap: Record<string, string> = {
|
||||
critical: "red",
|
||||
warning: "#f59e0b",
|
||||
info: "#3b82f6",
|
||||
success: "green",
|
||||
};
|
||||
return colorMap[severity] ?? "#3b82f6";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
const SERVICE_NAME = "MatrixProvider";
|
||||
import got from "got";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { AlertMatrixPayload, Notification } from "@/domain/notifications/notification.type.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import { randomUUID } from "crypto";
|
||||
|
||||
export class MatrixProvider extends NotificationProvider {
|
||||
sendTestAlert = async (notification: Partial<Notification>) => {
|
||||
const { homeserverUrl, accessToken, roomId } = notification;
|
||||
if (!homeserverUrl || !accessToken || !roomId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const body = {
|
||||
msgtype: "m.text",
|
||||
body: getTestMessage(),
|
||||
};
|
||||
return await this.sendMessageWithBody(notification, body);
|
||||
};
|
||||
|
||||
sendMessage = async (notification: Notification, message: NotificationMessage): Promise<boolean> => {
|
||||
const { homeserverUrl, accessToken, roomId } = notification;
|
||||
if (!homeserverUrl || !accessToken || !roomId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const { plainText, htmlText } = this.buildMatrixMessage(message);
|
||||
const body = {
|
||||
msgtype: "m.text",
|
||||
body: plainText,
|
||||
format: "org.matrix.custom.html",
|
||||
formatted_body: htmlText,
|
||||
};
|
||||
return this.sendMessageWithBody(notification, body);
|
||||
};
|
||||
|
||||
private sendMessageWithBody = async (notification: Partial<Notification>, body: unknown): Promise<boolean> => {
|
||||
const { homeserverUrl, accessToken, roomId } = notification;
|
||||
const txnId = randomUUID();
|
||||
const url = `${homeserverUrl}/_matrix/client/v3/rooms/${roomId}/send/m.room.message/${txnId}`;
|
||||
|
||||
try {
|
||||
await got.put(url, {
|
||||
json: body,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: `Matrix notification failed : ${err.message}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Build Matrix message from NotificationMessage
|
||||
* Returns both plain text and HTML formatted versions
|
||||
* Matrix supports HTML subset for rich formatting
|
||||
*/
|
||||
private buildMatrixMessage(message: NotificationMessage): AlertMatrixPayload {
|
||||
const plainLines: string[] = [];
|
||||
const htmlLines: string[] = [];
|
||||
|
||||
// Determine color based on severity
|
||||
const colorMap = {
|
||||
critical: "#FF0000", // Red
|
||||
warning: "#FFA500", // Orange
|
||||
success: "#00FF00", // Green
|
||||
info: "#0000FF", // Blue
|
||||
};
|
||||
const color = colorMap[message.severity] || "#808080";
|
||||
|
||||
// Title
|
||||
plainLines.push(`# ${message.content.title}`);
|
||||
htmlLines.push(`<h2 style="color: ${color};">${this.escapeHtml(message.content.title)}</h2>`);
|
||||
|
||||
// Summary
|
||||
plainLines.push("");
|
||||
plainLines.push(message.content.summary);
|
||||
htmlLines.push(`<p>${this.escapeHtml(message.content.summary)}</p>`);
|
||||
|
||||
// Monitor details
|
||||
plainLines.push("");
|
||||
plainLines.push("## Monitor Details");
|
||||
plainLines.push(`- Name: ${message.monitor.name}`);
|
||||
plainLines.push(`- URL: ${message.monitor.url}`);
|
||||
plainLines.push(`- Type: ${message.monitor.type}`);
|
||||
plainLines.push(`- Status: ${message.monitor.status}`);
|
||||
|
||||
htmlLines.push(`<h3>Monitor Details</h3>`);
|
||||
htmlLines.push(`<ul>`);
|
||||
htmlLines.push(`<li><strong>Name:</strong> ${this.escapeHtml(message.monitor.name)}</li>`);
|
||||
htmlLines.push(`<li><strong>URL:</strong> <a href="${this.escapeHtml(message.monitor.url)}">${this.escapeHtml(message.monitor.url)}</a></li>`);
|
||||
htmlLines.push(`<li><strong>Type:</strong> ${this.escapeHtml(message.monitor.type)}</li>`);
|
||||
htmlLines.push(`<li><strong>Status:</strong> ${this.escapeHtml(message.monitor.status)}</li>`);
|
||||
htmlLines.push(`</ul>`);
|
||||
|
||||
// Threshold breaches (if any)
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
plainLines.push("");
|
||||
plainLines.push("## Threshold Breaches");
|
||||
htmlLines.push(`<h3>Threshold Breaches</h3>`);
|
||||
htmlLines.push(`<ul>`);
|
||||
|
||||
message.content.thresholds.forEach((breach) => {
|
||||
plainLines.push(`- ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
|
||||
htmlLines.push(
|
||||
`<li><strong>${this.escapeHtml(breach.metric.toUpperCase())}:</strong> ${this.escapeHtml(breach.formattedValue)} (threshold: ${breach.threshold}${this.escapeHtml(breach.unit)})</li>`
|
||||
);
|
||||
});
|
||||
|
||||
htmlLines.push(`</ul>`);
|
||||
}
|
||||
|
||||
// Additional details (if any)
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
plainLines.push("");
|
||||
plainLines.push("## Additional Information");
|
||||
htmlLines.push(`<h3>Additional Information</h3>`);
|
||||
htmlLines.push(`<ul>`);
|
||||
|
||||
message.content.details.forEach((detail) => {
|
||||
plainLines.push(`- ${detail}`);
|
||||
htmlLines.push(`<li>${this.escapeHtml(detail)}</li>`);
|
||||
});
|
||||
|
||||
htmlLines.push(`</ul>`);
|
||||
}
|
||||
|
||||
// Incident link (if incident exists)
|
||||
if (message.content.incident) {
|
||||
const incidentUrl = `${message.clientHost}/infrastructure/${message.monitor.id}`;
|
||||
plainLines.push("");
|
||||
plainLines.push(`View Incident: ${incidentUrl}`);
|
||||
htmlLines.push(`<p><a href="${this.escapeHtml(incidentUrl)}">View Incident</a></p>`);
|
||||
}
|
||||
|
||||
// Footer with timestamp
|
||||
plainLines.push("");
|
||||
plainLines.push(`Checkmate | ${new Date(message.content.timestamp).toUTCString()}`);
|
||||
htmlLines.push(`<hr>`);
|
||||
htmlLines.push(`<p><small>Checkmate | ${new Date(message.content.timestamp).toUTCString()}</small></p>`);
|
||||
|
||||
return {
|
||||
plainText: plainLines.join("\n"),
|
||||
htmlText: htmlLines.join(""),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape HTML special characters for safe rendering
|
||||
*/
|
||||
private escapeHtml(text: string): string {
|
||||
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
const SERVICE_NAME = "NtfyProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got from "got";
|
||||
|
||||
export class NtfyProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
if (!notification.address || !notification.topic) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await got.post(this.buildTopicUrl(notification.address, notification.topic), {
|
||||
body: getTestMessage(),
|
||||
headers: {
|
||||
Title: "Checkmate test notification",
|
||||
Priority: "default",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "ntfy test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address || !notification.topic) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await got.post(this.buildTopicUrl(notification.address, notification.topic), {
|
||||
body: this.buildNtfyText(message),
|
||||
headers: {
|
||||
Title: message.content.title,
|
||||
Priority: this.mapPriority(message.severity),
|
||||
Tags: this.mapTags(message.severity),
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
this.logger.info({
|
||||
message: "ntfy notification sent",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "ntfy alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private buildTopicUrl(address: string, topic: string): string {
|
||||
return `${address.replace(/\/+$/, "")}/${encodeURIComponent(topic)}`;
|
||||
}
|
||||
|
||||
private buildNtfyText(message: NotificationMessage): string {
|
||||
const lines = [
|
||||
message.content.summary,
|
||||
"",
|
||||
"Monitor Details:",
|
||||
`- Name: ${message.monitor.name}`,
|
||||
`- URL: ${message.monitor.url}`,
|
||||
`- Type: ${message.monitor.type}`,
|
||||
`- Status: ${message.monitor.status}`,
|
||||
];
|
||||
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
lines.push("", "Additional Information:");
|
||||
message.content.details.forEach((detail) => lines.push(`- ${detail}`));
|
||||
}
|
||||
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
lines.push("", "Threshold Breaches:");
|
||||
message.content.thresholds.forEach((breach) => {
|
||||
lines.push(`- ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
|
||||
});
|
||||
}
|
||||
|
||||
if (message.content.incident) {
|
||||
lines.push("", `${message.clientHost}/infrastructure/${message.monitor.id}`);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
private mapPriority(severity: NotificationMessage["severity"]): string {
|
||||
switch (severity) {
|
||||
case "critical":
|
||||
return "high";
|
||||
case "warning":
|
||||
return "default";
|
||||
case "success":
|
||||
return "low";
|
||||
default:
|
||||
return "default";
|
||||
}
|
||||
}
|
||||
|
||||
private mapTags(severity: NotificationMessage["severity"]): string {
|
||||
switch (severity) {
|
||||
case "critical":
|
||||
return "rotating_light";
|
||||
case "warning":
|
||||
return "warning";
|
||||
case "success":
|
||||
return "white_check_mark";
|
||||
default:
|
||||
return "information_source";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
const SERVICE_NAME = "PagerDutyProvider";
|
||||
import got from "got";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import { AlertPagerDutyPayload } from "@/domain/notifications/notification.type.js";
|
||||
|
||||
export class PagerDutyProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
try {
|
||||
await got.post("https://events.pagerduty.com/v2/enqueue", {
|
||||
json: {
|
||||
routing_key: notification.address,
|
||||
event_action: "trigger",
|
||||
payload: {
|
||||
summary: getTestMessage(),
|
||||
severity: "info",
|
||||
source: "checkmate",
|
||||
timestamp: new Date().toISOString(),
|
||||
},
|
||||
},
|
||||
responseType: "json",
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "PagerDuty test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* New unified message format implementation
|
||||
*/
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
this.logger.warn({
|
||||
message: "PagerDuty notification missing routing key",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = this.buildPagerDutyPayload(notification, message);
|
||||
await got.post("https://events.pagerduty.com/v2/enqueue", {
|
||||
json: payload,
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
this.logger.info({
|
||||
message: "[NEW] PagerDuty notification sent via sendMessage",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "PagerDuty notification failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private buildPagerDutyPayload(notification: Notification, message: NotificationMessage): AlertPagerDutyPayload {
|
||||
// Map our notification type to PagerDuty event_action
|
||||
const eventAction = message.type === "monitor_up" || message.type === "threshold_resolved" ? "resolve" : "trigger";
|
||||
|
||||
// Map severity to PagerDuty severity levels
|
||||
const severityMap: Record<string, string> = {
|
||||
critical: "critical",
|
||||
warning: "warning",
|
||||
info: "info",
|
||||
success: "info",
|
||||
};
|
||||
|
||||
const severity = severityMap[message.severity] || "error";
|
||||
|
||||
// Build deduplication key based on monitor ID for event grouping
|
||||
const dedupKey = `checkmate-${message.monitor.id}`;
|
||||
|
||||
// Build summary
|
||||
let summary = `${message.content.title} - ${message.content.summary}`;
|
||||
|
||||
// Add threshold details to summary if present
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
const thresholdInfo = message.content.thresholds
|
||||
.map((t) => `${t.metric.toUpperCase()}: ${t.formattedValue}/${t.threshold}${t.unit}`)
|
||||
.join(", ");
|
||||
summary += ` [${thresholdInfo}]`;
|
||||
}
|
||||
|
||||
// Build custom details
|
||||
const customDetails: Record<string, unknown> = {
|
||||
monitor_name: message.monitor.name,
|
||||
monitor_url: message.monitor.url,
|
||||
monitor_type: message.monitor.type,
|
||||
monitor_status: message.monitor.status,
|
||||
notification_type: message.type,
|
||||
};
|
||||
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
customDetails.threshold_breaches = message.content.thresholds.map((t) => ({
|
||||
metric: t.metric,
|
||||
current: t.formattedValue,
|
||||
threshold: `${t.threshold}${t.unit}`,
|
||||
}));
|
||||
}
|
||||
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
customDetails.details = message.content.details;
|
||||
}
|
||||
|
||||
return {
|
||||
routing_key: notification.address,
|
||||
dedup_key: dedupKey,
|
||||
event_action: eventAction,
|
||||
payload: {
|
||||
summary,
|
||||
severity,
|
||||
source: message.monitor.url,
|
||||
timestamp: message.content.timestamp.toISOString(),
|
||||
custom_details: customDetails,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
const SERVICE_NAME = "PushoverProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got from "got";
|
||||
|
||||
export class PushoverProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
if (!notification.address || !notification.accessToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await got.post("https://api.pushover.net/1/messages.json", {
|
||||
form: {
|
||||
token: notification.accessToken,
|
||||
user: notification.address,
|
||||
message: getTestMessage(),
|
||||
title: "Checkmate Test Notification",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : "unknown error";
|
||||
const errStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.warn({
|
||||
message: "Pushover test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: errStack,
|
||||
details: { error: errMsg },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address || !notification.accessToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const text = this.buildPushoverText(message);
|
||||
|
||||
try {
|
||||
await got.post("https://api.pushover.net/1/messages.json", {
|
||||
form: {
|
||||
token: notification.accessToken,
|
||||
user: notification.address,
|
||||
message: text,
|
||||
title: message.content.title,
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
|
||||
this.logger.info({
|
||||
message: "Pushover notification sent",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : "unknown error";
|
||||
const errStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.warn({
|
||||
message: "Pushover alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: errStack,
|
||||
details: { error: errMsg },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private buildPushoverText(message: NotificationMessage): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(message.content.summary);
|
||||
lines.push("");
|
||||
lines.push("Monitor Details:");
|
||||
lines.push(`• Name: ${message.monitor.name}`);
|
||||
lines.push(`• URL: ${message.monitor.url}`);
|
||||
lines.push(`• Type: ${message.monitor.type}`);
|
||||
lines.push(`• Status: ${message.monitor.status}`);
|
||||
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
lines.push("");
|
||||
lines.push("Additional Information:");
|
||||
message.content.details.forEach((detail) => lines.push(`• ${detail}`));
|
||||
}
|
||||
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
lines.push("");
|
||||
lines.push("Threshold Breaches:");
|
||||
message.content.thresholds.forEach((breach) => {
|
||||
lines.push(`• ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
|
||||
});
|
||||
}
|
||||
|
||||
if (message.content.incident) {
|
||||
lines.push("");
|
||||
lines.push(`View Incident: ${message.clientHost}/incidents/${message.monitor.id}`);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
const SERVICE_NAME = "SlackProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got, { HTTPError } from "got";
|
||||
|
||||
export class SlackProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: { text: getTestMessage() },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as HTTPError;
|
||||
this.logger.warn({
|
||||
message: "Slack test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* New unified message format - builds Slack Block Kit payload from NotificationMessage
|
||||
*/
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payload = this.buildSlackPayload(message);
|
||||
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
this.logger.info({
|
||||
message: "[NEW] Slack notification sent via sendMessage",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "[NEW] Slack alert failed via sendMessage",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build Slack Block Kit payload from NotificationMessage
|
||||
* Uses Slack's rich formatting with sections, fields, and context blocks
|
||||
*/
|
||||
private buildSlackPayload(message: NotificationMessage): object {
|
||||
const blocks: unknown[] = [];
|
||||
|
||||
// Determine color based on severity
|
||||
const colorMap = {
|
||||
critical: "#FF0000", // Red
|
||||
warning: "#FFA500", // Orange
|
||||
success: "#00FF00", // Green
|
||||
info: "#0000FF", // Blue
|
||||
};
|
||||
const color = colorMap[message.severity] || "#808080";
|
||||
|
||||
// Header block with title
|
||||
blocks.push({
|
||||
type: "header",
|
||||
text: {
|
||||
type: "plain_text",
|
||||
text: message.content.title,
|
||||
emoji: true,
|
||||
},
|
||||
});
|
||||
|
||||
// Summary section
|
||||
blocks.push({
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: message.content.summary,
|
||||
},
|
||||
});
|
||||
|
||||
// Monitor details as fields
|
||||
const monitorFields = [
|
||||
{ type: "mrkdwn", text: `*Name:*\n${message.monitor.name}` },
|
||||
{ type: "mrkdwn", text: `*Type:*\n${message.monitor.type}` },
|
||||
{ type: "mrkdwn", text: `*Status:*\n${message.monitor.status}` },
|
||||
{ type: "mrkdwn", text: `*URL:*\n${message.monitor.url}` },
|
||||
];
|
||||
|
||||
blocks.push({
|
||||
type: "section",
|
||||
fields: monitorFields,
|
||||
});
|
||||
|
||||
// Divider
|
||||
blocks.push({ type: "divider" });
|
||||
|
||||
// Threshold breaches (if any)
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
const thresholdText = message.content.thresholds
|
||||
.map((breach) => `• *${breach.metric.toUpperCase()}:* ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`)
|
||||
.join("\n");
|
||||
|
||||
blocks.push({
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Threshold Breaches:*\n${thresholdText}`,
|
||||
},
|
||||
});
|
||||
|
||||
blocks.push({ type: "divider" });
|
||||
}
|
||||
|
||||
// Additional details (if any)
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
const detailsText = message.content.details.map((detail) => `• ${detail}`).join("\n");
|
||||
|
||||
blocks.push({
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Additional Information:*\n${detailsText}`,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Incident link button (if incident exists)
|
||||
if (message.content.incident) {
|
||||
blocks.push({
|
||||
type: "actions",
|
||||
elements: [
|
||||
{
|
||||
type: "button",
|
||||
text: {
|
||||
type: "plain_text",
|
||||
text: "View Incident",
|
||||
emoji: true,
|
||||
},
|
||||
url: `${message.clientHost}/infrastructure/${message.monitor.id}`,
|
||||
style: "primary",
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
// Context footer with timestamp
|
||||
blocks.push({
|
||||
type: "context",
|
||||
elements: [
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `Checkmate | ${new Date(message.content.timestamp).toUTCString()}`,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
// Return Slack payload with blocks and attachment color
|
||||
return {
|
||||
blocks,
|
||||
attachments: [
|
||||
{
|
||||
color,
|
||||
blocks: [], // Empty blocks in attachment for color bar
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
const SERVICE_NAME = "TeamsProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got, { HTTPError } from "got";
|
||||
|
||||
// Types for Adaptive Card elements
|
||||
type TextBlock = {
|
||||
type: "TextBlock";
|
||||
text: string;
|
||||
weight?: "Bolder" | "Normal" | "Lighter";
|
||||
size?: "Small" | "Medium" | "Large" | "ExtraLarge";
|
||||
color?: "Default" | "Dark" | "Light" | "Accent" | "Good" | "Warning" | "Attention";
|
||||
wrap?: boolean;
|
||||
spacing?: "None" | "Small" | "Medium" | "Large" | "ExtraLarge" | "Auto";
|
||||
isSubtle?: boolean;
|
||||
};
|
||||
|
||||
type ColumnSet = {
|
||||
type: "ColumnSet";
|
||||
separator?: boolean;
|
||||
spacing?: "None" | "Small" | "Medium" | "Large" | "ExtraLarge" | "Auto";
|
||||
columns: unknown[];
|
||||
};
|
||||
|
||||
type Fact = {
|
||||
title: string;
|
||||
value: string;
|
||||
};
|
||||
|
||||
type FactSet = {
|
||||
type: "FactSet";
|
||||
facts: Fact[];
|
||||
};
|
||||
|
||||
type Action = {
|
||||
type: string;
|
||||
title: string;
|
||||
url?: string;
|
||||
};
|
||||
|
||||
type AdaptiveCard = {
|
||||
type: "AdaptiveCard";
|
||||
$schema: "http://adaptivecards.io/schemas/adaptive-card.json";
|
||||
version: "1.4";
|
||||
body: (TextBlock | ColumnSet | FactSet)[];
|
||||
actions?: Action[];
|
||||
};
|
||||
|
||||
type TeamsMessage = {
|
||||
type: "message";
|
||||
attachments: Array<{
|
||||
contentType: "application/vnd.microsoft.card.adaptive";
|
||||
contentUrl: null;
|
||||
content: AdaptiveCard;
|
||||
}>;
|
||||
};
|
||||
|
||||
export class TeamsProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = this.wrapAdaptiveCard({
|
||||
type: "AdaptiveCard",
|
||||
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||
version: "1.4",
|
||||
body: [
|
||||
{
|
||||
type: "TextBlock",
|
||||
text: getTestMessage(),
|
||||
weight: "Bolder",
|
||||
size: "Medium",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await got.post(notification.address, {
|
||||
json: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as HTTPError;
|
||||
this.logger.warn({
|
||||
message: "Teams test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const payload = this.wrapAdaptiveCard(this.buildAdaptiveCard(message));
|
||||
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
this.logger.info({
|
||||
message: "Teams notification sent via sendMessage",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as HTTPError;
|
||||
this.logger.warn({
|
||||
message: "Teams alert failed via sendMessage",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap an Adaptive Card in the Teams webhook envelope format
|
||||
*/
|
||||
private wrapAdaptiveCard(card: AdaptiveCard): TeamsMessage {
|
||||
return {
|
||||
type: "message",
|
||||
attachments: [
|
||||
{
|
||||
contentType: "application/vnd.microsoft.card.adaptive",
|
||||
contentUrl: null,
|
||||
content: card,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an Adaptive Card from NotificationMessage
|
||||
*/
|
||||
private buildAdaptiveCard(message: NotificationMessage): AdaptiveCard {
|
||||
const colorMap: Record<string, string> = {
|
||||
critical: "attention",
|
||||
warning: "warning",
|
||||
success: "good",
|
||||
info: "accent",
|
||||
};
|
||||
const color = (colorMap[message.severity] || "default") as "Default" | "Dark" | "Light" | "Accent" | "Good" | "Warning" | "Attention" | undefined;
|
||||
|
||||
const body: (TextBlock | ColumnSet | FactSet)[] = [];
|
||||
|
||||
// Header with colored status indicator
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: message.content.title,
|
||||
weight: "Bolder",
|
||||
size: "Large",
|
||||
color,
|
||||
wrap: true,
|
||||
});
|
||||
|
||||
// Summary
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: message.content.summary,
|
||||
wrap: true,
|
||||
spacing: "Small",
|
||||
});
|
||||
|
||||
// Separator
|
||||
body.push({
|
||||
type: "ColumnSet",
|
||||
separator: true,
|
||||
spacing: "Medium",
|
||||
columns: [],
|
||||
});
|
||||
|
||||
// Monitor details as a FactSet
|
||||
body.push({
|
||||
type: "FactSet",
|
||||
facts: [
|
||||
{ title: "Name", value: message.monitor.name },
|
||||
{ title: "Type", value: message.monitor.type },
|
||||
{ title: "Status", value: message.monitor.status },
|
||||
{ title: "URL", value: message.monitor.url },
|
||||
],
|
||||
});
|
||||
|
||||
// Threshold breaches
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: "**Threshold Breaches**",
|
||||
weight: "Bolder",
|
||||
spacing: "Medium",
|
||||
wrap: true,
|
||||
});
|
||||
|
||||
for (const breach of message.content.thresholds) {
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: `• **${breach.metric.toUpperCase()}**: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`,
|
||||
wrap: true,
|
||||
spacing: "Small",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Additional details
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: "**Additional Information**",
|
||||
weight: "Bolder",
|
||||
spacing: "Medium",
|
||||
wrap: true,
|
||||
});
|
||||
|
||||
for (const detail of message.content.details) {
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: `• ${detail}`,
|
||||
wrap: true,
|
||||
spacing: "Small",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Timestamp footer
|
||||
body.push({
|
||||
type: "TextBlock",
|
||||
text: `Checkmate | ${new Date(message.content.timestamp).toUTCString()}`,
|
||||
size: "Small",
|
||||
isSubtle: true,
|
||||
spacing: "Medium",
|
||||
wrap: true,
|
||||
});
|
||||
|
||||
// Actions (incident link)
|
||||
const actions: Action[] = [];
|
||||
if (message.content.incident) {
|
||||
actions.push({
|
||||
type: "Action.OpenUrl",
|
||||
title: "View Incident",
|
||||
url: `${message.clientHost}/incidents/${message.content.incident.id}`,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
type: "AdaptiveCard",
|
||||
$schema: "http://adaptivecards.io/schemas/adaptive-card.json",
|
||||
version: "1.4",
|
||||
body,
|
||||
...(actions.length > 0 ? { actions } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
const SERVICE_NAME = "TelegramProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got from "got";
|
||||
|
||||
export class TelegramProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
if (!notification.address || !notification.accessToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await got.post(`https://api.telegram.org/bot${notification.accessToken}/sendMessage`, {
|
||||
json: {
|
||||
chat_id: notification.address,
|
||||
text: getTestMessage(),
|
||||
parse_mode: "HTML",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : "unknown error";
|
||||
const errStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.warn({
|
||||
message: "Telegram test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: errStack,
|
||||
details: { error: errMsg },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.address || !notification.accessToken) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const text = this.buildTelegramText(message);
|
||||
|
||||
try {
|
||||
await got.post(`https://api.telegram.org/bot${notification.accessToken}/sendMessage`, {
|
||||
json: {
|
||||
chat_id: notification.address,
|
||||
text,
|
||||
parse_mode: "HTML",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
|
||||
this.logger.info({
|
||||
message: "Telegram notification sent",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : "unknown error";
|
||||
const errStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.warn({
|
||||
message: "Telegram alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: errStack,
|
||||
details: { error: errMsg },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private buildTelegramText(message: NotificationMessage): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(`<b>${message.content.title}</b>`);
|
||||
lines.push(message.content.summary);
|
||||
lines.push("");
|
||||
|
||||
lines.push("<b>Monitor Details:</b>");
|
||||
lines.push(`• Name: ${message.monitor.name}`);
|
||||
lines.push(`• URL: ${message.monitor.url}`);
|
||||
lines.push(`• Type: ${message.monitor.type}`);
|
||||
lines.push(`• Status: ${message.monitor.status}`);
|
||||
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
lines.push("");
|
||||
lines.push("<b>Additional Information:</b>");
|
||||
message.content.details.forEach((detail) => lines.push(`• ${detail}`));
|
||||
}
|
||||
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
lines.push("");
|
||||
lines.push("<b>Threshold Breaches:</b>");
|
||||
message.content.thresholds.forEach((breach) => {
|
||||
lines.push(`• ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
|
||||
});
|
||||
}
|
||||
|
||||
if (message.content.incident) {
|
||||
lines.push("");
|
||||
lines.push(`<a href="${message.clientHost}/incidents/${message.monitor.id}">View Incident</a>`);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
const SERVICE_NAME = "TwilioProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got from "got";
|
||||
|
||||
export class TwilioProvider extends NotificationProvider {
|
||||
async sendTestAlert(notification: Partial<Notification>): Promise<boolean> {
|
||||
if (!notification.accountSid || !notification.accessToken || !notification.phone || !notification.twilioPhoneNumber) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await got.post(`https://api.twilio.com/2010-04-01/Accounts/${notification.accountSid}/Messages.json`, {
|
||||
form: {
|
||||
To: notification.phone,
|
||||
From: notification.twilioPhoneNumber,
|
||||
Body: getTestMessage(),
|
||||
},
|
||||
username: notification.accountSid,
|
||||
password: notification.accessToken,
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : "unknown error";
|
||||
const errStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.warn({
|
||||
message: "Twilio test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: errStack,
|
||||
details: { error: errMsg },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async sendMessage(notification: Notification, message: NotificationMessage): Promise<boolean> {
|
||||
if (!notification.accountSid || !notification.accessToken || !notification.phone || !notification.twilioPhoneNumber) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const text = this.buildSmsText(message);
|
||||
|
||||
try {
|
||||
await got.post(`https://api.twilio.com/2010-04-01/Accounts/${notification.accountSid}/Messages.json`, {
|
||||
form: {
|
||||
To: notification.phone,
|
||||
From: notification.twilioPhoneNumber,
|
||||
Body: text,
|
||||
},
|
||||
username: notification.accountSid,
|
||||
password: notification.accessToken,
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
|
||||
this.logger.info({
|
||||
message: "Twilio SMS notification sent",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const errMsg = error instanceof Error ? error.message : "unknown error";
|
||||
const errStack = error instanceof Error ? error.stack : undefined;
|
||||
this.logger.warn({
|
||||
message: "Twilio SMS alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: errStack,
|
||||
details: { error: errMsg },
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private buildSmsText(message: NotificationMessage): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
lines.push(message.content.title);
|
||||
lines.push(message.content.summary);
|
||||
lines.push("");
|
||||
lines.push(`URL: ${message.monitor.url}`);
|
||||
lines.push(`Status: ${message.monitor.status}`);
|
||||
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
message.content.thresholds.forEach((breach) => {
|
||||
lines.push(`${breach.metric.toUpperCase()}: ${breach.formattedValue}`);
|
||||
});
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { IEmailService } from "@/service/emailService.js";
|
||||
export const buildTestEmail = async (emailService: IEmailService) => {
|
||||
const context = { testName: "Monitoring System" };
|
||||
const html = await emailService.buildEmail("testEmailTemplate", context);
|
||||
return html;
|
||||
};
|
||||
|
||||
export const getTestMessage = () => {
|
||||
return "This is a test notification from Checkmate";
|
||||
};
|
||||
@@ -0,0 +1,119 @@
|
||||
const SERVICE_NAME = "WebhookProvider";
|
||||
import type { Notification } from "@/domain/notifications/notification.type.js";
|
||||
import { NotificationProvider } from "@/domain/notifications/providers/INotificationProvider.js";
|
||||
import type { NotificationMessage } from "@/domain/notifications/notification.type.js";
|
||||
import { getTestMessage } from "@/domain/notifications/providers/utils.js";
|
||||
import got from "got";
|
||||
|
||||
export class WebhookProvider extends NotificationProvider {
|
||||
sendMessage = async (notification: Notification, message: NotificationMessage): Promise<boolean> => {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Build webhook payload from unified message
|
||||
const payload = this.buildWebhookPayload(message);
|
||||
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: payload,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
this.logger.info({
|
||||
message: "Webhook notification sent",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "Webhook alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendMessage",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
private buildWebhookPayload(message: NotificationMessage): object {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Title and summary
|
||||
lines.push(`**${message.content.title}**`);
|
||||
lines.push(message.content.summary);
|
||||
lines.push("");
|
||||
|
||||
// Monitor information
|
||||
lines.push("**Monitor Details:**");
|
||||
lines.push(`- Name: ${message.monitor.name}`);
|
||||
lines.push(`- URL: ${message.monitor.url}`);
|
||||
lines.push(`- Type: ${message.monitor.type}`);
|
||||
lines.push(`- Status: ${message.monitor.status}`);
|
||||
lines.push("");
|
||||
|
||||
// Additional details
|
||||
if (message.content.details && message.content.details.length > 0) {
|
||||
lines.push("**Additional Information:**");
|
||||
message.content.details.forEach((detail) => lines.push(`- ${detail}`));
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
// Threshold breaches (for hardware monitors)
|
||||
if (message.content.thresholds && message.content.thresholds.length > 0) {
|
||||
lines.push("**Threshold Breaches:**");
|
||||
message.content.thresholds.forEach((breach) => {
|
||||
lines.push(`- ${breach.metric.toUpperCase()}: ${breach.formattedValue} (threshold: ${breach.threshold}${breach.unit})`);
|
||||
});
|
||||
lines.push("");
|
||||
}
|
||||
|
||||
// Incident link
|
||||
if (message.content.incident) {
|
||||
lines.push(`[View Incident](${message.clientHost}/infrastructure/${message.monitor.id})`);
|
||||
}
|
||||
|
||||
// Return webhook payload with both text and structured data
|
||||
return {
|
||||
text: lines.join("\n"),
|
||||
severity: message.severity,
|
||||
type: message.type,
|
||||
monitor: {
|
||||
id: message.monitor.id,
|
||||
name: message.monitor.name,
|
||||
url: message.monitor.url,
|
||||
status: message.monitor.status,
|
||||
},
|
||||
timestamp: message.content.timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
sendTestAlert = async (notification: Partial<Notification>) => {
|
||||
if (!notification.address) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
await got.post(notification.address, {
|
||||
json: { text: getTestMessage() },
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
...this.gotRequestOptions(),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
const err = error as Error;
|
||||
this.logger.warn({
|
||||
message: "Webhook test alert failed",
|
||||
service: SERVICE_NAME,
|
||||
method: "sendTestAlert",
|
||||
stack: err?.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Schema, model } from "mongoose";
|
||||
import { QueueModes } from "@/domain/app-settings/app-settings.type.js";
|
||||
import { QueueWorkerDocument } from "@/domain/queue-workers/queue-worker.type.js";
|
||||
|
||||
const QueueWorkerSchema = new Schema<QueueWorkerDocument>(
|
||||
{
|
||||
_id: { type: String, required: true },
|
||||
mode: { type: String, enum: QueueModes, required: true },
|
||||
lastSeenAt: { type: Date, default: Date.now, expires: 30 },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
const QueueWorkerModel = model<QueueWorkerDocument>("QueueWorker", QueueWorkerSchema);
|
||||
|
||||
export type { QueueWorkerDocument };
|
||||
export { QueueWorkerModel };
|
||||
export default QueueWorkerModel;
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { QueueMode } from "@/domain/app-settings/app-settings.type.js";
|
||||
import type { QueueWorker } from "@/domain/queue-workers/queue-worker.type.js";
|
||||
|
||||
export interface IQueueWorkersRepository {
|
||||
upsert(workerId: string, mode: QueueMode): Promise<void>;
|
||||
findRecent(maxAgeMs: number): Promise<QueueWorker[]>;
|
||||
deleteById(workerId: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { QueueMode } from "@/domain/app-settings/app-settings.type.js";
|
||||
import type { IQueueWorkersRepository } from "./queue-worker.repository.interface.js";
|
||||
import type { QueueWorker } from "@/domain/queue-workers/queue-worker.type.js";
|
||||
import { QueueWorkerModel, type QueueWorkerDocument } from "@/domain/queue-workers/queue-worker.model.js";
|
||||
const SERVICE_NAME = "MongoQueueWorkersRepository";
|
||||
|
||||
class MongoQueueWorkersRepository implements IQueueWorkersRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
protected toEntity = (doc: QueueWorkerDocument): QueueWorker => {
|
||||
return {
|
||||
workerId: doc._id,
|
||||
mode: doc.mode,
|
||||
lastSeenAt: doc.lastSeenAt.getTime(),
|
||||
};
|
||||
};
|
||||
|
||||
upsert = async (workerId: string, mode: QueueMode): Promise<void> => {
|
||||
await QueueWorkerModel.updateOne({ _id: workerId }, { $set: { mode, lastSeenAt: new Date() } }, { upsert: true });
|
||||
};
|
||||
|
||||
findRecent = async (maxAgeMs: number): Promise<QueueWorker[]> => {
|
||||
const cutoff = new Date(Date.now() - maxAgeMs);
|
||||
const docs = await QueueWorkerModel.find({ lastSeenAt: { $gte: cutoff } });
|
||||
return docs.map(this.toEntity);
|
||||
};
|
||||
|
||||
deleteById = async (workerId: string): Promise<void> => {
|
||||
await QueueWorkerModel.deleteOne({ _id: workerId });
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoQueueWorkersRepository;
|
||||
@@ -0,0 +1,18 @@
|
||||
import { type QueueMode } from "@/domain/app-settings/app-settings.type.js";
|
||||
|
||||
// Heartbeat presence record for a scheduler instance. _id is the scheduler's
|
||||
// workerId (hostname:pid:uuid). The TTL index on lastSeenAt garbage-collects
|
||||
// records for instances that have stopped heartbeating.
|
||||
export interface QueueWorkerDocument {
|
||||
_id: string;
|
||||
mode: QueueMode;
|
||||
lastSeenAt: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export type QueueWorker = {
|
||||
workerId: string; // hostname:pid:uuid
|
||||
mode: QueueMode;
|
||||
lastSeenAt: number; // epoch ms of the last heartbeat
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { RecoveryToken as RecoveryTokenEntity } from "@/domain/recovery-tokens/recovery-token.type.js";
|
||||
|
||||
type RecoveryTokenDocumentBase = Omit<RecoveryTokenEntity, "id" | "createdAt" | "updatedAt" | "expiry"> & {
|
||||
expiry: Date;
|
||||
};
|
||||
|
||||
interface RecoveryTokenDocument extends RecoveryTokenDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const RecoveryTokenSchema = new Schema<RecoveryTokenDocument>(
|
||||
{
|
||||
email: { type: String, required: true, unique: true },
|
||||
token: { type: String, required: true },
|
||||
expiry: { type: Date, default: Date.now, expires: 600 },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
const RecoveryTokenModel = model<RecoveryTokenDocument>("RecoveryToken", RecoveryTokenSchema);
|
||||
|
||||
export type { RecoveryTokenDocument };
|
||||
export { RecoveryTokenModel };
|
||||
export default RecoveryTokenModel;
|
||||
@@ -0,0 +1,12 @@
|
||||
import type { RecoveryToken } from "@/domain/recovery-tokens/recovery-token.type.js";
|
||||
|
||||
export interface IRecoveryTokensRepository {
|
||||
// create
|
||||
create(email: string): Promise<RecoveryToken>;
|
||||
// fetch
|
||||
findByToken(token: string): Promise<RecoveryToken>;
|
||||
// update
|
||||
// delete
|
||||
deleteManyByEmail(email: string): Promise<number>;
|
||||
// other
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import type { RecoveryToken } from "@/domain/recovery-tokens/recovery-token.type.js";
|
||||
import type { IRecoveryTokensRepository } from "./recovery-token.repository.interface.js";
|
||||
import type { RecoveryTokenDocument } from "@/domain/recovery-tokens/recovery-token.model.js";
|
||||
import { RecoveryTokenModel } from "@/domain/recovery-tokens/recovery-token.model.js";
|
||||
import mongoose from "mongoose";
|
||||
import crypto from "crypto";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
const SERVICE_NAME = "MongoRecoveryTokensRepository";
|
||||
|
||||
class MongoRecoveryTokensRepository implements IRecoveryTokensRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
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: RecoveryTokenDocument): RecoveryToken => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
email: doc.email,
|
||||
token: doc.token,
|
||||
expiry: this.toDateString(doc.expiry),
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (email: string): Promise<RecoveryToken> => {
|
||||
const token = await RecoveryTokenModel.create({
|
||||
email,
|
||||
token: crypto.randomBytes(32).toString("hex"),
|
||||
});
|
||||
return this.toEntity(token);
|
||||
};
|
||||
|
||||
findByToken = async (token: string): Promise<RecoveryToken> => {
|
||||
const recoveryToken = await RecoveryTokenModel.findOne({ token });
|
||||
if (!recoveryToken) {
|
||||
throw new AppError({ message: "Recovery token not found", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(recoveryToken);
|
||||
};
|
||||
|
||||
deleteManyByEmail = async (email: string) => {
|
||||
const result = await RecoveryTokenModel.deleteMany({
|
||||
email,
|
||||
});
|
||||
return Promise.resolve(result.deletedCount || 0);
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoRecoveryTokensRepository;
|
||||
@@ -0,0 +1,8 @@
|
||||
export interface RecoveryToken {
|
||||
id: string;
|
||||
email: string;
|
||||
token: string;
|
||||
expiry: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { StatusPage } from "@/domain/status-pages/status-page.type.js";
|
||||
|
||||
export interface IStatusPagesRepository {
|
||||
// create
|
||||
create(userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
|
||||
// single fetch
|
||||
findByUrl(url: string): Promise<StatusPage>;
|
||||
findByTeamId(teamId: string): Promise<StatusPage[]>;
|
||||
// collection fetch
|
||||
// update
|
||||
updateById(id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
|
||||
// delete
|
||||
deleteById(id: string, teamId: string): Promise<StatusPage>;
|
||||
// other
|
||||
removeMonitorFromStatusPages(monitorId: string): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js";
|
||||
import { type StatusPageDocument, StatusPageModel } from "@/domain/status-pages/status-page.model.js";
|
||||
import type { StatusPage, StatusPageLogo, StatusPageLogoDocument } from "@/domain/status-pages/status-page.type.js";
|
||||
import mongoose from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
// Type for update data that can include document-level fields (Buffer for logo)
|
||||
type StatusPageUpdateData = Partial<Omit<StatusPage, "id" | "userId" | "teamId" | "logo" | "createdAt" | "updatedAt">> & {
|
||||
logo?: StatusPageLogoDocument | null;
|
||||
};
|
||||
class MongoStatusPagesRepository implements IStatusPagesRepository {
|
||||
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();
|
||||
};
|
||||
|
||||
private mapIdArray = (values?: Array<mongoose.Types.ObjectId | string>): string[] => {
|
||||
return values?.map((value) => this.toStringId(value)) ?? [];
|
||||
};
|
||||
|
||||
private mapLogo = (logo?: StatusPageLogoDocument | null): StatusPageLogo | undefined => {
|
||||
if (!logo) {
|
||||
return undefined;
|
||||
}
|
||||
// Convert Buffer to base64 string for JSON serialization
|
||||
const base64Data = Buffer.isBuffer(logo.data) ? logo.data.toString("base64") : logo.data;
|
||||
return {
|
||||
data: base64Data,
|
||||
contentType: logo.contentType,
|
||||
};
|
||||
};
|
||||
|
||||
private toEntity = (doc: StatusPageDocument): StatusPage => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
userId: this.toStringId(doc.userId),
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
type: doc.type,
|
||||
companyName: doc.companyName,
|
||||
url: doc.url,
|
||||
timezone: doc.timezone ?? undefined,
|
||||
color: doc.color,
|
||||
monitors: this.mapIdArray(doc.monitors),
|
||||
subMonitors: this.mapIdArray(doc.subMonitors),
|
||||
originalMonitors: this.mapIdArray(doc.originalMonitors),
|
||||
logo: this.mapLogo(doc.logo),
|
||||
isPublished: doc.isPublished,
|
||||
showCharts: doc.showCharts,
|
||||
showUptimePercentage: doc.showUptimePercentage,
|
||||
showAdminLoginLink: doc.showAdminLoginLink,
|
||||
showInfrastructure: doc.showInfrastructure,
|
||||
customCSS: doc.customCSS,
|
||||
theme: doc.theme,
|
||||
themeMode: doc.themeMode,
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: StatusPageDocument[]): StatusPage[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
create = async (userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => {
|
||||
const { logo, ...restData } = data;
|
||||
void logo;
|
||||
const statusPage = new StatusPageModel({
|
||||
...restData,
|
||||
userId,
|
||||
teamId,
|
||||
});
|
||||
if (image) {
|
||||
statusPage.logo = {
|
||||
data: image.buffer as Buffer,
|
||||
contentType: image.mimetype,
|
||||
};
|
||||
}
|
||||
await statusPage.save();
|
||||
return this.toEntity(statusPage);
|
||||
};
|
||||
|
||||
findByUrl = async (url: string): Promise<StatusPage> => {
|
||||
const statusPage = await StatusPageModel.findOne({
|
||||
url,
|
||||
});
|
||||
if (!statusPage) {
|
||||
throw new AppError({ message: "Status page not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(statusPage);
|
||||
// Get status page
|
||||
};
|
||||
|
||||
findByTeamId = async (teamId: string): Promise<StatusPage[]> => {
|
||||
const statusPages = await StatusPageModel.find({ teamId });
|
||||
return this.mapDocuments(statusPages);
|
||||
};
|
||||
|
||||
updateById = async (
|
||||
id: string,
|
||||
teamId: string,
|
||||
image: Express.Multer.File | undefined,
|
||||
patch: Partial<StatusPage> & { removeLogo?: string }
|
||||
): Promise<StatusPage> => {
|
||||
const { logo, removeLogo, ...restPatch } = patch;
|
||||
void logo;
|
||||
const updateData: StatusPageUpdateData = { ...restPatch };
|
||||
if (image) {
|
||||
updateData.logo = {
|
||||
data: image.buffer as Buffer,
|
||||
contentType: image.mimetype,
|
||||
};
|
||||
} else if (removeLogo === "true") {
|
||||
updateData.logo = null;
|
||||
}
|
||||
|
||||
const statusPage = await StatusPageModel.findOneAndUpdate({ teamId, _id: id }, updateData, {
|
||||
new: true,
|
||||
});
|
||||
|
||||
if (!statusPage) {
|
||||
throw new AppError({ message: "Status page not found", status: 404 });
|
||||
}
|
||||
|
||||
return this.toEntity(statusPage);
|
||||
};
|
||||
|
||||
deleteById = async (id: string, teamId: string): Promise<StatusPage> => {
|
||||
const statusPage = await StatusPageModel.findOneAndDelete({ _id: id, teamId });
|
||||
if (!statusPage) {
|
||||
throw new AppError({ message: "Status page not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(statusPage);
|
||||
};
|
||||
|
||||
removeMonitorFromStatusPages = async (monitorId: string): Promise<number> => {
|
||||
const res = await StatusPageModel.updateMany({ monitors: monitorId }, { $pull: { monitors: monitorId } });
|
||||
return res.modifiedCount;
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoStatusPagesRepository;
|
||||
@@ -0,0 +1,135 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { StatusPage, StatusPageLogoDocument } from "@/domain/status-pages/status-page.type.js";
|
||||
import {
|
||||
DEFAULT_STATUS_PAGE_THEME,
|
||||
DEFAULT_STATUS_PAGE_THEME_MODE,
|
||||
StatusPageThemeModes,
|
||||
StatusPageThemes,
|
||||
StatusPageTypes,
|
||||
} from "@/domain/status-pages/status-page.type.js";
|
||||
|
||||
type StatusPageDocumentBase = Omit<
|
||||
StatusPage,
|
||||
"id" | "userId" | "teamId" | "monitors" | "subMonitors" | "originalMonitors" | "logo" | "createdAt" | "updatedAt"
|
||||
> & {
|
||||
monitors: Types.ObjectId[];
|
||||
subMonitors: Types.ObjectId[];
|
||||
originalMonitors?: Types.ObjectId[];
|
||||
logo?: StatusPageLogoDocument | null;
|
||||
};
|
||||
|
||||
interface StatusPageDocument extends StatusPageDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
userId: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const logoSchema = new Schema<StatusPageLogoDocument>(
|
||||
{
|
||||
data: { type: Buffer },
|
||||
contentType: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const StatusPageSchema = new Schema<StatusPageDocument>(
|
||||
{
|
||||
userId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "User",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
type: {
|
||||
type: [String],
|
||||
required: true,
|
||||
default: ["uptime"],
|
||||
enum: StatusPageTypes,
|
||||
},
|
||||
companyName: {
|
||||
type: String,
|
||||
required: true,
|
||||
default: "",
|
||||
},
|
||||
url: {
|
||||
type: String,
|
||||
unique: true,
|
||||
required: true,
|
||||
default: "",
|
||||
},
|
||||
timezone: {
|
||||
type: String,
|
||||
},
|
||||
color: {
|
||||
type: String,
|
||||
default: "#4169E1",
|
||||
},
|
||||
monitors: [
|
||||
{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Monitor",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
subMonitors: [
|
||||
{
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Monitor",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
logo: {
|
||||
type: logoSchema,
|
||||
default: null,
|
||||
},
|
||||
isPublished: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
showCharts: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
showUptimePercentage: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
showAdminLoginLink: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
showInfrastructure: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
customCSS: {
|
||||
type: String,
|
||||
default: "",
|
||||
},
|
||||
theme: {
|
||||
type: String,
|
||||
enum: StatusPageThemes,
|
||||
default: DEFAULT_STATUS_PAGE_THEME,
|
||||
},
|
||||
themeMode: {
|
||||
type: String,
|
||||
enum: StatusPageThemeModes,
|
||||
default: DEFAULT_STATUS_PAGE_THEME_MODE,
|
||||
},
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
const StatusPageModel = model<StatusPageDocument>("StatusPage", StatusPageSchema);
|
||||
|
||||
export type { StatusPageDocument };
|
||||
export { StatusPageModel };
|
||||
export default StatusPageModel;
|
||||
@@ -0,0 +1,67 @@
|
||||
import { type IStatusPagesRepository } from "@/domain/status-pages/status-page-repository.interface.js";
|
||||
import { ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import { DEFAULT_STATUS_PAGE_THEME, DEFAULT_STATUS_PAGE_THEME_MODE, StatusPage } from "@/domain/status-pages/status-page.type.js";
|
||||
|
||||
export interface IStatusPageService {
|
||||
createStatusPage(userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
|
||||
getStatusPageByUrl(url: string): Promise<StatusPage>;
|
||||
getStatusPagesByTeamId(teamId: string): Promise<StatusPage[]>;
|
||||
updateStatusPage(id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage>;
|
||||
|
||||
deleteStatusPage(statusPageId: string, teamId: string): Promise<StatusPage>;
|
||||
}
|
||||
|
||||
export class StatusPageService implements IStatusPageService {
|
||||
private statusPagesRepository: IStatusPagesRepository;
|
||||
private settingsService: ISettingsService;
|
||||
constructor(statusPagesRepository: IStatusPagesRepository, settingsService: ISettingsService) {
|
||||
this.statusPagesRepository = statusPagesRepository;
|
||||
this.settingsService = settingsService;
|
||||
}
|
||||
|
||||
private withoutThemeFields = (data: Partial<StatusPage>): Partial<StatusPage> => {
|
||||
const { theme: _theme, themeMode: _themeMode, ...rest } = data;
|
||||
return rest;
|
||||
};
|
||||
|
||||
private applyDefaultTheme = (statusPage: StatusPage): StatusPage => ({
|
||||
...statusPage,
|
||||
theme: DEFAULT_STATUS_PAGE_THEME,
|
||||
themeMode: DEFAULT_STATUS_PAGE_THEME_MODE,
|
||||
});
|
||||
|
||||
private normalizeTheme = (statusPage: StatusPage): StatusPage =>
|
||||
this.settingsService.areStatusPageThemesEnabled() ? statusPage : this.applyDefaultTheme(statusPage);
|
||||
|
||||
private normalizeInput = (data: Partial<StatusPage>): Partial<StatusPage> =>
|
||||
this.settingsService.areStatusPageThemesEnabled() ? data : this.withoutThemeFields(data);
|
||||
|
||||
createStatusPage = async (
|
||||
userId: string,
|
||||
teamId: string,
|
||||
image: Express.Multer.File | undefined,
|
||||
data: Partial<StatusPage>
|
||||
): Promise<StatusPage> => {
|
||||
const created = await this.statusPagesRepository.create(userId, teamId, image, this.normalizeInput(data));
|
||||
return this.normalizeTheme(created);
|
||||
};
|
||||
|
||||
getStatusPageByUrl = async (url: string): Promise<StatusPage> => {
|
||||
const statusPage = await this.statusPagesRepository.findByUrl(url);
|
||||
return this.normalizeTheme(statusPage);
|
||||
};
|
||||
|
||||
getStatusPagesByTeamId = async (teamId: string): Promise<StatusPage[]> => {
|
||||
const statusPages = await this.statusPagesRepository.findByTeamId(teamId);
|
||||
return statusPages.map((sp) => this.normalizeTheme(sp));
|
||||
};
|
||||
|
||||
updateStatusPage = async (id: string, teamId: string, image: Express.Multer.File | undefined, data: Partial<StatusPage>): Promise<StatusPage> => {
|
||||
const updated = await this.statusPagesRepository.updateById(id, teamId, image, this.normalizeInput(data));
|
||||
return this.normalizeTheme(updated);
|
||||
};
|
||||
|
||||
deleteStatusPage = async (statusPageId: string, teamId: string): Promise<StatusPage> => {
|
||||
return await this.statusPagesRepository.deleteById(statusPageId, teamId);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
export const StatusPageTypes = ["uptime", "infrastructure"] as const;
|
||||
export type StatusPageType = (typeof StatusPageTypes)[number];
|
||||
|
||||
export const StatusPageThemes = ["refined", "modern", "bold", "editorial"] as const;
|
||||
export type StatusPageTheme = (typeof StatusPageThemes)[number];
|
||||
export const DEFAULT_STATUS_PAGE_THEME: StatusPageTheme = "refined";
|
||||
|
||||
export const StatusPageThemeModes = ["auto", "light", "dark"] as const;
|
||||
export type StatusPageThemeMode = (typeof StatusPageThemeModes)[number];
|
||||
export const DEFAULT_STATUS_PAGE_THEME_MODE: StatusPageThemeMode = "auto";
|
||||
|
||||
export interface StatusPageLogo {
|
||||
data: string;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
export interface StatusPageLogoDocument {
|
||||
data: Buffer;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
export interface StatusPage {
|
||||
id: string;
|
||||
userId: string;
|
||||
teamId: string;
|
||||
type: StatusPageType[];
|
||||
companyName: string;
|
||||
url: string;
|
||||
timezone?: string;
|
||||
color: string;
|
||||
monitors: string[];
|
||||
subMonitors: string[];
|
||||
originalMonitors?: string[];
|
||||
logo?: StatusPageLogo | null;
|
||||
isPublished: boolean;
|
||||
showCharts: boolean;
|
||||
showUptimePercentage: boolean;
|
||||
showAdminLoginLink: boolean;
|
||||
showInfrastructure: boolean;
|
||||
customCSS: string;
|
||||
theme: StatusPageTheme;
|
||||
themeMode: StatusPageThemeMode;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import type { Tag as TagEntity } from "@/domain/tags/tag.type.js";
|
||||
|
||||
type TagDocumentBase = Omit<TagEntity, "id" | "teamId" | "createdAt" | "updatedAt">;
|
||||
|
||||
interface TagDocument extends TagDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
teamId: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const TagSchema = new Schema<TagDocument>(
|
||||
{
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
required: true,
|
||||
},
|
||||
name: { type: String, required: true },
|
||||
color: { type: String, required: true, default: "#13715B" },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
TagSchema.index({ teamId: 1, name: 1 }, { unique: true });
|
||||
|
||||
const TagModel = model<TagDocument>("Tag", TagSchema);
|
||||
|
||||
export type { TagDocument };
|
||||
export { TagModel };
|
||||
export default TagModel;
|
||||
@@ -0,0 +1,13 @@
|
||||
import { Tag } from "@/domain/tags/tag.type.js";
|
||||
|
||||
export interface ITagsRepository {
|
||||
// create
|
||||
create(tagData: Partial<Tag>): Promise<Tag>;
|
||||
// read
|
||||
findById(tagId: string, teamId: string): Promise<Tag>;
|
||||
findByTeamId(teamId: string): Promise<Tag[]>;
|
||||
// update
|
||||
updateById(tagId: string, teamId: string, patch: Partial<Tag>): Promise<Tag>;
|
||||
// delete
|
||||
deleteById(tagId: string, teamId: string): Promise<Tag>;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import { ITagsRepository } from "@/domain/tags/tag.repository.interface.js";
|
||||
import { Tag } from "@/domain/tags/tag.type.js";
|
||||
import { TagDocument, TagModel } from "@/domain/tags/tag.model.js";
|
||||
import mongoose from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
const SERVICE_NAME = "TagsRepository";
|
||||
|
||||
class MongoTagsRepository implements ITagsRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
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: TagDocument): Tag => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
name: doc.name,
|
||||
color: doc.color,
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
async create(tagData: Partial<Tag>): Promise<Tag> {
|
||||
try {
|
||||
const tag = await TagModel.create({ ...tagData });
|
||||
return this.toEntity(tag);
|
||||
} catch (error) {
|
||||
if (error && typeof error === "object" && (error as { code?: number }).code === 11000) {
|
||||
throw new AppError({ message: `A tag named "${tagData.name}" already exists`, service: SERVICE_NAME, status: 409 });
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async findById(tagId: string, teamId: string): Promise<Tag> {
|
||||
const tag = await TagModel.findOne({ _id: tagId, teamId });
|
||||
if (!tag) {
|
||||
throw new AppError({ message: "Tag not found", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(tag);
|
||||
}
|
||||
|
||||
async findByTeamId(teamId: string): Promise<Tag[]> {
|
||||
const tags = await TagModel.find({ teamId });
|
||||
return tags.map(this.toEntity);
|
||||
}
|
||||
|
||||
async updateById(tagId: string, teamId: string, patch: Partial<Tag>): Promise<Tag> {
|
||||
const updatedTag = await TagModel.findOneAndUpdate(
|
||||
{ _id: tagId, teamId },
|
||||
{
|
||||
$set: {
|
||||
...patch,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updatedTag) {
|
||||
throw new AppError({ message: "Tag not found or could not be updated", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(updatedTag);
|
||||
}
|
||||
|
||||
async deleteById(tagId: string, teamId: string): Promise<Tag> {
|
||||
const deletedTag = await TagModel.findOneAndDelete({ _id: tagId, teamId });
|
||||
if (!deletedTag) {
|
||||
throw new AppError({ message: "Tag not found or could not be deleted", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(deletedTag);
|
||||
}
|
||||
}
|
||||
|
||||
export default MongoTagsRepository;
|
||||
@@ -0,0 +1,38 @@
|
||||
import { Tag } from "@/domain/tags/tag.type.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import { ITagsRepository } from "@/domain/tags/tag.repository.interface.js";
|
||||
export interface ITagsService {
|
||||
createTag(tag: Partial<Tag>, teamId: string): Promise<Tag>;
|
||||
getTag(tagId: string, teamId: string): Promise<Tag>;
|
||||
getTagsByTeamId(teamId: string): Promise<Tag[]>;
|
||||
updateTag(tagId: string, teamId: string, patch: Partial<Tag>): Promise<Tag>;
|
||||
deleteTag(tagId: string, teamId: string): Promise<Tag>;
|
||||
}
|
||||
|
||||
export class TagsService implements ITagsService {
|
||||
constructor(
|
||||
private tagsRepository: ITagsRepository,
|
||||
private monitorsRepository: IMonitorsRepository
|
||||
) {}
|
||||
|
||||
createTag = async (tagData: Partial<Tag>, teamId: string): Promise<Tag> => {
|
||||
tagData.teamId = teamId;
|
||||
return await this.tagsRepository.create(tagData);
|
||||
};
|
||||
|
||||
getTag = async (tagId: string, teamId: string): Promise<Tag> => {
|
||||
return await this.tagsRepository.findById(tagId, teamId);
|
||||
};
|
||||
|
||||
getTagsByTeamId = async (teamId: string): Promise<Tag[]> => {
|
||||
return await this.tagsRepository.findByTeamId(teamId);
|
||||
};
|
||||
|
||||
updateTag = async (tagId: string, teamId: string, patch: Partial<Tag>): Promise<Tag> => {
|
||||
return await this.tagsRepository.updateById(tagId, teamId, patch);
|
||||
};
|
||||
deleteTag = async (tagId: string, teamId: string): Promise<Tag> => {
|
||||
await this.monitorsRepository.removeTagFromMonitors(tagId);
|
||||
return await this.tagsRepository.deleteById(tagId, teamId);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export interface Tag {
|
||||
id: string;
|
||||
teamId: string;
|
||||
name: string;
|
||||
color: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
|
||||
import type { Team } from "@/domain/teams/team.type.js";
|
||||
|
||||
type TeamDocumentBase = Omit<Team, "id" | "createdAt" | "updatedAt"> & {};
|
||||
interface TeamDocument extends TeamDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const TeamSchema = new Schema<TeamDocument>(
|
||||
{
|
||||
email: {
|
||||
type: String,
|
||||
required: true,
|
||||
unique: true,
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
const TeamModel = model<TeamDocument>("Team", TeamSchema);
|
||||
|
||||
export type { TeamDocument };
|
||||
export { TeamModel };
|
||||
export default TeamModel;
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { Team } from "@/domain/teams/team.type.js";
|
||||
export interface ITeamsRepository {
|
||||
// create
|
||||
create(email: string): Promise<Team>;
|
||||
// fetch
|
||||
// update
|
||||
// delete
|
||||
// other
|
||||
findAllTeamIds(): Promise<string[]>;
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Team } from "@/domain/teams/team.type.js";
|
||||
import { TeamDocument, TeamModel } from "@/domain/teams/team.model.js";
|
||||
import { ITeamsRepository } from "@/domain/teams/team.repository.interface.js";
|
||||
import mongoose from "mongoose";
|
||||
|
||||
class MongoTeamsRepository implements ITeamsRepository {
|
||||
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();
|
||||
};
|
||||
|
||||
private toEntity = (doc: TeamDocument): Team => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
email: doc.email,
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (email: string) => {
|
||||
const team = await TeamModel.create({ email });
|
||||
return this.toEntity(team);
|
||||
};
|
||||
|
||||
findAllTeamIds = async (): Promise<string[]> => {
|
||||
const teams = await TeamModel.find({}, { _id: 1 }).lean();
|
||||
return teams.map((team) => this.toStringId(team._id));
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoTeamsRepository;
|
||||
@@ -0,0 +1,6 @@
|
||||
export interface Team {
|
||||
id: string;
|
||||
email: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import bcrypt from "bcryptjs";
|
||||
import type { User, UserProfileImage, UserRole } from "@/domain/users/user.type.js";
|
||||
import { MonitorModel } from "@/domain/monitors/monitor.model.js";
|
||||
import Team from "../teams/team.model.js";
|
||||
import NotificationModel from "../notifications/notification.model.js";
|
||||
|
||||
type UserDocumentBase = Omit<User, "id" | "teamId" | "createdAt" | "updatedAt"> & {
|
||||
teamId?: Types.ObjectId;
|
||||
profileImage?: Required<UserProfileImage>;
|
||||
};
|
||||
|
||||
interface UserDocument extends UserDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
teamId?: Types.ObjectId;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
const profileImageSchema = new Schema<Required<UserProfileImage>>(
|
||||
{
|
||||
data: { type: Buffer },
|
||||
contentType: { type: String },
|
||||
},
|
||||
{ _id: false }
|
||||
);
|
||||
|
||||
const UserSchema = new Schema<UserDocument>(
|
||||
{
|
||||
firstName: { type: String, required: true },
|
||||
lastName: { type: String, required: true },
|
||||
email: { type: String, required: true, unique: true },
|
||||
password: { type: String, required: true },
|
||||
avatarImage: { type: String },
|
||||
profileImage: { type: profileImageSchema },
|
||||
isActive: { type: Boolean, default: true },
|
||||
isVerified: { type: Boolean, default: false },
|
||||
role: {
|
||||
type: [String],
|
||||
enum: ["user", "admin", "superadmin", "demo" satisfies UserRole],
|
||||
default: ["user"],
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
},
|
||||
checkTTL: { type: Number },
|
||||
},
|
||||
{ timestamps: true }
|
||||
);
|
||||
|
||||
UserSchema.pre("findOneAndDelete", async function (next) {
|
||||
try {
|
||||
const userToDelete = await this.model.findOne(this.getFilter());
|
||||
if (!userToDelete) return next();
|
||||
if (userToDelete.role.includes("superadmin")) {
|
||||
await Team.deleteOne({ _id: userToDelete.teamId });
|
||||
await MonitorModel.deleteMany({ userId: userToDelete._id });
|
||||
await this.model.deleteMany({ teamId: userToDelete.teamId, _id: { $ne: userToDelete._id } });
|
||||
await NotificationModel.deleteMany({ teamId: userToDelete.teamId });
|
||||
}
|
||||
next();
|
||||
} catch (error) {
|
||||
next(error as Error);
|
||||
}
|
||||
});
|
||||
|
||||
UserSchema.methods.comparePassword = async function (submittedPassword: string) {
|
||||
return bcrypt.compare(submittedPassword, this.password);
|
||||
};
|
||||
|
||||
const UserModel = model<UserDocument>("User", UserSchema);
|
||||
|
||||
export type { UserDocument };
|
||||
export { UserModel };
|
||||
export default UserModel;
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { User } from "@/domain/users/user.type.js";
|
||||
export interface IUsersRepository {
|
||||
// create
|
||||
create(user: Partial<User>, imageFile?: Express.Multer.File | null): Promise<User>;
|
||||
// fetch
|
||||
findByEmail(email: string): Promise<User>;
|
||||
findById(id: string): Promise<User>;
|
||||
findAll(): Promise<User[]>;
|
||||
// update
|
||||
updateById(id: string, patch: Partial<User>, file?: Express.Multer.File | null): Promise<User>;
|
||||
// delete
|
||||
deleteById(id: string): Promise<User>;
|
||||
// other
|
||||
findSuperAdmin(): Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import mongoose from "mongoose";
|
||||
import { IUsersRepository } from "@/domain/users/user.repository.interface.js";
|
||||
import { UserModel, type UserDocument } from "@/domain/users/user.model.js";
|
||||
import type { User, UserProfileImage } from "@/domain/users/user.type.js";
|
||||
import { GenerateAvatarImage } from "@/utils/imageProcessing.js";
|
||||
import { ParseBoolean } from "@/utils/utils.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
const SERVICE_NAME = "MongoUsersRepository";
|
||||
|
||||
class MongoUsersRepository implements IUsersRepository {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
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();
|
||||
};
|
||||
|
||||
private mapProfileImage = (image?: (UserProfileImage & { data?: Buffer }) | null) => {
|
||||
if (!image) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
data: image.data,
|
||||
contentType: image.contentType,
|
||||
};
|
||||
};
|
||||
|
||||
protected toEntity = (doc: UserDocument): User => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
firstName: doc.firstName,
|
||||
lastName: doc.lastName,
|
||||
email: doc.email,
|
||||
password: doc.password,
|
||||
avatarImage: doc.avatarImage ?? undefined,
|
||||
profileImage: this.mapProfileImage(doc.profileImage),
|
||||
isActive: doc.isActive ?? false,
|
||||
isVerified: doc.isVerified ?? false,
|
||||
role: doc.role ?? [],
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
checkTTL: doc.checkTTL ?? undefined,
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (user: Partial<User>, imageFile: Express.Multer.File | null) => {
|
||||
if (imageFile) {
|
||||
// 1. Save the full size image
|
||||
user.profileImage = {
|
||||
data: imageFile.buffer,
|
||||
contentType: imageFile.mimetype,
|
||||
};
|
||||
|
||||
// 2. Get the avatar sized image
|
||||
const avatar = await GenerateAvatarImage(imageFile);
|
||||
user.avatarImage = avatar;
|
||||
}
|
||||
|
||||
const newUser = new UserModel(user);
|
||||
await newUser.save();
|
||||
const sanitizedUser = await UserModel.findOne({ _id: newUser._id }).select("-password").select("-profileImage");
|
||||
if (!sanitizedUser) {
|
||||
throw new AppError({ message: "Failed to create user", service: SERVICE_NAME, status: 500 });
|
||||
}
|
||||
return this.toEntity(sanitizedUser);
|
||||
};
|
||||
|
||||
findByEmail = async (email: string) => {
|
||||
const user = await UserModel.findOne({ email: email }).select("-profileImage");
|
||||
if (!user) {
|
||||
throw new AppError({ message: "User not found", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(user);
|
||||
};
|
||||
|
||||
findById = async (id: string) => {
|
||||
const user = await UserModel.findById(id).select("-password").select("-profileImage");
|
||||
if (!user) {
|
||||
throw new Error("User not found");
|
||||
}
|
||||
|
||||
return this.toEntity(user);
|
||||
};
|
||||
|
||||
findAll = async () => {
|
||||
const users = await UserModel.find().select("-password").select("-profileImage");
|
||||
return this.mapDocuments(users);
|
||||
};
|
||||
|
||||
updateById = async (id: string, patch: Partial<User & { deleteProfileImage?: boolean }>, file?: Express.Multer.File | null): Promise<User> => {
|
||||
const candidateUser = { ...patch };
|
||||
let unsetFields: Record<string, 1> | undefined;
|
||||
|
||||
if (ParseBoolean(candidateUser.deleteProfileImage) === true) {
|
||||
unsetFields = { profileImage: 1, avatarImage: 1 };
|
||||
delete candidateUser.deleteProfileImage;
|
||||
} else if (file) {
|
||||
// 1. Save the full size image
|
||||
candidateUser.profileImage = {
|
||||
data: file.buffer,
|
||||
contentType: file.mimetype,
|
||||
};
|
||||
|
||||
// 2. Get the avatar sized image
|
||||
const avatar = await GenerateAvatarImage(file);
|
||||
candidateUser.avatarImage = avatar;
|
||||
}
|
||||
|
||||
delete candidateUser.deleteProfileImage;
|
||||
|
||||
const updateQuery: Record<string, unknown> = { $set: candidateUser };
|
||||
if (unsetFields) {
|
||||
updateQuery.$unset = unsetFields;
|
||||
}
|
||||
|
||||
const updatedUser = await UserModel.findOneAndUpdate({ _id: id }, updateQuery, { new: true }).select("-password").select("-profileImage");
|
||||
if (!updatedUser) {
|
||||
throw new AppError({ message: "User not found", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(updatedUser);
|
||||
};
|
||||
|
||||
deleteById = async (id: string) => {
|
||||
const deletedUser = await UserModel.findByIdAndDelete(id);
|
||||
if (!deletedUser) {
|
||||
throw new AppError({ message: "User not found", service: SERVICE_NAME, status: 404 });
|
||||
}
|
||||
return this.toEntity(deletedUser);
|
||||
};
|
||||
|
||||
findSuperAdmin = async () => {
|
||||
const superAdmin = await UserModel.findOne({ role: "superadmin" });
|
||||
if (superAdmin !== null) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: UserDocument[]): User[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoUsersRepository;
|
||||
@@ -0,0 +1,409 @@
|
||||
import { ISettingsRepository } from "@/domain/app-settings/app-settings-repository.interface.js";
|
||||
import { IInvitesRepository } from "@/domain/invites/invite.repository.interface.js";
|
||||
import { IRecoveryTokensRepository } from "@/domain/recovery-tokens/recovery-token.repository.interface.js";
|
||||
import { ITeamsRepository } from "@/domain/teams/team.repository.interface.js";
|
||||
import { IUsersRepository } from "@/domain/users/user.repository.interface.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { User } from "@/domain/users/user.type.js";
|
||||
import { canManageRole, type UserRole } from "@/domain/users/user.type.js";
|
||||
import bcrypt from "bcryptjs";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { IJobQueue } from "@/service/job-queues/job-queue.interface.js";
|
||||
import { IEmailService } from "@/service/emailService.js";
|
||||
import { EnvConfig, ISettingsService } from "@/domain/app-settings/app-settings.service.js";
|
||||
import { ILogger } from "@/utils/logger.js";
|
||||
import jwt from "jsonwebtoken";
|
||||
import crypto from "crypto";
|
||||
type CryptoType = typeof crypto;
|
||||
type JwtType = typeof jwt;
|
||||
const SERVICE_NAME = "userService";
|
||||
|
||||
export interface IUserService {
|
||||
issueToken(payload: Partial<User>, appSettings: EnvConfig): string;
|
||||
registerUser(user: Partial<User>, inviteToken: string, file: Express.Multer.File | null): Promise<{ user: User; token: string }>;
|
||||
createUser(userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: Express.Multer.File | null): Promise<User>;
|
||||
loginUser(email: string, password: string): Promise<{ user: User; token: string }>;
|
||||
editUser(
|
||||
updates: Partial<User & { newPassword?: string }>,
|
||||
file: Express.Multer.File | null,
|
||||
currentUserId: string,
|
||||
currentUserEmail: string
|
||||
): Promise<User>;
|
||||
checkSuperadminExists(): Promise<boolean>;
|
||||
requestRecovery(email: string): Promise<string | false | undefined>;
|
||||
validateRecovery(recoveryToken: string): Promise<void>;
|
||||
resetPassword(password: string, recoveryToken: string): Promise<{ user: User; token: string }>;
|
||||
deleteUser(params: { userId: string; teamId: string; roles: UserRole[] }): Promise<void>;
|
||||
deleteUserById(params: { actorId: string; actorTeamId: string; actorRoles: UserRole[]; targetUserId: string }): Promise<void>;
|
||||
getAllUsers(): Promise<User[]>;
|
||||
getUserById(roles: UserRole[], userId: string): Promise<User>;
|
||||
editUserById(userId: string, patch: Partial<User>): Promise<void>;
|
||||
setPasswordByUserId(userId: string, password: string): Promise<User>;
|
||||
}
|
||||
|
||||
export class UserService implements IUserService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
private hashPassword = (password: string): string => {
|
||||
const salt = bcrypt.genSaltSync(10);
|
||||
return bcrypt.hashSync(password, salt);
|
||||
};
|
||||
|
||||
private emailService: IEmailService;
|
||||
private settingsService: ISettingsService;
|
||||
private logger: ILogger;
|
||||
private jwt: JwtType;
|
||||
private jobQueue: IJobQueue;
|
||||
private crypto: CryptoType;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private usersRepository: IUsersRepository;
|
||||
private invitesRepository: IInvitesRepository;
|
||||
private recoveryTokensRepository: IRecoveryTokensRepository;
|
||||
private settingsRepository: ISettingsRepository;
|
||||
private teamsRepository: ITeamsRepository;
|
||||
|
||||
constructor({
|
||||
crypto,
|
||||
emailService,
|
||||
settingsService,
|
||||
logger,
|
||||
jwt,
|
||||
jobQueue,
|
||||
monitorsRepository,
|
||||
usersRepository,
|
||||
invitesRepository,
|
||||
recoveryTokensRepository,
|
||||
settingsRepository,
|
||||
teamsRepository,
|
||||
}: {
|
||||
crypto: CryptoType;
|
||||
emailService: IEmailService;
|
||||
settingsService: ISettingsService;
|
||||
logger: ILogger;
|
||||
jwt: JwtType;
|
||||
jobQueue: IJobQueue;
|
||||
monitorsRepository: IMonitorsRepository;
|
||||
usersRepository: IUsersRepository;
|
||||
invitesRepository: IInvitesRepository;
|
||||
recoveryTokensRepository: IRecoveryTokensRepository;
|
||||
settingsRepository: ISettingsRepository;
|
||||
teamsRepository: ITeamsRepository;
|
||||
}) {
|
||||
this.emailService = emailService;
|
||||
this.settingsService = settingsService;
|
||||
this.logger = logger;
|
||||
this.jwt = jwt;
|
||||
this.jobQueue = jobQueue;
|
||||
this.crypto = crypto;
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.usersRepository = usersRepository;
|
||||
this.invitesRepository = invitesRepository;
|
||||
this.recoveryTokensRepository = recoveryTokensRepository;
|
||||
this.settingsRepository = settingsRepository;
|
||||
this.teamsRepository = teamsRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return UserService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
issueToken = (payload: Partial<User>, appSettings: EnvConfig) => {
|
||||
return this.jwt.sign(payload, appSettings.jwtSecret, { expiresIn: appSettings.jwtTTL });
|
||||
};
|
||||
|
||||
registerUser = async (user: Partial<User>, inviteToken: string, file: Express.Multer.File | null) => {
|
||||
// Create a new user
|
||||
// If superAdmin exists, a token should be attached to all further register requests
|
||||
const superAdminExists = await this.usersRepository.findSuperAdmin();
|
||||
if (superAdminExists) {
|
||||
const invite = await this.invitesRepository.findByTokenAndDelete(inviteToken);
|
||||
user.role = invite.role ?? ["user"];
|
||||
user.teamId = invite.teamId;
|
||||
user.email = invite.email;
|
||||
} else {
|
||||
// This is the first account, create JWT secret to use if one is not supplied by env
|
||||
const jwtSecret = this.crypto.randomBytes(64).toString("hex");
|
||||
await this.settingsRepository.update({ jwtSecret });
|
||||
// Create a new team
|
||||
if (!user.email) {
|
||||
throw new AppError({ message: "Email is required for first user", service: SERVICE_NAME, method: "registerUser", status: 400 });
|
||||
}
|
||||
const team = await this.teamsRepository.create(user.email);
|
||||
user.teamId = team.id;
|
||||
user.role = ["superadmin"];
|
||||
}
|
||||
|
||||
// Hash password before storing
|
||||
if (user.password) {
|
||||
user.password = this.hashPassword(user.password);
|
||||
}
|
||||
|
||||
const newUser = await this.usersRepository.create(user as User, file);
|
||||
|
||||
this.logger.debug({
|
||||
message: "New user created",
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
details: { userId: newUser.id },
|
||||
});
|
||||
|
||||
delete newUser.profileImage;
|
||||
delete newUser.avatarImage;
|
||||
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
|
||||
const token = this.issueToken(newUser, appSettings);
|
||||
|
||||
try {
|
||||
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
|
||||
name: newUser.firstName,
|
||||
});
|
||||
if (!html) {
|
||||
throw new Error("Failed to build welcome email HTML");
|
||||
}
|
||||
this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error: unknown) => {
|
||||
this.logger.warn({
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
});
|
||||
} catch (error: unknown) {
|
||||
this.logger.warn({
|
||||
message: error instanceof Error ? error.message : "Unknown error",
|
||||
service: SERVICE_NAME,
|
||||
method: "registerUser",
|
||||
stack: error instanceof Error ? error.stack : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
return { user: newUser, token };
|
||||
};
|
||||
|
||||
createUser = async (userData: Partial<User>, teamId: string, actorRoles: UserRole[], file: Express.Multer.File | null) => {
|
||||
// Validate that the creator can assign the requested roles
|
||||
const targetRoles = userData.role ?? [];
|
||||
for (const targetRole of targetRoles) {
|
||||
const canManage = actorRoles.some((actorRole) => canManageRole(actorRole, targetRole));
|
||||
if (!canManage) {
|
||||
throw new AppError({
|
||||
message: "You do not have permission to assign this role",
|
||||
service: SERVICE_NAME,
|
||||
method: "createUser",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
userData.teamId = teamId;
|
||||
|
||||
if (userData.password) {
|
||||
userData.password = this.hashPassword(userData.password);
|
||||
}
|
||||
|
||||
const newUser = await this.usersRepository.create(userData as User, file);
|
||||
|
||||
this.logger.debug({
|
||||
message: "New user created by superadmin",
|
||||
service: SERVICE_NAME,
|
||||
method: "createUser",
|
||||
details: { userId: newUser.id },
|
||||
});
|
||||
|
||||
newUser.profileImage = undefined;
|
||||
newUser.avatarImage = undefined;
|
||||
newUser.password = "";
|
||||
|
||||
return newUser;
|
||||
};
|
||||
|
||||
loginUser = async (email: string, password: string) => {
|
||||
// Check if user exists
|
||||
const user = await this.usersRepository.findByEmail(email);
|
||||
// Compare password
|
||||
const match = await bcrypt.compare(password, user.password);
|
||||
|
||||
if (match !== true) {
|
||||
throw new AppError({ message: "Incorrect password", service: SERVICE_NAME, status: 401 });
|
||||
}
|
||||
|
||||
// Remove password from user object. Should this be abstracted to DB layer?
|
||||
const userWithoutPassword = { ...user };
|
||||
userWithoutPassword.password = "";
|
||||
userWithoutPassword.avatarImage = "";
|
||||
|
||||
// Happy path, return token
|
||||
const appSettings = await this.settingsService.getSettings();
|
||||
const token = this.issueToken(userWithoutPassword, appSettings);
|
||||
// reset avatar image
|
||||
userWithoutPassword.avatarImage = user.avatarImage;
|
||||
return { user: userWithoutPassword, token };
|
||||
};
|
||||
|
||||
editUser = async (
|
||||
updates: Partial<User & { newPassword?: string }>,
|
||||
file: Express.Multer.File | null,
|
||||
currentUserId: string,
|
||||
currentUserEmail: string
|
||||
) => {
|
||||
// Change Password check
|
||||
if (updates.password && updates.newPassword) {
|
||||
updates.email = currentUserEmail;
|
||||
const user = await this.usersRepository.findByEmail(currentUserEmail);
|
||||
const match = await bcrypt.compare(updates.password, user.password);
|
||||
// If not a match, throw a 403
|
||||
// 403 instead of 401 to avoid triggering axios interceptor
|
||||
if (!match) {
|
||||
throw new AppError({ message: "Incorrect current password", service: SERVICE_NAME, status: 403 });
|
||||
}
|
||||
// If a match, update the password
|
||||
updates.password = this.hashPassword(updates.newPassword);
|
||||
delete updates.newPassword;
|
||||
}
|
||||
|
||||
return await this.usersRepository.updateById(currentUserId, updates, file);
|
||||
};
|
||||
|
||||
checkSuperadminExists = async () => {
|
||||
return await this.usersRepository.findSuperAdmin();
|
||||
};
|
||||
|
||||
requestRecovery = async (email: string) => {
|
||||
const user = await this.usersRepository.findByEmail(email);
|
||||
|
||||
// Delete existing tokens
|
||||
await this.recoveryTokensRepository.deleteManyByEmail(email);
|
||||
const recoveryToken = await this.recoveryTokensRepository.create(email);
|
||||
const name = user.firstName;
|
||||
const settings = this.settingsService.getSettings();
|
||||
const url = `${settings.clientHost}/set-new-password/${recoveryToken.token}`;
|
||||
|
||||
const html = await this.emailService.buildEmail("passwordResetTemplate", {
|
||||
name,
|
||||
email,
|
||||
url,
|
||||
});
|
||||
if (!html) {
|
||||
throw new AppError({
|
||||
message: "Failed to build password reset email HTML",
|
||||
service: SERVICE_NAME,
|
||||
method: "requestRecovery",
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html);
|
||||
return msgId;
|
||||
};
|
||||
|
||||
validateRecovery = async (recoveryToken: string) => {
|
||||
// Throws if token not found, validating
|
||||
await this.recoveryTokensRepository.findByToken(recoveryToken);
|
||||
};
|
||||
|
||||
resetPassword = async (password: string, recoveryToken: string) => {
|
||||
const existingToken = await this.recoveryTokensRepository.findByToken(recoveryToken);
|
||||
const existingUser = await this.usersRepository.findByEmail(existingToken.email);
|
||||
|
||||
const match = await bcrypt.compare(password, existingUser.password);
|
||||
if (match === true) {
|
||||
throw new AppError({ message: "New password cannot be same as old password", service: SERVICE_NAME, status: 400 });
|
||||
}
|
||||
|
||||
const hashedPassword = this.hashPassword(password);
|
||||
await this.usersRepository.updateById(existingUser.id, { password: hashedPassword }, null);
|
||||
await this.recoveryTokensRepository.deleteManyByEmail(existingUser.email);
|
||||
|
||||
existingUser.password = "";
|
||||
existingUser.profileImage = undefined;
|
||||
|
||||
const token = this.issueToken(existingUser, await this.settingsService.getSettings());
|
||||
|
||||
return { user: existingUser, token };
|
||||
};
|
||||
|
||||
deleteUser = async ({ userId, teamId, roles }: { userId: string; teamId: string; roles: UserRole[] }) => {
|
||||
if (roles.includes("demo")) {
|
||||
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUser", status: 400 });
|
||||
}
|
||||
|
||||
if (roles.includes("superadmin")) {
|
||||
const monitors = await this.monitorsRepository.findByTeamId(teamId, {});
|
||||
if (monitors) {
|
||||
await Promise.all(monitors.map((monitor) => this.jobQueue.deleteJob(monitor)));
|
||||
}
|
||||
}
|
||||
// 6. Delete the user by id
|
||||
await this.usersRepository.deleteById(userId);
|
||||
};
|
||||
|
||||
deleteUserById = async ({
|
||||
actorId,
|
||||
actorRoles,
|
||||
actorTeamId,
|
||||
targetUserId,
|
||||
}: {
|
||||
actorId: string;
|
||||
actorTeamId: string;
|
||||
actorRoles: UserRole[];
|
||||
targetUserId: string;
|
||||
}) => {
|
||||
if (actorId === targetUserId) {
|
||||
throw new AppError({ message: "Cannot delete your own account from here", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
|
||||
}
|
||||
|
||||
const targetUser = await this.usersRepository.findById(targetUserId);
|
||||
|
||||
if (targetUser.teamId !== actorTeamId) {
|
||||
throw new AppError({ message: "User is not on your team", service: SERVICE_NAME, method: "deleteUserById", status: 403 });
|
||||
}
|
||||
|
||||
if (targetUser.role.includes("demo")) {
|
||||
throw new AppError({ message: "Demo user cannot be deleted", service: SERVICE_NAME, method: "deleteUserById", status: 400 });
|
||||
}
|
||||
|
||||
const targetRoles = targetUser.role;
|
||||
|
||||
// Check actor can manage all of target's roles
|
||||
for (const targetRole of targetRoles) {
|
||||
const canManage = actorRoles.some((actorRole) => canManageRole(actorRole, targetRole));
|
||||
if (!canManage) {
|
||||
throw new AppError({
|
||||
message: "You do not have permission to remove this user",
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteUserById",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
await this.usersRepository.deleteById(targetUserId);
|
||||
|
||||
this.logger.info({
|
||||
message: `User ${targetUserId} deleted by ${actorId}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteUserById",
|
||||
});
|
||||
};
|
||||
|
||||
getAllUsers = async () => {
|
||||
return await this.usersRepository.findAll();
|
||||
};
|
||||
|
||||
getUserById = async (roles: UserRole[], userId: string) => {
|
||||
if (!roles.includes("superadmin") && !roles.includes("admin")) {
|
||||
throw new AppError({ message: "Insufficient permissions", service: SERVICE_NAME, status: 403 });
|
||||
}
|
||||
return await this.usersRepository.findById(userId);
|
||||
};
|
||||
|
||||
editUserById = async (userId: string, patch: Partial<User>) => {
|
||||
await this.usersRepository.updateById(userId, patch, null);
|
||||
};
|
||||
|
||||
setPasswordByUserId = async (userId: string, password: string) => {
|
||||
const hashedPassword = this.hashPassword(password);
|
||||
const updatedUser = await this.usersRepository.updateById(userId, { password: hashedPassword }, null);
|
||||
return updatedUser;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
export const UserRoles = ["user", "admin", "superadmin", "demo"] as const;
|
||||
export type UserRole = (typeof UserRoles)[number];
|
||||
|
||||
export const RoleHierarchy: Record<UserRole, number> = {
|
||||
demo: 0,
|
||||
user: 1,
|
||||
admin: 2,
|
||||
superadmin: 3,
|
||||
};
|
||||
|
||||
export const canManageRole = (actorRole: UserRole, targetRole: UserRole): boolean => {
|
||||
return RoleHierarchy[actorRole] > RoleHierarchy[targetRole];
|
||||
};
|
||||
|
||||
export interface UserProfileImage {
|
||||
data?: Buffer;
|
||||
contentType?: string;
|
||||
}
|
||||
|
||||
export interface User {
|
||||
id: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
avatarImage?: string;
|
||||
profileImage?: UserProfileImage;
|
||||
isActive: boolean;
|
||||
isVerified: boolean;
|
||||
role: UserRole[];
|
||||
teamId: string;
|
||||
checkTTL?: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
Reference in new issue
Block a user