mirror of
https://github.com/supabase/supabase.git
synced 2026-09-06 09:59:03 +08:00
## 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>
278 lines
8.8 KiB
TypeScript
278 lines
8.8 KiB
TypeScript
import { render, screen } from '@testing-library/react'
|
|
import type { ReactNode } from 'react'
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
|
|
import { ComputeAndDiskUsageCharts } from './ComputeAndDiskUsageCharts'
|
|
import type { InfraMonitoringMultiResponse } from '@/data/analytics/infra-monitoring-query'
|
|
|
|
const { mockGetInfraMonitoringAttributes, mockUseInfraMonitoringAttributesQuery, mockUseProject } =
|
|
vi.hoisted(() => ({
|
|
mockGetInfraMonitoringAttributes: vi.fn(),
|
|
mockUseInfraMonitoringAttributesQuery: vi.fn(),
|
|
mockUseProject: vi.fn(),
|
|
}))
|
|
|
|
vi.mock('common', () => ({
|
|
useParams: () => ({ ref: 'project-ref' }),
|
|
}))
|
|
|
|
vi.mock('ui', () => ({
|
|
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
|
|
}))
|
|
|
|
vi.mock('ui-patterns/Chart', async () => {
|
|
const React = await vi.importActual<typeof import('react')>('react')
|
|
const ChartStateContext = React.createContext({ isLoading: false, isErrored: false })
|
|
|
|
return {
|
|
Chart: ({
|
|
children,
|
|
isLoading,
|
|
isErrored,
|
|
}: {
|
|
children: ReactNode
|
|
isLoading: boolean
|
|
isErrored: boolean
|
|
}) => (
|
|
<ChartStateContext.Provider value={{ isLoading, isErrored }}>
|
|
{children}
|
|
</ChartStateContext.Provider>
|
|
),
|
|
ChartCard: ({ children, className }: { children: ReactNode; className?: string }) => (
|
|
<div className={className}>{children}</div>
|
|
),
|
|
ChartContent: ({
|
|
children,
|
|
isEmpty,
|
|
loadingState,
|
|
errorState,
|
|
emptyState,
|
|
}: {
|
|
children: ReactNode
|
|
isEmpty: boolean
|
|
loadingState: ReactNode
|
|
errorState: ReactNode
|
|
emptyState: ReactNode
|
|
}) => {
|
|
const { isLoading, isErrored } = React.useContext(ChartStateContext)
|
|
|
|
if (isLoading) return loadingState
|
|
if (isErrored) return errorState
|
|
if (isEmpty) return emptyState
|
|
return children
|
|
},
|
|
ChartEmptyState: ({ title, description }: { title: string; description?: string }) => (
|
|
<div>
|
|
<span>{title}</span>
|
|
{description && <span>{description}</span>}
|
|
</div>
|
|
),
|
|
ChartHeader: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
|
ChartLine: ({ dataKey, dataKeys }: { dataKey: string; dataKeys: string[] }) => (
|
|
<div data-testid={`chart-line-${dataKey}`} data-keys={dataKeys.join(',')} />
|
|
),
|
|
ChartLoadingState: () => <div>Loading chart</div>,
|
|
ChartMetric: ({
|
|
label,
|
|
value,
|
|
status,
|
|
tooltip,
|
|
}: {
|
|
label: string
|
|
value: ReactNode
|
|
status?: string
|
|
tooltip?: ReactNode
|
|
}) => (
|
|
<div
|
|
data-testid={`metric-${label}`}
|
|
data-status={status}
|
|
data-has-tooltip={tooltip !== undefined}
|
|
>
|
|
{label}: {value}
|
|
</div>
|
|
),
|
|
}
|
|
})
|
|
|
|
vi.mock('@/data/analytics/infra-monitoring-query', () => ({
|
|
getInfraMonitoringAttributes: mockGetInfraMonitoringAttributes,
|
|
useInfraMonitoringAttributesQuery: mockUseInfraMonitoringAttributesQuery,
|
|
}))
|
|
|
|
vi.mock('@/hooks/misc/useSelectedProject', () => ({
|
|
useSelectedProjectQuery: mockUseProject,
|
|
}))
|
|
|
|
vi.mock('@/lib/helpers', () => ({
|
|
formatBytes: (bytes: number) => `${bytes} bytes`,
|
|
}))
|
|
|
|
const buildUsageResponse = ({
|
|
cpu = 40,
|
|
memory = 50,
|
|
diskIo = 60,
|
|
database = 40,
|
|
wal = 5,
|
|
system = 5,
|
|
diskSize = 100,
|
|
}: {
|
|
cpu?: number
|
|
memory?: number
|
|
diskIo?: number
|
|
database?: number
|
|
wal?: number
|
|
system?: number
|
|
diskSize?: number
|
|
} = {}): InfraMonitoringMultiResponse => ({
|
|
series: {},
|
|
data: [
|
|
{
|
|
period_start: '2026-07-20T00:00:00.000Z',
|
|
values: {
|
|
max_cpu_usage: String(cpu),
|
|
ram_usage: String(memory),
|
|
disk_io_consumption: String(diskIo),
|
|
pg_database_size: String(database),
|
|
disk_fs_used_wal: String(wal),
|
|
disk_fs_used_system: String(system),
|
|
disk_fs_size: String(diskSize),
|
|
},
|
|
},
|
|
],
|
|
})
|
|
|
|
describe('ComputeAndDiskUsageCharts', () => {
|
|
beforeEach(() => {
|
|
vi.clearAllMocks()
|
|
mockUseProject.mockReturnValue({ data: { infra_compute_size: 'micro' } })
|
|
mockUseInfraMonitoringAttributesQuery.mockReturnValue({
|
|
data: buildUsageResponse(),
|
|
isLoading: false,
|
|
isError: false,
|
|
})
|
|
mockGetInfraMonitoringAttributes.mockResolvedValue(buildUsageResponse())
|
|
})
|
|
|
|
afterEach(() => {
|
|
vi.useRealTimers()
|
|
})
|
|
|
|
it('renders warning and critical summaries and all chart data', () => {
|
|
mockUseInfraMonitoringAttributesQuery.mockReturnValue({
|
|
data: buildUsageResponse({
|
|
cpu: 80,
|
|
memory: 91,
|
|
diskIo: 70,
|
|
database: 80,
|
|
wal: 5,
|
|
system: 5,
|
|
}),
|
|
isLoading: false,
|
|
isError: false,
|
|
})
|
|
|
|
const { container } = render(<ComputeAndDiskUsageCharts />)
|
|
|
|
expect(screen.getByTestId('metric-Compute')).toHaveTextContent('91%')
|
|
expect(screen.getByTestId('metric-Compute')).toHaveAttribute('data-status', 'negative')
|
|
expect(screen.getByTestId('metric-CPU')).toHaveAttribute('data-status', 'warning')
|
|
expect(screen.getByTestId('metric-Memory')).toHaveAttribute('data-status', 'negative')
|
|
expect(screen.getByTestId('metric-Disk IO')).toHaveAttribute('data-status', 'default')
|
|
expect(screen.getByTestId('metric-Compute')).toHaveAttribute('data-has-tooltip', 'true')
|
|
expect(screen.getByTestId('metric-Disk')).toHaveAttribute('data-has-tooltip', 'true')
|
|
for (const label of ['CPU', 'Memory', 'Disk IO', 'Database', 'WAL', 'System']) {
|
|
expect(screen.getByTestId(`metric-${label}`)).toHaveAttribute('data-has-tooltip', 'false')
|
|
}
|
|
expect(screen.getByTestId('metric-Disk')).toHaveTextContent('90%')
|
|
expect(screen.getByTestId('metric-Disk')).toHaveAttribute('data-status', 'negative')
|
|
expect(screen.getByTestId('chart-line-maxCpuUsage')).toHaveAttribute(
|
|
'data-keys',
|
|
'maxCpuUsage,ramUsage,diskIoConsumption'
|
|
)
|
|
expect(container.firstElementChild).toHaveClass(
|
|
'grid-cols-1',
|
|
'@[680px]:grid-cols-2',
|
|
'@[680px]:items-stretch'
|
|
)
|
|
expect(container.querySelector('#cpu')).toBeInTheDocument()
|
|
expect(container.querySelector('#ram')).toBeInTheDocument()
|
|
expect(container.querySelector('#disk_io')).toBeInTheDocument()
|
|
expect(container.querySelector('#disk')).toBeInTheDocument()
|
|
})
|
|
|
|
it('hides burst-only disk IO and excludes it from status on dedicated-I/O compute', () => {
|
|
mockUseProject.mockReturnValue({ data: { infra_compute_size: '4xlarge' } })
|
|
mockUseInfraMonitoringAttributesQuery.mockReturnValue({
|
|
data: buildUsageResponse({ cpu: 40, memory: 50, diskIo: 95 }),
|
|
isLoading: false,
|
|
isError: false,
|
|
})
|
|
|
|
render(<ComputeAndDiskUsageCharts />)
|
|
|
|
expect(screen.getByTestId('metric-Compute')).toHaveTextContent('50%')
|
|
expect(screen.getByTestId('metric-Compute')).toHaveAttribute('data-status', 'default')
|
|
expect(screen.queryByTestId('metric-Disk IO')).not.toBeInTheDocument()
|
|
expect(screen.getByTestId('chart-line-maxCpuUsage')).toHaveAttribute(
|
|
'data-keys',
|
|
'maxCpuUsage,ramUsage'
|
|
)
|
|
})
|
|
|
|
it('renders empty states without presenting missing disk metrics as zero', () => {
|
|
mockUseInfraMonitoringAttributesQuery.mockReturnValue({
|
|
data: undefined,
|
|
isLoading: false,
|
|
isError: false,
|
|
})
|
|
|
|
render(<ComputeAndDiskUsageCharts />)
|
|
|
|
expect(screen.getByText('No compute data')).toBeInTheDocument()
|
|
expect(screen.getByText('No disk data')).toBeInTheDocument()
|
|
expect(screen.getByTestId('metric-Database')).toHaveTextContent('—')
|
|
expect(screen.getByTestId('metric-WAL')).toHaveTextContent('—')
|
|
expect(screen.getByTestId('metric-System')).toHaveTextContent('—')
|
|
})
|
|
|
|
it.each([
|
|
{
|
|
state: 'loading',
|
|
queryState: { data: undefined, isLoading: true, isError: false },
|
|
expectedText: 'Loading chart',
|
|
},
|
|
{
|
|
state: 'error',
|
|
queryState: { data: undefined, isLoading: false, isError: true },
|
|
expectedText: 'Failed to load usage data',
|
|
},
|
|
])('renders both $state states', ({ queryState, expectedText }) => {
|
|
mockUseInfraMonitoringAttributesQuery.mockReturnValue(queryState)
|
|
|
|
render(<ComputeAndDiskUsageCharts />)
|
|
|
|
expect(screen.getAllByText(expectedText)).toHaveLength(2)
|
|
})
|
|
|
|
it('uses a fresh rolling seven-day window when the query refetches', async () => {
|
|
vi.useFakeTimers()
|
|
vi.setSystemTime(new Date('2026-07-20T12:00:00.000Z'))
|
|
|
|
render(<ComputeAndDiskUsageCharts />)
|
|
|
|
const [, options] = mockUseInfraMonitoringAttributesQuery.mock.calls[0]
|
|
vi.setSystemTime(new Date('2026-07-27T12:00:00.000Z'))
|
|
await options.queryFn({ signal: undefined })
|
|
|
|
expect(mockGetInfraMonitoringAttributes).toHaveBeenCalledWith(
|
|
expect.objectContaining({
|
|
projectRef: 'project-ref',
|
|
startDate: '2026-07-20T12:00:00.000Z',
|
|
endDate: '2026-07-27T12:00:00.000Z',
|
|
interval: '1d',
|
|
}),
|
|
undefined
|
|
)
|
|
})
|
|
})
|