remove in memory modification of monitor stats

This commit is contained in:
Alex Holliday committed 2026-04-13 11:39:29 -07:00
1 parent ff114b3ab2
commit b3930b31f2
7 files changed
+147 -248

No files matched your search

+1 -1
View File
@@ -16,7 +16,7 @@ const MonitorStatsSchema = new Schema<MonitorStatsDocument>(
monitorId: { monitorId: {
type: Schema.Types.ObjectId, type: Schema.Types.ObjectId,
ref: "Monitor", ref: "Monitor",
index: true, unique: true,
required: true, required: true,
}, },
avgResponseTime: { avgResponseTime: {
@@ -1,11 +1,12 @@
import type { MonitorStats } from "@/types/index.js"; import type { MonitorStats, CheckResultInput } from "@/types/index.js";
export interface IMonitorStatsRepository { export interface IMonitorStatsRepository {
// create // create
create(data: Omit<MonitorStats, "id" | "createdAt" | "updatedAt">): Promise<MonitorStats>; create(data: Omit<MonitorStats, "id" | "createdAt" | "updatedAt">): Promise<MonitorStats>;
// single fetch // single fetch
findByMonitorId(monitorId: string): Promise<MonitorStats>; findByMonitorId(monitorId: string): Promise<MonitorStats>;
// update // Upsert must be atomic to prevent race conditions
updateByMonitorId(monitorId: string, data: Omit<MonitorStats, "id" | "monitorId" | "createdAt" | "updatedAt">): Promise<MonitorStats>; updateByMonitorId(monitorId: string, result: CheckResultInput): Promise<MonitorStats>;
// delete // delete
deleteByMonitorId(monitorId: string): Promise<MonitorStats>; deleteByMonitorId(monitorId: string): Promise<MonitorStats>;
deleteByMonitorIds(monitorIds: string[]): Promise<number>; deleteByMonitorIds(monitorIds: string[]): Promise<number>;
@@ -1,5 +1,5 @@
import { type MonitorStatsDocument, MonitorStatsModel } from "@/db/models/index.js"; import { type MonitorStatsDocument, MonitorStatsModel } from "@/db/models/index.js";
import type { MonitorStats } from "@/types/index.js"; import type { MonitorStats, CheckResultInput } from "@/types/index.js";
import { IMonitorStatsRepository } from "@/repositories/index.js"; import { IMonitorStatsRepository } from "@/repositories/index.js";
import mongoose from "mongoose"; import mongoose from "mongoose";
import { AppError } from "@/utils/AppError.js"; import { AppError } from "@/utils/AppError.js";
@@ -46,10 +46,48 @@ class MongoMonitorStatsRepository implements IMonitorStatsRepository {
return this.toEntity(monitorStats); return this.toEntity(monitorStats);
}; };
updateByMonitorId = async (monitorId: string, data: Omit<MonitorStats, "id" | "monitorId" | "createdAt" | "updatedAt">): Promise<MonitorStats> => { updateByMonitorId = async (monitorId: string, result: CheckResultInput): Promise<MonitorStats> => {
const updated = await MonitorStatsModel.findOneAndUpdate({ monitorId: new mongoose.Types.ObjectId(monitorId) }, { $set: data }, { new: true }); const { status, responseTime, now } = result;
const objectId = new mongoose.Types.ObjectId(monitorId);
const upDelta = status ? 1 : 0;
const downDelta = status ? 0 : 1;
const pipeline = [
{
$set: {
monitorId: objectId,
totalChecks: { $add: [{ $ifNull: ["$totalChecks", 0] }, 1] },
totalUpChecks: { $add: [{ $ifNull: ["$totalUpChecks", 0] }, upDelta] },
totalDownChecks: { $add: [{ $ifNull: ["$totalDownChecks", 0] }, downDelta] },
avgResponseTime: {
$divide: [
{
$add: [{ $multiply: [{ $ifNull: ["$avgResponseTime", 0] }, { $ifNull: ["$totalChecks", 0] }] }, responseTime],
},
{ $add: [{ $ifNull: ["$totalChecks", 0] }, 1] },
],
},
uptimePercentage: {
$divide: [{ $add: [{ $ifNull: ["$totalUpChecks", 0] }, upDelta] }, { $add: [{ $ifNull: ["$totalChecks", 0] }, 1] }],
},
maxResponseTime: { $max: [{ $ifNull: ["$maxResponseTime", 0] }, responseTime] },
lastResponseTime: responseTime,
lastCheckTimestamp: now,
timeOfLastFailure: status
? {
$cond: [{ $eq: [{ $ifNull: ["$timeOfLastFailure", 0] }, 0] }, now, "$timeOfLastFailure"],
}
: 0,
},
},
];
const updated = await MonitorStatsModel.findOneAndUpdate({ monitorId: objectId }, pipeline, {
upsert: true,
new: true,
setDefaultsOnInsert: true,
});
if (!updated) { if (!updated) {
throw new AppError({ message: "Monitor stats not found", status: 404 }); throw new AppError({ message: "Failed to apply check result to monitor stats", status: 500 });
} }
return this.toEntity(updated); return this.toEntity(updated);
}; };
@@ -1,6 +1,6 @@
import type { Pool } from "pg"; import type { Pool } from "pg";
import type { IMonitorStatsRepository } from "./IMonitorStatsRepository.js"; import type { IMonitorStatsRepository } from "./IMonitorStatsRepository.js";
import type { MonitorStats } from "@/types/monitorStats.js"; import type { MonitorStats, CheckResultInput } from "@/types/monitorStats.js";
import { AppError } from "@/utils/AppError.js"; import { AppError } from "@/utils/AppError.js";
interface MonitorStatsRow { interface MonitorStatsRow {
@@ -61,37 +61,60 @@ export class TimescaleMonitorStatsRepository implements IMonitorStatsRepository
return this.toEntity(row); return this.toEntity(row);
}; };
updateByMonitorId = async (monitorId: string, data: Omit<MonitorStats, "id" | "monitorId" | "createdAt" | "updatedAt">): Promise<MonitorStats> => { updateByMonitorId = async (monitorId: string, result: CheckResultInput): Promise<MonitorStats> => {
const result = await this.pool.query<MonitorStatsRow>( const { status, responseTime, now } = result;
`UPDATE monitor_stats SET const upDelta = status ? 1 : 0;
avg_response_time = $2, const downDelta = status ? 0 : 1;
max_response_time = $3, const nowTs = new Date(now);
total_checks = $4,
total_up_checks = $5, // Atomic upsert via INSERT ... ON CONFLICT DO UPDATE
total_down_checks = $6, const queryResult = await this.pool.query<MonitorStatsRow>(
uptime_percentage = $7, `INSERT INTO monitor_stats (
last_check_timestamp = $8, monitor_id,
last_response_time = $9, avg_response_time,
time_of_last_failure = $10, max_response_time,
total_checks,
total_up_checks,
total_down_checks,
uptime_percentage,
last_check_timestamp,
last_response_time,
time_of_last_failure
) VALUES (
$1,
$2,
$2,
1,
$3,
$4,
$3::float,
$5,
$2,
CASE WHEN $6::boolean THEN $5 ELSE NULL END
)
ON CONFLICT (monitor_id) DO UPDATE SET
total_checks = monitor_stats.total_checks + 1,
total_up_checks = monitor_stats.total_up_checks + $3,
total_down_checks = monitor_stats.total_down_checks + $4,
avg_response_time = (monitor_stats.avg_response_time * monitor_stats.total_checks + $2)
/ (monitor_stats.total_checks + 1),
uptime_percentage = (monitor_stats.total_up_checks + $3)::float
/ (monitor_stats.total_checks + 1),
max_response_time = GREATEST(monitor_stats.max_response_time, $2),
last_response_time = $2,
last_check_timestamp = $5,
time_of_last_failure = CASE
WHEN $6::boolean AND monitor_stats.time_of_last_failure IS NULL THEN $5
WHEN $6::boolean THEN monitor_stats.time_of_last_failure
ELSE NULL
END,
updated_at = NOW() updated_at = NOW()
WHERE monitor_id = $1 RETURNING ${COLUMNS}`,
RETURNING ${COLUMNS}`, [monitorId, responseTime, upDelta, downDelta, nowTs, status]
[
monitorId,
data.avgResponseTime,
data.maxResponseTime,
data.totalChecks,
data.totalUpChecks,
data.totalDownChecks,
data.uptimePercentage,
data.lastCheckTimestamp ? new Date(data.lastCheckTimestamp) : null,
data.lastResponseTime,
data.timeOfLastFailure ? new Date(data.timeOfLastFailure) : null,
]
); );
const row = result.rows[0]; const row = queryResult.rows[0];
if (!row) { if (!row) {
throw new AppError({ message: "Monitor stats not found", status: 404 }); throw new AppError({ message: "Failed to apply check result to monitor stats", status: 500 });
} }
return this.toEntity(row); return this.toEntity(row);
}; };
@@ -14,7 +14,6 @@ import type {
GameStatusPayload, GameStatusPayload,
GrpcStatusPayload, GrpcStatusPayload,
CheckSnapshot, CheckSnapshot,
MonitorStats,
CheckDiskInfo, CheckDiskInfo,
} from "@/types/index.js"; } from "@/types/index.js";
import { AppError } from "@/utils/AppError.js"; import { AppError } from "@/utils/AppError.js";
@@ -68,97 +67,11 @@ export class StatusService implements IStatusService {
async updateRunningStats(monitor: Monitor, networkResponse: MonitorStatusResponse) { async updateRunningStats(monitor: Monitor, networkResponse: MonitorStatusResponse) {
try { try {
const monitorId = monitor.id; await this.monitorStatsRepository.updateByMonitorId(monitor.id, {
const { responseTime, status } = networkResponse; status: networkResponse.status === true,
let existingStats: MonitorStats | null = null; responseTime: networkResponse.responseTime ?? 0,
existingStats = await this.monitorStatsRepository now: Date.now(),
.findByMonitorId(monitorId) });
.then((result) => result)
.catch(() => {
this.logger.debug({
service: SERVICE_NAME,
method: "updateRunningStats",
message: `No existing stats found for monitor ${monitorId}, initializing new stats.`,
});
return null;
});
let stats: Omit<MonitorStats, "id" | "monitorId" | "createdAt" | "updatedAt">;
if (!existingStats) {
// Initialize new stats
stats = {
avgResponseTime: 0,
maxResponseTime: 0,
totalChecks: 0,
totalUpChecks: 0,
totalDownChecks: 0,
uptimePercentage: 0,
lastResponseTime: 0,
lastCheckTimestamp: 0,
};
} else {
// Use existing stats (omit id, monitorId, createdAt, updatedAt)
stats = {
avgResponseTime: existingStats.avgResponseTime,
maxResponseTime: existingStats.maxResponseTime,
totalChecks: existingStats.totalChecks,
totalUpChecks: existingStats.totalUpChecks,
totalDownChecks: existingStats.totalDownChecks,
uptimePercentage: existingStats.uptimePercentage,
lastResponseTime: existingStats.lastResponseTime,
lastCheckTimestamp: existingStats.lastCheckTimestamp,
timeOfLastFailure: existingStats.timeOfLastFailure,
};
}
// Update stats
stats.totalChecks++;
// Last response time
stats.lastResponseTime = responseTime ?? 0;
// Max response time
if (responseTime && responseTime > stats.maxResponseTime) {
stats.maxResponseTime = responseTime;
}
// Avg response time:
let avgResponseTime = stats.avgResponseTime;
if (typeof responseTime !== "undefined" && responseTime !== null) {
if (avgResponseTime === 0) {
avgResponseTime = responseTime;
} else {
avgResponseTime = (avgResponseTime * (stats.totalChecks - 1) + responseTime) / stats.totalChecks;
}
}
stats.avgResponseTime = avgResponseTime;
// Total checks
if (status === true) {
stats.totalUpChecks++;
// Update the timeSinceLastFailure if needed
if (stats.timeOfLastFailure === 0) {
stats.timeOfLastFailure = new Date().getTime();
}
} else {
stats.totalDownChecks++;
stats.timeOfLastFailure = 0;
}
// Calculate uptime percentage
stats.uptimePercentage = stats.totalUpChecks / stats.totalChecks;
// latest check
stats.lastCheckTimestamp = new Date().getTime();
// Create or update
if (!existingStats) {
await this.monitorStatsRepository.create({ monitorId, ...stats });
} else {
await this.monitorStatsRepository.updateByMonitorId(monitorId, stats);
}
return true; return true;
} catch (error: unknown) { } catch (error: unknown) {
this.logger.error({ this.logger.error({
@@ -190,7 +103,14 @@ export class StatusService implements IStatusService {
const monitor = await this.monitorsRepository.findById(monitorId, teamId); const monitor = await this.monitorsRepository.findById(monitorId, teamId);
// Update running stats // Update running stats
this.updateRunningStats(monitor, statusResponse); const statsOk = await this.updateRunningStats(monitor, statusResponse);
if (!statsOk) {
this.logger.warn({
service: SERVICE_NAME,
method: "updateMonitorStatus",
message: `Stats update failed for monitor ${monitor.id}`,
});
}
monitor.statusWindow = monitor.statusWindow || []; monitor.statusWindow = monitor.statusWindow || [];
monitor.statusWindow.push(status); monitor.statusWindow.push(status);
+6
View File
@@ -1,3 +1,9 @@
export interface CheckResultInput {
status: boolean;
responseTime: number;
now: number;
}
export interface MonitorStats { export interface MonitorStats {
id: string; id: string;
monitorId: string; monitorId: string;
+29 -118
View File
@@ -126,144 +126,67 @@ describe("StatusService", () => {
// ── updateRunningStats ─────────────────────────────────────────────────── // ── updateRunningStats ───────────────────────────────────────────────────
describe("updateRunningStats", () => { describe("updateRunningStats", () => {
it("creates new stats when none exist", async () => { // The service now delegates the entire running-stats computation to the repository's
// atomic `updateByMonitorId`, so the service-level tests only verify forwarding and error
// handling. The math (running average, uptimePercentage, timeOfLastFailure state machine)
// is a repository-level concern and is exercised by the repository tests.
it("forwards a successful check to updateByMonitorId", async () => {
const { service, monitorStatsRepository } = createService(); const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockRejectedValue(new Error("not found")); (monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
(monitorStatsRepository.create as jest.Mock).mockResolvedValue({});
const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 50 })); const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 50 }));
expect(result).toBe(true); expect(result).toBe(true);
expect(monitorStatsRepository.create).toHaveBeenCalledWith( expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith(
"mon-1",
expect.objectContaining({ expect.objectContaining({
monitorId: "mon-1", status: true,
totalChecks: 1, responseTime: 50,
totalUpChecks: 1, now: expect.any(Number),
avgResponseTime: 50,
lastResponseTime: 50,
}) })
); );
}); });
it("updates existing stats for a successful check", async () => { it("forwards a failed check to updateByMonitorId", async () => {
const { service, monitorStatsRepository } = createService(); const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats());
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({}); (monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 110 })); const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse({ status: false, responseTime: 100 }));
expect(result).toBe(true); expect(result).toBe(true);
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith( expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ status: false, responseTime: 100 }));
"mon-1",
expect.objectContaining({
totalChecks: 11,
totalUpChecks: 10,
totalDownChecks: 1,
})
);
}); });
it("increments totalDownChecks and resets timeOfLastFailure on failure", async () => { it("passes 0 when responseTime is undefined", async () => {
const { service, monitorStatsRepository } = createService(); const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats());
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ status: false, responseTime: 100 }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith(
"mon-1",
expect.objectContaining({
totalDownChecks: 2,
timeOfLastFailure: 0,
})
);
});
it("sets timeOfLastFailure when status is up and it was previously 0", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ timeOfLastFailure: 0 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ status: true }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith(
"mon-1",
expect.objectContaining({
timeOfLastFailure: expect.any(Number),
})
);
const call = (monitorStatsRepository.updateByMonitorId as jest.Mock).mock.calls[0] as [string, Record<string, unknown>];
expect(call[1].timeOfLastFailure).toBeGreaterThan(0);
});
it("updates maxResponseTime when new response is higher", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ maxResponseTime: 200 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 300 }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ maxResponseTime: 300 }));
});
it("does not update maxResponseTime when new response is lower", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ maxResponseTime: 200 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 50 }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ maxResponseTime: 200 }));
});
it("initializes avgResponseTime when previous avg was 0", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ avgResponseTime: 0 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 75 }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ avgResponseTime: 75 }));
});
it("computes running average when avgResponseTime is nonzero", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ avgResponseTime: 100, totalChecks: 10 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 210 }));
const call = (monitorStatsRepository.updateByMonitorId as jest.Mock).mock.calls[0] as [string, Record<string, unknown>];
// (100 * 10 + 210) / 11 = 110
expect(call[1].avgResponseTime).toBe(110);
});
it("leaves avgResponseTime unchanged when responseTime is undefined", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ avgResponseTime: 100 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({}); (monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: undefined })); await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: undefined }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ avgResponseTime: 100 })); expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ responseTime: 0 }));
}); });
it("handles responseTime of 0 (falsy but defined)", async () => { it("forwards responseTime of 0 as 0 (falsy but defined)", async () => {
const { service, monitorStatsRepository } = createService(); const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats({ avgResponseTime: 100, maxResponseTime: 200 }));
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({}); (monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 0 })); await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 0 }));
const call = (monitorStatsRepository.updateByMonitorId as jest.Mock).mock.calls[0] as [string, Record<string, unknown>]; expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ responseTime: 0 }));
expect(call[1].lastResponseTime).toBe(0);
// responseTime 0 is falsy, so maxResponseTime stays unchanged
expect(call[1].maxResponseTime).toBe(200);
}); });
it("returns false and logs error when an exception is thrown", async () => { it("coerces a non-true status to false (e.g. undefined)", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockResolvedValue({});
await service.updateRunningStats(makeMonitor(), makeStatusResponse({ status: undefined as unknown as boolean }));
expect(monitorStatsRepository.updateByMonitorId).toHaveBeenCalledWith("mon-1", expect.objectContaining({ status: false }));
});
it("returns false and logs error when updateByMonitorId throws", async () => {
const { service, logger, monitorStatsRepository } = createService(); const { service, logger, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats());
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockRejectedValue(new Error("db write failed")); (monitorStatsRepository.updateByMonitorId as jest.Mock).mockRejectedValue(new Error("db write failed"));
const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse()); const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse());
@@ -280,7 +203,6 @@ describe("StatusService", () => {
it("logs error with 'Unknown error' for non-Error exceptions", async () => { it("logs error with 'Unknown error' for non-Error exceptions", async () => {
const { service, logger, monitorStatsRepository } = createService(); const { service, logger, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(makeExistingStats());
(monitorStatsRepository.updateByMonitorId as jest.Mock).mockRejectedValue("string error"); (monitorStatsRepository.updateByMonitorId as jest.Mock).mockRejectedValue("string error");
const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse()); const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse());
@@ -288,17 +210,6 @@ describe("StatusService", () => {
expect(result).toBe(false); expect(result).toBe(false);
expect(logger.error).toHaveBeenCalledWith(expect.objectContaining({ message: "Unknown error", stack: undefined })); expect(logger.error).toHaveBeenCalledWith(expect.objectContaining({ message: "Unknown error", stack: undefined }));
}); });
it("creates new stats when findByMonitorId resolves to null", async () => {
const { service, monitorStatsRepository } = createService();
(monitorStatsRepository.findByMonitorId as jest.Mock).mockResolvedValue(null);
(monitorStatsRepository.create as jest.Mock).mockResolvedValue({});
const result = await service.updateRunningStats(makeMonitor(), makeStatusResponse({ responseTime: 50, status: true }));
expect(result).toBe(true);
expect(monitorStatsRepository.create).toHaveBeenCalled();
});
}); });
// ── updateMonitorStatus ────────────────────────────────────────────────── // ── updateMonitorStatus ──────────────────────────────────────────────────