Merge branch 'develop' into feat/incidents-clear

This commit is contained in:
Alex Holliday committed 2025-06-25 09:03:00 +08:00
commit 95b832c1c6
93 files changed
+3104 -2182

No files matched your search

+3 -11
View File
@@ -82,7 +82,7 @@ class AuthController {
}
const newUser = await this.db.insertUser({ ...req.body }, req.file);
logger.info({
this.logger.info({
message: this.stringService.authCreateUser,
service: SERVICE_NAME,
details: newUser._id,
@@ -111,7 +111,7 @@ class AuthController {
});
});
} catch (error) {
logger.warn({
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
@@ -412,8 +412,7 @@ class AuthController {
// 1. Find all the monitors associated with the team ID if superadmin
const result = await this.db.getMonitorsByTeamId({
query: {},
params: { teamId: user.teamId.toString() },
teamId: user.teamId.toString(),
});
if (user.role.includes("superadmin")) {
@@ -424,13 +423,6 @@ class AuthController {
await this.jobQueue.deleteJob(monitor);
})
));
// 3. Delete team
await this.db.deleteTeam(user.teamId);
// 4. Delete all other team members
await this.db.deleteAllOtherUsers();
// 5. Delete each monitor
await this.db.deleteMonitorsByUserId(user._id);
}
// 6. Delete the user by id
await this.db.deleteUser(user._id);
+23
View File
@@ -0,0 +1,23 @@
import { handleError } from "./controllerUtils.js";
const SERVICE_NAME = "JobQueueController";
class LogController {
constructor(logger) {
this.logger = logger;
}
getLogs = async (req, res, next) => {
try {
const logs = await this.logger.getLogs();
res.success({
msg: "Logs fetched successfully",
data: logs,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getLogs"));
return;
}
};
}
export default LogController;
+37 -1
View File
@@ -681,7 +681,7 @@ class MonitorController {
explain,
});
return res.success({
msg: "OK", // TODO
msg: "OK",
data: result,
});
} catch (error) {
@@ -698,6 +698,42 @@ class MonitorController {
next(handleError(error, SERVICE_NAME, "seedDb"));
}
};
exportMonitorsToCSV = async (req, res, next) => {
try {
const { teamId } = req.user;
const monitors = await this.db.getMonitorsByTeamId({ teamId });
if (!monitors || monitors.length === 0) {
return res.success({
msg: this.stringService.noMonitorsFound,
data: null,
});
}
const csvData = monitors?.filteredMonitors?.map((monitor) => ({
name: monitor.name,
description: monitor.description,
type: monitor.type,
url: monitor.url,
interval: monitor.interval,
port: monitor.port,
ignoreTlsErrors: monitor.ignoreTlsErrors,
isActive: monitor.isActive,
}));
const csv = pkg.unparse(csvData);
return res.file({
data: csv,
headers: {
"Content-Type": "text/csv",
"Content-Disposition": "attachment; filename=monitors.csv",
},
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "exportMonitorsToCSV"));
}
};
}
export default MonitorController;
+1 -73
View File
@@ -23,85 +23,13 @@ class NotificationController {
this.stringService = stringService;
this.statusService = statusService;
this.db = db;
this.triggerNotification = this.triggerNotification.bind(this);
}
async triggerNotification(req, res, next) {
try {
await triggerNotificationBodyValidation.validateAsync(req.body, {
abortEarly: false,
stripUnknown: true,
});
} catch (error) {
next(handleValidationError(error, SERVICE_NAME));
return;
}
try {
const { monitorId, type, platform, config, status = false } = req.body;
// Create a simplified networkResponse similar to what would come from monitoring
const networkResponse = {
monitorId,
status,
};
// Use the statusService to get monitor details and handle status change logic
// This returns { monitor, statusChanged, prevStatus } exactly like your job queue uses
const statusResult = await this.statusService.updateStatus(networkResponse);
if (type === NOTIFICATION_TYPES.WEBHOOK) {
const notification = {
type,
platform,
config,
};
await this.notificationService.sendWebhookNotification(
statusResult, // Contains monitor, statusChanged, and prevStatus
notification
);
}
return res.success({
msg: this.stringService.webhookSendSuccess,
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "triggerNotification"));
}
}
createTestNetworkResponse() {
return {
monitor: {
_id: "test-monitor-id",
name: "Test Monitor",
url: "https://example.com",
},
status: true,
statusChanged: true,
prevStatus: false,
};
}
testNotification = async (req, res, next) => {
try {
const notification = req.body;
let success;
if (notification?.type === "email") {
success = await this.notificationService.sendTestEmail(notification);
}
if (notification?.type === "webhook") {
success =
await this.notificationService.sendTestWebhookNotification(notification);
}
if (notification?.type === "pager_duty") {
success =
await this.notificationService.sendTestPagerDutyNotification(notification);
}
const success = await this.notificationService.sendTestNotification(notification);
if (!success) {
return res.error({
+15 -1
View File
@@ -25,7 +25,7 @@ class JobQueueController {
try {
const jobs = await this.jobQueue.getJobs();
return res.success({
msg: this.stringService.queueGetMetrics,
msg: this.stringService.queueGetJobs,
data: jobs,
});
} catch (error) {
@@ -34,6 +34,20 @@ class JobQueueController {
}
};
getAllMetrics = async (req, res, next) => {
try {
const jobs = await this.jobQueue.getJobs();
const metrics = await this.jobQueue.getMetrics();
return res.success({
msg: this.stringService.queueGetAllMetrics,
data: { jobs, metrics },
});
} catch (error) {
next(handleError(error, SERVICE_NAME, "getAllMetrics"));
return;
}
};
addJob = async (req, res, next) => {
try {
await this.jobQueue.addJob(Math.random().toString(36).substring(7));
+62 -7
View File
@@ -69,6 +69,15 @@ const MonitorSchema = mongoose.Schema(
type: Number,
default: undefined,
},
notifications: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Notification",
},
],
secret: {
type: String,
},
thresholds: {
type: {
usage_cpu: { type: Number },
@@ -78,14 +87,33 @@ const MonitorSchema = mongoose.Schema(
},
_id: false,
},
notifications: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Notification",
alertThreshold: {
type: Number,
default: 5,
},
cpuAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
memoryAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
diskAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
tempAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
],
secret: {
type: String,
},
},
{
@@ -132,6 +160,33 @@ MonitorSchema.pre("deleteMany", async function (next) {
next();
});
MonitorSchema.pre("save", function (next) {
if (!this.cpuAlertThreshold || this.isModified("alertThreshold")) {
this.cpuAlertThreshold = this.alertThreshold;
}
if (!this.memoryAlertThreshold || this.isModified("alertThreshold")) {
this.memoryAlertThreshold = this.alertThreshold;
}
if (!this.diskAlertThreshold || this.isModified("alertThreshold")) {
this.diskAlertThreshold = this.alertThreshold;
}
if (!this.tempAlertThreshold || this.isModified("alertThreshold")) {
this.tempAlertThreshold = this.alertThreshold;
}
next();
});
MonitorSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if (update.alertThreshold) {
update.cpuAlertThreshold = update.alertThreshold;
update.memoryAlertThreshold = update.alertThreshold;
update.diskAlertThreshold = update.alertThreshold;
update.tempAlertThreshold = update.alertThreshold;
}
next();
});
MonitorSchema.index({ teamId: 1, type: 1 });
export default mongoose.model("Monitor", MonitorSchema);
+46
View File
@@ -0,0 +1,46 @@
import mongoose from "mongoose";
import { BaseCheckSchema } from "./Check.js";
const networkInterfaceSchema = mongoose.Schema({
name: { type: String, required: true },
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 },
});
const captureSchema = mongoose.Schema({
version: { type: String, default: "" },
mode: { type: String, default: "" },
});
const NetworkCheckSchema = mongoose.Schema(
{
...BaseCheckSchema.obj,
data: {
type: [networkInterfaceSchema],
default: () => [],
},
capture: {
type: captureSchema,
default: () => ({}),
},
errors: {
type: mongoose.Schema.Types.Mixed,
default: null,
},
},
{ timestamps: true }
);
NetworkCheckSchema.index({ createdAt: 1 });
NetworkCheckSchema.index({ monitorId: 1, createdAt: 1 });
NetworkCheckSchema.index({ monitorId: 1, createdAt: -1 });
export default mongoose.model("NetworkCheck", NetworkCheckSchema);
+1 -50
View File
@@ -1,19 +1,5 @@
import mongoose from "mongoose";
const configSchema = mongoose.Schema(
{
webhookUrl: { type: String },
botToken: { type: String },
chatId: { type: String },
platform: {
type: String,
enum: ["slack", "pager_duty", "webhook", "discord"],
},
routingKey: { type: String },
},
{ _id: false }
);
const NotificationSchema = mongoose.Schema(
{
userId: {
@@ -30,14 +16,7 @@ const NotificationSchema = mongoose.Schema(
},
type: {
type: String,
enum: ["email", "sms", "webhook", "pager_duty"],
},
platform: {
type: String,
},
config: {
type: configSchema,
default: () => ({}),
enum: ["email", "slack", "discord", "webhook", "pager_duty"],
},
notificationName: {
type: String,
@@ -49,34 +28,6 @@ const NotificationSchema = mongoose.Schema(
phone: {
type: String,
},
alertThreshold: {
type: Number,
default: 5,
},
cpuAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
memoryAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
diskAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
tempAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
},
{
timestamps: true,
+4
View File
@@ -70,6 +70,10 @@ const StatusPageSchema = mongoose.Schema(
type: Boolean,
default: true,
},
showAdminLoginLink: {
type: Boolean,
default: false,
},
},
{ timestamps: true }
);
+22
View File
@@ -1,6 +1,9 @@
import mongoose from "mongoose";
import bcrypt from "bcryptjs";
import logger from "../../utils/logger.js";
import Monitor from "./Monitor.js";
import Team from "./Team.js";
import Notification from "./Notification.js";
const UserSchema = mongoose.Schema(
{
@@ -74,6 +77,25 @@ UserSchema.pre("findOneAndUpdate", function (next) {
next();
});
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 Monitor.deleteMany({ userId: userToDelete._id });
await this.model.deleteMany({
teamId: userToDelete.teamId,
_id: { $ne: userToDelete._id },
});
await Notification.deleteMany({ teamId: userToDelete.teamId });
}
next();
} catch (error) {
next(error);
}
});
UserSchema.methods.comparePassword = async function (submittedPassword) {
const res = await bcrypt.compare(submittedPassword, this.password);
return res;
@@ -0,0 +1,46 @@
import NetworkCheck from "../../models/NetworkCheck.js";
const SERVICE_NAME = "networkCheckModule";
/**
* Creates and saves a new network check document to the database.
* @async
* @param {object} networkCheckData - The data for the new network check. This should conform to the NetworkCheckSchema.
* @param {string} networkCheckData.monitorId - The ID of the monitor associated with this check.
* @returns {Promise<object>} A promise that resolves to the newly created network check document.
* @throws {Error} Throws an error if the database operation fails.
*/
const createNetworkCheck = async (networkCheckData) => {
try {
const networkCheck = await new NetworkCheck(networkCheckData);
await networkCheck.save();
return networkCheck;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createNetworkCheck";
throw error;
}
};
/**
* Retrieves a list of network checks for a specific monitor, sorted by most recent.
* @async
* @param {string} monitorId - The ID of the monitor to retrieve checks for.
* @param {number} [limit=100] - The maximum number of checks to return. Defaults to 100.
* @returns {Promise<Array<object>>} A promise that resolves to an array of network check documents.
* @throws {Error} Throws an error if the database operation fails.
*/
const getNetworkChecksByMonitorId = async (monitorId, limit = 100) => {
try {
const networkChecks = await NetworkCheck.find({ monitorId })
.sort({ createdAt: -1 })
.limit(limit);
return networkChecks;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNetworkChecksByMonitorId";
throw error;
}
};
export { createNetworkCheck, getNetworkChecksByMonitorId };
@@ -153,6 +153,7 @@ const getStatusPage = async (url) => {
showCharts: 1,
showUptimePercentage: 1,
timezone: 1,
showAdminLoginLink: 1,
url: 1,
},
monitors: {
+17 -3
View File
@@ -36,6 +36,9 @@ import StatusPageController from "./controllers/statusPageController.js";
import QueueRoutes from "./routes/queueRoute.js";
import QueueController from "./controllers/queueController.js";
import LogRoutes from "./routes/logRoutes.js";
import LogController from "./controllers/logController.js";
import NotificationRoutes from "./routes/notificationRoute.js";
import NotificationController from "./controllers/notificationController.js";
@@ -73,6 +76,7 @@ import StatusService from "./service/statusService.js";
// Notification Service and dependencies
import NotificationService from "./service/notificationService.js";
import NotificationUtils from "./service/notificationUtils.js";
// Buffer Service and dependencies
import BufferService from "./service/bufferService.js";
@@ -173,13 +177,19 @@ const startApp = async () => {
);
const bufferService = new BufferService({ db, logger });
const statusService = new StatusService({ db, logger, buffer: bufferService });
const notificationService = new NotificationService(
const notificationUtils = new NotificationUtils({
stringService,
emailService,
});
const notificationService = new NotificationService({
emailService,
db,
logger,
networkService,
stringService
);
stringService,
notificationUtils,
});
const redisService = new RedisService({ Redis: IORedis, logger });
@@ -287,6 +297,8 @@ const startApp = async () => {
ServiceRegistry.get(StringService.SERVICE_NAME)
);
const logController = new LogController(logger);
const statusPageController = new StatusPageController(
ServiceRegistry.get(MongoDB.SERVICE_NAME),
ServiceRegistry.get(StringService.SERVICE_NAME)
@@ -313,6 +325,7 @@ const startApp = async () => {
maintenanceWindowController
);
const queueRoutes = new QueueRoutes(queueController);
const logRoutes = new LogRoutes(logController);
const statusPageRoutes = new StatusPageRoutes(statusPageController);
const notificationRoutes = new NotificationRoutes(notificationController);
@@ -365,6 +378,7 @@ const startApp = async () => {
app.use("/api/v1/checks", verifyJWT, checkRoutes.getRouter());
app.use("/api/v1/maintenance-window", verifyJWT, maintenanceWindowRoutes.getRouter());
app.use("/api/v1/queue", verifyJWT, queueRoutes.getRouter());
app.use("/api/v1/logs", verifyJWT, logRoutes.getRouter());
app.use("/api/v1/status-page", statusPageRoutes.getRouter());
app.use("/api/v1/notifications", verifyJWT, notificationRoutes.getRouter());
app.use("/api/v1/diagnostic", verifyJWT, diagnosticRoutes.getRouter());
+1
View File
@@ -123,6 +123,7 @@
"monitorCertificate": "Got monitor certificate successfully",
"monitorDemoAdded": "Successfully added demo monitors",
"queueGetMetrics": "Got metrics successfully",
"queueGetJobs": "Got jobs successfully",
"queueAddJob": "Job added successfully",
"queueObliterate": "Queue obliterated",
"jobQueueDeleteJobSuccess": "Job removed successfully",
+21 -1
View File
@@ -16,7 +16,12 @@ const responseHandler = (req, res, next) => {
* @param {*} [options.data=null] - Response data payload
* @returns {Object} Express response object
*/
res.success = ({ status = 200, msg = "OK", data = null }) => {
res.success = ({ status = 200, msg = "OK", data = null, headers = {} }) => {
// Set custom headers if provided
Object.entries(headers).forEach(([key, value]) => {
res.set(key, value);
});
return res.status(status).json({
success: true,
msg: msg,
@@ -40,6 +45,21 @@ const responseHandler = (req, res, next) => {
data,
});
};
/**
* Sends a raw file response (for CSV, PDF, etc.)
* @param {Object} options
* @param {Buffer|string} options.data - The file content
* @param {Object} options.headers - Headers to set (e.g. Content-Type, Content-Disposition)
* @param {number} [options.status=200] - HTTP status code
*/
res.file = ({ data, headers = {}, status = 200 }) => {
Object.entries(headers).forEach(([key, value]) => {
res.setHeader(key, value);
});
return res.status(status).send(data);
};
next();
};
+8 -2
View File
@@ -1,14 +1,20 @@
import logger from "../utils/logger.js";
import ServiceRegistry from "../service/serviceRegistry.js";
import StringService from "../service/stringService.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "verifyOwnership";
const verifyOwnership = (Model, paramName) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
return async (req, res, next) => {
const userId = req.user._id;
const documentId = req.params[paramName];
let documentId = req.params[paramName];
try {
if (typeof documentId === "string") {
documentId = ObjectId.createFromHexString(documentId);
}
const doc = await Model.findById(documentId);
//If the document is not found, return a 404 error
if (!doc) {
@@ -35,7 +41,7 @@ const verifyOwnership = (Model, paramName) => {
// If the userID does not match the document's userID, return a 403 error
if (userId.toString() !== doc.userId.toString()) {
const error = new Error(stringService.verifyOwnerUnauthorized);
const error = new Error("Unauthorized");
error.status = 403;
throw error;
}
+38
View File
@@ -0,0 +1,38 @@
const SERVICE_NAME = "verifyTeamAccess";
const verifyTeamAccess = (Model, paramName) => {
return async (req, res, next) => {
try {
const documentId = req.params[paramName];
const doc = await Model.findById(documentId);
if (!doc) {
const error = new Error("Document not found");
error.status = 404;
throw error;
}
if (!req?.user?.teamId || !doc.teamId) {
const error = new Error("Missing team information");
error.status = 400;
throw error;
}
if (req.user.teamId.toString() === doc.teamId.toString()) {
next();
return;
}
const error = new Error("Unauthorized");
error.status = 403;
throw error;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "verifyTeamAccess";
next(error);
return;
}
};
};
export { verifyTeamAccess };
+18
View File
@@ -0,0 +1,18 @@
import { Router } from "express";
import { isAllowed } from "../middleware/isAllowed.js";
class LogRoutes {
constructor(logController) {
this.router = Router();
this.logController = logController;
this.initRoutes();
}
initRoutes() {
this.router.get("/", isAllowed(["admin", "superadmin"]), this.logController.getLogs);
}
getRouter() {
return this.router;
}
}
export default LogRoutes;
+12 -3
View File
@@ -1,7 +1,8 @@
import { Router } from "express";
import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { verifyTeamAccess } from "../middleware/verifyTeamAccess.js";
import Monitor from "../db/models/Monitor.js";
import MaintenanceWindow from "../db/models/MaintenanceWindow.js";
class MaintenanceWindowRoutes {
constructor(maintenanceWindowController) {
this.router = Router();
@@ -24,9 +25,17 @@ class MaintenanceWindowRoutes {
this.router.get("/:id", this.maintenanceWindowController.getMaintenanceWindowById);
this.router.put("/:id", this.maintenanceWindowController.editMaintenanceWindow);
this.router.put(
"/:id",
verifyTeamAccess(MaintenanceWindow, "id"),
this.maintenanceWindowController.editMaintenanceWindow
);
this.router.delete("/:id", this.maintenanceWindowController.deleteMaintenanceWindow);
this.router.delete(
"/:id",
verifyTeamAccess(MaintenanceWindow, "id"),
this.maintenanceWindowController.deleteMaintenanceWindow
);
}
getRouter() {
+10 -1
View File
@@ -2,7 +2,9 @@ import { Router } from "express";
import { isAllowed } from "../middleware/isAllowed.js";
import multer from "multer";
import { fetchMonitorCertificate } from "../controllers/controllerUtils.js";
import Monitor from "../db/models/Monitor.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { verifyTeamAccess } from "../middleware/verifyTeamAccess.js";
const upload = multer({
storage: multer.memoryStorage(), // Store file in memory as Buffer
});
@@ -17,6 +19,11 @@ class MonitorRoutes {
initRoutes() {
this.router.get("/", this.monitorController.getAllMonitors);
this.router.get("/uptime", this.monitorController.getAllMonitorsWithUptimeStats);
this.router.get(
"/export",
isAllowed(["admin", "superadmin"]),
this.monitorController.exportMonitorsToCSV
);
this.router.get("/stats/:monitorId", this.monitorController.getMonitorStatsById);
this.router.get(
"/hardware/details/:monitorId",
@@ -57,6 +64,7 @@ class MonitorRoutes {
this.router.delete(
"/:monitorId",
verifyOwnership(Monitor, "monitorId"),
isAllowed(["admin", "superadmin"]),
this.monitorController.deleteMonitor
);
@@ -69,6 +77,7 @@ class MonitorRoutes {
this.router.put(
"/:monitorId",
verifyTeamAccess(Monitor, "monitorId"),
isAllowed(["admin", "superadmin"]),
this.monitorController.editMonitor
);
+13 -5
View File
@@ -1,6 +1,8 @@
import { Router } from "express";
import { verifyJWT } from "../middleware/verifyJWT.js";
import { verifyOwnership } from "../middleware/verifyOwnership.js";
import { verifyTeamAccess } from "../middleware/verifyTeamAccess.js";
import Notification from "../db/models/Notification.js";
class NotificationRoutes {
constructor(notificationController) {
this.router = Router();
@@ -11,8 +13,6 @@ class NotificationRoutes {
initializeRoutes() {
this.router.use(verifyJWT);
this.router.post("/trigger", this.notificationController.triggerNotification);
this.router.post("/test", this.notificationController.testNotification);
this.router.post("/test/all", this.notificationController.testAllNotifications);
@@ -20,10 +20,18 @@ class NotificationRoutes {
this.router.get("/team", this.notificationController.getNotificationsByTeamId);
this.router.delete("/:id", this.notificationController.deleteNotification);
this.router.delete(
"/:id",
verifyOwnership(Notification, "id"),
this.notificationController.deleteNotification
);
this.router.get("/:id", this.notificationController.getNotificationById);
this.router.put("/:id", this.notificationController.editNotification);
this.router.put(
"/:id",
verifyTeamAccess(Notification, "id"),
this.notificationController.editNotification
);
}
getRouter() {
+6
View File
@@ -19,6 +19,12 @@ class QueueRoutes {
this.queueController.getJobs
);
this.router.get(
"/all-metrics",
isAllowed(["admin", "superadmin"]),
this.queueController.getAllMetrics
);
this.router.post(
"/jobs",
isAllowed(["admin", "superadmin"]),
+23 -2
View File
@@ -1,5 +1,4 @@
import { Pulse } from "@pulsecron/pulse";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "PulseQueue";
class PulseQueue {
@@ -58,6 +57,9 @@ class PulseQueue {
job.unique({ "data.monitor._id": monitor._id });
job.attrs.jobId = monitorId.toString();
job.repeatEvery(`${intervalInSeconds} seconds`);
if (monitor.isActive === false) {
job.disable();
}
await job.save();
};
@@ -137,6 +139,8 @@ class PulseQueue {
const jobs = await this.pulse.jobs();
const metrics = jobs.reduce(
(acc, job) => {
acc.totalRuns += job.attrs.runCount || 0;
acc.totalFailures += job.attrs.failCount || 0;
acc.jobs++;
if (job.attrs.failCount > 0 && job.attrs.failedAt >= job.attrs.lastFinishedAt) {
acc.failingJobs++;
@@ -148,13 +152,22 @@ class PulseQueue {
acc.jobsWithFailures.push({
monitorId: job.attrs.data.monitor._id,
monitorUrl: job.attrs.data.monitor.url,
monitorType: job.attrs.data.monitor.type,
failedAt: job.attrs.failedAt,
failCount: job.attrs.failCount,
failReason: job.attrs.failReason,
});
}
return acc;
},
{ jobs: 0, activeJobs: 0, failingJobs: 0, jobsWithFailures: [] }
{
jobs: 0,
activeJobs: 0,
failingJobs: 0,
jobsWithFailures: [],
totalRuns: 0,
totalFailures: 0,
}
);
return metrics;
};
@@ -165,10 +178,18 @@ class PulseQueue {
return {
monitorId: job.attrs.data.monitor._id,
monitorUrl: job.attrs.data.monitor.url,
monitorType: job.attrs.data.monitor.type,
active: !job.attrs.disabled,
lockedAt: job.attrs.lockedAt,
runCount: job.attrs.runCount || 0,
failCount: job.attrs.failCount || 0,
failReason: job.attrs.failReason,
lastRunAt: job.attrs.lastRunAt,
lastFinishedAt: job.attrs.lastFinishedAt,
lastRunTook: job.attrs.lockedAt
? null
: job.attrs.lastFinishedAt - job.attrs.lastRunAt,
lastFailedAt: job.attrs.failedAt,
};
});
};
+4 -10
View File
@@ -432,9 +432,9 @@ class NetworkService {
throw err;
}
async requestWebhook(platform, url, message) {
async requestWebhook(type, url, body) {
try {
const response = await this.axios.post(url, message, {
const response = await this.axios.post(url, body, {
headers: {
"Content-Type": "application/json",
},
@@ -444,7 +444,7 @@ class NetworkService {
type: "webhook",
status: true,
code: response.status,
message: `Successfully sent ${platform} notification`,
message: `Successfully sent ${type} notification`,
payload: response.data,
};
} catch (error) {
@@ -452,19 +452,13 @@ class NetworkService {
message: error.message,
service: this.SERVICE_NAME,
method: "requestWebhook",
url,
platform,
error: error.message,
statusCode: error.response?.status,
responseData: error.response?.data,
requestPayload: message,
});
return {
type: "webhook",
status: false,
code: error.response?.status || this.NETWORK_ERROR,
message: `Failed to send ${platform} notification`,
message: `Failed to send ${type} notification`,
payload: error.response?.data,
};
}
+83 -472
View File
@@ -1,512 +1,123 @@
const SERVICE_NAME = "NotificationService";
const TELEGRAM_API_BASE_URL = "https://api.telegram.org/bot";
const PLATFORM_TYPES = ["telegram", "slack", "discord", "webhook"];
const MESSAGE_FORMATTERS = {
telegram: (messageText, chatId) => ({ chat_id: chatId, text: messageText }),
slack: (messageText) => ({ text: messageText }),
discord: (messageText) => ({ content: messageText }),
webhook: (messageText) => ({ text: messageText }),
};
class NotificationService {
static SERVICE_NAME = SERVICE_NAME;
/**
* Creates an instance of NotificationService.
*
* @param {Object} emailService - The email service used for sending notifications.
* @param {Object} db - The database instance for storing notification data.
* @param {Object} logger - The logger instance for logging activities.
* @param {Object} networkService - The network service for sending webhook notifications.
*/
constructor(emailService, db, logger, networkService, stringService) {
this.SERVICE_NAME = SERVICE_NAME;
constructor({
emailService,
db,
logger,
networkService,
stringService,
notificationUtils,
}) {
this.emailService = emailService;
this.db = db;
this.logger = logger;
this.networkService = networkService;
this.stringService = stringService;
this.notificationUtils = notificationUtils;
}
/**
* Formats a notification message based on the monitor status and platform.
*
* @param {Object} monitor - The monitor object.
* @param {string} monitor.name - The name of the monitor.
* @param {string} monitor.url - The URL of the monitor.
* @param {boolean} status - The current status of the monitor (true for up, false for down).
* @param {string} platform - The notification platform (e.g., "telegram", "slack", "discord").
* @param {string} [chatId] - The chat ID for platforms that require it (e.g., Telegram).
* @returns {Object|null} The formatted message object for the specified platform, or null if the platform is unsupported.
*/
sendNotification = async ({ notification, subject, content, html }) => {
const { type, address } = notification;
formatNotificationMessage(monitor, status, platform, chatId, code, timestamp) {
// Format timestamp using the local system timezone
const formatTime = (timestamp) => {
const date = new Date(timestamp);
// Get timezone abbreviation and format the date
const timeZoneAbbr = date
.toLocaleTimeString("en-US", { timeZoneName: "short" })
.split(" ")
.pop();
// Format the date with readable format
return (
date
.toLocaleString("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
})
.replace(/(\d+)\/(\d+)\/(\d+),\s/, "$3-$1-$2 ") +
" " +
timeZoneAbbr
);
};
// Get formatted time
const formattedTime = timestamp
? formatTime(timestamp)
: formatTime(new Date().getTime());
// Create different messages based on status with extra spacing
let messageText;
if (status === true) {
messageText = this.stringService.monitorUpAlert
.replace("{monitorName}", monitor.name)
.replace("{time}", formattedTime)
.replace("{code}", code || "Unknown");
} else {
messageText = this.stringService.monitorDownAlert
.replace("{monitorName}", monitor.name)
.replace("{time}", formattedTime)
.replace("{code}", code || "Unknown");
}
if (!PLATFORM_TYPES.includes(platform)) {
return undefined;
}
return MESSAGE_FORMATTERS[platform](messageText, chatId);
}
formatHardwareNotificationMessage = (
monitor,
status,
platform,
chatId,
code,
timestamp,
alerts
) => {
const messageText = alerts.map((alert) => alert).join("\n");
return MESSAGE_FORMATTERS[platform](messageText, chatId);
};
sendTestWebhookNotification = async (notification) => {
const config = notification.config;
const response = await this.networkService.requestWebhook(
config.platform,
config.webhookUrl,
"This is a test notification"
);
return response.status;
};
/**
* Sends a webhook notification to a specified platform.
*
* @param {Object} networkResponse - The response object from the network.
* @param {Object} networkResponse.monitor - The monitor object.
* @param {boolean} networkResponse.status - The monitor's status (true for up, false for down).
* @param {Object} notification - The notification settings.
* @param {string} notification.platform - The target platform ("telegram", "slack", "discord").
* @param {Object} notification.config - The configuration object for the webhook.
* @param {string} notification.config.webhookUrl - The webhook URL for the platform.
* @param {string} [notification.config.botToken] - The bot token for Telegram notifications.
* @param {string} [notification.config.chatId] - The chat ID for Telegram notifications.
* @returns {Promise<boolean>} A promise that resolves to true if the notification was sent successfully, otherwise false.
*/
async sendWebhookNotification(networkResponse, notification, alerts = []) {
const { monitor, status, code } = networkResponse;
const { webhookUrl, platform, botToken, chatId } = notification.config;
// Early return if platform is not supported
if (!PLATFORM_TYPES.includes(platform)) {
this.logger.warn({
message: this.stringService.getWebhookUnsupportedPlatform(platform),
service: this.SERVICE_NAME,
method: "sendWebhookNotification",
details: { platform },
});
return false;
}
// Early return for telegram if required fields are missing
if (platform === "telegram" && (!botToken || !chatId)) {
this.logger.warn({
message: "Missing required fields for Telegram notification",
service: this.SERVICE_NAME,
method: "sendWebhookNotification",
details: { platform },
});
return false;
}
let url = webhookUrl;
if (platform === "telegram") {
url = `${TELEGRAM_API_BASE_URL}${botToken}/sendMessage`;
}
let message;
if (monitor.type === "hardware") {
message = this.formatHardwareNotificationMessage(
monitor,
status,
platform,
chatId,
code,
networkResponse.timestamp,
alerts
);
} else {
message = this.formatNotificationMessage(
monitor,
status,
platform,
chatId,
code, // Pass the code field directly
networkResponse.timestamp
);
}
try {
const response = await this.networkService.requestWebhook(platform, url, message);
return response.status;
} catch (error) {
this.logger.error({
message: this.stringService.getWebhookSendError(platform),
service: this.SERVICE_NAME,
method: "sendWebhookNotification",
stack: error.stack,
});
return false;
}
}
/**
* Sends an email notification for hardware infrastructure alerts
*
* @async
* @function sendHardwareEmail
* @param {Object} networkResponse - Response object containing monitor information
* @param {string} address - Email address to send the notification to
* @param {Array} [alerts=[]] - List of hardware alerts to include in the email
* @returns {Promise<boolean>} - Indicates whether email was sent successfully
* @throws {Error}
*/
async sendHardwareEmail(networkResponse, address, alerts = []) {
if (alerts.length === 0) return false;
const { monitor, status, prevStatus } = networkResponse;
const template = "hardwareIncidentTemplate";
const context = { monitor: monitor.name, url: monitor.url, alerts };
const subject = `Monitor ${monitor.name} infrastructure alerts`;
const html = await this.emailService.buildEmail(template, context);
this.emailService.sendEmail(address, subject, html).catch((error) => {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "sendHardwareEmail",
stack: error.stack,
});
});
return true;
}
sendTestEmail = async (notification) => {
const to = notification?.address;
if (!to || typeof to !== "string") {
throw new Error(this.stringService.errorForValidEmailAddress);
}
const subject = this.stringService.testEmailSubject;
const context = { testName: "Monitoring System" };
try {
const html = await this.emailService.buildEmail("testEmailTemplate", context);
const messageId = await this.emailService.sendEmail(to, subject, html);
if (messageId) {
return true;
}
} catch (error) {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "sendTestEmail",
stack: error.stack,
});
return false;
}
};
/**
* Sends an email notification about monitor status change
*
* @async
* @function sendEmail
* @param {Object} networkResponse - Response object containing monitor status information
* @param {string} address - Email address to send the notification to
* @returns {Promise<boolean>} - Indicates email was sent successfully
*/
async sendEmail(networkResponse, address) {
const { monitor, status, prevStatus } = networkResponse;
const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate";
const context = { monitor: monitor.name, url: monitor.url };
const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`;
const html = await this.emailService.buildEmail(template, context);
this.emailService.sendEmail(address, subject, html).catch((error) => {
this.logger.warn({
message: error.message,
service: this.SERVICE_NAME,
method: "sendEmail",
stack: error.stack,
});
});
return true;
}
async sendTestPagerDutyNotification(notification) {
const { routingKey } = notification.config;
const response = await this.networkService.requestPagerDuty({
message: "This is a test notification",
monitorUrl: "Test notification",
routingKey,
});
return response;
}
async sendPagerDutyNotification(networkResponse, notification, alerts = []) {
const { monitor, status, code } = networkResponse;
const { routingKey, platform } = notification.config;
let message;
if (monitor.type === "hardware") {
message = this.formatHardwareNotificationMessage(
monitor,
status,
platform,
null,
code,
networkResponse.timestamp,
alerts
);
} else {
message = this.formatNotificationMessage(
monitor,
status,
platform,
null,
code, // Pass the code field directly
networkResponse.timestamp
);
}
try {
const response = await this.networkService.requestPagerDuty({
message,
routingKey,
monitorUrl: monitor.url,
});
return response;
} catch (error) {
this.logger.error({
message: "Failed to send PagerDuty notification",
details: error.details,
service: error.service || this.SERVICE_NAME,
method: error.method || "sendPagerDutyNotification",
stack: error.stack,
});
return false;
}
}
async handleStatusNotifications(networkResponse) {
try {
// If status hasn't changed, we're done
if (networkResponse.statusChanged === false) return false;
// if prevStatus is undefined, monitor is resuming, we're done
if (networkResponse.prevStatus === undefined) return false;
const notificationIDs = networkResponse.monitor?.notifications ?? [];
const notifications = await this.db.getNotificationsByIds(notificationIDs);
for (const notification of notifications) {
if (notification.type === "email") {
await this.sendEmail(networkResponse, notification.address);
} else if (notification.type === "webhook") {
await this.sendWebhookNotification(networkResponse, notification);
} else if (notification.type === "pager_duty") {
await this.sendPagerDutyNotification(networkResponse, notification);
}
}
if (type === "email") {
const messageId = await this.emailService.sendEmail(address, subject, html);
if (!messageId) return false;
return true;
} catch (error) {
this.logger.error({
message: error.message,
service: this.SERVICE_NAME,
method: "handleNotifications",
stack: error.stack,
});
}
}
/**
* Handles status change notifications for a monitor
*
* @async
* @function handleStatusNotifications
* @param {Object} networkResponse - Response object containing monitor status information
* @returns {Promise<boolean>} - Indicates whether notifications were processed
* @throws {Error}
*/
async handleHardwareNotifications(networkResponse) {
const thresholds = networkResponse?.monitor?.thresholds;
if (thresholds === undefined) return false; // No thresholds set, we're done
// Get thresholds from monitor
const {
usage_cpu: cpuThreshold = -1,
usage_memory: memoryThreshold = -1,
usage_disk: diskThreshold = -1,
} = thresholds;
// Create a body for webhooks
let body = { text: content };
if (type === "discord") {
body = { content };
}
// Get metrics from response
const metrics = networkResponse?.payload?.data ?? null;
if (metrics === null) return false;
if (type === "slack" || type === "discord" || type === "webhook") {
const response = await this.networkService.requestWebhook(type, address, body);
return response.status;
}
if (type === "pager_duty") {
const response = await this.networkService.requestPagerDuty({
message: content,
monitorUrl: subject,
routingKey: address,
});
const {
cpu: { usage_percent: cpuUsage = -1 } = {},
memory: { usage_percent: memoryUsage = -1 } = {},
disk = [],
} = metrics;
return response;
}
};
const alerts = {
cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
disk:
disk?.some(
(d) =>
diskThreshold !== -1 &&
typeof d?.usage_percent === "number" &&
d?.usage_percent > diskThreshold
) ?? false,
};
async handleNotifications(networkResponse) {
const { monitor, statusChanged, prevStatus } = networkResponse;
const { type } = monitor;
if (type !== "hardware" && statusChanged === false) return false;
// if prevStatus is undefined, monitor is resuming, we're done
if (type !== "hardware" && prevStatus === undefined) return false;
const notificationIDs = networkResponse.monitor?.notifications ?? [];
const notifications = await this.db.getNotificationsByIds(notificationIDs);
if (notificationIDs.length === 0) return false;
for (const notification of notifications) {
const alertsToSend = [];
const alertTypes = ["cpu", "memory", "disk"];
if (networkResponse.monitor.type === "hardware") {
const thresholds = networkResponse?.monitor?.thresholds;
for (const type of alertTypes) {
// Iterate over each alert type to see if any need to be decremented
if (alerts[type] === true) {
notification[`${type}AlertThreshold`]--; // Decrement threshold if an alert is triggered
if (thresholds === undefined) return false; // No thresholds set, we're done
const metrics = networkResponse?.payload?.data ?? null;
if (metrics === null) return false; // No metrics, we're done
if (notification[`${type}AlertThreshold`] <= 0) {
// If threshold drops below 0, reset and send notification
notification[`${type}AlertThreshold`] = notification.alertThreshold;
const alerts = await this.notificationUtils.buildHardwareAlerts(networkResponse);
if (alerts.length === 0) return false;
const formatAlert = {
cpu: () =>
`Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
memory: () =>
`Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`,
disk: () =>
`Your current disk usage: ${disk
.map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`)
.join(
", "
)} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
};
alertsToSend.push(formatAlert[type]());
}
}
}
const { subject, html } = await this.notificationUtils.buildHardwareEmail(
networkResponse,
alerts
);
const content =
await this.notificationUtils.buildHardwareNotificationMessage(alerts);
await notification.save();
if (alertsToSend.length === 0) continue; // No alerts to send, we're done
if (notification.type === "email") {
await this.sendHardwareEmail(networkResponse, notification.address, alertsToSend);
} else if (notification.type === "webhook") {
await this.sendWebhookNotification(networkResponse, notification, alertsToSend);
} else if (notification.type === "pager_duty") {
await this.sendPagerDutyNotification(networkResponse, notification, alertsToSend);
}
const success = await this.notifyAll({ notificationIDs, subject, html, content });
return success;
}
return true;
// Status monitors
const { subject, html } =
await this.notificationUtils.buildStatusEmail(networkResponse);
const content = await this.notificationUtils.buildWebhookMessage(networkResponse);
const success = this.notifyAll({ notificationIDs, subject, html, content });
return success;
}
/**
* Handles notifications for different monitor types
*
* @async
* @function handleNotifications
* @param {Object} networkResponse - Response object containing monitor information
* @returns {Promise<boolean>} - Indicates whether notifications were processed successfully
*/
async handleNotifications(networkResponse) {
try {
if (networkResponse.monitor.type === "hardware") {
this.handleHardwareNotifications(networkResponse);
}
this.handleStatusNotifications(networkResponse);
return true;
} catch (error) {
this.logger.error({
message: error.message,
service: this.SERVICE_NAME,
method: "handleNotifications",
stack: error.stack,
});
}
}
async testAllNotifications(notificationIDs) {
async notifyAll({ notificationIDs, subject, html, content }) {
const notifications = await this.db.getNotificationsByIds(notificationIDs);
// Map each notification to a test promise
const testPromises = notifications.map(async (notification) => {
const promises = notifications.map(async (notification) => {
try {
if (notification.type === "email") {
await this.sendTestEmail(notification);
} else if (notification.type === "webhook") {
await this.sendTestWebhookNotification(notification);
} else if (notification.type === "pager_duty") {
await this.sendTestPagerDutyNotification(notification);
}
await this.sendNotification({ notification, subject, content, html });
return true;
} catch (err) {
return false;
}
});
const results = await Promise.all(testPromises);
const results = await Promise.all(promises);
return results.every((r) => r === true);
}
async getTestNotification() {
const html = await this.notificationUtils.buildTestEmail();
const content = "This is a test notification";
const subject = "Test Notification";
return { subject, html, content };
}
async testAllNotifications(notificationIDs) {
const { subject, html, content } = await this.getTestNotification();
return this.notifyAll({ notificationIDs, subject, html, content });
}
async sendTestNotification(notification) {
const { subject, html, content } = await this.getTestNotification();
const success = await this.sendNotification({ notification, subject, content, html });
return success;
}
}
export default NotificationService;
+146
View File
@@ -0,0 +1,146 @@
class NotificationUtils {
constructor({ stringService, emailService }) {
this.stringService = stringService;
this.emailService = emailService;
}
buildTestEmail = async () => {
const context = { testName: "Monitoring System" };
const html = await this.emailService.buildEmail("testEmailTemplate", context);
return html;
};
buildStatusEmail = async (networkResponse) => {
const { monitor, status, prevStatus } = networkResponse;
const template = prevStatus === false ? "serverIsUpTemplate" : "serverIsDownTemplate";
const context = { monitor: monitor.name, url: monitor.url };
const subject = `Monitor ${monitor.name} is ${status === true ? "up" : "down"}`;
const html = await this.emailService.buildEmail(template, context);
return { subject, html };
};
buildWebhookMessage = (networkResponse) => {
const { monitor, status, code, timestamp } = networkResponse;
// Format timestamp using the local system timezone
const formatTime = (timestamp) => {
const date = new Date(timestamp);
// Get timezone abbreviation and format the date
const timeZoneAbbr = date
.toLocaleTimeString("en-US", { timeZoneName: "short" })
.split(" ")
.pop();
// Format the date with readable format
return (
date
.toLocaleString("en-US", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
second: "2-digit",
hour12: false,
})
.replace(/(\d+)\/(\d+)\/(\d+),\s/, "$3-$1-$2 ") +
" " +
timeZoneAbbr
);
};
// Get formatted time
const formattedTime = timestamp
? formatTime(timestamp)
: formatTime(new Date().getTime());
// Create different messages based on status with extra spacing
let messageText;
if (status === true) {
messageText = this.stringService.monitorUpAlert
.replace("{monitorName}", monitor.name)
.replace("{time}", formattedTime)
.replace("{code}", code || "Unknown");
} else {
messageText = this.stringService.monitorDownAlert
.replace("{monitorName}", monitor.name)
.replace("{time}", formattedTime)
.replace("{code}", code || "Unknown");
}
return messageText;
};
buildHardwareAlerts = async (networkResponse) => {
const monitor = networkResponse?.monitor;
const thresholds = networkResponse?.monitor?.thresholds;
const {
usage_cpu: cpuThreshold = -1,
usage_memory: memoryThreshold = -1,
usage_disk: diskThreshold = -1,
} = thresholds;
const metrics = networkResponse?.payload?.data;
const {
cpu: { usage_percent: cpuUsage = -1 } = {},
memory: { usage_percent: memoryUsage = -1 } = {},
disk = [],
} = metrics;
const alerts = {
cpu: cpuThreshold !== -1 && cpuUsage > cpuThreshold ? true : false,
memory: memoryThreshold !== -1 && memoryUsage > memoryThreshold ? true : false,
disk:
disk?.some(
(d) =>
diskThreshold !== -1 &&
typeof d?.usage_percent === "number" &&
d?.usage_percent > diskThreshold
) ?? false,
};
const alertsToSend = [];
const alertTypes = ["cpu", "memory", "disk"];
for (const type of alertTypes) {
// Iterate over each alert type to see if any need to be decremented
if (alerts[type] === true) {
monitor[`${type}AlertThreshold`]--; // Decrement threshold if an alert is triggered
if (monitor[`${type}AlertThreshold`] <= 0) {
// If threshold drops below 0, reset and send notification
monitor[`${type}AlertThreshold`] = monitor.alertThreshold;
const formatAlert = {
cpu: () =>
`Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
memory: () =>
`Your current memory usage (${(memoryUsage * 100).toFixed(0)}%) is above your threshold (${(memoryThreshold * 100).toFixed(0)}%)`,
disk: () =>
`Your current disk usage: ${disk
.map((d, idx) => `(Disk${idx}: ${(d.usage_percent * 100).toFixed(0)}%)`)
.join(
", "
)} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
};
alertsToSend.push(formatAlert[type]());
}
}
}
await monitor.save();
return alertsToSend;
};
buildHardwareEmail = async (networkResponse, alerts) => {
const { monitor } = networkResponse;
const template = "hardwareIncidentTemplate";
const context = { monitor: monitor.name, url: monitor.url, alerts };
const subject = `Monitor ${monitor.name} infrastructure alerts`;
const html = await this.emailService.buildEmail(template, context);
return { subject, html };
};
buildHardwareNotificationMessage = (alerts) => {
return alerts.map((alert) => alert).join("\n");
};
}
export default NotificationUtils;
+16
View File
@@ -276,6 +276,10 @@ class StringService {
return this.translationService.getTranslation("queueGetMetrics");
}
get queueGetJobs() {
return this.translationService.getTranslation("queueGetJobs");
}
get queueAddJob() {
return this.translationService.getTranslation("queueAddJob");
}
@@ -432,6 +436,18 @@ class StringService {
get testEmailSubject() {
return this.translationService.getTranslation("testEmailSubject");
}
get verifyOwnerNotFound() {
return this.translationService.getTranslation("verifyOwnerNotFound");
}
get verifyOwnerUnauthorized() {
return this.translationService.getTranslation("verifyOwnerUnauthorized");
}
get dbUserNotFound() {
return this.translationService.getTranslation("dbUserNotFound");
}
}
export default StringService;
+33 -18
View File
@@ -4,6 +4,8 @@ dotenv.config();
class Logger {
constructor() {
this.logCache = [];
this.maxCacheSize = 1000;
const consoleFormat = format.printf(
({ level, message, service, method, details, timestamp, stack }) => {
if (message instanceof Object) {
@@ -72,11 +74,9 @@ class Logger {
* @param {Object} config.details - Additional details.
*/
info(config) {
this.logger.info(config.message, {
service: config.service,
method: config.method,
details: config.details,
});
const logEntry = this.buildLogEntry("info", config);
this.cacheLog(logEntry);
this.logger.info(config.message, logEntry);
}
/**
@@ -88,11 +88,9 @@ class Logger {
* @param {Object} config.details - Additional details.
*/
warn(config) {
this.logger.warn(config.message, {
service: config.service,
method: config.method,
details: config.details,
});
const logEntry = this.buildLogEntry("warn", config);
this.cacheLog(logEntry);
this.logger.warn(config.message, logEntry);
}
/**
@@ -104,12 +102,9 @@ class Logger {
* @param {Object} config.details - Additional details.
*/
error(config) {
this.logger.error(config.message, {
service: config.service,
method: config.method,
details: config.details,
stack: config.stack,
});
const logEntry = this.buildLogEntry("error", config);
this.cacheLog(logEntry);
this.logger.error(config.message, logEntry);
}
/**
* Logs a debug message.
@@ -120,12 +115,32 @@ class Logger {
* @param {Object} config.details - Additional details.
*/
debug(config) {
this.logger.debug(config.message, {
const logEntry = this.buildLogEntry("debug", config);
this.cacheLog(logEntry);
this.logger.debug(config.message, logEntry);
}
cacheLog(entry) {
this.logCache.push(entry);
if (this.logCache.length > this.maxCacheSize) {
this.logCache.shift();
}
}
getLogs() {
return this.logCache;
}
buildLogEntry(level, config) {
return {
level,
message: config.message,
service: config.service,
method: config.method,
details: config.details,
stack: config.stack,
});
timestamp: new Date().toISOString(),
};
}
}
+9 -17
View File
@@ -478,6 +478,7 @@ const createStatusPageBodyValidation = joi.object({
isPublished: joi.boolean(),
showCharts: joi.boolean().optional(),
showUptimePercentage: joi.boolean(),
showAdminLoginLink: joi.boolean().optional(),
});
const imageValidation = joi
@@ -585,24 +586,15 @@ const createNotificationBodyValidation = joi.object({
"string.email": "Please enter a valid e-mail address",
}),
}),
type: joi.string().valid("email", "webhook", "pager_duty").required().messages({
"string.empty": "Notification type is required",
"any.required": "Notification type is required",
"any.only": "Notification type must be email, webhook, or pager_duty",
}),
config: joi.when("type", {
is: "webhook",
then: joi.object({
webhookUrl: joi.string().uri().required().messages({
"string.uri": "Webhook URL must be a valid URI",
"any.required": "Webhook URL is required",
}),
platform: joi.string().required().messages({
"string.empty": "Platform is required",
"any.required": "Platform is required",
}),
type: joi
.string()
.valid("email", "webhook", "slack", "discord", "pager_duty")
.required()
.messages({
"string.empty": "Notification type is required",
"any.required": "Notification type is required",
"any.only": "Notification type must be email, webhook, or pager_duty",
}),
}),
});
//****************************************