Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions server/src/db/migration/0014_clearCheckRollups.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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;
}
}
2 changes: 2 additions & 0 deletions server/src/db/migration/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -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) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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[] => [
{
Expand Down
3 changes: 1 addition & 2 deletions server/src/domain/check-rollups/check-rollup.pipeline.ts
Original file line number Diff line number Diff line change
@@ -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<PipelineStage, PipelineStage.Out | PipelineStage.Merge>;
Expand All @@ -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" },
Expand Down
6 changes: 3 additions & 3 deletions server/src/domain/check-rollups/check-rollup.type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
6 changes: 3 additions & 3 deletions server/src/worker/worker.job-scheduler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down Expand Up @@ -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));
Expand Down
45 changes: 32 additions & 13 deletions server/test/integration/checkRollupService.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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 });
Expand All @@ -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);
});
});
Loading
Loading