Merge pull request #3818 from bluewave-labs/feat/chart-cleanup

feat: chart cleanup
This commit is contained in:
Alexander Holliday authored and GitHub committed 2026-07-30 12:16:24 -07:00
commit 093553f9ba
9 files changed
+605 -241

No files matched your search

+14 -4
View File
@@ -1,18 +1,28 @@
import type { CSSProperties } from "react";
export const DotSizes = ["xs", "sm", "md", "lg"] as const;
export type DotSize = (typeof DotSizes)[number];
const DOT_SIZE_PX: Record<DotSize, string> = {
xs: "2px",
sm: "4px",
md: "8px",
lg: "12px",
};
interface DotProps {
color?: string;
size?: string;
size?: DotSize;
style?: CSSProperties;
}
export const Dot = ({ color = "gray", size = "4px", style }: DotProps) => {
export const Dot = ({ color = "gray", size = "sm", style }: DotProps) => {
return (
<span
style={{
content: '""',
width: size,
height: size,
width: DOT_SIZE_PX[size],
height: DOT_SIZE_PX[size],
borderRadius: "50%",
backgroundColor: color,
opacity: 0.8,
@@ -23,11 +23,12 @@ export const PHASE_COLOR_KEYS = {
avgDownload: "download",
} as const;
export const PHASE_LABELS: Record<(typeof PHASE_KEYS)[number], string> = {
avgDns: "DNS",
avgTcp: "TCP",
avgTls: "TLS",
avgRequest: "Request",
avgFirstByte: "First byte",
avgDownload: "Download",
// i18n keys, resolved with t() at render
export const PHASE_LABEL_KEYS: Record<(typeof PHASE_KEYS)[number], string> = {
avgDns: "common.charts.phases.dns",
avgTcp: "common.charts.phases.tcp",
avgTls: "common.charts.phases.tls",
avgRequest: "common.charts.phases.request",
avgFirstByte: "common.charts.phases.firstByte",
avgDownload: "common.charts.phases.download",
};
@@ -17,6 +17,7 @@ import Typography from "@mui/material/Typography";
import prettyMilliseconds from "pretty-ms";
import { XTick } from "@/Components/monitors/charts/XTick";
import { useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
import { formatDateWithTz, tooltipDateFormatLookup } from "@/Utils/TimeUtils";
import { useTheme } from "@mui/material/styles";
import type { Theme } from "@mui/material/styles";
@@ -25,11 +26,11 @@ import type { RootState } from "@/Types/state";
import { computeYAxisCap } from "@/Components/monitors/charts/ChartUtils";
import { useMemo, useState } from "react";
import { SPACING } from "@/Utils/Theme/constants";
import { LAYOUT, SPACING } from "@/Utils/Theme/constants";
import {
PHASE_COLOR_KEYS,
PHASE_KEYS,
PHASE_LABELS,
PHASE_LABEL_KEYS,
} from "@/Components/monitors/charts/ChartUtils";
type DetailsCheck = GroupedCheck &
@@ -49,6 +50,7 @@ const ResponseTimeToolTip = ({
theme,
uiTimezone,
}: ResponseTimeToolTipProps) => {
const { t } = useTranslation();
if (!label) return null;
if (!payload) return null;
if (!active) return null;
@@ -59,8 +61,12 @@ const ResponseTimeToolTip = ({
<BaseBox sx={{ py: theme.spacing(2), px: theme.spacing(4) }}>
<Typography>{formatDateWithTz(String(label), format, uiTimezone)}</Typography>
<Typography>
Response time:{" "}
{prettyMilliseconds(responseTime, { formatSubMilliseconds: true, compact: true })}
{t("common.charts.histogram.responseTime", {
value: prettyMilliseconds(responseTime, {
formatSubMilliseconds: true,
compact: true,
}),
})}
</Typography>
</BaseBox>
);
@@ -79,6 +85,7 @@ const TimingPhasesToolTip = ({
theme,
uiTimezone,
}: TimingPhaseToolTipProps) => {
const { t } = useTranslation();
if (!active || !payload?.length) return null;
const bucket = payload[0].payload as GroupedUptimeCheck;
const total = PHASE_KEYS.reduce((sum, key) => sum + bucket[key], 0);
@@ -86,7 +93,9 @@ const TimingPhasesToolTip = ({
return (
<BaseBox sx={{ py: theme.spacing(2), px: theme.spacing(4) }}>
<Typography>{formatDateWithTz(bucket.bucketDate, format, uiTimezone)}</Typography>
<Typography>Total: {prettyMilliseconds(total)}</Typography>
<Typography>
{t("common.charts.histogram.total", { value: prettyMilliseconds(total) })}
</Typography>
{PHASE_KEYS.map((key) => (
<Stack
alignItems={"center"}
@@ -95,11 +104,11 @@ const TimingPhasesToolTip = ({
gap={SPACING.LG}
>
<Dot
size={"12px"}
size="lg"
color={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
/>
<Typography>
{PHASE_LABELS[key]}:{" "}
{t(PHASE_LABEL_KEYS[key])}:{" "}
{prettyMilliseconds(bucket[key], {
formatSubMilliseconds: true,
compact: true,
@@ -119,6 +128,9 @@ export const HistogramDetails = ({
range: string;
}) => {
const [showTimingPhases, setShowTimingPhases] = useState(false);
const [hoveredPhase, setHoveredPhase] = useState<string | null>(null);
const { t } = useTranslation();
const theme = useTheme();
const uiTimezone = useSelector((state: RootState) => state.ui.timezone);
const yMax = useMemo(() => {
@@ -142,7 +154,11 @@ export const HistogramDetails = ({
strokeWidth={1.5}
/>
}
title={showTimingPhases ? "Timing Phases" : "Response Time"}
title={
showTimingPhases
? t("common.charts.labels.timingPhases")
: t("common.charts.labels.responseTime")
}
onClick={() => {
if (!hasTimingPhases) return;
setShowTimingPhases((prev) => !prev);
@@ -253,6 +269,7 @@ export const HistogramDetails = ({
{hasTimingPhases &&
showTimingPhases &&
PHASE_KEYS.map((key) => {
const dimmed = hoveredPhase !== null && hoveredPhase !== key;
return (
<Area
key={key}
@@ -261,11 +278,56 @@ export const HistogramDetails = ({
dataKey={key}
stroke={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
fill={`url(#phaseGradient-${key})`}
fillOpacity={dimmed ? 0.2 : undefined}
strokeOpacity={dimmed ? 0.2 : undefined}
/>
);
})}
</AreaChart>
</ResponsiveContainer>
<Stack
justifyContent={"center"}
gap={LAYOUT.XS}
direction={"row"}
flexWrap={"wrap"}
>
{showTimingPhases ? (
PHASE_KEYS.map((key) => {
return (
<Stack
direction="row"
alignItems="center"
gap={SPACING.LG}
key={key}
onMouseEnter={() => setHoveredPhase(key)}
onMouseLeave={() => setHoveredPhase(null)}
>
<Dot
color={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
size="lg"
/>
<Typography lineHeight={1}>{t(PHASE_LABEL_KEYS[key])}</Typography>
</Stack>
);
})
) : (
<Stack
direction="row"
alignItems="center"
gap={SPACING.LG}
onMouseEnter={() => setHoveredPhase("avgResponseTime")}
onMouseLeave={() => setHoveredPhase(null)}
>
<Dot
color={theme.palette.primary.main}
size="lg"
/>
<Typography lineHeight={1}>
{t("common.charts.labels.totalResponseTime")}
</Typography>
</Stack>
)}
</Stack>
</BaseChart>
);
};
@@ -1,207 +0,0 @@
import type { GroupedUptimeCheck } from "@/Types/Check";
import type { TooltipProps } from "recharts";
import type { NameType, ValueType } from "recharts/types/component/DefaultTooltipContent";
import type { Theme } from "@mui/material/styles";
import type { RootState } from "@/Types/state";
import { Clock } from "lucide-react";
import prettyMilliseconds from "pretty-ms";
import Stack from "@mui/material/Stack";
import {
Area,
AreaChart,
CartesianGrid,
ResponsiveContainer,
YAxis,
XAxis,
Tooltip,
} from "recharts";
import { BaseBox, BaseChart, Dot } from "@/Components/design-elements";
import Typography from "@mui/material/Typography";
import { XTick } from "@/Components/monitors/charts/XTick";
import { formatDateWithTz, tooltipDateFormatLookup } from "@/Utils/TimeUtils";
import { useSelector } from "react-redux";
import { useMemo } from "react";
import { useTheme } from "@mui/material";
import { SPACING } from "@/Utils/Theme/constants";
import { computeYAxisCap } from "@/Components/monitors/charts/ChartUtils";
export const PHASE_KEYS = [
"avgDns",
"avgTcp",
"avgTls",
"avgRequest",
"avgFirstByte",
"avgDownload",
] as const;
const PHASE_COLOR_KEYS = {
avgDns: "dns",
avgTcp: "tcp",
avgTls: "tls",
avgRequest: "request",
avgFirstByte: "firstByte",
avgDownload: "download",
} as const;
const PHASE_LABELS: Record<(typeof PHASE_KEYS)[number], string> = {
avgDns: "DNS",
avgTcp: "TCP",
avgTls: "TLS",
avgRequest: "Request",
avgFirstByte: "First byte",
avgDownload: "Download",
};
type TimingPhaseToolTipProps = TooltipProps<ValueType, NameType> & {
range: string;
theme: Theme;
uiTimezone: string;
};
const TimingPhasesToolTip = ({
active,
payload,
range,
theme,
uiTimezone,
}: TimingPhaseToolTipProps) => {
if (!active || !payload?.length) return null;
const bucket = payload[0].payload as GroupedUptimeCheck;
const total = PHASE_KEYS.reduce((sum, key) => sum + bucket[key], 0);
const format = tooltipDateFormatLookup(range);
return (
<BaseBox sx={{ py: theme.spacing(2), px: theme.spacing(4) }}>
<Typography>{formatDateWithTz(bucket.bucketDate, format, uiTimezone)}</Typography>
<Typography>Total: {prettyMilliseconds(total)}</Typography>
{PHASE_KEYS.map((key) => (
<Stack
alignItems={"center"}
direction="row"
key={key}
gap={SPACING.LG}
>
<Dot
size={"12px"}
color={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
/>
<Typography>
{PHASE_LABELS[key]}:{" "}
{prettyMilliseconds(bucket[key], {
formatSubMilliseconds: true,
compact: true,
})}
</Typography>
</Stack>
))}
</BaseBox>
);
};
export const HistogramDetailsStacked = ({
checks = [],
range,
}: {
checks: GroupedUptimeCheck[];
range: string;
}) => {
const theme = useTheme();
const uiTimezone = useSelector((state: RootState) => state.ui.timezone);
// Cap the y domain at 2x the p95 of bucket totals, so typical stacks sit
// around mid-height with headroom above
const yMax = useMemo(() => {
const totals = checks.map((check) =>
PHASE_KEYS.reduce((sum, key) => sum + check[key], 0)
);
return computeYAxisCap(totals);
}, [checks]);
return (
<BaseChart
icon={
<Clock
size={20}
strokeWidth={1.5}
/>
}
title="Timing phases"
>
<ResponsiveContainer
width="100%"
height={300}
>
<AreaChart data={checks.slice()}>
<CartesianGrid
stroke={theme.palette.divider}
strokeWidth={1}
strokeOpacity={1}
fill="transparent"
vertical={false}
/>
<defs>
{PHASE_KEYS.map((key) => (
<linearGradient
key={key}
id={`phaseGradient-${key}`}
x1="0"
y1="0"
x2="0"
y2="1"
>
<stop
offset="0%"
stopColor={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
stopOpacity={0.8}
/>
<stop
offset="100%"
stopColor={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
stopOpacity={0.2}
/>
</linearGradient>
))}
</defs>
<YAxis
hide
// scale="sqrt"
domain={[0, yMax ?? "auto"]}
allowDataOverflow
/>
<XAxis
axisLine={false}
tickLine={false}
dataKey="bucketDate"
tick={(props) => (
<XTick
{...props}
range={range}
/>
)}
/>
<Tooltip
content={(props) => (
<TimingPhasesToolTip
{...props}
range={range}
theme={theme}
uiTimezone={uiTimezone}
/>
)}
/>
{PHASE_KEYS.map((key) => (
<Area
key={key}
type="monotone"
stackId={1}
dataKey={key}
stroke={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]}
fill={`url(#phaseGradient-${key})`}
/>
))}
</AreaChart>
</ResponsiveContainer>
</BaseChart>
);
};
+14 -1
View File
@@ -68,11 +68,24 @@
"downtime": "Downtime",
"high": "High",
"low": "Low",
"responseTime": "Response time",
"timingPhases": "Timing phases",
"totalResponseTime": "Total response time",
"uptime": "Uptime"
},
"histogram": {
"avg": "Avg: {{value}} ms",
"max": "Max: {{value}} ms"
"max": "Max: {{value}} ms",
"responseTime": "Response time: {{value}}",
"total": "Total: {{value}}"
},
"phases": {
"dns": "DNS",
"tcp": "TCP",
"tls": "TLS",
"request": "Request",
"firstByte": "First byte",
"download": "Download"
}
},
"dialogs": {
+343 -13
View File
@@ -536,6 +536,341 @@
"updatedAt": "2026-04-15T14:30:00.000Z"
}
},
"UptimeDetails": {
"type": "object",
"properties": {
"monitorData": {
"type": "object",
"properties": {
"monitor": {
"type": "object",
"properties": {
"name": {
"type": "string"
},
"description": {
"type": "string"
},
"type": {
"type": "string",
"enum": ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "grpc", "websocket", "dns", "unknown"]
},
"url": {
"type": "string"
},
"port": {
"type": "number"
},
"isActive": {
"type": "boolean"
},
"interval": {
"type": "number"
},
"status": {
"type": "string",
"enum": ["up", "down", "paused", "initializing", "maintenance", "breached"]
},
"statusWindowSize": {
"type": "number"
},
"statusWindowThreshold": {
"type": "number"
},
"ignoreTlsErrors": {
"type": "boolean"
},
"useAdvancedMatching": {
"type": "boolean"
},
"jsonPath": {
"type": "string"
},
"expectedValue": {
"type": "string"
},
"matchMethod": {
"type": "string",
"enum": ["equal", "include", "regex"]
},
"method": {
"type": "string",
"enum": ["GET", "HEAD"]
},
"notifications": {
"type": "array",
"items": {
"type": "string"
}
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"customUpCodes": {
"type": "array",
"items": {
"type": "number"
}
},
"secret": {
"type": "string"
},
"cpuAlertThreshold": {
"type": "number"
},
"memoryAlertThreshold": {
"type": "number"
},
"diskAlertThreshold": {
"type": "number"
},
"tempAlertThreshold": {
"type": "number"
},
"selectedDisks": {
"type": "array",
"items": {
"type": "string"
}
},
"gameId": {
"type": "string"
},
"grpcServiceName": {
"type": "string"
},
"group": {
"type": "string",
"nullable": true
},
"geoCheckEnabled": {
"type": "boolean"
},
"geoCheckLocations": {
"type": "array",
"items": {
"type": "string",
"enum": ["EU", "NA", "AS", "SA", "AF", "OC"]
}
},
"geoCheckInterval": {
"type": "number"
},
"dnsServer": {
"type": "string"
},
"dnsRecordType": {
"type": "string",
"enum": ["A", "AAAA", "CNAME", "MX", "TXT", "NS"]
},
"teamId": {
"type": "string"
},
"userId": {
"type": "string"
},
"createdAt": {
"type": "string"
},
"updatedAt": {
"type": "string"
},
"lastEvaluatedAt": {
"type": "number"
},
"id": {
"type": "string"
}
},
"required": [
"name",
"type",
"url",
"isActive",
"interval",
"status",
"statusWindowSize",
"statusWindowThreshold",
"ignoreTlsErrors",
"useAdvancedMatching",
"method",
"notifications",
"tags",
"cpuAlertThreshold",
"memoryAlertThreshold",
"diskAlertThreshold",
"tempAlertThreshold",
"selectedDisks",
"geoCheckEnabled",
"geoCheckLocations",
"geoCheckInterval",
"teamId",
"userId",
"createdAt",
"updatedAt",
"lastEvaluatedAt",
"id"
],
"additionalProperties": {
"nullable": true
}
},
"groupedChecks": {
"type": "array",
"items": {
"type": "object",
"properties": {
"bucketDate": {
"type": "string"
},
"avgResponseTime": {
"type": "number"
},
"totalChecks": {
"type": "number"
},
"avgDns": {
"type": "number"
},
"avgTcp": {
"type": "number"
},
"avgTls": {
"type": "number"
},
"avgRequest": {
"type": "number"
},
"avgFirstByte": {
"type": "number"
},
"avgDownload": {
"type": "number"
}
},
"required": [
"bucketDate",
"avgResponseTime",
"totalChecks",
"avgDns",
"avgTcp",
"avgTls",
"avgRequest",
"avgFirstByte",
"avgDownload"
]
}
},
"groupedUpChecks": {
"type": "array",
"items": {
"type": "object",
"properties": {
"bucketDate": {
"type": "string"
},
"avgResponseTime": {
"type": "number"
},
"totalChecks": {
"type": "number"
}
},
"required": ["bucketDate", "avgResponseTime", "totalChecks"]
}
},
"groupedDownChecks": {
"type": "array",
"items": {
"type": "object",
"properties": {
"bucketDate": {
"type": "string"
},
"avgResponseTime": {
"type": "number"
},
"totalChecks": {
"type": "number"
}
},
"required": ["bucketDate", "avgResponseTime", "totalChecks"]
}
},
"groupedAvgResponseTime": {
"type": "number"
},
"groupedUptimePercentage": {
"type": "number"
}
},
"required": ["monitor", "groupedChecks", "groupedUpChecks", "groupedDownChecks", "groupedAvgResponseTime", "groupedUptimePercentage"]
},
"monitorStats": {
"type": "object",
"nullable": true,
"properties": {
"id": {
"type": "string"
},
"monitorId": {
"type": "string"
},
"avgResponseTime": {
"type": "number"
},
"maxResponseTime": {
"type": "number"
},
"totalChecks": {
"type": "number"
},
"totalUpChecks": {
"type": "number"
},
"totalDownChecks": {
"type": "number"
},
"uptimePercentage": {
"type": "number"
},
"lastCheckTimestamp": {
"type": "number"
},
"lastResponseTime": {
"type": "number"
},
"timeOfLastFailure": {
"type": "number"
},
"createdAt": {
"type": "string"
},
"updatedAt": {
"type": "string"
}
},
"required": [
"id",
"monitorId",
"avgResponseTime",
"maxResponseTime",
"totalChecks",
"totalUpChecks",
"totalDownChecks",
"uptimePercentage",
"lastCheckTimestamp",
"lastResponseTime",
"createdAt",
"updatedAt"
]
}
},
"required": ["monitorData", "monitorStats"]
},
"NotificationChannelBody": {
"oneOf": [
{
@@ -2426,6 +2761,9 @@
"minLength": 8,
"pattern": "^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!?@#$%^&*()\\-_=+[\\]{};:'\",.~`|\\\\/])[A-Za-z0-9!?@#$%^&*()\\-_=+[\\]{};:'\",.~`|\\\\/]+$"
},
"deleteProfileImage": {
"type": "boolean"
},
"profileImage": {
"type": "string",
"format": "binary"
@@ -3747,7 +4085,7 @@
{
"schema": {
"type": "string",
"enum": ["manual", "automatic"]
"enum": ["automatic", "manual"]
},
"required": false,
"name": "resolutionType",
@@ -6013,14 +6351,6 @@
"required": true,
"name": "dateRange",
"in": "query"
},
{
"schema": {
"type": "boolean"
},
"required": false,
"name": "normalize",
"in": "query"
}
],
"responses": {
@@ -6039,10 +6369,10 @@
"type": "string"
},
"data": {
"nullable": true
"$ref": "#/components/schemas/UptimeDetails"
}
},
"required": ["success", "msg"]
"required": ["success", "msg", "data"]
}
}
}
@@ -10538,7 +10868,7 @@
},
"theme": {
"type": "string",
"enum": ["refined", "modern", "bold", "editorial"]
"enum": ["refined", "modern", "bold", "editorial", "minimal"]
},
"themeMode": {
"type": "string",
@@ -10756,7 +11086,7 @@
},
"theme": {
"type": "string",
"enum": ["refined", "modern", "bold", "editorial"]
"enum": ["refined", "modern", "bold", "editorial", "minimal"]
},
"themeMode": {
"type": "string",
+4 -1
View File
@@ -16,6 +16,7 @@ import {
getHardwareDetailsByIdParamValidation,
getHardwareDetailsByIdQueryValidation,
monitorResponseSchema,
uptimeDetailsResponseSchema,
} from "@/api/validation/monitorValidation.js";
import { updateNotificationsValidation } from "@/api/validation/notificationValidation.js";
@@ -81,6 +82,8 @@ registry.registerPath({
responses: { "200": okJson(z.array(z.string())), ...standardErrors },
});
const uptimeDetailsObject = uptimeDetailsResponseSchema.openapi("UptimeDetails");
registry.registerPath({
method: "get",
path: "/monitors/uptime/details/{monitorId}",
@@ -88,7 +91,7 @@ registry.registerPath({
summary: "Get uptime details for a monitor",
security: bearer,
request: { params: getUptimeDetailsByIdParamValidation, query: getUptimeDetailsByIdQueryValidation },
responses: { "200": okUnknown, ...standardErrors },
responses: { "200": okJson(uptimeDetailsObject), ...standardErrors },
});
registry.registerPath({
@@ -311,3 +311,52 @@ export const monitorResponseSchema = z
lastEvaluatedAt: z.number(),
})
.passthrough();
// Grouped-check buckets returned by GET /monitors/uptime/details/{monitorId}. Keep
// aligned with GroupedCheck / GroupedUptimeCheck in domain/checks/check.type.ts.
export const groupedCheckResponseSchema = z.object({
bucketDate: z.string(),
avgResponseTime: z.number(),
totalChecks: z.number(),
});
export const groupedUptimeCheckResponseSchema = groupedCheckResponseSchema.extend({
avgDns: z.number(),
avgTcp: z.number(),
avgTls: z.number(),
avgRequest: z.number(),
avgFirstByte: z.number(),
avgDownload: z.number(),
});
// Keep aligned with MonitorStats in domain/monitor-stats/monitor-stats.type.ts.
export const monitorStatsResponseSchema = z.object({
id: z.string(),
monitorId: z.string(),
avgResponseTime: z.number(),
maxResponseTime: z.number(),
totalChecks: z.number(),
totalUpChecks: z.number(),
totalDownChecks: z.number(),
uptimePercentage: z.number(),
lastCheckTimestamp: z.number(),
lastResponseTime: z.number(),
timeOfLastFailure: z.number().optional(),
createdAt: z.string(),
updatedAt: z.string(),
});
// Response of GET /monitors/uptime/details/{monitorId}. Keep aligned with
// UptimeDetailsResult in domain/monitors/monitor.type.ts; the monitor here is the
// repository's domain entity, which serializes `id` rather than `_id`.
export const uptimeDetailsResponseSchema = z.object({
monitorData: z.object({
monitor: monitorResponseSchema.omit({ _id: true }).extend({ id: z.string() }),
groupedChecks: z.array(groupedUptimeCheckResponseSchema),
groupedUpChecks: z.array(groupedCheckResponseSchema),
groupedDownChecks: z.array(groupedCheckResponseSchema),
groupedAvgResponseTime: z.number(),
groupedUptimePercentage: z.number(),
}),
monitorStats: monitorStatsResponseSchema.nullable(),
});
@@ -0,0 +1,103 @@
import { describe, expect, it, beforeAll, afterAll, beforeEach } from "@jest/globals";
import mongoose from "mongoose";
import { MongoMemoryServer } from "mongodb-memory-server";
import MongoChecksRepository from "../../src/domain/checks/check.repository.mongo.ts";
import { CheckModel } from "../../src/domain/checks/check.model.ts";
import type { UptimeChecksResult } from "../../src/domain/checks/check.type.ts";
import type { ILogger } from "../../src/utils/logger.ts";
import { createMockLogger } from "../helpers/createMockLogger.ts";
// ── Real-Mongo harness ─────────────────────────────────────────────────────────
// The guarantee under test — every phase average uses the full bucket as its
// denominator — IS the $ifNull-inside-$avg behavior of the groupedChecks facet, so it
// can only be exercised against a live aggregation engine. Reused keep-alive sockets
// produce checks with no timings subdocument at all; without the coercion, $avg would
// skip them and average dns/tcp/tls over fresh-connection checks only.
let mongod: MongoMemoryServer;
beforeAll(async () => {
mongod = await MongoMemoryServer.create();
await mongoose.connect(mongod.getUri());
await CheckModel.createCollection(); // timeseries collections must exist before insert
}, 120_000);
afterAll(async () => {
await mongoose.disconnect();
await mongod.stop();
});
beforeEach(async () => {
await CheckModel.deleteMany({});
});
// ── Helpers ──────────────────────────────────────────────────────────────────
const MONITOR_ID = new mongoose.Types.ObjectId();
const TEAM_ID = new mongoose.Types.ObjectId();
// One shared createdAt puts every seeded check in the same hourly bucket of the "day"
// range, keeping the facet's group stage deterministic.
const BUCKET_TIME = new Date(Date.now() - 10 * 60 * 1000);
const seedCheck = (overrides: Record<string, unknown> = {}) =>
CheckModel.create({
metadata: { monitorId: MONITOR_ID, teamId: TEAM_ID, type: "http" },
status: true,
responseTime: 100,
createdAt: BUCKET_TIME,
...overrides,
});
const findGrouped = async (repo: MongoChecksRepository) =>
(await repo.findByDateRangeAndMonitorId(MONITOR_ID.toString(), "day", { type: "http" })) as UptimeChecksResult;
describe("MongoChecksRepository groupedChecks facet", () => {
let repo: MongoChecksRepository;
beforeEach(() => {
repo = new MongoChecksRepository(createMockLogger() as unknown as ILogger);
});
it("averages each phase over the full bucket, counting checks without timings as 0", async () => {
await seedCheck({
responseTime: 100,
timings: { phases: { dns: 10, tcp: 20, tls: 30, request: 8, firstByte: 40, download: 6 } },
});
await seedCheck({ responseTime: 200 }); // reused socket: no timings subdocument at all
const result = await findGrouped(repo);
expect(result.groupedChecks).toHaveLength(1);
// Plain $avg would skip the timings-less check and report 10/20/30/8/40/6 here.
expect(result.groupedChecks[0]).toMatchObject({
totalChecks: 2,
avgDns: 5,
avgTcp: 10,
avgTls: 15,
avgRequest: 4,
avgFirstByte: 20,
avgDownload: 3,
avgResponseTime: 150,
});
});
it("yields 0 (not null) for every phase in a bucket of only timings-less checks", async () => {
await seedCheck();
await seedCheck();
const result = await findGrouped(repo);
expect(result.groupedChecks).toHaveLength(1);
// The client sums these fields for the stacked chart; null would poison the math.
expect(result.groupedChecks[0]).toMatchObject({
totalChecks: 2,
avgDns: 0,
avgTcp: 0,
avgTls: 0,
avgRequest: 0,
avgFirstByte: 0,
avgDownload: 0,
});
});
});