Files
supabase/apps/studio/components/interfaces/Observability/DatabaseInfrastructureSection.tsx
Jordi Enric 833a875ea2 fix(studio): friendly database metric errors DEBUG-155 (#52216)
## 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.

![Peak Connections stuck on Unable to load after
Refresh](https://k6dwnfm8zepsmdni.public.blob.vercel-storage.com/qa/wrun_41M8XTANCW0GQ8139AY6ECPK81/1796297469653-screenshot-1796297456016.png)

**After · `ee646999af`.** Once the connection-limit request could
succeed, the next Refresh click restored Peak Connections to `6/90`.

![Peak Connections showing 6/90 after in-app
Refresh](https://k6dwnfm8zepsmdni.public.blob.vercel-storage.com/qa/wrun_41M8XTANCW0GQ8139AY6ECPK81/1796299167534-screenshot-1796299160944.png)

### 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.

![Full request failure — local HTTP
override](https://github.com/user-attachments/assets/f9b85b1d-f836-47ce-ad48-bab13e558079)

**Partial failure:** only Disk IO Budget shows “Unable to load”; healthy
metrics and Slow Queries remain visible.

![Partial metric failure — local HTTP
override](https://github.com/user-attachments/assets/f7dbc088-d505-4f20-8a55-45d832b828a8)

**Recovery:** after restoring a successful response and reloading, all
metric cards render normally.

![Healthy recovery — local HTTP
override](https://github.com/user-attachments/assets/34d3332e-717b-47ff-ba56-e00128fa474c)

### Verified hosted preview

Studio staging deployment for `dbf78487f5`, 1440 × 900. All database
metric cards and Slow Queries return after Refresh.

![Overview after
Refresh](https://github.com/user-attachments/assets/67304cac-3dfd-4afe-b717-0a1fa12a30ba)

The CPU card opens the Database report and preserves Last 24 hours.

![Database report opened from a metric
card](https://github.com/user-attachments/assets/c70eb7c8-4151-4080-ba6c-69efb675d7ab)
2026-12-03 14:03:33 +01:00

170 lines
5.0 KiB
TypeScript

import { Link } from '@tanstack/react-router'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { useMemo } from 'react'
import {
MetricCard,
MetricCardContent,
MetricCardHeader,
MetricCardLabel,
MetricCardValue,
} from 'ui-patterns/MetricCard'
import {
DatabaseInfrastructureMetric,
INFRASTRUCTURE_METRIC_ATTRIBUTES,
} from './DatabaseInfrastructureMetric'
import { AlertError } from '@/components/ui/AlertError'
import { InlineLink } from '@/components/ui/InlineLink'
import { useInfraMonitoringAttributesQuery } from '@/data/analytics/infra-monitoring-query'
import { useMaxConnectionsQuery } from '@/data/database/max-connections-query'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
type DatabaseInfrastructureSectionProps = {
interval: '1hr' | '1day' | '7day'
refreshKey: number
dbErrorRate: number
isLoading: boolean
slowQueriesCount?: number
slowQueriesLoading?: boolean
}
export const DatabaseInfrastructureSection = ({
interval,
refreshKey,
dbErrorRate: _dbErrorRate,
isLoading: _dbLoading,
slowQueriesCount = 0,
slowQueriesLoading = false,
}: DatabaseInfrastructureSectionProps) => {
const { ref: projectRef } = useParams()
const { data: project } = useSelectedProjectQuery()
// refreshKey forces date recalculation when user clicks refresh button
const { startDate, endDate, infraInterval } = useMemo(() => {
const now = dayjs()
const end = now.toISOString()
let start: string
let infraInterval: '1h' | '1d'
switch (interval) {
case '1hr':
start = now.subtract(1, 'hour').toISOString()
infraInterval = '1h'
break
case '1day':
start = now.subtract(1, 'day').toISOString()
infraInterval = '1h'
break
case '7day':
start = now.subtract(7, 'day').toISOString()
infraInterval = '1d'
break
default:
start = now.subtract(1, 'hour').toISOString()
infraInterval = '1h'
}
return { startDate: start, endDate: end, infraInterval }
}, [interval, refreshKey])
const infraQuery = useInfraMonitoringAttributesQuery({
projectRef,
attributes: INFRASTRUCTURE_METRIC_ATTRIBUTES,
startDate,
endDate,
interval: infraInterval,
})
const maxConnectionsQuery = useMaxConnectionsQuery({
projectRef,
connectionString: project?.connectionString,
})
// Generate database report URL with time range parameters
const getDatabaseReportUrl = () => {
const now = dayjs()
let its: string
let helperText: string
switch (interval) {
case '1hr':
its = now.subtract(1, 'hour').toISOString()
helperText = 'Last 60 minutes'
break
case '1day':
its = now.subtract(24, 'hour').toISOString()
helperText = 'Last 24 hours'
break
case '7day':
its = now.subtract(7, 'day').toISOString()
helperText = 'Last 7 days'
break
default:
its = now.subtract(24, 'hour').toISOString()
helperText = 'Last 24 hours'
}
const ite = now.toISOString()
const params = new URLSearchParams({
its,
ite,
isHelper: 'true',
helperText,
})
return `/project/${projectRef}/observability/database?${params.toString()}`
}
const databaseReportUrl = getDatabaseReportUrl()
return (
<div>
<h2 className="mb-4">Database</h2>
{infraQuery.isError && (
<AlertError
projectRef={projectRef}
subject="Failed to load database metrics"
className="mb-4"
>
<p>
Check the{' '}
<InlineLink href="https://status.supabase.com/">Supabase status page</InlineLink> for
service updates.
</p>
</AlertError>
)}
<div className="grid grid-cols-3 gap-2">
<Link
to="/project/$ref/observability/query-performance"
params={{ ref: projectRef ?? '_' }}
search={{ totalTimeFilter: JSON.stringify({ operator: '>', value: 1000 }) }}
className="block group"
>
<MetricCard isLoading={slowQueriesLoading}>
<MetricCardHeader linkTooltip="Go to query performance">
<MetricCardLabel tooltip="Queries with total execution time (execution time + planning time) greater than 1000ms. High values may indicate query optimization opportunities">
Slow Queries
</MetricCardLabel>
</MetricCardHeader>
<MetricCardContent>
<MetricCardValue>{slowQueriesCount}</MetricCardValue>
</MetricCardContent>
</MetricCard>
</Link>
{!infraQuery.isError &&
(['connections', 'disk', 'diskIo', 'ram', 'cpu'] as const).map((metric) => (
<DatabaseInfrastructureMetric
key={metric}
metric={metric}
infraQuery={infraQuery}
href={databaseReportUrl}
maxConnectionsQuery={maxConnectionsQuery}
/>
))}
</div>
</div>
)
}