reorg to domain and api
This commit is contained in:
1 parent
0fb210e9e1
commit
d022f7d849
190 files changed
+643
-830
No files matched your search
@@ -0,0 +1,67 @@
|
||||
import { Schema, model, type Types } from "mongoose";
|
||||
import { DurationUnits, type MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
|
||||
type MaintenanceWindowDocumentBase = Omit<MaintenanceWindow, "id" | "monitorIds" | "teamId" | "start" | "end" | "createdAt" | "updatedAt"> & {
|
||||
monitorIds: Types.ObjectId[];
|
||||
teamId: Types.ObjectId;
|
||||
start: Date;
|
||||
end: Date;
|
||||
expiry?: Date;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
};
|
||||
|
||||
interface MaintenanceWindowDocument extends MaintenanceWindowDocumentBase {
|
||||
_id: Types.ObjectId;
|
||||
}
|
||||
|
||||
const MaintenanceWindowSchema = new Schema<MaintenanceWindowDocument>(
|
||||
{
|
||||
monitorIds: {
|
||||
type: [Schema.Types.ObjectId],
|
||||
ref: "Monitor",
|
||||
index: true,
|
||||
},
|
||||
teamId: {
|
||||
type: Schema.Types.ObjectId,
|
||||
ref: "Team",
|
||||
immutable: true,
|
||||
},
|
||||
active: {
|
||||
type: Boolean,
|
||||
default: true,
|
||||
},
|
||||
name: {
|
||||
type: String,
|
||||
},
|
||||
duration: {
|
||||
type: Number,
|
||||
},
|
||||
durationUnit: {
|
||||
type: String,
|
||||
enum: DurationUnits,
|
||||
},
|
||||
repeat: {
|
||||
type: Number,
|
||||
},
|
||||
start: {
|
||||
type: Date,
|
||||
},
|
||||
end: {
|
||||
type: Date,
|
||||
},
|
||||
expiry: {
|
||||
type: Date,
|
||||
index: { expires: "0s" },
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamps: true,
|
||||
}
|
||||
);
|
||||
|
||||
const MaintenanceWindowModel = model<MaintenanceWindowDocument>("MaintenanceWindow", MaintenanceWindowSchema);
|
||||
|
||||
export type { MaintenanceWindowDocument };
|
||||
export { MaintenanceWindowModel };
|
||||
export default MaintenanceWindowModel;
|
||||
@@ -0,0 +1,17 @@
|
||||
import type { MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
export interface IMaintenanceWindowsRepository {
|
||||
// create
|
||||
create(data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow>;
|
||||
// fetch
|
||||
findById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
||||
findByMonitorId(monitorId: string, teamId: string): Promise<MaintenanceWindow[]>;
|
||||
findByMonitorIds(monitorIds: string[], teamId: string, excludeId?: string): Promise<MaintenanceWindow[]>;
|
||||
findByTeamId(teamId: string, page: number, rowsPerPage: number, field?: string, order?: string, active?: boolean): Promise<MaintenanceWindow[]>;
|
||||
|
||||
// update
|
||||
updateById(id: string, teamId: string, data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow>;
|
||||
// delete
|
||||
deleteById(id: string, teamId: string): Promise<MaintenanceWindow>;
|
||||
// other
|
||||
countByTeamId(teamId: string, active?: boolean): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import type { MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
import { type MaintenanceWindowDocument, MaintenanceWindowModel } from "@/domain/maintenance-windows/maintenance-window.model.js";
|
||||
import { IMaintenanceWindowsRepository } from "./maintenance-window.repository.interface.js";
|
||||
import mongoose, { SortOrder } from "mongoose";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
|
||||
class MongoMaintenanceWindowsRepository implements IMaintenanceWindowsRepository {
|
||||
private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => {
|
||||
if (!value) {
|
||||
return "";
|
||||
}
|
||||
return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value);
|
||||
};
|
||||
|
||||
private toDateString = (value?: Date | string | null): string => {
|
||||
if (!value) {
|
||||
return new Date(0).toISOString();
|
||||
}
|
||||
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
|
||||
};
|
||||
|
||||
private mapDocuments = (documents: MaintenanceWindowDocument[]): MaintenanceWindow[] => {
|
||||
if (!documents?.length) {
|
||||
return [];
|
||||
}
|
||||
return documents.map((doc) => this.toEntity(doc));
|
||||
};
|
||||
|
||||
private toEntity = (doc: MaintenanceWindowDocument): MaintenanceWindow => {
|
||||
return {
|
||||
id: this.toStringId(doc._id),
|
||||
monitorIds: doc.monitorIds.map(this.toStringId),
|
||||
teamId: this.toStringId(doc.teamId),
|
||||
active: doc.active,
|
||||
name: doc.name,
|
||||
duration: doc.duration,
|
||||
durationUnit: doc.durationUnit,
|
||||
repeat: doc.repeat,
|
||||
start: this.toDateString(doc.start),
|
||||
end: this.toDateString(doc.end),
|
||||
createdAt: this.toDateString(doc.createdAt),
|
||||
updatedAt: this.toDateString(doc.updatedAt),
|
||||
};
|
||||
};
|
||||
|
||||
create = async (data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow> => {
|
||||
const maintenanceWindow = new MaintenanceWindowModel(data);
|
||||
|
||||
// If the maintenance window is a one time window, set the expiry to the end date
|
||||
if (maintenanceWindow.repeat === 0) {
|
||||
maintenanceWindow.expiry = maintenanceWindow.end;
|
||||
}
|
||||
const result = await maintenanceWindow.save();
|
||||
return this.toEntity(result);
|
||||
};
|
||||
|
||||
findById = async (id: string, teamId: string): Promise<MaintenanceWindow> => {
|
||||
const maintenanceWindow = await MaintenanceWindowModel.findOne({
|
||||
_id: id,
|
||||
teamId: teamId,
|
||||
});
|
||||
if (!maintenanceWindow) {
|
||||
throw new AppError({ message: "Maintenance Window not found", status: 404 });
|
||||
}
|
||||
return this.toEntity(maintenanceWindow);
|
||||
};
|
||||
|
||||
findByMonitorIds = async (monitorIds: string[], teamId: string, excludeId?: string): Promise<MaintenanceWindow[]> => {
|
||||
const query: Record<string, unknown> = {
|
||||
monitorIds: { $in: monitorIds },
|
||||
teamId,
|
||||
};
|
||||
if (excludeId) {
|
||||
query._id = { $ne: new mongoose.Types.ObjectId(excludeId) };
|
||||
}
|
||||
const maintenanceWindows = await MaintenanceWindowModel.find(query);
|
||||
return this.mapDocuments(maintenanceWindows);
|
||||
};
|
||||
|
||||
findByMonitorId = async (monitorId: string, teamId: string): Promise<MaintenanceWindow[]> => {
|
||||
const maintenanceWindows = await MaintenanceWindowModel.find({
|
||||
monitorIds: monitorId,
|
||||
teamId: teamId,
|
||||
});
|
||||
return this.mapDocuments(maintenanceWindows);
|
||||
};
|
||||
|
||||
findByTeamId = async (
|
||||
teamId: string,
|
||||
page: number,
|
||||
rowsPerPage: number,
|
||||
field?: string,
|
||||
order?: string,
|
||||
active?: boolean
|
||||
): Promise<MaintenanceWindow[]> => {
|
||||
const maintenanceQuery: Record<string, unknown> = { teamId };
|
||||
|
||||
if (active !== undefined) maintenanceQuery.active = active;
|
||||
|
||||
// Pagination
|
||||
let skip = 0;
|
||||
if (page && rowsPerPage) {
|
||||
skip = page * rowsPerPage;
|
||||
}
|
||||
|
||||
// Sorting
|
||||
const sort: Record<string, SortOrder> = {};
|
||||
if (field !== undefined && order !== undefined) {
|
||||
sort[field] = order === "asc" ? 1 : -1;
|
||||
}
|
||||
|
||||
const maintenanceWindows = await MaintenanceWindowModel.find(maintenanceQuery).skip(skip).limit(rowsPerPage).sort(sort);
|
||||
return this.mapDocuments(maintenanceWindows);
|
||||
};
|
||||
|
||||
updateById = async (id: string, teamId: string, data: Partial<MaintenanceWindow>): Promise<MaintenanceWindow> => {
|
||||
const updated = await MaintenanceWindowModel.findOneAndUpdate(
|
||||
{
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
},
|
||||
{ $set: data },
|
||||
{ new: true, runValidators: true }
|
||||
);
|
||||
if (!updated) {
|
||||
throw new AppError({ message: "Maintenance window not found or could not be updated", status: 404 });
|
||||
}
|
||||
|
||||
return this.toEntity(updated);
|
||||
};
|
||||
|
||||
deleteById = async (id: string, teamId: string): Promise<MaintenanceWindow> => {
|
||||
const deleted = await MaintenanceWindowModel.findOneAndDelete({
|
||||
_id: new mongoose.Types.ObjectId(id),
|
||||
teamId: new mongoose.Types.ObjectId(teamId),
|
||||
});
|
||||
if (!deleted) {
|
||||
throw new AppError({ message: "Maintenance window not found or could not be deleted", status: 404 });
|
||||
}
|
||||
|
||||
return this.toEntity(deleted);
|
||||
};
|
||||
countByTeamId = async (teamId: string, active?: boolean) => {
|
||||
const maintenanceQuery: Record<string, unknown> = { teamId };
|
||||
|
||||
if (active !== undefined) maintenanceQuery.active = active;
|
||||
|
||||
return await MaintenanceWindowModel.countDocuments(maintenanceQuery);
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoMaintenanceWindowsRepository;
|
||||
@@ -0,0 +1,218 @@
|
||||
import { IMaintenanceWindowsRepository } from "@/domain/maintenance-windows/maintenance-window.repository.interface.js";
|
||||
import { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
|
||||
import type { DurationUnit, MaintenanceWindow } from "@/domain/maintenance-windows/maintenance-window.type.js";
|
||||
import { AppError } from "@/utils/AppError.js";
|
||||
import { isWindowActive } from "@/utils/maintenanceWindow.js";
|
||||
|
||||
const SERVICE_NAME = "maintenanceWindowService";
|
||||
|
||||
export interface IMaintenanceWindowService {
|
||||
createMaintenanceWindow(params: {
|
||||
teamId: string;
|
||||
monitorIDs: string[];
|
||||
name: string;
|
||||
active: boolean;
|
||||
duration: number;
|
||||
durationUnit: DurationUnit;
|
||||
repeat: number;
|
||||
start: string;
|
||||
end: string;
|
||||
}): Promise<void>;
|
||||
getMaintenanceWindowById(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||
getMaintenanceWindowsByTeamId(params: {
|
||||
teamId: string;
|
||||
active?: boolean;
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
field?: string;
|
||||
order?: string;
|
||||
}): Promise<{ maintenanceWindows: MaintenanceWindow[]; maintenanceWindowCount: number }>;
|
||||
getMaintenanceWindowsByMonitorId(params: { monitorId: string; teamId: string }): Promise<MaintenanceWindow[]>;
|
||||
deleteMaintenanceWindow(params: { id: string; teamId: string }): Promise<MaintenanceWindow>;
|
||||
editMaintenanceWindow(params: {
|
||||
id: string;
|
||||
teamId: string;
|
||||
body: Partial<Omit<MaintenanceWindow, "monitorIds">> & { monitors?: string[] };
|
||||
}): Promise<MaintenanceWindow>;
|
||||
}
|
||||
|
||||
export class MaintenanceWindowService implements IMaintenanceWindowService {
|
||||
static SERVICE_NAME = SERVICE_NAME;
|
||||
private monitorsRepository: IMonitorsRepository;
|
||||
private maintenanceWindowsRepository: IMaintenanceWindowsRepository;
|
||||
|
||||
constructor({
|
||||
monitorsRepository,
|
||||
maintenanceWindowsRepository,
|
||||
}: {
|
||||
monitorsRepository: IMonitorsRepository;
|
||||
maintenanceWindowsRepository: IMaintenanceWindowsRepository;
|
||||
}) {
|
||||
this.monitorsRepository = monitorsRepository;
|
||||
this.maintenanceWindowsRepository = maintenanceWindowsRepository;
|
||||
}
|
||||
|
||||
get serviceName() {
|
||||
return MaintenanceWindowService.SERVICE_NAME;
|
||||
}
|
||||
|
||||
private flipMonitorsLeavingMaintenance = async (monitorIds: string[], teamId: string, excludeWindowId: string, now: Date): Promise<void> => {
|
||||
if (monitorIds.length === 0) return;
|
||||
|
||||
const otherWindows = await this.maintenanceWindowsRepository.findByMonitorIds(monitorIds, teamId, excludeWindowId);
|
||||
const stillCovered = new Set<string>();
|
||||
for (const otherWindow of otherWindows) {
|
||||
if (!isWindowActive(otherWindow, now)) continue;
|
||||
for (const monitorId of otherWindow.monitorIds) {
|
||||
if (monitorIds.includes(monitorId)) stillCovered.add(monitorId);
|
||||
}
|
||||
}
|
||||
|
||||
const toInitializing = monitorIds.filter((monitorId) => !stillCovered.has(monitorId));
|
||||
if (toInitializing.length > 0) {
|
||||
await this.monitorsRepository.updateByIds(toInitializing, teamId, { status: "initializing" }, ["paused"]);
|
||||
}
|
||||
};
|
||||
|
||||
createMaintenanceWindow = async ({
|
||||
teamId,
|
||||
monitorIDs,
|
||||
name,
|
||||
active,
|
||||
duration,
|
||||
durationUnit,
|
||||
repeat,
|
||||
start,
|
||||
end,
|
||||
}: {
|
||||
teamId: string;
|
||||
monitorIDs: string[];
|
||||
name: string;
|
||||
active: boolean;
|
||||
duration: number;
|
||||
durationUnit: DurationUnit;
|
||||
repeat: number;
|
||||
start: string;
|
||||
end: string;
|
||||
}) => {
|
||||
const monitors = await this.monitorsRepository.findByIds(monitorIDs);
|
||||
|
||||
const unauthorizedMonitors = monitors.filter((monitor) => monitor.teamId !== teamId);
|
||||
|
||||
if (unauthorizedMonitors.length > 0) {
|
||||
throw new AppError({
|
||||
message: "Unauthorized to create maintenance window for one or more monitors",
|
||||
service: SERVICE_NAME,
|
||||
method: "createMaintenanceWindow",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
|
||||
const created = await this.maintenanceWindowsRepository.create({
|
||||
teamId,
|
||||
monitorIds: monitorIDs,
|
||||
name: name,
|
||||
active: active,
|
||||
duration: duration,
|
||||
durationUnit: durationUnit,
|
||||
repeat: repeat,
|
||||
start: start,
|
||||
end: end,
|
||||
});
|
||||
|
||||
if (isWindowActive(created)) {
|
||||
await this.monitorsRepository.updateByIds(created.monitorIds, teamId, { status: "maintenance" }, ["paused"]);
|
||||
}
|
||||
};
|
||||
|
||||
getMaintenanceWindowById = async ({ id, teamId }: { id: string; teamId: string }) => {
|
||||
return await this.maintenanceWindowsRepository.findById(id, teamId);
|
||||
};
|
||||
|
||||
getMaintenanceWindowsByTeamId = async ({
|
||||
teamId,
|
||||
active,
|
||||
page,
|
||||
rowsPerPage,
|
||||
field,
|
||||
order,
|
||||
}: {
|
||||
teamId: string;
|
||||
active?: boolean;
|
||||
page?: number;
|
||||
rowsPerPage?: number;
|
||||
field?: string;
|
||||
order?: string;
|
||||
}) => {
|
||||
page = page ?? 0;
|
||||
rowsPerPage = rowsPerPage ?? 10;
|
||||
|
||||
const maintenanceWindows = await this.maintenanceWindowsRepository.findByTeamId(teamId, page, rowsPerPage, field, order, active);
|
||||
const maintenanceWindowCount = await this.maintenanceWindowsRepository.countByTeamId(teamId, active);
|
||||
return { maintenanceWindows, maintenanceWindowCount };
|
||||
};
|
||||
|
||||
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }: { monitorId: string; teamId: string }) => {
|
||||
return await this.maintenanceWindowsRepository.findByMonitorId(monitorId, teamId);
|
||||
};
|
||||
|
||||
deleteMaintenanceWindow = async ({ id, teamId }: { id: string; teamId: string }) => {
|
||||
const deleted = await this.maintenanceWindowsRepository.deleteById(id, teamId);
|
||||
|
||||
const now = new Date();
|
||||
if (isWindowActive(deleted, now)) {
|
||||
await this.flipMonitorsLeavingMaintenance(deleted.monitorIds, teamId, deleted.id, now);
|
||||
}
|
||||
|
||||
return deleted;
|
||||
};
|
||||
|
||||
editMaintenanceWindow = async ({
|
||||
id,
|
||||
teamId,
|
||||
body,
|
||||
}: {
|
||||
id: string;
|
||||
teamId: string;
|
||||
body: Partial<Omit<MaintenanceWindow, "monitorIds">> & { monitors?: string[] };
|
||||
}) => {
|
||||
const existing = await this.maintenanceWindowsRepository.findById(id, teamId);
|
||||
|
||||
const { monitors, ...rest } = body;
|
||||
const update: Partial<MaintenanceWindow> = rest;
|
||||
|
||||
if (monitors !== undefined) {
|
||||
const monitorDocs = await this.monitorsRepository.findByIds(monitors);
|
||||
const unauthorizedMonitors = monitorDocs.filter((monitor) => monitor.teamId !== teamId);
|
||||
if (unauthorizedMonitors.length > 0) {
|
||||
throw new AppError({
|
||||
message: "Unauthorized to edit maintenance window for one or more monitors",
|
||||
service: SERVICE_NAME,
|
||||
method: "editMaintenanceWindow",
|
||||
status: 403,
|
||||
});
|
||||
}
|
||||
update.monitorIds = monitors;
|
||||
}
|
||||
|
||||
const updated = await this.maintenanceWindowsRepository.updateById(id, teamId, update);
|
||||
|
||||
const now = new Date();
|
||||
const wasActive = isWindowActive(existing, now);
|
||||
const isActive = isWindowActive(updated, now);
|
||||
|
||||
const enteringMaintenance = isActive ? updated.monitorIds.filter((monitorId) => !wasActive || !existing.monitorIds.includes(monitorId)) : [];
|
||||
|
||||
const leavingCandidates = wasActive ? existing.monitorIds.filter((monitorId) => !isActive || !updated.monitorIds.includes(monitorId)) : [];
|
||||
|
||||
if (enteringMaintenance.length > 0) {
|
||||
await this.monitorsRepository.updateByIds(enteringMaintenance, teamId, { status: "maintenance" }, ["paused"]);
|
||||
}
|
||||
|
||||
if (leavingCandidates.length > 0) {
|
||||
await this.flipMonitorsLeavingMaintenance(leavingCandidates, teamId, existing.id, now);
|
||||
}
|
||||
|
||||
return updated;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export const DurationUnits = ["seconds", "minutes", "hours", "days"] as const;
|
||||
export type DurationUnit = (typeof DurationUnits)[number];
|
||||
|
||||
export interface MaintenanceWindow {
|
||||
id: string;
|
||||
monitorIds: string[];
|
||||
teamId: string;
|
||||
active: boolean;
|
||||
name: string;
|
||||
duration: number;
|
||||
durationUnit: DurationUnit;
|
||||
repeat: number;
|
||||
start: string;
|
||||
end: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
Reference in new issue
Block a user