mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
## Problem The Database section of Observability displays raw infrastructure API errors in metric cards, making failures confusing and repetitive. ## Fix Show one friendly alert with refresh, support, and service-status guidance when the infrastructure request fails. Keep Slow Queries visible, and show “Unable to load” only on affected cards for partial failures while preserving healthy metrics. The Overview Refresh button now invalidates the active project’s connection-limit query. Previously it used a cache key that matched no active query, so Peak Connections could stay on “Unable to load” while the other cards refreshed. Consolidates and supersedes #47491 and #47495, adapted to the current batched metrics implementation. ## How to test - Open Observability and verify that successful database metrics still render. - Simulate a failed infrastructure request. Expect one friendly alert, no raw backend message, and Slow Queries still visible. - Simulate an individual metric or connection-limit failure. Expect only the affected card to show “Unable to load”. - With the connection-limit request failing, click **Refresh** and confirm that Peak Connections shows “Unable to load”. Restore the response and click **Refresh** again. The card should show the peak and limit without a browser reload. ## QA results - **Hosted Refresh recovery passed on `ee646999af`.** After the connection-limit request recovered, one click sent a new request and replaced “Unable to load” with `6/90`. The other five hosted cases passed on `dbf78487f5`. [Automated QA review](https://github.com/supabase/supabase/pull/52216#pullrequestreview-6169329677) - **Local Chromium recovery passed on the same commit.** With a simulated HTTP 500 followed by success, Refresh retried the query and displayed `12/100`. CPU, Memory, and Disk remained healthy. - All 52 focused tests passed with retries disabled and shuffled order. The recovery test failed with the original Refresh handler. Studio typecheck passed. GitHub reported 38 successful checks and six skipped checks. Fixes https://linear.app/supabase/issue/DEBUG-155/frontend-should-render-nice-error-message-on-infra-monitoring-api ## QA screenshots ### Peak Connections before and after the Refresh fix **Before · `dbf78487f5`.** Peak Connections still showed “Unable to load” after two Refresh clicks, even as the other metrics reloaded.  **After · `ee646999af`.** Once the connection-limit request could succeed, the next Refresh click restored Peak Connections to `6/90`.  ### Local browser with HTTP overrides Actual PR component at `dbf78487f5`, rendered in a local fixture harness at a 1440 × 900 viewport. Playwright intercepted the infrastructure API request; these are local simulated error states, not hosted-preview captures. **Full request failure:** one friendly alert; raw backend details are hidden and Slow Queries remains visible.  **Partial failure:** only Disk IO Budget shows “Unable to load”; healthy metrics and Slow Queries remain visible.  **Recovery:** after restoring a successful response and reloading, all metric cards render normally.  ### Verified hosted preview Studio staging deployment for `dbf78487f5`, 1440 × 900. All database metric cards and Slow Queries return after Refresh.  The CPU card opens the Database report and preserves Last 24 hours. 
222 lines
8.6 KiB
TypeScript
222 lines
8.6 KiB
TypeScript
import { QueryClient } from '@tanstack/react-query'
|
|
import { fireEvent, screen, waitFor, within } from '@testing-library/react'
|
|
import { HttpResponse } from 'msw'
|
|
import { describe, expect, it, vi } from 'vitest'
|
|
|
|
import { DatabaseInfrastructureSection } from './DatabaseInfrastructureSection'
|
|
import { ObservabilityOverview } from './ObservabilityOverview'
|
|
import type { InfraMonitoringMultiResponse } from '@/data/analytics/infra-monitoring-query'
|
|
import { configKeys } from '@/data/config/keys'
|
|
import { databaseKeys } from '@/data/database/keys'
|
|
import { miscKeys } from '@/data/misc/keys'
|
|
import { projectKeys } from '@/data/projects/keys'
|
|
import { customRender } from '@/tests/lib/custom-render'
|
|
import { addAPIMock, type APIErrorBody } from '@/tests/lib/msw'
|
|
|
|
vi.mock('./ServiceHealthTable', () => ({ ServiceHealthTable: () => null }))
|
|
vi.mock('@/components/ui/Logs/ChartIntervalDropdown', () => ({
|
|
ChartIntervalDropdown: () => null,
|
|
}))
|
|
|
|
const values: Record<string, number> = {
|
|
avg_cpu_usage: 25,
|
|
ram_usage: 60,
|
|
disk_io_budget: 99,
|
|
disk_fs_used_system: 10,
|
|
disk_fs_used_wal: 5,
|
|
pg_database_size: 35,
|
|
disk_fs_size: 100,
|
|
pg_stat_database_num_backends: 12,
|
|
}
|
|
|
|
function mockMetrics(failedAttribute?: string, includeErrors = true) {
|
|
const requests: string[][] = []
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref/infra-monitoring',
|
|
response: ({ request }) => {
|
|
const attributes = new URL(request.url).searchParams.get('attributes')!.split(',')
|
|
requests.push(attributes)
|
|
const succeeded = attributes.filter(
|
|
(attribute) => failedAttribute !== '*' && attribute !== failedAttribute
|
|
)
|
|
const failed = attributes.filter((attribute) => !succeeded.includes(attribute))
|
|
const series = Object.fromEntries(
|
|
succeeded.map((attribute) => [
|
|
attribute,
|
|
{
|
|
totalAverage: values[attribute],
|
|
total: values[attribute],
|
|
format: '%',
|
|
yAxisLimit: 100,
|
|
},
|
|
])
|
|
)
|
|
const pointValues = Object.fromEntries(
|
|
succeeded.map((attribute) => [attribute, String(values[attribute])])
|
|
)
|
|
return HttpResponse.json<InfraMonitoringMultiResponse>({
|
|
series,
|
|
data: succeeded.length
|
|
? [{ period_start: '2026-09-24T00:00:00Z', values: pointValues }]
|
|
: [],
|
|
...(includeErrors
|
|
? {
|
|
errors: Object.fromEntries(
|
|
failed.map((attribute) => [attribute, { message: 'Metric is not supported' }])
|
|
),
|
|
}
|
|
: {}),
|
|
})
|
|
},
|
|
})
|
|
return requests
|
|
}
|
|
|
|
function renderMetrics({ hasMaxConnections = true, showOverview = false } = {}) {
|
|
const queryClient = new QueryClient({
|
|
defaultOptions: { queries: { retry: false, staleTime: Infinity } },
|
|
})
|
|
queryClient.setQueryData(projectKeys.detail('default'), {
|
|
ref: 'default',
|
|
status: 'ACTIVE_HEALTHY',
|
|
connectionString: 'postgresql://localhost/postgres',
|
|
})
|
|
if (hasMaxConnections) {
|
|
queryClient.setQueryData(databaseKeys.maxConnections('default'), { maxConnections: 100 })
|
|
}
|
|
queryClient.setQueryData(configKeys.postgrest('default'), { db_schema: 'public' })
|
|
queryClient.setQueryData(miscKeys.enabledFeaturesOverride(), { disabled_features: [] })
|
|
customRender(
|
|
showOverview ? (
|
|
<ObservabilityOverview />
|
|
) : (
|
|
<DatabaseInfrastructureSection
|
|
interval="1day"
|
|
refreshKey={0}
|
|
dbErrorRate={0}
|
|
isLoading={false}
|
|
slowQueriesCount={7}
|
|
/>
|
|
),
|
|
{ queryClient }
|
|
)
|
|
}
|
|
|
|
function card(label: string) {
|
|
return within(screen.getByRole('link', { name: new RegExp(label) }))
|
|
}
|
|
|
|
describe('DatabaseInfrastructureSection batched metrics', () => {
|
|
// Responses with an `errors` field are exercised by the isolation cases below
|
|
it('renders all metrics from one request without an errors field', async () => {
|
|
const requests = mockMetrics(undefined, false)
|
|
renderMetrics()
|
|
|
|
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
|
|
expect(await card('Memory').findByText('60%')).toBeInTheDocument()
|
|
expect(await card('Disk IO balance').findByText('99%')).toBeInTheDocument()
|
|
expect(await card('Disk Usage').findByText('50%')).toBeInTheDocument()
|
|
expect(await card('Peak Connections').findByText('12/100')).toBeInTheDocument()
|
|
expect(requests).toHaveLength(1)
|
|
expect(requests[0].sort()).toEqual(Object.keys(values).sort())
|
|
})
|
|
|
|
it.each([
|
|
['disk_io_budget', 'Disk IO balance'],
|
|
['disk_fs_used_wal', 'Disk Usage'],
|
|
['pg_stat_database_num_backends', 'Peak Connections'],
|
|
])('isolates a failed %s result to %s', async (attribute, label) => {
|
|
const requests = mockMetrics(attribute)
|
|
renderMetrics()
|
|
|
|
expect(await card(label).findByText('Unable to load')).toBeInTheDocument()
|
|
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
|
|
expect(await card('Memory').findByText('60%')).toBeInTheDocument()
|
|
expect(screen.getAllByText('Unable to load')).toHaveLength(1)
|
|
expect(screen.queryByText('Metric is not supported')).not.toBeInTheDocument()
|
|
expect(card(label).queryByText('0%')).not.toBeInTheDocument()
|
|
expect(requests).toHaveLength(1)
|
|
})
|
|
|
|
it('shows every affected card error when all results fail', async () => {
|
|
const requests = mockMetrics('*')
|
|
renderMetrics()
|
|
await waitFor(() => expect(screen.getAllByText('Unable to load')).toHaveLength(5))
|
|
expect(requests).toHaveLength(1)
|
|
})
|
|
|
|
it('does not display missing series as zero', async () => {
|
|
mockMetrics('disk_io_budget', false)
|
|
renderMetrics()
|
|
expect(await card('Disk IO balance').findByText('Unable to load')).toBeInTheDocument()
|
|
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
|
|
})
|
|
|
|
it('retries the failed connection limit when the overview Refresh button is clicked', async () => {
|
|
mockMetrics()
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref/analytics/endpoints/service-health',
|
|
response: { result: [] },
|
|
})
|
|
let hasConnectionLimitFailed = false
|
|
addAPIMock({
|
|
method: 'post',
|
|
path: '/platform/pg-meta/:ref/query',
|
|
response: ({ request }) => {
|
|
const key = new URL(request.url).searchParams.get('key')
|
|
if (key !== 'max-connections') {
|
|
return HttpResponse.json<{ slow_queries_count: number }[]>([{ slow_queries_count: 7 }])
|
|
}
|
|
if (!hasConnectionLimitFailed) {
|
|
hasConnectionLimitFailed = true
|
|
return HttpResponse.json<APIErrorBody>(
|
|
{ message: 'Connection limit query failed' },
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
return HttpResponse.json<{ max_connections: string }[]>([{ max_connections: '100' }])
|
|
},
|
|
})
|
|
renderMetrics({ hasMaxConnections: false, showOverview: true })
|
|
|
|
expect(await card('Peak Connections').findByText('Unable to load')).toBeInTheDocument()
|
|
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
|
|
expect(await card('Memory').findByText('60%')).toBeInTheDocument()
|
|
expect(screen.getAllByText('Unable to load')).toHaveLength(1)
|
|
expect(screen.queryByText('Connection limit query failed')).not.toBeInTheDocument()
|
|
|
|
fireEvent.click(screen.getByRole('button', { name: 'Refresh' }))
|
|
|
|
expect(await card('Peak Connections').findByText('12/100')).toBeInTheDocument()
|
|
expect(card('Peak Connections').queryByText('Unable to load')).not.toBeInTheDocument()
|
|
expect(await card('CPU').findByText('25%')).toBeInTheDocument()
|
|
}, 15000)
|
|
|
|
it('shows one friendly request-wide failure and preserves slow queries', async () => {
|
|
addAPIMock({
|
|
method: 'get',
|
|
path: '/platform/projects/:ref/infra-monitoring',
|
|
response: () =>
|
|
HttpResponse.json<APIErrorBody>({ message: 'Project not found' }, { status: 404 }),
|
|
})
|
|
renderMetrics()
|
|
expect(await screen.findByText('Failed to load database metrics')).toBeInTheDocument()
|
|
expect(screen.getAllByText('Failed to load database metrics')).toHaveLength(1)
|
|
expect(screen.queryByText('Project not found')).not.toBeInTheDocument()
|
|
expect(screen.queryByText('Unable to load')).not.toBeInTheDocument()
|
|
expect(screen.queryByRole('link', { name: /CPU/ })).not.toBeInTheDocument()
|
|
expect(card('Slow Queries').getByText('7')).toBeInTheDocument()
|
|
expect(screen.getByText(/Try refreshing your browser/)).toBeInTheDocument()
|
|
expect(screen.getByRole('link', { name: 'contact support' })).toHaveAttribute(
|
|
'href',
|
|
expect.stringContaining('projectRef=default')
|
|
)
|
|
expect(screen.getByRole('link', { name: 'Supabase status page' })).toHaveAttribute(
|
|
'href',
|
|
'https://status.supabase.com/'
|
|
)
|
|
})
|
|
})
|