restore repo structure

This commit is contained in:
Alex Holliday committed 2025-04-20 11:29:53 -07:00
1 parent 6df099a5b6
commit 8b7e3c650b
592 files changed
+37663 -127

No files matched your search

+138
View File
@@ -0,0 +1,138 @@
// **************************
// The idea here is to provide a layer of abstraction between the database and whoever is using it.
// Instead of directly calling mongoose methods, we can call the methods on the DB object.
// If this were Typescript or Java or Golang an interface would be implemented to ensure the methods are available.
// But we do the best we can with Javascript.
//
// If the methods are consistent all we have to do to swap out one DB for another is simply change the import.
//
// Example:
// We start with the fake DB:
//
// const db = require("../db/FakeDb");
// const monitors = await db.getAllMonitors();
//
// And when we want to swtich to a real DB, all we have to do is swap the import
//
// const db = require("../db/MongoDb");
// const monitors = await db.getAllMonitors();
//
// The rest of the code is the same, as all the `db` methods are standardized.
// **************************
const Monitor = require("./models/Monitor");
const UserModel = require("./models/User");
const bcrypt = require("bcrypt");
let FAKE_MONITOR_DATA = [];
const USERS = [];
const connect = async () => {
try {
await console.log("Connected to FakeDB");
} catch (error) {
console.error(error);
}
};
const insertUser = async (req, res) => {
try {
const newUser = new UserModel({ ...req.body });
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
newUser.password = await bcrypt.hash(newUser.password, salt); // hash is also async, need to eitehr await or use hashSync
USERS.push(newUser);
const userToReturn = { ...newUser._doc };
delete userToReturn.password;
return userToReturn;
} catch (error) {
throw error;
}
};
const getUserByEmail = async (req, res) => {
const email = req.body.email;
try {
const idx = USERS.findIndex((user) => {
return user.email === email;
});
if (idx === -1) {
return null;
}
return USERS[idx];
} catch (error) {
throw new Error(`User with email ${email} not found`);
}
};
const getAllMonitors = async () => {
return FAKE_MONITOR_DATA;
};
const getMonitorById = async (monitorId) => {
const idx = FAKE_MONITOR_DATA.findIndex((monitor) => {
return monitor.id === monitorId;
});
if (idx === -1) {
throw new Error(`Monitor with id ${monitorId} not found`);
}
return FAKE_MONITOR_DATA[idx];
};
const getMonitorsByUserId = async (userId) => {
const userMonitors = FAKE_MONITOR_DATA.filter((monitor) => {
return monitor.userId === userId;
});
if (userMonitors.length === 0) {
throw new Error(`Monitors for user ${userId} not found`);
}
return userMonitors;
};
const createMonitor = async (req, res) => {
const monitor = new Monitor(req.body);
monitor.createdAt = Date.now();
monitor.updatedAt = Date.now();
FAKE_MONITOR_DATA.push(monitor);
return monitor;
};
const deleteMonitor = async (req, res) => {
const monitorId = req.params.monitorId;
try {
const monitor = getMonitorById(monitorId);
FAKE_MONITOR_DATA = FAKE_MONITOR_DATA.filter((monitor) => {
return monitor.id !== monitorId;
});
return monitor;
} catch (error) {
throw error;
}
};
const editMonitor = async (req, res) => {
const monitorId = req.params.monitorId;
const idx = FAKE_MONITOR_DATA.findIndex((monitor) => {
return monitor._id.toString() === monitorId;
});
const oldMonitor = FAKE_MONITOR_DATA[idx];
const editedMonitor = new Monitor({ ...req.body });
editedMonitor._id = oldMonitor._id;
editedMonitor.userId = oldMonitor.userId;
editedMonitor.updatedAt = Date.now();
editedMonitor.createdAt = oldMonitor.createdAt;
FAKE_MONITOR_DATA[idx] = editedMonitor;
return FAKE_MONITOR_DATA[idx];
};
module.exports = {
connect,
insertUser,
getUserByEmail,
getAllMonitors,
getMonitorById,
getMonitorsByUserId,
createMonitor,
deleteMonitor,
editMonitor,
};
+80
View File
@@ -0,0 +1,80 @@
import mongoose from "mongoose";
const AppSettingsSchema = mongoose.Schema(
{
apiBaseUrl: {
type: String,
required: true,
default: "http://localhost:5000/api/v1",
},
language: {
type: String,
default: "en",
},
logLevel: {
type: String,
default: "debug",
enum: ["debug", "none", "error", "warn"],
},
clientHost: {
type: String,
required: true,
default: "http://localhost:5173",
},
jwtSecret: {
type: String,
required: true,
default: "my_secret",
},
dbType: {
type: String,
required: true,
default: "MongoDB",
},
dbConnectionString: {
type: String,
required: true,
default: "mongodb://localhost:27017/uptime_db",
},
redisUrl: {
type: String,
default: "redis://127.0.0.1:6379",
},
jwtTTL: {
type: String,
required: true,
default: "2h",
},
pagespeedApiKey: {
type: String,
default: "",
},
systemEmailHost: {
type: String,
default: "smtp.gmail.com",
},
systemEmailPort: {
type: Number,
default: 465,
},
systemEmailAddress: {
type: String,
default: "",
},
systemEmailPassword: {
type: String,
default: "",
},
singleton: {
type: Boolean,
required: true,
unique: true,
default: true,
},
},
{
timestamps: true,
}
);
export default mongoose.model("AppSettings", AppSettingsSchema);
+83
View File
@@ -0,0 +1,83 @@
import mongoose from "mongoose";
const BaseCheckSchema = mongoose.Schema({
/**
* Reference to the associated Monitor document.
*
* @type {mongoose.Schema.Types.ObjectId}
*/
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
index: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
index: true,
},
/**
* Status of the check (true for up, false for down).
*
* @type {Boolean}
*/
status: {
type: Boolean,
index: true,
},
/**
* Response time of the check in milliseconds.
*
* @type {Number}
*/
responseTime: {
type: Number,
},
/**
* HTTP status code received during the check.
*
* @type {Number}
*/
statusCode: {
type: Number,
index: true,
},
/**
* Message or description of the check result.
*
* @type {String}
*/
message: {
type: String,
},
/**
* Expiry date of the check, auto-calculated to expire after 30 days.
*
* @type {Date}
*/
expiry: {
type: Date,
default: Date.now,
expires: 60 * 60 * 24 * 30, // 30 days
},
});
/**
* Check Schema for MongoDB collection.
*
* Represents a check associated with a monitor, storing information
* about the status and response of a particular check event.
*/
const CheckSchema = mongoose.Schema({ ...BaseCheckSchema.obj }, { timestamps: true });
CheckSchema.index({ updatedAt: 1 });
CheckSchema.index({ monitorId: 1, updatedAt: 1 });
CheckSchema.index({ monitorId: 1, updatedAt: -1 });
CheckSchema.index({ teamId: 1, updatedAt: -1 });
CheckSchema.index({ teamId: 1 });
export default mongoose.model("Check", CheckSchema);
export { BaseCheckSchema };
+137
View File
@@ -0,0 +1,137 @@
import mongoose from "mongoose";
import { BaseCheckSchema } from "./Check.js";
// {
// "id": "12123",
// "result": {
// "task_arrived": "2025-01-13T19:21:37.463466602Z",
// "dns_start": "2025-01-14T00:21:33.1801319+05:00",
// "dns_end": "2025-01-14T00:21:33.4582552+05:00",
// "conn_start": "2025-01-14T00:21:33.1801319+05:00",
// "conn_end": "2025-01-14T00:21:33.7076318+05:00",
// "connect_start": "2025-01-14T00:21:33.4582552+05:00",
// "connect_end": "2025-01-14T00:21:33.541899+05:00",
// "tls_hand_shake_start": "2025-01-14T00:21:33.541899+05:00",
// "tls_hand_shake_end": "2025-01-14T00:21:33.7076318+05:00",
// "body_read_start": "2025-01-14T00:21:34.1894707+05:00",
// "body_read_end": "2025-01-14T00:21:34.1894707+05:00",
// "wrote_request": "2025-01-14T00:21:33.7076318+05:00",
// "got_first_response_byte": "2025-01-14T00:21:34.1327652+05:00",
// "first_byte_took": 425133400,
// "body_read_took": 56030000,
// "dns_took": 278123300,
// "conn_took": 527499900,
// "connect_took": 83643800,
// "tls_took": 165732800,
// "sni_name": "uprock.com",
// "status_code": 200,
// "body_size": 19320,
// "request_header_size": 95,
// "response_header_size": 246,
// "response_headers": "X-Vercel-Id: bom1::iad1::sm87v-1736796096856-aec270c01f23\nDate: Mon, 13 Jan 2025 19:21:37 GMT\nServer: Vercel\nStrict-Transport-Security: max-age=63072000\nVary: RSC, Next-Router-State-Tree, Next-Router-Prefetch, Next-Url\nX-Matched-Path: /\nX-Powered-By: Next.js\nX-Vercel-Cache: MISS\nAge: 0\nCache-Control: private, no-cache, no-store, max-age=0, must-revalidate\nContent-Type: text/html; charset=utf-8",
// "error": "",
// "device_id": "d5f578e143a2cd603dd6bf5f846a86a538bde4a8fbe2ad1fca284ad9f033daf8",
// "ip_address": "223.123.19.0",
// "proof": "",
// "created_at": "2025-01-13T19:21:37.463466912Z",
// "continent": "AS",
// "country_code": "PK",
// "city": "Muzaffargarh",
// "upt_burnt" : "0.01",
// "location": {
// "lat": 71.0968,
// "lng": 30.0208
// },
// "payload": {
// "callback": "https://webhook.site/2a15b0af-545a-4ac2-b913-153b97592d7a",
// "x": "y"
// }
// }
// }
const LocationSchema = new mongoose.Schema(
{
lat: { type: Number, required: true },
lng: { type: Number, required: true },
},
{ _id: false }
);
const DistributedUptimeCheckSchema = mongoose.Schema(
{
...BaseCheckSchema.obj,
first_byte_took: {
type: Number,
required: false,
},
body_read_took: {
type: Number,
required: false,
},
dns_took: {
type: Number,
required: false,
},
conn_took: {
type: Number,
required: false,
},
connect_took: {
type: Number,
required: false,
},
tls_took: {
type: Number,
required: false,
},
location: {
type: LocationSchema,
required: false,
},
continent: {
type: String,
required: false,
},
countryCode: {
type: String,
required: false,
},
city: {
type: String,
required: false,
},
uptBurnt: {
type: mongoose.Schema.Types.Decimal128,
required: false,
},
count: {
type: Number,
required: false,
},
},
{ timestamps: true }
);
DistributedUptimeCheckSchema.pre("save", function (next) {
if (this.isModified("uptBurnt") && typeof this.uptBurnt === "string") {
this.uptBurnt = mongoose.Types.Decimal128.fromString(this.uptBurnt);
}
next();
});
DistributedUptimeCheckSchema.index({ createdAt: 1 });
DistributedUptimeCheckSchema.index({ monitorId: 1, updatedAt: 1 });
DistributedUptimeCheckSchema.index({ monitorId: 1, updatedAt: -1 });
DistributedUptimeCheckSchema.index(
{
monitorId: 1,
createdAt: -1,
city: 1,
"location.lat": 1,
"location.lng": 1,
responseTime: 1,
},
{ background: true }
);
export default mongoose.model("DistributedUptimeCheck", DistributedUptimeCheckSchema);
+70
View File
@@ -0,0 +1,70 @@
import mongoose from "mongoose";
import { BaseCheckSchema } from "./Check.js";
const cpuSchema = mongoose.Schema({
physical_core: { type: Number, default: 0 },
logical_core: { type: Number, default: 0 },
frequency: { type: Number, default: 0 },
temperature: { type: [Number], default: [] },
free_percent: { type: Number, default: 0 },
usage_percent: { type: Number, default: 0 },
});
const memorySchema = mongoose.Schema({
total_bytes: { type: Number, default: 0 },
available_bytes: { type: Number, default: 0 },
used_bytes: { type: Number, default: 0 },
usage_percent: { type: Number, default: 0 },
});
const diskSchema = mongoose.Schema({
read_speed_bytes: { type: Number, default: 0 },
write_speed_bytes: { type: Number, default: 0 },
total_bytes: { type: Number, default: 0 },
free_bytes: { type: Number, default: 0 },
usage_percent: { type: Number, default: 0 },
});
const hostSchema = mongoose.Schema({
os: { type: String, default: "" },
platform: { type: String, default: "" },
kernel_version: { type: String, default: "" },
});
const errorSchema = mongoose.Schema({
metric: { type: [String], default: [] },
err: { type: String, default: "" },
});
const HardwareCheckSchema = mongoose.Schema(
{
...BaseCheckSchema.obj,
cpu: {
type: cpuSchema,
default: () => ({}),
},
memory: {
type: memorySchema,
default: () => ({}),
},
disk: {
type: [diskSchema],
default: () => [],
},
host: {
type: hostSchema,
default: () => ({}),
},
errors: {
type: [errorSchema],
default: () => [],
},
},
{ timestamps: true }
);
HardwareCheckSchema.index({ createdAt: 1 });
HardwareCheckSchema.index({ monitorId: 1, createdAt: 1 });
HardwareCheckSchema.index({ monitorId: 1, createdAt: -1 });
export default mongoose.model("HardwareCheck", HardwareCheckSchema);
+34
View File
@@ -0,0 +1,34 @@
import mongoose from "mongoose";
const InviteTokenSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
role: {
type: Array,
required: true,
},
token: {
type: String,
required: true,
},
expiry: {
type: Date,
default: Date.now,
expires: 3600,
},
},
{
timestamps: true,
}
);
export default mongoose.model("InviteToken", InviteTokenSchema);
+68
View File
@@ -0,0 +1,68 @@
import mongoose from "mongoose";
/**
* MaintenanceWindow Schema
* @module MaintenanceWindow
* @typedef {Object} MaintenanceWindow
* @property {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor. This is a reference to the Monitor model and is immutable.
* @property {Boolean} active - Indicates whether the maintenance window is active.
* @property {Number} repeat - Indicates how often this maintenance window should repeat.
* @property {Date} start - The start date and time of the maintenance window.
* @property {Date} end - The end date and time of the maintenance window.
* @property {Date} expiry - The expiry date and time of the maintenance window. This is used for MongoDB's TTL index to automatically delete the document at this time. This field is set to the same value as `end` when `oneTime` is `true`.
*
* @example
*
* let maintenanceWindow = new MaintenanceWindow({
* monitorId: monitorId,
* active: active,
* repeat: repeat,
* start: start,
* end: end,
* });
*
* if (repeat === 0) {
* maintenanceWindow.expiry = end;
* }
*
*/
const MaintenanceWindow = mongoose.Schema(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
},
active: {
type: Boolean,
default: true,
},
name: {
type: String,
},
repeat: {
type: Number,
},
start: {
type: Date,
},
end: {
type: Date,
},
expiry: {
type: Date,
index: { expires: "0s" },
},
},
{
timestamps: true,
}
);
export default mongoose.model("MaintenanceWindow", MaintenanceWindow);
+98
View File
@@ -0,0 +1,98 @@
import mongoose from "mongoose";
const MonitorSchema = mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
immutable: true,
required: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
name: {
type: String,
required: true,
},
description: {
type: String,
},
status: {
type: Boolean,
default: undefined,
},
type: {
type: String,
required: true,
enum: [
"http",
"ping",
"pagespeed",
"hardware",
"docker",
"port",
"distributed_http",
"distributed_test",
],
},
jsonPath: {
type: String,
},
expectedValue: {
type: String,
},
matchMethod: {
type: String,
enum: ["equal", "include", "regex"],
},
url: {
type: String,
required: true,
},
port: {
type: Number,
},
isActive: {
type: Boolean,
default: true,
},
interval: {
// in milliseconds
type: Number,
default: 60000,
},
uptimePercentage: {
type: Number,
default: undefined,
},
thresholds: {
type: {
usage_cpu: { type: Number },
usage_memory: { type: Number },
usage_disk: { type: Number },
usage_temperature: { type: Number },
},
_id: false,
},
notifications: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Notification",
},
],
secret: {
type: String,
},
},
{
timestamps: true,
}
);
MonitorSchema.index({ teamId: 1, type: 1 });
export default mongoose.model("Monitor", MonitorSchema);
+53
View File
@@ -0,0 +1,53 @@
import mongoose from "mongoose";
const MonitorStatsSchema = new mongoose.Schema(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
index: true,
},
avgResponseTime: {
type: Number,
default: 0,
},
totalChecks: {
type: Number,
default: 0,
},
totalUpChecks: {
type: Number,
default: 0,
},
totalDownChecks: {
type: Number,
default: 0,
},
uptimePercentage: {
type: Number,
default: 0,
},
lastCheckTimestamp: {
type: Number,
default: 0,
},
lastResponseTime: {
type: Number,
default: 0,
},
timeOfLastFailure: {
type: Number,
default: 0,
},
uptBurnt: {
type: mongoose.Schema.Types.Decimal128,
required: false,
},
},
{ timestamps: true }
);
const MonitorStats = mongoose.model("MonitorStats", MonitorStatsSchema);
export default MonitorStats;
+97
View File
@@ -0,0 +1,97 @@
import mongoose from "mongoose";
const configSchema = mongoose.Schema(
{
webhookUrl: { type: String },
botToken: { type: String },
chatId: { type: String },
},
{ _id: false }
);
const NotificationSchema = mongoose.Schema(
{
monitorId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
immutable: true,
},
type: {
type: String,
enum: ["email", "sms", "webhook"],
},
platform: {
type: String,
},
config: {
type: configSchema,
default: () => ({}),
},
address: {
type: String,
},
phone: {
type: String,
},
alertThreshold: {
type: Number,
default: 5,
},
cpuAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
memoryAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
diskAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
tempAlertThreshold: {
type: Number,
default: function () {
return this.alertThreshold;
},
},
},
{
timestamps: true,
}
);
NotificationSchema.pre("save", function (next) {
if (!this.cpuAlertThreshold || this.isModified("alertThreshold")) {
this.cpuAlertThreshold = this.alertThreshold;
}
if (!this.memoryAlertThreshold || this.isModified("alertThreshold")) {
this.memoryAlertThreshold = this.alertThreshold;
}
if (!this.diskAlertThreshold || this.isModified("alertThreshold")) {
this.diskAlertThreshold = this.alertThreshold;
}
if (!this.tempAlertThreshold || this.isModified("alertThreshold")) {
this.tempAlertThreshold = this.alertThreshold;
}
next();
});
NotificationSchema.pre("findOneAndUpdate", function (next) {
const update = this.getUpdate();
if (update.alertThreshold) {
update.cpuAlertThreshold = update.alertThreshold;
update.memoryAlertThreshold = update.alertThreshold;
update.diskAlertThreshold = update.alertThreshold;
update.tempAlertThreshold = update.alertThreshold;
}
next();
});
export default mongoose.model("Notification", NotificationSchema);
+85
View File
@@ -0,0 +1,85 @@
import mongoose from "mongoose";
import { BaseCheckSchema } from "./Check.js";
import logger from "../../utils/logger.js";
import { time } from "console";
const AuditSchema = mongoose.Schema({
id: { type: String, required: true },
title: { type: String, required: true },
description: { type: String, required: true },
score: { type: Number, required: true },
scoreDisplayMode: { type: String, required: true },
displayValue: { type: String, required: true },
numericValue: { type: Number, required: true },
numericUnit: { type: String, required: true },
});
const AuditsSchema = mongoose.Schema({
cls: {
type: AuditSchema,
required: true,
},
si: {
type: AuditSchema,
required: true,
},
fcp: {
type: AuditSchema,
required: true,
},
lcp: {
type: AuditSchema,
required: true,
},
tbt: {
type: AuditSchema,
required: true,
},
});
/**
* Mongoose schema for storing metrics from Google Lighthouse.
* @typedef {Object} PageSpeedCheck
* @property {mongoose.Schema.Types.ObjectId} monitorId - Reference to the Monitor model.
* @property {number} accessibility - Accessibility score.
* @property {number} bestPractices - Best practices score.
* @property {number} seo - SEO score.
* @property {number} performance - Performance score.
*/
const PageSpeedCheck = mongoose.Schema(
{
...BaseCheckSchema.obj,
accessibility: {
type: Number,
required: true,
},
bestPractices: {
type: Number,
required: true,
},
seo: {
type: Number,
required: true,
},
performance: {
type: Number,
required: true,
},
audits: {
type: AuditsSchema,
required: true,
},
},
{ timestamps: true }
);
/**
* Mongoose model for storing metrics from Google Lighthouse.
* @typedef {mongoose.Model<PageSpeedCheck>} LighthouseMetricsModel
*/
PageSpeedCheck.index({ createdAt: 1 });
PageSpeedCheck.index({ monitorId: 1, createdAt: 1 });
PageSpeedCheck.index({ monitorId: 1, createdAt: -1 });
export default mongoose.model("PageSpeedCheck", PageSpeedCheck);
+25
View File
@@ -0,0 +1,25 @@
import mongoose from "mongoose";
const RecoveryTokenSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
token: {
type: String,
required: true,
},
expiry: {
type: Date,
default: Date.now,
expires: 600,
},
},
{
timestamps: true,
}
);
export default mongoose.model("RecoveryToken", RecoveryTokenSchema);
+77
View File
@@ -0,0 +1,77 @@
import mongoose from "mongoose";
const StatusPageSchema = mongoose.Schema(
{
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
immutable: true,
required: true,
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
required: true,
},
type: {
type: String,
required: true,
default: "uptime",
enum: ["uptime", "distributed"],
},
companyName: {
type: String,
required: true,
default: "",
},
url: {
type: String,
unique: true,
required: true,
default: "",
},
timezone: {
type: String,
required: false,
},
color: {
type: String,
required: false,
default: "#4169E1",
},
monitors: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
required: true,
},
],
subMonitors: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Monitor",
required: true,
},
],
logo: {
data: Buffer,
contentType: String,
},
isPublished: {
type: Boolean,
default: false,
},
showCharts: {
type: Boolean,
default: true,
},
showUptimePercentage: {
type: Boolean,
default: true,
},
},
{ timestamps: true }
);
export default mongoose.model("StatusPage", StatusPageSchema);
+14
View File
@@ -0,0 +1,14 @@
import mongoose from "mongoose";
const TeamSchema = mongoose.Schema(
{
email: {
type: String,
required: true,
unique: true,
},
},
{
timestamps: true,
}
);
export default mongoose.model("Team", TeamSchema);
+92
View File
@@ -0,0 +1,92 @@
import mongoose from "mongoose";
import bcrypt from "bcrypt";
import logger from "../../utils/logger.js";
const UserSchema = mongoose.Schema(
{
firstName: {
type: String,
required: true,
},
lastName: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
avatarImage: {
type: String,
},
profileImage: {
data: Buffer,
contentType: String,
},
isActive: {
type: Boolean,
default: true,
},
isVerified: {
type: Boolean,
default: false,
},
role: {
type: [String],
default: "user",
enum: ["user", "admin", "superadmin", "demo"],
},
teamId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Team",
immutable: true,
},
checkTTL: {
type: Number,
},
},
{
timestamps: true,
}
);
UserSchema.pre("save", async function (next) {
if (!this.isModified("password")) {
next();
}
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
this.password = await bcrypt.hash(this.password, salt); // hash is also async, need to eitehr await or use hashSync
next();
});
UserSchema.pre("findOneAndUpdate", async function (next) {
const update = this.getUpdate();
if ("password" in update) {
const salt = await bcrypt.genSalt(10); //genSalt is asynchronous, need to wait
update.password = await bcrypt.hash(update.password, salt); // hash is also async, need to eitehr await or use hashSync
}
next();
});
UserSchema.methods.comparePassword = async function (submittedPassword) {
const res = await bcrypt.compare(submittedPassword, this.password);
return res;
};
const User = mongoose.model("User", UserSchema);
User.init().then(() => {
logger.info({
message: "User model initialized",
service: "UserModel",
method: "init",
});
});
export default mongoose.model("User", UserSchema);
+156
View File
@@ -0,0 +1,156 @@
import mongoose from "mongoose";
import UserModel from "../models/User.js";
import AppSettings from "../models/AppSettings.js";
import logger from "../../utils/logger.js";
//****************************************
// User Operations
//****************************************
import * as userModule from "./modules/userModule.js";
//****************************************
// Invite Token Operations
//****************************************
import * as inviteModule from "./modules/inviteModule.js";
//****************************************
// Recovery Operations
//****************************************
import * as recoveryModule from "./modules/recoveryModule.js";
//****************************************
// Monitors
//****************************************
import * as monitorModule from "./modules/monitorModule.js";
//****************************************
// Page Speed Checks
//****************************************
import * as pageSpeedCheckModule from "./modules/pageSpeedCheckModule.js";
//****************************************
// Hardware Checks
//****************************************
import * as hardwareCheckModule from "./modules/hardwareCheckModule.js";
//****************************************
// Checks
//****************************************
import * as checkModule from "./modules/checkModule.js";
//****************************************
// Distributed Checks
//****************************************
import * as distributedCheckModule from "./modules/distributedCheckModule.js";
//****************************************
// Maintenance Window
//****************************************
import * as maintenanceWindowModule from "./modules/maintenanceWindowModule.js";
//****************************************
// Notifications
//****************************************
import * as notificationModule from "./modules/notificationModule.js";
//****************************************
// AppSettings
//****************************************
import * as settingsModule from "./modules/settingsModule.js";
//****************************************
// Status Page
//****************************************
import * as statusPageModule from "./modules/statusPageModule.js";
//****************************************
// Diagnostic
//****************************************
import * as diagnosticModule from "./modules/diagnosticModule.js";
class MongoDB {
static SERVICE_NAME = "MongoDB";
constructor() {
Object.assign(this, userModule);
Object.assign(this, inviteModule);
Object.assign(this, recoveryModule);
Object.assign(this, monitorModule);
Object.assign(this, pageSpeedCheckModule);
Object.assign(this, hardwareCheckModule);
Object.assign(this, checkModule);
Object.assign(this, distributedCheckModule);
Object.assign(this, maintenanceWindowModule);
Object.assign(this, notificationModule);
Object.assign(this, settingsModule);
Object.assign(this, statusPageModule);
Object.assign(this, diagnosticModule);
}
connect = async () => {
try {
const connectionString =
process.env.DB_CONNECTION_STRING || "mongodb://localhost:27017/uptime_db";
await mongoose.connect(connectionString);
// If there are no AppSettings, create one
await AppSettings.findOneAndUpdate(
{}, // empty filter to match any document
{}, // empty update
{
new: true,
setDefaultsOnInsert: true,
}
);
// Sync indexes
const models = mongoose.modelNames();
for (const modelName of models) {
const model = mongoose.model(modelName);
await model.syncIndexes();
}
logger.info({
message: "Connected to MongoDB",
service: this.SERVICE_NAME,
method: "connect",
});
} catch (error) {
logger.error({
message: error.message,
service: this.SERVICE_NAME,
method: "connect",
stack: error.stack,
});
throw error;
}
};
disconnect = async () => {
try {
logger.info({ message: "Disconnecting from MongoDB" });
await mongoose.disconnect();
logger.info({ message: "Disconnected from MongoDB" });
return;
} catch (error) {
logger.error({
message: error.message,
service: this.SERVICE_NAME,
method: "disconnect",
stack: error.stack,
});
}
};
checkSuperadmin = async (req, res) => {
const superAdmin = await UserModel.findOne({ role: "superadmin" });
if (superAdmin !== null) {
return true;
}
return false;
};
}
export default MongoDB;
+319
View File
@@ -0,0 +1,319 @@
import Check from "../../models/Check.js";
import Monitor from "../../models/Monitor.js";
import HardwareCheck from "../../models/HardwareCheck.js";
import PageSpeedCheck from "../../models/PageSpeedCheck.js";
import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import User from "../../models/User.js";
import logger from "../../../utils/logger.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "checkModule";
const dateRangeLookup = {
recent: new Date(new Date().setDate(new Date().getDate() - 2)),
hour: new Date(new Date().setHours(new Date().getHours() - 1)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
all: undefined,
};
/**
* Create a check for a monitor
* @async
* @param {Object} checkData
* @param {string} checkData.monitorId
* @param {boolean} checkData.status
* @param {number} checkData.responseTime
* @param {number} checkData.statusCode
* @param {string} checkData.message
* @returns {Promise<Check>}
* @throws {Error}
*/
const createCheck = async (checkData) => {
try {
const check = await new Check({ ...checkData }).save();
return check;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createCheck";
throw error;
}
};
const createChecks = async (checks) => {
try {
await Check.insertMany(checks);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createCheck";
throw error;
}
};
/**
* Get all checks for a monitor
* @async
* @param {string} monitorId
* @returns {Promise<Array<Check>>}
* @throws {Error}
*/
const getChecksByMonitor = async (req) => {
try {
const { monitorId } = req.params;
let { type, sortOrder, dateRange, filter, page, rowsPerPage, status } = req.query;
status = typeof status !== "undefined" ? false : undefined;
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
// Match
const matchStage = {
monitorId: ObjectId.createFromHexString(monitorId),
...(typeof status !== "undefined" && { status }),
...(dateRangeLookup[dateRange] && {
createdAt: {
$gte: dateRangeLookup[dateRange],
},
}),
};
if (filter !== undefined) {
switch (filter) {
case "all":
break;
case "down":
break;
case "resolve":
matchStage.statusCode = 5000;
break;
default:
logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getChecks",
});
break;
}
}
//Sort
sortOrder = sortOrder === "asc" ? 1 : -1;
// Pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
const checkModels = {
http: Check,
ping: Check,
docker: Check,
port: Check,
pagespeed: PageSpeedCheck,
hardware: HardwareCheck,
distributed_http: DistributedUptimeCheck,
distributed_test: DistributedUptimeCheck,
};
const Model = checkModels[type];
const checks = await Model.aggregate([
{ $match: matchStage },
{ $sort: { createdAt: sortOrder } },
{
$facet: {
summary: [{ $count: "checksCount" }],
checks: [{ $skip: skip }, { $limit: rowsPerPage }],
},
},
{
$project: {
checksCount: {
$ifNull: [{ $arrayElemAt: ["$summary.checksCount", 0] }, 0],
},
checks: {
$ifNull: ["$checks", []],
},
},
},
]);
return checks[0];
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getChecks";
throw error;
}
};
const getChecksByTeam = async (req) => {
try {
let { sortOrder, dateRange, filter, page, rowsPerPage } = req.query;
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
const { teamId } = req.params;
const matchStage = {
teamId: ObjectId.createFromHexString(teamId),
status: false,
...(dateRangeLookup[dateRange] && {
createdAt: {
$gte: dateRangeLookup[dateRange],
},
}),
};
// Add filter to match stage
if (filter !== undefined) {
switch (filter) {
case "all":
break;
case "down":
break;
case "resolve":
matchStage.statusCode = 5000;
break;
default:
logger.warn({
message: "invalid filter",
service: SERVICE_NAME,
method: "getChecksByTeam",
});
break;
}
}
sortOrder = sortOrder === "asc" ? 1 : -1;
// pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
const aggregatePipeline = [
{ $match: matchStage },
{
$unionWith: {
coll: "hardwarechecks",
pipeline: [{ $match: matchStage }],
},
},
{
$unionWith: {
coll: "pagespeedchecks",
pipeline: [{ $match: matchStage }],
},
},
{
$unionWith: {
coll: "distributeduptimechecks",
pipeline: [{ $match: matchStage }],
},
},
{ $sort: { createdAt: sortOrder } },
{
$facet: {
summary: [{ $count: "checksCount" }],
checks: [{ $skip: skip }, { $limit: rowsPerPage }],
},
},
{
$project: {
checksCount: { $arrayElemAt: ["$summary.checksCount", 0] },
checks: "$checks",
},
},
];
const checks = await Check.aggregate(aggregatePipeline);
return checks[0];
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getChecksByTeam";
throw error;
}
};
/**
* Delete all checks for a monitor
* @async
* @param {string} monitorId
* @returns {number}
* @throws {Error}
*/
const deleteChecks = async (monitorId) => {
try {
const result = await Check.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecks";
throw error;
}
};
/**
* Delete all checks for a team
* @async
* @param {string} monitorId
* @returns {number}
* @throws {Error}
*/
const deleteChecksByTeamId = async (teamId) => {
try {
// Find all monitor IDs for this team (only get _id field for efficiency)
const teamMonitors = await Monitor.find({ teamId }, { _id: 1 });
const monitorIds = teamMonitors.map((monitor) => monitor._id);
// Delete all checks for these monitors in one operation
const deleteResult = await Check.deleteMany({ monitorId: { $in: monitorIds } });
return deleteResult.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteChecksByTeamId";
throw error;
}
};
const updateChecksTTL = async (teamId, ttl) => {
try {
await Check.collection.dropIndex("expiry_1");
} catch (error) {
logger.error({
message: error.message,
service: SERVICE_NAME,
method: "updateChecksTTL",
stack: error.stack,
});
}
try {
await Check.collection.createIndex(
{ expiry: 1 },
{ expireAfterSeconds: ttl } // TTL in seconds, adjust as necessary
);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateChecksTTL";
throw error;
}
// Update user
try {
await User.updateMany({ teamId: teamId }, { checkTTL: ttl });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateChecksTTL";
throw error;
}
};
export {
createCheck,
createChecks,
getChecksByMonitor,
getChecksByTeam,
deleteChecks,
deleteChecksByTeamId,
updateChecksTTL,
};
+107
View File
@@ -0,0 +1,107 @@
import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import Monitor from "../../models/Monitor.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "diagnosticModule";
import {
buildMonitorSummaryByTeamIdPipeline,
buildMonitorsByTeamIdPipeline,
buildFilteredMonitorsByTeamIdPipeline,
buildDePINDetailsByDateRange,
buildDePINLatestChecks,
} from "./monitorModuleQueries.js";
import { getDateRange } from "./monitorModule.js";
const getDistributedUptimeDbExecutionStats = async (req) => {
try {
const { monitorId } = req?.params ?? {};
if (typeof monitorId === "undefined") {
throw new Error();
}
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
throw new Error(this.stringService.dbFindMonitorById(monitorId));
}
const { dateRange } = req.query;
const dates = getDateRange(dateRange);
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: {
$concat: [
{ $dateToString: { format: "%Y-%m-%dT%H:", date: "$createdAt" } },
{
$cond: [{ $lt: [{ $minute: "$createdAt" }, 30] }, "00:00Z", "30:00Z"],
},
],
},
week: "%Y-%m-%dT%H:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const dePINDetailsByDateRangeStats = await DistributedUptimeCheck.aggregate(
buildDePINDetailsByDateRange(monitor, dates, dateString)
).explain("executionStats");
const latestChecksStats = await DistributedUptimeCheck.aggregate(
buildDePINLatestChecks(monitor)
).explain("executionStats");
return {
dePINDetailsByDateRangeStats,
latestChecksStats,
};
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitorsWithUptimeStats";
throw error;
}
};
const getMonitorsByTeamIdExecutionStats = async (req) => {
try {
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
if (field === undefined) {
field = "name";
order = "asc";
}
// Build match stage
const matchStage = { teamId: ObjectId.createFromHexString(req.params.teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
const summary = await Monitor.aggregate(
buildMonitorSummaryByTeamIdPipeline({ matchStage })
).explain("executionStats");
const monitors = await Monitor.aggregate(
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
).explain("executionStats");
const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
).explain("executionStats");
return { summary, monitors, filteredMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorSummaryByTeamIdExecutionStats";
throw error;
}
};
export { getDistributedUptimeDbExecutionStats, getMonitorsByTeamIdExecutionStats };
+157
View File
@@ -0,0 +1,157 @@
import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import { ObjectId } from "mongodb";
const SERVICE_NAME = "distributedCheckModule";
const createDistributedCheck = async (checkData) => {
try {
if (typeof checkData.monitorId === "string") {
checkData.monitorId = ObjectId.createFromHexString(checkData.monitorId);
}
const check = await DistributedUptimeCheck.findOneAndUpdate(
{
monitorId: checkData.monitorId,
city: checkData.city,
},
[
{
$set: {
...checkData,
responseTime: {
$cond: {
if: { $ifNull: ["$count", false] },
then: {
$cond: {
// Check if the new value is an outlier (3x the current average)
if: {
$and: [
{ $gt: ["$responseTime", 0] },
{
$gt: [
checkData.responseTime,
{ $multiply: ["$responseTime", 3] },
],
},
],
},
then: "$responseTime", // Keep the current value if it's an outlier
else: {
// Normal case - calculate new average
$round: [
{
$divide: [
{
$add: [
{ $multiply: ["$responseTime", "$count"] },
checkData.responseTime,
],
},
{ $add: ["$count", 1] },
],
},
2,
],
},
},
},
else: checkData.responseTime,
},
},
count: { $add: [{ $ifNull: ["$count", 0] }, 1] },
},
},
],
{
upsert: true,
new: true,
runValidators: true,
}
);
return check;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createCheck";
throw error;
}
};
const createDistributedChecks = async (checksData) => {
try {
if (!Array.isArray(checksData) || checksData.length === 0) {
return;
}
const bulkOps = checksData.map((checkData) => {
if (typeof checkData.monitorId === "string") {
checkData.monitorId = ObjectId.createFromHexString(checkData.monitorId);
}
return {
updateOne: {
filter: {
monitorId: checkData.monitorId,
city: checkData.city,
},
update: [
{
$set: {
...checkData,
responseTime: {
$cond: {
if: { $ifNull: ["$count", false] },
then: {
$round: [
{
$divide: [
{
$add: [
{ $multiply: ["$responseTime", "$count"] },
checkData.responseTime,
],
},
{ $add: ["$count", 1] },
],
},
2,
],
},
else: checkData.responseTime,
},
},
count: { $add: [{ $ifNull: ["$count", 0] }, 1] },
},
},
],
upsert: true,
},
};
});
// Execute bulk operation
await DistributedUptimeCheck.bulkWrite(bulkOps, {
ordered: false, // Allow parallel processing
});
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createDistributedChecks";
throw error;
}
};
const deleteDistributedChecksByMonitorId = async (monitorId) => {
try {
const result = await DistributedUptimeCheck.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteDistributedChecksByMonitorId";
throw error;
}
};
export {
createDistributedCheck,
createDistributedChecks,
deleteDistributedChecksByMonitorId,
};
+74
View File
@@ -0,0 +1,74 @@
import HardwareCheck from "../../models/HardwareCheck.js";
import Monitor from "../../models/Monitor.js";
import logger from "../../../utils/logger.js";
const SERVICE_NAME = "hardwareCheckModule";
const createHardwareCheck = async (hardwareCheckData) => {
try {
const { monitorId, status } = hardwareCheckData;
const n = (await HardwareCheck.countDocuments({ monitorId })) + 1;
const monitor = await Monitor.findById(monitorId);
if (!monitor) {
logger.error({
message: "Monitor not found",
service: SERVICE_NAME,
method: "createHardwareCheck",
details: `monitor ID: ${monitorId}`,
});
return null;
}
let newUptimePercentage;
if (monitor.uptimePercentage === undefined) {
newUptimePercentage = status === true ? 1 : 0;
} else {
newUptimePercentage =
(monitor.uptimePercentage * (n - 1) + (status === true ? 1 : 0)) / n;
}
await Monitor.findOneAndUpdate(
{ _id: monitorId },
{ uptimePercentage: newUptimePercentage }
);
const hardwareCheck = await new HardwareCheck({
...hardwareCheckData,
}).save();
return hardwareCheck;
} catch (error) {
logger.error({
message: "Error creating hardware check",
service: SERVICE_NAME,
method: "createHardwareCheck",
stack: error.stack,
});
error.service = SERVICE_NAME;
error.method = "createHardwareCheck";
throw error;
}
};
const createHardwareChecks = async (hardwareChecks) => {
try {
await HardwareCheck.insertMany(hardwareChecks);
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createHardwareChecks";
throw error;
}
};
const deleteHardwareChecksByMonitorId = async (monitorId) => {
try {
const result = await HardwareCheck.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteHardwareChecksByMonitorId";
throw error;
}
};
export { createHardwareCheck, createHardwareChecks, deleteHardwareChecksByMonitorId };
+89
View File
@@ -0,0 +1,89 @@
import InviteToken from "../../models/InviteToken.js";
import crypto from "crypto";
import ServiceRegistry from "../../../service/serviceRegistry.js";
import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "inviteModule";
/**
* Request an invite token for a user.
*
* This function deletes any existing invite tokens for the user's email,
* generates a new token, saves it, and then returns the new token.
*
* @param {Object} userData - The user data.
* @param {string} userData.email - The user's email.
* @param {mongoose.Schema.Types.ObjectId} userData.teamId - The ID of the team.
* @param {Array} userData.role - The user's role(s).
* @param {Date} [userData.expiry=Date.now] - The expiry date of the token. Defaults to the current date and time.
* @returns {Promise<InviteToken>} The invite token.
* @throws {Error} If there is an error.
*/
const requestInviteToken = async (userData) => {
try {
await InviteToken.deleteMany({ email: userData.email });
userData.token = crypto.randomBytes(32).toString("hex");
let inviteToken = new InviteToken(userData);
await inviteToken.save();
return inviteToken;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "requestInviteToken";
throw error;
}
};
/**
* Retrieves an invite token
*
* This function searches for an invite token in the database and deletes it.
* If the invite token is not found, it throws an error.
*
* @param {string} token - The invite token to search for.
* @returns {Promise<InviteToken>} The invite token data.
* @throws {Error} If the invite token is not found or there is another error.
*/
const getInviteToken = async (token) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const invite = await InviteToken.findOne({
token,
});
if (invite === null) {
throw new Error(stringService.authInviteNotFound);
}
return invite;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteToken";
throw error;
}
};
/**
* Retrieves and deletes an invite token
*
* This function searches for an invite token in the database and deletes it.
* If the invite token is not found, it throws an error.
*
* @param {string} token - The invite token to search for.
* @returns {Promise<InviteToken>} The invite token data.
* @throws {Error} If the invite token is not found or there is another error.
*/
const getInviteTokenAndDelete = async (token) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const invite = await InviteToken.findOneAndDelete({
token,
});
if (invite === null) {
throw new Error(stringService.authInviteNotFound);
}
return invite;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getInviteTokenAndDelete";
throw error;
}
};
export { requestInviteToken, getInviteToken, getInviteTokenAndDelete };
+199
View File
@@ -0,0 +1,199 @@
import MaintenanceWindow from "../../models/MaintenanceWindow.js";
const SERVICE_NAME = "maintenanceWindowModule";
/**
* Asynchronously creates a new MaintenanceWindow document and saves it to the database.
* If the maintenance window is a one-time event, the expiry field is set to the same value as the end field.
* @async
* @function createMaintenanceWindow
* @param {Object} maintenanceWindowData - The data for the new MaintenanceWindow document.
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowData.monitorId - The ID of the monitor.
* @param {Boolean} maintenanceWindowData.active - Indicates whether the maintenance window is active.
* @param {Boolean} maintenanceWindowData.oneTime - Indicates whether the maintenance window is a one-time event.
* @param {Date} maintenanceWindowData.start - The start date and time of the maintenance window.
* @param {Date} maintenanceWindowData.end - The end date and time of the maintenance window.
* @returns {Promise<MaintenanceWindow>} The saved MaintenanceWindow document.
* @throws {Error} If there is an error saving the document.
*/
const createMaintenanceWindow = async (maintenanceWindowData) => {
try {
const maintenanceWindow = new MaintenanceWindow({
...maintenanceWindowData,
});
// If the maintenance window is a one time window, set the expiry to the end date
if (maintenanceWindowData.oneTime) {
maintenanceWindow.expiry = maintenanceWindowData.end;
}
const result = await maintenanceWindow.save();
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createMaintenanceWindow";
throw error;
}
};
const getMaintenanceWindowById = async (maintenanceWindowId) => {
try {
const maintenanceWindow = await MaintenanceWindow.findById({
_id: maintenanceWindowId,
});
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowById";
throw error;
}
};
/**
* Asynchronously retrieves all MaintenanceWindow documents associated with a specific team ID.
* @async
* @function getMaintenanceWindowByUserId
* @param {String} teamId - The ID of the team.
* @param {Object} query - The request body.
* @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
*/
const getMaintenanceWindowsByTeamId = async (teamId, query) => {
try {
let { active, page, rowsPerPage, field, order } = query || {};
const maintenanceQuery = { teamId };
if (active !== undefined) maintenanceQuery.active = active;
const maintenanceWindowCount =
await MaintenanceWindow.countDocuments(maintenanceQuery);
// Pagination
let skip = 0;
if (page && rowsPerPage) {
skip = page * rowsPerPage;
}
// Sorting
let sort = {};
if (field !== undefined && order !== undefined) {
sort[field] = order === "asc" ? 1 : -1;
}
const maintenanceWindows = await MaintenanceWindow.find(maintenanceQuery)
.skip(skip)
.limit(rowsPerPage)
.sort(sort);
return { maintenanceWindows, maintenanceWindowCount };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowByUserId";
throw error;
}
};
/**
* Asynchronously retrieves all MaintenanceWindow documents associated with a specific monitor ID.
* @async
* @function getMaintenanceWindowsByMonitorId
* @param {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise<Array<MaintenanceWindow>>} An array of MaintenanceWindow documents.
* @throws {Error} If there is an error retrieving the documents.
*/
const getMaintenanceWindowsByMonitorId = async (monitorId) => {
try {
const maintenanceWindows = await MaintenanceWindow.find({
monitorId: monitorId,
});
return maintenanceWindows;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMaintenanceWindowsByMonitorId";
throw error;
}
};
/**
* Asynchronously deletes a MaintenanceWindow document by its ID.
* @async
* @function deleteMaintenanceWindowById
* @param {mongoose.Schema.Types.ObjectId} maintenanceWindowId - The ID of the MaintenanceWindow document to delete.
* @returns {Promise<MaintenanceWindow>} The deleted MaintenanceWindow document.
* @throws {Error} If there is an error deleting the document.
*/
const deleteMaintenanceWindowById = async (maintenanceWindowId) => {
try {
const maintenanceWindow =
await MaintenanceWindow.findByIdAndDelete(maintenanceWindowId);
return maintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowById";
throw error;
}
};
/**
* Asynchronously deletes all MaintenanceWindow documents associated with a specific monitor ID.
* @async
* @function deleteMaintenanceWindowByMonitorId
* @param {mongoose.Schema.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise<Object>} The result of the delete operation. This object contains information about the operation, such as the number of documents deleted.
* @throws {Error} If there is an error deleting the documents.
* @example
*/
const deleteMaintenanceWindowByMonitorId = async (monitorId) => {
try {
const result = await MaintenanceWindow.deleteMany({ monitorId: monitorId });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByMonitorId";
throw error;
}
};
/**
* Asynchronously deletes all MaintenanceWindow documents associated with a specific user ID.
* @async
* @function deleteMaintenanceWindowByUserId
* @param {String} userId - The ID of the user.
* @returns {Promise<Object>} The result of the delete operation. This object contains information about the operation, such as the number of documents deleted.
* @throws {Error} If there is an error deleting the documents.
* @example
*/
const deleteMaintenanceWindowByUserId = async (userId) => {
try {
const result = await MaintenanceWindow.deleteMany({ userId: userId });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMaintenanceWindowByUserId";
throw error;
}
};
const editMaintenanceWindowById = async (maintenanceWindowId, maintenanceWindowData) => {
try {
const editedMaintenanceWindow = await MaintenanceWindow.findByIdAndUpdate(
maintenanceWindowId,
maintenanceWindowData,
{ new: true }
);
return editedMaintenanceWindow;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editMaintenanceWindowById";
throw error;
}
};
export {
createMaintenanceWindow,
getMaintenanceWindowById,
getMaintenanceWindowsByTeamId,
getMaintenanceWindowsByMonitorId,
deleteMaintenanceWindowById,
deleteMaintenanceWindowByMonitorId,
deleteMaintenanceWindowByUserId,
editMaintenanceWindowById,
};
+922
View File
@@ -0,0 +1,922 @@
import Monitor from "../../models/Monitor.js";
import MonitorStats from "../../models/MonitorStats.js";
import Check from "../../models/Check.js";
import PageSpeedCheck from "../../models/PageSpeedCheck.js";
import HardwareCheck from "../../models/HardwareCheck.js";
import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import Notification from "../../models/Notification.js";
import { NormalizeData, NormalizeDataUptimeDetails } from "../../../utils/dataUtils.js";
import ServiceRegistry from "../../../service/serviceRegistry.js";
import StringService from "../../../service/stringService.js";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import { ObjectId } from "mongodb";
import {
buildUptimeDetailsPipeline,
buildHardwareDetailsPipeline,
buildMonitorStatsPipeline,
buildMonitorSummaryByTeamIdPipeline,
buildMonitorsByTeamIdPipeline,
buildMonitorsAndSummaryByTeamIdPipeline,
buildMonitorsWithChecksByTeamIdPipeline,
buildFilteredMonitorsByTeamIdPipeline,
buildDePINDetailsByDateRange,
buildDePINLatestChecks,
} from "./monitorModuleQueries.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const demoMonitorsPath = path.resolve(__dirname, "../../../utils/demoMonitors.json");
const demoMonitors = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8"));
const SERVICE_NAME = "monitorModule";
const CHECK_MODEL_LOOKUP = {
http: Check,
ping: Check,
docker: Check,
port: Check,
pagespeed: PageSpeedCheck,
hardware: HardwareCheck,
};
/**
* Get all monitors
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Array<Monitor>>}
* @throws {Error}
*/
const getAllMonitors = async (req, res) => {
try {
const monitors = await Monitor.find();
return monitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitors";
throw error;
}
};
/**
* Get all monitors with uptime stats for 1,7,30, and 90 days
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Array<Monitor>>}
* @throws {Error}
*/
const getAllMonitorsWithUptimeStats = async () => {
const timeRanges = {
1: new Date(Date.now() - 24 * 60 * 60 * 1000),
7: new Date(Date.now() - 7 * 24 * 60 * 60 * 1000),
30: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
90: new Date(Date.now() - 90 * 24 * 60 * 60 * 1000),
};
try {
const monitors = await Monitor.find();
const monitorsWithStats = await Promise.all(
monitors.map(async (monitor) => {
const model = CHECK_MODEL_LOOKUP[monitor.type];
const uptimeStats = await Promise.all(
Object.entries(timeRanges).map(async ([days, startDate]) => {
const checks = await model.find({
monitorId: monitor._id,
createdAt: { $gte: startDate },
});
return [days, getUptimePercentage(checks)];
})
);
return {
...monitor.toObject(),
...Object.fromEntries(uptimeStats),
};
})
);
return monitorsWithStats;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllMonitorsWithUptimeStats";
throw error;
}
};
/**
* Function to calculate uptime duration based on the most recent check.
* @param {Array} checks Array of check objects.
* @returns {number} Uptime duration in ms.
*/
const calculateUptimeDuration = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
const latestCheck = new Date(checks[0].createdAt);
let latestDownCheck = 0;
for (let i = checks.length - 1; i >= 0; i--) {
if (checks[i].status === false) {
latestDownCheck = new Date(checks[i].createdAt);
break;
}
}
// If no down check is found, uptime is from the last check to now
if (latestDownCheck === 0) {
return Date.now() - new Date(checks[checks.length - 1].createdAt);
}
// Otherwise the uptime is from the last check to the last down check
return latestCheck - latestDownCheck;
};
/**
* Helper function to get duration since last check
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getLastChecked = (checks) => {
if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available
}
// Data is sorted newest->oldest, so last check is the most recent
return new Date() - new Date(checks[0].createdAt);
};
/**
* Helper function to get latestResponseTime
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getLatestResponseTime = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
return checks[0]?.responseTime ?? 0;
};
/**
* Helper function to get average response time
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getAverageResponseTime = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
const validChecks = checks.filter((check) => typeof check.responseTime === "number");
if (validChecks.length === 0) {
return 0;
}
const aggResponseTime = validChecks.reduce((sum, check) => {
return sum + check.responseTime;
}, 0);
return aggResponseTime / validChecks.length;
};
/**
* Helper function to get percentage 24h uptime
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getUptimePercentage = (checks) => {
if (!checks || checks.length === 0) {
return 0;
}
const upCount = checks.reduce((count, check) => {
return check.status === true ? count + 1 : count;
}, 0);
return (upCount / checks.length) * 100;
};
/**
* Helper function to get all incidents
* @param {Array} checks Array of check objects.
* @returns {number} Timestamp of the most recent check.
*/
const getIncidents = (checks) => {
if (!checks || checks.length === 0) {
return 0; // Handle case when no checks are available
}
return checks.reduce((acc, check) => {
return check.status === false ? (acc += 1) : acc;
}, 0);
};
/**
* Get date range parameters
* @param {string} dateRange - 'day' | 'week' | 'month' | 'all'
* @returns {Object} Start and end dates
*/
const getDateRange = (dateRange) => {
const startDates = {
recent: new Date(new Date().setHours(new Date().getHours() - 2)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
all: new Date(0),
};
return {
start: startDates[dateRange],
end: new Date(),
};
};
/**
* Get checks for a monitor
* @param {string} monitorId - Monitor ID
* @param {Object} model - Check model to use
* @param {Object} dateRange - Date range parameters
* @param {number} sortOrder - Sort order (1 for ascending, -1 for descending)
* @returns {Promise<Object>} All checks and date-ranged checks
*/
const getMonitorChecks = async (monitorId, model, dateRange, sortOrder) => {
const indexSpec = {
monitorId: 1,
createdAt: sortOrder, // This will be 1 or -1
};
const [checksAll, checksForDateRange] = await Promise.all([
model.find({ monitorId }).sort({ createdAt: sortOrder }).hint(indexSpec).lean(),
model
.find({
monitorId,
createdAt: { $gte: dateRange.start, $lte: dateRange.end },
})
.hint(indexSpec)
.lean(),
]);
return { checksAll, checksForDateRange };
};
/**
* Process checks for display
* @param {Array} checks - Checks to process
* @param {number} numToDisplay - Number of checks to display
* @param {boolean} normalize - Whether to normalize the data
* @returns {Array} Processed checks
*/
const processChecksForDisplay = (normalizeData, checks, numToDisplay, normalize) => {
let processedChecks = checks;
if (numToDisplay && checks.length > numToDisplay) {
const n = Math.ceil(checks.length / numToDisplay);
processedChecks = checks.filter((_, index) => index % n === 0);
}
return normalize ? normalizeData(processedChecks, 1, 100) : processedChecks;
};
/**
* Get time-grouped checks based on date range
* @param {Array} checks Array of check objects
* @param {string} dateRange 'day' | 'week' | 'month'
* @returns {Object} Grouped checks by time period
*/
const groupChecksByTime = (checks, dateRange) => {
return checks.reduce((acc, check) => {
// Validate the date
const checkDate = new Date(check.createdAt);
if (Number.isNaN(checkDate.getTime()) || checkDate.getTime() === 0) {
return acc;
}
const time =
dateRange === "day"
? checkDate.setMinutes(0, 0, 0)
: checkDate.toISOString().split("T")[0];
if (!acc[time]) {
acc[time] = { time, checks: [] };
}
acc[time].checks.push(check);
return acc;
}, {});
};
/**
* Calculate aggregate stats for a group of checks
* @param {Object} group Group of checks
* @returns {Object} Stats for the group
*/
const calculateGroupStats = (group) => {
const totalChecks = group.checks.length;
const checksWithResponseTime = group.checks.filter(
(check) => typeof check.responseTime === "number" && !Number.isNaN(check.responseTime)
);
return {
time: group.time,
uptimePercentage: getUptimePercentage(group.checks),
totalChecks,
totalIncidents: group.checks.filter((check) => !check.status).length,
avgResponseTime:
checksWithResponseTime.length > 0
? checksWithResponseTime.reduce((sum, check) => sum + check.responseTime, 0) /
checksWithResponseTime.length
: 0,
};
};
/**
* Get uptime details by monitor ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getUptimeDetailsById = async (req) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const { monitorId } = req.params;
const { dateRange, normalize } = req.query;
const dates = getDateRange(dateRange);
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT%H:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const results = await Check.aggregate(
buildUptimeDetailsPipeline(monitorId, dates, dateString)
);
const monitorData = results[0];
monitorData.groupedUpChecks = NormalizeDataUptimeDetails(
monitorData.groupedUpChecks,
10,
100
);
monitorData.groupedDownChecks = NormalizeDataUptimeDetails(
monitorData.groupedDownChecks,
10,
100
);
const normalizedGroupChecks = NormalizeDataUptimeDetails(
monitorData.groupedChecks,
10,
100
);
monitorData.groupedChecks = normalizedGroupChecks;
const monitorStats = await MonitorStats.findOne({ monitorId });
return { monitorData, monitorStats };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUptimeDetailsById";
throw error;
}
};
const getDistributedUptimeDetailsById = async (req) => {
try {
const { monitorId } = req?.params ?? {};
if (typeof monitorId === "undefined") {
throw new Error();
}
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
throw new Error(this.stringService.dbFindMonitorById(monitorId));
}
const { dateRange, normalize } = req.query;
const dates = getDateRange(dateRange);
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: {
$concat: [
{ $dateToString: { format: "%Y-%m-%dT%H:", date: "$updatedAt" } },
{
$cond: [{ $lt: [{ $minute: "$updatedAt" }, 30] }, "00:00Z", "30:00Z"],
},
],
},
week: "%Y-%m-%dT%H:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const monitorStatsResult = await MonitorStats.aggregate(
buildMonitorStatsPipeline(monitor)
);
const monitorStats = monitorStatsResult[0];
const dePINDetailsByDateRange = await DistributedUptimeCheck.aggregate(
buildDePINDetailsByDateRange(monitor, dates, dateString)
);
const latestChecks = await DistributedUptimeCheck.aggregate(
buildDePINLatestChecks(monitor)
);
const checkData = dePINDetailsByDateRange[0];
const normalizedGroupChecks = NormalizeDataUptimeDetails(
checkData.groupedChecks,
10,
100
);
const data = {
...monitor.toObject(),
latestChecks,
totalChecks: monitorStats?.totalChecks,
avgResponseTime: monitorStats?.avgResponseTime,
uptimePercentage: monitorStats?.uptimePercentage,
timeSinceLastCheck: monitorStats?.timeSinceLastCheck,
uptBurnt: monitorStats?.uptBurnt,
groupedChecks: normalizedGroupChecks,
groupedMapChecks: checkData.groupedMapChecks,
};
return data;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getDistributedUptimeDetailsById";
throw error;
}
};
/**
* Get stats by monitor ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getMonitorStatsById = async (req) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const { monitorId } = req.params;
// Get monitor, if we can't find it, abort with error
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
throw new Error(stringService.getDbFindMonitorById(monitorId));
}
// Get query params
let { limit, sortOrder, dateRange, numToDisplay, normalize } = req.query;
const sort = sortOrder === "asc" ? 1 : -1;
// Get Checks for monitor in date range requested
const model = CHECK_MODEL_LOOKUP[monitor.type];
const dates = getDateRange(dateRange);
const { checksAll, checksForDateRange } = await getMonitorChecks(
monitorId,
model,
dates,
sort
);
// Build monitor stats
const monitorStats = {
...monitor.toObject(),
uptimeDuration: calculateUptimeDuration(checksAll),
lastChecked: getLastChecked(checksAll),
latestResponseTime: getLatestResponseTime(checksAll),
periodIncidents: getIncidents(checksForDateRange),
periodTotalChecks: checksForDateRange.length,
checks: processChecksForDisplay(
NormalizeData,
checksForDateRange,
numToDisplay,
normalize
),
};
if (
monitor.type === "http" ||
monitor.type === "ping" ||
monitor.type === "docker" ||
monitor.type === "port"
) {
// HTTP/PING Specific stats
monitorStats.periodAvgResponseTime = getAverageResponseTime(checksForDateRange);
monitorStats.periodUptime = getUptimePercentage(checksForDateRange);
const groupedChecks = groupChecksByTime(checksForDateRange, dateRange);
monitorStats.aggregateData = Object.values(groupedChecks).map(calculateGroupStats);
}
return monitorStats;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorStatsById";
throw error;
}
};
const getHardwareDetailsById = async (req) => {
try {
const { monitorId } = req.params;
const { dateRange } = req.query;
const monitor = await Monitor.findById(monitorId);
const dates = getDateRange(dateRange);
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT%H:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
};
const dateString = formatLookup[dateRange];
const hardwareStats = await HardwareCheck.aggregate(
buildHardwareDetailsPipeline(monitor, dates, dateString)
);
const monitorStats = {
...monitor.toObject(),
stats: hardwareStats[0],
};
return monitorStats;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getHardwareDetailsById";
throw error;
}
};
/**
* Get a monitor by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const getMonitorById = async (monitorId) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const monitor = await Monitor.findById(monitorId);
if (monitor === null || monitor === undefined) {
const error = new Error(stringService.getDbFindMonitorById(monitorId));
error.status = 404;
throw error;
}
// Get notifications
const notifications = await Notification.find({
monitorId: monitorId,
});
// Update monitor with notifications and save
monitor.notifications = notifications;
await monitor.save();
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorById";
throw error;
}
};
const getMonitorsByTeamId = async (req) => {
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
if (field === undefined) {
field = "name";
order = "asc";
}
// Build match stage
const matchStage = { teamId: ObjectId.createFromHexString(req.params.teamId) };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
const summaryResult = await Monitor.aggregate(
buildMonitorSummaryByTeamIdPipeline({ matchStage })
);
const summary = summaryResult[0];
const monitors = await Monitor.aggregate(
buildMonitorsByTeamIdPipeline({ matchStage, field, order })
);
const filteredMonitors = await Monitor.aggregate(
buildFilteredMonitorsByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
);
const normalizedFilteredMonitors = filteredMonitors.map((monitor) => {
if (!monitor.checks) {
return monitor;
}
monitor.checks = NormalizeData(monitor.checks, 10, 100);
return monitor;
});
return { summary, monitors, filteredMonitors: normalizedFilteredMonitors };
};
const getMonitorsAndSummaryByTeamId = async (req) => {
try {
const { type } = req.query;
const teamId = ObjectId.createFromHexString(req.params.teamId);
const matchStage = { teamId };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
if (req.explain === true) {
return Monitor.aggregate(
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
).explain("executionStats");
}
const queryResult = await Monitor.aggregate(
buildMonitorsAndSummaryByTeamIdPipeline({ matchStage })
);
const { monitors, summary } = queryResult?.[0] ?? {};
return { monitors, summary };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsAndSummaryByTeamId";
throw error;
}
};
const getMonitorsWithChecksByTeamId = async (req) => {
try {
let { limit, type, page, rowsPerPage, filter, field, order } = req.query;
limit = parseInt(limit);
page = parseInt(page);
rowsPerPage = parseInt(rowsPerPage);
if (field === undefined) {
field = "name";
order = "asc";
}
const teamId = ObjectId.createFromHexString(req.params.teamId);
// Build match stage
const matchStage = { teamId };
if (type !== undefined) {
matchStage.type = Array.isArray(type) ? { $in: type } : type;
}
if (req.explain === true) {
return Monitor.aggregate(
buildMonitorsWithChecksByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
).explain("executionStats");
}
const queryResult = await Monitor.aggregate(
buildMonitorsWithChecksByTeamIdPipeline({
matchStage,
filter,
page,
rowsPerPage,
field,
order,
limit,
type,
})
);
const monitors = queryResult[0]?.monitors;
const count = queryResult[0]?.count;
const normalizedFilteredMonitors = monitors.map((monitor) => {
if (!monitor.checks) {
return monitor;
}
monitor.checks = NormalizeData(monitor.checks, 10, 100);
return monitor;
});
return { count, monitors: normalizedFilteredMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getMonitorsWithChecksByTeamId";
throw error;
}
};
/**
* Create a monitor
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const createMonitor = async (req, res) => {
try {
const monitor = new Monitor({ ...req.body });
// Remove notifications fom monitor as they aren't needed here
monitor.notifications = undefined;
await monitor.save();
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createMonitor";
throw error;
}
};
/**
* Create bulk monitors
* @async
* @param {Express.Request} req
* @returns {Promise<Monitors>}
* @throws {Error}
*/
const createBulkMonitors = async (req) => {
try {
const monitors = req.body.map(
(item) => new Monitor({ ...item, notifications: undefined })
);
await Monitor.bulkSave(monitors);
return monitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createBulkMonitors";
throw error;
}
};
/**
* Delete a monitor by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const deleteMonitor = async (req, res) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
const monitorId = req.params.monitorId;
try {
const monitor = await Monitor.findByIdAndDelete(monitorId);
if (!monitor) {
throw new Error(stringService.getDbFindMonitorById(monitorId));
}
return monitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMonitor";
throw error;
}
};
/**
* DELETE ALL MONITORS (TEMP)
*/
const deleteAllMonitors = async (teamId) => {
try {
const monitors = await Monitor.find({ teamId });
const { deletedCount } = await Monitor.deleteMany({ teamId });
return { monitors, deletedCount };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteAllMonitors";
throw error;
}
};
/**
* Delete all monitors associated with a user ID
* @async
* @param {string} userId - The ID of the user whose monitors are to be deleted.
* @returns {Promise} A promise that resolves when the operation is complete.
*/
const deleteMonitorsByUserId = async (userId) => {
try {
const result = await Monitor.deleteMany({ userId: userId });
return result;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteMonitorsByUserId";
throw error;
}
};
/**
* Edit a monitor by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<Monitor>}
* @throws {Error}
*/
const editMonitor = async (candidateId, candidateMonitor) => {
candidateMonitor.notifications = undefined;
try {
const editedMonitor = await Monitor.findByIdAndUpdate(candidateId, candidateMonitor, {
new: true,
});
return editedMonitor;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "editMonitor";
throw error;
}
};
const addDemoMonitors = async (userId, teamId) => {
try {
const demoMonitorsToInsert = demoMonitors.map((monitor) => {
return {
userId,
teamId,
name: monitor.name,
description: monitor.name,
type: "http",
url: monitor.url,
interval: 60000,
};
});
const insertedMonitors = await Monitor.insertMany(demoMonitorsToInsert);
return insertedMonitors;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "addDemoMonitors";
throw error;
}
};
export {
getAllMonitors,
getAllMonitorsWithUptimeStats,
getMonitorStatsById,
getMonitorById,
getMonitorsByTeamId,
getMonitorsAndSummaryByTeamId,
getMonitorsWithChecksByTeamId,
getUptimeDetailsById,
getDistributedUptimeDetailsById,
createMonitor,
createBulkMonitors,
deleteMonitor,
deleteAllMonitors,
deleteMonitorsByUserId,
editMonitor,
addDemoMonitors,
getHardwareDetailsById,
};
// Helper functions
export {
calculateUptimeDuration,
getLastChecked,
getLatestResponseTime,
getAverageResponseTime,
getUptimePercentage,
getIncidents,
getDateRange,
getMonitorChecks,
processChecksForDisplay,
groupChecksByTime,
calculateGroupStats,
};
// limit 25
// page 1
// rowsPerPage 25
// filter undefined
// field name
// order asc
// skip 25
// sort { name: 1 }
// filteredMonitors []
// limit 25
// page NaN
// rowsPerPage 25
// filter undefined
// field name
// order asc
// skip 0
// sort { name: 1 }
File diff suppressed because it is too large. Load diff
+56
View File
@@ -0,0 +1,56 @@
import Notification from "../../models/Notification.js";
const SERVICE_NAME = "notificationModule";
/**
* Creates a new notification.
* @param {Object} notificationData - The data for the new notification.
* @param {mongoose.Types.ObjectId} notificationData.monitorId - The ID of the monitor.
* @param {string} notificationData.type - The type of the notification (e.g., "email", "sms").
* @param {string} [notificationData.address] - The address for the notification (if applicable).
* @param {string} [notificationData.phone] - The phone number for the notification (if applicable).
* @returns {Promise<Object>} The created notification.
* @throws Will throw an error if the notification cannot be created.
*/
const createNotification = async (notificationData) => {
try {
const notification = await new Notification({ ...notificationData }).save();
return notification;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createNotification";
throw error;
}
};
/**
* Retrieves notifications by monitor ID.
* @param {mongoose.Types.ObjectId} monitorId - The ID of the monitor.
* @returns {Promise<Array<Object>>} An array of notifications.
* @throws Will throw an error if the notifications cannot be retrieved.
*/
const getNotificationsByMonitorId = async (monitorId) => {
try {
const notifications = await Notification.find({ monitorId });
return notifications;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getNotificationsByMonitorId";
throw error;
}
};
const deleteNotificationsByMonitorId = async (monitorId) => {
try {
const result = await Notification.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteNotificationsByMonitorId";
throw error;
}
};
export {
createNotification,
getNotificationsByMonitorId,
deleteNotificationsByMonitorId,
};
+57
View File
@@ -0,0 +1,57 @@
import PageSpeedCheck from "../../models/PageSpeedCheck.js";
const SERVICE_NAME = "pageSpeedCheckModule";
/**
* Create a PageSpeed check for a monitor
* @async
* @param {Object} pageSpeedCheckData
* @param {string} pageSpeedCheckData.monitorId
* @param {number} pageSpeedCheckData.accessibility
* @param {number} pageSpeedCheckData.bestPractices
* @param {number} pageSpeedCheckData.seo
* @param {number} pageSpeedCheckData.performance
* @returns {Promise<PageSpeedCheck>}
* @throws {Error}
*/
const createPageSpeedCheck = async (pageSpeedCheckData) => {
try {
const pageSpeedCheck = await new PageSpeedCheck({
...pageSpeedCheckData,
}).save();
return pageSpeedCheck;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck";
throw error;
}
};
const createPageSpeedChecks = async (pageSpeedChecks) => {
try {
await PageSpeedCheck.insertMany(pageSpeedChecks);
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "createPageSpeedCheck";
throw error;
}
};
/**
* Delete all PageSpeed checks for a monitor
* @async
* @param {string} monitorId
* @returns {number}
* @throws {Error}
*/
const deletePageSpeedChecksByMonitorId = async (monitorId) => {
try {
const result = await PageSpeedCheck.deleteMany({ monitorId });
return result.deletedCount;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deletePageSpeedChecksByMonitorId";
throw error;
}
};
export { createPageSpeedCheck, createPageSpeedChecks, deletePageSpeedChecksByMonitorId };
+88
View File
@@ -0,0 +1,88 @@
import UserModel from "../../models/User.js";
import RecoveryToken from "../../models/RecoveryToken.js";
import crypto from "crypto";
import serviceRegistry from "../../../service/serviceRegistry.js";
import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "recoveryModule";
/**
* Request a recovery token
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const requestRecoveryToken = async (req, res) => {
try {
// Delete any existing tokens
await RecoveryToken.deleteMany({ email: req.body.email });
let recoveryToken = new RecoveryToken({
email: req.body.email,
token: crypto.randomBytes(32).toString("hex"),
});
await recoveryToken.save();
return recoveryToken;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "requestRecoveryToken";
throw error;
}
};
const validateRecoveryToken = async (req, res) => {
const stringService = serviceRegistry.get(StringService.SERVICE_NAME);
try {
const candidateToken = req.body.recoveryToken;
const recoveryToken = await RecoveryToken.findOne({
token: candidateToken,
});
if (recoveryToken !== null) {
return recoveryToken;
} else {
throw new Error(stringService.dbTokenNotFound);
}
} catch (error) {
error.service = SERVICE_NAME;
error.method = "validateRecoveryToken";
throw error;
}
};
const resetPassword = async (req, res) => {
const stringService = serviceRegistry.get(StringService.SERVICE_NAME);
try {
const newPassword = req.body.password;
// Validate token again
const recoveryToken = await validateRecoveryToken(req, res);
const user = await UserModel.findOne({ email: recoveryToken.email });
if (user === null) {
throw new Error(stringService.dbUserNotFound);
}
const match = await user.comparePassword(newPassword);
if (match === true) {
throw new Error(stringService.dbResetPasswordBadMatch);
}
user.password = newPassword;
await user.save();
await RecoveryToken.deleteMany({ email: recoveryToken.email });
// Fetch the user again without the password
const userWithoutPassword = await UserModel.findOne({
email: recoveryToken.email,
})
.select("-password")
.select("-profileImage");
return userWithoutPassword;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "resetPassword";
throw error;
}
};
export { requestRecoveryToken, validateRecoveryToken, resetPassword };
+30
View File
@@ -0,0 +1,30 @@
import AppSettings from "../../models/AppSettings.js";
const SERVICE_NAME = "SettingsModule";
const getAppSettings = async () => {
try {
const settings = AppSettings.findOne();
return settings;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getSettings";
throw error;
}
};
const updateAppSettings = async (newSettings) => {
try {
const settings = await AppSettings.findOneAndUpdate(
{},
{ $set: newSettings },
{ new: true }
);
return settings;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateAppSettings";
throw error;
}
};
export { getAppSettings, updateAppSettings };
+310
View File
@@ -0,0 +1,310 @@
import StatusPage from "../../models/StatusPage.js";
import Monitor from "../../models/Monitor.js";
import { NormalizeData } from "../../../utils/dataUtils.js";
import ServiceRegistry from "../../../service/serviceRegistry.js";
import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "statusPageModule";
const createStatusPage = async (statusPageData, image) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const statusPage = new StatusPage({ ...statusPageData });
if (image) {
statusPage.logo = {
data: image.buffer,
contentType: image.mimetype,
};
}
await statusPage.save();
return statusPage;
} catch (error) {
if (error?.code === 11000) {
// Handle duplicate URL errors
error.status = 400;
error.message = stringService.statusPageUrlNotUnique;
}
error.service = SERVICE_NAME;
error.method = "createStatusPage";
throw error;
}
};
const updateStatusPage = async (statusPageData, image) => {
try {
if (image) {
statusPageData.logo = {
data: image.buffer,
contentType: image.mimetype,
};
}
if (statusPageData.deleteSubmonitors === "true") {
statusPageData.subMonitors = [];
}
const statusPage = await StatusPage.findOneAndUpdate(
{ url: statusPageData.url },
statusPageData,
{
new: true,
}
);
return statusPage;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateStatusPage";
throw error;
}
};
const getDistributedStatusPageByUrl = async ({ url, daysToShow = 30 }) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const statusPage = await StatusPage.findOne({ url }).lean();
if (!statusPage) {
const error = new Error(stringService.statusPageNotFound);
error.status = 404;
throw error;
}
// No sub monitors, return status page
if (statusPage.subMonitors.length === 0) {
return statusPage;
}
// Sub monitors, return status page with sub monitors
const daysAgo = new Date();
daysAgo.setDate(daysAgo.getDate() - daysToShow);
const subMonitors = await Monitor.aggregate([
{ $match: { _id: { $in: statusPage.subMonitors } } },
{
$addFields: {
orderIndex: { $indexOfArray: [statusPage.subMonitors, "$_id"] },
},
},
// Return 30 days of checks by default
{
$lookup: {
from: "checks",
let: { monitorId: "$_id" },
pipeline: [
{
$match: {
$expr: {
$and: [
{ $eq: ["$monitorId", "$$monitorId"] },
{ $gte: ["$updatedAt", daysAgo] },
],
},
},
},
{
$group: {
_id: {
$dateToString: { format: "%Y-%m-%d", date: "$updatedAt" },
},
responseTime: {
$avg: "$responseTime",
},
trueCount: {
$sum: {
$cond: [{ $eq: ["$status", true] }, 1, 0],
},
},
totalCount: {
$sum: 1,
},
},
},
{
$project: {
_id: 1,
responseTime: 1,
upPercentage: {
$cond: [
{ $eq: ["$totalCount", 0] },
0,
{ $multiply: [{ $divide: ["$trueCount", "$totalCount"] }, 100] },
],
},
},
},
{
$sort: { _id: -1 },
},
],
as: "checks",
},
},
{ $sort: { orderIndex: 1 } },
{ $project: { orderIndex: 0 } },
]);
const normalizedSubMonitors = subMonitors.map((monitor) => {
return {
...monitor,
checks: NormalizeData(monitor.checks, 10, 100),
};
});
return { ...statusPage, subMonitors: normalizedSubMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getDistributedStatusPageByUrl";
throw error;
}
};
const getStatusPageByUrl = async (url, type) => {
// TODO This is deprecated, can remove and have controller call getStatusPage
try {
return getStatusPage(url);
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error;
}
};
const getStatusPagesByTeamId = async (teamId) => {
try {
const statusPages = await StatusPage.find({ teamId });
return statusPages;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPagesByTeamId";
throw error;
}
};
const getStatusPage = async (url) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const statusPageQuery = await StatusPage.aggregate([
{ $match: { url: url } },
{
$set: {
originalMonitors: "$monitors",
},
},
{
$lookup: {
from: "monitors",
localField: "monitors",
foreignField: "_id",
as: "monitors",
},
},
{
$unwind: "$monitors",
},
{
$lookup: {
from: "checks",
let: { monitorId: "$monitors._id" },
pipeline: [
{
$match: {
$expr: { $eq: ["$monitorId", "$$monitorId"] },
},
},
{ $sort: { createdAt: -1 } },
{ $limit: 25 },
],
as: "monitors.checks",
},
},
{
$addFields: {
"monitors.orderIndex": {
$indexOfArray: ["$originalMonitors", "$monitors._id"],
},
},
},
{
$group: {
_id: "$_id",
statusPage: { $first: "$$ROOT" },
monitors: { $push: "$monitors" },
},
},
{
$project: {
statusPage: {
_id: 1,
color: 1,
companyName: 1,
isPublished: 1,
logo: 1,
originalMonitors: 1,
showCharts: 1,
showUptimePercentage: 1,
timezone: 1,
url: 1,
},
monitors: {
$sortArray: {
input: "$monitors",
sortBy: { orderIndex: 1 },
},
},
},
},
]);
if (!statusPageQuery.length) {
const error = new Error(stringService.statusPageNotFound);
error.status = 404;
throw error;
}
const { statusPage, monitors } = statusPageQuery[0];
const normalizedMonitors = monitors.map((monitor) => {
return {
...monitor,
checks: NormalizeData(monitor.checks, 10, 100),
};
});
return { statusPage, monitors: normalizedMonitors };
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getStatusPageByUrl";
throw error;
}
};
const deleteStatusPage = async (url) => {
try {
await StatusPage.deleteOne({ url });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPage";
throw error;
}
};
const deleteStatusPagesByMonitorId = async (monitorId) => {
try {
await StatusPage.deleteMany({ monitors: { $in: [monitorId] } });
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteStatusPageByMonitorId";
throw error;
}
};
export {
createStatusPage,
updateStatusPage,
getStatusPagesByTeamId,
getStatusPage,
getStatusPageByUrl,
getDistributedStatusPageByUrl,
deleteStatusPage,
deleteStatusPagesByMonitorId,
};
+232
View File
@@ -0,0 +1,232 @@
import UserModel from "../../models/User.js";
import TeamModel from "../../models/Team.js";
import { GenerateAvatarImage } from "../../../utils/imageProcessing.js";
const DUPLICATE_KEY_CODE = 11000; // MongoDB error code for duplicate key
import { ParseBoolean } from "../../../utils/utils.js";
import ServiceRegistry from "../../../service/serviceRegistry.js";
import StringService from "../../../service/stringService.js";
const SERVICE_NAME = "userModule";
/**
* Insert a User
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const insertUser = async (
userData,
imageFile,
generateAvatarImage = GenerateAvatarImage
) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
if (imageFile) {
// 1. Save the full size image
userData.profileImage = {
data: imageFile.buffer,
contentType: imageFile.mimetype,
};
// 2. Get the avatar sized image
const avatar = await generateAvatarImage(imageFile);
userData.avatarImage = avatar;
}
// Handle creating team if superadmin
if (userData.role.includes("superadmin")) {
const team = new TeamModel({
email: userData.email,
});
userData.teamId = team._id;
userData.checkTTL = 60 * 60 * 24 * 30;
await team.save();
}
const newUser = new UserModel(userData);
await newUser.save();
return await UserModel.findOne({ _id: newUser._id })
.select("-password")
.select("-profileImage"); // .select() doesn't work with create, need to save then find
} catch (error) {
if (error.code === DUPLICATE_KEY_CODE) {
error.message = stringService.dbUserExists;
}
error.service = SERVICE_NAME;
error.method = "insertUser";
throw error;
}
};
/**
* Get User by Email
* Gets a user by Email. Not sure if we'll ever need this except for login.
* If not needed except for login, we can move password comparison here
* Throws error if user not found
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const getUserByEmail = async (email) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
// Need the password to be able to compare, removed .select()
// We can strip the hash before returning the user
const user = await UserModel.findOne({ email: email }).select("-profileImage");
if (!user) {
throw new Error(stringService.dbUserNotFound);
}
return user;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getUserByEmail";
throw error;
}
};
/**
* Update a user by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const updateUser = async (
req,
res,
parseBoolean = ParseBoolean,
generateAvatarImage = GenerateAvatarImage
) => {
const candidateUserId = req.params.userId;
try {
const candidateUser = { ...req.body };
// ******************************************
// Handle profile image
// ******************************************
if (parseBoolean(candidateUser.deleteProfileImage) === true) {
candidateUser.profileImage = null;
candidateUser.avatarImage = null;
} else if (req.file) {
// 1. Save the full size image
candidateUser.profileImage = {
data: req.file.buffer,
contentType: req.file.mimetype,
};
// 2. Get the avatar sized image
const avatar = await generateAvatarImage(req.file);
candidateUser.avatarImage = avatar;
}
// ******************************************
// End handling profile image
// ******************************************
const updatedUser = await UserModel.findByIdAndUpdate(
candidateUserId,
candidateUser,
{ new: true } // Returns updated user instead of pre-update user
)
.select("-password")
.select("-profileImage");
return updatedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "updateUser";
throw error;
}
};
/**
* Delete a user by ID
* @async
* @param {Express.Request} req
* @param {Express.Response} res
* @returns {Promise<UserModel>}
* @throws {Error}
*/
const deleteUser = async (userId) => {
const stringService = ServiceRegistry.get(StringService.SERVICE_NAME);
try {
const deletedUser = await UserModel.findByIdAndDelete(userId);
if (!deletedUser) {
throw new Error(stringService.dbUserNotFound);
}
return deletedUser;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteUser";
throw error;
}
};
/**
* Delete a user by ID
* @async
* @param {string} teamId
* @returns {void}
* @throws {Error}
*/
const deleteTeam = async (teamId) => {
try {
await TeamModel.findByIdAndDelete(teamId);
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteTeam";
throw error;
}
};
const deleteAllOtherUsers = async () => {
try {
await UserModel.deleteMany({ role: { $ne: "superadmin" } });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "deleteAllOtherUsers";
throw error;
}
};
const getAllUsers = async (req, res) => {
try {
const users = await UserModel.find().select("-password").select("-profileImage");
return users;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "getAllUsers";
throw error;
}
};
const logoutUser = async (userId) => {
try {
await UserModel.updateOne({ _id: userId }, { $unset: { authToken: null } });
return true;
} catch (error) {
error.service = SERVICE_NAME;
error.method = "logoutUser";
throw error;
}
};
export {
insertUser,
getUserByEmail,
updateUser,
deleteUser,
deleteTeam,
deleteAllOtherUsers,
getAllUsers,
logoutUser,
};
+177
View File
@@ -0,0 +1,177 @@
import Monitor from "../../models/Monitor.js";
import Check from "../../models/Check.js";
import DistributedUptimeCheck from "../../models/DistributedUptimeCheck.js";
import logger from "../../../utils/logger.js";
const generateRandomUrl = () => {
const domains = ["example.com", "test.org", "demo.net", "sample.io", "mock.dev"];
const paths = ["api", "status", "health", "ping", "check"];
return `https://${domains[Math.floor(Math.random() * domains.length)]}/${paths[Math.floor(Math.random() * paths.length)]}`;
};
const generateChecks = (monitorId, teamId, count) => {
const checks = [];
const endTime = new Date(Date.now() - 10 * 60 * 1000); // 10 minutes ago
const startTime = new Date(endTime - count * 60 * 1000); // count minutes before endTime
for (let i = 0; i < count; i++) {
const timestamp = new Date(startTime.getTime() + i * 60 * 1000);
const status = Math.random() > 0.05; // 95% chance of being up
checks.push({
monitorId,
teamId,
status,
responseTime: Math.floor(Math.random() * 1000), // Random response time between 0-1000ms
createdAt: timestamp,
updatedAt: timestamp,
});
}
return checks;
};
const seedDb = async (userId, teamId) => {
try {
logger.info({
message: "Deleting all monitors and checks",
service: "seedDb",
method: "seedDb",
});
await Monitor.deleteMany({});
await Check.deleteMany({});
logger.info({
message: "Adding monitors",
service: "DB",
method: "seedDb",
});
for (let i = 0; i < 300; i++) {
const monitor = await Monitor.create({
name: `Monitor ${i}`,
url: generateRandomUrl(),
type: "http",
userId,
teamId,
interval: 60000,
active: false,
});
logger.info({
message: `Adding monitor and checks for monitor ${i}`,
service: "DB",
method: "seedDb",
});
const checks = generateChecks(monitor._id, teamId, 10000);
await Check.insertMany(checks);
}
} catch (error) {
logger.error({
message: "Error seeding DB",
service: "DB",
method: "seedDb",
stack: error.stack,
});
}
};
const generateDistributedChecks = (monitorId, teamId, count = 2880) => {
const checks = [];
const endTime = new Date();
const startTime = new Date(endTime - 48 * 60 * 60 * 1000);
// Sample locations for variety
const locations = [
{
city: "New York",
countryCode: "US",
continent: "NA",
location: { lat: 40.7128, lng: -74.006 },
},
{
city: "London",
countryCode: "GB",
continent: "EU",
location: { lat: 51.5074, lng: -0.1278 },
},
{
city: "Singapore",
countryCode: "SG",
continent: "AS",
location: { lat: 1.3521, lng: 103.8198 },
},
];
for (let i = 0; i < count; i++) {
const timestamp = new Date(startTime.getTime() + i * 60 * 1000);
const location = locations[Math.floor(Math.random() * locations.length)];
const status = Math.random() > 0.05; // 95% success rate
checks.push({
monitorId,
teamId,
status,
responseTime: Math.floor(Math.random() * 1000), // Random response time between 0-1000ms
first_byte_took: Math.floor(Math.random() * 300000), // 0-300ms
body_read_took: Math.floor(Math.random() * 100000), // 0-100ms
dns_took: Math.floor(Math.random() * 100000), // 0-100ms
conn_took: Math.floor(Math.random() * 200000), // 0-200ms
connect_took: Math.floor(Math.random() * 150000), // 0-150ms
tls_took: Math.floor(Math.random() * 200000), // 0-200ms
location: location.location,
continent: location.continent,
countryCode: location.countryCode,
city: location.city,
uptBurnt: "0.01", // Will be converted to Decimal128 by the schema
createdAt: timestamp,
updatedAt: timestamp,
});
}
return checks;
};
export const seedDistributedTest = async (userId, teamId) => {
try {
logger.info({
message: "Deleting all test monitors and checks",
service: "DB",
method: "seedDistributedTest",
});
const testMonitors = await Monitor.find({
type: "distributed_test",
});
testMonitors.forEach(async (monitor) => {
await DistributedUptimeCheck.deleteMany({ monitorId: monitor._id });
await Monitor.deleteOne({ _id: monitor._id });
});
logger.info({
message: "Adding test monitors and checks",
service: "DB",
method: "seedDistributedTest",
});
const monitor = await Monitor.create({
name: "Distributed Test",
url: "https://distributed-test.com",
type: "distributed_test",
userId,
teamId,
interval: 60000,
active: false,
});
const checks = generateDistributedChecks(monitor._id, teamId, 2800);
await DistributedUptimeCheck.insertMany(checks);
return monitor;
} catch (error) {
logger.error({
message: "Error seeding distributed test",
service: "DB",
method: "seedDistributedTest",
stack: error.stack,
});
throw error;
}
};
export default seedDb;