Merge branch 'develop' into fix/missing-be-validation
This commit is contained in:
18 files changed
+448
-158
No files matched your search
@@ -9,6 +9,8 @@ const {
|
||||
getMonitorStatsByIdParamValidation,
|
||||
getMonitorStatsByIdQueryValidation,
|
||||
getCertificateParamValidation,
|
||||
getMonitorAggregateStatsParamValidation,
|
||||
getMonitorAggregateStatsQueryValidation,
|
||||
} = require("../validation/joi");
|
||||
|
||||
const sslChecker = require("ssl-checker");
|
||||
@@ -37,6 +39,44 @@ const getAllMonitors = async (req, res, next) => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns agregate stats for a monitor
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
* @param {Express.Response} res
|
||||
* @returns {Promise<Express.Response>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
|
||||
const getMonitorAggregateStats = async (req, res, next) => {
|
||||
try {
|
||||
await getMonitorAggregateStatsParamValidation.validateAsync(req.params);
|
||||
await getMonitorAggregateStatsQueryValidation.validateAsync(req.query);
|
||||
} catch (error) {
|
||||
error.status = 422;
|
||||
error.message =
|
||||
error.details?.[0]?.message || error.message || "Validation Error";
|
||||
next(error);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { monitorId } = req.params;
|
||||
const dateRange = req.query.dateRange;
|
||||
const aggregateStats = await req.db.getMonitorAggregateStats(
|
||||
monitorId,
|
||||
dateRange
|
||||
);
|
||||
return res.json({
|
||||
success: true,
|
||||
msg: successMessages.MONTIOR_STATS_BY_ID,
|
||||
data: aggregateStats,
|
||||
});
|
||||
} catch (error) {
|
||||
next(error);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns monitor stats for monitor with matching ID
|
||||
* @async
|
||||
@@ -362,6 +402,7 @@ const pauseMonitor = async (req, res, next) => {
|
||||
await req.jobQueue.addJob(monitor._id, monitor);
|
||||
}
|
||||
monitor.isActive = !monitor.isActive;
|
||||
monitor.status = undefined;
|
||||
monitor.save();
|
||||
return res.status(200).json({
|
||||
success: true,
|
||||
@@ -379,6 +420,7 @@ const pauseMonitor = async (req, res, next) => {
|
||||
|
||||
module.exports = {
|
||||
getAllMonitors,
|
||||
getMonitorAggregateStats,
|
||||
getMonitorStatsById,
|
||||
getMonitorCertificate,
|
||||
getMonitorById,
|
||||
|
||||
@@ -64,6 +64,7 @@ const {
|
||||
|
||||
const {
|
||||
getAllMonitors,
|
||||
getMonitorAggregateStats,
|
||||
getMonitorStatsById,
|
||||
getMonitorById,
|
||||
getMonitorsByTeamId,
|
||||
@@ -144,6 +145,7 @@ module.exports = {
|
||||
resetPassword,
|
||||
checkSuperadmin,
|
||||
getAllMonitors,
|
||||
getMonitorAggregateStats,
|
||||
getMonitorStatsById,
|
||||
getMonitorById,
|
||||
getMonitorsByTeamId,
|
||||
|
||||
@@ -143,6 +143,87 @@ const getStatusBarValues = (monitor, checks) => {
|
||||
}
|
||||
return statusBarValues.reverse();
|
||||
};
|
||||
|
||||
/**
|
||||
* Get aggregate monitor stats for charts
|
||||
* @async
|
||||
* @param {Express.Request} req
|
||||
* @param {Express.Response} res
|
||||
* @returns {Promise<Monitor>}
|
||||
* @throws {Error}
|
||||
*/
|
||||
const getMonitorAggregateStats = async (monitorId, dateRange) => {
|
||||
const startDates = {
|
||||
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)),
|
||||
};
|
||||
|
||||
try {
|
||||
const startDate = startDates[dateRange];
|
||||
if (!startDate) {
|
||||
throw new Error("Invalid date range specified");
|
||||
}
|
||||
const endDate = new Date();
|
||||
|
||||
const checks = await Check.find({
|
||||
monitorId: monitorId,
|
||||
createdAt: {
|
||||
$gte: startDate,
|
||||
$lte: endDate,
|
||||
},
|
||||
});
|
||||
|
||||
let groupedChecks;
|
||||
// Group checks by hour if range is day
|
||||
if (dateRange === "day") {
|
||||
groupedChecks = checks.reduce((acc, check) => {
|
||||
const hour = new Date(check.createdAt).getHours();
|
||||
if (!acc[hour]) {
|
||||
acc[hour] = { hour, checks: [] };
|
||||
}
|
||||
acc[hour].checks.push(check);
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
// Group checks by day if range is week or month
|
||||
else {
|
||||
groupedChecks = checks.reduce((acc, check) => {
|
||||
const day = new Date(check.createdAt).toISOString().split("T")[0]; // Extract the date part
|
||||
if (!acc[day]) {
|
||||
acc[day] = { day, checks: [] };
|
||||
}
|
||||
acc[day].checks.push(check);
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
|
||||
// Map grouped checks to stats
|
||||
stats = Object.values(groupedChecks).map((group) => {
|
||||
const totalChecks = group.checks.length;
|
||||
const totalIncidents = group.checks.filter(
|
||||
(check) => check.status === false
|
||||
).length;
|
||||
const avgResponseTime =
|
||||
group.checks.reduce((sum, check) => sum + check.responseTime, 0) /
|
||||
totalChecks;
|
||||
|
||||
return {
|
||||
hour: group.hour,
|
||||
day: group.day,
|
||||
totalChecks,
|
||||
totalIncidents,
|
||||
avgResponseTime,
|
||||
};
|
||||
});
|
||||
|
||||
return stats;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get stats by monitor ID
|
||||
* @async
|
||||
@@ -200,6 +281,10 @@ const getMonitorStatsById = async (req) => {
|
||||
...checksQuery,
|
||||
createdAt: { $gte: filterLookup.day },
|
||||
};
|
||||
const checksQuery7Days = {
|
||||
...checksQuery,
|
||||
createdAt: { $gte: filterLookup.week },
|
||||
};
|
||||
const checksQuery30Days = {
|
||||
...checksQuery,
|
||||
createdAt: { $gte: filterLookup.month },
|
||||
@@ -209,15 +294,18 @@ const getMonitorStatsById = async (req) => {
|
||||
createdAt: { $gte: filterLookup.hour },
|
||||
};
|
||||
|
||||
const [checks24Hours, checks30Days, checks60Mins] = await Promise.all([
|
||||
model.find(checksQuery24Hours).sort({ createdAt: sortOrder }),
|
||||
model.find(checksQuery30Days).sort({ createdAt: sortOrder }),
|
||||
model.find(checksQuery60Mins).sort({ createdAt: sortOrder }),
|
||||
]);
|
||||
const [checks24Hours, checks7Days, checks30Days, checks60Mins] =
|
||||
await Promise.all([
|
||||
model.find(checksQuery24Hours).sort({ createdAt: sortOrder }),
|
||||
model.find(checksQuery7Days).sort({ createdAt: sortOrder }),
|
||||
model.find(checksQuery30Days).sort({ createdAt: sortOrder }),
|
||||
model.find(checksQuery60Mins).sort({ createdAt: sortOrder }),
|
||||
]);
|
||||
|
||||
// HTTP/PING Specific stats
|
||||
monitorStats.avgResponseTime24hours =
|
||||
getAverageResponseTime24Hours(checks24Hours);
|
||||
monitorStats.uptime7Days = getUptimePercentage(checks7Days);
|
||||
monitorStats.uptime24Hours = getUptimePercentage(checks24Hours);
|
||||
monitorStats.uptime30Days = getUptimePercentage(checks30Days);
|
||||
monitorStats.statusBar = getStatusBarValues(monitor, checks60Mins);
|
||||
@@ -452,6 +540,7 @@ const editMonitor = async (candidateId, candidateMonitor) => {
|
||||
|
||||
module.exports = {
|
||||
getAllMonitors,
|
||||
getMonitorAggregateStats,
|
||||
getMonitorStatsById,
|
||||
getMonitorById,
|
||||
getMonitorsByTeamId,
|
||||
|
||||
@@ -24,7 +24,7 @@ const MonitorSchema = mongoose.Schema(
|
||||
},
|
||||
status: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
default: undefined,
|
||||
},
|
||||
type: {
|
||||
type: String,
|
||||
@@ -46,7 +46,7 @@ const MonitorSchema = mongoose.Schema(
|
||||
},
|
||||
uptimePercentage: {
|
||||
type: Number,
|
||||
default: undefined,
|
||||
default: undefined,
|
||||
},
|
||||
notifications: [
|
||||
{
|
||||
|
||||
@@ -3,6 +3,7 @@ const monitorController = require("../controllers/monitorController");
|
||||
const { isAllowed } = require("../middleware/isAllowed");
|
||||
|
||||
router.get("/", monitorController.getAllMonitors);
|
||||
router.get("/aggregate/:monitorId", monitorController.getMonitorAggregateStats);
|
||||
router.get("/stats/:monitorId", monitorController.getMonitorStatsById);
|
||||
router.get("/certificate/:monitorId", monitorController.getMonitorCertificate);
|
||||
router.get("/:monitorId", monitorController.getMonitorById);
|
||||
|
||||
@@ -238,7 +238,6 @@ class JobQueue {
|
||||
console.log("Adding job", payload.url);
|
||||
// Execute job immediately
|
||||
await this.queue.add(jobName, payload);
|
||||
|
||||
await this.queue.add(jobName, payload, {
|
||||
repeat: {
|
||||
every: payload.interval,
|
||||
|
||||
@@ -15,44 +15,60 @@ class NetworkService {
|
||||
this.NETWORK_ERROR = 5000;
|
||||
}
|
||||
|
||||
async handleNotification(job, isAlive) {
|
||||
async handleNotification(monitor, isAlive) {
|
||||
try {
|
||||
const { _id } = job.data;
|
||||
const monitor = await this.db.getMonitorById(_id);
|
||||
if (monitor === null || monitor === undefined) {
|
||||
logger.error(`Null Monitor: ${_id}`, {
|
||||
method: "handleNotification",
|
||||
service: this.SERVICE_NAME,
|
||||
jobId: job.id,
|
||||
});
|
||||
return;
|
||||
}
|
||||
let template =
|
||||
isAlive === true ? "serverIsUpTemplate" : "serverIsDownTemplate";
|
||||
let status = isAlive === true ? "up" : "down";
|
||||
|
||||
// If monitor status changes, update monitor status and send notification
|
||||
if (monitor.status !== isAlive) {
|
||||
monitor.status = !monitor.status;
|
||||
await monitor.save();
|
||||
|
||||
let template =
|
||||
isAlive === true ? "serverIsUpTemplate" : "serverIsDownTemplate";
|
||||
let status = isAlive === true ? "up" : "down";
|
||||
|
||||
const notifications = await this.db.getNotificationsByMonitorId(_id);
|
||||
for (const notification of notifications) {
|
||||
if (notification.type === "email") {
|
||||
await this.emailService.buildAndSendEmail(
|
||||
template,
|
||||
{ monitorName: monitor.name, monitorUrl: monitor.url },
|
||||
notification.address,
|
||||
`Monitor ${monitor.name} is ${status}`
|
||||
);
|
||||
}
|
||||
const notifications = await this.db.getNotificationsByMonitorId(
|
||||
monitor._id
|
||||
);
|
||||
for (const notification of notifications) {
|
||||
if (notification.type === "email") {
|
||||
await this.emailService.buildAndSendEmail(
|
||||
template,
|
||||
{ monitorName: monitor.name, monitorUrl: monitor.url },
|
||||
notification.address,
|
||||
`Monitor ${monitor.name} is ${status}`
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error.message, {
|
||||
method: "handleNotification",
|
||||
service: this.SERVICE_NAME,
|
||||
monitorId: monitor._id,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleStatusUpdate(job, isAlive) {
|
||||
try {
|
||||
const { _id } = job.data;
|
||||
const monitor = await this.db.getMonitorById(_id);
|
||||
|
||||
if (monitor === null || monitor === undefined) {
|
||||
logger.error(`Null Monitor: ${_id}`, {
|
||||
method: "handleStatusUpdate",
|
||||
service: this.SERVICE_NAME,
|
||||
jobId: job.id,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (monitor.status === undefined || monitor.status !== isAlive) {
|
||||
const oldStatus = monitor.status;
|
||||
monitor.status = isAlive;
|
||||
await monitor.save();
|
||||
|
||||
if (oldStatus !== undefined && oldStatus !== isAlive) {
|
||||
this.handleNotification(monitor, isAlive);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error.message, {
|
||||
method: "handleStatusUpdate",
|
||||
service: this.SERVICE_NAME,
|
||||
jobId: job.id,
|
||||
});
|
||||
}
|
||||
@@ -113,7 +129,7 @@ class NetworkService {
|
||||
};
|
||||
return await this.logAndStoreCheck(checkData, this.db.createCheck);
|
||||
} finally {
|
||||
this.handleNotification(job, isAlive);
|
||||
this.handleStatusUpdate(job, isAlive);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -161,7 +177,7 @@ class NetworkService {
|
||||
|
||||
return await this.logAndStoreCheck(checkData, this.db.createCheck);
|
||||
} finally {
|
||||
this.handleNotification(job, isAlive);
|
||||
this.handleStatusUpdate(job, isAlive);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,7 +257,7 @@ class NetworkService {
|
||||
};
|
||||
this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck);
|
||||
} finally {
|
||||
this.handleNotification(job, isAlive);
|
||||
this.handleStatusUpdate(job, isAlive);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -218,6 +218,13 @@ const pauseMonitorParamValidation = joi.object({
|
||||
monitorId: joi.string().required(),
|
||||
});
|
||||
|
||||
const getMonitorAggregateStatsParamValidation = joi.object({
|
||||
monitorId: joi.string().required(),
|
||||
});
|
||||
const getMonitorAggregateStatsQueryValidation = joi.object({
|
||||
dateRange: joi.string().valid("day", "week", "month"),
|
||||
});
|
||||
|
||||
//****************************************
|
||||
// Alerts
|
||||
//****************************************
|
||||
@@ -377,6 +384,8 @@ module.exports = {
|
||||
getMonitorStatsByIdParamValidation,
|
||||
getMonitorStatsByIdQueryValidation,
|
||||
getCertificateParamValidation,
|
||||
getMonitorAggregateStatsParamValidation,
|
||||
getMonitorAggregateStatsQueryValidation,
|
||||
editMonitorBodyValidation,
|
||||
pauseMonitorParamValidation,
|
||||
editUserParamValidation,
|
||||
|
||||
Reference in new issue
Block a user