Merge remote-tracking branch 'upstream/develop' into feat/be/webhook-integrations

This commit is contained in:
Skorpios committed 2025-02-12 17:29:57 -08:00
commit 023d9434c1
47 files changed
+1340 -497

No files matched your search

+6 -4
View File
@@ -12,7 +12,7 @@ const QUEUE_LOOKUP = {
};
const getSchedulerId = (monitor) => `scheduler:${monitor.type}:${monitor._id}`;
import { successMessages, errorMessages } from "../utils/messages.js";
class NewJobQueue {
static SERVICE_NAME = SERVICE_NAME;
@@ -22,6 +22,7 @@ class NewJobQueue {
networkService,
notificationService,
settingsService,
stringService,
logger,
Queue,
Worker
@@ -44,6 +45,7 @@ class NewJobQueue {
this.settingsService = settingsService;
this.logger = logger;
this.Worker = Worker;
this.stringService = stringService;
QUEUE_NAMES.forEach((name) => {
this.queues[name] = new Queue(name, { connection });
@@ -455,7 +457,7 @@ class NewJobQueue {
if (wasDeleted === true) {
this.logger.info({
message: successMessages.JOB_QUEUE_DELETE_JOB,
message: this.stringService.jobQueueDeleteJob,
service: SERVICE_NAME,
method: "deleteJob",
details: `Deleted job ${monitor._id}`,
@@ -464,7 +466,7 @@ class NewJobQueue {
await this.scaleWorkers(workerStats, queue);
} else {
this.logger.error({
message: errorMessages.JOB_QUEUE_DELETE_JOB,
message: this.stringService.jobQueueDeleteJob,
service: SERVICE_NAME,
method: "deleteJob",
details: `Failed to delete job ${monitor._id}`,
@@ -587,7 +589,7 @@ class NewJobQueue {
const metrics = await this.getMetrics();
this.logger.info({
message: successMessages.JOB_QUEUE_OBLITERATE,
message: this.stringService.jobQueueObliterate,
service: SERVICE_NAME,
method: "obliterate",
details: metrics,
+69 -18
View File
@@ -1,4 +1,4 @@
import { errorMessages, successMessages } from "../utils/messages.js";
import jmespath from 'jmespath';
const SERVICE_NAME = "NetworkService";
const UPROCK_ENDPOINT = "https://api.uprock.com/checkmate/push";
@@ -13,7 +13,8 @@ const UPROCK_ENDPOINT = "https://api.uprock.com/checkmate/push";
*/
class NetworkService {
static SERVICE_NAME = SERVICE_NAME;
constructor(axios, ping, logger, http, Docker, net) {
constructor(axios, ping, logger, http, Docker, net, stringService) {
this.TYPE_PING = "ping";
this.TYPE_HTTP = "http";
this.TYPE_PAGESPEED = "pagespeed";
@@ -30,6 +31,7 @@ class NetworkService {
this.http = http;
this.Docker = Docker;
this.net = net;
this.stringService = stringService;
}
/**
@@ -87,13 +89,13 @@ class NetworkService {
if (error) {
pingResponse.status = false;
pingResponse.code = this.PING_ERROR;
pingResponse.message = errorMessages.PING_CANNOT_RESOLVE;
pingResponse.message = "No response";
return pingResponse;
}
pingResponse.code = 200;
pingResponse.status = response.alive;
pingResponse.message = successMessages.PING_SUCCESS;
pingResponse.message = "Success";
return pingResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -121,20 +123,19 @@ class NetworkService {
*/
async requestHttp(job) {
try {
const url = job.data.url;
const { url, secret, _id, name, teamId, type, jsonPath, matchMethod, expectedValue } = job.data;
const config = {};
job.data.secret !== undefined &&
(config.headers = { Authorization: `Bearer ${job.data.secret}` });
secret !== undefined && (config.headers = { Authorization: `Bearer ${secret}` });
const { response, responseTime, error } = await this.timeRequest(() =>
this.axios.get(url, config)
);
const httpResponse = {
monitorId: job.data._id,
teamId: job.data.teamId,
type: job.data.type,
monitorId: _id,
teamId,
type,
responseTime,
payload: response?.data,
};
@@ -143,12 +144,62 @@ class NetworkService {
const code = error.response?.status || this.NETWORK_ERROR;
httpResponse.code = code;
httpResponse.status = false;
httpResponse.message = this.http.STATUS_CODES[code] || "Network Error";
httpResponse.message = this.http.STATUS_CODES[code] || this.stringService.httpNetworkError;
return httpResponse;
}
httpResponse.status = true;
httpResponse.code = response.status;
httpResponse.message = this.http.STATUS_CODES[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;
@@ -240,7 +291,7 @@ class NetworkService {
const containers = await docker.listContainers({ all: true });
const containerExists = containers.some((c) => c.Id.startsWith(job.data.url));
if (!containerExists) {
throw new Error(errorMessages.DOCKER_NOT_FOUND);
throw new Error(this.stringService.dockerNotFound);
}
const container = docker.getContainer(job.data.url);
@@ -257,12 +308,12 @@ class NetworkService {
if (error) {
dockerResponse.status = false;
dockerResponse.code = error.statusCode || this.NETWORK_ERROR;
dockerResponse.message = error.reason || errorMessages.DOCKER_FAIL;
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 = successMessages.DOCKER_SUCCESS;
dockerResponse.message = "Docker container status fetched successfully";
return dockerResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
@@ -310,13 +361,13 @@ class NetworkService {
if (error) {
portResponse.status = false;
portResponse.code = this.NETWORK_ERROR;
portResponse.message = errorMessages.PORT_FAIL;
portResponse.message = this.stringService.portFail;
return portResponse;
}
portResponse.status = response.success;
portResponse.code = 200;
portResponse.message = successMessages.PORT_SUCCESS;
portResponse.message = this.stringService.portSuccess;
return portResponse;
} catch (error) {
error.service = this.SERVICE_NAME;
+358
View File
@@ -0,0 +1,358 @@
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 monitorCreate() {
return this.translationService.getTranslation('monitorCreate');
}
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');
}
// 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;
+90
View File
@@ -0,0 +1,90 @@
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;