initial commit
This commit is contained in:
1 parent
7cb985116e
commit
75acf7b38f
955 files changed
+37333
-87054
No files matched your search
@@ -0,0 +1,624 @@
|
||||
import bcrypt from "bcryptjs";
|
||||
import {
|
||||
User,
|
||||
Org,
|
||||
OrgMembership,
|
||||
Team,
|
||||
ITeam,
|
||||
IUserReturnable,
|
||||
TeamMembership,
|
||||
Role,
|
||||
IRole,
|
||||
IUser,
|
||||
ITokenizedUser,
|
||||
Monitor,
|
||||
Check,
|
||||
NotificationChannel,
|
||||
IInvite,
|
||||
} from "@/db/models/index.js";
|
||||
import { Types } from "mongoose";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { IJobQueue } from "../infrastructure/JobQueue.js";
|
||||
import { hashPassword } from "@/utils/JWTUtils.js";
|
||||
|
||||
const SERVICE_NAME = "AuthService";
|
||||
|
||||
export const PERMISSIONS = {
|
||||
users: {
|
||||
all: "users.*",
|
||||
write: "users.write",
|
||||
read: "users.read",
|
||||
delete: "users.delete",
|
||||
},
|
||||
|
||||
monitors: {
|
||||
all: "monitors.*",
|
||||
write: "monitors.write",
|
||||
read: "monitors.read",
|
||||
update: "monitors.update",
|
||||
delete: "monitors.delete",
|
||||
},
|
||||
notifications: {
|
||||
all: "notifications.*",
|
||||
write: "notifications.write",
|
||||
read: "notifications.read",
|
||||
update: "notifications.update",
|
||||
delete: "notifications.delete",
|
||||
},
|
||||
maintenance: {
|
||||
all: "maintenance.*",
|
||||
write: "maintenance.write",
|
||||
read: "maintenance.read",
|
||||
update: "maintenance.update",
|
||||
delete: "maintenance.delete",
|
||||
},
|
||||
invite: {
|
||||
all: "invite.*",
|
||||
write: "invite.write",
|
||||
read: "invite.read",
|
||||
delete: "invite.delete",
|
||||
},
|
||||
checks: {
|
||||
all: "checks.*",
|
||||
write: "checks.write",
|
||||
read: "checks.read",
|
||||
update: "checks.update",
|
||||
delete: "checks.delete",
|
||||
},
|
||||
statusPages: {
|
||||
all: "statusPages.*",
|
||||
write: "statusPages.write",
|
||||
read: "statusPages.read",
|
||||
update: "statusPages.update",
|
||||
delete: "statusPages.delete",
|
||||
},
|
||||
teams: {
|
||||
all: "teams.*",
|
||||
write: "teams.write",
|
||||
read: "teams.read",
|
||||
update: "teams.update",
|
||||
delete: "teams.delete",
|
||||
},
|
||||
roles: {
|
||||
all: "roles.*",
|
||||
write: "roles.write",
|
||||
read: "roles.read",
|
||||
update: "roles.update",
|
||||
delete: "roles.delete",
|
||||
},
|
||||
|
||||
diagnostic: {
|
||||
all: "diagnostic.*",
|
||||
write: "diagnostic.write",
|
||||
read: "diagnostic.read",
|
||||
update: "diagnostic.update",
|
||||
delete: "diagnostic.delete",
|
||||
},
|
||||
incidents: {
|
||||
all: "incidents.*",
|
||||
write: "incidents.write",
|
||||
read: "incidents.read",
|
||||
update: "incidents.update",
|
||||
delete: "incidents.delete",
|
||||
},
|
||||
};
|
||||
|
||||
export type RegisterData = {
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type LoginData = {
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type AuthResult = Partial<ITokenizedUser>;
|
||||
|
||||
export interface IAuthService {
|
||||
me(userId: string): Promise<IUserReturnable>;
|
||||
register(signupData: RegisterData): Promise<{
|
||||
tokenizedUser: ITokenizedUser;
|
||||
returnableUser: IUserReturnable;
|
||||
}>;
|
||||
registerWithInvite(
|
||||
invite: IInvite,
|
||||
signupData: RegisterData
|
||||
): Promise<{
|
||||
tokenizedUser: ITokenizedUser;
|
||||
returnableUser: IUserReturnable;
|
||||
}>;
|
||||
login(loginData: LoginData): Promise<{
|
||||
tokenizedUser: ITokenizedUser;
|
||||
returnableUser: IUserReturnable;
|
||||
}>;
|
||||
getTeamIds(userId: string): Promise<string[]>;
|
||||
getTeams(teamIds: string[]): Promise<ITeam[]>;
|
||||
cleanup(): Promise<void>;
|
||||
cleanMonitors(): Promise<void>;
|
||||
changePassword(userId: Types.ObjectId, newPassword: string): Promise<boolean>;
|
||||
}
|
||||
|
||||
class AuthService implements IAuthService {
|
||||
public SERVICE_NAME: string;
|
||||
private jobQueue: IJobQueue;
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
me = async (userId: string) => {
|
||||
// Need to get teamIds
|
||||
const user = await User.findById(userId);
|
||||
if (!user) {
|
||||
throw new ApiError("User not found", 404);
|
||||
}
|
||||
|
||||
// Find OrgMembership
|
||||
const orgMembership = await OrgMembership.findOne({
|
||||
userId: user._id,
|
||||
}).lean();
|
||||
if (!orgMembership) {
|
||||
throw new ApiError("User is not part of any organization");
|
||||
}
|
||||
|
||||
// Find org and roles
|
||||
const org = await Org.findById(orgMembership.orgId).lean();
|
||||
|
||||
if (!org) {
|
||||
throw new ApiError("Organization not found");
|
||||
}
|
||||
|
||||
const orgRoles = await Role.findById(orgMembership.roleId).lean();
|
||||
|
||||
// Get teams
|
||||
const teamMembershipWithRoles = await TeamMembership.find({
|
||||
userId: user._id,
|
||||
})
|
||||
.populate<{ roleId: IRole }>("roleId")
|
||||
.lean();
|
||||
|
||||
const teamIds = teamMembershipWithRoles.map((tm) => tm.teamId.toString());
|
||||
|
||||
const teams = await this.getTeams(teamIds);
|
||||
const teamMap = new Map(teams.map((t) => [t._id.toString(), t]));
|
||||
const returnableTeams = teamMembershipWithRoles.map((tm) => {
|
||||
const team = teamMap.get(tm.teamId.toString());
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found for membership");
|
||||
}
|
||||
return {
|
||||
id: team._id.toString(),
|
||||
name: team.name,
|
||||
permissions: tm.roleId?.permissions ?? [],
|
||||
};
|
||||
});
|
||||
|
||||
const returnableUser: IUserReturnable = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
org: {
|
||||
name: org.name,
|
||||
permissions: orgRoles?.permissions || [],
|
||||
},
|
||||
teams: returnableTeams,
|
||||
};
|
||||
|
||||
return returnableUser;
|
||||
};
|
||||
|
||||
async register(signupData: RegisterData) {
|
||||
const passwordHash = await hashPassword(signupData.password);
|
||||
|
||||
const created: Record<string, any> = {
|
||||
user: null,
|
||||
org: null,
|
||||
roles: [],
|
||||
team: null,
|
||||
teamMembership: null,
|
||||
orgMembership: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const newUserData: Partial<IUser> = {
|
||||
firstName: signupData.firstName,
|
||||
lastName: signupData.lastName,
|
||||
email: signupData.email,
|
||||
passwordHash,
|
||||
};
|
||||
|
||||
const user = await User.create(newUserData);
|
||||
created.user = user._id;
|
||||
|
||||
const org = await Org.create({
|
||||
name: `${user.firstName}'s Org`,
|
||||
ownerId: user._id,
|
||||
});
|
||||
created.org = org._id;
|
||||
|
||||
const roles = await Role.insertMany([
|
||||
{
|
||||
organizationId: org._id,
|
||||
name: "Org Admin",
|
||||
scope: "organization",
|
||||
permissions: ["*"],
|
||||
},
|
||||
{
|
||||
organizationId: org._id,
|
||||
name: "Org Member",
|
||||
scope: "organization",
|
||||
permissions: [
|
||||
PERMISSIONS.monitors.read,
|
||||
PERMISSIONS.monitors.write,
|
||||
PERMISSIONS.statusPages.read,
|
||||
PERMISSIONS.statusPages.write,
|
||||
PERMISSIONS.notifications.read,
|
||||
PERMISSIONS.notifications.write,
|
||||
PERMISSIONS.teams.read,
|
||||
PERMISSIONS.teams.write,
|
||||
PERMISSIONS.roles.read,
|
||||
PERMISSIONS.roles.write,
|
||||
PERMISSIONS.invite.read,
|
||||
PERMISSIONS.invite.write,
|
||||
PERMISSIONS.incidents.read,
|
||||
PERMISSIONS.incidents.write,
|
||||
],
|
||||
},
|
||||
{
|
||||
organizationId: org._id,
|
||||
name: "Team Admin",
|
||||
permissions: [
|
||||
PERMISSIONS.monitors.all,
|
||||
PERMISSIONS.statusPages.all,
|
||||
PERMISSIONS.notifications.all,
|
||||
PERMISSIONS.incidents.all,
|
||||
],
|
||||
scope: "team",
|
||||
},
|
||||
{
|
||||
organizationId: org._id,
|
||||
name: "Team Member",
|
||||
permissions: [
|
||||
PERMISSIONS.monitors.read,
|
||||
PERMISSIONS.statusPages.read,
|
||||
PERMISSIONS.notifications.read,
|
||||
PERMISSIONS.incidents.read,
|
||||
],
|
||||
scope: "team",
|
||||
},
|
||||
]);
|
||||
|
||||
created.roles = roles.map((r) => r._id);
|
||||
|
||||
const membership = await OrgMembership.create({
|
||||
userId: user._id,
|
||||
orgId: org._id,
|
||||
roleId: roles[0]?._id,
|
||||
});
|
||||
created.orgMembership = membership._id;
|
||||
|
||||
const team = await Team.create({
|
||||
name: "Default Team",
|
||||
orgId: org._id,
|
||||
description: "This is your default team",
|
||||
isSystem: true,
|
||||
});
|
||||
created.team = team._id;
|
||||
|
||||
const teamMembership = await TeamMembership.create({
|
||||
orgId: org._id,
|
||||
userId: user._id,
|
||||
teamId: team._id,
|
||||
roleId: roles[2]?._id,
|
||||
});
|
||||
created.teamMembership = teamMembership._id;
|
||||
|
||||
const tokenizedUser: ITokenizedUser = {
|
||||
sub: user._id.toString(),
|
||||
email: user.email,
|
||||
orgId: org._id.toString(),
|
||||
};
|
||||
|
||||
const returnableTeam = {
|
||||
id: team._id.toString(),
|
||||
name: team.name,
|
||||
permissions: roles[2]?.permissions || [],
|
||||
};
|
||||
|
||||
const returnableUser: IUserReturnable = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
org: {
|
||||
name: org.name,
|
||||
permissions: roles[0]?.permissions || [],
|
||||
},
|
||||
teams: [returnableTeam],
|
||||
};
|
||||
|
||||
return { tokenizedUser, returnableUser };
|
||||
} catch (error) {
|
||||
await TeamMembership.deleteOne({ _id: created.teamMembership });
|
||||
await OrgMembership.deleteOne({ _id: created.orgMembership });
|
||||
await Team.deleteOne({ _id: created.team });
|
||||
await Role.deleteMany({ _id: { $in: created.roles } });
|
||||
if (created.org) await Org.findByIdAndDelete(created.org);
|
||||
if (created.user) await User.findByIdAndDelete(created.user);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
registerWithInvite = async (invite: IInvite, signupData: RegisterData) => {
|
||||
const created: Record<string, any> = {
|
||||
user: null,
|
||||
orgMembership: null,
|
||||
teamMembership: null,
|
||||
};
|
||||
|
||||
try {
|
||||
if (!invite) {
|
||||
throw new ApiError("No token found", 404);
|
||||
}
|
||||
|
||||
const { orgId, orgRoleId, teamId, teamRoleId, email, expiry } = invite;
|
||||
|
||||
if (expiry < new Date()) {
|
||||
throw new ApiError("Invite token has expired", 400);
|
||||
}
|
||||
if (!orgId) {
|
||||
throw new ApiError("No organization ID", 400);
|
||||
}
|
||||
// Check for org
|
||||
const org = await Org.findById(orgId);
|
||||
if (!org) {
|
||||
throw new ApiError("Organization not found", 404);
|
||||
}
|
||||
|
||||
// Get or Create user
|
||||
let user = await User.findOne({ email });
|
||||
if (!user) {
|
||||
const passwordHash = await hashPassword(signupData.password);
|
||||
user = await User.create({
|
||||
email,
|
||||
firstName: signupData.firstName,
|
||||
lastName: signupData.lastName,
|
||||
passwordHash,
|
||||
});
|
||||
created.user = user._id;
|
||||
}
|
||||
|
||||
const team = await Team.findById(teamId);
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found", 404);
|
||||
}
|
||||
|
||||
// Get or create orgMembership
|
||||
let orgMembership = await OrgMembership.findOne({
|
||||
userId: user._id,
|
||||
orgId,
|
||||
});
|
||||
if (orgMembership && !orgMembership.roleId && orgRoleId) {
|
||||
orgMembership.roleId = orgRoleId;
|
||||
await orgMembership.save();
|
||||
}
|
||||
if (!orgMembership) {
|
||||
orgMembership = await OrgMembership.create({
|
||||
orgId,
|
||||
userId: user._id,
|
||||
...(orgRoleId ? { roleId: orgRoleId } : {}),
|
||||
});
|
||||
created.orgMembership = orgMembership._id;
|
||||
}
|
||||
|
||||
// Create TeamMembership
|
||||
let teamMembership = await TeamMembership.findOne({
|
||||
userId: user._id,
|
||||
teamId,
|
||||
});
|
||||
if (teamMembership) {
|
||||
throw new ApiError("User is already a member of the team", 400);
|
||||
}
|
||||
teamMembership = await TeamMembership.create({
|
||||
orgId,
|
||||
teamId,
|
||||
userId: user._id,
|
||||
roleId: teamRoleId,
|
||||
});
|
||||
created.teamMembership = teamMembership._id;
|
||||
|
||||
// Get data for return
|
||||
const teamMembershipWithRoles = await TeamMembership.find({
|
||||
userId: user._id,
|
||||
})
|
||||
.populate<{ roleId: IRole }>("roleId")
|
||||
.lean();
|
||||
|
||||
const teamIds = teamMembershipWithRoles.map((tm) => tm.teamId.toString());
|
||||
|
||||
const teams = await this.getTeams(teamIds);
|
||||
const teamMap = new Map(teams.map((t) => [t._id.toString(), t]));
|
||||
|
||||
const tokenizedUser: ITokenizedUser = {
|
||||
sub: user._id.toString(),
|
||||
email: user.email,
|
||||
orgId: orgId.toString(),
|
||||
};
|
||||
|
||||
const returnableTeams = teamMembershipWithRoles.map((tm) => {
|
||||
const team = teamMap.get(tm.teamId.toString());
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found for membership");
|
||||
}
|
||||
return {
|
||||
id: team._id.toString(),
|
||||
name: team.name,
|
||||
permissions: tm.roleId?.permissions ?? [],
|
||||
};
|
||||
});
|
||||
|
||||
const orgRole = await Role.findById(orgMembership.roleId);
|
||||
const orgPermissions = orgRole?.permissions || [];
|
||||
|
||||
const returnableUser: IUserReturnable = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
org: {
|
||||
name: org.name,
|
||||
permissions: orgPermissions,
|
||||
},
|
||||
teams: returnableTeams,
|
||||
};
|
||||
|
||||
return {
|
||||
tokenizedUser,
|
||||
returnableUser,
|
||||
};
|
||||
} catch (error) {
|
||||
if (created.orgMembership) {
|
||||
await OrgMembership.deleteOne({ _id: created.orgMembership });
|
||||
}
|
||||
if (created.teamMembership) {
|
||||
await TeamMembership.deleteOne({ _id: created.teamMembership });
|
||||
}
|
||||
if (created.user) {
|
||||
await User.findByIdAndDelete(created.user);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
async login(loginData: LoginData): Promise<{
|
||||
tokenizedUser: ITokenizedUser;
|
||||
returnableUser: IUserReturnable;
|
||||
}> {
|
||||
const { email, password } = loginData;
|
||||
|
||||
// Find user by email
|
||||
const user = await User.findOne({ email });
|
||||
|
||||
if (!user) {
|
||||
throw new ApiError("Invalid email or password");
|
||||
}
|
||||
|
||||
// Check password
|
||||
const isPasswordValid = await bcrypt.compare(password, user.passwordHash);
|
||||
if (!isPasswordValid) {
|
||||
throw new ApiError("Invalid email or password");
|
||||
}
|
||||
|
||||
// Find OrgMembership
|
||||
const orgMembership = await OrgMembership.findOne({
|
||||
userId: user._id,
|
||||
}).lean();
|
||||
if (!orgMembership) {
|
||||
throw new ApiError("User is not part of any organization");
|
||||
}
|
||||
|
||||
// Find org and roles
|
||||
const org = await Org.findById(orgMembership.orgId).lean();
|
||||
|
||||
if (!org) {
|
||||
throw new ApiError("Organization not found");
|
||||
}
|
||||
|
||||
const orgRoles = await Role.findById(orgMembership.roleId).lean();
|
||||
|
||||
// Get teams
|
||||
const teamMemberships = await TeamMembership.find({ userId: user._id })
|
||||
.populate<{ roleId: IRole }>("roleId")
|
||||
.lean();
|
||||
|
||||
const teamIds = teamMemberships.map((tm) => tm.teamId.toString());
|
||||
|
||||
const teams = await this.getTeams(teamIds);
|
||||
const teamMap = new Map(teams.map((t) => [t._id.toString(), t]));
|
||||
const returnableTeams = teamMemberships.map((tm) => {
|
||||
const team = teamMap.get(tm.teamId.toString());
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found for membership");
|
||||
}
|
||||
return {
|
||||
id: team._id.toString(),
|
||||
name: team.name,
|
||||
permissions: tm.roleId?.permissions ?? [],
|
||||
};
|
||||
});
|
||||
|
||||
const tokenizedUser: ITokenizedUser = {
|
||||
sub: user._id.toString(),
|
||||
email: user.email,
|
||||
orgId: orgMembership.orgId.toString(),
|
||||
};
|
||||
|
||||
const returnableUser: IUserReturnable = {
|
||||
id: user._id.toString(),
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
org: {
|
||||
name: org.name,
|
||||
permissions: orgRoles?.permissions || [],
|
||||
},
|
||||
teams: returnableTeams,
|
||||
};
|
||||
|
||||
return {
|
||||
tokenizedUser,
|
||||
returnableUser,
|
||||
};
|
||||
}
|
||||
|
||||
async getTeamIds(userId: string): Promise<string[]> {
|
||||
const teamMemberships = await TeamMembership.find({ userId })
|
||||
.select("teamId")
|
||||
.lean();
|
||||
const teamIds = teamMemberships.map((t) => t.teamId.toString());
|
||||
return teamIds;
|
||||
}
|
||||
|
||||
async getTeams(teamIds: string[]): Promise<ITeam[]> {
|
||||
const teams = await Team.find({ _id: { $in: teamIds } }).select(
|
||||
"_id, name"
|
||||
);
|
||||
return teams;
|
||||
}
|
||||
|
||||
async cleanup() {
|
||||
await User.deleteMany({});
|
||||
await Role.deleteMany({});
|
||||
await Monitor.deleteMany({});
|
||||
await Check.deleteMany({});
|
||||
await NotificationChannel.deleteMany({});
|
||||
await this.jobQueue.flush();
|
||||
}
|
||||
|
||||
async cleanMonitors() {
|
||||
await Monitor.deleteMany({});
|
||||
await Check.deleteMany({});
|
||||
}
|
||||
|
||||
changePassword = async (
|
||||
userId: Types.ObjectId,
|
||||
newPassword: string
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
const passwordHash = await hashPassword(newPassword);
|
||||
const result = await User.updateOne(
|
||||
{ _id: userId },
|
||||
{ $set: { passwordHash } }
|
||||
);
|
||||
return result.modifiedCount > 0;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default AuthService;
|
||||
@@ -0,0 +1,273 @@
|
||||
import { ICheck, Check, Monitor, ISystemInfo } from "@/db/models/index.js";
|
||||
import { MonitorStatus } from "@/db/models/monitors/Monitor.js";
|
||||
import { MonitorType } from "@/db/models/monitors/Monitor.js";
|
||||
import { StatusResponse } from "../infrastructure/NetworkService.js";
|
||||
import type {
|
||||
ICapturePayload,
|
||||
ILighthousePayload,
|
||||
} from "../infrastructure/NetworkService.js";
|
||||
import mongoose from "mongoose";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
|
||||
const SERVICE_NAME = "CheckService";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
|
||||
export interface ICheckService {
|
||||
buildCheck: (
|
||||
statusResponse: StatusResponse,
|
||||
type: MonitorType
|
||||
) => Promise<ICheck>;
|
||||
getMonitorChecks: (
|
||||
monitorId: string,
|
||||
page: number,
|
||||
rowsPerPage: number
|
||||
) => Promise<{ checks: ICheck[]; count: number }>;
|
||||
getChecksByStatus: (
|
||||
status: MonitorStatus,
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
range: string
|
||||
) => Promise<{ checks: ICheck[]; count: number }>;
|
||||
|
||||
cleanupOrphanedChecks: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
class CheckService implements ICheckService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
private getStartDate(range: string): Date {
|
||||
const now = new Date();
|
||||
switch (range) {
|
||||
case "2h":
|
||||
return new Date(now.getTime() - 2 * 60 * 60 * 1000);
|
||||
case "24h":
|
||||
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
case "7d":
|
||||
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
case "30d":
|
||||
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
default:
|
||||
throw new ApiError("Invalid range parameter", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private isCapturePayload = (payload: any): payload is ICapturePayload => {
|
||||
if (!payload || typeof payload !== "object") return false;
|
||||
|
||||
if (!("data" in payload) || typeof payload.data !== "object") {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = payload.data as Partial<ISystemInfo>;
|
||||
if (
|
||||
!data.cpu ||
|
||||
typeof data.cpu !== "object" ||
|
||||
typeof data.cpu.usage_percent !== "number"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
!data.memory ||
|
||||
typeof data.memory !== "object" ||
|
||||
typeof data.memory.usage_percent !== "number"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (data.disk && !Array.isArray(data.disk)) {
|
||||
return false;
|
||||
}
|
||||
if (data.net && !Array.isArray(data.net)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!("capture" in payload) || typeof payload.capture !== "object")
|
||||
return false;
|
||||
const capture = payload.capture as Record<string, any>;
|
||||
if (typeof capture.version !== "string" || typeof capture.mode !== "string")
|
||||
return false;
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
private isPagespeedPayload = (
|
||||
payload: any
|
||||
): payload is ILighthousePayload => {
|
||||
if (!payload || typeof payload !== "object") return false;
|
||||
|
||||
if (
|
||||
!("lighthouseResult" in payload) ||
|
||||
typeof payload.lighthouseResult !== "object"
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
private buildBaseCheck = (statusResponse: StatusResponse) => {
|
||||
const monitorId = new mongoose.Types.ObjectId(statusResponse.monitorId);
|
||||
const teamId = new mongoose.Types.ObjectId(statusResponse.teamId);
|
||||
const checkData: Partial<ICheck> = {
|
||||
metadata: {
|
||||
monitorId: monitorId,
|
||||
teamId: teamId,
|
||||
type: statusResponse?.type,
|
||||
},
|
||||
status: statusResponse?.status,
|
||||
httpStatusCode: statusResponse?.code,
|
||||
message: statusResponse?.message,
|
||||
responseTime: statusResponse?.responseTime,
|
||||
timings: statusResponse?.timings,
|
||||
};
|
||||
|
||||
const check: ICheck = new Check(checkData);
|
||||
return check;
|
||||
};
|
||||
|
||||
private buildInfrastructureCheck = (
|
||||
statusResponse: StatusResponse<ICapturePayload>
|
||||
) => {
|
||||
if (!this.isCapturePayload(statusResponse.payload)) {
|
||||
throw new Error("Invalid payload for infrastructure monitor");
|
||||
}
|
||||
const check = this.buildBaseCheck(statusResponse);
|
||||
check.system = statusResponse.payload.data;
|
||||
check.capture = statusResponse.payload.capture;
|
||||
return check;
|
||||
};
|
||||
|
||||
private buildPagespeedCheck = (
|
||||
statusResponse: StatusResponse<ILighthousePayload>
|
||||
) => {
|
||||
if (!this.isPagespeedPayload(statusResponse.payload)) {
|
||||
throw new Error("Invalid payload for pagespeed monitor");
|
||||
}
|
||||
const check = this.buildBaseCheck(statusResponse);
|
||||
const lighthouseResult = statusResponse?.payload?.lighthouseResult;
|
||||
check.lighthouse = {
|
||||
accessibility: lighthouseResult?.categories?.accessibility?.score || 0,
|
||||
bestPractices:
|
||||
lighthouseResult?.categories?.["best-practices"]?.score || 0,
|
||||
seo: lighthouseResult?.categories?.seo?.score || 0,
|
||||
performance: lighthouseResult?.categories?.performance?.score || 0,
|
||||
audits: {
|
||||
cls: lighthouseResult?.audits?.["cumulative-layout-shift"] || {},
|
||||
si: lighthouseResult?.audits?.["speed-index"] || {},
|
||||
fcp: lighthouseResult?.audits?.["first-contentful-paint"] || {},
|
||||
lcp: lighthouseResult?.audits?.["largest-contentful-paint"] || {},
|
||||
tbt: lighthouseResult?.audits?.["total-blocking-time"] || {},
|
||||
},
|
||||
};
|
||||
return check;
|
||||
};
|
||||
|
||||
buildCheck = async (
|
||||
statusResponse: StatusResponse,
|
||||
type: MonitorType
|
||||
): Promise<ICheck> => {
|
||||
switch (type) {
|
||||
case "infrastructure":
|
||||
return this.buildInfrastructureCheck(
|
||||
statusResponse as StatusResponse<ICapturePayload>
|
||||
);
|
||||
|
||||
case "pagespeed":
|
||||
return this.buildPagespeedCheck(
|
||||
statusResponse as StatusResponse<ILighthousePayload>
|
||||
);
|
||||
case "http":
|
||||
case "https":
|
||||
return this.buildBaseCheck(statusResponse);
|
||||
|
||||
case "ping":
|
||||
return this.buildBaseCheck(statusResponse);
|
||||
default:
|
||||
throw new Error(`Unsupported monitor type: ${type}`);
|
||||
}
|
||||
};
|
||||
|
||||
cleanupOrphanedChecks = async () => {
|
||||
try {
|
||||
const monitorIds = await Monitor.find().distinct("_id");
|
||||
const result = await Check.deleteMany({
|
||||
"metadata.monitorId": { $nin: monitorIds },
|
||||
});
|
||||
logger.info(`Deleted ${result.deletedCount} orphaned Checks.`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error("Error cleaning up orphaned Checks:", error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
getMonitorChecks = async (
|
||||
monitorId: string,
|
||||
page: number,
|
||||
rowsPerPage: number
|
||||
) => {
|
||||
const count = await Check.countDocuments({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
});
|
||||
|
||||
const checks = await Check.find({
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
})
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(page * rowsPerPage)
|
||||
.limit(rowsPerPage);
|
||||
return { checks, count };
|
||||
};
|
||||
|
||||
getChecksByStatus = async (
|
||||
status: MonitorStatus,
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
range: string
|
||||
) => {
|
||||
let match;
|
||||
const startDate = this.getStartDate(range);
|
||||
|
||||
if (monitorId) {
|
||||
const authorized = await Monitor.exists({
|
||||
_id: monitorId,
|
||||
teamId,
|
||||
});
|
||||
if (!authorized) {
|
||||
throw new ApiError("Not authorized", 403);
|
||||
}
|
||||
|
||||
match = {
|
||||
status,
|
||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitorId),
|
||||
createdAt: { $gte: startDate },
|
||||
};
|
||||
} else {
|
||||
match = {
|
||||
status,
|
||||
"metadata.teamId": new mongoose.Types.ObjectId(teamId),
|
||||
createdAt: { $gte: startDate },
|
||||
};
|
||||
}
|
||||
const [count, checks] = await Promise.all([
|
||||
Check.countDocuments(match),
|
||||
Check.find(match)
|
||||
.populate({ path: "metadata.monitorId", select: "name" })
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(page * rowsPerPage)
|
||||
.limit(rowsPerPage),
|
||||
]);
|
||||
return { checks, count };
|
||||
};
|
||||
}
|
||||
|
||||
export default CheckService;
|
||||
@@ -0,0 +1,37 @@
|
||||
import { IJobQueue } from "@/services/infrastructure/JobQueue.js";
|
||||
import type {
|
||||
IJobData,
|
||||
IJobMetrics,
|
||||
} from "@/services/infrastructure/JobQueue.js";
|
||||
import { memoryTransport } from "@/logger/Logger.js";
|
||||
|
||||
export interface IDiagnosticService {
|
||||
getLogs: () => any[];
|
||||
getJobs: () => Promise<{
|
||||
jobs: IJobData[] | null;
|
||||
metrics: IJobMetrics | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
const SERVICE_NAME = "DiagnosticService";
|
||||
class DiagnosticService implements IDiagnosticService {
|
||||
public SERVICE_NAME: string;
|
||||
private jobQueue: IJobQueue;
|
||||
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
getLogs = () => {
|
||||
return memoryTransport.getLogs();
|
||||
};
|
||||
|
||||
getJobs = async () => {
|
||||
const jobs = await this.jobQueue.getJobs();
|
||||
const metrics = await this.jobQueue.getMetrics();
|
||||
return { jobs, metrics };
|
||||
};
|
||||
}
|
||||
|
||||
export default DiagnosticService;
|
||||
@@ -0,0 +1,204 @@
|
||||
import { IIncident, Incident, IMonitor, ICheck } from "@/db/models/index.js";
|
||||
import type { ResolutionType } from "@/db/models/index.js";
|
||||
import mongoose from "mongoose";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
export interface IIncidentService {
|
||||
handleStatusChange: (
|
||||
updatedMonitor: IMonitor,
|
||||
lastCheck: ICheck
|
||||
) => Promise<IIncident | null>;
|
||||
create: (
|
||||
teamId: mongoose.Types.ObjectId,
|
||||
monitorId: mongoose.Types.ObjectId,
|
||||
startCheckId: mongoose.Types.ObjectId
|
||||
) => Promise<IIncident>;
|
||||
get: (
|
||||
teamId: mongoose.Types.ObjectId,
|
||||
incidentId: mongoose.Types.ObjectId
|
||||
) => Promise<IIncident | null>;
|
||||
getAll: (
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
range: string,
|
||||
resolved?: boolean,
|
||||
resolutionType?: ResolutionType
|
||||
) => Promise<{ incidents: IIncident[]; count: number }>;
|
||||
resolve: (
|
||||
teamId: string,
|
||||
incidentId: string,
|
||||
resolutionType: ResolutionType,
|
||||
lastCheck?: ICheck,
|
||||
resolvedBy?: string,
|
||||
resolutionNote?: string
|
||||
) => Promise<IIncident | null>;
|
||||
delete: (
|
||||
teamId: mongoose.Types.ObjectId,
|
||||
incidentId: mongoose.Types.ObjectId
|
||||
) => Promise<boolean>;
|
||||
}
|
||||
|
||||
const SERVICE_NAME = "IncidentService";
|
||||
|
||||
class IncidentService implements IIncidentService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
private getStartDate(range: string): Date {
|
||||
const now = new Date();
|
||||
switch (range) {
|
||||
case "2h":
|
||||
return new Date(now.getTime() - 2 * 60 * 60 * 1000);
|
||||
case "24h":
|
||||
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
case "7d":
|
||||
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
case "30d":
|
||||
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
default:
|
||||
throw new ApiError("Invalid range parameter", 400);
|
||||
}
|
||||
}
|
||||
|
||||
handleStatusChange = async (updatedMonitor: IMonitor, lastCheck: ICheck) => {
|
||||
if (updatedMonitor.status === "down") {
|
||||
const incident = await this.create(
|
||||
updatedMonitor.teamId,
|
||||
updatedMonitor._id,
|
||||
lastCheck._id
|
||||
);
|
||||
return incident;
|
||||
} else if (updatedMonitor.status === "up") {
|
||||
const incident = await Incident.findOne({
|
||||
monitorId: updatedMonitor._id,
|
||||
teamId: updatedMonitor.teamId,
|
||||
resolved: false,
|
||||
});
|
||||
|
||||
if (!incident) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const resolvedIncident = await this.resolve(
|
||||
updatedMonitor.teamId.toString(),
|
||||
incident._id.toString(),
|
||||
"auto",
|
||||
lastCheck
|
||||
);
|
||||
return resolvedIncident;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
create = async (
|
||||
teamId: mongoose.Types.ObjectId,
|
||||
monitorId: mongoose.Types.ObjectId,
|
||||
startCheckId: mongoose.Types.ObjectId
|
||||
) => {
|
||||
const existing = await Incident.findOne({
|
||||
monitorId,
|
||||
teamId,
|
||||
resolved: false,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
let data: Partial<IIncident> = {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
monitorId: new mongoose.Types.ObjectId(monitorId),
|
||||
startedAt: new Date(),
|
||||
startCheck: new mongoose.Types.ObjectId(startCheckId),
|
||||
};
|
||||
const incident = await Incident.create(data);
|
||||
return incident;
|
||||
};
|
||||
|
||||
get = async (
|
||||
teamId: mongoose.Types.ObjectId,
|
||||
incidentId: mongoose.Types.ObjectId
|
||||
) => {
|
||||
const incident = await Incident.findOne({
|
||||
_id: new mongoose.Types.ObjectId(incidentId),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
})
|
||||
.populate("monitorId")
|
||||
.populate("resolvedBy");
|
||||
return incident;
|
||||
};
|
||||
|
||||
getAll = async (
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
range: string,
|
||||
resolved?: boolean,
|
||||
resolutionType?: ResolutionType
|
||||
) => {
|
||||
const startDate = this.getStartDate(range);
|
||||
const match = {
|
||||
teamId: teamId,
|
||||
...(monitorId && { monitorId }),
|
||||
createdAt: { $gte: startDate },
|
||||
...(resolved !== undefined && { resolved }),
|
||||
...(resolutionType !== undefined && { resolutionType }),
|
||||
};
|
||||
|
||||
const [count, incidents] = await Promise.all([
|
||||
Incident.countDocuments(match),
|
||||
Incident.find(match)
|
||||
.populate("monitorId")
|
||||
.populate("resolvedBy")
|
||||
.sort({ createdAt: -1 })
|
||||
.skip(page * rowsPerPage)
|
||||
.limit(rowsPerPage),
|
||||
]);
|
||||
return { count, incidents };
|
||||
};
|
||||
|
||||
resolve = async (
|
||||
teamId: string,
|
||||
incidentId: string,
|
||||
resolutionType: ResolutionType,
|
||||
lastCheck?: ICheck,
|
||||
resolvedBy?: string,
|
||||
resolutionNote?: string
|
||||
) => {
|
||||
const incident = await Incident.findOneAndUpdate(
|
||||
{ _id: incidentId, teamId, resolved: false },
|
||||
{
|
||||
$set: {
|
||||
resolved: true,
|
||||
endedAt: new Date(),
|
||||
endCheck: lastCheck ? lastCheck._id : undefined,
|
||||
resolvedBy: resolvedBy ? resolvedBy : undefined,
|
||||
resolutionType,
|
||||
resolutionNote: resolutionNote ? resolutionNote : undefined,
|
||||
},
|
||||
},
|
||||
{ new: true }
|
||||
);
|
||||
|
||||
return incident;
|
||||
};
|
||||
|
||||
delete = async (
|
||||
teamId: mongoose.Types.ObjectId,
|
||||
incidentId: mongoose.Types.ObjectId
|
||||
) => {
|
||||
const result = await Incident.deleteOne({
|
||||
_id: new mongoose.Types.ObjectId(incidentId),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default IncidentService;
|
||||
@@ -0,0 +1,118 @@
|
||||
import crypto from "node:crypto";
|
||||
import {
|
||||
IInvite,
|
||||
Invite,
|
||||
User,
|
||||
IUser,
|
||||
Role,
|
||||
Team,
|
||||
TeamMembership,
|
||||
} from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "InviteService";
|
||||
export interface IInviteService {
|
||||
create: (
|
||||
userId: string,
|
||||
email: string,
|
||||
orgId: string,
|
||||
orgRoleId: string,
|
||||
teamId: string,
|
||||
teamRoleId: string
|
||||
) => Promise<string>;
|
||||
getAll: () => Promise<IInvite[]>;
|
||||
get: (tokenHash: string) => Promise<{ user: IUser | null; invite: IInvite }>;
|
||||
delete: (id: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class InviteService implements IInviteService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
create = async (
|
||||
userId: string,
|
||||
email: string,
|
||||
orgId: string,
|
||||
orgRoleId: string,
|
||||
teamId: string,
|
||||
teamRoleId: string
|
||||
) => {
|
||||
try {
|
||||
const role = await Role.findOne({
|
||||
_id: teamRoleId,
|
||||
organizationId: orgId,
|
||||
});
|
||||
|
||||
if (!role) {
|
||||
throw new ApiError("Role not found", 404);
|
||||
}
|
||||
|
||||
const team = await Team.findOne({
|
||||
_id: teamId,
|
||||
orgId,
|
||||
});
|
||||
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found", 404);
|
||||
}
|
||||
|
||||
// Check if already a team member
|
||||
const user = await User.findOne({ email });
|
||||
const existingMembership = await TeamMembership.findOne({
|
||||
userId: user?._id,
|
||||
teamId,
|
||||
});
|
||||
|
||||
if (existingMembership) {
|
||||
throw new ApiError("User is already a team member", 409);
|
||||
}
|
||||
|
||||
const token = crypto.randomBytes(32).toString("hex");
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
|
||||
const invite = await Invite.create({
|
||||
orgId,
|
||||
...(orgRoleId && { orgRoleId }),
|
||||
teamId,
|
||||
teamRoleId,
|
||||
email,
|
||||
tokenHash,
|
||||
createdBy: userId,
|
||||
updatedBy: userId,
|
||||
});
|
||||
|
||||
if (!invite) {
|
||||
throw new ApiError("Failed to create invite", 500);
|
||||
}
|
||||
return token;
|
||||
} catch (error: any) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
get = async (token: string) => {
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
const invite = await Invite.findOne({ tokenHash });
|
||||
if (!invite) {
|
||||
throw new ApiError("Invite not found", 404);
|
||||
}
|
||||
const user = await User.findOne({ email: invite.email });
|
||||
return { user, invite };
|
||||
};
|
||||
|
||||
getAll = async () => {
|
||||
return Invite.find();
|
||||
};
|
||||
|
||||
delete = async (id: string) => {
|
||||
const result = await Invite.deleteOne({ _id: id });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Invite not found", 404);
|
||||
}
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default InviteService;
|
||||
@@ -0,0 +1,235 @@
|
||||
import {
|
||||
Monitor,
|
||||
IUserContext,
|
||||
IMaintenance,
|
||||
Maintenance,
|
||||
MaintenanceRepeats,
|
||||
} from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "MaintenanceService";
|
||||
const DAY_MS = 24 * 60 * 60 * 1000;
|
||||
const WEEK_MS = 7 * DAY_MS;
|
||||
|
||||
export interface IMaintenanceService {
|
||||
create: (
|
||||
userContext: IUserContext,
|
||||
maintenance: IMaintenance
|
||||
) => Promise<IMaintenance>;
|
||||
getAll: (teamId: string) => Promise<IMaintenance[]>;
|
||||
get: (teamId: string, id: string) => Promise<IMaintenance>;
|
||||
toggleActive: (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string
|
||||
) => Promise<IMaintenance>;
|
||||
update: (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string,
|
||||
updateData: Partial<IMaintenance>
|
||||
) => Promise<IMaintenance>;
|
||||
delete: (teamId: string, id: string) => Promise<boolean>;
|
||||
isInMaintenance: (monitorId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
type MaintenanceCache = Map<string, IMaintenance[]>;
|
||||
|
||||
class MaintenanceService implements IMaintenanceService {
|
||||
public SERVICE_NAME: string;
|
||||
private maintenanceCache: MaintenanceCache;
|
||||
private lastRefresh: number;
|
||||
private CACHE_TTL_MS = 60 * 1000;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.maintenanceCache = new Map();
|
||||
this.lastRefresh = 0;
|
||||
}
|
||||
|
||||
create = async (userContext: IUserContext, maintenanceData: IMaintenance) => {
|
||||
// Make sure monitors belong to current team
|
||||
const monitorIds = maintenanceData.monitors || [];
|
||||
const count = await Monitor.countDocuments({
|
||||
_id: { $in: monitorIds },
|
||||
teamId: userContext.currentTeamId,
|
||||
});
|
||||
|
||||
if (count !== monitorIds.length) {
|
||||
throw new ApiError(
|
||||
"One or more monitors do not belong to the current team",
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
const maintenance = await Maintenance.create({
|
||||
...maintenanceData,
|
||||
orgId: userContext.orgId,
|
||||
teamId: userContext.currentTeamId,
|
||||
createdBy: userContext.sub,
|
||||
updatedBy: userContext.sub,
|
||||
});
|
||||
return maintenance;
|
||||
};
|
||||
|
||||
get = async (teamId: string, id: string) => {
|
||||
const maintenance = await Maintenance.findOne({ _id: id, teamId });
|
||||
if (!maintenance) {
|
||||
throw new ApiError("Maintenance not found", 404);
|
||||
}
|
||||
return maintenance;
|
||||
};
|
||||
|
||||
getAll = async (teamId: string) => {
|
||||
return Maintenance.find({ teamId });
|
||||
};
|
||||
|
||||
toggleActive = async (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string
|
||||
) => {
|
||||
const updatedMaintenance = await Maintenance.findOneAndUpdate(
|
||||
{ _id: id, teamId },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
isActive: { $not: "$isActive" },
|
||||
updatedBy: userContext.sub,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
},
|
||||
],
|
||||
{ new: true }
|
||||
);
|
||||
if (!updatedMaintenance) {
|
||||
throw new ApiError("Maintenance not found", 404);
|
||||
}
|
||||
return updatedMaintenance;
|
||||
};
|
||||
|
||||
update = async (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string,
|
||||
updateData: Partial<IMaintenance>
|
||||
) => {
|
||||
// Make sure monitors belong to current team
|
||||
const monitorIds = updateData.monitors || [];
|
||||
const count = await Monitor.countDocuments({
|
||||
_id: { $in: monitorIds },
|
||||
teamId: userContext.currentTeamId,
|
||||
});
|
||||
|
||||
if (count !== monitorIds.length) {
|
||||
throw new ApiError(
|
||||
"One or more monitors do not belong to the current team",
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
const allowedFields: (keyof IMaintenance)[] = [
|
||||
"name",
|
||||
"monitors",
|
||||
"repeat",
|
||||
"startTime",
|
||||
"endTime",
|
||||
"isActive",
|
||||
];
|
||||
const safeUpdate: Partial<IMaintenance> = {};
|
||||
for (const field of allowedFields) {
|
||||
if (updateData[field] !== undefined) {
|
||||
(safeUpdate as any)[field] = updateData[field];
|
||||
}
|
||||
}
|
||||
|
||||
const updatedMaintenance = await Maintenance.findOneAndUpdate(
|
||||
{ _id: id, teamId },
|
||||
{
|
||||
$set: {
|
||||
...safeUpdate,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: userContext.sub,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedMaintenance) {
|
||||
throw new ApiError("Failed to update maintenance", 500);
|
||||
}
|
||||
|
||||
return updatedMaintenance;
|
||||
};
|
||||
|
||||
delete = async (teamId: string, id: string) => {
|
||||
const result = await Maintenance.deleteOne({ _id: id, teamId });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Maintenance not found", 404);
|
||||
}
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
|
||||
private refreshCache = async () => {
|
||||
const now = new Date();
|
||||
|
||||
const activeMaintenances = await Maintenance.find({
|
||||
isActive: true,
|
||||
$or: [
|
||||
{ repeat: { $in: MaintenanceRepeats } },
|
||||
{ startTime: { $lte: now }, endTime: { $gte: now } },
|
||||
],
|
||||
}).lean();
|
||||
|
||||
// Reset cache
|
||||
const newCache = new Map();
|
||||
|
||||
for (const m of activeMaintenances) {
|
||||
for (const monitorId of m.monitors) {
|
||||
const key = monitorId.toString();
|
||||
if (!newCache.has(key)) newCache.set(key, []);
|
||||
newCache.get(key)!.push(m);
|
||||
}
|
||||
}
|
||||
|
||||
this.maintenanceCache = newCache;
|
||||
this.lastRefresh = Date.now();
|
||||
};
|
||||
|
||||
isInMaintenance = async (monitorId: string) => {
|
||||
const now = Date.now();
|
||||
|
||||
if (now - this.lastRefresh > this.CACHE_TTL_MS) {
|
||||
await this.refreshCache();
|
||||
}
|
||||
|
||||
const maintenances = this.maintenanceCache.get(monitorId) || [];
|
||||
|
||||
for (const m of maintenances) {
|
||||
const start = m.startTime.getTime();
|
||||
const end = m.endTime.getTime();
|
||||
const duration = end - start;
|
||||
|
||||
let isActiveNow = false;
|
||||
if (!m.repeat || m.repeat === "no repeat") {
|
||||
isActiveNow = start <= now && now <= end;
|
||||
} else {
|
||||
const elapsed = now - start;
|
||||
if (elapsed >= 0) {
|
||||
const period = m.repeat === "daily" ? DAY_MS : WEEK_MS;
|
||||
const offset = elapsed % period;
|
||||
if (offset < duration) {
|
||||
isActiveNow = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (isActiveNow) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
export default MaintenanceService;
|
||||
@@ -0,0 +1,603 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
import { IMonitor, Monitor, MonitorStats, Check } from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { IJobQueue } from "@/services/infrastructure/JobQueue.js";
|
||||
import { MonitorWithChecksResponse } from "@/types/index.js";
|
||||
import { MonitorStatus, MonitorType } from "@/db/models/monitors/Monitor.js";
|
||||
|
||||
const SERVICE_NAME = "MonitorService";
|
||||
|
||||
export interface IMonitorService {
|
||||
create: (
|
||||
orgId: string,
|
||||
userId: string,
|
||||
currentTeamId: string,
|
||||
monitorData: IMonitor
|
||||
) => Promise<IMonitor>;
|
||||
getAll: (teamId: string) => Promise<IMonitor[]>;
|
||||
getAllEmbedChecks: (
|
||||
teamId: string,
|
||||
page: number,
|
||||
limit: number,
|
||||
type: MonitorType[]
|
||||
) => Promise<{
|
||||
count: number;
|
||||
upCount: number;
|
||||
downCount: number;
|
||||
pausedCount: number;
|
||||
monitors: any[];
|
||||
}>;
|
||||
get: (teamId: string, monitorId: string) => Promise<IMonitor>;
|
||||
getEmbedChecks: (
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
range: string,
|
||||
status?: string
|
||||
) => Promise<MonitorWithChecksResponse>;
|
||||
toggleActive: (
|
||||
userId: string,
|
||||
teamId: string,
|
||||
monitorId: string
|
||||
) => Promise<IMonitor>;
|
||||
update: (
|
||||
userId: string,
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
updateData: Partial<IMonitor>
|
||||
) => Promise<IMonitor>;
|
||||
delete: (teamId: string, monitorId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class MonitorService implements IMonitorService {
|
||||
public SERVICE_NAME: string;
|
||||
private jobQueue: IJobQueue;
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
create = async (
|
||||
orgId: string,
|
||||
userId: string,
|
||||
currentTeamId: string,
|
||||
monitorData: IMonitor
|
||||
) => {
|
||||
const monitorLiteral: Partial<IMonitor> = {
|
||||
...monitorData,
|
||||
orgId: new mongoose.Types.ObjectId(orgId),
|
||||
teamId: new mongoose.Types.ObjectId(currentTeamId),
|
||||
createdBy: new mongoose.Types.ObjectId(userId),
|
||||
updatedBy: new mongoose.Types.ObjectId(userId),
|
||||
};
|
||||
|
||||
const monitor = await Monitor.create(monitorLiteral);
|
||||
await MonitorStats.create({
|
||||
monitorId: monitor._id,
|
||||
currentStreakStartedAt: Date.now(),
|
||||
});
|
||||
await this.jobQueue.addJob(monitor);
|
||||
return monitor;
|
||||
};
|
||||
|
||||
getAll = async (teamId: string) => {
|
||||
return Monitor.find({ teamId });
|
||||
};
|
||||
|
||||
getAllEmbedChecks = async (
|
||||
teamId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
type: MonitorType[] = []
|
||||
) => {
|
||||
const countResult = await Monitor.aggregate([
|
||||
{
|
||||
$match: {
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
type: { $in: type },
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: null,
|
||||
total: { $sum: 1 },
|
||||
upCount: { $sum: { $cond: [{ $eq: ["$status", "up"] }, 1, 0] } },
|
||||
downCount: { $sum: { $cond: [{ $eq: ["$status", "down"] }, 1, 0] } },
|
||||
pausedCount: {
|
||||
$sum: { $cond: [{ $eq: ["$isActive", false] }, 1, 0] },
|
||||
},
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const counts = countResult[0] || {
|
||||
total: 0,
|
||||
upCount: 0,
|
||||
downCount: 0,
|
||||
pausedCount: 0,
|
||||
};
|
||||
|
||||
const skip = page * rowsPerPage;
|
||||
let find = {};
|
||||
if (type.length > 0) find = { type: { $in: type } };
|
||||
find = { ...find, teamId };
|
||||
|
||||
const monitors = await Monitor.find(find)
|
||||
.lean()
|
||||
.skip(skip)
|
||||
.limit(rowsPerPage);
|
||||
|
||||
if (
|
||||
type.length === 1 &&
|
||||
(type[0] === "pagespeed" || type[0] === "infrastructure")
|
||||
) {
|
||||
const monitorIds = monitors.map((m) => m._id);
|
||||
|
||||
const checks = await Check.aggregate([
|
||||
{
|
||||
$match: {
|
||||
"metadata.monitorId": { $in: monitorIds },
|
||||
},
|
||||
},
|
||||
{ $sort: { createdAt: -1 } },
|
||||
{
|
||||
$group: {
|
||||
_id: "$metadata.monitorId",
|
||||
latestChecks: { $push: "$$ROOT" },
|
||||
},
|
||||
},
|
||||
{ $project: { latestChecks: { $slice: ["$latestChecks", 25] } } },
|
||||
]);
|
||||
|
||||
const checksMap = new Map(
|
||||
checks.map((c: any) => [c._id.toString(), c.latestChecks])
|
||||
);
|
||||
|
||||
monitors.forEach((monitor) => {
|
||||
monitor.latestChecks = checksMap.get(monitor._id.toString()) || [];
|
||||
});
|
||||
}
|
||||
return {
|
||||
count: counts.total,
|
||||
upCount: counts.upCount,
|
||||
downCount: counts.downCount,
|
||||
pausedCount: counts.pausedCount,
|
||||
monitors,
|
||||
};
|
||||
};
|
||||
|
||||
get = async (teamId: string, monitorId: string) => {
|
||||
const monitor = await Monitor.findOne({ _id: monitorId, teamId });
|
||||
if (!monitor) {
|
||||
throw new ApiError("Monitor not found", 404);
|
||||
}
|
||||
return monitor;
|
||||
};
|
||||
|
||||
private getStartDate(range: string): Date {
|
||||
const now = new Date();
|
||||
switch (range) {
|
||||
case "2h":
|
||||
return new Date(now.getTime() - 2 * 60 * 60 * 1000);
|
||||
case "24h":
|
||||
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
||||
case "7d":
|
||||
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
||||
case "30d":
|
||||
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
||||
default:
|
||||
throw new ApiError("Invalid range parameter", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private getDateFormat(range: string): string {
|
||||
switch (range) {
|
||||
case "2h":
|
||||
return "%Y-%m-%dT%H:%M:00Z";
|
||||
case "24h":
|
||||
case "7d":
|
||||
return "%Y-%m-%dT%H:00:00Z";
|
||||
case "30d":
|
||||
return "%Y-%m-%d";
|
||||
default:
|
||||
throw new ApiError("Invalid range parameter", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private getBaseGroup = (dateFormat: string): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateToString: { format: dateFormat, date: "$createdAt" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
};
|
||||
};
|
||||
|
||||
private getBaseProjection = (): object => {
|
||||
return { status: 1, responseTime: 1, createdAt: 1 };
|
||||
};
|
||||
|
||||
private getPageSpeedGroup = (dateFormat: string): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateToString: { format: dateFormat, date: "$createdAt" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
accessibility: { $avg: "$lighthouse.accessibility" },
|
||||
bestPractices: { $avg: "$lighthouse.bestPractices" },
|
||||
seo: { $avg: "$lighthouse.seo" },
|
||||
performance: { $avg: "$lighthouse.performance" },
|
||||
cls: { $avg: "$lighthouse.audits.cls.score" },
|
||||
si: { $avg: "$lighthouse.audits.si.score" },
|
||||
fcp: { $avg: "$lighthouse.audits.fcp.score" },
|
||||
lcp: { $avg: "$lighthouse.audits.lcp.score" },
|
||||
tbt: { $avg: "$lighthouse.audits.tbt.score" },
|
||||
};
|
||||
};
|
||||
|
||||
private getPageSpeedProjection = (): object => {
|
||||
const projectStage: any = { status: 1, responseTime: 1, createdAt: 1 };
|
||||
projectStage["lighthouse.accessibility"] = 1;
|
||||
projectStage["lighthouse.seo"] = 1;
|
||||
projectStage["lighthouse.bestPractices"] = 1;
|
||||
projectStage["lighthouse.performance"] = 1;
|
||||
projectStage["lighthouse.audits.cls.score"] = 1;
|
||||
projectStage["lighthouse.audits.si.score"] = 1;
|
||||
projectStage["lighthouse.audits.fcp.score"] = 1;
|
||||
projectStage["lighthouse.audits.lcp.score"] = 1;
|
||||
projectStage["lighthouse.audits.tbt.score"] = 1;
|
||||
return projectStage;
|
||||
};
|
||||
|
||||
private getInfraGroup = (dateFormat: string): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateToString: { format: dateFormat, date: "$createdAt" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
physicalCores: { $last: "$system.cpu.physical_core" },
|
||||
logicalCores: { $last: "$system.cpu.logical_core" },
|
||||
frequency: { $avg: "$system.cpu.frequency" },
|
||||
currentFrequency: { $last: "$system.cpu.current_frequency" },
|
||||
tempsArrays: { $push: "$system.cpu.temperature" },
|
||||
freePercent: { $avg: "$system.cpu.free_percent" },
|
||||
usedPercent: { $avg: "$system.cpu.usage_percent" },
|
||||
total_bytes: { $last: "$system.memory.total_bytes" },
|
||||
available_bytes: { $last: "$system.memory.available_bytes" },
|
||||
used_bytes: { $last: "$system.memory.used_bytes" },
|
||||
memory_usage_percent: { $avg: "$system.memory.usage_percent" },
|
||||
disksArray: { $push: "$system.disk" },
|
||||
os: { $last: "$system.host.os" },
|
||||
platform: { $last: "$system.host.platform" },
|
||||
kernel_version: { $last: "$system.host.kernel_version" },
|
||||
pretty_name: { $last: "$system.host.pretty_name" },
|
||||
netsArray: { $push: "$system.net" },
|
||||
};
|
||||
};
|
||||
|
||||
private getInfraProjection = (): object => {
|
||||
const projectStage: any = { status: 1, responseTime: 1, createdAt: 1 };
|
||||
projectStage["system.cpu.physical_core"] = 1;
|
||||
projectStage["system.cpu.logical_core"] = 1;
|
||||
projectStage["system.cpu.frequency"] = 1;
|
||||
projectStage["system.cpu.current_frequency"] = 1;
|
||||
projectStage["system.cpu.temperature"] = 1;
|
||||
projectStage["system.cpu.free_percent"] = 1;
|
||||
projectStage["system.cpu.usage_percent"] = 1;
|
||||
projectStage["system.memory.total_bytes"] = 1;
|
||||
projectStage["system.memory.available_bytes"] = 1;
|
||||
projectStage["system.memory.used_bytes"] = 1;
|
||||
projectStage["system.memory.usage_percent"] = 1;
|
||||
projectStage["system.disk"] = 1;
|
||||
projectStage["system.host.os"] = 1;
|
||||
projectStage["system.host.platform"] = 1;
|
||||
projectStage["system.host.kernel_version"] = 1;
|
||||
projectStage["system.host.pretty_name"] = 1;
|
||||
projectStage["system.net"] = 1;
|
||||
return projectStage;
|
||||
};
|
||||
|
||||
private getFinalProjection = (type: string): object => {
|
||||
if (type === "pagespeed") {
|
||||
return {
|
||||
_id: 1,
|
||||
count: 1,
|
||||
avgResponseTime: 1,
|
||||
accessibility: "$accessibility",
|
||||
seo: "$seo",
|
||||
bestPractices: "$bestPractices",
|
||||
performance: "$performance",
|
||||
cls: "$cls",
|
||||
si: "$si",
|
||||
fcp: "$fcp",
|
||||
lcp: "$lcp",
|
||||
tbt: "$tbt",
|
||||
};
|
||||
}
|
||||
|
||||
if (type === "infrastructure") {
|
||||
return {
|
||||
_id: 1,
|
||||
count: 1,
|
||||
avgResponseTime: 1,
|
||||
cpu: {
|
||||
physical_core: "$physicalCores",
|
||||
logical_core: "$logicalCores",
|
||||
frequency: "$frequency",
|
||||
current_frequency: "$currentFrequency",
|
||||
temperature: {
|
||||
$map: {
|
||||
input: {
|
||||
$range: [0, { $size: { $arrayElemAt: ["$tempsArrays", 0] } }],
|
||||
},
|
||||
as: "idx",
|
||||
in: {
|
||||
$avg: {
|
||||
$map: {
|
||||
input: "$tempsArrays",
|
||||
as: "arr",
|
||||
in: { $arrayElemAt: ["$$arr", "$$idx"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
free_percent: "$freePercent",
|
||||
used_percent: "$usedPercent",
|
||||
},
|
||||
memory: {
|
||||
total_bytes: "$total_bytes",
|
||||
available_bytes: "$available_bytes",
|
||||
used_bytes: "$used_bytes",
|
||||
usage_percent: "$memory_usage_percent",
|
||||
},
|
||||
disk: {
|
||||
$map: {
|
||||
input: {
|
||||
$range: [0, { $size: { $arrayElemAt: ["$disksArray", 0] } }],
|
||||
},
|
||||
as: "idx",
|
||||
in: {
|
||||
$let: {
|
||||
vars: {
|
||||
diskGroup: {
|
||||
$map: {
|
||||
input: "$disksArray",
|
||||
as: "diskArr",
|
||||
in: { $arrayElemAt: ["$$diskArr", "$$idx"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
in: {
|
||||
device: { $arrayElemAt: ["$$diskGroup.device", 0] },
|
||||
total_bytes: { $avg: "$$diskGroup.total_bytes" },
|
||||
free_bytes: { $avg: "$$diskGroup.free_bytes" },
|
||||
used_bytes: { $avg: "$$diskGroup.used_bytes" },
|
||||
usage_percent: { $avg: "$$diskGroup.usage_percent" },
|
||||
total_inodes: { $avg: "$$diskGroup.total_inodes" },
|
||||
free_inodes: { $avg: "$$diskGroup.free_inodes" },
|
||||
used_inodes: { $avg: "$$diskGroup.used_inodes" },
|
||||
inodes_usage_percent: {
|
||||
$avg: "$$diskGroup.inodes_usage_percent",
|
||||
},
|
||||
read_bytes: { $avg: "$$diskGroup.read_bytes" },
|
||||
write_bytes: { $avg: "$$diskGroup.write_bytes" },
|
||||
read_time: { $avg: "$$diskGroup.read_time" },
|
||||
write_time: { $avg: "$$diskGroup.write_time" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
host: {
|
||||
os: "$os",
|
||||
platform: "$platform",
|
||||
kernel_version: "$kernel_version",
|
||||
pretty_name: "$pretty_name",
|
||||
},
|
||||
net: {
|
||||
$map: {
|
||||
input: {
|
||||
$range: [0, { $size: { $arrayElemAt: ["$netsArray", 0] } }],
|
||||
},
|
||||
as: "idx",
|
||||
in: {
|
||||
$let: {
|
||||
vars: {
|
||||
netGroup: {
|
||||
$map: {
|
||||
input: "$netsArray",
|
||||
as: "netArr",
|
||||
in: { $arrayElemAt: ["$$netArr", "$$idx"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
in: {
|
||||
name: { $arrayElemAt: ["$$netGroup.name", 0] },
|
||||
bytes_sent: { $avg: "$$netGroup.bytes_sent" },
|
||||
bytes_recv: { $avg: "$$netGroup.bytes_recv" },
|
||||
packets_sent: { $avg: "$$netGroup.packets_sent" },
|
||||
packets_recv: { $avg: "$$netGroup.packets_recv" },
|
||||
err_in: { $avg: "$$netGroup.err_in" },
|
||||
err_out: { $avg: "$$netGroup.err_out" },
|
||||
drop_in: { $avg: "$$netGroup.drop_in" },
|
||||
drop_out: { $avg: "$$netGroup.drop_out" },
|
||||
fifo_in: { $avg: "$$netGroup.fifo_in" },
|
||||
fifo_out: { $avg: "$$netGroup.fifo_out" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
getEmbedChecks = async (
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
range: string,
|
||||
status: string | undefined
|
||||
): Promise<MonitorWithChecksResponse> => {
|
||||
const monitor = await Monitor.findOne({ _id: monitorId, teamId });
|
||||
if (!monitor) {
|
||||
throw new ApiError("Monitor not found", 404);
|
||||
}
|
||||
|
||||
const startDate = this.getStartDate(range);
|
||||
const dateFormat = this.getDateFormat(range);
|
||||
|
||||
// Build match stage
|
||||
const matchStage: {
|
||||
"metadata.monitorId": mongoose.Types.ObjectId;
|
||||
createdAt: { $gte: Date };
|
||||
status?: string;
|
||||
} = {
|
||||
"metadata.monitorId": monitor._id,
|
||||
createdAt: { $gte: startDate },
|
||||
};
|
||||
|
||||
if (status) {
|
||||
matchStage.status = status;
|
||||
}
|
||||
|
||||
let groupClause;
|
||||
|
||||
if (monitor.type === "pagespeed") {
|
||||
groupClause = this.getPageSpeedGroup(dateFormat);
|
||||
} else if (monitor.type === "infrastructure") {
|
||||
groupClause = this.getInfraGroup(dateFormat);
|
||||
} else {
|
||||
groupClause = this.getBaseGroup(dateFormat);
|
||||
}
|
||||
|
||||
let projectStage;
|
||||
if (monitor.type === "pagespeed") {
|
||||
projectStage = this.getPageSpeedProjection();
|
||||
} else if (monitor.type === "infrastructure") {
|
||||
projectStage = this.getInfraProjection();
|
||||
} else {
|
||||
projectStage = this.getBaseProjection();
|
||||
}
|
||||
|
||||
let finalProjection = {};
|
||||
if (monitor.type === "pagespeed" || monitor.type === "infrastructure") {
|
||||
finalProjection = this.getFinalProjection(monitor.type);
|
||||
} else {
|
||||
finalProjection = { _id: 1, count: 1, avgResponseTime: 1 };
|
||||
}
|
||||
|
||||
const checks = await Check.aggregate([
|
||||
{
|
||||
$match: matchStage,
|
||||
},
|
||||
{ $sort: { createdAt: 1 } },
|
||||
{ $project: projectStage },
|
||||
{ $group: groupClause },
|
||||
{ $sort: { _id: -1 } },
|
||||
{
|
||||
$project: finalProjection,
|
||||
},
|
||||
]);
|
||||
|
||||
// Get monitor stats
|
||||
const monitorStats = await MonitorStats.findOne({
|
||||
monitorId: monitor._id,
|
||||
});
|
||||
|
||||
if (!monitorStats) {
|
||||
throw new ApiError("Monitor stats not found", 404);
|
||||
}
|
||||
|
||||
return {
|
||||
monitor: monitor.toObject(),
|
||||
checks,
|
||||
stats: monitorStats,
|
||||
};
|
||||
};
|
||||
|
||||
async toggleActive(userId: string, teamId: string, id: string) {
|
||||
const pendingStatus: MonitorStatus = "initializing";
|
||||
const updatedMonitor = await Monitor.findOneAndUpdate(
|
||||
{ _id: id, teamId },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
isActive: { $not: "$isActive" },
|
||||
status: pendingStatus,
|
||||
updatedBy: userId,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
},
|
||||
],
|
||||
{ new: true }
|
||||
);
|
||||
|
||||
if (!updatedMonitor) {
|
||||
throw new ApiError("Monitor not found", 404);
|
||||
}
|
||||
|
||||
await this.jobQueue.updateJob(updatedMonitor);
|
||||
|
||||
if (updatedMonitor?.isActive) {
|
||||
await this.jobQueue.resumeJob(updatedMonitor);
|
||||
} else {
|
||||
await this.jobQueue.pauseJob(updatedMonitor);
|
||||
}
|
||||
return updatedMonitor;
|
||||
}
|
||||
|
||||
async update(
|
||||
userId: string,
|
||||
teamId: string,
|
||||
monitorId: string,
|
||||
updateData: Partial<IMonitor>
|
||||
) {
|
||||
const allowedFields: (keyof IMonitor)[] = [
|
||||
"name",
|
||||
"secret",
|
||||
"interval",
|
||||
"isActive",
|
||||
"n",
|
||||
"notificationChannels",
|
||||
];
|
||||
const safeUpdate: Partial<IMonitor> = {};
|
||||
|
||||
for (const field of allowedFields) {
|
||||
if (updateData[field] !== undefined) {
|
||||
(safeUpdate as any)[field] = updateData[field];
|
||||
}
|
||||
}
|
||||
|
||||
const updatedMonitor = await Monitor.findOneAndUpdate(
|
||||
{ _id: monitorId, teamId },
|
||||
{
|
||||
$set: {
|
||||
...safeUpdate,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: userId,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedMonitor) {
|
||||
throw new ApiError("Monitor not found", 404);
|
||||
}
|
||||
await this.jobQueue.updateJob(updatedMonitor);
|
||||
return updatedMonitor;
|
||||
}
|
||||
|
||||
async delete(teamId: string, monitorId: string) {
|
||||
const monitor = await Monitor.findOne({ _id: monitorId, teamId });
|
||||
if (!monitor) {
|
||||
throw new ApiError("Monitor not found", 404);
|
||||
}
|
||||
const deleted = await this.jobQueue.deleteJob(monitor);
|
||||
if (!deleted) {
|
||||
throw new ApiError("Failed to delete monitor job from queue", 500);
|
||||
}
|
||||
await monitor.deleteOne();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
export default MonitorService;
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Monitor, MonitorStats } from "@/db/models/index.js";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
|
||||
const SERVICE_NAME = "MonitorStatsService";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
export interface IMonitorStatsService {
|
||||
cleanupOrphanedMonitorStats: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
class MonitorStatsService implements IMonitorStatsService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
async cleanupOrphanedMonitorStats() {
|
||||
try {
|
||||
const monitorIds = await Monitor.find().distinct("_id");
|
||||
const result = await MonitorStats.deleteMany({
|
||||
monitorId: { $nin: monitorIds },
|
||||
});
|
||||
logger.info(`Deleted ${result.deletedCount} orphaned MonitorStats.`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error("Error cleaning up orphaned MonitorStats:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default MonitorStatsService;
|
||||
@@ -0,0 +1,132 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
import {
|
||||
IUserContext,
|
||||
INotificationChannel,
|
||||
NotificationChannel,
|
||||
Monitor,
|
||||
} from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "NotificationChannelService";
|
||||
|
||||
export interface INotificationChannelService {
|
||||
create: (
|
||||
tokenizedUser: IUserContext,
|
||||
notificationChannel: INotificationChannel
|
||||
) => Promise<INotificationChannel>;
|
||||
getAll: (teamId: string) => Promise<INotificationChannel[]>;
|
||||
get: (teamId: string, id: string) => Promise<INotificationChannel>;
|
||||
toggleActive: (
|
||||
teamId: string,
|
||||
tokenizedUser: IUserContext,
|
||||
id: string
|
||||
) => Promise<INotificationChannel>;
|
||||
update: (
|
||||
teamId: string,
|
||||
tokenizedUser: IUserContext,
|
||||
id: string,
|
||||
updateData: Partial<INotificationChannel>
|
||||
) => Promise<INotificationChannel>;
|
||||
delete: (teamId: string, id: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class NotificationChannelService implements INotificationChannelService {
|
||||
public SERVICE_NAME: string;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
create = async (
|
||||
userContext: IUserContext,
|
||||
notificationChannelData: INotificationChannel
|
||||
) => {
|
||||
const data: INotificationChannel = {
|
||||
...notificationChannelData,
|
||||
orgId: new mongoose.Types.ObjectId(userContext.orgId),
|
||||
teamId: new mongoose.Types.ObjectId(userContext.currentTeamId),
|
||||
createdBy: new mongoose.Types.ObjectId(userContext.sub),
|
||||
updatedBy: new mongoose.Types.ObjectId(userContext.sub),
|
||||
};
|
||||
|
||||
const notificationChannel = await NotificationChannel.create(data);
|
||||
return notificationChannel;
|
||||
};
|
||||
|
||||
get = async (teamId: string, id: string) => {
|
||||
const channel = await NotificationChannel.findOne({ _id: id, teamId });
|
||||
if (!channel) {
|
||||
throw new ApiError("Notification channel not found", 404);
|
||||
}
|
||||
return channel;
|
||||
};
|
||||
|
||||
getAll = async (teamId: string) => {
|
||||
return NotificationChannel.find({ teamId });
|
||||
};
|
||||
|
||||
toggleActive = async (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string
|
||||
) => {
|
||||
const updatedChannel = await NotificationChannel.findOneAndUpdate(
|
||||
{ _id: id, teamId },
|
||||
[
|
||||
{
|
||||
$set: {
|
||||
isActive: { $not: "$isActive" },
|
||||
updatedBy: userContext.sub,
|
||||
updatedAt: new Date(),
|
||||
},
|
||||
},
|
||||
],
|
||||
{ new: true }
|
||||
);
|
||||
if (!updatedChannel) {
|
||||
throw new ApiError("Notification channel not found", 404);
|
||||
}
|
||||
return updatedChannel;
|
||||
};
|
||||
|
||||
update = async (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string,
|
||||
updateData: Partial<INotificationChannel>
|
||||
) => {
|
||||
const updatedChannel = await NotificationChannel.findOneAndUpdate(
|
||||
{ _id: id, teamId },
|
||||
{
|
||||
$set: {
|
||||
...updateData,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: userContext.sub,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedChannel) {
|
||||
throw new ApiError("Failed to update notification channel", 500);
|
||||
}
|
||||
|
||||
return updatedChannel;
|
||||
};
|
||||
|
||||
delete = async (teamId: string, id: string) => {
|
||||
const result = await NotificationChannel.deleteOne({ _id: id, teamId });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Notification channel not found", 404);
|
||||
}
|
||||
|
||||
await Monitor.updateMany(
|
||||
{ notificationChannels: id },
|
||||
{ $pull: { notificationChannels: id } }
|
||||
);
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default NotificationChannelService;
|
||||
@@ -0,0 +1,27 @@
|
||||
import { IJobQueue } from "@/services/infrastructure/JobQueue.js";
|
||||
|
||||
const SERVICE_NAME = "QueueService";
|
||||
|
||||
class QueueService {
|
||||
public SERVICE_NAME: string;
|
||||
private jobQueue: IJobQueue;
|
||||
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.jobQueue = jobQueue;
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
async getMetrics() {
|
||||
return await this.jobQueue.getMetrics();
|
||||
}
|
||||
|
||||
async getJobs() {
|
||||
return await this.jobQueue.getJobs();
|
||||
}
|
||||
|
||||
async flush() {
|
||||
return await this.jobQueue.flush();
|
||||
}
|
||||
}
|
||||
|
||||
export default QueueService;
|
||||
@@ -0,0 +1,54 @@
|
||||
import crypto from "node:crypto";
|
||||
import { RecoveryToken, IRecoveryToken } from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { Types } from "mongoose";
|
||||
const SERVICE_NAME = "RecoveryService";
|
||||
|
||||
export interface IRecoveryService {
|
||||
create: (userId: Types.ObjectId) => Promise<string>;
|
||||
get: (token: string) => Promise<IRecoveryToken>;
|
||||
delete: (id: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class RecoveryService implements IRecoveryService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
create = async (userId: Types.ObjectId) => {
|
||||
const token = crypto.randomBytes(32).toString("hex");
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
|
||||
await RecoveryToken.create({
|
||||
userId,
|
||||
tokenHash,
|
||||
});
|
||||
return token;
|
||||
};
|
||||
|
||||
get = async (token: string) => {
|
||||
const tokenHash = crypto.createHash("sha256").update(token).digest("hex");
|
||||
|
||||
const recoveryToken = await RecoveryToken.findOne({ tokenHash });
|
||||
if (!recoveryToken) {
|
||||
throw new ApiError("Recovery token not found", 404);
|
||||
}
|
||||
|
||||
if (recoveryToken.expiry.getTime() <= Date.now()) {
|
||||
throw new ApiError("Recovery token expired", 400);
|
||||
}
|
||||
|
||||
return recoveryToken;
|
||||
};
|
||||
|
||||
delete = async (id: string) => {
|
||||
const result = await RecoveryToken.deleteOne({ _id: id });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Recovery token not found", 404);
|
||||
}
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default RecoveryService;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { Role, IRole } from "@/db/models/index.js";
|
||||
import type { IJobQueue } from "../infrastructure/JobQueue.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "RoleService";
|
||||
export interface IRoleService {
|
||||
getAll: (orgId: string, type: string) => Promise<Partial<IRole[]>>;
|
||||
getTeam: (orgId: string, teamId: string) => Promise<Partial<IRole[]>>;
|
||||
get: (roleId: string) => Promise<IRole>;
|
||||
}
|
||||
|
||||
class RoleService implements IRoleService {
|
||||
public SERVICE_NAME: string;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
getAll = async (orgId: string, type: string) => {
|
||||
if (!type) {
|
||||
return await Role.find({ organizationId: orgId });
|
||||
}
|
||||
const roles = await Role.find({ organizationId: orgId, scope: type });
|
||||
return roles;
|
||||
};
|
||||
|
||||
getTeam = async (orgId: string, teamId: string) => {
|
||||
const roles = await Role.find({
|
||||
organizationId: orgId,
|
||||
teamId,
|
||||
scope: "team",
|
||||
});
|
||||
return roles;
|
||||
};
|
||||
|
||||
get = async (roleId: string) => {
|
||||
const role = await Role.findById(roleId);
|
||||
if (!role) {
|
||||
throw new ApiError("Role not found", 404);
|
||||
}
|
||||
return role;
|
||||
};
|
||||
}
|
||||
|
||||
export default RoleService;
|
||||
@@ -0,0 +1,136 @@
|
||||
import mongoose from "mongoose";
|
||||
|
||||
import {
|
||||
IUserContext,
|
||||
IStatusPage,
|
||||
StatusPage,
|
||||
Monitor,
|
||||
} from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "StatusPageService";
|
||||
|
||||
export interface IStatusPageService {
|
||||
create: (
|
||||
tokenizedUser: IUserContext,
|
||||
statusPage: IStatusPage
|
||||
) => Promise<IStatusPage>;
|
||||
getAll: (teamId: string) => Promise<IStatusPage[]>;
|
||||
get: (teamId: string, id: string) => Promise<IStatusPage>;
|
||||
getPublic: (url: string) => Promise<IStatusPage>;
|
||||
update: (
|
||||
teamId: string,
|
||||
tokenizedUser: IUserContext,
|
||||
id: string,
|
||||
updateData: Partial<IStatusPage>
|
||||
) => Promise<IStatusPage>;
|
||||
delete: (teamId: string, id: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class StatusPageService implements IStatusPageService {
|
||||
public SERVICE_NAME: string;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
create = async (userContext: IUserContext, statusPageData: IStatusPage) => {
|
||||
const monitorIds = statusPageData.monitors || [];
|
||||
const count = await Monitor.countDocuments({
|
||||
_id: { $in: monitorIds },
|
||||
teamId: userContext.currentTeamId,
|
||||
});
|
||||
|
||||
if (count !== monitorIds.length) {
|
||||
throw new ApiError(
|
||||
"One or more monitors do not belong to the current team",
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
const data: IStatusPage = {
|
||||
...statusPageData,
|
||||
orgId: new mongoose.Types.ObjectId(userContext.orgId),
|
||||
teamId: new mongoose.Types.ObjectId(userContext.currentTeamId),
|
||||
createdBy: new mongoose.Types.ObjectId(userContext.sub),
|
||||
updatedBy: new mongoose.Types.ObjectId(userContext.sub),
|
||||
};
|
||||
|
||||
const statusPage = await StatusPage.create(data);
|
||||
return statusPage;
|
||||
};
|
||||
|
||||
get = async (teamId: string, id: string) => {
|
||||
const statusPage = await StatusPage.findOne({ _id: id, teamId }).populate(
|
||||
"monitors"
|
||||
);
|
||||
if (!statusPage) {
|
||||
throw new ApiError("Status page not found", 404);
|
||||
}
|
||||
return statusPage;
|
||||
};
|
||||
|
||||
getPublic = async (url: string) => {
|
||||
const statusPage = await StatusPage.findOne({
|
||||
url,
|
||||
isPublished: true,
|
||||
}).populate("monitors");
|
||||
if (!statusPage) {
|
||||
throw new ApiError("Public status page not found", 404);
|
||||
}
|
||||
return statusPage;
|
||||
};
|
||||
|
||||
getAll = async (teamId: string) => {
|
||||
return StatusPage.find({ teamId });
|
||||
};
|
||||
|
||||
update = async (
|
||||
teamId: string,
|
||||
userContext: IUserContext,
|
||||
id: string,
|
||||
updateData: Partial<IStatusPage>
|
||||
) => {
|
||||
const monitorIds = updateData.monitors || [];
|
||||
const count = await Monitor.countDocuments({
|
||||
_id: { $in: monitorIds },
|
||||
teamId: userContext.currentTeamId,
|
||||
});
|
||||
|
||||
if (count !== monitorIds.length) {
|
||||
throw new ApiError(
|
||||
"One or more monitors do not belong to the current team",
|
||||
403
|
||||
);
|
||||
}
|
||||
|
||||
const updatedStatusPage = await StatusPage.findOneAndUpdate(
|
||||
{ _id: id, teamId },
|
||||
{
|
||||
$set: {
|
||||
...updateData,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: userContext.sub,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
|
||||
if (!updatedStatusPage) {
|
||||
throw new ApiError("Failed to update status page", 500);
|
||||
}
|
||||
|
||||
return updatedStatusPage;
|
||||
};
|
||||
|
||||
delete = async (teamId: string, id: string) => {
|
||||
const result = await StatusPage.deleteOne({ _id: id, teamId });
|
||||
if (!result.deletedCount) {
|
||||
throw new ApiError("Status page not found", 404);
|
||||
}
|
||||
|
||||
return result.deletedCount === 1;
|
||||
};
|
||||
}
|
||||
|
||||
export default StatusPageService;
|
||||
@@ -0,0 +1,148 @@
|
||||
import mongoose from "mongoose";
|
||||
import {
|
||||
ITeamMembership,
|
||||
TeamMembership,
|
||||
IUser,
|
||||
IRole,
|
||||
Role,
|
||||
Team,
|
||||
OrgMembership,
|
||||
IOrgMembership,
|
||||
} from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "TeamMemberService";
|
||||
export interface ITeamMemberService {
|
||||
create: (
|
||||
orgId: string,
|
||||
data: Partial<ITeamMembership>
|
||||
) => Promise<ITeamMembership>;
|
||||
getAll: (
|
||||
orgId: string,
|
||||
teamId: string | undefined,
|
||||
type: string
|
||||
) => Promise<Array<ITeamMembership | IOrgMembership>>;
|
||||
get: (orgId: string, teamMemberId: string) => Promise<ITeamMembership>;
|
||||
update: (
|
||||
orgId: string,
|
||||
teamMembershipId: string,
|
||||
roleId: string
|
||||
) => Promise<ITeamMembership>;
|
||||
delete: (orgId: string, teamMemberId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class TeamMemberService implements ITeamMemberService {
|
||||
public SERVICE_NAME: string;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
create = async (orgId: string, data: Partial<ITeamMembership>) => {
|
||||
const userId = data.userId?.toString();
|
||||
if (!userId) {
|
||||
throw new ApiError("User ID is required", 400);
|
||||
}
|
||||
|
||||
const existing = await TeamMembership.findOne({
|
||||
teamId: data.teamId,
|
||||
userId: data.userId,
|
||||
orgId: orgId,
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
throw new ApiError("User is already a member of the team", 400);
|
||||
}
|
||||
|
||||
const role = await Role.findOne({
|
||||
_id: data.roleId,
|
||||
organizationId: orgId,
|
||||
});
|
||||
if (!role) {
|
||||
throw new ApiError("Role not found", 404);
|
||||
}
|
||||
|
||||
const tm = await TeamMembership.create({
|
||||
...data,
|
||||
orgId: new mongoose.Types.ObjectId(orgId),
|
||||
});
|
||||
|
||||
return tm;
|
||||
};
|
||||
|
||||
getAll = async (orgId: string, teamId: string | undefined, type: string) => {
|
||||
if (type === "org") {
|
||||
return await OrgMembership.find({ orgId }).populate<IUser>(
|
||||
"userId",
|
||||
"firstName lastName email"
|
||||
);
|
||||
}
|
||||
|
||||
if (!teamId) {
|
||||
return await TeamMembership.find({ orgId })
|
||||
.populate<IUser>("userId", "firstName lastName email")
|
||||
.populate<IRole>("roleId", "name scope permissions");
|
||||
}
|
||||
|
||||
const team = await Team.findOne({ _id: teamId, orgId: orgId });
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found", 404);
|
||||
}
|
||||
|
||||
const teamMembers = await TeamMembership.find({ orgId, teamId })
|
||||
.populate<IUser>("userId", "firstName lastName email")
|
||||
.populate<IRole>("roleId", "name scope permissions");
|
||||
|
||||
return teamMembers;
|
||||
};
|
||||
|
||||
get = async (orgId: string, teamMemberId: string) => {
|
||||
const teamMember = await TeamMembership.findOne({
|
||||
_id: teamMemberId,
|
||||
orgId: orgId,
|
||||
})
|
||||
.populate<IUser>("userId", "firstName lastName email")
|
||||
.populate<IRole>("roleId", "name scope permissions");
|
||||
|
||||
if (!teamMember) {
|
||||
throw new ApiError("Team member not found", 404);
|
||||
}
|
||||
|
||||
return teamMember;
|
||||
};
|
||||
|
||||
update = async (orgId: string, teamMembershipId: string, roleId: string) => {
|
||||
const role = await Role.findOne({ _id: roleId, organizationId: orgId });
|
||||
if (!role) {
|
||||
throw new ApiError("Role not found", 404);
|
||||
}
|
||||
|
||||
const teamMembership = await TeamMembership.findOneAndUpdate(
|
||||
{ orgId: orgId, _id: teamMembershipId },
|
||||
{ roleId: roleId },
|
||||
{ new: true }
|
||||
)
|
||||
.populate<IUser>("userId", "firstName lastName email")
|
||||
.populate<IRole>("roleId", "name scope permissions");
|
||||
|
||||
if (!teamMembership) {
|
||||
throw new ApiError("Team membership not found", 404);
|
||||
}
|
||||
|
||||
return teamMembership;
|
||||
};
|
||||
|
||||
delete = async (orgId: string, teamMemberId: string) => {
|
||||
const tm = await TeamMembership.findOne({
|
||||
_id: teamMemberId,
|
||||
orgId: orgId,
|
||||
});
|
||||
if (!tm) {
|
||||
throw new ApiError("Team member not found", 404);
|
||||
}
|
||||
await TeamMembership.findOneAndDelete({ _id: teamMemberId, orgId: orgId });
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
export default TeamMemberService;
|
||||
@@ -0,0 +1,163 @@
|
||||
import mongoose from "mongoose";
|
||||
import {
|
||||
Monitor,
|
||||
Role,
|
||||
IRole,
|
||||
ITeam,
|
||||
Team,
|
||||
TeamMembership,
|
||||
OrgMembership,
|
||||
IUserContext,
|
||||
} from "@/db/models/index.js";
|
||||
import type { IJobQueue } from "../infrastructure/JobQueue.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { PERMISSIONS } from "@/services/business/AuthService.js";
|
||||
|
||||
const SERVICE_NAME = "TeamService";
|
||||
export interface ITeamService {
|
||||
create: (
|
||||
orgId: string,
|
||||
userId: string,
|
||||
teamData: ITeam,
|
||||
roleId: string
|
||||
) => Promise<boolean>;
|
||||
getOrg: (orgId: string) => Promise<Partial<ITeam[]>>;
|
||||
getJoined: (teamId: string, orgId: string) => Promise<Partial<ITeam[]>>;
|
||||
get: (teamId: string, orgId: string) => Promise<ITeam>;
|
||||
update: (
|
||||
user: IUserContext,
|
||||
teamId: string,
|
||||
teamData: Partial<ITeam>
|
||||
) => Promise<ITeam>;
|
||||
delete: (orgId: string, teamId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class TeamService implements ITeamService {
|
||||
public SERVICE_NAME: string;
|
||||
private jobQueue: IJobQueue;
|
||||
|
||||
constructor(jobQueue: IJobQueue) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.jobQueue = jobQueue;
|
||||
}
|
||||
|
||||
create = async (
|
||||
orgId: string,
|
||||
userId: string,
|
||||
teamData: ITeam,
|
||||
roleId: string
|
||||
) => {
|
||||
const created: Record<string, any> = {
|
||||
team: null,
|
||||
memberships: null,
|
||||
};
|
||||
|
||||
try {
|
||||
const teamLiteral: Partial<ITeam> = {
|
||||
name: teamData.name,
|
||||
description: teamData.description,
|
||||
orgId: new mongoose.Types.ObjectId(orgId),
|
||||
};
|
||||
|
||||
// Check for roles
|
||||
const roles = await Role.find({ organizationId: orgId });
|
||||
|
||||
if (!roles.some((r) => r._id.toString() === roleId)) {
|
||||
throw new Error("Role does not exist");
|
||||
}
|
||||
|
||||
const team = await Team.create(teamLiteral);
|
||||
created.teamId = team._id;
|
||||
const membership = await TeamMembership.create({
|
||||
teamId: team._id,
|
||||
orgId: new mongoose.Types.ObjectId(orgId),
|
||||
userId: new mongoose.Types.ObjectId(userId),
|
||||
roleId: new mongoose.Types.ObjectId(roleId),
|
||||
});
|
||||
created.teamMembershipId = membership._id;
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
await Team.deleteOne({ _id: created.teamId });
|
||||
await TeamMembership.deleteOne({ _id: created.teamMembershipId });
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
getOrg = async (orgId: string) => {
|
||||
const teams = await Team.find({ orgId }).select("_id name description");
|
||||
return teams;
|
||||
};
|
||||
|
||||
getJoined = async (orgId: string, userId: string) => {
|
||||
const teamMemberships = await TeamMembership.find({
|
||||
orgId,
|
||||
userId,
|
||||
}).select("teamId");
|
||||
|
||||
const teamIds = teamMemberships.map((tm) => tm.teamId);
|
||||
|
||||
const teams = await Team.find({ _id: { $in: teamIds }, orgId }).select(
|
||||
"_id name description"
|
||||
);
|
||||
return teams;
|
||||
};
|
||||
|
||||
get = async (teamId: string, orgId: string) => {
|
||||
const team = await Team.findOne({ _id: teamId, orgId });
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found");
|
||||
}
|
||||
return team;
|
||||
};
|
||||
|
||||
update = async (
|
||||
user: IUserContext,
|
||||
teamId: string,
|
||||
teamData: Partial<ITeam>
|
||||
) => {
|
||||
const updatedTeam = await Team.findOneAndUpdate(
|
||||
{ _id: teamId, orgId: user.orgId },
|
||||
{
|
||||
$set: {
|
||||
...teamData,
|
||||
updatedAt: new Date(),
|
||||
updatedBy: user.sub,
|
||||
},
|
||||
},
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updatedTeam) {
|
||||
throw new ApiError("Team not found");
|
||||
}
|
||||
|
||||
return updatedTeam;
|
||||
};
|
||||
|
||||
delete = async (orgId: string, teamId: string) => {
|
||||
const team = await Team.findOne({ _id: teamId, orgId }).lean();
|
||||
if (!team) {
|
||||
throw new ApiError("Team not found");
|
||||
}
|
||||
|
||||
if (team.isSystem) {
|
||||
throw new ApiError("Cannot delete your default team");
|
||||
}
|
||||
|
||||
const memberships = await TeamMembership.find({ teamId });
|
||||
for (const membership of memberships) {
|
||||
await membership.deleteOne();
|
||||
}
|
||||
|
||||
const monitors = await Monitor.find({ teamId });
|
||||
await Promise.all(
|
||||
monitors.map((monitor) => this.jobQueue.deleteJob(monitor))
|
||||
);
|
||||
|
||||
await Monitor.deleteMany({ teamId });
|
||||
await Team.deleteOne({ _id: teamId });
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
export default TeamService;
|
||||
@@ -0,0 +1,63 @@
|
||||
import { IUser, IUserProfile, User } from "@/db/models/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { hashPassword } from "@/utils/JWTUtils.js";
|
||||
import { object } from "joi";
|
||||
|
||||
const SERVICE_NAME = "UserService";
|
||||
export interface IUserService {
|
||||
get(email: string): Promise<IUser>;
|
||||
getAllUsers(): Promise<IUser[]>;
|
||||
}
|
||||
|
||||
class UserService implements IUserService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
async get(email: string): Promise<IUser> {
|
||||
const user = await User.findOne({ email });
|
||||
if (!user) {
|
||||
throw new ApiError("User not found", 404);
|
||||
}
|
||||
return user;
|
||||
}
|
||||
|
||||
async update(userId: string, data: Partial<IUserProfile>): Promise<IUser> {
|
||||
let passwordHash = null;
|
||||
|
||||
const updateData: Record<string, any> = {};
|
||||
if (data.firstName !== undefined) updateData.firstName = data.firstName;
|
||||
if (data.lastName !== undefined) updateData.lastName = data.lastName;
|
||||
if (data.password !== undefined) {
|
||||
updateData.passwordHash = await hashPassword(data.password);
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 0) {
|
||||
throw new ApiError("No valid fields to update", 400);
|
||||
}
|
||||
|
||||
const updatedUser = await User.findOneAndUpdate(
|
||||
{
|
||||
_id: userId,
|
||||
},
|
||||
{
|
||||
$set: updateData,
|
||||
},
|
||||
{
|
||||
new: true,
|
||||
}
|
||||
);
|
||||
|
||||
if (!updatedUser) {
|
||||
throw new ApiError("User not found", 404);
|
||||
}
|
||||
return updatedUser;
|
||||
}
|
||||
|
||||
async getAllUsers(): Promise<IUser[]> {
|
||||
return await User.find();
|
||||
}
|
||||
}
|
||||
|
||||
export default UserService;
|
||||
@@ -0,0 +1,26 @@
|
||||
export { default as AuthService } from "@/services/business/AuthService.js";
|
||||
export { default as CheckService } from "@/services/business/CheckService.js";
|
||||
export { default as InviteService } from "@/services/business/InviteService.js";
|
||||
export { default as MaintenanceService } from "@/services/business/MaintenanceService.js";
|
||||
export { default as MonitorService } from "@/services/business/MonitorService.js";
|
||||
export { default as MonitorStatsService } from "@/services/business/MonitorStatsService.js";
|
||||
export { default as NotificationChannelService } from "@/services/business/NotificationChannelService.js";
|
||||
export { default as QueueService } from "@/services/business/QueueService.js";
|
||||
export { default as UserService } from "@/services/business/UserService.js";
|
||||
export { default as TeamService } from "@/services/business/TeamService.js";
|
||||
export { default as RoleService } from "@/services/business/RoleService.js";
|
||||
export { default as TeamMemberService } from "@/services/business/TeamMemberServices.js";
|
||||
export { default as StatusPageService } from "@/services/business/StatusPageService.js";
|
||||
export { default as DiagnosticService } from "@/services/business/DiagnosticService.js";
|
||||
export { default as RecoveryService } from "@/services/business/RecoveryService.js";
|
||||
export { default as IncidentService } from "@/services/business/IncidentService.js";
|
||||
|
||||
export { default as NetworkService } from "@/services/infrastructure/NetworkService.js";
|
||||
export { default as NotificationService } from "@/services/infrastructure/NotificationService.js";
|
||||
export { default as StatusService } from "@/services/infrastructure/StatusService.js";
|
||||
export { default as JobQueue } from "@/services/infrastructure/JobQueue.js";
|
||||
export { default as JobGenerator } from "@/services/infrastructure/JobGenerator.js";
|
||||
|
||||
export { default as ServiceRegistry } from "@/services/system/ServiceRegistry.js";
|
||||
|
||||
export * from "@/services/infrastructure/NotificationServices/index.js";
|
||||
@@ -0,0 +1,108 @@
|
||||
import { IMonitor } from "@/db/models/index.js";
|
||||
import { INetworkService } from "./NetworkService.js";
|
||||
import { ICheckService } from "../business/CheckService.js";
|
||||
import { IMonitorStatsService } from "../business/MonitorStatsService.js";
|
||||
import { IStatusService } from "./StatusService.js";
|
||||
import { INotificationService } from "./NotificationService.js";
|
||||
import { IMaintenanceService } from "../business/MaintenanceService.js";
|
||||
import { IIncidentService } from "../business/IncidentService.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
|
||||
const SERVICE_NAME = "JobGenerator";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
export interface IJobGenerator {
|
||||
generateJob: () => (Monitor: IMonitor) => Promise<void>;
|
||||
generateCleanupJob: () => () => Promise<void>;
|
||||
}
|
||||
|
||||
class JobGenerator implements IJobGenerator {
|
||||
public SERVICE_NAME: string;
|
||||
private networkService: INetworkService;
|
||||
private checkService: ICheckService;
|
||||
private monitorStatsService: IMonitorStatsService;
|
||||
private statusService: IStatusService;
|
||||
private notificationService: INotificationService;
|
||||
private maintenanceService: IMaintenanceService;
|
||||
private incidentService: IIncidentService;
|
||||
|
||||
constructor(
|
||||
networkService: INetworkService,
|
||||
checkService: ICheckService,
|
||||
monitorStatsService: IMonitorStatsService,
|
||||
statusService: IStatusService,
|
||||
notificationService: INotificationService,
|
||||
incidentService: IIncidentService,
|
||||
maintenanceService: IMaintenanceService
|
||||
) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.networkService = networkService;
|
||||
this.checkService = checkService;
|
||||
this.monitorStatsService = monitorStatsService;
|
||||
this.statusService = statusService;
|
||||
this.notificationService = notificationService;
|
||||
this.incidentService = incidentService;
|
||||
this.maintenanceService = maintenanceService;
|
||||
}
|
||||
|
||||
generateJob = () => {
|
||||
return async (monitor: IMonitor) => {
|
||||
try {
|
||||
const monitorId = monitor._id.toString();
|
||||
if (!monitorId) {
|
||||
throw new ApiError("No monitorID for creating job", 400);
|
||||
}
|
||||
|
||||
// Check for active maintenance window, if found, skip the check
|
||||
const isInMaintenance = await this.maintenanceService.isInMaintenance(
|
||||
monitorId
|
||||
);
|
||||
if (isInMaintenance) {
|
||||
return;
|
||||
}
|
||||
|
||||
const status = await this.networkService.requestStatus(monitor);
|
||||
const check = await this.checkService.buildCheck(status, monitor.type);
|
||||
await check.save();
|
||||
const [updatedMonitor, statusChanged] =
|
||||
await this.statusService.updateMonitorStatus(monitor, status);
|
||||
|
||||
if (statusChanged) {
|
||||
const incident = await this.incidentService.handleStatusChange(
|
||||
updatedMonitor,
|
||||
check
|
||||
);
|
||||
|
||||
// Best effort, don't wait, don't fail
|
||||
if (incident) {
|
||||
this.notificationService
|
||||
.handleNotifications(updatedMonitor, incident)
|
||||
.catch((error) => {
|
||||
logger.warn(error);
|
||||
});
|
||||
}
|
||||
}
|
||||
await this.statusService.updateMonitorStats(
|
||||
updatedMonitor,
|
||||
status,
|
||||
statusChanged
|
||||
);
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
generateCleanupJob = () => {
|
||||
return async () => {
|
||||
try {
|
||||
await this.checkService.cleanupOrphanedChecks();
|
||||
await this.monitorStatsService.cleanupOrphanedMonitorStats();
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export default JobGenerator;
|
||||
@@ -0,0 +1,252 @@
|
||||
import { IJob } from "super-simple-scheduler/dist/job/job.js";
|
||||
import { Monitor, IMonitor } from "@/db/models/index.js";
|
||||
import Scheduler from "super-simple-scheduler";
|
||||
import { IJobGenerator } from "./JobGenerator.js";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
|
||||
const SERVICE_NAME = "JobQueue";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
export interface IJobMetrics {
|
||||
jobs: number;
|
||||
activeJobs: number;
|
||||
failingJobs: number;
|
||||
jobsWithFailures: Array<{
|
||||
monitorId: string | number;
|
||||
monitorUrl: string | null;
|
||||
monitorType: string | null;
|
||||
failedAt: number | null;
|
||||
failCount: number | null;
|
||||
failReason: string | null;
|
||||
}>;
|
||||
totalRuns: number;
|
||||
totalFailures: number;
|
||||
}
|
||||
|
||||
export interface IJobData extends IJob {
|
||||
lastRunTook: number | null;
|
||||
}
|
||||
|
||||
export interface IJobQueue {
|
||||
init: () => Promise<boolean>;
|
||||
addJob: (monitor: IMonitor) => Promise<boolean>;
|
||||
pauseJob: (monitor: IMonitor) => Promise<boolean>;
|
||||
resumeJob: (monitor: IMonitor) => Promise<boolean>;
|
||||
updateJob: (monitor: IMonitor) => Promise<boolean>;
|
||||
deleteJob: (monitor: IMonitor) => Promise<boolean>;
|
||||
getMetrics: () => Promise<IJobMetrics | null>;
|
||||
getJobs: () => Promise<IJobData[] | null>;
|
||||
flush: () => Promise<boolean>;
|
||||
shutdown: () => Promise<boolean>;
|
||||
}
|
||||
|
||||
export default class JobQueue implements IJobQueue {
|
||||
public SERVICE_NAME: string;
|
||||
private scheduler: Scheduler;
|
||||
private static instance: JobQueue | null = null;
|
||||
private jobGenerator: any;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.scheduler = new Scheduler({
|
||||
logLevel: "debug",
|
||||
});
|
||||
}
|
||||
|
||||
static async create(jobGenerator: IJobGenerator) {
|
||||
if (!JobQueue.instance) {
|
||||
const instance = new JobQueue();
|
||||
instance.jobGenerator = jobGenerator;
|
||||
await instance.init();
|
||||
JobQueue.instance = instance;
|
||||
}
|
||||
return JobQueue.instance;
|
||||
}
|
||||
|
||||
static getInstance(): JobQueue | null {
|
||||
return JobQueue.instance;
|
||||
}
|
||||
|
||||
init = async () => {
|
||||
try {
|
||||
this.scheduler.start();
|
||||
// Add template and jobs
|
||||
this.scheduler.addTemplate(
|
||||
"monitor-job",
|
||||
this.jobGenerator.generateJob()
|
||||
);
|
||||
|
||||
// Add a cleanup job
|
||||
this.scheduler.addTemplate(
|
||||
"cleanup-job",
|
||||
this.jobGenerator.generateCleanupJob()
|
||||
);
|
||||
await this.scheduler.addJob({
|
||||
id: "cleanup-orphaned-checks",
|
||||
template: "cleanup-job",
|
||||
repeat: 24 * 60 * 60 * 1000, // 24 hours
|
||||
active: true,
|
||||
});
|
||||
|
||||
const monitors = await Monitor.find();
|
||||
for (const monitor of monitors) {
|
||||
const randomOffset = 1000 + Math.random() * 1000;
|
||||
|
||||
setTimeout(async () => {
|
||||
const exists = await Monitor.exists({ _id: monitor._id });
|
||||
if (exists) {
|
||||
this.addJob(monitor);
|
||||
}
|
||||
}, randomOffset);
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
addJob = async (monitor: IMonitor) => {
|
||||
try {
|
||||
return await this.scheduler?.addJob({
|
||||
id: monitor._id.toString(),
|
||||
template: "monitor-job",
|
||||
repeat: monitor.interval,
|
||||
active: monitor.isActive,
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
pauseJob = async (monitor: IMonitor) => {
|
||||
try {
|
||||
return await this.scheduler?.pauseJob(monitor._id.toString());
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
resumeJob = async (monitor: IMonitor) => {
|
||||
try {
|
||||
return await this.scheduler.resumeJob(monitor._id.toString());
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
updateJob = async (monitor: IMonitor) => {
|
||||
try {
|
||||
return await this.scheduler.updateJob(monitor._id.toString(), {
|
||||
repeat: monitor.interval,
|
||||
data: monitor,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
deleteJob = async (monitor: IMonitor) => {
|
||||
try {
|
||||
this.scheduler?.removeJob(monitor._id.toString());
|
||||
return true;
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
getMetrics = async (): Promise<IJobMetrics | null> => {
|
||||
try {
|
||||
const jobs = await this.scheduler.getJobs();
|
||||
const metrics: IJobMetrics = jobs.reduce<IJobMetrics>(
|
||||
(acc, job) => {
|
||||
if (!job.data) return acc;
|
||||
|
||||
acc.totalRuns += job.runCount || 0;
|
||||
acc.totalFailures += job.failCount || 0;
|
||||
acc.jobs++;
|
||||
|
||||
// Check if job is currently failing (has recent failures)
|
||||
const hasFailures = job.failCount && job.failCount > 0;
|
||||
const isCurrentlyFailing =
|
||||
hasFailures &&
|
||||
job.lastFailedAt &&
|
||||
(!job.lastRunAt || job.lastFailedAt > job.lastRunAt);
|
||||
|
||||
if (isCurrentlyFailing) {
|
||||
acc.failingJobs++;
|
||||
}
|
||||
|
||||
if (job.lockedAt) {
|
||||
acc.activeJobs++;
|
||||
}
|
||||
|
||||
if (hasFailures) {
|
||||
acc.jobsWithFailures.push({
|
||||
monitorId: job.id,
|
||||
monitorUrl: job.data?.url || null,
|
||||
monitorType: job.data?.type || null,
|
||||
failedAt: job.lastFailedAt || null,
|
||||
failCount: job.failCount || null,
|
||||
failReason: job.lastFailReason || null,
|
||||
});
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{
|
||||
jobs: 0,
|
||||
activeJobs: 0,
|
||||
failingJobs: 0,
|
||||
jobsWithFailures: [],
|
||||
totalRuns: 0,
|
||||
totalFailures: 0,
|
||||
}
|
||||
);
|
||||
return metrics;
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
getJobs = async (): Promise<IJobData[] | null> => {
|
||||
try {
|
||||
const jobs = await this.scheduler.getJobs();
|
||||
return jobs.map((job) => {
|
||||
return {
|
||||
...job,
|
||||
lastRunTook:
|
||||
job.lockedAt || !job.lastFinishedAt || !job.lastRunAt
|
||||
? null
|
||||
: job.lastFinishedAt - job.lastRunAt,
|
||||
};
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
flush = async () => {
|
||||
try {
|
||||
return await this.scheduler.flushJobs();
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
shutdown = async () => {
|
||||
try {
|
||||
return await this.scheduler.stop();
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { Got, HTTPError } from "got";
|
||||
import got from "got";
|
||||
import ping from "ping";
|
||||
import { IMonitor } from "@/db/models/index.js";
|
||||
import { GotTimings } from "@/db/models/checks/Check.js";
|
||||
import type { Response } from "got";
|
||||
import type {
|
||||
ISystemInfo,
|
||||
ICaptureInfo,
|
||||
ILighthouseResult,
|
||||
} from "@/db/models/index.js";
|
||||
import { MonitorType, MonitorStatus } from "@/db/models/monitors/Monitor.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { config } from "@/config/index.js";
|
||||
import CacheableLookup from "cacheable-lookup";
|
||||
import http from "http";
|
||||
import https from "https";
|
||||
|
||||
const SERVICE_NAME = "NetworkService";
|
||||
export interface INetworkService {
|
||||
requestHttp: (monitor: IMonitor) => Promise<StatusResponse>;
|
||||
requestInfrastructure: (monitor: IMonitor) => Promise<StatusResponse>;
|
||||
requestStatus: (monitor: IMonitor) => Promise<StatusResponse>;
|
||||
requestPagespeed: (monitor: IMonitor) => Promise<StatusResponse>;
|
||||
requestPing: (monitor: IMonitor) => Promise<StatusResponse>;
|
||||
}
|
||||
|
||||
export interface ICapturePayload {
|
||||
data: ISystemInfo;
|
||||
capture: ICaptureInfo;
|
||||
}
|
||||
|
||||
export interface ILighthousePayload {
|
||||
lighthouseResult: ILighthouseResult;
|
||||
}
|
||||
|
||||
export interface StatusResponse<TPayload = unknown> {
|
||||
monitorId: string;
|
||||
teamId: string;
|
||||
type: MonitorType;
|
||||
code?: number;
|
||||
status: MonitorStatus;
|
||||
message: string;
|
||||
responseTime: number;
|
||||
timings?: GotTimings;
|
||||
payload?: TPayload;
|
||||
}
|
||||
|
||||
class NetworkService implements INetworkService {
|
||||
public SERVICE_NAME = SERVICE_NAME;
|
||||
private got: Got;
|
||||
private NETWORK_ERROR: number;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.NETWORK_ERROR = 5000;
|
||||
|
||||
const cacheable = new CacheableLookup();
|
||||
|
||||
this.got = got.extend({
|
||||
dnsCache: cacheable,
|
||||
timeout: {
|
||||
request: 30000,
|
||||
},
|
||||
retry: { limit: 1 },
|
||||
});
|
||||
}
|
||||
|
||||
private buildStatusResponse = <T>(
|
||||
monitor: IMonitor,
|
||||
response: Response<T> | null,
|
||||
error: any | null
|
||||
): StatusResponse<T> => {
|
||||
if (error) {
|
||||
const statusResponse: StatusResponse<T> = {
|
||||
monitorId: monitor._id.toString(),
|
||||
teamId: monitor.teamId.toString(),
|
||||
type: monitor.type,
|
||||
status: "down" as MonitorStatus,
|
||||
code: this.NETWORK_ERROR,
|
||||
message: error.message || "Network error",
|
||||
responseTime: 0,
|
||||
timings: { phases: {} } as GotTimings,
|
||||
};
|
||||
if (error instanceof HTTPError) {
|
||||
statusResponse.code = error?.response?.statusCode || this.NETWORK_ERROR;
|
||||
statusResponse.message = error.message || "HTTP error";
|
||||
statusResponse.responseTime = error.timings?.phases?.total || 0;
|
||||
statusResponse.timings = error.timings;
|
||||
}
|
||||
return statusResponse;
|
||||
}
|
||||
|
||||
const statusResponse: StatusResponse<T> = {
|
||||
monitorId: monitor._id.toString(),
|
||||
teamId: monitor.teamId.toString(),
|
||||
type: monitor.type,
|
||||
code: response?.statusCode || this.NETWORK_ERROR,
|
||||
status: response?.ok === true ? "up" : "down",
|
||||
message: response?.statusMessage || "",
|
||||
responseTime: response?.timings?.phases?.total || 0,
|
||||
timings: response?.timings || ({ phases: {} } as GotTimings),
|
||||
};
|
||||
|
||||
return statusResponse;
|
||||
};
|
||||
|
||||
requestHttp = async (monitor: IMonitor) => {
|
||||
try {
|
||||
const url = monitor.url;
|
||||
if (!url) {
|
||||
throw new Error("No URL provided");
|
||||
}
|
||||
|
||||
try {
|
||||
const response: Response = await this.got(url);
|
||||
return this.buildStatusResponse(monitor, response, null);
|
||||
} catch (error) {
|
||||
return this.buildStatusResponse(monitor, null, error);
|
||||
}
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
requestInfrastructure = async (monitor: IMonitor) => {
|
||||
const url = monitor.url;
|
||||
if (!url) {
|
||||
throw new Error("No URL provided");
|
||||
}
|
||||
const secret = monitor.secret;
|
||||
if (!secret) {
|
||||
throw new Error("No secret provided for infrastructure monitor");
|
||||
}
|
||||
|
||||
let statusResponse: StatusResponse<ICapturePayload>;
|
||||
try {
|
||||
const response: Response<ICapturePayload> | null = await this.got(url, {
|
||||
headers: { Authorization: `Bearer ${secret}` },
|
||||
responseType: "json",
|
||||
});
|
||||
|
||||
statusResponse = this.buildStatusResponse(monitor, response, null);
|
||||
if (!response?.body) {
|
||||
throw new ApiError(
|
||||
"No payload received from infrastructure monitor",
|
||||
500
|
||||
);
|
||||
}
|
||||
statusResponse.payload = response?.body;
|
||||
return statusResponse;
|
||||
} catch (error) {
|
||||
statusResponse = this.buildStatusResponse(monitor, null, error);
|
||||
}
|
||||
return statusResponse;
|
||||
};
|
||||
|
||||
requestPagespeed = async (monitor: IMonitor) => {
|
||||
const apiKey = config.PAGESPEED_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error("No API key provided for pagespeed monitor");
|
||||
}
|
||||
const url = monitor.url;
|
||||
if (!url) {
|
||||
throw new Error("No URL provided");
|
||||
}
|
||||
|
||||
let statusResponse: StatusResponse<ILighthousePayload>;
|
||||
|
||||
try {
|
||||
const response: Response = await this.got(url);
|
||||
statusResponse = this.buildStatusResponse(
|
||||
monitor,
|
||||
response,
|
||||
null
|
||||
) as StatusResponse<ILighthousePayload>;
|
||||
} catch (error) {
|
||||
statusResponse = this.buildStatusResponse(monitor, null, error);
|
||||
}
|
||||
|
||||
const pagespeedUrl = `https://pagespeedonline.googleapis.com/pagespeedonline/v5/runPagespeed?url=${url}&category=seo&category=accessibility&category=best-practices&category=performance&key=${apiKey}`;
|
||||
const pagespeedResponse = await this.got<ILighthousePayload>(pagespeedUrl, {
|
||||
responseType: "json",
|
||||
});
|
||||
const payload = pagespeedResponse.body;
|
||||
if (payload) {
|
||||
statusResponse.payload = payload;
|
||||
return statusResponse;
|
||||
} else {
|
||||
throw new ApiError("No payload received from pagespeed monitor", 500);
|
||||
}
|
||||
};
|
||||
|
||||
requestPing = async (monitor: IMonitor) => {
|
||||
const response = await ping.promise.probe(monitor.url);
|
||||
const status = response?.alive === true ? "up" : "down";
|
||||
|
||||
const rawTime =
|
||||
typeof response?.time === "string"
|
||||
? parseFloat(response.time)
|
||||
: Number(response?.time);
|
||||
const responseTime = Number.isFinite(rawTime) ? rawTime : 0;
|
||||
|
||||
return {
|
||||
monitorId: monitor._id.toString(),
|
||||
teamId: monitor.teamId.toString(),
|
||||
type: monitor.type,
|
||||
status: status as MonitorStatus,
|
||||
message: "Ping successful",
|
||||
responseTime,
|
||||
timings: { phases: {} } as GotTimings,
|
||||
};
|
||||
};
|
||||
|
||||
requestStatus = async (monitor: IMonitor) => {
|
||||
switch (monitor?.type) {
|
||||
case "http":
|
||||
return await this.requestHttp(monitor); // uses GOT
|
||||
case "https":
|
||||
return await this.requestHttp(monitor); // uses GOT
|
||||
case "infrastructure":
|
||||
return await this.requestInfrastructure(monitor); // uses GOT
|
||||
case "pagespeed":
|
||||
return await this.requestPagespeed(monitor); // uses GOT
|
||||
case "ping":
|
||||
return await this.requestPing(monitor); // uses PING
|
||||
default:
|
||||
throw new Error("Not implemented");
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default NetworkService;
|
||||
@@ -0,0 +1,186 @@
|
||||
import UserService from "../business/UserService.js";
|
||||
import {
|
||||
IMonitor,
|
||||
Monitor,
|
||||
NotificationChannel,
|
||||
INotificationChannel,
|
||||
IIncident,
|
||||
} from "@/db/models/index.js";
|
||||
import {
|
||||
EmailService,
|
||||
SlackService,
|
||||
DiscordService,
|
||||
WebhookService,
|
||||
} from "./NotificationServices/index.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
|
||||
const SERVICE_NAME = "NotificationService";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
|
||||
export interface ITestResult {
|
||||
channelName: string;
|
||||
channelUrl: string;
|
||||
channelType: string;
|
||||
sent: boolean;
|
||||
}
|
||||
export interface INotificationService {
|
||||
handleNotifications: (
|
||||
monitor: IMonitor,
|
||||
incident: IIncident
|
||||
) => Promise<void>;
|
||||
testNotificationChannels: (
|
||||
monitorId: string,
|
||||
teamId: string
|
||||
) => Promise<ITestResult[]>;
|
||||
testNotificationChannel: (
|
||||
notificationChannel: INotificationChannel
|
||||
) => Promise<Boolean>;
|
||||
}
|
||||
|
||||
class NotificationService implements INotificationService {
|
||||
public SERVICE_NAME: string;
|
||||
private emailService: EmailService;
|
||||
private slackService: SlackService;
|
||||
private discordService: DiscordService;
|
||||
private webhookService: WebhookService;
|
||||
private userService: UserService;
|
||||
|
||||
constructor(userService: UserService) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.userService = userService;
|
||||
this.emailService = new EmailService(userService);
|
||||
this.slackService = new SlackService();
|
||||
this.discordService = new DiscordService();
|
||||
this.webhookService = new WebhookService();
|
||||
}
|
||||
|
||||
handleNotifications = async (monitor: IMonitor, incident: IIncident) => {
|
||||
const notificationIds = monitor.notificationChannels || [];
|
||||
|
||||
if (notificationIds.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const notificationChannels = await NotificationChannel.find({
|
||||
_id: { $in: notificationIds },
|
||||
});
|
||||
|
||||
for (const channel of notificationChannels) {
|
||||
// Implement sending logic based on channel.type and channel.config
|
||||
let service;
|
||||
switch (channel.type) {
|
||||
case "email":
|
||||
await this.emailService.sendMessage(
|
||||
this.emailService.buildAlert(monitor, incident),
|
||||
channel
|
||||
);
|
||||
break;
|
||||
case "slack":
|
||||
await this.slackService.sendMessage(
|
||||
this.slackService.buildAlert(monitor, incident),
|
||||
channel
|
||||
);
|
||||
break;
|
||||
case "discord":
|
||||
await this.discordService.sendMessage(
|
||||
this.discordService.buildAlert(monitor, incident),
|
||||
channel
|
||||
);
|
||||
break;
|
||||
case "webhook":
|
||||
await this.webhookService.sendMessage(
|
||||
this.webhookService.buildAlert(monitor, incident),
|
||||
channel
|
||||
);
|
||||
break;
|
||||
default:
|
||||
logger.warn(`Unknown notification channel type: ${channel.type}`);
|
||||
}
|
||||
}
|
||||
return;
|
||||
};
|
||||
|
||||
private testNotification = async (
|
||||
channel: INotificationChannel,
|
||||
results: any[]
|
||||
) => {
|
||||
switch (channel.type) {
|
||||
case "email":
|
||||
const sentEmail = await this.emailService.testMessage(channel);
|
||||
results.push({
|
||||
channelName: channel.name,
|
||||
channelType: channel.type,
|
||||
channelUrl: channel.config?.emailAddress || "N/A",
|
||||
sent: sentEmail,
|
||||
});
|
||||
break;
|
||||
case "slack":
|
||||
const sentSlack = await this.slackService.testMessage(channel);
|
||||
results.push({
|
||||
channelName: channel.name,
|
||||
channelType: channel.type,
|
||||
channelUrl: channel.config?.url || "N/A",
|
||||
sent: sentSlack,
|
||||
});
|
||||
break;
|
||||
case "discord":
|
||||
const sentDiscord = await this.discordService.testMessage(channel);
|
||||
results.push({
|
||||
channelName: channel.name,
|
||||
channelType: channel.type,
|
||||
channelUrl: channel.config?.url || "N/A",
|
||||
sent: sentDiscord,
|
||||
});
|
||||
break;
|
||||
case "webhook":
|
||||
const sentWebhook = await this.webhookService.testMessage(channel);
|
||||
results.push({
|
||||
channelName: channel.name,
|
||||
channelType: channel.type,
|
||||
channelUrl: channel.config?.url || "N/A",
|
||||
sent: sentWebhook,
|
||||
});
|
||||
break;
|
||||
default:
|
||||
logger.warn(`Unknown notification channel type: ${channel.type}`);
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
testNotificationChannels = async (monitorId: string, teamId: string) => {
|
||||
const monitor = await Monitor.findOne({
|
||||
_id: monitorId,
|
||||
teamId: teamId,
|
||||
});
|
||||
|
||||
if (!monitor) {
|
||||
throw new ApiError("Monitor not found", 404);
|
||||
}
|
||||
|
||||
const notificationIds = monitor.notificationChannels || [];
|
||||
const notificationChannels = await NotificationChannel.find({
|
||||
_id: { $in: notificationIds },
|
||||
}).lean();
|
||||
|
||||
const results: any[] = [];
|
||||
|
||||
for (const channel of notificationChannels) {
|
||||
await this.testNotification(channel, results);
|
||||
}
|
||||
return results;
|
||||
};
|
||||
|
||||
testNotificationChannel = async (
|
||||
notificationChannel: INotificationChannel
|
||||
) => {
|
||||
const result: any[] = [];
|
||||
await this.testNotification(notificationChannel, result);
|
||||
if (result.length > 0) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
export default NotificationService;
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
IMonitor,
|
||||
INotificationChannel,
|
||||
IIncident,
|
||||
} from "@/db/models/index.js";
|
||||
import { IAlert, IMessageService } from "./IMessageService.js";
|
||||
import got from "got";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
const SERVICE_NAME = "DiscordService";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
class DiscordService implements IMessageService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
private toDiscordEmbeds = (alert: IAlert) => {
|
||||
return {
|
||||
color: alert.status === "up" ? 65280 : 16711680,
|
||||
title: `Monitor name: ${alert.name}`,
|
||||
description: `Status: **${alert.status}**`,
|
||||
fields: [
|
||||
{
|
||||
name: "Url",
|
||||
value: alert.url,
|
||||
},
|
||||
{
|
||||
name: "Checked at",
|
||||
value: alert.checkTime ? alert.checkTime.toISOString() : "N/A",
|
||||
},
|
||||
{
|
||||
name: "Resolved",
|
||||
value: alert.resolved ? "Yes" : "No",
|
||||
},
|
||||
{
|
||||
name: "Resolution type",
|
||||
value: alert.resolutionType || "N/A",
|
||||
},
|
||||
{
|
||||
name: "Resolution note",
|
||||
value: alert.resolutionNote || "N/A",
|
||||
},
|
||||
{ name: "Alert time", value: alert.alertTime.toISOString() },
|
||||
...(alert.details
|
||||
? Object.entries(alert.details).map(([key, value]) => ({
|
||||
name: key,
|
||||
value,
|
||||
}))
|
||||
: []),
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
buildAlert = (monitor: IMonitor, incident: IIncident) => {
|
||||
const name = monitor?.name || "Unnamed monitor";
|
||||
const monitorStatus = monitor?.status || "unknown status";
|
||||
const url = monitor?.url || "no URL";
|
||||
const checkTime = monitor?.lastCheckedAt || null;
|
||||
const alertTime = new Date();
|
||||
return {
|
||||
name,
|
||||
url,
|
||||
status: monitorStatus,
|
||||
resolved: incident.resolved,
|
||||
resolutionType: incident.resolutionType,
|
||||
resolvedBy: incident.resolvedBy?.toString(),
|
||||
resolutionNote: incident.resolutionNote,
|
||||
checkTime,
|
||||
alertTime,
|
||||
};
|
||||
};
|
||||
|
||||
sendMessage = async (alert: IAlert, channel: INotificationChannel) => {
|
||||
const notificationUrl = channel?.config?.url;
|
||||
if (!notificationUrl) {
|
||||
throw new ApiError("Webhook URL not configured", 400);
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
content: "Status Alert",
|
||||
embeds: [this.toDiscordEmbeds(alert)],
|
||||
};
|
||||
await got.post(notificationUrl, { json: payload });
|
||||
} catch (error) {
|
||||
logger.warn("Failed to send Discord message", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
testMessage = async (channel: INotificationChannel) => {
|
||||
return this.sendMessage(
|
||||
{
|
||||
name: "This is a test",
|
||||
url: "Test URL",
|
||||
status: "Test status",
|
||||
checkTime: new Date(),
|
||||
alertTime: new Date(),
|
||||
resolved: true,
|
||||
resolutionType: "auto",
|
||||
resolvedBy: "system",
|
||||
resolutionNote: "This is a test message",
|
||||
},
|
||||
channel
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export default DiscordService;
|
||||
@@ -0,0 +1,113 @@
|
||||
import {
|
||||
IMonitor,
|
||||
INotificationChannel,
|
||||
IIncident,
|
||||
} from "@/db/models/index.js";
|
||||
import { IMessageService, IAlert } from "./IMessageService.js";
|
||||
import nodemailer, { Transporter } from "nodemailer";
|
||||
import { config } from "@/config/index.js";
|
||||
import UserService from "../../business/UserService.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "EmailService";
|
||||
|
||||
export interface IEmailService extends IMessageService {
|
||||
sendGeneric: (
|
||||
to: string,
|
||||
subject: string,
|
||||
content: string
|
||||
) => Promise<boolean>;
|
||||
}
|
||||
|
||||
class EmailService implements IEmailService {
|
||||
public SERVICE_NAME = SERVICE_NAME;
|
||||
private transporter: Transporter;
|
||||
private userService: UserService;
|
||||
|
||||
constructor(userService: UserService) {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.userService = userService;
|
||||
this.transporter = nodemailer.createTransport({
|
||||
host: config.SMTP_HOST,
|
||||
port: config.SMTP_PORT,
|
||||
secure: config.SMTP_PORT === 465,
|
||||
auth: {
|
||||
user: config.SMTP_USER,
|
||||
pass: config.SMTP_PASS,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
buildAlert = (monitor: IMonitor, incident: IIncident) => {
|
||||
const name = monitor?.name || "Unnamed monitor";
|
||||
const monitorStatus = monitor?.status || "unknown status";
|
||||
const url = monitor?.url || "no URL";
|
||||
const checkTime = monitor?.lastCheckedAt || null;
|
||||
const alertTime = new Date();
|
||||
return {
|
||||
name,
|
||||
url,
|
||||
status: monitorStatus,
|
||||
resolved: incident.resolved,
|
||||
resolutionType: incident.resolutionType,
|
||||
resolvedBy: incident.resolvedBy?.toString(),
|
||||
resolutionNote: incident.resolutionNote,
|
||||
checkTime,
|
||||
alertTime,
|
||||
};
|
||||
};
|
||||
|
||||
sendMessage = async (alert: IAlert, channel: INotificationChannel) => {
|
||||
try {
|
||||
const users = await this.userService.getAllUsers();
|
||||
const emails = users.map((u) => u.email).join(",");
|
||||
|
||||
if (!emails || emails.length === 0) {
|
||||
throw new ApiError("No user emails found", 500);
|
||||
}
|
||||
|
||||
await this.transporter.sendMail({
|
||||
from: `"Checkmate" <${config.SMTP_USER}>`,
|
||||
to: emails,
|
||||
subject: "Monitor Alert",
|
||||
text: JSON.stringify(alert, null, 2),
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
testMessage = async (channel: INotificationChannel) => {
|
||||
return this.sendMessage(
|
||||
{
|
||||
name: "This is a test",
|
||||
url: "Test URL",
|
||||
status: "Test status",
|
||||
checkTime: new Date(),
|
||||
alertTime: new Date(),
|
||||
resolved: true,
|
||||
resolutionType: "auto",
|
||||
resolvedBy: "system",
|
||||
resolutionNote: "This is a test message",
|
||||
},
|
||||
channel
|
||||
);
|
||||
};
|
||||
|
||||
sendGeneric = async (to: string, subject: string, content: string) => {
|
||||
try {
|
||||
await this.transporter.sendMail({
|
||||
from: `"Checkmate" <${config.SMTP_USER}>`,
|
||||
to: to,
|
||||
subject: subject,
|
||||
text: content,
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export default EmailService;
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
IMonitor,
|
||||
INotificationChannel,
|
||||
IIncident,
|
||||
ResolutionType,
|
||||
} from "@/db/models/index.js";
|
||||
|
||||
export interface IAlert {
|
||||
name: string;
|
||||
url: string;
|
||||
status: string;
|
||||
resolved: boolean;
|
||||
resolutionType: ResolutionType | undefined;
|
||||
resolvedBy?: string | undefined;
|
||||
resolutionNote?: string | undefined;
|
||||
details?: Record<string, string>;
|
||||
checkTime: Date | null;
|
||||
alertTime: Date;
|
||||
}
|
||||
export interface IMessageService {
|
||||
buildAlert: (monitor: IMonitor, incident: IIncident) => IAlert;
|
||||
sendMessage: (
|
||||
alert: IAlert,
|
||||
channel: INotificationChannel
|
||||
) => Promise<boolean>;
|
||||
testMessage: (channel: INotificationChannel) => Promise<boolean>;
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
import {
|
||||
IMonitor,
|
||||
INotificationChannel,
|
||||
IIncident,
|
||||
} from "@/db/models/index.js";
|
||||
import { IAlert, IMessageService } from "./IMessageService.js";
|
||||
import got from "got";
|
||||
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
const SERVICE_NAME = "SlackService";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
class SlackService implements IMessageService {
|
||||
public SERVICE_NAME = SERVICE_NAME;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
private toSlackBlocks = (alert: IAlert) => {
|
||||
return [
|
||||
{
|
||||
type: "header",
|
||||
text: {
|
||||
type: "plain_text",
|
||||
text: "Status Alert",
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Monitor name:* ${alert.name}`,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Status:* ${alert.status}`,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*URL:* ${alert.url}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `resolved: ${alert.resolved ? "Yes" : "No"}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `Resolution Type: ${alert.resolutionType || "N/A"}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `Resolution note: ${alert.resolutionNote || "N/A"}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Checked at:* ${alert?.checkTime?.toISOString() || "N/A"}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "section",
|
||||
text: {
|
||||
type: "mrkdwn",
|
||||
text: `*Checked at:* ${alert?.checkTime?.toISOString() || "N/A"}`,
|
||||
},
|
||||
},
|
||||
|
||||
{
|
||||
type: "divider",
|
||||
},
|
||||
|
||||
...(alert.details
|
||||
? Object.entries(alert.details).map(([key, value]) => ({
|
||||
type: "section",
|
||||
fields: [
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `*${key}:* ${value}`,
|
||||
},
|
||||
],
|
||||
}))
|
||||
: []),
|
||||
|
||||
{
|
||||
type: "context",
|
||||
elements: [
|
||||
{
|
||||
type: "mrkdwn",
|
||||
text: `*Alert generated at:* ${
|
||||
alert?.alertTime?.toISOString() || "N/A"
|
||||
}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
buildAlert = (monitor: IMonitor, incident: IIncident) => {
|
||||
const name = monitor?.name || "Unnamed monitor";
|
||||
const monitorStatus = monitor?.status || "unknown status";
|
||||
const url = monitor?.url || "no URL";
|
||||
const checkTime = monitor?.lastCheckedAt || null;
|
||||
const alertTime = new Date();
|
||||
return {
|
||||
name,
|
||||
url,
|
||||
status: monitorStatus,
|
||||
resolved: incident.resolved,
|
||||
resolutionType: incident.resolutionType,
|
||||
resolvedBy: incident.resolvedBy?.toString(),
|
||||
resolutionNote: incident.resolutionNote,
|
||||
checkTime,
|
||||
alertTime,
|
||||
};
|
||||
};
|
||||
|
||||
sendMessage = async (alert: IAlert, channel: INotificationChannel) => {
|
||||
const notificationUrl = channel?.config?.url;
|
||||
if (!notificationUrl) {
|
||||
throw new Error("Webhook URL not configured");
|
||||
}
|
||||
|
||||
try {
|
||||
const payload = {
|
||||
text: "Status Alert",
|
||||
blocks: this.toSlackBlocks(alert),
|
||||
};
|
||||
await got.post(notificationUrl, { json: payload });
|
||||
} catch (error) {
|
||||
logger.warn("Error sending Slack message:", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
testMessage = async (channel: INotificationChannel) => {
|
||||
return this.sendMessage(
|
||||
{
|
||||
name: "This is a test",
|
||||
url: "Test URL",
|
||||
status: "Test status",
|
||||
checkTime: new Date(),
|
||||
alertTime: new Date(),
|
||||
resolved: true,
|
||||
resolutionType: "auto",
|
||||
resolvedBy: "system",
|
||||
resolutionNote: "This is a test message",
|
||||
},
|
||||
channel
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export default SlackService;
|
||||
@@ -0,0 +1,60 @@
|
||||
import { IMonitor, INotificationChannel } from "@/db/models/index.js";
|
||||
import { IAlert, IMessageService } from "./IMessageService.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
import got from "got";
|
||||
import { getChildLogger } from "@/logger/Logger.js";
|
||||
|
||||
const SERVICE_NAME = "WebhookService";
|
||||
const logger = getChildLogger(SERVICE_NAME);
|
||||
class WebhookService implements IMessageService {
|
||||
public SERVICE_NAME: string;
|
||||
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
buildAlert = (monitor: IMonitor) => {
|
||||
const name = monitor?.name || "Unnamed monitor";
|
||||
const monitorStatus = monitor?.status || "unknown status";
|
||||
const url = monitor?.url || "no URL";
|
||||
const checkTime = monitor?.lastCheckedAt || null;
|
||||
const alertTime = new Date();
|
||||
return {
|
||||
name,
|
||||
url,
|
||||
status: monitorStatus,
|
||||
checkTime,
|
||||
alertTime,
|
||||
};
|
||||
};
|
||||
|
||||
sendMessage = async (alert: IAlert, channel: INotificationChannel) => {
|
||||
const notificationUrl = channel?.config?.url;
|
||||
if (!notificationUrl) {
|
||||
throw new ApiError("Webhook URL not configured", 400);
|
||||
}
|
||||
try {
|
||||
await got.post(notificationUrl, { json: { ...alert } });
|
||||
} catch (error) {
|
||||
logger.warn("Failed to send webhook notification:", error);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
testMessage = async (channel: INotificationChannel) => {
|
||||
return this.sendMessage(
|
||||
{
|
||||
name: "This is a test",
|
||||
url: "Test URL",
|
||||
status: "Test status",
|
||||
checkTime: new Date(),
|
||||
alertTime: new Date(),
|
||||
},
|
||||
channel
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
export default WebhookService;
|
||||
@@ -0,0 +1,5 @@
|
||||
export { default as DiscordService } from "./Discord.js";
|
||||
export { default as EmailService } from "./Email.js";
|
||||
export { default as SlackService } from "./Slack.js";
|
||||
export { default as WebhookService } from "./Webhook.js";
|
||||
export * from "./IMessageService.js";
|
||||
@@ -0,0 +1,141 @@
|
||||
import { IMonitor, IMonitorStats, MonitorStats } from "@/db/models/index.js";
|
||||
import { StatusResponse } from "./NetworkService.js";
|
||||
import ApiError from "@/utils/ApiError.js";
|
||||
|
||||
const SERVICE_NAME = "StatusService";
|
||||
const MAX_LATEST_CHECKS = 25;
|
||||
export interface IStatusService {
|
||||
updateMonitorStatus: (
|
||||
monitor: IMonitor,
|
||||
status: StatusResponse
|
||||
) => Promise<StatusChangeResult>;
|
||||
|
||||
calculateAvgResponseTime: (
|
||||
stats: IMonitorStats,
|
||||
statusResponse: StatusResponse
|
||||
) => number;
|
||||
|
||||
updateMonitorStats: (
|
||||
monitor: IMonitor,
|
||||
status: StatusResponse,
|
||||
statusChanged: boolean
|
||||
) => Promise<IMonitorStats | null>;
|
||||
}
|
||||
|
||||
export type StatusChangeResult = [
|
||||
updatedMonitor: IMonitor,
|
||||
statusChanged: boolean
|
||||
];
|
||||
|
||||
class StatusService implements IStatusService {
|
||||
public SERVICE_NAME: string;
|
||||
constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
}
|
||||
|
||||
updateMonitorStatus = async (
|
||||
monitor: IMonitor,
|
||||
statusResponse: StatusResponse
|
||||
): Promise<StatusChangeResult> => {
|
||||
const newStatus = statusResponse.status;
|
||||
monitor.lastCheckedAt = new Date();
|
||||
|
||||
// Store latest checks for display
|
||||
monitor.latestChecks = monitor.latestChecks || [];
|
||||
monitor.latestChecks.push({
|
||||
status: newStatus,
|
||||
responseTime: statusResponse.responseTime,
|
||||
checkedAt: monitor.lastCheckedAt,
|
||||
});
|
||||
while (monitor.latestChecks.length > MAX_LATEST_CHECKS) {
|
||||
monitor.latestChecks.shift();
|
||||
}
|
||||
|
||||
// Update monitor status
|
||||
if (monitor.status === "initializing") {
|
||||
monitor.status = newStatus;
|
||||
return [await monitor.save(), monitor.latestChecks.length === 0];
|
||||
} else {
|
||||
const { n } = monitor;
|
||||
const latestChecks = monitor.latestChecks.slice(-n);
|
||||
// Return early if not enough statuses to evaluate
|
||||
if (latestChecks.length < n) {
|
||||
return [await monitor.save(), false];
|
||||
}
|
||||
|
||||
// If all different than current status, update status
|
||||
const allDifferent = latestChecks.every(
|
||||
(check) => check.status !== monitor.status
|
||||
);
|
||||
if (allDifferent && monitor.status !== newStatus) {
|
||||
monitor.status = newStatus;
|
||||
}
|
||||
return [await monitor.save(), allDifferent];
|
||||
}
|
||||
};
|
||||
|
||||
calculateAvgResponseTime = (
|
||||
stats: IMonitorStats,
|
||||
statusResponse: StatusResponse
|
||||
): number => {
|
||||
let avgResponseTime = stats.avgResponseTime;
|
||||
// Set initial
|
||||
if (avgResponseTime === 0) {
|
||||
avgResponseTime = statusResponse.responseTime;
|
||||
} else {
|
||||
avgResponseTime =
|
||||
(avgResponseTime * (stats.totalChecks - 1) +
|
||||
statusResponse.responseTime) /
|
||||
stats.totalChecks;
|
||||
}
|
||||
return avgResponseTime;
|
||||
};
|
||||
|
||||
updateMonitorStats = async (
|
||||
monitor: IMonitor,
|
||||
statusResponse: StatusResponse,
|
||||
statusChanged: boolean
|
||||
) => {
|
||||
const stats = await MonitorStats.findOne({ monitorId: monitor._id });
|
||||
if (!stats) {
|
||||
throw new ApiError("MonitorStats not found", 500);
|
||||
}
|
||||
|
||||
// Update check counts
|
||||
stats.totalChecks += 1;
|
||||
stats.totalUpChecks += statusResponse.status === "up" ? 1 : 0;
|
||||
stats.totalDownChecks += statusResponse.status === "down" ? 1 : 0;
|
||||
|
||||
// Update streak
|
||||
if (!statusChanged) {
|
||||
stats.currentStreak += 1;
|
||||
} else {
|
||||
stats.currentStreak = 1;
|
||||
stats.currentStreakStatus = statusResponse.status;
|
||||
stats.currentStreakStartedAt = Date.now();
|
||||
}
|
||||
|
||||
// Update time stamps
|
||||
stats.lastCheckTimestamp = Date.now();
|
||||
stats.timeOfLastFailure =
|
||||
statusResponse.status === "down" ? Date.now() : stats.timeOfLastFailure;
|
||||
|
||||
// Update stats that need updated check counts
|
||||
stats.avgResponseTime = this.calculateAvgResponseTime(
|
||||
stats,
|
||||
statusResponse
|
||||
);
|
||||
stats.uptimePercentage = stats.totalUpChecks / stats.totalChecks;
|
||||
|
||||
// Other
|
||||
stats.lastResponseTime = statusResponse.responseTime;
|
||||
stats.maxResponseTime = Math.max(
|
||||
stats.maxResponseTime,
|
||||
statusResponse.responseTime
|
||||
);
|
||||
|
||||
return await stats.save();
|
||||
};
|
||||
}
|
||||
|
||||
export default StatusService;
|
||||
@@ -0,0 +1,69 @@
|
||||
const SERVICE_NAME = "ServiceRegistry";
|
||||
|
||||
export interface IServiceRegistry {
|
||||
register: (name: string, service: any) => void;
|
||||
get: (name: string) => any;
|
||||
listServices: () => string[];
|
||||
}
|
||||
|
||||
class ServiceRegistry implements IServiceRegistry {
|
||||
public SERVICE_NAME: string;
|
||||
private static _instance: ServiceRegistry;
|
||||
|
||||
private services: { [key: string]: any };
|
||||
|
||||
private constructor() {
|
||||
this.SERVICE_NAME = SERVICE_NAME;
|
||||
this.services = {};
|
||||
}
|
||||
|
||||
static get instance(): ServiceRegistry {
|
||||
if (!this._instance) {
|
||||
this._instance = new ServiceRegistry();
|
||||
}
|
||||
return this._instance;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return this.SERVICE_NAME;
|
||||
}
|
||||
|
||||
// Instance methods
|
||||
register(name: string, service: any) {
|
||||
this.services[name] = service;
|
||||
}
|
||||
|
||||
get(name: string) {
|
||||
if (!this.services[name]) {
|
||||
throw new Error(`Service ${name} is not registered`);
|
||||
}
|
||||
return this.services[name];
|
||||
}
|
||||
|
||||
listServices() {
|
||||
return Object.keys(this.services);
|
||||
}
|
||||
|
||||
static get(name: string) {
|
||||
if (!ServiceRegistry.instance) {
|
||||
throw new Error("ServiceRegistry not initialized");
|
||||
}
|
||||
return ServiceRegistry.instance.get(name);
|
||||
}
|
||||
|
||||
static register(name: string, service: any) {
|
||||
if (!ServiceRegistry.instance) {
|
||||
throw new Error("ServiceRegistry not initialized");
|
||||
}
|
||||
return ServiceRegistry.instance.register(name, service);
|
||||
}
|
||||
|
||||
static listServices() {
|
||||
if (!ServiceRegistry.instance) {
|
||||
throw new Error("ServiceRegistry not initialized");
|
||||
}
|
||||
return ServiceRegistry.instance.listServices();
|
||||
}
|
||||
}
|
||||
|
||||
export default ServiceRegistry;
|
||||
Reference in new issue
Block a user