diff --git a/server/src/db/migration/0014_clearCheckRollups.ts b/server/src/db/migration/0014_clearCheckRollups.ts new file mode 100644 index 0000000000..07948187f1 --- /dev/null +++ b/server/src/db/migration/0014_clearCheckRollups.ts @@ -0,0 +1,15 @@ +import { CheckRollupModel } from "../../domain/check-rollups/check-rollup.model.js"; +import type { ILogger } from "@/utils/logger/logger.js"; + +export async function clearCheckRollups(logger: ILogger): Promise { + const SERVICE_NAME = "Migration:ClearCheckRollups"; + const log = logger.child({ service: SERVICE_NAME }); + + try { + const result = await CheckRollupModel.deleteMany({}); + log.info({ deletedCount: result.deletedCount }, "Cleared check rollups, the rollup job rebuilds them as daily rows"); + } catch (error) { + log.error({ err: error }, "Error clearing check rollups"); + throw error; + } +} diff --git a/server/src/db/migration/index.ts b/server/src/db/migration/index.ts index f49ed8abae..05cf89522d 100644 --- a/server/src/db/migration/index.ts +++ b/server/src/db/migration/index.ts @@ -12,6 +12,7 @@ import { slimRecentChecks } from "./0010_slimRecentChecks.js"; import { backfillMonitorProxyMode } from "./0011_backfillMonitorProxyMode.js"; import { migrateDockerMonitorUrls } from "./0012_migrateDockerMonitorUrls.js"; import { backfillStatusPageTimezone } from "./0013_backfillStatusPageTimezone.js"; +import { clearCheckRollups } from "./0014_clearCheckRollups.js"; import type { ILogger } from "@/utils/logger/logger.js"; type MigrationEntry = { @@ -33,6 +34,7 @@ const migrations: MigrationEntry[] = [ { name: "0011_backfillMonitorProxyMode", execute: backfillMonitorProxyMode }, { name: "0012_migrateDockerMonitorUrls", execute: migrateDockerMonitorUrls }, { name: "0013_backfillStatusPageTimezone", execute: backfillStatusPageTimezone }, + { name: "0014_clearCheckRollups", execute: clearCheckRollups }, ]; const runMigrations = async (logger: ILogger) => { diff --git a/server/src/domain/check-rollups/check-rollup.hardware.pipeline.ts b/server/src/domain/check-rollups/check-rollup.hardware.pipeline.ts index e410e45de5..011bfc9550 100644 --- a/server/src/domain/check-rollups/check-rollup.hardware.pipeline.ts +++ b/server/src/domain/check-rollups/check-rollup.hardware.pipeline.ts @@ -2,7 +2,7 @@ import { Types, type PipelineStage } from "mongoose"; import { DISK_COUNTERS, DISK_LEVELS, INTERFACE_COUNTERS, counterPairStages } from "@/domain/checks/check.hardware.pipeline.js"; import { EXCLUDE_DEGRADED_EGRESS_MATCH } from "@/domain/checks/check.query.js"; import { HARDWARE_COUNTER_MAX_GAP_INTERVALS } from "@/domain/checks/check.type.js"; -import { ROLLUP_BUCKET_MINUTES, type HardwareMonitorInterval } from "@/domain/check-rollups/check-rollup.type.js"; +import type { HardwareMonitorInterval } from "@/domain/check-rollups/check-rollup.type.js"; import { buildCoreRollupStages, type UnionWithStage } from "@/domain/check-rollups/check-rollup.pipeline.js"; import { MS_PER_SECOND } from "@/utils/time.js"; @@ -22,7 +22,7 @@ const countOf = (field: string) => ({ $sum: { $cond: [{ $isNumber: field }, 1, 0 const temperatures = { $ifNull: ["$cpu.temperature", []] }; const readingAt = { $arrayElemAt: ["$$reading", "$$sensor"] }; -const bucketStart = { $dateTrunc: { date: "$createdAt", unit: "minute", binSize: ROLLUP_BUCKET_MINUTES } }; +const bucketStart = { $dateTrunc: { date: "$createdAt", unit: "day" } }; export const buildHardwareLevelsRollupStages = (from: Date, to: Date, monitorIds?: Types.ObjectId[]): UnionWithStage[] => [ { diff --git a/server/src/domain/check-rollups/check-rollup.pipeline.ts b/server/src/domain/check-rollups/check-rollup.pipeline.ts index 706001d9c1..40f2dd141e 100644 --- a/server/src/domain/check-rollups/check-rollup.pipeline.ts +++ b/server/src/domain/check-rollups/check-rollup.pipeline.ts @@ -1,6 +1,5 @@ import type { PipelineStage, Types } from "mongoose"; import { ONLY_DEGRADED_EGRESS_MATCH } from "@/domain/checks/check.query.js"; -import { ROLLUP_BUCKET_MINUTES } from "@/domain/check-rollups/check-rollup.type.js"; import { UptimeDetailsSupportedTypes } from "@/domain/monitors/monitor.type.js"; export type UnionWithStage = Exclude; @@ -21,7 +20,7 @@ export const buildCoreRollupStages = (from: Date, to: Date, monitorIds?: Types.O $group: { _id: { monitorId: "$metadata.monitorId", - bucketStart: { $dateTrunc: { date: "$createdAt", unit: "minute", binSize: ROLLUP_BUCKET_MINUTES } }, + bucketStart: { $dateTrunc: { date: "$createdAt", unit: "day" } }, }, teamId: { $first: "$metadata.teamId" }, type: { $first: "$metadata.type" }, diff --git a/server/src/domain/check-rollups/check-rollup.type.ts b/server/src/domain/check-rollups/check-rollup.type.ts index ca55a20792..b9a151b30d 100644 --- a/server/src/domain/check-rollups/check-rollup.type.ts +++ b/server/src/domain/check-rollups/check-rollup.type.ts @@ -9,9 +9,9 @@ import type { checkRollupSumCountSchema, checkRollupUptimeSchema, } from "@/domain/check-rollups/check-rollup.schema.js"; -import { MS_PER_MINUTE } from "@/utils/time.js"; -export const ROLLUP_BUCKET_MINUTES = 15; -export const ROLLUP_BUCKET_MS = ROLLUP_BUCKET_MINUTES * MS_PER_MINUTE; +import { MS_PER_DAY, MS_PER_HOUR } from "@/utils/time.js"; +export const ROLLUP_BUCKET_MS = MS_PER_DAY; +export const ROLLUP_JOB_INTERVAL_MS = MS_PER_HOUR; export const floorToRollupBucket = (ms: number): number => Math.floor(ms / ROLLUP_BUCKET_MS) * ROLLUP_BUCKET_MS; export const ROLLUP_REROLL_HOURS = 2; diff --git a/server/src/worker/worker.job-scheduler.ts b/server/src/worker/worker.job-scheduler.ts index 64173cb5b4..17c1b2e0ee 100644 --- a/server/src/worker/worker.job-scheduler.ts +++ b/server/src/worker/worker.job-scheduler.ts @@ -8,7 +8,7 @@ import { WorkerJobsPagination, WorkerJobSummary, WorkerMetrics } from "@/worker/ import { WORKER_STALE_MS } from "@/domain/queue-workers/queue-worker.model.js"; import { QueueMode } from "@/domain/app-settings/app-settings.type.js"; import { ILogger } from "@/utils/logger/logger.js"; -import { ROLLUP_BUCKET_MINUTES } from "@/domain/check-rollups/check-rollup.type.js"; +import { ROLLUP_JOB_INTERVAL_MS } from "@/domain/check-rollups/check-rollup.type.js"; import { MS_PER_MINUTE, MS_PER_HOUR, MS_PER_DAY } from "@/utils/time.js"; export const POLL_MS = 250; // base poll interval while a loop is actively claiming work @@ -18,7 +18,6 @@ const CLEANUP_INTERVAL_MS = MS_PER_DAY; const TELEMETRY_INTERVAL_MS = MS_PER_DAY; const TELEMETRY_FIRST_RUN_JITTER_MS = MS_PER_HOUR; const CONNECT_HEARTBEAT_INTERVAL_MS = MS_PER_MINUTE; -const ROLLUP_INTERVAL_MS = ROLLUP_BUCKET_MINUTES * MS_PER_MINUTE; export class JobScheduler implements IJobScheduler { static SERVICE_NAME = SERVICE_NAME; @@ -299,7 +298,8 @@ export class JobScheduler implements IJobScheduler { await this.jobsRepository.upsertJobAndSchedule(this.toCleanupJob("cleanup-orphaned", now)); await this.jobsRepository.upsertJobAndSchedule(this.toCleanupJob("cleanup-retention", now)); - await this.jobsRepository.upsertJobAndSchedule(this.toGlobalRecurringJob("rollup-checks", ROLLUP_INTERVAL_MS, now)); + // Rollup job + await this.jobsRepository.upsertJobAndSchedule(this.toGlobalRecurringJob("rollup-checks", ROLLUP_JOB_INTERVAL_MS, now)); if (this.telemetryEnabled) { await this.jobsRepository.upsertJob(this.toTelemetryJob(now)); diff --git a/server/test/integration/checkRollupService.test.ts b/server/test/integration/checkRollupService.test.ts index 63f14e54f3..664dbe06e6 100644 --- a/server/test/integration/checkRollupService.test.ts +++ b/server/test/integration/checkRollupService.test.ts @@ -1,4 +1,4 @@ -import { afterAll, beforeAll, beforeEach, describe, expect, it } from "@jest/globals"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, jest } from "@jest/globals"; import mongoose from "mongoose"; import { MongoMemoryServer } from "mongodb-memory-server"; import { CheckModel } from "../../src/domain/checks/check.model.ts"; @@ -32,8 +32,6 @@ beforeEach(async () => { const MONITOR_ID = new mongoose.Types.ObjectId(); const TEAM_ID = new mongoose.Types.ObjectId(); -const MINUTE_MS = 60 * 1000; -const DAY_MS = 24 * 60 * MINUTE_MS; const seedCheckAt = (createdAt: Date) => CheckModel.create({ metadata: { monitorId: MONITOR_ID, teamId: TEAM_ID, type: "http" }, status: true, responseTime: 100, createdAt }); @@ -50,29 +48,50 @@ const totalRolledChecks = async () => { return rows.reduce((sum, row) => sum + row.totalChecks, 0); }; +const at = (iso: string) => new Date(iso); + +afterEach(() => { + jest.restoreAllMocks(); +}); + describe("CheckRollupService against MongoDB", () => { - it("backfills every closed bucket from the oldest check and leaves the open bucket out", async () => { + it("backfills every day that has ended from the oldest check and leaves today out", async () => { const service = setup(); - const now = Date.now(); - await seedCheckAt(new Date(now - 3 * DAY_MS)); - await seedCheckAt(new Date(now - 20 * MINUTE_MS)); - await seedCheckAt(new Date(now)); + jest.spyOn(Date, "now").mockReturnValue(at("2026-03-10T10:00:00.000Z").getTime()); + await seedCheckAt(at("2026-03-07T10:00:00.000Z")); + await seedCheckAt(at("2026-03-09T23:59:59.000Z")); + await seedCheckAt(at("2026-03-10T00:00:00.000Z")); await service.rollUpClosedBuckets(); - expect(await CheckRollupModel.countDocuments({ monitorId: MONITOR_ID })).toBe(2); + const rows = await CheckRollupModel.find({ monitorId: MONITOR_ID }).sort({ bucketStart: 1 }).lean(); + expect(rows.map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-07T00:00:00.000Z", "2026-03-09T00:00:00.000Z"]); expect(await totalRolledChecks()).toBe(2); }); - it("picks up a check that lands in an already rolled bucket", async () => { + it("picks up a check that lands in yesterday while today is less than two hours old", async () => { const service = setup(); - const now = Date.now(); - await seedCheckAt(new Date(now - 40 * MINUTE_MS)); + jest.spyOn(Date, "now").mockReturnValue(at("2026-03-10T00:30:00.000Z").getTime()); + await seedCheckAt(at("2026-03-09T12:00:00.000Z")); await service.rollUpClosedBuckets(); - await seedCheckAt(new Date(now - 40 * MINUTE_MS + 1000)); + await seedCheckAt(at("2026-03-09T23:59:00.000Z")); await service.rollUpClosedBuckets(); + expect(await CheckRollupModel.countDocuments({ monitorId: MONITOR_ID })).toBe(1); expect(await totalRolledChecks()).toBe(2); }); + + it("leaves yesterday's row alone once today is two hours old", async () => { + const service = setup(); + const now = jest.spyOn(Date, "now").mockReturnValue(at("2026-03-10T00:30:00.000Z").getTime()); + await seedCheckAt(at("2026-03-09T12:00:00.000Z")); + await service.rollUpClosedBuckets(); + + now.mockReturnValue(at("2026-03-10T02:30:00.000Z").getTime()); + await seedCheckAt(at("2026-03-09T23:59:00.000Z")); + await service.rollUpClosedBuckets(); + + expect(await totalRolledChecks()).toBe(1); + }); }); diff --git a/server/test/integration/checkRollupsHardware.test.ts b/server/test/integration/checkRollupsHardware.test.ts index 43d322353d..7aea74075c 100644 --- a/server/test/integration/checkRollupsHardware.test.ts +++ b/server/test/integration/checkRollupsHardware.test.ts @@ -28,8 +28,9 @@ const TEAM_ID = new mongoose.Types.ObjectId(); const MONITOR_ID = new mongoose.Types.ObjectId(); const OTHER_MONITOR_ID = new mongoose.Types.ObjectId(); -const BUCKET_START = new Date("2026-03-10T10:00:00.000Z"); +const BUCKET_START = new Date("2026-03-10T00:00:00.000Z"); const at = (minutes: number, seconds = 0) => new Date(BUCKET_START.getTime() + minutes * 60_000 + seconds * 1000); +const day = (days: number, minutes = 0, seconds = 0) => at(days * 24 * 60 + minutes, seconds); const reading = (cpuUsage: number | null, memoryUsage: number | null, temperature: (number | null)[] | null = [40, 50]) => ({ cpu: { usage_percent: cpuUsage, current_frequency: 3000, temperature }, @@ -106,7 +107,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { await seedCheck({ ...reading(0.2, 0.4), createdAt: at(1) }); await seedCheck({ ...reading(0.6, 0.5), createdAt: at(2) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.cpuUsage.sum).toBeCloseTo(0.8); @@ -125,7 +126,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { await seedCheck({ ...reading(0.2, 0.4), createdAt: at(1) }); await seedCheck({ ...reading(null, 0.6), createdAt: at(2) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.cpuUsage).toEqual({ sum: 0.2, count: 1 }); @@ -139,7 +140,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { await seedCheck({ ...reading(0.2, 0.4, [20, null]), createdAt: at(3) }); await seedCheck({ ...reading(0.2, 0.4, null), createdAt: at(4) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.temperature).toEqual([ @@ -153,7 +154,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4, null) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.temperature).toEqual([]); @@ -163,7 +164,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ status: false, statusCode: 5000 }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row).toMatchObject({ totalChecks: 1, upChecks: 0, downChecks: 1 }); @@ -175,7 +176,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { await seedCheck({ ...reading(0.2, 0.4), createdAt: at(1) }); await seedCheck({ ...reading(0.9, 0.9), createdAt: at(2), egressStatus: "degraded" }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.cpuUsage).toEqual({ sum: 0.2, count: 1 }); @@ -185,10 +186,10 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { it("writes one block per monitor per bucket", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), createdAt: at(1) }); - await seedCheck({ ...reading(0.4, 0.4), createdAt: at(16) }); + await seedCheck({ ...reading(0.4, 0.4), createdAt: day(1, 1) }); await seedCheck({ ...reading(0.8, 0.4), createdAt: at(1) }, { monitorId: OTHER_MONITOR_ID }); - await repo.rollUp(at(0), at(30)); + await repo.rollUp(at(0), day(2)); const rows = await findRows(); const [other] = await findRows(OTHER_MONITOR_ID); @@ -200,7 +201,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({}, { type: "http" }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.totalChecks).toBe(1); @@ -210,11 +211,11 @@ describe("MongoCheckRollupsRepository.rollUp hardware block", () => { it("is idempotent and leaves the core fields as the core pipeline wrote them", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), createdAt: at(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); await seedCheck({ ...reading(0.6, 0.4), createdAt: at(2) }); - await repo.rollUp(at(0), at(15)); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); + await repo.rollUp(at(0), day(1)); const rows = await findRows(); expect(rows).toHaveLength(1); @@ -234,7 +235,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { await seedCheck({ disk: [disk(...ROOT, { usage_percent: 0.2, used_bytes: 200 }), disk(...DATA, { usage_percent: 0.9 })], createdAt: at(1) }); await seedCheck({ disk: [disk(...DATA, { usage_percent: 0.7 }), disk(...ROOT, { usage_percent: 0.4, used_bytes: 400 })], createdAt: at(2) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [disks] = await findDisks(); expect(disks.map((entry) => [entry.device, entry.mountpoint])).toEqual([ @@ -252,7 +253,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { await seedCheck({ disk: [disk(...ROOT, { read_bytes: 1600, write_time: 800 })], createdAt: at(2) }); await seedCheck({ disk: [disk(...ROOT, { read_bytes: 1900, write_time: 800 })], createdAt: at(3) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [disks] = await findDisks(); expect(disks[0]).toMatchObject({ @@ -267,7 +268,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { await seedCheck({ disk: [disk(...ROOT, { read_bytes: 900000 })], createdAt: at(1) }); await seedCheck({ disk: [disk(...ROOT, { read_bytes: 600 })], createdAt: at(2) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [disks] = await findDisks(); expect(disks[0]?.readBytes).toEqual({ change: 600, seconds: 60 }); @@ -281,7 +282,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { await seedCheck({ disk: [disk(...ROOT, { read_bytes: 6000 })], createdAt: at(11) }, { monitorId }); } - await repo.rollUp(at(0), at(15), [...INTERVALS, slow]); + await repo.rollUp(at(0), day(1), [...INTERVALS, slow]); const [fast] = await findDisks(MONITOR_ID); const [slower] = await findDisks(OTHER_MONITOR_ID); @@ -291,10 +292,10 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { it("gives a pair that spans two buckets to the bucket of the later check", async () => { const repo = new MongoCheckRollupsRepository(); - await seedCheck({ disk: [disk(...ROOT, { read_bytes: 0 })], createdAt: at(14, 30) }); - await seedCheck({ disk: [disk(...ROOT, { read_bytes: 600 })], createdAt: at(15, 30) }); + await seedCheck({ disk: [disk(...ROOT, { read_bytes: 0 })], createdAt: day(0, 1439, 30) }); + await seedCheck({ disk: [disk(...ROOT, { read_bytes: 600 })], createdAt: day(1, 0, 30) }); - await repo.rollUp(at(0), at(30), INTERVALS); + await repo.rollUp(at(0), day(2), INTERVALS); const [first, second] = await findDisks(); expect(first?.[0]?.readBytes).toEqual({ change: 0, seconds: 0 }); @@ -303,13 +304,13 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { it("pairs the first check in the window with the one just before it, without rolling up the earlier bucket", async () => { const repo = new MongoCheckRollupsRepository(); - await seedCheck({ disk: [disk(...ROOT, { read_bytes: 0 })], createdAt: at(14, 30) }); - await seedCheck({ disk: [disk(...ROOT, { read_bytes: 600 })], createdAt: at(15, 30) }); + await seedCheck({ disk: [disk(...ROOT, { read_bytes: 0 })], createdAt: day(0, 1439, 30) }); + await seedCheck({ disk: [disk(...ROOT, { read_bytes: 600 })], createdAt: day(1, 0, 30) }); - await repo.rollUp(at(15), at(30), INTERVALS); + await repo.rollUp(day(1), day(2), INTERVALS); const rows = await findRows(); - expect(rows.map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-10T10:15:00.000Z"]); + expect(rows.map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-11T00:00:00.000Z"]); expect(rows[0]?.hardware?.disks?.[0]?.readBytes).toEqual({ change: 600, seconds: 60 }); }); @@ -319,7 +320,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { await seedCheck({ disk: [disk(...ROOT, noIo)], createdAt: at(1) }); await seedCheck({ disk: [disk(...ROOT, noIo)], createdAt: at(2) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [disks] = await findDisks(); expect(disks[0]).toMatchObject({ readBytes: { change: 0, seconds: 0 }, usage: { count: 2 } }); @@ -329,8 +330,8 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), disk: [disk(...ROOT)], createdAt: at(1) }); - await repo.rollUp(at(0), at(15), INTERVALS); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [row] = await findRows(); expect(row?.hardware?.cpuUsage).toEqual({ sum: 0.2, count: 1 }); @@ -343,9 +344,9 @@ describe("MongoCheckRollupsRepository.rollUp hardware disks", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), disk: [disk(...ROOT)], createdAt: at(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [withoutIntervals] = await findRows(); - await repo.rollUp(at(0), at(15), [{ monitorId: OTHER_MONITOR_ID.toString(), intervalMs: MINUTE_MS }]); + await repo.rollUp(at(0), day(1), [{ monitorId: OTHER_MONITOR_ID.toString(), intervalMs: MINUTE_MS }]); const [notListed] = await findRows(); expect(withoutIntervals?.hardware?.cpuUsage.count).toBe(1); @@ -365,7 +366,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { await seedCheck({ net: [iface("eth0", { bytes_sent: 1000, packets_recv: 10, err_in: 5 }), iface("lo")], createdAt: at(1) }); await seedCheck({ net: [iface("lo", { bytes_sent: 60 }), iface("eth0", { bytes_sent: 1600, packets_recv: 130, err_in: 8 })], createdAt: at(2) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [interfaces] = await findInterfaces(); expect(interfaces.map((entry) => entry.name)).toEqual(["eth0", "lo"]); @@ -383,7 +384,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { await seedCheck({ net: [iface("eth0", { bytes_sent: 900000 })], createdAt: at(1) }); await seedCheck({ net: [iface("eth0", { bytes_sent: 600 })], createdAt: at(2) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [interfaces] = await findInterfaces(); expect(interfaces[0]?.bytesSent).toEqual({ change: 600, seconds: 60 }); @@ -394,7 +395,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { await seedCheck({ net: [iface("eth0", { bytes_sent: 0 })], createdAt: at(1) }); await seedCheck({ net: [iface("eth0", { bytes_sent: 6000 })], createdAt: at(11) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [interfaces] = await findInterfaces(); expect(interfaces[0]?.bytesSent).toEqual({ change: 0, seconds: 0 }); @@ -406,7 +407,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { await seedCheck({ ...reading(0.2, 0.4), createdAt: at(2) }); await seedCheck({ net: [iface("eth0", { bytes_sent: 1200 })], createdAt: at(3) }); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [interfaces] = await findInterfaces(); expect(interfaces[0]?.bytesSent).toEqual({ change: 1200, seconds: 120 }); @@ -414,10 +415,10 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { it("pairs the first check in the window with the one just before it", async () => { const repo = new MongoCheckRollupsRepository(); - await seedCheck({ net: [iface("eth0", { bytes_sent: 0 })], createdAt: at(14, 30) }); - await seedCheck({ net: [iface("eth0", { bytes_sent: 600 })], createdAt: at(15, 30) }); + await seedCheck({ net: [iface("eth0", { bytes_sent: 0 })], createdAt: day(0, 1439, 30) }); + await seedCheck({ net: [iface("eth0", { bytes_sent: 600 })], createdAt: day(1, 0, 30) }); - await repo.rollUp(at(15), at(30), INTERVALS); + await repo.rollUp(day(1), day(2), INTERVALS); const rows = await findRows(); expect(rows).toHaveLength(1); @@ -428,8 +429,8 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), disk: [disk(...ROOT)], net: [iface("eth0")], createdAt: at(1) }); - await repo.rollUp(at(0), at(15), INTERVALS); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [row] = await findRows(); expect(row?.hardware?.cpuUsage).toEqual({ sum: 0.2, count: 1 }); @@ -441,7 +442,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware interfaces", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), net: [iface("eth0")], createdAt: at(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.cpuUsage.count).toBe(1); @@ -462,9 +463,9 @@ describe("MongoCheckRollupsRepository.rollUp hardware raid", () => { await seedCheck({ raid: [raidArray("/dev/md0")], createdAt: at(1) }); await seedCheck({ raid: [raidArray("/dev/md0", { state: "active", degraded_disks: 1, sync_action: "recover" })], createdAt: at(2) }); await seedCheck({ raid: [raidArray("/dev/md0", { state: "active", degraded_disks: 1, sync_action: "recover" })], createdAt: at(3) }); - await seedCheck({ raid: [raidArray("/dev/md0")], createdAt: at(16) }); + await seedCheck({ raid: [raidArray("/dev/md0")], createdAt: day(1, 1) }); - await repo.rollUp(at(0), at(30)); + await repo.rollUp(at(0), day(2)); const [first, second] = await findRaid(); expect(first).toEqual([{ device: "/dev/md0", states: ["active", "clean"], syncActions: ["idle", "recover"], maxDegradedDisks: 1 }]); @@ -476,7 +477,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware raid", () => { await seedCheck({ raid: [raidArray("/dev/md1", { state: "inactive" }), raidArray("/dev/md0")], createdAt: at(1) }); await seedCheck({ raid: [raidArray("/dev/md0"), raidArray("/dev/md1", { state: "inactive" })], createdAt: at(2) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [arrays] = await findRaid(); expect(arrays?.map((array) => [array.device, array.states])).toEqual([ @@ -489,7 +490,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware raid", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ raid: [raidArray("/dev/md2", { level: "raid0", degraded_disks: null, sync_action: null })], createdAt: at(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [arrays] = await findRaid(); expect(arrays).toEqual([{ device: "/dev/md2", states: ["clean"], syncActions: [], maxDegradedDisks: null }]); @@ -499,7 +500,7 @@ describe("MongoCheckRollupsRepository.rollUp hardware raid", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), raid: [], createdAt: at(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.hardware?.cpuUsage.count).toBe(1); @@ -510,10 +511,10 @@ describe("MongoCheckRollupsRepository.rollUp hardware raid", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ ...reading(0.2, 0.4), disk: [disk(...ROOT)], net: [iface("eth0")], raid: [raidArray("/dev/md0")], createdAt: at(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [withoutIntervals] = await findRows(); - await repo.rollUp(at(0), at(15), INTERVALS); - await repo.rollUp(at(0), at(15), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); + await repo.rollUp(at(0), day(1), INTERVALS); const [row] = await findRows(); expect(withoutIntervals?.hardware?.raid).toHaveLength(1); diff --git a/server/test/integration/checkRollupsHardwareRead.test.ts b/server/test/integration/checkRollupsHardwareRead.test.ts index 3f3963301c..9ece1dffe9 100644 --- a/server/test/integration/checkRollupsHardwareRead.test.ts +++ b/server/test/integration/checkRollupsHardwareRead.test.ts @@ -34,7 +34,7 @@ const TEAM_ID = new mongoose.Types.ObjectId(); const MINUTE_MS = 60 * 1000; const HOUR_MS = 60 * MINUTE_MS; const DAY_MS = 24 * HOUR_MS; -const BUCKET_MS = 15 * MINUTE_MS; +const BUCKET_MS = DAY_MS; const INTERVAL_MS = MINUTE_MS; const INTERVALS = [{ monitorId: MONITOR_ID.toString(), intervalMs: INTERVAL_MS }]; @@ -112,7 +112,7 @@ const seedHistory = async () => { }; describe("MongoCheckRollupsRepository.findHardwareMetrics", () => { - it.each(["day", "week", "month"] as const)("returns what the raw read returns for the %s range", async (dateRange) => { + it.each(["week", "month"] as const)("returns what the raw read returns for the %s range", async (dateRange) => { const { rollUpEverything, readRollups, readRaw } = setup(); await seedHistory(); await rollUpEverything(); @@ -172,7 +172,7 @@ describe("MongoCheckRollupsRepository.findHardwareMetrics", () => { it("counts a counter pair across the start of the raw tail once", async () => { const { rollUpEverything, readRollups, readRaw } = setup(); - const sinceRawTailStart = Date.now() - (Math.floor(Date.now() / BUCKET_MS) * BUCKET_MS - 2 * HOUR_MS); + const sinceRawTailStart = Date.now() - Math.floor((Date.now() - 2 * HOUR_MS) / BUCKET_MS) * BUCKET_MS; await seedCheck(sinceRawTailStart + 2 * MINUTE_MS, reading(0.2, 0.3, [40, 50], 0)); await seedCheck(sinceRawTailStart + MINUTE_MS, reading(0.2, 0.3, [40, 50], 600)); await seedCheck(sinceRawTailStart - MINUTE_MS + 1000, reading(0.2, 0.3, [40, 50], 1800)); @@ -185,12 +185,12 @@ describe("MongoCheckRollupsRepository.findHardwareMetrics", () => { expect(rounded(fromRollups.disks)).toEqual(rounded(fromRaw.disks)); }); - it("reads the last two hours from raw checks, including checks that are not rolled up yet", async () => { + it("reads today from raw checks", async () => { const { readRollups } = setup(); await seedCheck(30 * MINUTE_MS, reading(0.2, 0.3)); await seedCheck(MINUTE_MS, reading(0.6, 0.5)); - const result = await readRollups("day"); + const result = await readRollups("week"); expect(result.checks).toEqual({ total: 2, up: 2 }); expect(result.buckets.reduce((sum, bucket) => sum + (bucket.cpu.usage ?? 0), 0)).toBeGreaterThan(0); diff --git a/server/test/integration/checkRollupsRepository.test.ts b/server/test/integration/checkRollupsRepository.test.ts index 7ca722d62b..acc2769d2a 100644 --- a/server/test/integration/checkRollupsRepository.test.ts +++ b/server/test/integration/checkRollupsRepository.test.ts @@ -29,8 +29,9 @@ const OTHER_TEAM_ID = new mongoose.Types.ObjectId(); const MONITOR_ID = new mongoose.Types.ObjectId(); const OTHER_MONITOR_ID = new mongoose.Types.ObjectId(); -const BUCKET_START = new Date("2026-03-10T10:00:00.000Z"); +const BUCKET_START = new Date("2026-03-10T00:00:00.000Z"); const at = (minutes: number, seconds = 0) => new Date(BUCKET_START.getTime() + minutes * 60_000 + seconds * 1000); +const day = (days: number, minutes = 0, seconds = 0) => at(days * 24 * 60 + minutes, seconds); const seedCheck = (overrides: Record = {}, metadata: Record = {}) => CheckModel.create({ @@ -44,17 +45,17 @@ const seedCheck = (overrides: Record = {}, metadata: Record CheckRollupModel.find({ monitorId }).sort({ bucketStart: 1 }).lean(); describe("MongoCheckRollupsRepository.rollUp", () => { - it("writes one row per monitor per 15-minute bucket", async () => { + it("writes one row per monitor per UTC day", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ createdAt: at(0) }); - await seedCheck({ createdAt: at(14, 59) }); - await seedCheck({ createdAt: at(15) }); + await seedCheck({ createdAt: day(0, 1439, 59) }); + await seedCheck({ createdAt: day(1) }); await seedCheck({ createdAt: at(1) }, { monitorId: OTHER_MONITOR_ID }); - await repo.rollUp(at(0), at(30)); + await repo.rollUp(at(0), day(2)); const rows = await findRows(); - expect(rows.map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-10T10:00:00.000Z", "2026-03-10T10:15:00.000Z"]); + expect(rows.map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-10T00:00:00.000Z", "2026-03-11T00:00:00.000Z"]); expect(rows.map((row) => row.totalChecks)).toEqual([2, 1]); expect(rows[0]).toMatchObject({ monitorId: MONITOR_ID, teamId: TEAM_ID, type: "http" }); expect(await findRows(OTHER_MONITOR_ID)).toHaveLength(1); @@ -63,13 +64,13 @@ describe("MongoCheckRollupsRepository.rollUp", () => { it("treats the window as half-open", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ createdAt: at(0) }); - await seedCheck({ createdAt: at(15) }); + await seedCheck({ createdAt: day(1) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const rows = await findRows(); expect(rows).toHaveLength(1); - expect(rows[0]?.bucketStart.toISOString()).toBe("2026-03-10T10:00:00.000Z"); + expect(rows[0]?.bucketStart.toISOString()).toBe("2026-03-10T00:00:00.000Z"); }); it("splits up, down and degraded checks and keeps degraded checks out of every sum", async () => { @@ -79,7 +80,7 @@ describe("MongoCheckRollupsRepository.rollUp", () => { await seedCheck({ status: false, responseTime: 5000 }); await seedCheck({ status: false, responseTime: 9000, egressStatus: "degraded" }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row).toMatchObject({ @@ -100,7 +101,7 @@ describe("MongoCheckRollupsRepository.rollUp", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ status: false, egressStatus: "degraded" }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row).toMatchObject({ totalChecks: 0, upChecks: 0, downChecks: 0, degradedChecks: 1, responseTimeSum: 0, responseTimeCount: 0 }); @@ -111,7 +112,7 @@ describe("MongoCheckRollupsRepository.rollUp", () => { await seedCheck({ responseTime: 100 }); await seedCheck({ responseTime: undefined }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row).toMatchObject({ totalChecks: 2, upChecks: 2, responseTimeSum: 100, responseTimeCount: 1, upResponseTimeCount: 1 }); @@ -122,7 +123,7 @@ describe("MongoCheckRollupsRepository.rollUp", () => { await seedCheck({ timings: { start: 1, phases: { dns: 10, tcp: 20, tls: 30, request: 8, firstByte: 40, download: 6 } } }); await seedCheck(); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row?.totalChecks).toBe(2); @@ -133,7 +134,7 @@ describe("MongoCheckRollupsRepository.rollUp", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({}, { type }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [row] = await findRows(); expect(row).toMatchObject({ type, totalChecks: 1 }); @@ -143,12 +144,12 @@ describe("MongoCheckRollupsRepository.rollUp", () => { it("is idempotent and picks up checks added since the last run", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck(); - await repo.rollUp(at(0), at(15)); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); + await repo.rollUp(at(0), day(1)); expect(await findRows()).toHaveLength(1); await seedCheck({ createdAt: at(2) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const rows = await findRows(); expect(rows).toHaveLength(1); @@ -159,12 +160,12 @@ describe("MongoCheckRollupsRepository.rollUp", () => { const repo = new MongoCheckRollupsRepository(); await seedCheck(); const before = Date.now(); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [first] = await findRows(); expect(first?.updatedAt.getTime()).toBeGreaterThanOrEqual(before - 1000); await new Promise((resolve) => setTimeout(resolve, 50)); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const [second] = await findRows(); expect(second?.updatedAt.getTime()).toBeGreaterThan(first?.updatedAt.getTime() ?? 0); @@ -173,11 +174,11 @@ describe("MongoCheckRollupsRepository.rollUp", () => { it("keeps fields it does not write when it re-rolls a row", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck(); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); await CheckRollupModel.collection.updateOne({ monitorId: MONITOR_ID }, { $set: { unwritten: { value: 5 } } }); await seedCheck({ createdAt: at(2) }); - await repo.rollUp(at(0), at(15)); + await repo.rollUp(at(0), day(1)); const row = await CheckRollupModel.collection.findOne({ monitorId: MONITOR_ID }); expect(row?.totalChecks).toBe(2); @@ -195,21 +196,21 @@ describe("MongoCheckRollupsRepository.findLatestBucketStart", () => { it("returns the newest bucket across all monitors", async () => { const repo = new MongoCheckRollupsRepository(); await seedCheck({ createdAt: at(1) }); - await seedCheck({ createdAt: at(31) }, { monitorId: OTHER_MONITOR_ID }); - await repo.rollUp(at(0), at(45)); + await seedCheck({ createdAt: day(2, 1) }, { monitorId: OTHER_MONITOR_ID }); + await repo.rollUp(at(0), day(3)); const latest = await repo.findLatestBucketStart(); - expect(latest?.toISOString()).toBe("2026-03-10T10:30:00.000Z"); + expect(latest?.toISOString()).toBe("2026-03-12T00:00:00.000Z"); }); }); describe("MongoCheckRollupsRepository deletes", () => { const seedTwoMonitors = async (repo: MongoCheckRollupsRepository) => { await seedCheck({ createdAt: at(1) }); - await seedCheck({ createdAt: at(16) }); + await seedCheck({ createdAt: day(1, 1) }); await seedCheck({ createdAt: at(1) }, { monitorId: OTHER_MONITOR_ID, teamId: OTHER_TEAM_ID }); - await repo.rollUp(at(0), at(30)); + await repo.rollUp(at(0), day(2)); }; it("deletes every row of one monitor", async () => { @@ -246,10 +247,10 @@ describe("MongoCheckRollupsRepository deletes", () => { const repo = new MongoCheckRollupsRepository(); await seedTwoMonitors(repo); - const deleted = await repo.deleteOlderThan(at(15)); + const deleted = await repo.deleteOlderThan(day(1)); expect(deleted).toBe(2); - expect((await findRows()).map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-10T10:15:00.000Z"]); + expect((await findRows()).map((row) => row.bucketStart.toISOString())).toEqual(["2026-03-11T00:00:00.000Z"]); expect(await findRows(OTHER_MONITOR_ID)).toHaveLength(0); }); diff --git a/server/test/integration/checkRollupsUptimeRead.test.ts b/server/test/integration/checkRollupsUptimeRead.test.ts index 6849c7812b..9482682fe8 100644 --- a/server/test/integration/checkRollupsUptimeRead.test.ts +++ b/server/test/integration/checkRollupsUptimeRead.test.ts @@ -35,7 +35,7 @@ const TEAM_ID = new mongoose.Types.ObjectId(); const MINUTE_MS = 60 * 1000; const HOUR_MS = 60 * MINUTE_MS; const DAY_MS = 24 * HOUR_MS; -const BUCKET_MS = 15 * MINUTE_MS; +const BUCKET_MS = DAY_MS; const PHASES = { dns: 10, tcp: 20, tls: 30, request: 8, firstByte: 40, download: 6 }; const seedCheck = (ageMs: number, overrides: Record = {}, monitorId = MONITOR_ID) => @@ -54,7 +54,8 @@ const setup = () => { const readRollups = (dateRange: DateRange) => rollups.findUptimeDateRange(MONITOR_ID.toString(), "http", dateRange); const readRaw = async (dateRange: DateRange) => (await checks.findByDateRangeAndMonitorId(MONITOR_ID.toString(), dateRange, { type: "http" })) as UptimeChecksResult; - return { rollUpEverything, readRollups, readRaw }; + const rollUpIncludingToday = () => rollups.rollUp(new Date(Date.now() - 400 * DAY_MS), new Date(Date.now() + DAY_MS)); + return { rollUpEverything, rollUpIncludingToday, readRollups, readRaw }; }; const rounded = (value: unknown): unknown => { @@ -78,7 +79,7 @@ const seedHistory = async () => { }; describe("MongoCheckRollupsRepository.findUptimeDateRange", () => { - it.each(["day", "week", "month", "year", "all"] as const)("returns the same result as the raw query for the %s range", async (dateRange) => { + it.each(["week", "month", "year", "all"] as const)("returns the same result as the raw query for the %s range", async (dateRange) => { const { rollUpEverything, readRollups, readRaw } = setup(); await seedHistory(); await rollUpEverything(); @@ -90,23 +91,36 @@ describe("MongoCheckRollupsRepository.findUptimeDateRange", () => { expect(rounded(fromRollups)).toEqual(rounded(fromRaw)); }); - it("reads the last two hours from raw checks when they have not been rolled up", async () => { + it("reads days that have ended from rollup rows, not from raw checks", async () => { + const { rollUpEverything, readRollups, readRaw } = setup(); + await seedHistory(); + await rollUpEverything(); + const fromRaw = await readRaw("month"); + await CheckModel.deleteMany({ createdAt: { $lt: new Date(Date.now() - 2 * DAY_MS) } }); + + const fromRollups = await readRollups("month"); + + expect(fromRollups.groupedChecks.length).toBeGreaterThan(2); + expect(rounded(fromRollups)).toEqual(rounded(fromRaw)); + }); + + it("reads today from raw checks", async () => { const { readRollups } = setup(); await seedCheck(30 * MINUTE_MS); await seedCheck(1000, { status: false }); - const result = await readRollups("day"); + const result = await readRollups("week"); expect(result.groupedChecks.reduce((sum, bucket) => sum + bucket.totalChecks, 0)).toBe(2); expect(result.uptimePercentage).toBe(0.5); }); - it("does not count a bucket twice when it is rolled up and inside the raw tail", async () => { - const { rollUpEverything, readRollups } = setup(); + it("does not count today twice when it has a rollup row", async () => { + const { rollUpIncludingToday, readRollups } = setup(); await seedCheck(30 * MINUTE_MS); - await rollUpEverything(); + await rollUpIncludingToday(); - const result = await readRollups("day"); + const result = await readRollups("week"); expect(result.groupedChecks.reduce((sum, bucket) => sum + bucket.totalChecks, 0)).toBe(1); }); diff --git a/server/test/integration/clearCheckRollups.test.ts b/server/test/integration/clearCheckRollups.test.ts new file mode 100644 index 0000000000..76c7069a65 --- /dev/null +++ b/server/test/integration/clearCheckRollups.test.ts @@ -0,0 +1,62 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it, jest } from "@jest/globals"; +import mongoose from "mongoose"; +import { MongoMemoryServer } from "mongodb-memory-server"; +import { clearCheckRollups } from "../../src/db/migration/0014_clearCheckRollups.ts"; +import { CheckRollupModel } from "../../src/domain/check-rollups/check-rollup.model.ts"; + +let mongod: MongoMemoryServer; + +beforeAll(async () => { + mongod = await MongoMemoryServer.create(); + await mongoose.connect(mongod.getUri()); + await CheckRollupModel.init(); +}, 120_000); + +afterAll(async () => { + await mongoose.disconnect(); + await mongod.stop(); +}); + +beforeEach(async () => { + await CheckRollupModel.deleteMany({}); +}); + +const logger = { + child: jest.fn().mockReturnThis(), + info: jest.fn(), + error: jest.fn(), +} as any; + +const MONITOR_ID = new mongoose.Types.ObjectId(); +const TEAM_ID = new mongoose.Types.ObjectId(); + +const seedRow = (bucketStart: string, extra: Record = {}) => + CheckRollupModel.collection.insertOne({ + monitorId: MONITOR_ID, + teamId: TEAM_ID, + type: "http", + bucketStart: new Date(bucketStart), + totalChecks: 15, + upChecks: 15, + updatedAt: new Date(), + ...extra, + }); + +describe("0014_clearCheckRollups", () => { + it("deletes every rollup row, whatever its bucket", async () => { + await seedRow("2026-03-10T00:00:00.000Z"); + await seedRow("2026-03-10T10:15:00.000Z"); + await seedRow("2026-03-10T10:30:00.000Z", { bucketMinutes: 15 }); + + await clearCheckRollups(logger); + + expect(await CheckRollupModel.countDocuments()).toBe(0); + }); + + it("does nothing on an empty collection and can run twice", async () => { + await clearCheckRollups(logger); + await clearCheckRollups(logger); + + expect(await CheckRollupModel.countDocuments()).toBe(0); + }); +}); diff --git a/server/test/unit/services/checkRollupService.test.ts b/server/test/unit/services/checkRollupService.test.ts index 612eaca9b3..9c37437098 100644 --- a/server/test/unit/services/checkRollupService.test.ts +++ b/server/test/unit/services/checkRollupService.test.ts @@ -2,11 +2,14 @@ import { afterEach, describe, expect, it, jest } from "@jest/globals"; import { CheckRollupService } from "../../../src/domain/check-rollups/check-rollup.service.ts"; const NOW = new Date("2026-03-10T10:07:30.000Z"); -const CURRENT_BUCKET_START = "2026-03-10T10:00:00.000Z"; +const TODAY = "2026-03-10T00:00:00.000Z"; +const YESTERDAY = "2026-03-09T00:00:00.000Z"; -const setup = (options: { latest?: Date; oldest?: Date; checkTTL?: number; monitors?: { id: string; type: string; interval: number }[] } = {}) => { +const setup = ( + options: { now?: Date; latest?: Date; oldest?: Date; checkTTL?: number; monitors?: { id: string; type: string; interval: number }[] } = {} +) => { jest.useFakeTimers(); - jest.setSystemTime(NOW); + jest.setSystemTime(options.now ?? NOW); const checkRollupsRepository = { rollUp: jest.fn().mockResolvedValue(undefined), findLatestBucketStart: jest.fn().mockResolvedValue(options.latest ?? null), @@ -38,44 +41,71 @@ describe("CheckRollupService.rollUpClosedBuckets", () => { expect(checkRollupsRepository.rollUp).not.toHaveBeenCalled(); }); - it("backfills from the oldest check's bucket in 24-hour chunks up to the open bucket", async () => { + it("backfills from the oldest check's day, one day per call, up to the start of today", async () => { const { service, windows } = setup({ oldest: new Date("2026-03-08T09:20:00.000Z") }); await service.rollUpClosedBuckets(); expect(windows()).toEqual([ - ["2026-03-08T09:15:00.000Z", "2026-03-09T09:15:00.000Z"], - ["2026-03-09T09:15:00.000Z", "2026-03-10T09:15:00.000Z"], - ["2026-03-10T09:15:00.000Z", CURRENT_BUCKET_START], + ["2026-03-08T00:00:00.000Z", YESTERDAY], + [YESTERDAY, TODAY], ]); }); - it("re-rolls from the bucket that was open two hours ago on a normal run", async () => { - const { service, checksRepository, windows } = setup({ latest: new Date("2026-03-10T09:45:00.000Z") }); + it("rolls up yesterday on the first run after midnight", async () => { + const { service, checksRepository, windows } = setup({ now: new Date("2026-03-10T00:10:00.000Z"), latest: new Date("2026-03-08T00:00:00.000Z") }); await service.rollUpClosedBuckets(); - expect(windows()).toEqual([["2026-03-10T08:00:00.000Z", CURRENT_BUCKET_START]]); + expect(windows()).toEqual([[YESTERDAY, TODAY]]); expect(checksRepository.findOldestCreatedAt).not.toHaveBeenCalled(); }); - it("catches up in chunks from the bucket after the latest after downtime", async () => { - const { service, windows } = setup({ latest: new Date("2026-03-08T12:00:00.000Z") }); + it("rolls up yesterday again while the day is less than two hours old", async () => { + const { service, windows } = setup({ now: new Date("2026-03-10T01:59:00.000Z"), latest: new Date(YESTERDAY) }); + + await service.rollUpClosedBuckets(); + + expect(windows()).toEqual([[YESTERDAY, TODAY]]); + }); + + it("does nothing once yesterday is rolled up and the day is two hours old", async () => { + const { service, checkRollupsRepository } = setup({ now: new Date("2026-03-10T02:00:00.000Z"), latest: new Date(YESTERDAY) }); + + await service.rollUpClosedBuckets(); + + expect(checkRollupsRepository.rollUp).not.toHaveBeenCalled(); + }); + + it("catches up one day per call from the day after the latest after downtime", async () => { + const { service, windows } = setup({ latest: new Date("2026-03-06T00:00:00.000Z") }); await service.rollUpClosedBuckets(); expect(windows()).toEqual([ - ["2026-03-08T12:15:00.000Z", "2026-03-09T12:15:00.000Z"], - ["2026-03-09T12:15:00.000Z", CURRENT_BUCKET_START], + ["2026-03-07T00:00:00.000Z", "2026-03-08T00:00:00.000Z"], + ["2026-03-08T00:00:00.000Z", YESTERDAY], + [YESTERDAY, TODAY], ]); }); - it("does not roll buckets within the margin of the retention boundary", async () => { - const { service, windows } = setup({ oldest: new Date("2026-03-05T00:00:00.000Z"), checkTTL: 1 }); + it("does not roll up a day that retention has started to expire", async () => { + const { service, windows } = setup({ oldest: new Date("2026-03-05T00:00:00.000Z"), checkTTL: 3 }); await service.rollUpClosedBuckets(); - expect(windows()).toEqual([["2026-03-09T12:15:00.000Z", CURRENT_BUCKET_START]]); + expect(windows()).toEqual([ + ["2026-03-08T00:00:00.000Z", YESTERDAY], + [YESTERDAY, TODAY], + ]); + }); + + it("rolls up nothing when checks are kept for one day", async () => { + const { service, checkRollupsRepository } = setup({ oldest: new Date("2026-03-05T00:00:00.000Z"), checkTTL: 1 }); + + await service.rollUpClosedBuckets(); + + expect(checkRollupsRepository.rollUp).not.toHaveBeenCalled(); }); it("applies no retention boundary when retention is unlimited", async () => { @@ -86,7 +116,7 @@ describe("CheckRollupService.rollUpClosedBuckets", () => { expect(windows()[0]?.[0]).toBe("2025-01-01T00:00:00.000Z"); }); - it("does nothing when the only checks are in the open bucket", async () => { + it("does nothing when the only checks are from today", async () => { const { service, checkRollupsRepository } = setup({ oldest: new Date("2026-03-10T10:03:00.000Z") }); await service.rollUpClosedBuckets();