diff --git a/client/src/Components/common/charts/HeatmapResponseTimeTooltip.tsx b/client/src/Components/common/charts/HeatmapResponseTimeTooltip.tsx index 8bc651c8c..38ad25b9f 100644 --- a/client/src/Components/common/charts/HeatmapResponseTimeTooltip.tsx +++ b/client/src/Components/common/charts/HeatmapResponseTimeTooltip.tsx @@ -7,6 +7,7 @@ import { useTheme } from "@mui/material/styles"; import { useSelector } from "react-redux"; import type { RootState } from "@/Types/state"; import { useTranslation } from "react-i18next"; +import prettyMilliseconds from "pretty-ms"; type HeatmapCheck = | CheckSnapshot @@ -58,7 +59,9 @@ export const HeatmapResponseTimeTooltip = ({ {t("common.labels.responseTime")}:{" "} - {check?.originalResponseTime?.toFixed() ?? "N/A"} ms + {check?.responseTime + ? prettyMilliseconds(check.responseTime, { compact: true }) + : "N/A"} Status:{" "} diff --git a/client/src/Components/common/charts/HistogramResponseTime.tsx b/client/src/Components/common/charts/HistogramResponseTime.tsx index d9485318a..eca798011 100644 --- a/client/src/Components/common/charts/HistogramResponseTime.tsx +++ b/client/src/Components/common/charts/HistogramResponseTime.tsx @@ -8,6 +8,7 @@ import { HeatmapResponseTimeTooltip } from "./HeatmapResponseTimeTooltip"; import { useMemo } from "react"; import { useTranslation } from "react-i18next"; import { MAX_RECENT_CHECKS } from "@/Types/Monitor"; +import { computeBarHeights } from "@/Utils/DataUtils"; interface HistogramResponseTimeProps { checks: CheckSnapshot[]; @@ -29,12 +30,12 @@ const calculateResponseTimeStats = (checks: CheckSnapshot[]): ResponseTimeStats return { max: "-", avg: "-" }; } - const validChecks = checks.filter((check) => check.originalResponseTime != null); + const validChecks = checks.filter((check) => check.responseTime != null); if (validChecks.length === 0) { return { max: "-", avg: "-" }; } - const responseTimes = validChecks.map((check) => check.originalResponseTime); + const responseTimes = validChecks.map((check) => check.responseTime); const max = Math.round(Math.max(...responseTimes)); const avg = Math.round( responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length @@ -54,7 +55,7 @@ export const HistogramResponseTime = ({ const { t } = useTranslation(); const stats = useMemo(() => calculateResponseTimeStats(checks), [checks]); - + const barHeights = useMemo(() => computeBarHeights(checks), [checks]); if (!Array.isArray(checks) || checks.length === 0) return null; const data = @@ -111,7 +112,7 @@ export const HistogramResponseTime = ({ > {data.map((check, index) => { const isPlaceholder = (check as any).status === "placeholder"; - const heightPct = `${Math.max(0, Math.min(100, (check as any).responseTime ?? 0))}%`; + const heightPct = `${barHeights[index] ?? 0}%`; const barColor = check.status === true ? theme.palette.success.light diff --git a/client/src/Pages/Settings/DummyChart.tsx b/client/src/Pages/Settings/DummyChart.tsx index 47b3e45ea..78a05ed5f 100644 --- a/client/src/Pages/Settings/DummyChart.tsx +++ b/client/src/Pages/Settings/DummyChart.tsx @@ -13,13 +13,12 @@ const generateDummyChecks = (): CheckSnapshot[] => { const checks: CheckSnapshot[] = []; for (let i = 0; i < MAX_RECENT_CHECKS; i++) { const isUp = Math.random() > 0.1; - const responseTime = Math.floor(Math.random() * 80) + 20; + const responseTime = Math.floor(Math.random() * 800) + 20; checks.push({ id: `dummy-${i}`, status: isUp, statusCode: isUp ? 200 : 500, responseTime: responseTime, - originalResponseTime: responseTime, message: "", createdAt: new Date(Date.now() - i * 60000).toISOString(), }); diff --git a/client/src/Pages/StatusPage/Status/themes/shared/BaseStatusPage.tsx b/client/src/Pages/StatusPage/Status/themes/shared/BaseStatusPage.tsx index 1dfc0bd1b..96beeb173 100644 --- a/client/src/Pages/StatusPage/Status/themes/shared/BaseStatusPage.tsx +++ b/client/src/Pages/StatusPage/Status/themes/shared/BaseStatusPage.tsx @@ -29,7 +29,7 @@ import { import { useStatusPageTheme } from "@/Pages/StatusPage/Status/themes/StatusPageThemeProvider"; import { formatPercentage } from "@/Utils/FormatUtils"; -type StatusPageMonitor = Monitor & { checks?: Monitor["recentChecks"] }; +type StatusPageMonitor = Monitor; export interface BaseStyles { page: SxProps; diff --git a/client/src/Pages/StatusPage/Status/themes/shared/ThemedChartTooltip.tsx b/client/src/Pages/StatusPage/Status/themes/shared/ThemedChartTooltip.tsx new file mode 100644 index 000000000..597000b17 --- /dev/null +++ b/client/src/Pages/StatusPage/Status/themes/shared/ThemedChartTooltip.tsx @@ -0,0 +1,30 @@ +import type { CheckSnapshot } from "@/Types/Check"; +import Stack from "@mui/material/Stack"; +import Typography from "@mui/material/Typography"; +import prettyMilliseconds from "pretty-ms"; +import { formatDateWithTz } from "@/Utils/TimeUtils"; +import { useStatusPageTheme } from "@/Pages/StatusPage/Status/themes/StatusPageThemeProvider"; +import { useTranslation } from "react-i18next"; + +export const ThemedChartTooltip = ({ check }: { check: CheckSnapshot }) => { + const { t } = useTranslation(); + const { timezone } = useStatusPageTheme(); + return ( + + + {check.status + ? `${prettyMilliseconds(check.responseTime, { compact: true })}` + : t("pages.statusPages.monitorsList.chart.downTooltip")} + + + {formatDateWithTz(check.createdAt, "ddd, MMMM D, YYYY, HH:mm A", timezone)} + + + ); +}; diff --git a/client/src/Pages/StatusPage/Status/themes/shared/ThemedHeatmap.tsx b/client/src/Pages/StatusPage/Status/themes/shared/ThemedHeatmap.tsx index fe56155c3..375fd1b0e 100644 --- a/client/src/Pages/StatusPage/Status/themes/shared/ThemedHeatmap.tsx +++ b/client/src/Pages/StatusPage/Status/themes/shared/ThemedHeatmap.tsx @@ -1,13 +1,10 @@ import Tooltip from "@mui/material/Tooltip"; import Box from "@mui/material/Box"; -import Stack from "@mui/material/Stack"; -import Typography from "@mui/material/Typography"; import type { SxProps, Theme } from "@mui/material/styles"; import { useTranslation } from "react-i18next"; import type { CheckSnapshot } from "@/Types/Check"; -import { formatDateWithTz } from "@/Utils/TimeUtils"; import { MAX_RECENT_CHECKS } from "@/Types/Monitor"; -import { useStatusPageTheme } from "../StatusPageThemeProvider"; +import { ThemedChartTooltip } from "@/Pages/StatusPage/Status/themes/shared/ThemedChartTooltip"; const CELLS = MAX_RECENT_CHECKS; @@ -29,7 +26,6 @@ const classify = (check: CheckSnapshot): Exclude => { export const ThemedHeatmap = ({ checks, containerSx, cellSx }: Props) => { const { t } = useTranslation(); - const { timezone } = useStatusPageTheme(); const source = checks.slice(-CELLS); const padded: (CheckSnapshot | null)[] = [ @@ -53,24 +49,7 @@ export const ThemedHeatmap = ({ checks, containerSx, cellSx }: Props) => { ); } const kind = classify(check); - const tooltipContent = ( - - - {check.status - ? `${check.responseTime} ms` - : t("pages.statusPages.monitorsList.chart.downTooltip")} - - - {formatDateWithTz(check.createdAt, "ddd, MMMM D, YYYY, HH:mm A", timezone)} - - - ); + const tooltipContent = ; return ( { const { t } = useTranslation(); - const { timezone } = useStatusPageTheme(); - const { padded, max, avg, peak } = useMemo(() => { + const { padded, heights, avg, peak } = useMemo(() => { const source = checks.slice(-CELLS); const out: (CheckSnapshot | null)[] = [ ...source, ...Array.from({ length: Math.max(0, CELLS - source.length) }, () => null), ]; + const heights = computeBarHeights(source); const valid = out.filter((c): c is CheckSnapshot => c !== null && c.responseTime > 0); const maxRt = valid.length ? Math.max(...valid.map((c) => c.responseTime)) : 1; const avgRt = valid.length ? Math.round(valid.reduce((s, c) => s + c.responseTime, 0) / valid.length) : 0; - return { padded: out, max: maxRt, avg: avgRt, peak: valid.length ? maxRt : 0 }; + return { padded: out, heights, avg: avgRt, peak: maxRt }; }, [checks]); return ( @@ -61,32 +60,8 @@ export const ThemedHistogram = ({ /> ); } - const height = Math.max( - MIN_HEIGHT_PCT, - Math.round((check.responseTime / max) * 100) - ); - const tooltipContent = ( - - - {check.status - ? `${check.responseTime} ms` - : t("pages.statusPages.monitorsList.chart.downTooltip")} - - - {formatDateWithTz( - check.createdAt, - "ddd, MMMM D, YYYY, HH:mm A", - timezone - )} - - - ); + const height = heights[i] ?? MIN_HEIGHT_PCT; + const tooltipContent = ; return ( export const ThemedInfrastructure = ({ monitor, sxApi }: Props) => { const { t } = useTranslation(); - const latest = monitor.recentChecks?.[0] ?? monitor.checks?.[0]; + const latest = monitor.recentChecks?.[0]; const renderEmpty = () => ( {t("pages.statusPages.monitorsList.noData")} diff --git a/client/src/Types/Check.ts b/client/src/Types/Check.ts index cfd072944..c930eacad 100644 --- a/client/src/Types/Check.ts +++ b/client/src/Types/Check.ts @@ -250,14 +250,7 @@ export interface ChecksSummary { downChecks: number; } -export type CheckSnapshot = Omit & { - originalResponseTime: number; -}; - +export type CheckSnapshot = Omit; export interface HasResponseTime { responseTime: number; } - -export type NormalizedCheck = T & { - originalResponseTime: number; -}; diff --git a/client/src/Utils/DataUtils.ts b/client/src/Utils/DataUtils.ts index 40bbd1b8b..28fdfb7b5 100644 --- a/client/src/Utils/DataUtils.ts +++ b/client/src/Utils/DataUtils.ts @@ -1,47 +1,3 @@ -const MIN_OUT = 10; -const MAX_OUT = 100; - -export const normalizeResponseTimes = ( - checks: T[], - key: K -): (T & { normalResponseTime: number })[] => { - if (!Array.isArray(checks) || checks.length === 0) - return checks as (T & { - normalResponseTime: number; - })[]; - - if (checks.length === 1) { - return [ - { - ...checks[0], - normalResponseTime: 50, - }, - ]; - } - - const getVal = (check: T): number => { - const v = check[key] as unknown; - return typeof v === "number" && Number.isFinite(v) ? v : 0; - }; - - const { min, max } = checks.reduce( - (acc, check) => { - const v = getVal(check); - if (v > acc.max) acc.max = v; - if (v < acc.min) acc.min = v; - return acc; - }, - { max: -Infinity, min: Infinity } - ); - - const range = max - min || 1; - - return checks.map((check) => ({ - ...check, - normalResponseTime: MIN_OUT + ((getVal(check) - min) * (MAX_OUT - MIN_OUT)) / range, - })); -}; - // Interpolate color between three theme colors over 0-100 range. // 0-50 => start (success.light), 50-75 => mid (warning.light), 75-100 => end (error.light) export const getResponseColor = ( @@ -129,3 +85,32 @@ export const getResponseColor = ( } return normalizeToHex(safe.end); }; + +const MIN_HEIGHT_PCT = 8; +const CAP_PERCENTILE = 95; + +const percentile = (sortedValues: number[], p: number): number => { + const index = (p / 100) * (sortedValues.length - 1); + const lower = Math.floor(index); + const upper = lower + 1; + const weight = index % 1; + if (upper >= sortedValues.length) return sortedValues[lower]; + return sortedValues[lower] * (1 - weight) + sortedValues[upper] * weight; +}; + +export const computeBarHeights = ( + checks: { responseTime?: number | null }[] +): number[] => { + const values = checks.map((check) => { + return typeof check.responseTime === "number" && Number.isFinite(check.responseTime) + ? Math.max(0, check.responseTime) + : 0; + }); + + const sorted = values.slice().sort((a, b) => a - b); + const cap = percentile(sorted, CAP_PERCENTILE); + if (cap <= 0) return values.map(() => MIN_HEIGHT_PCT); + return values.map((value) => { + return Math.max(MIN_HEIGHT_PCT, Math.min(100, (value / cap) * 100)); + }); +}; diff --git a/server/src/api/validation/monitorValidation.ts b/server/src/api/validation/monitorValidation.ts index 86db942a5..441809c42 100644 --- a/server/src/api/validation/monitorValidation.ts +++ b/server/src/api/validation/monitorValidation.ts @@ -25,7 +25,6 @@ export const getMonitorByIdQueryValidation = z.object({ limit: z.coerce.number().optional(), dateRange: z.enum(DateRanges).optional(), numToDisplay: z.coerce.number().optional(), - normalize: booleanCoercion.optional(), continent: z.union([z.enum(GeoContinents), z.array(z.enum(GeoContinents))]).optional(), }); diff --git a/server/src/domain/checks/check.type.ts b/server/src/domain/checks/check.type.ts index d4c47cfb9..d6e60c3e3 100644 --- a/server/src/domain/checks/check.type.ts +++ b/server/src/domain/checks/check.type.ts @@ -168,10 +168,6 @@ export interface HasResponseTime { responseTime: number; } -export type NormalizedCheck = T & { - originalResponseTime: number; -}; - export type CheckSnapshot = Omit; export interface HardwareDiskStats { diff --git a/server/src/domain/monitors/monitor.service.ts b/server/src/domain/monitors/monitor.service.ts index 29046f83d..7a8478c5a 100644 --- a/server/src/domain/monitors/monitor.service.ts +++ b/server/src/domain/monitors/monitor.service.ts @@ -1,4 +1,3 @@ -import { NormalizeData } from "@/utils/dataUtils.js"; import { type Monitor } from "@/domain/monitors/monitor.type.js"; import type { MonitorType, @@ -364,7 +363,7 @@ export class MonitorService implements IMonitorService { const monitorsWithChecks = monitors.map((monitor: Monitor) => { const rawChecks = monitor.recentChecks ?? []; const isSnapshotType = snapshotOnlyRequest || snapshotTypes.includes(monitor.type); - const checks = isSnapshotType ? rawChecks.slice(0, 1) : NormalizeData(rawChecks, 10, 100); + const checks = isSnapshotType ? rawChecks.slice(0, 1) : rawChecks; monitor.recentChecks = checks; return monitor; }); diff --git a/server/src/domain/status-pages/status-page.service.ts b/server/src/domain/status-pages/status-page.service.ts index 834f87384..7a2a0724b 100644 --- a/server/src/domain/status-pages/status-page.service.ts +++ b/server/src/domain/status-pages/status-page.service.ts @@ -10,7 +10,6 @@ import { import { AppError } from "@/utils/AppError.js"; import { normalizeStatusPageDomain } from "@/utils/statusPageDomain.js"; import { Monitor } from "@/domain/monitors/monitor.type.js"; -import { NormalizeData } from "@/utils/dataUtils.js"; export interface IStatusPageService { createStatusPage(userId: string, teamId: string, image: Express.Multer.File | undefined, data: Partial): Promise; @@ -79,7 +78,6 @@ export class StatusPageService implements IStatusPageService { status: monitor.status, uptimePercentage: monitor.uptimePercentage, recentChecks: monitor.recentChecks, - checks: NormalizeData(monitor.recentChecks, 10, 100), }; if (showURL) { diff --git a/server/src/domain/status-pages/status-page.type.ts b/server/src/domain/status-pages/status-page.type.ts index 65f331ad9..e80087b39 100644 --- a/server/src/domain/status-pages/status-page.type.ts +++ b/server/src/domain/status-pages/status-page.type.ts @@ -1,5 +1,4 @@ import type { Monitor } from "@/domain/monitors/monitor.type.js"; -import type { NormalizedCheck, CheckSnapshot } from "@/domain/checks/check.type.js"; export const StatusPageTypes = ["uptime", "infrastructure"] as const; export type StatusPageType = (typeof StatusPageTypes)[number]; @@ -48,7 +47,7 @@ export interface StatusPage { } export type PublicStatusPageMonitor = Pick & - Partial> & { checks: NormalizedCheck[] }; + Partial>; export interface PublicStatusPagePayload { statusPage: StatusPage; diff --git a/server/src/utils/dataUtils.ts b/server/src/utils/dataUtils.ts index 2c15b943e..08e8de740 100755 --- a/server/src/utils/dataUtils.ts +++ b/server/src/utils/dataUtils.ts @@ -1,4 +1,3 @@ -import type { HasResponseTime, NormalizedCheck } from "@/domain/checks/check.type.js"; import { type DateRange } from "@/types/query.js"; export const getDateForRange = (dateRange: DateRange): Date => { @@ -32,32 +31,3 @@ export const getDateFormat = (dateRange: DateRange): string => { }; return formatLookup[dateRange]; }; - -const percentileBy = (arr: T[], percentile: number, value: (item: T) => number): number => { - const sorted = arr.slice().sort((a, b) => value(a) - value(b)); - const index = (percentile / 100) * (sorted.length - 1); - const lower = Math.floor(index); - const upper = lower + 1; - const weight = index % 1; - if (upper >= sorted.length) return value(sorted[lower]!); - return value(sorted[lower]!) * (1 - weight) + value(sorted[upper]!) * weight; -}; - -const rescale = (raw: number, min: number, max: number, rangeMin: number, rangeMax: number): number => { - const scaled = rangeMin + ((raw - min) * (rangeMax - rangeMin)) / (max - min); - return Math.max(rangeMin, Math.min(rangeMax, scaled)); -}; - -export const NormalizeData = (checks: T[], rangeMin: number, rangeMax: number): NormalizedCheck[] => { - const original = (check: T) => (typeof check.responseTime === "number" ? check.responseTime : 0); - if (checks.length <= 1) { - return checks.map((check) => ({ ...check, originalResponseTime: original(check) })); - } - const min = percentileBy(checks, 0, (c) => c.responseTime); - const max = percentileBy(checks, 95, (c) => c.responseTime); - return checks.map((check) => ({ - ...check, - responseTime: rescale(check.responseTime, min, max, rangeMin, rangeMax), - originalResponseTime: original(check), - })); -}; diff --git a/server/test/unit/services/statusPageService.test.ts b/server/test/unit/services/statusPageService.test.ts index e0115ab99..149179bd7 100644 --- a/server/test/unit/services/statusPageService.test.ts +++ b/server/test/unit/services/statusPageService.test.ts @@ -315,8 +315,8 @@ describe("StatusPageService", () => { status: "up", uptimePercentage: 99.9, recentChecks: [], - checks: [], }); + expect(monitors[0]).not.toHaveProperty("checks"); }); it("orders monitors to match the status page's monitor list", async () => { diff --git a/server/test/unit/utils/dataUtils.test.ts b/server/test/unit/utils/dataUtils.test.ts index af9434bab..d89cc0762 100644 --- a/server/test/unit/utils/dataUtils.test.ts +++ b/server/test/unit/utils/dataUtils.test.ts @@ -1,18 +1,7 @@ import { describe, expect, it } from "@jest/globals"; -import { getDateForRange, getDateFormat, NormalizeData } from "../../../src/utils/dataUtils.ts"; +import { getDateForRange, getDateFormat } from "../../../src/utils/dataUtils.ts"; import { DateRanges, type DateRange } from "../../../src/types/query.ts"; -// ── Helpers ────────────────────────────────────────────────────────────────── - -const makeCheck = (responseTime: number, overrides?: Record) => ({ - id: `check-${responseTime}`, - status: true, - responseTime, - ...overrides, -}); - -// ── Tests ──────────────────────────────────────────────────────────────────── - describe("getDateForRange", () => { it.each([ ["recent", 2 * 60 * 60 * 1000], @@ -53,68 +42,3 @@ describe("getDateFormat", () => { } }); }); - -describe("NormalizeData", () => { - // Fixture math: p0 of [100..500] is 100; p95 interpolates between the 4th and 5th - // sorted values at weight 0.8 → 400*0.2 + 500*0.8 = 480. Values rescale into - // [10, 100] via 10 + (rt - 100) * 90 / 380, clamped. - it("rescales responseTime into [rangeMin, rangeMax] anchored to the p0–p95 window", () => { - const checks = [100, 200, 300, 400, 500].map((rt) => makeCheck(rt)); - - const result = NormalizeData(checks, 10, 100); - - expect(result[0]!.responseTime).toBe(10); - expect(result[1]!.responseTime).toBeCloseTo(33.6842, 4); - expect(result[2]!.responseTime).toBeCloseTo(57.3684, 4); - expect(result[3]!.responseTime).toBeCloseTo(81.0526, 4); - }); - - it("clamps values above the p95 anchor to rangeMax", () => { - const checks = [100, 200, 300, 400, 500].map((rt) => makeCheck(rt)); - - const result = NormalizeData(checks, 10, 100); - - expect(result[4]!.responseTime).toBe(100); - }); - - it("preserves the raw value in originalResponseTime and spreads other fields", () => { - const checks = [makeCheck(100, { message: "OK" }), makeCheck(500)]; - - const result = NormalizeData(checks, 10, 100); - - expect(result[0]!.originalResponseTime).toBe(100); - expect(result[1]!.originalResponseTime).toBe(500); - expect(result[0]).toMatchObject({ id: "check-100", status: true, message: "OK" }); - }); - - it("passes a single check through, only adding originalResponseTime", () => { - const result = NormalizeData([makeCheck(250)], 10, 100); - - expect(result).toEqual([{ id: "check-250", status: true, responseTime: 250, originalResponseTime: 250 }]); - }); - - it("returns an empty array for empty input", () => { - expect(NormalizeData([], 10, 100)).toEqual([]); - }); - - it("records originalResponseTime as 0 for a non-numeric responseTime (failed checks)", () => { - const checks = [makeCheck(undefined as unknown as number), makeCheck(100), makeCheck(200)]; - - const result = NormalizeData(checks, 10, 100); - - expect(result[0]!.originalResponseTime).toBe(0); - }); - - // Characterization, not endorsement: when every value is equal the p0–p95 window - // has zero width and the rescale divides by zero. Fixing this is a planned - // follow-up (docs/planning/dataUtils-generic-normalization-refactor.md); this - // test pins the current behavior so the fix is a deliberate, visible change. - it("produces NaN when all values are equal (division by zero — known edge case)", () => { - const result = NormalizeData([makeCheck(50), makeCheck(50), makeCheck(50)], 10, 100); - - result.forEach((check) => { - expect(check.responseTime).toBeNaN(); - expect(check.originalResponseTime).toBe(50); - }); - }); -});