Files
supabase/apps/studio/components/interfaces/DiskManagement/ComputeAndDiskUsageCharts.utils.ts
Saxon Fletcher b455d871e5 Add compute and disk usage charts (#48369)
## Summary

This is the second step towards merging compute and disk with
infrastructure. There are some usage charts on the current
infrastructure page that are useful to have in the context of compute
and disk settings. This branch adds two charts which give a general
sense of usage and whether an upgrade needs to happen. Other data points
in infrastructure can be found within observability and organisation
usage.

- Adds rolling seven-day Compute and Disk charts to the existing Compute
and Disk page.
- Shows CPU, memory, optional burstable disk IO, and disk usage split
into database, WAL, and system data.
- Covers loading, error, empty, warning, and critical states, retaining
the 75% warning and 90% critical thresholds.
- Uses a dedicated PageSection and keeps the charts in two columns from
680px.
- Uses the concise primary labels Compute and Disk, removes the database
report link, and removes tooltip icons from secondary metrics.
- Adds transformation, summary, and component tests covering dedicated
IO behavior, legacy anchors, responsive layout, rolling refetch, and
tooltip behavior.

## Stack

1. #48368
2. #48369 (this PR)
3. #48370

## How to test

1. Check out `chore/infra-compute-2-charts` and start Studio with `pnpm
dev:studio`.
2. Open `/project/<ref>/settings/compute-and-disk` on a project with
recent metrics.
3. Confirm the charts are in their own page section with standard
spacing below the page header.
4. Confirm the Compute chart shows CPU and memory, plus disk IO when
applicable, and the Disk chart splits usage into database, WAL, and
system data.
5. Confirm the primary labels are Compute and Disk, secondary metrics do
not show tooltip icons, and there is no Database Observability/report
link.
6. Resize across 680px. The charts should remain in two columns at and
above the breakpoint and stack into two rows below it.
7. Exercise loading, error, empty, warning, and critical responses with
the metrics mocks or response overrides. Confirm warning styling begins
at 75%, critical styling begins at 90%, and an error or empty response
does not break the configuration form.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added compute and disk usage charts to the disk management interface,
including metric cards for CPU, memory, disk I/O, database, WAL, and
system.
* Added usage status indicators, peak calculations, tooltips, and a
detailed disk breakdown with placeholders when data is missing.
* Added special handling for dedicated-I/O instances to hide burst-only
disk I/O.
* **Style**
* Simplified the disk space display by removing supplemental explanatory
text.
* **Tests**
* Added comprehensive test coverage for chart rendering,
loading/error/empty states, status/peak calculations, and rolling 7-day
data window behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-07-29 17:57:10 +08:00

150 lines
5.0 KiB
TypeScript

import type { InfraMonitoringResponse } from '@/data/analytics/infra-monitoring-query'
export type UsageMetricStatus = 'default' | 'warning' | 'negative'
export type ComputeUsageChartDatum = {
timestamp: string
maxCpuUsage: number
ramUsage: number
diskIoConsumption: number
}
export type DiskUsageChartDatum = {
timestamp: string
databaseBytes: number
walBytes: number
systemBytes: number
diskSizeBytes: number
databaseUsagePercent: number
walUsagePercent: number
systemUsagePercent: number
}
/** Coerces an API value (string | number | undefined) into a finite number, defaulting to 0. */
export const toNumber = (value: string | number | undefined) => {
const parsedValue = Number(value)
return Number.isFinite(parsedValue) ? parsedValue : 0
}
/** Constrains a percentage to the [0, 100] range so charts never overflow their axis. */
export const clampPercentage = (value: number) => Math.min(Math.max(value, 0), 100)
export const formatUsagePercent = (value: number | undefined) =>
value === undefined ? '—' : `${value.toFixed(0)}%`
export const getUsageMetricStatus = (value: number | undefined): UsageMetricStatus => {
if (value === undefined) return 'default'
if (value >= 90) return 'negative'
if (value >= 75) return 'warning'
return 'default'
}
export const getWorstUsageMetricStatus = (
...values: Array<number | undefined>
): UsageMetricStatus => {
const statuses = values.map(getUsageMetricStatus)
if (statuses.includes('negative')) return 'negative'
if (statuses.includes('warning')) return 'warning'
return 'default'
}
/** Returns the highest numeric value for a given key across all data points, or undefined when empty. */
export const getPeakChartValue = <T extends Record<string, unknown>>(
data: T[],
dataKey: keyof T
): number | undefined => {
const values = data
.map((point) => point[dataKey] as unknown)
.filter((value): value is number => typeof value === 'number')
if (values.length === 0) return undefined
return Math.max(...values)
}
/**
* Transforms a raw infra-monitoring response into the compute and disk chart series.
* Disk points without a known disk size are dropped so usage percentages stay meaningful.
*/
export const buildUsageChartData = (
usageData: InfraMonitoringResponse | undefined
): { computeChartData: ComputeUsageChartDatum[]; diskChartData: DiskUsageChartDatum[] } => {
if (!usageData || !('series' in usageData)) {
return { computeChartData: [], diskChartData: [] }
}
const computeChartData = usageData.data.map((point) => ({
timestamp: point.period_start,
maxCpuUsage: clampPercentage(toNumber(point.values.max_cpu_usage)),
ramUsage: clampPercentage(toNumber(point.values.ram_usage)),
diskIoConsumption: clampPercentage(toNumber(point.values.disk_io_consumption)),
}))
const diskChartData = usageData.data.flatMap((point) => {
const databaseBytes = toNumber(point.values.pg_database_size)
const walBytes = toNumber(point.values.disk_fs_used_wal)
const systemBytes = toNumber(point.values.disk_fs_used_system)
const totalBytes = toNumber(point.values.disk_fs_size)
if (totalBytes <= 0) return []
return {
timestamp: point.period_start,
databaseBytes,
walBytes,
systemBytes,
diskSizeBytes: totalBytes,
databaseUsagePercent: clampPercentage((databaseBytes / totalBytes) * 100),
walUsagePercent: clampPercentage((walBytes / totalBytes) * 100),
systemUsagePercent: clampPercentage((systemBytes / totalBytes) * 100),
}
})
return { computeChartData, diskChartData }
}
/** Derives peak compute values and the worst-case status for metrics supported by the instance. */
export const getComputeUsageSummary = (
data: ComputeUsageChartDatum[],
includeDiskIo: boolean = true
) => {
const peakCpuUsage = getPeakChartValue(data, 'maxCpuUsage')
const peakMemoryUsage = getPeakChartValue(data, 'ramUsage')
const peakDiskIoUsage = getPeakChartValue(data, 'diskIoConsumption')
const supportedPeaks = [
peakCpuUsage,
peakMemoryUsage,
...(includeDiskIo ? [peakDiskIoUsage] : []),
]
const peaks = supportedPeaks.filter((value): value is number => value !== undefined)
const peakComputeUsage = peaks.length > 0 ? Math.max(...peaks) : undefined
return {
peakCpuUsage,
peakMemoryUsage,
peakDiskIoUsage,
peakComputeUsage,
status: getWorstUsageMetricStatus(...supportedPeaks),
}
}
/** Derives the latest used/total bytes, overall usage percentage, and status for the disk card. */
export const getDiskUsageSummary = (data: DiskUsageChartDatum[]) => {
const latestDataPoint = data[data.length - 1]
const usedBytes =
(latestDataPoint?.databaseBytes ?? 0) +
(latestDataPoint?.walBytes ?? 0) +
(latestDataPoint?.systemBytes ?? 0)
const sizeBytes = latestDataPoint?.diskSizeBytes ?? 0
const usagePercent = sizeBytes > 0 ? clampPercentage((usedBytes / sizeBytes) * 100) : undefined
return {
latestDataPoint,
usedBytes,
sizeBytes,
usagePercent,
status: getUsageMetricStatus(usagePercent),
}
}