add heartbeat tests

This commit is contained in:
Alex Holliday committed 2026-04-11 14:45:36 -07:00
1 parent 45d4779b45
commit 233966b73d
10 files changed
+1148 -1

No files matched your search

@@ -0,0 +1,138 @@
import type { IIncidentsRepository } from "../../src/repositories/incidents/IIncidentsRepository.ts";
import type { Incident, IncidentSummary } from "../../src/types/index.ts";
import { randomUUID } from "crypto";
export class InMemoryIncidentsRepository implements IIncidentsRepository {
private incidents: Incident[] = [];
async create(incident: Partial<Incident>): Promise<Incident> {
const now = new Date().toISOString();
const full: Incident = {
id: randomUUID(),
monitorId: incident.monitorId ?? "",
teamId: incident.teamId ?? "",
startTime: incident.startTime ?? now,
endTime: incident.endTime ?? null,
status: incident.status ?? true,
message: incident.message ?? null,
statusCode: incident.statusCode ?? null,
resolutionType: incident.resolutionType ?? null,
resolvedBy: incident.resolvedBy ?? null,
resolvedByEmail: incident.resolvedByEmail ?? null,
comment: incident.comment ?? null,
createdAt: now,
updatedAt: now,
};
this.incidents.push(full);
return { ...full };
}
async findById(incidentId: string, teamId: string): Promise<Incident> {
const incident = this.incidents.find((i) => i.id === incidentId && i.teamId === teamId);
if (!incident) {
throw new Error(`Incident ${incidentId} not found`);
}
return { ...incident };
}
async findActiveByIncidentId(incidentId: string, teamId: string): Promise<Incident | null> {
const incident = this.incidents.find((i) => i.id === incidentId && i.teamId === teamId && i.status === true);
return incident ? { ...incident } : null;
}
async findActiveByMonitorId(monitorId: string, teamId: string): Promise<Incident | null> {
const incident = this.incidents.find((i) => i.monitorId === monitorId && i.teamId === teamId && i.status === true);
return incident ? { ...incident } : null;
}
async findByTeamId(
teamId: string,
startDate: Date | undefined,
page: number,
rowsPerPage: number,
sortOrder?: string,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<Incident[]> {
let results = this.incidents.filter((i) => i.teamId === teamId);
if (startDate) {
results = results.filter((i) => new Date(i.startTime) >= startDate);
}
if (status !== undefined) {
results = results.filter((i) => i.status === status);
}
if (monitorId) {
results = results.filter((i) => i.monitorId === monitorId);
}
if (resolutionType) {
results = results.filter((i) => i.resolutionType === resolutionType);
}
results.sort((a, b) => {
const cmp = new Date(a.startTime).getTime() - new Date(b.startTime).getTime();
return sortOrder === "desc" ? -cmp : cmp;
});
return results.slice(page * rowsPerPage, (page + 1) * rowsPerPage).map((i) => ({ ...i }));
}
async findSummaryByTeamId(_teamId: string, _limit?: number): Promise<IncidentSummary> {
throw new Error("Not implemented");
}
async countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise<number> {
let results = this.incidents.filter((i) => i.teamId === teamId);
if (startDate) {
results = results.filter((i) => new Date(i.startTime) >= startDate);
}
if (status !== undefined) {
results = results.filter((i) => i.status === status);
}
if (monitorId) {
results = results.filter((i) => i.monitorId === monitorId);
}
if (resolutionType) {
results = results.filter((i) => i.resolutionType === resolutionType);
}
return results.length;
}
async updateById(incidentId: string, teamId: string, updateData: Partial<Incident>): Promise<Incident> {
const index = this.incidents.findIndex((i) => i.id === incidentId && i.teamId === teamId);
if (index === -1) {
throw new Error(`Incident ${incidentId} not found`);
}
const updated: Incident = {
...this.incidents[index],
...updateData,
id: this.incidents[index].id,
monitorId: this.incidents[index].monitorId,
teamId: this.incidents[index].teamId,
createdAt: this.incidents[index].createdAt,
updatedAt: new Date().toISOString(),
};
this.incidents[index] = updated;
return { ...updated };
}
async deleteByMonitorId(monitorId: string, teamId: string): Promise<number> {
const before = this.incidents.length;
this.incidents = this.incidents.filter((i) => !(i.monitorId === monitorId && i.teamId === teamId));
return before - this.incidents.length;
}
async deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number> {
const before = this.incidents.length;
this.incidents = this.incidents.filter((i) => monitorIds.includes(i.monitorId));
return before - this.incidents.length;
}
// Test helpers — not part of the interface
getAll(): Incident[] {
return this.incidents.map((i) => ({ ...i }));
}
clear(): void {
this.incidents = [];
}
}
@@ -0,0 +1,116 @@
import type { IMonitorsRepository, TeamQueryConfig, SummaryConfig } from "../../src/repositories/monitors/IMonitorsRepository.ts";
import type { Monitor, MonitorsSummary } from "../../src/types/index.ts";
export class InMemoryMonitorsRepository implements IMonitorsRepository {
private monitors: Monitor[] = [];
async create(monitor: Monitor, _teamId: string, _userId: string): Promise<Monitor> {
this.monitors.push({ ...monitor });
return { ...monitor };
}
async createMonitors(monitors: Monitor[]): Promise<Monitor[]> {
const created = monitors.map((m) => ({ ...m }));
this.monitors.push(...created);
return created;
}
async findById(monitorId: string, teamId: string): Promise<Monitor> {
const monitor = this.monitors.find((m) => m.id === monitorId && m.teamId === teamId);
if (!monitor) {
throw new Error(`Monitor ${monitorId} not found`);
}
return { ...monitor };
}
async findAll(): Promise<Monitor[]> {
return this.monitors.map((m) => ({ ...m }));
}
async findByTeamId(_teamId: string, _config: TeamQueryConfig): Promise<Monitor[]> {
return this.monitors.filter((m) => m.teamId === _teamId).map((m) => ({ ...m }));
}
async findByIds(monitorIds: string[]): Promise<Monitor[]> {
return this.monitors.filter((m) => monitorIds.includes(m.id)).map((m) => ({ ...m }));
}
async findByIdsWithChecks(monitorIds: string[], _checksCount?: number): Promise<Monitor[]> {
return this.findByIds(monitorIds);
}
async updateById(monitorId: string, teamId: string, updates: Partial<Monitor>): Promise<Monitor> {
const index = this.monitors.findIndex((m) => m.id === monitorId && m.teamId === teamId);
if (index === -1) {
throw new Error(`Monitor ${monitorId} not found`);
}
const updated = { ...this.monitors[index], ...updates, id: this.monitors[index].id, teamId: this.monitors[index].teamId };
this.monitors[index] = updated;
return { ...updated };
}
async togglePauseById(monitorId: string, teamId: string): Promise<Monitor> {
const monitor = await this.findById(monitorId, teamId);
const newStatus = monitor.status === "paused" ? "up" : "paused";
return this.updateById(monitorId, teamId, { status: newStatus });
}
async deleteById(monitorId: string, teamId: string): Promise<Monitor> {
const index = this.monitors.findIndex((m) => m.id === monitorId && m.teamId === teamId);
if (index === -1) {
throw new Error(`Monitor ${monitorId} not found`);
}
const [deleted] = this.monitors.splice(index, 1);
return { ...deleted };
}
async deleteByTeamId(teamId: string): Promise<{ monitors: Monitor[]; deletedCount: number }> {
const toDelete = this.monitors.filter((m) => m.teamId === teamId);
this.monitors = this.monitors.filter((m) => m.teamId !== teamId);
return { monitors: toDelete, deletedCount: toDelete.length };
}
async findMonitorCountByTeamIdAndType(teamId: string, _config: TeamQueryConfig): Promise<number> {
return this.monitors.filter((m) => m.teamId === teamId).length;
}
async findMonitorsSummaryByTeamId(_teamId: string, _config?: SummaryConfig): Promise<MonitorsSummary> {
throw new Error("Not implemented");
}
async findGroupsByTeamId(_teamId: string): Promise<string[]> {
throw new Error("Not implemented");
}
async removeNotificationFromMonitors(_notificationId: string): Promise<void> {
throw new Error("Not implemented");
}
async updateNotifications(_teamId: string, _monitorIds: string[], _notificationIds: string[], _action: "add" | "remove" | "set"): Promise<number> {
throw new Error("Not implemented");
}
async deleteByTeamIdsNotIn(teamIds: string[]): Promise<number> {
const before = this.monitors.length;
this.monitors = this.monitors.filter((m) => teamIds.includes(m.teamId));
return before - this.monitors.length;
}
async findAllMonitorIds(): Promise<string[]> {
return this.monitors.map((m) => m.id);
}
// Test helpers
seed(monitor: Monitor): void {
this.monitors.push({ ...monitor });
}
getAll(): Monitor[] {
return this.monitors.map((m) => ({ ...m }));
}
clear(): void {
this.monitors = [];
}
}
+179
View File
@@ -0,0 +1,179 @@
import { jest } from "@jest/globals";
import { SuperSimpleQueueHelper } from "../../src/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.ts";
import { StatusService } from "../../src/service/infrastructure/statusService.ts";
import { IncidentService } from "../../src/service/business/incidentService.ts";
import { InMemoryMonitorsRepository } from "./InMemoryMonitorsRepository.ts";
import { InMemoryIncidentsRepository } from "./InMemoryIncidentsRepository.ts";
import { createMockLogger } from "./createMockLogger.ts";
import type { Monitor } from "../../src/types/monitor.ts";
import type { MonitorStatusResponse } from "../../src/types/network.ts";
import type { Check } from "../../src/types/check.ts";
import type { MaintenanceWindow } from "../../src/types/maintenanceWindow.ts";
let checkCounter = 0;
export const makeMonitor = (overrides?: Partial<Monitor>): Monitor =>
({
id: "mon-1",
teamId: "team-1",
name: "Test Monitor",
type: "http",
url: "https://example.com",
status: "up",
// Pre-fill window so threshold evaluation runs immediately.
// Without this, the warm-up path sets monitor.status directly
// from each check, bypassing the threshold logic.
statusWindow: [true, true, true, true, true],
statusWindowSize: 5,
statusWindowThreshold: 60,
recentChecks: [],
notifications: [],
...overrides,
}) as Monitor;
export const makeStatusResponse = (status: boolean, code: number): MonitorStatusResponse => ({
monitorId: "mon-1",
teamId: "team-1",
type: "http",
status,
code,
message: status ? "OK" : "Service Unavailable",
responseTime: status ? 150 : 0,
});
export const makeCheck = (status: boolean, code: number): Check => {
const now = new Date().toISOString();
return {
id: `check-${++checkCounter}`,
metadata: { monitorId: "mon-1", teamId: "team-1", type: "http" },
status,
statusCode: code,
responseTime: status ? 150 : 0,
message: status ? "OK" : "Service Unavailable",
createdAt: now,
updatedAt: now,
};
};
const createStubMonitorStatsRepo = () => ({
findByMonitorId: jest.fn().mockRejectedValue(new Error("no stats")),
create: jest.fn().mockResolvedValue({}),
updateByMonitorId: jest.fn().mockResolvedValue({}),
deleteByMonitorId: jest.fn(),
deleteByMonitorIds: jest.fn(),
deleteByMonitorIdsNotIn: jest.fn(),
});
const createStubChecksRepo = () => ({
create: jest.fn(),
createChecks: jest.fn(),
findByMonitorId: jest.fn(),
findByTeamId: jest.fn(),
findLatestByMonitorIds: jest.fn(),
findByDateRangeAndMonitorId: jest.fn(),
findSummaryByTeamId: jest.fn(),
deleteByMonitorId: jest.fn(),
deleteByTeamId: jest.fn(),
deleteByMonitorIdsNotIn: jest.fn(),
deleteOlderThan: jest.fn(),
});
export interface HeartbeatTestHarness {
monitorsRepo: InMemoryMonitorsRepository;
incidentsRepo: InMemoryIncidentsRepository;
statusService: StatusService;
incidentService: IncidentService;
notificationsService: { handleNotifications: jest.Mock };
networkService: { requestStatus: jest.Mock };
bufferStub: { addToBuffer: jest.Mock; addGeoCheckToBuffer: jest.Mock; scheduleNextFlush: jest.Mock };
maintenanceWindowsRepo: { findByMonitorId: jest.Mock };
messageBuilder: { extractThresholdBreaches: jest.Mock };
heartbeatJob: (monitor: Monitor) => Promise<void>;
setNextResponse: (status: boolean, code: number) => void;
setNextResponseFull: (response: MonitorStatusResponse) => void;
}
export function createHeartbeatTestHarness(): HeartbeatTestHarness {
checkCounter = 0;
const monitorsRepo = new InMemoryMonitorsRepository();
const incidentsRepo = new InMemoryIncidentsRepository();
const logger = createMockLogger() as any;
const bufferStub = { addToBuffer: jest.fn(), addGeoCheckToBuffer: jest.fn(), scheduleNextFlush: jest.fn() };
const statusService = new StatusService(
logger,
bufferStub as any,
monitorsRepo as any,
createStubMonitorStatsRepo() as any,
createStubChecksRepo() as any
);
const messageBuilder = { extractThresholdBreaches: jest.fn().mockReturnValue([]) };
const incidentService = new IncidentService(logger, incidentsRepo, monitorsRepo as any, { findById: jest.fn() } as any, messageBuilder as any);
const notificationsService = { handleNotifications: jest.fn().mockResolvedValue(true) };
let nextResponse: MonitorStatusResponse | null = null;
let nextStatus = true;
let nextCode = 200;
const networkService = {
requestStatus: jest.fn().mockImplementation(() => {
if (nextResponse) {
return Promise.resolve(nextResponse);
}
return Promise.resolve(makeStatusResponse(nextStatus, nextCode));
}),
};
const checkService = {
buildCheck: jest.fn().mockImplementation((response: MonitorStatusResponse) => {
return makeCheck(response.status, response.code);
}),
};
const setNextResponse = (status: boolean, code: number) => {
nextResponse = null;
nextStatus = status;
nextCode = code;
};
const setNextResponseFull = (response: MonitorStatusResponse) => {
nextResponse = response;
};
const maintenanceWindowsRepo = { findByMonitorId: jest.fn().mockResolvedValue([]) };
const helper = new SuperSimpleQueueHelper(
logger,
networkService as any,
statusService as any,
notificationsService as any,
checkService as any,
{ getDBSettings: jest.fn() } as any,
bufferStub as any,
incidentService as any,
maintenanceWindowsRepo as any,
monitorsRepo as any,
{ findAllTeamIds: jest.fn() } as any,
createStubMonitorStatsRepo() as any,
createStubChecksRepo() as any,
incidentsRepo as any,
{ buildGeoCheck: jest.fn() } as any,
{ deleteByMonitorIdsNotIn: jest.fn() } as any
);
return {
monitorsRepo,
incidentsRepo,
statusService,
incidentService,
notificationsService,
networkService,
bufferStub,
maintenanceWindowsRepo,
messageBuilder,
heartbeatJob: helper.getHeartbeatJob(),
setNextResponse,
setNextResponseFull,
};
}