This commit is contained in:
Alex Holliday committed 2025-07-21 10:34:16 -07:00
1 parent 846564a17e
commit bfa6832beb
83 files changed
+338 -1249

No files matched your search

+1 -5
View File
@@ -150,11 +150,7 @@ class JobQueue {
};
const schedulerId = getSchedulerId(monitor);
await queue.upsertJobScheduler(
schedulerId,
{ every: monitor?.interval ?? 60000 },
jobTemplate
);
await queue.upsertJobScheduler(schedulerId, { every: monitor?.interval ?? 60000 }, jobTemplate);
}
async deleteJob(monitor) {
+2 -15
View File
@@ -1,16 +1,7 @@
const SERVICE_NAME = "JobQueueHelper";
class JobQueueHelper {
constructor({
redisService,
Queue,
Worker,
logger,
db,
networkService,
statusService,
notificationService,
}) {
constructor({ redisService, Queue, Worker, logger, db, networkService, statusService, notificationService }) {
this.db = db;
this.redisService = redisService;
this.Queue = Queue;
@@ -265,11 +256,7 @@ class JobQueueHelper {
// Handle status change
await job.updateProgress(60);
const {
monitor: updatedMonitor,
statusChanged,
prevStatus,
} = await this.statusService.updateStatus(networkResponse);
const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse);
// Handle notifications
await job.updateProgress(80);
this.notificationService
+2 -5
View File
@@ -22,8 +22,7 @@ class PulseQueue {
// ****************************************
init = async () => {
try {
const mongoConnectionString =
this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
const mongoConnectionString = this.appSettings.dbConnectionString || "mongodb://localhost:27017/uptime_db";
this.pulse = new Pulse({ db: { address: mongoConnectionString } });
await this.pulse.start();
this.pulse.define("monitor-job", this.pulseQueueHelper.getMonitorJob(), {});
@@ -186,9 +185,7 @@ class PulseQueue {
failReason: job.attrs.failReason,
lastRunAt: job.attrs.lastRunAt,
lastFinishedAt: job.attrs.lastFinishedAt,
lastRunTook: job.attrs.lockedAt
? null
: job.attrs.lastFinishedAt - job.attrs.lastRunAt,
lastRunTook: job.attrs.lockedAt ? null : job.attrs.lastFinishedAt - job.attrs.lastRunAt,
lastFailedAt: job.attrs.failedAt,
};
});
@@ -34,11 +34,7 @@ class PulseQueueHelper {
throw new Error("No network response");
}
const {
monitor: updatedMonitor,
statusChanged,
prevStatus,
} = await this.statusService.updateStatus(networkResponse);
const { monitor: updatedMonitor, statusChanged, prevStatus } = await this.statusService.updateStatus(networkResponse);
this.notificationService
.handleNotifications({
+1 -4
View File
@@ -42,10 +42,7 @@ class EmailService {
*/
this.loadTemplate = (templateName) => {
try {
const templatePath = this.path.join(
__dirname,
`../templates/${templateName}.mjml`
);
const templatePath = this.path.join(__dirname, `../templates/${templateName}.mjml`);
const templateContent = this.fs.readFileSync(templatePath, "utf8");
return this.compile(templateContent);
} catch (error) {
+7 -28
View File
@@ -78,9 +78,7 @@ class NetworkService {
async requestPing(monitor) {
try {
const url = monitor.url;
const { response, responseTime, error } = await this.timeRequest(() =>
this.ping.promise.probe(url)
);
const { response, responseTime, error } = await this.timeRequest(() => this.ping.promise.probe(url));
const pingResponse = {
monitorId: monitor._id,
@@ -133,18 +131,7 @@ class NetworkService {
*/
async requestHttp(monitor) {
try {
const {
url,
secret,
_id,
name,
teamId,
type,
ignoreTlsErrors,
jsonPath,
matchMethod,
expectedValue,
} = monitor;
const { url, secret, _id, name, teamId, type, ignoreTlsErrors, jsonPath, matchMethod, expectedValue } = monitor;
const config = {};
secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` });
@@ -155,9 +142,7 @@ class NetworkService {
});
}
const { response, responseTime, error } = await this.timeRequest(() =>
this.axios.get(url, config)
);
const { response, responseTime, error } = await this.timeRequest(() => this.axios.get(url, config));
const httpResponse = {
monitorId: _id,
@@ -171,8 +156,7 @@ class NetworkService {
const code = error.response?.status || this.NETWORK_ERROR;
httpResponse.code = code;
httpResponse.status = false;
httpResponse.message =
this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
httpResponse.message = this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
return httpResponse;
}
@@ -227,9 +211,7 @@ class NetworkService {
else match = result === expectedValue;
httpResponse.status = match;
httpResponse.message = match
? this.stringService.httpMatchSuccess
: this.stringService.httpMatchFail;
httpResponse.message = match ? this.stringService.httpMatchSuccess : this.stringService.httpMatchFail;
return httpResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -320,9 +302,7 @@ class NetworkService {
}
const container = docker.getContainer(monitor.url);
const { response, responseTime, error } = await this.timeRequest(() =>
container.inspect()
);
const { response, responseTime, error } = await this.timeRequest(() => container.inspect());
const dockerResponse = {
monitorId: monitor._id,
@@ -333,8 +313,7 @@ class NetworkService {
if (error) {
dockerResponse.status = false;
dockerResponse.code = error.statusCode || this.NETWORK_ERROR;
dockerResponse.message =
error.reason || "Failed to fetch Docker container information";
dockerResponse.message = error.reason || "Failed to fetch Docker container information";
return dockerResponse;
}
dockerResponse.status = response?.State?.Status === "running" ? true : false;
+4 -16
View File
@@ -3,14 +3,7 @@ const SERVICE_NAME = "NotificationService";
class NotificationService {
static SERVICE_NAME = SERVICE_NAME;
constructor({
emailService,
db,
logger,
networkService,
stringService,
notificationUtils,
}) {
constructor({ emailService, db, logger, networkService, stringService, notificationUtils }) {
this.emailService = emailService;
this.db = db;
this.logger = logger;
@@ -69,20 +62,15 @@ class NotificationService {
const alerts = await this.notificationUtils.buildHardwareAlerts(networkResponse);
if (alerts.length === 0) return false;
const { subject, html } = await this.notificationUtils.buildHardwareEmail(
networkResponse,
alerts
);
const content =
await this.notificationUtils.buildHardwareNotificationMessage(alerts);
const { subject, html } = await this.notificationUtils.buildHardwareEmail(networkResponse, alerts);
const content = await this.notificationUtils.buildHardwareNotificationMessage(alerts);
const success = await this.notifyAll({ notificationIDs, subject, html, content });
return success;
}
// Status monitors
const { subject, html } =
await this.notificationUtils.buildStatusEmail(networkResponse);
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;
+7 -29
View File
@@ -26,10 +26,7 @@ class NotificationUtils {
const date = new Date(timestamp);
// Get timezone abbreviation and format the date
const timeZoneAbbr = date
.toLocaleTimeString("en-US", { timeZoneName: "short" })
.split(" ")
.pop();
const timeZoneAbbr = date.toLocaleTimeString("en-US", { timeZoneName: "short" }).split(" ").pop();
// Format the date with readable format
return (
@@ -50,9 +47,7 @@ class NotificationUtils {
};
// Get formatted time
const formattedTime = timestamp
? formatTime(timestamp)
: formatTime(new Date().getTime());
const formattedTime = timestamp ? formatTime(timestamp) : formatTime(new Date().getTime());
// Create different messages based on status with extra spacing
let messageText;
@@ -73,29 +68,15 @@ class NotificationUtils {
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 { 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 { 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,
disk: disk?.some((d) => diskThreshold !== -1 && typeof d?.usage_percent === "number" && d?.usage_percent > diskThreshold) ?? false,
};
const alertsToSend = [];
@@ -110,16 +91,13 @@ class NotificationUtils {
monitor[`${type}AlertThreshold`] = monitor.alertThreshold;
const formatAlert = {
cpu: () =>
`Your current CPU usage (${(cpuUsage * 100).toFixed(0)}%) is above your threshold (${(cpuThreshold * 100).toFixed(0)}%)`,
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)}%)`,
.join(", ")} is above your threshold (${(diskThreshold * 100).toFixed(0)}%)`,
};
alertsToSend.push(formatAlert[type]());
}
+2 -6
View File
@@ -62,14 +62,10 @@ class SettingsService {
// Remove any old settings
await this.AppSettings.deleteMany({ version: { $exists: false } });
let settings = await this.AppSettings.findOne({ singleton: true })
.select("-__v -_id -createdAt -updatedAt -singleton")
.lean();
let settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
if (settings === null) {
await this.AppSettings.create({});
settings = await this.AppSettings.findOne({ singleton: true })
.select("-__v -_id -createdAt -updatedAt -singleton")
.lean();
settings = await this.AppSettings.findOne({ singleton: true }).select("-__v -_id -createdAt -updatedAt -singleton").lean();
}
return settings;
}
+3 -9
View File
@@ -48,9 +48,7 @@ class StatusService {
if (avgResponseTime === 0) {
avgResponseTime = responseTime;
} else {
avgResponseTime =
(avgResponseTime * (stats.totalChecks - 1) + responseTime) /
stats.totalChecks;
avgResponseTime = (avgResponseTime * (stats.totalChecks - 1) + responseTime) / stats.totalChecks;
}
}
stats.avgResponseTime = avgResponseTime;
@@ -138,9 +136,7 @@ class StatusService {
// Monitor status changed, save prev status and update monitor
this.logger.info({
service: this.SERVICE_NAME,
message: `${monitor.name} went from ${this.getStatusString(
monitor.status
)} to ${this.getStatusString(status)}`,
message: `${monitor.name} went from ${this.getStatusString(monitor.status)} to ${this.getStatusString(status)}`,
prevStatus: monitor.status,
newStatus: status,
});
@@ -279,9 +275,7 @@ class StatusService {
message: error.message,
service: error.service || this.SERVICE_NAME,
method: error.method || "insertCheck",
details:
error.details ||
`Error inserting check for monitor: ${networkResponse?.monitorId}`,
details: error.details || `Error inserting check for monitor: ${networkResponse?.monitorId}`,
stack: error.stack,
});
}
+5 -16
View File
@@ -211,23 +211,16 @@ class StringService {
}
getWebhookUnsupportedPlatform(platform) {
return this.translationService
.getTranslation("webhookUnsupportedPlatform")
.replace("{platform}", platform);
return this.translationService.getTranslation("webhookUnsupportedPlatform").replace("{platform}", platform);
}
getWebhookSendError(platform) {
return this.translationService
.getTranslation("webhookSendError")
.replace("{platform}", platform);
return this.translationService.getTranslation("webhookSendError").replace("{platform}", platform);
}
getMonitorStatus(name, status, url) {
const translationKey = status === true ? "monitorStatusUp" : "monitorStatusDown";
return this.translationService
.getTranslation(translationKey)
.replace("{name}", name)
.replace("{url}", url);
return this.translationService.getTranslation(translationKey).replace("{name}", name).replace("{url}", url);
}
// Error Messages
@@ -378,9 +371,7 @@ class StringService {
}
getDeletedCount(count) {
return this.translationService
.getTranslation("deletedCount")
.replace("{count}", count);
return this.translationService.getTranslation("deletedCount").replace("{count}", count);
}
get pingSuccess() {
@@ -424,9 +415,7 @@ class StringService {
}
getDbFindMonitorById(monitorId) {
return this.translationService
.getTranslation("dbFindMonitorById")
.replace("${monitorId}", monitorId);
return this.translationService.getTranslation("dbFindMonitorById").replace("${monitorId}", monitorId);
}
get dbUserExists() {
+1 -3
View File
@@ -38,9 +38,7 @@ class TranslationService {
return false;
}
const files = fs
.readdirSync(this.localesDir)
.filter((file) => file.endsWith(".json"));
const files = fs.readdirSync(this.localesDir).filter((file) => file.endsWith(".json"));
if (files.length === 0) {
return false;