restore repo structure
This commit is contained in:
1 parent
6df099a5b6
commit
8b7e3c650b
592 files changed
+37663
-127
No files matched your search
Executable
+95
@@ -0,0 +1,95 @@
|
||||
const SERVICE_NAME = "BufferService";
|
||||
const BUFFER_TIMEOUT = 1000 * 60 * 1; // 1 minute
|
||||
const TYPE_MAP = {
|
||||
http: "checks",
|
||||
ping: "checks",
|
||||
port: "checks",
|
||||
docker: "checks",
|
||||
pagespeed: "pagespeedChecks",
|
||||
hardware: "hardwareChecks",
|
||||
distributed_http: "distributedChecks",
|
||||
};
|
||||
|
||||
class BufferService {
|
||||
constructor({ db, logger }) {
|
||||
this.db = db;
|
||||
this.logger = logger;
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.buffers = {
|
||||
checks: [],
|
||||
pagespeedChecks: [],
|
||||
hardwareChecks: [],
|
||||
distributedChecks: [],
|
||||
};
|
||||
this.OPERATION_MAP = {
|
||||
checks: this.db.createChecks,
|
||||
pagespeedChecks: this.db.createPageSpeedChecks,
|
||||
hardwareChecks: this.db.createHardwareChecks,
|
||||
distributedChecks: this.db.createDistributedChecks,
|
||||
};
|
||||
|
||||
this.scheduleNextFlush();
|
||||
this.logger.info({
|
||||
message: `Buffer service initialized, flushing every ${BUFFER_TIMEOUT / 1000}s`,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "constructor",
|
||||
});
|
||||
}
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
addToBuffer({ check, type }) {
|
||||
try {
|
||||
this.buffers[TYPE_MAP[type]].push(check);
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "addToBuffer",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
scheduleNextFlush() {
|
||||
this.bufferTimer = setTimeout(async () => {
|
||||
try {
|
||||
await this.flushBuffers();
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: `Error in flush cycle: ${error.message}`,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "scheduleNextFlush",
|
||||
stack: error.stack,
|
||||
});
|
||||
} finally {
|
||||
// Schedule the next flush only after the current one completes
|
||||
this.scheduleNextFlush();
|
||||
}
|
||||
}, BUFFER_TIMEOUT);
|
||||
}
|
||||
async flushBuffers() {
|
||||
let items = 0;
|
||||
for (const [bufferName, buffer] of Object.entries(this.buffers)) {
|
||||
items += buffer.length;
|
||||
const operation = this.OPERATION_MAP[bufferName];
|
||||
if (!operation) {
|
||||
this.logger.error({
|
||||
message: `No operation found for ${bufferName}`,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "flushBuffers",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
await operation(buffer);
|
||||
this.buffers[bufferName] = [];
|
||||
}
|
||||
this.logger.info({
|
||||
message: `Flushed ${items} items`,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "flushBuffers",
|
||||
});
|
||||
items = 0;
|
||||
}
|
||||
}
|
||||
|
||||
export default BufferService;
|
||||
Executable
+145
@@ -0,0 +1,145 @@
|
||||
import { fileURLToPath } from "url";
|
||||
import path from "path";
|
||||
|
||||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
const SERVICE_NAME = "EmailService";
|
||||
|
||||
/**
|
||||
* Represents an email service that can load templates, build, and send emails.
|
||||
*/
|
||||
class EmailService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
/**
|
||||
* Constructs an instance of the EmailService, initializing template loaders and the email transporter.
|
||||
* @param {Object} settingsService - The settings service to get email configuration.
|
||||
* @param {Object} fs - The file system module.
|
||||
* @param {Object} path - The path module.
|
||||
* @param {Function} compile - The Handlebars compile function.
|
||||
* @param {Function} mjml2html - The MJML to HTML conversion function.
|
||||
* @param {Object} nodemailer - The nodemailer module.
|
||||
* @param {Object} logger - The logger module.
|
||||
*/
|
||||
constructor(settingsService, fs, path, compile, mjml2html, nodemailer, logger) {
|
||||
this.settingsService = settingsService;
|
||||
this.fs = fs;
|
||||
this.path = path;
|
||||
this.compile = compile;
|
||||
this.mjml2html = mjml2html;
|
||||
this.nodemailer = nodemailer;
|
||||
this.logger = logger;
|
||||
|
||||
/**
|
||||
* Loads an email template from the filesystem.
|
||||
*
|
||||
* @param {string} templateName - The name of the template to load.
|
||||
* @returns {Function} A compiled template function that can be used to generate HTML email content.
|
||||
*/
|
||||
this.loadTemplate = (templateName) => {
|
||||
try {
|
||||
const templatePath = this.path.join(
|
||||
__dirname,
|
||||
`../templates/${templateName}.mjml`
|
||||
);
|
||||
const templateContent = this.fs.readFileSync(templatePath, "utf8");
|
||||
return this.compile(templateContent);
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "loadTemplate",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A lookup object to access preloaded email templates.
|
||||
* @type {Object.<string, Function>}
|
||||
* TODO Load less used templates in their respective functions
|
||||
*/
|
||||
this.templateLookup = {
|
||||
welcomeEmailTemplate: this.loadTemplate("welcomeEmail"),
|
||||
employeeActivationTemplate: this.loadTemplate("employeeActivation"),
|
||||
noIncidentsThisWeekTemplate: this.loadTemplate("noIncidentsThisWeek"),
|
||||
serverIsDownTemplate: this.loadTemplate("serverIsDown"),
|
||||
serverIsUpTemplate: this.loadTemplate("serverIsUp"),
|
||||
passwordResetTemplate: this.loadTemplate("passwordReset"),
|
||||
hardwareIncidentTemplate: this.loadTemplate("hardwareIncident"),
|
||||
};
|
||||
|
||||
/**
|
||||
* The email transporter used to send emails.
|
||||
* @type {Object}
|
||||
*/
|
||||
|
||||
const {
|
||||
systemEmailHost,
|
||||
systemEmailPort,
|
||||
systemEmailUser,
|
||||
systemEmailAddress,
|
||||
systemEmailPassword,
|
||||
} = this.settingsService.getSettings();
|
||||
|
||||
const emailConfig = {
|
||||
host: systemEmailHost,
|
||||
port: systemEmailPort,
|
||||
secure: true,
|
||||
auth: {
|
||||
user: systemEmailUser || systemEmailAddress,
|
||||
pass: systemEmailPassword,
|
||||
},
|
||||
};
|
||||
|
||||
this.transporter = this.nodemailer.createTransport(emailConfig);
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronously builds and sends an email using a specified template and context.
|
||||
*
|
||||
* @param {string} template - The name of the template to use for the email body.
|
||||
* @param {Object} context - The data context to render the template with.
|
||||
* @param {string} to - The recipient's email address.
|
||||
* @param {string} subject - The subject of the email.
|
||||
* @returns {Promise<string>} A promise that resolves to the messageId of the sent email.
|
||||
*/
|
||||
buildAndSendEmail = async (template, context, to, subject) => {
|
||||
const buildHtml = async (template, context) => {
|
||||
try {
|
||||
const mjml = this.templateLookup[template](context);
|
||||
const html = await this.mjml2html(mjml);
|
||||
return html.html;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "buildAndSendEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const sendEmail = async (to, subject, html) => {
|
||||
try {
|
||||
const info = await this.transporter.sendMail({
|
||||
to: to,
|
||||
subject: subject,
|
||||
html: html,
|
||||
});
|
||||
return info;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "sendEmail",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
const html = await buildHtml(template, context);
|
||||
const info = await sendEmail(to, subject, html);
|
||||
return info?.messageId;
|
||||
};
|
||||
}
|
||||
export default EmailService;
|
||||
Executable
+818
@@ -0,0 +1,818 @@
|
||||
import IORedis from "ioredis";
|
||||
|
||||
const QUEUE_NAMES = ["uptime", "pagespeed", "hardware", "distributed"];
|
||||
const SERVICE_NAME = "JobQueue";
|
||||
const JOBS_PER_WORKER = 5;
|
||||
const HEALTH_CHECK_INTERVAL = 10 * 60 * 1000; // 10 minutes
|
||||
const QUEUE_LOOKUP = {
|
||||
hardware: "hardware",
|
||||
http: "uptime",
|
||||
ping: "uptime",
|
||||
port: "uptime",
|
||||
docker: "uptime",
|
||||
pagespeed: "pagespeed",
|
||||
distributed_http: "distributed",
|
||||
};
|
||||
const getSchedulerId = (monitor) => `scheduler:${monitor.type}:${monitor._id}`;
|
||||
|
||||
class NewJobQueue {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
constructor(
|
||||
db,
|
||||
statusService,
|
||||
networkService,
|
||||
notificationService,
|
||||
settingsService,
|
||||
stringService,
|
||||
logger,
|
||||
Queue,
|
||||
Worker
|
||||
) {
|
||||
const settings = settingsService.getSettings() || {};
|
||||
const { redisUrl } = settings;
|
||||
const connection = new IORedis(redisUrl, { maxRetriesPerRequest: null });
|
||||
this.queues = {};
|
||||
this.workers = {};
|
||||
this.lastJobProcessedTime = {};
|
||||
|
||||
this.connection = connection;
|
||||
this.db = db;
|
||||
this.networkService = networkService;
|
||||
this.statusService = statusService;
|
||||
this.notificationService = notificationService;
|
||||
this.settingsService = settingsService;
|
||||
this.logger = logger;
|
||||
this.Worker = Worker;
|
||||
this.stringService = stringService;
|
||||
|
||||
QUEUE_NAMES.forEach((name) => {
|
||||
const q = new Queue(name, { connection });
|
||||
this.lastJobProcessedTime[q.name] = Date.now();
|
||||
q.on("error", (error) => {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "queue:error",
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
this.queues[name] = q;
|
||||
|
||||
this.workers[name] = [];
|
||||
});
|
||||
|
||||
this.healthCheckInterval = setInterval(async () => {
|
||||
try {
|
||||
const health = await this.checkQueueHealth();
|
||||
if (health.stuck === true) {
|
||||
this.logger.error({
|
||||
message: `Queue is stuck: ${health.stuckQueues.join(", ")}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "healthCheckInterval",
|
||||
});
|
||||
await this.flushQueue();
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "periodicHealthCheck",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
}, HEALTH_CHECK_INTERVAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes job queues by adding jobs for all active monitors
|
||||
* @async
|
||||
* @function initJobQueue
|
||||
* @description Retrieves all monitors from the database and adds jobs for active ones to their respective queues
|
||||
* @throws {Error} If there's an error retrieving monitors or adding jobs
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initJobQueue() {
|
||||
await this.connection.flushall();
|
||||
const monitors = await this.db.getAllMonitors();
|
||||
await Promise.all(
|
||||
monitors
|
||||
.filter((monitor) => monitor.isActive)
|
||||
.map(async (monitor) => {
|
||||
try {
|
||||
await this.addJob(monitor._id, monitor);
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: `Failed to add job for monitor ${monitor._id}:`,
|
||||
service: SERVICE_NAME,
|
||||
method: "initJobQueue",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a monitor is currently in a maintenance window
|
||||
* @async
|
||||
* @param {string} monitorId - The ID of the monitor to check
|
||||
* @returns {Promise<boolean>} Returns true if the monitor is in an active maintenance window, false otherwise
|
||||
* @throws {Error} If there's an error retrieving maintenance windows from the database
|
||||
* @description
|
||||
* Retrieves all maintenance windows for a monitor and checks if any are currently active.
|
||||
* A maintenance window is considered active if:
|
||||
* 1. The window is marked as active AND
|
||||
* 2. Either:
|
||||
* - Current time falls between start and end times
|
||||
* - For repeating windows: Current time falls between any repeated interval
|
||||
*/
|
||||
async isInMaintenanceWindow(monitorId) {
|
||||
const maintenanceWindows = await this.db.getMaintenanceWindowsByMonitorId(monitorId);
|
||||
// Check for active maintenance window:
|
||||
const maintenanceWindowIsActive = maintenanceWindows.reduce((acc, window) => {
|
||||
if (window.active) {
|
||||
const start = new Date(window.start);
|
||||
const end = new Date(window.end);
|
||||
const now = new Date();
|
||||
const repeatInterval = window.repeat || 0;
|
||||
|
||||
// If start is < now and end > now, we're in maintenance
|
||||
if (start <= now && end >= now) return true;
|
||||
|
||||
// If maintenance window was set in the past with a repeat,
|
||||
// we need to advance start and end to see if we are in range
|
||||
|
||||
while (start < now && repeatInterval !== 0) {
|
||||
start.setTime(start.getTime() + repeatInterval);
|
||||
end.setTime(end.getTime() + repeatInterval);
|
||||
if (start <= now && end >= now) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return acc;
|
||||
}, false);
|
||||
return maintenanceWindowIsActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a job processing handler for monitor checks
|
||||
* @function createJobHandler
|
||||
* @returns {Function} An async function that processes monitor check jobs
|
||||
* @description
|
||||
* Creates and returns a job handler that:
|
||||
* 1. Checks if monitor is in maintenance window
|
||||
* 2. If not in maintenance, performs network status check
|
||||
* 3. Updates monitor status in database
|
||||
* 4. Triggers notifications if status changed
|
||||
*
|
||||
* @param {Object} job - The job to process
|
||||
* @param {Object} job.data - The monitor data
|
||||
* @param {string} job.data._id - Monitor ID
|
||||
* @param {string} job.id - Job ID
|
||||
*
|
||||
* @throws {Error} Logs errors but doesn't throw them to prevent job failure
|
||||
* @returns {Promise<void>} Resolves when job processing is complete
|
||||
*/
|
||||
createJobHandler() {
|
||||
return async (job) => {
|
||||
try {
|
||||
// Update the last job processed time for this queue
|
||||
this.lastJobProcessedTime[job.queue.name] = Date.now();
|
||||
// Get all maintenance windows for this monitor
|
||||
await job.updateProgress(0);
|
||||
const monitorId = job.data._id;
|
||||
const maintenanceWindowActive = await this.isInMaintenanceWindow(monitorId);
|
||||
// If a maintenance window is active, we're done
|
||||
|
||||
if (maintenanceWindowActive) {
|
||||
await job.updateProgress(100);
|
||||
this.logger.info({
|
||||
message: `Monitor ${monitorId} is in maintenance window`,
|
||||
service: SERVICE_NAME,
|
||||
method: "createWorker",
|
||||
});
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get the current status
|
||||
await job.updateProgress(30);
|
||||
const networkResponse = await this.networkService.getStatus(job);
|
||||
if (
|
||||
job.data.type === "distributed_http" ||
|
||||
job.data.type === "distributed_test"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
// Handle status change
|
||||
await job.updateProgress(60);
|
||||
const { monitor, statusChanged, prevStatus } =
|
||||
await this.statusService.updateStatus(networkResponse);
|
||||
// Handle notifications
|
||||
await job.updateProgress(80);
|
||||
this.notificationService
|
||||
.handleNotifications({
|
||||
...networkResponse,
|
||||
monitor,
|
||||
prevStatus,
|
||||
statusChanged,
|
||||
})
|
||||
.catch((error) => {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "createJobHandler",
|
||||
details: `Error sending notifications for job ${job.id}: ${error.message}`,
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
await job.updateProgress(100);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: error.service ?? SERVICE_NAME,
|
||||
method: error.method ?? "createJobHandler",
|
||||
details: `Error processing job ${job.id}: ${error.message}`,
|
||||
stack: error.stack,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new worker for processing jobs in a queue
|
||||
* @param {Queue} queue - The BullMQ queue to create a worker for
|
||||
* @returns {Worker} A new BullMQ worker instance
|
||||
* @description
|
||||
* Creates and configures a new worker with:
|
||||
* - Queue-specific job handler
|
||||
* - Redis connection settings
|
||||
* - Default worker options
|
||||
* The worker processes jobs from the specified queue using the job handler
|
||||
* created by createJobHandler()
|
||||
*
|
||||
* @throws {Error} If worker creation fails or connection is invalid
|
||||
*/
|
||||
createWorker(queue) {
|
||||
try {
|
||||
const worker = new this.Worker(queue.name, this.createJobHandler(), {
|
||||
connection: this.connection,
|
||||
concurrency: 5,
|
||||
stalledInterval: 10000,
|
||||
maxStalledCount: 1,
|
||||
lockDuration: 60000,
|
||||
});
|
||||
|
||||
worker.on("failed", (job, err) => {
|
||||
this.logger.error({
|
||||
message: `Job ${job.id} failed: ${err.message}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "worker:failed",
|
||||
stack: err.stack,
|
||||
jobData: job.data,
|
||||
});
|
||||
});
|
||||
worker.on("error", (job, err) => {
|
||||
this.logger.error({
|
||||
message: `Job ${job.id} error: ${err.message}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "worker:error",
|
||||
stack: err.stack,
|
||||
jobData: job.data,
|
||||
});
|
||||
});
|
||||
|
||||
worker.on("stalled", (jobId) => {
|
||||
this.logger.warn({
|
||||
message: `Job ${jobId} stalled`,
|
||||
service: SERVICE_NAME,
|
||||
method: "worker:stalled",
|
||||
});
|
||||
});
|
||||
|
||||
return worker;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "createWorker",
|
||||
stack: error.stack,
|
||||
});
|
||||
error.service = SERVICE_NAME;
|
||||
error.method = "createWorker";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets stats related to the workers
|
||||
* This is used for scaling workers right now
|
||||
* In the future we will likely want to scale based on server performance metrics
|
||||
* CPU Usage & memory usage, if too high, scale down workers.
|
||||
* When to scale up? If jobs are taking too long to complete?
|
||||
* @async
|
||||
* @returns {Promise<WorkerStats>} - Returns the worker stats
|
||||
*/
|
||||
async getWorkerStats(queue) {
|
||||
try {
|
||||
const jobs = await queue.getRepeatableJobs();
|
||||
const load = jobs.length / this.workers[queue.name].length;
|
||||
return { jobs, load };
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "getWorkerStats") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Scales workers up or down based on queue load
|
||||
* @async
|
||||
* @param {Object} workerStats - Statistics about current worker load
|
||||
* @param {number} workerStats.load - Current load per worker
|
||||
* @param {Array} workerStats.jobs - Array of current jobs
|
||||
* @param {Queue} queue - The BullMQ queue to scale workers for
|
||||
* @returns {Promise<boolean>} True if scaling occurred, false if no scaling was needed
|
||||
* @throws {Error} If no workers array exists for the queue
|
||||
* @description
|
||||
* Scales workers based on these rules:
|
||||
* - Maintains minimum of 5 workers
|
||||
* - Adds workers if load exceeds JOBS_PER_WORKER
|
||||
* - Removes workers if load is below JOBS_PER_WORKER
|
||||
* - Creates initial workers if none exist
|
||||
* Worker scaling is calculated based on excess jobs or excess capacity
|
||||
*/
|
||||
async scaleWorkers(workerStats, queue) {
|
||||
const workers = this.workers[queue.name];
|
||||
if (workers === undefined) {
|
||||
throw new Error(`No workers found for ${queue.name}`);
|
||||
}
|
||||
|
||||
if (workers.length === 0) {
|
||||
// There are no workers, need to add one
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const worker = this.createWorker(queue);
|
||||
workers.push(worker);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (workerStats.load > JOBS_PER_WORKER) {
|
||||
// Find out how many more jobs we have than current workers can handle
|
||||
const excessJobs = workerStats.jobs.length - workers.length * JOBS_PER_WORKER;
|
||||
// Divide by jobs/worker to find out how many workers to add
|
||||
const workersToAdd = Math.ceil(excessJobs / JOBS_PER_WORKER);
|
||||
for (let i = 0; i < workersToAdd; i++) {
|
||||
const worker = this.createWorker(queue);
|
||||
workers.push(worker);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if (workerStats.load < JOBS_PER_WORKER) {
|
||||
// Find out how much excess capacity we have
|
||||
const workerCapacity = workers.length * JOBS_PER_WORKER;
|
||||
const excessCapacity = workerCapacity - workerStats.jobs.length;
|
||||
// Calculate how many workers to remove
|
||||
let workersToRemove = Math.floor(excessCapacity / JOBS_PER_WORKER); // Make sure there are always at least 5
|
||||
while (workersToRemove > 0 && workers.length > 5) {
|
||||
const worker = workers.pop();
|
||||
workersToRemove--;
|
||||
await worker.close().catch((error) => {
|
||||
// Catch the error instead of throwing it
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "scaleWorkers",
|
||||
stack: error.stack,
|
||||
});
|
||||
});
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all jobs in the queue.
|
||||
*
|
||||
* @async
|
||||
* @returns {Promise<Array<Job>>}
|
||||
* @throws {Error} - Throws error if getting jobs fails
|
||||
*/
|
||||
async getJobs(queue) {
|
||||
try {
|
||||
const jobs = await queue.getRepeatableJobs();
|
||||
return jobs;
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "getJobs") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves detailed statistics about jobs and workers for all queues
|
||||
* @async
|
||||
* @returns {Promise<Object>} Queue statistics object
|
||||
* @throws {Error} If there's an error retrieving job information
|
||||
* @description
|
||||
* Returns an object with statistics for each queue including:
|
||||
* - List of jobs with their URLs and current states
|
||||
* - Number of workers assigned to the queue
|
||||
*/
|
||||
async getJobStats() {
|
||||
try {
|
||||
let stats = {};
|
||||
await Promise.all(
|
||||
QUEUE_NAMES.map(async (name) => {
|
||||
const queue = this.queues[name];
|
||||
const jobs = await queue.getJobs();
|
||||
const ret = await Promise.all(
|
||||
jobs.map(async (job) => {
|
||||
const state = await job.getState();
|
||||
return { url: job.data.url, state, progress: job.progress };
|
||||
})
|
||||
);
|
||||
stats[name] = { jobs: ret, workers: this.workers[name].length };
|
||||
})
|
||||
);
|
||||
return stats;
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "getJobStats") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds both immediate and repeatable jobs to the appropriate queue
|
||||
* @async
|
||||
* @param {string} jobName - Name identifier for the job
|
||||
* @param {Object} monitor - Job data and configuration
|
||||
* @param {string} monitor.type - Type of monitor/queue ('uptime', 'pagespeed', 'hardware')
|
||||
* @param {string} [monitor.url] - URL to monitor (optional)
|
||||
* @param {number} [monitor.interval=60000] - Repeat interval in milliseconds
|
||||
* @param {string} monitor._id - Monitor ID
|
||||
* @throws {Error} If queue not found for payload type
|
||||
* @throws {Error} If job addition fails
|
||||
* @description
|
||||
* 1. Identifies correct queue based on payload type
|
||||
* 2. Adds immediate job execution
|
||||
* 3. Adds repeatable job with specified interval
|
||||
* 4. Scales workers based on updated queue load
|
||||
* Jobs are configured with exponential backoff, single attempt,
|
||||
* and automatic removal on completion
|
||||
*/
|
||||
async addJob(jobName, monitor) {
|
||||
try {
|
||||
this.logger.info({
|
||||
message: `Adding job ${monitor?.url ?? "No URL"}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "addJob",
|
||||
});
|
||||
|
||||
// Find the correct queue
|
||||
|
||||
const queue = this.queues[QUEUE_LOOKUP[monitor.type]];
|
||||
if (queue === undefined) {
|
||||
throw new Error(`Queue for ${monitor.type} not found`);
|
||||
}
|
||||
|
||||
const jobTemplate = {
|
||||
name: jobName,
|
||||
data: monitor,
|
||||
opts: {
|
||||
attempts: 1,
|
||||
backoff: {
|
||||
type: "exponential",
|
||||
delay: 1000,
|
||||
},
|
||||
removeOnComplete: true,
|
||||
removeOnFail: false,
|
||||
timeout: 1 * 60 * 1000,
|
||||
},
|
||||
};
|
||||
|
||||
const schedulerId = getSchedulerId(monitor);
|
||||
await queue.upsertJobScheduler(
|
||||
schedulerId,
|
||||
{ every: monitor?.interval ?? 60000 },
|
||||
jobTemplate
|
||||
);
|
||||
|
||||
const workerStats = await this.getWorkerStats(queue);
|
||||
await this.scaleWorkers(workerStats, queue);
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "addJob") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a repeatable job from its queue and adjusts worker scaling
|
||||
* @async
|
||||
* @param {Object} monitor - Monitor object containing job details
|
||||
* @param {string} monitor._id - ID of the monitor/job to delete
|
||||
* @param {string} monitor.type - Type of monitor determining queue selection
|
||||
* @param {number} monitor.interval - Job repeat interval in milliseconds
|
||||
* @throws {Error} If queue not found for monitor type
|
||||
* @throws {Error} If job deletion fails
|
||||
* @description
|
||||
* 1. Identifies correct queue based on monitor type
|
||||
* 2. Removes repeatable job using monitor ID and interval
|
||||
* 3. Logs success or failure of deletion
|
||||
* 4. Updates worker scaling based on new queue load
|
||||
* Returns void but logs operation result
|
||||
*/
|
||||
async deleteJob(monitor) {
|
||||
try {
|
||||
const queue = this.queues[QUEUE_LOOKUP[monitor.type]];
|
||||
const schedulerId = getSchedulerId(monitor);
|
||||
const wasDeleted = await queue.removeJobScheduler(schedulerId);
|
||||
|
||||
if (wasDeleted === true) {
|
||||
this.logger.info({
|
||||
message: this.stringService.jobQueueDeleteJob,
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteJob",
|
||||
details: `Deleted job ${monitor._id}`,
|
||||
});
|
||||
const workerStats = await this.getWorkerStats(queue);
|
||||
await this.scaleWorkers(workerStats, queue);
|
||||
} else {
|
||||
this.logger.error({
|
||||
message: this.stringService.jobQueueDeleteJob,
|
||||
service: SERVICE_NAME,
|
||||
method: "deleteJob",
|
||||
details: `Failed to delete job ${monitor._id}`,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "deleteJob") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Retrieves comprehensive metrics for all queues
|
||||
* @async
|
||||
* @returns {Promise<Object.<string, QueueMetrics>>} Object with metrics for each queue
|
||||
* @throws {Error} If metrics retrieval fails
|
||||
* @description
|
||||
* Collects the following metrics for each queue:
|
||||
* - Number of waiting jobs
|
||||
* - Number of active jobs
|
||||
* - Number of completed jobs
|
||||
* - Number of failed jobs
|
||||
* - Number of delayed jobs
|
||||
* - Number of repeatable jobs
|
||||
* - Number of active workers
|
||||
*
|
||||
* @typedef {Object} QueueMetrics
|
||||
* @property {number} waiting - Count of jobs waiting to be processed
|
||||
* @property {number} active - Count of jobs currently being processed
|
||||
* @property {number} completed - Count of successfully completed jobs
|
||||
* @property {number} failed - Count of failed jobs
|
||||
* @property {number} delayed - Count of delayed jobs
|
||||
* @property {number} repeatableJobs - Count of repeatable job patterns
|
||||
* @property {number} workers - Count of active workers for this queue
|
||||
*/
|
||||
async getMetrics() {
|
||||
try {
|
||||
let metrics = {};
|
||||
|
||||
await Promise.all(
|
||||
QUEUE_NAMES.map(async (name) => {
|
||||
const queue = this.queues[name];
|
||||
const workers = this.workers[name];
|
||||
const [waiting, active, completed, failed, delayed, repeatableJobs] =
|
||||
await Promise.all([
|
||||
queue.getWaitingCount(),
|
||||
queue.getActiveCount(),
|
||||
queue.getCompletedCount(),
|
||||
queue.getFailedCount(),
|
||||
queue.getDelayedCount(),
|
||||
queue.getRepeatableJobs(),
|
||||
]);
|
||||
|
||||
metrics[name] = {
|
||||
waiting,
|
||||
active,
|
||||
completed,
|
||||
failed,
|
||||
delayed,
|
||||
repeatableJobs: repeatableJobs.length,
|
||||
workers: workers.length,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: SERVICE_NAME,
|
||||
method: "getMetrics",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @async
|
||||
* @returns {Promise<boolean>} - Returns true if obliteration is successful
|
||||
*/
|
||||
|
||||
async obliterate() {
|
||||
try {
|
||||
this.logger.info({
|
||||
message: "Attempting to obliterate job queue...",
|
||||
service: SERVICE_NAME,
|
||||
method: "obliterate",
|
||||
});
|
||||
|
||||
if (this.healthCheckInterval) {
|
||||
clearInterval(this.healthCheckInterval);
|
||||
this.healthCheckInterval = null;
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
QUEUE_NAMES.map(async (name) => {
|
||||
const queue = this.queues[name];
|
||||
await queue.pause();
|
||||
const jobs = await this.getJobs(queue);
|
||||
|
||||
// Remove all repeatable jobs
|
||||
for (const job of jobs) {
|
||||
await queue.removeRepeatableByKey(job.key);
|
||||
await queue.remove(job.id);
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
// Close workers
|
||||
await Promise.all(
|
||||
QUEUE_NAMES.map(async (name) => {
|
||||
const workers = this.workers[name];
|
||||
await Promise.all(
|
||||
workers.map(async (worker) => {
|
||||
await worker.close();
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
|
||||
QUEUE_NAMES.forEach(async (name) => {
|
||||
const queue = this.queues[name];
|
||||
await queue.obliterate();
|
||||
});
|
||||
|
||||
const metrics = await this.getMetrics();
|
||||
this.logger.info({
|
||||
message: this.stringService.jobQueueObliterate,
|
||||
service: SERVICE_NAME,
|
||||
method: "obliterate",
|
||||
details: metrics,
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "obliterate") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// **************************
|
||||
// Queue Health Checks
|
||||
// **************************
|
||||
async getKeyValuePairs() {
|
||||
try {
|
||||
// Get all keys
|
||||
const keys = await this.connection.keys("*");
|
||||
|
||||
if (keys.length === 0) {
|
||||
return {}; // Return an empty object if no keys are found
|
||||
}
|
||||
|
||||
// Get values for all keys
|
||||
const values = await this.connection.mget(keys);
|
||||
|
||||
// Combine keys and values into an object
|
||||
const keyValuePairs = keys.reduce((result, key, index) => {
|
||||
result[key] = values[index];
|
||||
return result;
|
||||
}, {});
|
||||
this.logger.info({
|
||||
message: "Redis key-value",
|
||||
service: SERVICE_NAME,
|
||||
method: "flushQueue",
|
||||
details: keyValuePairs,
|
||||
});
|
||||
return keyValuePairs;
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "getKeyValuePairs") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async flushQueue() {
|
||||
try {
|
||||
const keyValuePairs = await this.getKeyValuePairs();
|
||||
this.logger.info({
|
||||
message: "Before flush",
|
||||
service: SERVICE_NAME,
|
||||
method: "flushQueue",
|
||||
details: keyValuePairs,
|
||||
});
|
||||
const flushResult = await this.connection.flushall();
|
||||
const keyValuePairsAfter = await this.getKeyValuePairs();
|
||||
this.logger.info({
|
||||
message: "After flush",
|
||||
service: SERVICE_NAME,
|
||||
method: "flushQueue",
|
||||
details: keyValuePairsAfter,
|
||||
});
|
||||
if (flushResult !== "OK") {
|
||||
throw new Error("Failed to flush queue");
|
||||
}
|
||||
await this.initJobQueue();
|
||||
return {
|
||||
keyValuePairs,
|
||||
flush: flushResult,
|
||||
keyValuePairsAfter,
|
||||
init: true,
|
||||
};
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "flushQueue") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets metrics for a specific queue
|
||||
* @async
|
||||
* @function getQueueHealthMetrics
|
||||
* @param {Queue} queue - The queue to get metrics for
|
||||
* @returns {Promise<Object>} Queue metrics
|
||||
*/
|
||||
async getQueueHealthMetrics(queue) {
|
||||
return await queue.getJobCounts();
|
||||
}
|
||||
|
||||
getQueueIdleTimes() {
|
||||
const now = Date.now();
|
||||
const idleTimes = {};
|
||||
Object.entries(this.lastJobProcessedTime).forEach(([queueName, lastProcessed]) => {
|
||||
idleTimes[queueName] = now - lastProcessed;
|
||||
});
|
||||
return idleTimes;
|
||||
}
|
||||
async checkQueueHealth() {
|
||||
try {
|
||||
const currentTime = Date.now();
|
||||
const stuckQueues = [];
|
||||
const idleTimes = this.getQueueIdleTimes();
|
||||
for (const queueName of QUEUE_NAMES) {
|
||||
const queue = this.queues[queueName];
|
||||
|
||||
const jobCounts = await this.getQueueHealthMetrics(queue);
|
||||
const hasJobs = Object.values(jobCounts).some((count) => count > 0);
|
||||
|
||||
const timeSinceLastProcessed = currentTime - this.lastJobProcessedTime[queueName];
|
||||
const isStuck = hasJobs && timeSinceLastProcessed > HEALTH_CHECK_INTERVAL;
|
||||
|
||||
if (isStuck) {
|
||||
stuckQueues.push(queueName);
|
||||
}
|
||||
}
|
||||
|
||||
const queueHealth = { stuck: false, stuckQueues, idleTimes };
|
||||
|
||||
if (stuckQueues.length > 0) {
|
||||
queueHealth.stuck = true;
|
||||
}
|
||||
|
||||
this.logger.info({
|
||||
message: "Queue health check",
|
||||
service: SERVICE_NAME,
|
||||
method: "checkQueueHealth",
|
||||
details: queueHealth,
|
||||
});
|
||||
return queueHealth;
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "checkQueueHealth") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default NewJobQueue;
|
||||
Executable
+519
@@ -0,0 +1,519 @@
|
||||
import jmespath from "jmespath";
|
||||
const SERVICE_NAME = "NetworkService";
|
||||
const UPROCK_ENDPOINT = "https://api.uprock.com/checkmate/push";
|
||||
|
||||
/**
|
||||
* Constructs a new NetworkService instance.
|
||||
*
|
||||
* @param {Object} axios - The axios instance for HTTP requests.
|
||||
* @param {Object} ping - The ping utility for network checks.
|
||||
* @param {Object} logger - The logger instance for logging.
|
||||
* @param {Object} http - The HTTP utility for network operations.
|
||||
* @param {Object} net - The net utility for network operations.
|
||||
*/
|
||||
class NetworkService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
|
||||
constructor(axios, ping, logger, http, Docker, net, stringService, settingsService) {
|
||||
this.TYPE_PING = "ping";
|
||||
this.TYPE_HTTP = "http";
|
||||
this.TYPE_PAGESPEED = "pagespeed";
|
||||
this.TYPE_HARDWARE = "hardware";
|
||||
this.TYPE_DOCKER = "docker";
|
||||
this.TYPE_PORT = "port";
|
||||
this.TYPE_DISTRIBUTED_HTTP = "distributed_http";
|
||||
this.TYPE_DISTRIBUTED_TEST = "distributed_test";
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.NETWORK_ERROR = 5000;
|
||||
this.PING_ERROR = 5001;
|
||||
this.axios = axios;
|
||||
this.ping = ping;
|
||||
this.logger = logger;
|
||||
this.http = http;
|
||||
this.Docker = Docker;
|
||||
this.net = net;
|
||||
this.stringService = stringService;
|
||||
this.settingsService = settingsService;
|
||||
this.settings = settingsService.getSettings();
|
||||
}
|
||||
|
||||
/**
|
||||
* Times the execution of an asynchronous operation.
|
||||
*
|
||||
* @param {Function} operation - The asynchronous operation to be timed.
|
||||
* @returns {Promise<Object>} An object containing the response, response time, and optionally an error.
|
||||
* @property {Object|null} response - The response from the operation, or null if an error occurred.
|
||||
* @property {number} responseTime - The time taken for the operation to complete, in milliseconds.
|
||||
* @property {Error} [error] - The error object if an error occurred during the operation.
|
||||
*/
|
||||
async timeRequest(operation) {
|
||||
const startTime = Date.now();
|
||||
try {
|
||||
const response = await operation();
|
||||
const endTime = Date.now();
|
||||
const responseTime = endTime - startTime;
|
||||
return { response, responseTime };
|
||||
} catch (error) {
|
||||
const endTime = Date.now();
|
||||
const responseTime = endTime - startTime;
|
||||
return { response: null, responseTime, error };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a ping request to the specified URL and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the ping request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to ping.
|
||||
* @param {string} job.data._id - The monitor ID for the ping request.
|
||||
* @returns {Promise<Object>} An object containing the ping response details.
|
||||
* @property {string} monitorId - The monitor ID for the ping request.
|
||||
* @property {string} type - The type of request, which is "ping".
|
||||
* @property {number} responseTime - The time taken for the ping request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the ping request.
|
||||
* @property {boolean} status - The status of the ping request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the ping request.
|
||||
*/
|
||||
async requestPing(job) {
|
||||
try {
|
||||
const url = job.data.url;
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
this.ping.promise.probe(url)
|
||||
);
|
||||
|
||||
const pingResponse = {
|
||||
monitorId: job.data._id,
|
||||
type: "ping",
|
||||
responseTime,
|
||||
payload: response,
|
||||
};
|
||||
if (error) {
|
||||
pingResponse.status = false;
|
||||
pingResponse.code = this.PING_ERROR;
|
||||
pingResponse.message = "No response";
|
||||
return pingResponse;
|
||||
}
|
||||
|
||||
pingResponse.code = 200;
|
||||
pingResponse.status = response.alive;
|
||||
pingResponse.message = "Success";
|
||||
return pingResponse;
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestPing";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an HTTP GET request to the specified URL and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the HTTP request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to send the HTTP GET request to.
|
||||
* @param {string} job.data._id - The monitor ID for the HTTP request.
|
||||
* @param {string} [job.data.secret] - Secret for authorization if provided.
|
||||
* @returns {Promise<Object>} An object containing the HTTP response details.
|
||||
* @property {string} monitorId - The monitor ID for the HTTP request.
|
||||
* @property {string} type - The type of request, which is "http".
|
||||
* @property {number} responseTime - The time taken for the HTTP request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the HTTP request.
|
||||
* @property {boolean} status - The status of the HTTP request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the HTTP request.
|
||||
*/
|
||||
async requestHttp(job) {
|
||||
try {
|
||||
const {
|
||||
url,
|
||||
secret,
|
||||
_id,
|
||||
name,
|
||||
teamId,
|
||||
type,
|
||||
jsonPath,
|
||||
matchMethod,
|
||||
expectedValue,
|
||||
} = job.data;
|
||||
const config = {};
|
||||
|
||||
secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` });
|
||||
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
this.axios.get(url, config)
|
||||
);
|
||||
|
||||
const httpResponse = {
|
||||
monitorId: _id,
|
||||
teamId,
|
||||
type,
|
||||
responseTime,
|
||||
payload: response?.data,
|
||||
};
|
||||
|
||||
if (error) {
|
||||
const code = error.response?.status || this.NETWORK_ERROR;
|
||||
httpResponse.code = code;
|
||||
httpResponse.status = false;
|
||||
httpResponse.message =
|
||||
this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
httpResponse.code = response.status;
|
||||
|
||||
if (!expectedValue) {
|
||||
// not configure expected value, return
|
||||
httpResponse.status = true;
|
||||
httpResponse.message = this.http.STATUS_CODES[response.status];
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
// validate if response data match expected value
|
||||
let result = response?.data;
|
||||
|
||||
this.logger.info({
|
||||
service: this.SERVICE_NAME,
|
||||
method: "requestHttp",
|
||||
message: `Job: [${name}](${_id}) match result with expected value`,
|
||||
details: { expectedValue, result, jsonPath, matchMethod },
|
||||
});
|
||||
|
||||
if (jsonPath) {
|
||||
const contentType = response.headers["content-type"];
|
||||
|
||||
const isJson = contentType?.includes("application/json");
|
||||
if (!isJson) {
|
||||
httpResponse.status = false;
|
||||
httpResponse.message = this.stringService.httpNotJson;
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
try {
|
||||
result = jmespath.search(result, jsonPath);
|
||||
} catch (error) {
|
||||
httpResponse.status = false;
|
||||
httpResponse.message = this.stringService.httpJsonPathError;
|
||||
return httpResponse;
|
||||
}
|
||||
}
|
||||
|
||||
if (result === null || result === undefined) {
|
||||
httpResponse.status = false;
|
||||
httpResponse.message = this.stringService.httpEmptyResult;
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
let match;
|
||||
result = typeof result === "object" ? JSON.stringify(result) : result.toString();
|
||||
if (matchMethod === "include") match = result.includes(expectedValue);
|
||||
else if (matchMethod === "regex") match = new RegExp(expectedValue).test(result);
|
||||
else match = result === expectedValue;
|
||||
|
||||
httpResponse.status = match;
|
||||
httpResponse.message = match
|
||||
? this.stringService.httpMatchSuccess
|
||||
: this.stringService.httpMatchFail;
|
||||
return httpResponse;
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestHttp";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request to the Google PageSpeed Insights API for the specified URL and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the PageSpeed request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to analyze with PageSpeed Insights.
|
||||
* @param {string} job.data._id - The monitor ID for the PageSpeed request.
|
||||
* @returns {Promise<Object>} An object containing the PageSpeed response details.
|
||||
* @property {string} monitorId - The monitor ID for the PageSpeed request.
|
||||
* @property {string} type - The type of request, which is "pagespeed".
|
||||
* @property {number} responseTime - The time taken for the PageSpeed request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the PageSpeed request.
|
||||
* @property {boolean} status - The status of the PageSpeed request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the PageSpeed request.
|
||||
*/
|
||||
async requestPagespeed(job) {
|
||||
try {
|
||||
const url = job.data.url;
|
||||
const updatedJob = { ...job };
|
||||
let pagespeedUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&category=seo&category=accessibility&category=best-practices&category=performance`;
|
||||
if (this.settings?.pagespeedApiKey) {
|
||||
pagespeedUrl += `&key=${this.settings.pagespeedApiKey}`;
|
||||
}
|
||||
updatedJob.data.url = pagespeedUrl;
|
||||
return await this.requestHttp(updatedJob);
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestPagespeed";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends an HTTP request to check hardware status and returns the response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the hardware request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The URL to send the hardware status request to.
|
||||
* @param {string} job.data._id - The monitor ID for the hardware request.
|
||||
* @param {string} job.data.type - The type of request, which is "hardware".
|
||||
* @returns {Promise<Object>} An object containing the hardware status response details.
|
||||
* @property {string} monitorId - The monitor ID for the hardware request.
|
||||
* @property {string} type - The type of request ("hardware").
|
||||
* @property {number} responseTime - The time taken for the request to complete, in milliseconds.
|
||||
* @property {Object} payload - The response payload from the hardware status request.
|
||||
* @property {boolean} status - The status of the request (true if successful, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the hardware status request.
|
||||
*/
|
||||
async requestHardware(job) {
|
||||
try {
|
||||
return await this.requestHttp(job);
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestHardware";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request to inspect a Docker container and returns its status.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the Docker request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.url - The container ID or name to inspect.
|
||||
* @param {string} job.data._id - The monitor ID for the Docker request.
|
||||
* @param {string} job.data.type - The type of request, which is "docker".
|
||||
* @returns {Promise<Object>} An object containing the Docker container status details.
|
||||
* @property {string} monitorId - The monitor ID for the Docker request.
|
||||
* @property {string} type - The type of request ("docker").
|
||||
* @property {number} responseTime - The time taken for the Docker inspection to complete, in milliseconds.
|
||||
* @property {boolean} status - The status of the container (true if running, false otherwise).
|
||||
* @property {number} code - The response code (200 if successful, error code otherwise).
|
||||
* @property {string} message - The message indicating the result of the Docker inspection.
|
||||
*/
|
||||
async requestDocker(job) {
|
||||
try {
|
||||
const docker = new this.Docker({
|
||||
socketPath: "/var/run/docker.sock",
|
||||
handleError: true, // Enable error handling
|
||||
});
|
||||
|
||||
const containers = await docker.listContainers({ all: true });
|
||||
const containerExists = containers.some((c) => c.Id.startsWith(job.data.url));
|
||||
if (!containerExists) {
|
||||
throw new Error(this.stringService.dockerNotFound);
|
||||
}
|
||||
const container = docker.getContainer(job.data.url);
|
||||
|
||||
const { response, responseTime, error } = await this.timeRequest(() =>
|
||||
container.inspect()
|
||||
);
|
||||
|
||||
const dockerResponse = {
|
||||
monitorId: job.data._id,
|
||||
type: job.data.type,
|
||||
responseTime,
|
||||
};
|
||||
|
||||
if (error) {
|
||||
dockerResponse.status = false;
|
||||
dockerResponse.code = error.statusCode || this.NETWORK_ERROR;
|
||||
dockerResponse.message =
|
||||
error.reason || "Failed to fetch Docker container information";
|
||||
return dockerResponse;
|
||||
}
|
||||
dockerResponse.status = response?.State?.Status === "running" ? true : false;
|
||||
dockerResponse.code = 200;
|
||||
dockerResponse.message = "Docker container status fetched successfully";
|
||||
return dockerResponse;
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestDocker";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async requestPort(job) {
|
||||
try {
|
||||
const { url, port } = job.data;
|
||||
const { response, responseTime, error } = await this.timeRequest(async () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = this.net.createConnection(
|
||||
{
|
||||
host: url,
|
||||
port,
|
||||
},
|
||||
() => {
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
resolve({ success: true });
|
||||
}
|
||||
);
|
||||
|
||||
socket.setTimeout(5000);
|
||||
socket.on("timeout", () => {
|
||||
socket.destroy();
|
||||
reject(new Error("Connection timeout"));
|
||||
});
|
||||
|
||||
socket.on("error", (err) => {
|
||||
socket.destroy();
|
||||
reject(err);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const portResponse = {
|
||||
monitorId: job.data._id,
|
||||
type: job.data.type,
|
||||
responseTime,
|
||||
};
|
||||
|
||||
if (error) {
|
||||
portResponse.status = false;
|
||||
portResponse.code = this.NETWORK_ERROR;
|
||||
portResponse.message = this.stringService.portFail;
|
||||
return portResponse;
|
||||
}
|
||||
|
||||
portResponse.status = response.success;
|
||||
portResponse.code = 200;
|
||||
portResponse.message = this.stringService.portSuccess;
|
||||
return portResponse;
|
||||
} catch (error) {
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestTCP";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async requestDistributedHttp(job) {
|
||||
try {
|
||||
const monitor = job.data;
|
||||
const CALLBACK_URL = process.env.CALLBACK_URL;
|
||||
|
||||
const response = await this.axios.post(
|
||||
UPROCK_ENDPOINT,
|
||||
{
|
||||
id: monitor._id,
|
||||
url: monitor.url,
|
||||
callback: `${CALLBACK_URL}/api/v1/distributed-uptime/callback`,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"x-checkmate-key": process.env.UPROCK_API_KEY,
|
||||
},
|
||||
}
|
||||
);
|
||||
if (response.data.success === false) {
|
||||
throw new Error(response.data.message);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: "Error in requestDistributedHttp",
|
||||
service: this.SERVICE_NAME,
|
||||
method: "requestDistributedHttp",
|
||||
stack: error.stack,
|
||||
});
|
||||
error.service = this.SERVICE_NAME;
|
||||
error.method = "requestDistributedHttp";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles unsupported job types by throwing an error with details.
|
||||
*
|
||||
* @param {string} type - The unsupported job type that was provided
|
||||
* @throws {Error} An error with service name, method name and unsupported type message
|
||||
*/
|
||||
handleUnsupportedType(type) {
|
||||
const err = new Error(`Unsupported type: ${type}`);
|
||||
err.service = this.SERVICE_NAME;
|
||||
err.method = "getStatus";
|
||||
throw err;
|
||||
}
|
||||
|
||||
async requestWebhook(platform, url, message) {
|
||||
try {
|
||||
const response = await this.axios.post(url, message, {
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
type: "webhook",
|
||||
status: true,
|
||||
code: response.status,
|
||||
message: `Successfully sent ${platform} notification`,
|
||||
payload: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.warn({
|
||||
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`,
|
||||
payload: error.response?.data,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the status of a job based on its type and returns the appropriate response.
|
||||
*
|
||||
* @param {Object} job - The job object containing the data for the status request.
|
||||
* @param {Object} job.data - The data object within the job.
|
||||
* @param {string} job.data.type - The type of the job (e.g., "ping", "http", "pagespeed", "hardware").
|
||||
* @returns {Promise<Object>} The response object from the appropriate request method.
|
||||
* @throws {Error} Throws an error if the job type is unsupported.
|
||||
*/
|
||||
async getStatus(job) {
|
||||
const type = job?.data?.type ?? "unknown";
|
||||
switch (type) {
|
||||
case this.TYPE_PING:
|
||||
return await this.requestPing(job);
|
||||
case this.TYPE_HTTP:
|
||||
return await this.requestHttp(job);
|
||||
case this.TYPE_PAGESPEED:
|
||||
return await this.requestPagespeed(job);
|
||||
case this.TYPE_HARDWARE:
|
||||
return await this.requestHardware(job);
|
||||
case this.TYPE_DOCKER:
|
||||
return await this.requestDocker(job);
|
||||
case this.TYPE_PORT:
|
||||
return await this.requestPort(job);
|
||||
case this.TYPE_DISTRIBUTED_HTTP:
|
||||
return await this.requestDistributedHttp(job);
|
||||
case this.TYPE_DISTRIBUTED_TEST:
|
||||
return;
|
||||
default:
|
||||
return this.handleUnsupportedType(type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default NetworkService;
|
||||
Executable
+335
@@ -0,0 +1,335 @@
|
||||
const SERVICE_NAME = "NotificationService";
|
||||
const TELEGRAM_API_BASE_URL = "https://api.telegram.org/bot";
|
||||
const PLATFORM_TYPES = ["telegram", "slack", "discord"];
|
||||
|
||||
const MESSAGE_FORMATTERS = {
|
||||
telegram: (messageText, chatId) => ({ chat_id: chatId, text: messageText }),
|
||||
slack: (messageText) => ({ text: messageText }),
|
||||
discord: (messageText) => ({ content: 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;
|
||||
this.emailService = emailService;
|
||||
this.db = db;
|
||||
this.logger = logger;
|
||||
this.networkService = networkService;
|
||||
this.stringService = stringService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
const { monitor, status, code } = networkResponse;
|
||||
const { platform } = notification;
|
||||
const { webhookUrl, 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`;
|
||||
}
|
||||
|
||||
const 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`;
|
||||
this.emailService.buildAndSendEmail(template, context, address, subject);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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"}`;
|
||||
this.emailService.buildAndSendEmail(template, context, address, subject);
|
||||
return true;
|
||||
}
|
||||
|
||||
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 notifications = await this.db.getNotificationsByMonitorId(
|
||||
networkResponse.monitorId
|
||||
);
|
||||
|
||||
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);
|
||||
}
|
||||
// Handle other types of notifications here
|
||||
}
|
||||
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;
|
||||
|
||||
// Get metrics from response
|
||||
const metrics = networkResponse?.payload?.data ?? null;
|
||||
if (metrics === null) return false;
|
||||
|
||||
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 && d.usage_percent > diskThreshold)
|
||||
? true
|
||||
: false,
|
||||
};
|
||||
|
||||
const notifications = await this.db.getNotificationsByMonitorId(
|
||||
networkResponse.monitorId
|
||||
);
|
||||
for (const notification of notifications) {
|
||||
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) {
|
||||
notification[`${type}AlertThreshold`]--; // Decrement threshold if an alert is triggered
|
||||
|
||||
if (notification[`${type}AlertThreshold`] <= 0) {
|
||||
// If threshold drops below 0, reset and send notification
|
||||
notification[`${type}AlertThreshold`] = notification.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 notification.save();
|
||||
|
||||
if (alertsToSend.length === 0) continue; // No alerts to send, we're done
|
||||
|
||||
if (notification.type === "email") {
|
||||
this.sendHardwareEmail(networkResponse, notification.address, alertsToSend);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default NotificationService;
|
||||
Executable
+35
@@ -0,0 +1,35 @@
|
||||
const SERVICE_NAME = "ServiceRegistry";
|
||||
import logger from "../utils/logger.js";
|
||||
class ServiceRegistry {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
constructor() {
|
||||
this.services = {};
|
||||
}
|
||||
|
||||
register(name, service) {
|
||||
logger.info({
|
||||
message: `Registering service ${name}`,
|
||||
service: SERVICE_NAME,
|
||||
method: "register",
|
||||
});
|
||||
this.services[name] = service;
|
||||
}
|
||||
|
||||
get(name) {
|
||||
if (!this.services[name]) {
|
||||
logger.error({
|
||||
message: `Service ${name} is not registered`,
|
||||
service: SERVICE_NAME,
|
||||
method: "get",
|
||||
});
|
||||
throw new Error(`Service ${name} is not registered`);
|
||||
}
|
||||
return this.services[name];
|
||||
}
|
||||
|
||||
listServices() {
|
||||
return Object.keys(this.services);
|
||||
}
|
||||
}
|
||||
|
||||
export default new ServiceRegistry();
|
||||
Executable
+86
@@ -0,0 +1,86 @@
|
||||
const SERVICE_NAME = "SettingsService";
|
||||
import dotenv from "dotenv";
|
||||
dotenv.config();
|
||||
const envConfig = {
|
||||
logLevel: process.env.LOG_LEVEL,
|
||||
apiBaseUrl: undefined,
|
||||
language: process.env.LANGUAGE,
|
||||
clientHost: process.env.CLIENT_HOST,
|
||||
jwtSecret: process.env.JWT_SECRET,
|
||||
dbType: process.env.DB_TYPE,
|
||||
dbConnectionString: process.env.DB_CONNECTION_STRING,
|
||||
redisUrl: process.env.REDIS_URL,
|
||||
jwtTTL: process.env.TOKEN_TTL,
|
||||
pagespeedApiKey: process.env.PAGESPEED_API_KEY,
|
||||
systemEmailHost: process.env.SYSTEM_EMAIL_HOST,
|
||||
systemEmailPort: process.env.SYSTEM_EMAIL_PORT,
|
||||
systemEmailUser: process.env.SYSTEM_EMAIL_USER,
|
||||
systemEmailAddress: process.env.SYSTEM_EMAIL_ADDRESS,
|
||||
systemEmailPassword: process.env.SYSTEM_EMAIL_PASSWORD,
|
||||
};
|
||||
/**
|
||||
* SettingsService
|
||||
*
|
||||
* This service is responsible for loading and managing the application settings.
|
||||
* It gives priority to environment variables and will only load settings
|
||||
* from the database if they are not set in the environment.
|
||||
*/
|
||||
class SettingsService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
/**
|
||||
* Constructs a new SettingsService
|
||||
* @constructor
|
||||
* @throws {Error}
|
||||
*/ constructor(appSettings) {
|
||||
this.appSettings = appSettings;
|
||||
this.settings = { ...envConfig };
|
||||
}
|
||||
/**
|
||||
* Load settings from the database and merge with environment settings.
|
||||
* If there are any settings that weren't set by environment variables, use user settings from the database.
|
||||
* @returns {Promise<Object>} The merged settings.
|
||||
* @throws Will throw an error if settings are not found in the database or if settings have not been loaded.
|
||||
*/ async loadSettings() {
|
||||
try {
|
||||
const dbSettings = await this.appSettings.findOne();
|
||||
if (!this.settings) {
|
||||
throw new Error("Settings not found");
|
||||
}
|
||||
|
||||
// If there are any settings that weren't set by environment variables, use user settings from DB
|
||||
for (const key in envConfig) {
|
||||
if (
|
||||
typeof envConfig?.[key] === "undefined" &&
|
||||
typeof dbSettings?.[key] !== "undefined"
|
||||
) {
|
||||
this.settings[key] = dbSettings[key];
|
||||
}
|
||||
}
|
||||
return this.settings;
|
||||
} catch (error) {
|
||||
error.service === undefined ? (error.service = SERVICE_NAME) : null;
|
||||
error.method === undefined ? (error.method = "loadSettings") : null;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Reload settings by calling loadSettings.
|
||||
* @returns {Promise<Object>} The reloaded settings.
|
||||
*/
|
||||
async reloadSettings() {
|
||||
return this.loadSettings();
|
||||
}
|
||||
/**
|
||||
* Get the current settings.
|
||||
* @returns {Object} The current settings.
|
||||
* @throws Will throw an error if settings have not been loaded.
|
||||
*/
|
||||
getSettings() {
|
||||
if (!this.settings) {
|
||||
throw new Error("Settings have not been loaded");
|
||||
}
|
||||
return this.settings;
|
||||
}
|
||||
}
|
||||
|
||||
export default SettingsService;
|
||||
Executable
+302
@@ -0,0 +1,302 @@
|
||||
import MonitorStats from "../db/models/MonitorStats.js";
|
||||
import { safelyParseFloat } from "../utils/dataUtils.js";
|
||||
const SERVICE_NAME = "StatusService";
|
||||
|
||||
class StatusService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
/**
|
||||
* Creates an instance of StatusService.
|
||||
*
|
||||
* @param {Object} db - The database instance.
|
||||
* @param {Object} logger - The logger instance.
|
||||
*/
|
||||
constructor({ db, logger, buffer }) {
|
||||
this.db = db;
|
||||
this.logger = logger;
|
||||
this.buffer = buffer;
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
async updateRunningStats({ monitor, networkResponse }) {
|
||||
try {
|
||||
const monitorId = monitor._id;
|
||||
const { responseTime, status, upt_burnt } = networkResponse;
|
||||
// Get stats
|
||||
let stats = await MonitorStats.findOne({ monitorId });
|
||||
if (!stats) {
|
||||
stats = new MonitorStats({
|
||||
monitorId,
|
||||
avgResponseTime: 0,
|
||||
totalChecks: 0,
|
||||
totalUpChecks: 0,
|
||||
totalDownChecks: 0,
|
||||
uptimePercentage: 0,
|
||||
lastCheck: null,
|
||||
timeSInceLastCheck: 0,
|
||||
uptBurnt: 0,
|
||||
});
|
||||
}
|
||||
|
||||
// Update stats
|
||||
|
||||
// Last response time
|
||||
stats.lastResponseTime = responseTime;
|
||||
|
||||
// Avg response time:
|
||||
let avgResponseTime = stats.avgResponseTime;
|
||||
if (typeof responseTime !== "undefined" && responseTime !== null) {
|
||||
if (avgResponseTime === 0) {
|
||||
avgResponseTime = responseTime;
|
||||
} else {
|
||||
avgResponseTime =
|
||||
(avgResponseTime * (stats.totalChecks - 1) + responseTime) /
|
||||
stats.totalChecks;
|
||||
}
|
||||
}
|
||||
stats.avgResponseTime = avgResponseTime;
|
||||
|
||||
// Total checks
|
||||
stats.totalChecks++;
|
||||
if (status === true) {
|
||||
stats.totalUpChecks++;
|
||||
// Update the timeSinceLastFailure if needed
|
||||
if (stats.timeOfLastFailure === 0) {
|
||||
stats.timeOfLastFailure = new Date().getTime();
|
||||
}
|
||||
} else {
|
||||
stats.totalDownChecks++;
|
||||
stats.timeOfLastFailure = 0;
|
||||
}
|
||||
|
||||
// Calculate uptime percentage
|
||||
let uptimePercentage;
|
||||
if (stats.totalChecks > 0) {
|
||||
uptimePercentage = stats.totalUpChecks / stats.totalChecks;
|
||||
} else {
|
||||
uptimePercentage = status === true ? 100 : 0;
|
||||
}
|
||||
stats.uptimePercentage = uptimePercentage;
|
||||
|
||||
// latest check
|
||||
stats.lastCheckTimestamp = new Date().getTime();
|
||||
|
||||
// UPT burned
|
||||
if (typeof upt_burnt !== "undefined" && upt_burnt !== null) {
|
||||
const currentUptBurnt = safelyParseFloat(stats.uptBurnt);
|
||||
const newUptBurnt = safelyParseFloat(upt_burnt);
|
||||
stats.uptBurnt = currentUptBurnt + newUptBurnt;
|
||||
}
|
||||
await stats.save();
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
service: this.SERVICE_NAME,
|
||||
message: error.message,
|
||||
method: "updateRunningStats",
|
||||
stack: error.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
getStatusString = (status) => {
|
||||
if (status === true) return "up";
|
||||
if (status === false) return "down";
|
||||
return "unknown";
|
||||
};
|
||||
/**
|
||||
* Updates the status of a monitor based on the network response.
|
||||
*
|
||||
* @param {Object} networkResponse - The network response containing monitorId and status.
|
||||
* @param {string} networkResponse.monitorId - The ID of the monitor.
|
||||
* @param {string} networkResponse.status - The new status of the monitor.
|
||||
* @returns {Promise<Object>} - A promise that resolves to an object containinfg the monitor, statusChanged flag, and previous status if the status changed, or false if an error occurred.
|
||||
* @returns {Promise<Object>} returnObject - The object returned by the function.
|
||||
* @returns {Object} returnObject.monitor - The monitor object.
|
||||
* @returns {boolean} returnObject.statusChanged - Flag indicating if the status has changed.
|
||||
* @returns {boolean} returnObject.prevStatus - The previous status of the monitor
|
||||
*/
|
||||
updateStatus = async (networkResponse) => {
|
||||
this.insertCheck(networkResponse);
|
||||
try {
|
||||
const { monitorId, status, code } = networkResponse;
|
||||
const monitor = await this.db.getMonitorById(monitorId);
|
||||
|
||||
// Update running stats
|
||||
this.updateRunningStats({ monitor, networkResponse });
|
||||
|
||||
// No change in monitor status, return early
|
||||
if (monitor.status === status)
|
||||
return {
|
||||
monitor,
|
||||
statusChanged: false,
|
||||
prevStatus: monitor.status,
|
||||
code,
|
||||
timestamp: new Date().getTime(),
|
||||
};
|
||||
|
||||
// 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)}`,
|
||||
prevStatus: monitor.status,
|
||||
newStatus: status,
|
||||
});
|
||||
|
||||
const prevStatus = monitor.status;
|
||||
monitor.status = status;
|
||||
await monitor.save();
|
||||
|
||||
return {
|
||||
monitor,
|
||||
statusChanged: true,
|
||||
prevStatus,
|
||||
code,
|
||||
timestamp: new Date().getTime(),
|
||||
};
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
service: this.SERVICE_NAME,
|
||||
message: error.message,
|
||||
method: "updateStatus",
|
||||
stack: error.stack,
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Builds a check object from the network response.
|
||||
*
|
||||
* @param {Object} networkResponse - The network response object.
|
||||
* @param {string} networkResponse.monitorId - The monitor ID.
|
||||
* @param {string} networkResponse.type - The type of the response.
|
||||
* @param {string} networkResponse.status - The status of the response.
|
||||
* @param {number} networkResponse.responseTime - The response time.
|
||||
* @param {number} networkResponse.code - The status code.
|
||||
* @param {string} networkResponse.message - The message.
|
||||
* @param {Object} networkResponse.payload - The payload of the response.
|
||||
* @returns {Object} The check object.
|
||||
*/
|
||||
buildCheck = (networkResponse) => {
|
||||
const {
|
||||
monitorId,
|
||||
teamId,
|
||||
type,
|
||||
status,
|
||||
responseTime,
|
||||
code,
|
||||
message,
|
||||
payload,
|
||||
first_byte_took,
|
||||
body_read_took,
|
||||
dns_took,
|
||||
conn_took,
|
||||
connect_took,
|
||||
tls_took,
|
||||
} = networkResponse;
|
||||
|
||||
const check = {
|
||||
monitorId,
|
||||
teamId,
|
||||
status,
|
||||
statusCode: code,
|
||||
responseTime,
|
||||
message,
|
||||
first_byte_took,
|
||||
body_read_took,
|
||||
dns_took,
|
||||
conn_took,
|
||||
connect_took,
|
||||
tls_took,
|
||||
};
|
||||
|
||||
if (type === "distributed_http") {
|
||||
if (typeof payload === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
check.continent = payload.continent;
|
||||
check.countryCode = payload.country_code;
|
||||
check.city = payload.city;
|
||||
check.location = payload.location;
|
||||
check.uptBurnt = payload.upt_burnt;
|
||||
check.first_byte_took = payload.first_byte_took;
|
||||
check.body_read_took = payload.body_read_took;
|
||||
check.dns_took = payload.dns_took;
|
||||
check.conn_took = payload.conn_took;
|
||||
check.connect_took = payload.connect_took;
|
||||
check.tls_took = payload.tls_took;
|
||||
}
|
||||
|
||||
if (type === "pagespeed") {
|
||||
if (typeof payload === "undefined") {
|
||||
return undefined;
|
||||
}
|
||||
const categories = payload?.lighthouseResult?.categories ?? {};
|
||||
const audits = payload?.lighthouseResult?.audits ?? {};
|
||||
const {
|
||||
"cumulative-layout-shift": cls = 0,
|
||||
"speed-index": si = 0,
|
||||
"first-contentful-paint": fcp = 0,
|
||||
"largest-contentful-paint": lcp = 0,
|
||||
"total-blocking-time": tbt = 0,
|
||||
} = audits;
|
||||
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, si, fcp, lcp, tbt };
|
||||
}
|
||||
|
||||
if (type === "hardware") {
|
||||
const { cpu, memory, disk, host } = payload?.data ?? {};
|
||||
const { errors } = payload?.errors ?? [];
|
||||
check.cpu = cpu ?? {};
|
||||
check.memory = memory ?? {};
|
||||
check.disk = disk ?? {};
|
||||
check.host = host ?? {};
|
||||
check.errors = errors ?? [];
|
||||
}
|
||||
return check;
|
||||
};
|
||||
|
||||
/**
|
||||
* Inserts a check into the database based on the network response.
|
||||
*
|
||||
* @param {Object} networkResponse - The network response object.
|
||||
* @param {string} networkResponse.monitorId - The monitor ID.
|
||||
* @param {string} networkResponse.type - The type of the response.
|
||||
* @param {string} networkResponse.status - The status of the response.
|
||||
* @param {number} networkResponse.responseTime - The response time.
|
||||
* @param {number} networkResponse.code - The status code.
|
||||
* @param {string} networkResponse.message - The message.
|
||||
* @param {Object} networkResponse.payload - The payload of the response.
|
||||
* @returns {Promise<void>} A promise that resolves when the check is inserted.
|
||||
*/
|
||||
insertCheck = async (networkResponse) => {
|
||||
try {
|
||||
const check = this.buildCheck(networkResponse);
|
||||
if (typeof check === "undefined") {
|
||||
this.logger.warn({
|
||||
message: "Failed to build check",
|
||||
service: this.SERVICE_NAME,
|
||||
method: "insertCheck",
|
||||
details: networkResponse,
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.buffer.addToBuffer({ check, type: networkResponse.type });
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: this.SERVICE_NAME,
|
||||
method: "insertCheck",
|
||||
details: `Error inserting check for monitor: ${networkResponse?.monitorId}`,
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
export default StatusService;
|
||||
Executable
+425
@@ -0,0 +1,425 @@
|
||||
class StringService {
|
||||
static SERVICE_NAME = "StringService";
|
||||
|
||||
constructor(translationService) {
|
||||
if (StringService.instance) {
|
||||
return StringService.instance;
|
||||
}
|
||||
|
||||
this.translationService = translationService;
|
||||
this._language = "en"; // default language
|
||||
StringService.instance = this;
|
||||
}
|
||||
|
||||
setLanguage(language) {
|
||||
this._language = language;
|
||||
}
|
||||
|
||||
get language() {
|
||||
return this._language;
|
||||
}
|
||||
|
||||
// Auth Messages
|
||||
get dontHaveAccount() {
|
||||
return this.translationService.getTranslation("dontHaveAccount");
|
||||
}
|
||||
|
||||
get email() {
|
||||
return this.translationService.getTranslation("email");
|
||||
}
|
||||
|
||||
get forgotPassword() {
|
||||
return this.translationService.getTranslation("forgotPassword");
|
||||
}
|
||||
|
||||
get password() {
|
||||
return this.translationService.getTranslation("password");
|
||||
}
|
||||
|
||||
get signUp() {
|
||||
return this.translationService.getTranslation("signUp");
|
||||
}
|
||||
|
||||
get submit() {
|
||||
return this.translationService.getTranslation("submit");
|
||||
}
|
||||
|
||||
get title() {
|
||||
return this.translationService.getTranslation("title");
|
||||
}
|
||||
|
||||
get continue() {
|
||||
return this.translationService.getTranslation("continue");
|
||||
}
|
||||
|
||||
get enterEmail() {
|
||||
return this.translationService.getTranslation("enterEmail");
|
||||
}
|
||||
|
||||
get authLoginTitle() {
|
||||
return this.translationService.getTranslation("authLoginTitle");
|
||||
}
|
||||
|
||||
get authLoginEnterPassword() {
|
||||
return this.translationService.getTranslation("authLoginEnterPassword");
|
||||
}
|
||||
|
||||
get commonPassword() {
|
||||
return this.translationService.getTranslation("commonPassword");
|
||||
}
|
||||
|
||||
get commonBack() {
|
||||
return this.translationService.getTranslation("commonBack");
|
||||
}
|
||||
|
||||
get authForgotPasswordTitle() {
|
||||
return this.translationService.getTranslation("authForgotPasswordTitle");
|
||||
}
|
||||
|
||||
get authForgotPasswordResetPassword() {
|
||||
return this.translationService.getTranslation("authForgotPasswordResetPassword");
|
||||
}
|
||||
|
||||
get createPassword() {
|
||||
return this.translationService.getTranslation("createPassword");
|
||||
}
|
||||
|
||||
get createAPassword() {
|
||||
return this.translationService.getTranslation("createAPassword");
|
||||
}
|
||||
|
||||
get authRegisterAlreadyHaveAccount() {
|
||||
return this.translationService.getTranslation("authRegisterAlreadyHaveAccount");
|
||||
}
|
||||
|
||||
get commonAppName() {
|
||||
return this.translationService.getTranslation("commonAppName");
|
||||
}
|
||||
|
||||
get authLoginEnterEmail() {
|
||||
return this.translationService.getTranslation("authLoginEnterEmail");
|
||||
}
|
||||
|
||||
get authRegisterTitle() {
|
||||
return this.translationService.getTranslation("authRegisterTitle");
|
||||
}
|
||||
|
||||
get monitorGetAll() {
|
||||
return this.translationService.getTranslation("monitorGetAll");
|
||||
}
|
||||
|
||||
get monitorGetById() {
|
||||
return this.translationService.getTranslation("monitorGetById");
|
||||
}
|
||||
|
||||
get monitorGetByIdSuccess() {
|
||||
return this.translationService.getTranslation("monitorGetByIdSuccess");
|
||||
}
|
||||
|
||||
get monitorCreate() {
|
||||
return this.translationService.getTranslation("monitorCreate");
|
||||
}
|
||||
|
||||
get bulkMonitorsCreate() {
|
||||
return this.translationService.getTranslation("bulkMonitorsCreate");
|
||||
}
|
||||
|
||||
get monitorEdit() {
|
||||
return this.translationService.getTranslation("monitorEdit");
|
||||
}
|
||||
|
||||
get monitorDelete() {
|
||||
return this.translationService.getTranslation("monitorDelete");
|
||||
}
|
||||
|
||||
get monitorPause() {
|
||||
return this.translationService.getTranslation("monitorPause");
|
||||
}
|
||||
|
||||
get monitorResume() {
|
||||
return this.translationService.getTranslation("monitorResume");
|
||||
}
|
||||
|
||||
get monitorDemoAdded() {
|
||||
return this.translationService.getTranslation("monitorDemoAdded");
|
||||
}
|
||||
|
||||
get monitorStatsById() {
|
||||
return this.translationService.getTranslation("monitorStatsById");
|
||||
}
|
||||
|
||||
get monitorCertificate() {
|
||||
return this.translationService.getTranslation("monitorCertificate");
|
||||
}
|
||||
|
||||
// Maintenance Window Messages
|
||||
get maintenanceWindowCreate() {
|
||||
return this.translationService.getTranslation("maintenanceWindowCreate");
|
||||
}
|
||||
|
||||
get maintenanceWindowGetById() {
|
||||
return this.translationService.getTranslation("maintenanceWindowGetById");
|
||||
}
|
||||
|
||||
get maintenanceWindowGetByTeam() {
|
||||
return this.translationService.getTranslation("maintenanceWindowGetByTeam");
|
||||
}
|
||||
|
||||
get maintenanceWindowDelete() {
|
||||
return this.translationService.getTranslation("maintenanceWindowDelete");
|
||||
}
|
||||
|
||||
get maintenanceWindowEdit() {
|
||||
return this.translationService.getTranslation("maintenanceWindowEdit");
|
||||
}
|
||||
|
||||
// Webhook Messages
|
||||
get webhookUnsupportedPlatform() {
|
||||
return this.translationService.getTranslation("webhookUnsupportedPlatform");
|
||||
}
|
||||
|
||||
get webhookSendError() {
|
||||
return this.translationService.getTranslation("webhookSendError");
|
||||
}
|
||||
|
||||
get webhookSendSuccess() {
|
||||
return this.translationService.getTranslation("webhookSendSuccess");
|
||||
}
|
||||
|
||||
get telegramRequiresBotTokenAndChatId() {
|
||||
return this.translationService.getTranslation("telegramRequiresBotTokenAndChatId");
|
||||
}
|
||||
|
||||
get webhookUrlRequired() {
|
||||
return this.translationService.getTranslation("webhookUrlRequired");
|
||||
}
|
||||
|
||||
get platformRequired() {
|
||||
return this.translationService.getTranslation("platformRequired");
|
||||
}
|
||||
|
||||
get testNotificationFailed() {
|
||||
return this.translationService.getTranslation("testNotificationFailed");
|
||||
}
|
||||
|
||||
get monitorUpAlert() {
|
||||
return this.translationService.getTranslation("monitorUpAlert");
|
||||
}
|
||||
|
||||
get monitorDownAlert() {
|
||||
return this.translationService.getTranslation("monitorDownAlert");
|
||||
}
|
||||
|
||||
getWebhookUnsupportedPlatform(platform) {
|
||||
return this.translationService
|
||||
.getTranslation("webhookUnsupportedPlatform")
|
||||
.replace("{platform}", platform);
|
||||
}
|
||||
|
||||
getWebhookSendError(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);
|
||||
}
|
||||
|
||||
// Error Messages
|
||||
get unknownError() {
|
||||
return this.translationService.getTranslation("unknownError");
|
||||
}
|
||||
|
||||
get friendlyError() {
|
||||
return this.translationService.getTranslation("friendlyError");
|
||||
}
|
||||
|
||||
get authIncorrectPassword() {
|
||||
return this.translationService.getTranslation("authIncorrectPassword");
|
||||
}
|
||||
|
||||
get unauthorized() {
|
||||
return this.translationService.getTranslation("unauthorized");
|
||||
}
|
||||
|
||||
get authAdminExists() {
|
||||
return this.translationService.getTranslation("authAdminExists");
|
||||
}
|
||||
|
||||
get authInviteNotFound() {
|
||||
return this.translationService.getTranslation("authInviteNotFound");
|
||||
}
|
||||
|
||||
get unknownService() {
|
||||
return this.translationService.getTranslation("unknownService");
|
||||
}
|
||||
|
||||
get noAuthToken() {
|
||||
return this.translationService.getTranslation("noAuthToken");
|
||||
}
|
||||
|
||||
get invalidAuthToken() {
|
||||
return this.translationService.getTranslation("invalidAuthToken");
|
||||
}
|
||||
|
||||
get expiredAuthToken() {
|
||||
return this.translationService.getTranslation("expiredAuthToken");
|
||||
}
|
||||
|
||||
// Queue Messages
|
||||
get queueGetMetrics() {
|
||||
return this.translationService.getTranslation("queueGetMetrics");
|
||||
}
|
||||
|
||||
get queueAddJob() {
|
||||
return this.translationService.getTranslation("queueAddJob");
|
||||
}
|
||||
|
||||
get queueObliterate() {
|
||||
return this.translationService.getTranslation("queueObliterate");
|
||||
}
|
||||
|
||||
// Job Queue Messages
|
||||
get jobQueueDeleteJobSuccess() {
|
||||
return this.translationService.getTranslation("jobQueueDeleteJobSuccess");
|
||||
}
|
||||
|
||||
get jobQueuePauseJob() {
|
||||
return this.translationService.getTranslation("jobQueuePauseJob");
|
||||
}
|
||||
|
||||
get jobQueueResumeJob() {
|
||||
return this.translationService.getTranslation("jobQueueResumeJob");
|
||||
}
|
||||
|
||||
// Status Page Messages
|
||||
get statusPageByUrl() {
|
||||
return this.translationService.getTranslation("statusPageByUrl");
|
||||
}
|
||||
|
||||
get statusPageCreate() {
|
||||
return this.translationService.getTranslation("statusPageCreate");
|
||||
}
|
||||
|
||||
get statusPageDelete() {
|
||||
return this.translationService.getTranslation("statusPageDelete");
|
||||
}
|
||||
|
||||
get statusPageUpdate() {
|
||||
return this.translationService.getTranslation("statusPageUpdate");
|
||||
}
|
||||
|
||||
get statusPageNotFound() {
|
||||
return this.translationService.getTranslation("statusPageNotFound");
|
||||
}
|
||||
|
||||
get statusPageByTeamId() {
|
||||
return this.translationService.getTranslation("statusPageByTeamId");
|
||||
}
|
||||
|
||||
get statusPageUrlNotUnique() {
|
||||
return this.translationService.getTranslation("statusPageUrlNotUnique");
|
||||
}
|
||||
|
||||
// Docker Messages
|
||||
get dockerFail() {
|
||||
return this.translationService.getTranslation("dockerFail");
|
||||
}
|
||||
|
||||
get dockerNotFound() {
|
||||
return this.translationService.getTranslation("dockerNotFound");
|
||||
}
|
||||
|
||||
get dockerSuccess() {
|
||||
return this.translationService.getTranslation("dockerSuccess");
|
||||
}
|
||||
|
||||
// Port Messages
|
||||
get portFail() {
|
||||
return this.translationService.getTranslation("portFail");
|
||||
}
|
||||
|
||||
get portSuccess() {
|
||||
return this.translationService.getTranslation("portSuccess");
|
||||
}
|
||||
|
||||
// Alert Messages
|
||||
get alertCreate() {
|
||||
return this.translationService.getTranslation("alertCreate");
|
||||
}
|
||||
|
||||
get alertGetByUser() {
|
||||
return this.translationService.getTranslation("alertGetByUser");
|
||||
}
|
||||
|
||||
get alertGetByMonitor() {
|
||||
return this.translationService.getTranslation("alertGetByMonitor");
|
||||
}
|
||||
|
||||
get alertGetById() {
|
||||
return this.translationService.getTranslation("alertGetById");
|
||||
}
|
||||
|
||||
get alertEdit() {
|
||||
return this.translationService.getTranslation("alertEdit");
|
||||
}
|
||||
|
||||
get alertDelete() {
|
||||
return this.translationService.getTranslation("alertDelete");
|
||||
}
|
||||
|
||||
getDeletedCount(count) {
|
||||
return this.translationService
|
||||
.getTranslation("deletedCount")
|
||||
.replace("{count}", count);
|
||||
}
|
||||
|
||||
get pingSuccess() {
|
||||
return this.translationService.getTranslation("pingSuccess");
|
||||
}
|
||||
|
||||
get getAppSettings() {
|
||||
return this.translationService.getTranslation("getAppSettings");
|
||||
}
|
||||
|
||||
get httpNetworkError() {
|
||||
return this.translationService.getTranslation("httpNetworkError");
|
||||
}
|
||||
|
||||
get httpNotJson() {
|
||||
return this.translationService.getTranslation("httpNotJson");
|
||||
}
|
||||
|
||||
get httpJsonPathError() {
|
||||
return this.translationService.getTranslation("httpJsonPathError");
|
||||
}
|
||||
|
||||
get httpEmptyResult() {
|
||||
return this.translationService.getTranslation("httpEmptyResult");
|
||||
}
|
||||
|
||||
get httpMatchSuccess() {
|
||||
return this.translationService.getTranslation("httpMatchSuccess");
|
||||
}
|
||||
|
||||
get httpMatchFail() {
|
||||
return this.translationService.getTranslation("httpMatchFail");
|
||||
}
|
||||
|
||||
get updateAppSettings() {
|
||||
return this.translationService.getTranslation("updateAppSettings");
|
||||
}
|
||||
|
||||
getDbFindMonitorById(monitorId) {
|
||||
return this.translationService
|
||||
.getTranslation("dbFindMonitorById")
|
||||
.replace("${monitorId}", monitorId);
|
||||
}
|
||||
}
|
||||
|
||||
export default StringService;
|
||||
Executable
+91
@@ -0,0 +1,91 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
class TranslationService {
|
||||
static SERVICE_NAME = "TranslationService";
|
||||
|
||||
constructor(logger) {
|
||||
this.logger = logger;
|
||||
this.translations = {};
|
||||
this._language = "en";
|
||||
this.localesDir = path.join(process.cwd(), "locales");
|
||||
}
|
||||
|
||||
setLanguage(language) {
|
||||
this._language = language;
|
||||
}
|
||||
|
||||
get language() {
|
||||
return this._language;
|
||||
}
|
||||
|
||||
async initialize() {
|
||||
try {
|
||||
await this.loadFromFiles();
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: "TranslationService",
|
||||
method: "initialize",
|
||||
stack: error.stack,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async loadFromFiles() {
|
||||
try {
|
||||
if (!fs.existsSync(this.localesDir)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const files = fs
|
||||
.readdirSync(this.localesDir)
|
||||
.filter((file) => file.endsWith(".json"));
|
||||
|
||||
if (files.length === 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const language = file.replace(".json", "");
|
||||
const filePath = path.join(this.localesDir, file);
|
||||
const content = fs.readFileSync(filePath, "utf8");
|
||||
this.translations[language] = JSON.parse(content);
|
||||
}
|
||||
|
||||
this.logger.info({
|
||||
message: "Translations loaded from files successfully",
|
||||
service: "TranslationService",
|
||||
method: "loadFromFiles",
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: "TranslationService",
|
||||
method: "loadFromFiles",
|
||||
stack: error.stack,
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
getTranslation(key) {
|
||||
let language = this._language;
|
||||
|
||||
try {
|
||||
return this.translations[language]?.[key] || this.translations["en"]?.[key] || key;
|
||||
} catch (error) {
|
||||
this.logger.error({
|
||||
message: error.message,
|
||||
service: "TranslationService",
|
||||
method: "getTranslation",
|
||||
stack: error.stack,
|
||||
});
|
||||
return key;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default TranslationService;
|
||||
Reference in new issue
Block a user