From c102cd8d26e610581c0bb0a03a8e2cd7a0484915 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 30 Jul 2026 10:35:01 -0700 Subject: [PATCH 1/5] openapi schemas --- server/openapi.json | 356 +++++++++++++++++- server/openapi/routes/monitor.ts | 5 +- .../src/api/validation/monitorValidation.ts | 49 +++ 3 files changed, 396 insertions(+), 14 deletions(-) diff --git a/server/openapi.json b/server/openapi.json index 4b710b639..28a22f394 100644 --- a/server/openapi.json +++ b/server/openapi.json @@ -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", diff --git a/server/openapi/routes/monitor.ts b/server/openapi/routes/monitor.ts index a941e54bf..01b687678 100644 --- a/server/openapi/routes/monitor.ts +++ b/server/openapi/routes/monitor.ts @@ -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({ diff --git a/server/src/api/validation/monitorValidation.ts b/server/src/api/validation/monitorValidation.ts index 0e8b7b0bd..86db942a5 100644 --- a/server/src/api/validation/monitorValidation.ts +++ b/server/src/api/validation/monitorValidation.ts @@ -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(), +}); From 6856914d411f908fd340b6b1d7172013599246e7 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 30 Jul 2026 10:56:24 -0700 Subject: [PATCH 2/5] extract hardcoded strings --- .../Components/monitors/charts/ChartUtils.ts | 15 +- .../monitors/charts/HistogramDetails.tsx | 26 ++- .../charts/HistogramDetailsStacked.tsx | 207 ------------------ client/src/locales/en.json | 14 +- 4 files changed, 41 insertions(+), 221 deletions(-) delete mode 100644 client/src/Components/monitors/charts/HistogramDetailsStacked.tsx diff --git a/client/src/Components/monitors/charts/ChartUtils.ts b/client/src/Components/monitors/charts/ChartUtils.ts index fb9d1779c..0516eaac3 100644 --- a/client/src/Components/monitors/charts/ChartUtils.ts +++ b/client/src/Components/monitors/charts/ChartUtils.ts @@ -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", }; diff --git a/client/src/Components/monitors/charts/HistogramDetails.tsx b/client/src/Components/monitors/charts/HistogramDetails.tsx index 0736abd6c..1f78c692e 100644 --- a/client/src/Components/monitors/charts/HistogramDetails.tsx +++ b/client/src/Components/monitors/charts/HistogramDetails.tsx @@ -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"; @@ -29,7 +30,7 @@ import { 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 = ({ {formatDateWithTz(String(label), format, uiTimezone)} - Response time:{" "} - {prettyMilliseconds(responseTime, { formatSubMilliseconds: true, compact: true })} + {t("common.charts.histogram.responseTime", { + value: prettyMilliseconds(responseTime, { + formatSubMilliseconds: true, + compact: true, + }), + })} ); @@ -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 ( {formatDateWithTz(bucket.bucketDate, format, uiTimezone)} - Total: {prettyMilliseconds(total)} + + {t("common.charts.histogram.total", { value: prettyMilliseconds(total) })} + {PHASE_KEYS.map((key) => ( - {PHASE_LABELS[key]}:{" "} + {t(PHASE_LABEL_KEYS[key])}:{" "} {prettyMilliseconds(bucket[key], { formatSubMilliseconds: true, compact: true, @@ -119,6 +128,7 @@ export const HistogramDetails = ({ range: string; }) => { const [showTimingPhases, setShowTimingPhases] = useState(false); + const { t } = useTranslation(); const theme = useTheme(); const uiTimezone = useSelector((state: RootState) => state.ui.timezone); const yMax = useMemo(() => { @@ -142,7 +152,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); diff --git a/client/src/Components/monitors/charts/HistogramDetailsStacked.tsx b/client/src/Components/monitors/charts/HistogramDetailsStacked.tsx deleted file mode 100644 index 2ef74f56b..000000000 --- a/client/src/Components/monitors/charts/HistogramDetailsStacked.tsx +++ /dev/null @@ -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 & { - 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 ( - - {formatDateWithTz(bucket.bucketDate, format, uiTimezone)} - Total: {prettyMilliseconds(total)} - {PHASE_KEYS.map((key) => ( - - - - {PHASE_LABELS[key]}:{" "} - {prettyMilliseconds(bucket[key], { - formatSubMilliseconds: true, - compact: true, - })} - - - ))} - - ); -}; - -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 ( - - } - title="Timing phases" - > - - - - - {PHASE_KEYS.map((key) => ( - - - - - ))} - - - ( - - )} - /> - ( - - )} - /> - {PHASE_KEYS.map((key) => ( - - ))} - - - - ); -}; diff --git a/client/src/locales/en.json b/client/src/locales/en.json index d940f95fc..82d144b1c 100644 --- a/client/src/locales/en.json +++ b/client/src/locales/en.json @@ -68,11 +68,23 @@ "downtime": "Downtime", "high": "High", "low": "Low", + "responseTime": "Response time", + "timingPhases": "Timing phases", "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": { From 89464e9be4460c25b98f4f528b53541ccc8c9fb8 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 30 Jul 2026 11:54:12 -0700 Subject: [PATCH 3/5] add legend --- client/src/Components/design-elements/Dot.tsx | 18 +++++-- .../monitors/charts/HistogramDetails.tsx | 52 ++++++++++++++++++- client/src/locales/en.json | 1 + 3 files changed, 65 insertions(+), 6 deletions(-) diff --git a/client/src/Components/design-elements/Dot.tsx b/client/src/Components/design-elements/Dot.tsx index 541e90812..ff97de9b4 100644 --- a/client/src/Components/design-elements/Dot.tsx +++ b/client/src/Components/design-elements/Dot.tsx @@ -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 = { + 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 ( @@ -128,6 +128,8 @@ export const HistogramDetails = ({ range: string; }) => { const [showTimingPhases, setShowTimingPhases] = useState(false); + const [hoveredPhase, setHoveredPhase] = useState(null); + const { t } = useTranslation(); const theme = useTheme(); const uiTimezone = useSelector((state: RootState) => state.ui.timezone); @@ -267,6 +269,7 @@ export const HistogramDetails = ({ {hasTimingPhases && showTimingPhases && PHASE_KEYS.map((key) => { + const dimmed = hoveredPhase !== null && hoveredPhase !== key; return ( ); })} + + {showTimingPhases ? ( + PHASE_KEYS.map((key) => { + return ( + setHoveredPhase(key)} + onMouseLeave={() => setHoveredPhase(null)} + > + + {t(PHASE_LABEL_KEYS[key])} + + ); + }) + ) : ( + setHoveredPhase("avgResponseTime")} + onMouseLeave={() => setHoveredPhase(null)} + > + + + {t("common.charts.labels.totalResponseTime")} + + + )} + ); }; diff --git a/client/src/locales/en.json b/client/src/locales/en.json index 82d144b1c..ce7f74dfb 100644 --- a/client/src/locales/en.json +++ b/client/src/locales/en.json @@ -70,6 +70,7 @@ "low": "Low", "responseTime": "Response time", "timingPhases": "Timing phases", + "totalResponseTime": "Total response time", "uptime": "Uptime" }, "histogram": { From 6b4444038c2f6977d397692e25715c6093b4b07f Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 30 Jul 2026 11:54:19 -0700 Subject: [PATCH 4/5] add tests --- .../checksRepositoryGroupedChecks.test.ts | 103 ++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 server/test/integration/checksRepositoryGroupedChecks.test.ts diff --git a/server/test/integration/checksRepositoryGroupedChecks.test.ts b/server/test/integration/checksRepositoryGroupedChecks.test.ts new file mode 100644 index 000000000..cf5384d0c --- /dev/null +++ b/server/test/integration/checksRepositoryGroupedChecks.test.ts @@ -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 = {}) => + 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, + }); + }); +}); From e5282b90997e6e0284163805a60ce910b622d462 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Thu, 30 Jul 2026 12:04:25 -0700 Subject: [PATCH 5/5] opacity -> 0.2 --- client/src/Components/monitors/charts/HistogramDetails.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/src/Components/monitors/charts/HistogramDetails.tsx b/client/src/Components/monitors/charts/HistogramDetails.tsx index a9dea6e0c..f0d501327 100644 --- a/client/src/Components/monitors/charts/HistogramDetails.tsx +++ b/client/src/Components/monitors/charts/HistogramDetails.tsx @@ -278,8 +278,8 @@ export const HistogramDetails = ({ dataKey={key} stroke={theme.palette.chart.phases[PHASE_COLOR_KEYS[key]]} fill={`url(#phaseGradient-${key})`} - fillOpacity={dimmed ? 0.05 : undefined} - strokeOpacity={dimmed ? 0.05 : undefined} + fillOpacity={dimmed ? 0.2 : undefined} + strokeOpacity={dimmed ? 0.2 : undefined} /> ); })}