Files
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

252 lines
9.4 KiB
TypeScript

import { useQueryClient } from '@tanstack/react-query'
import { useNavigate } from '@tanstack/react-router'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { RefreshCwIcon } from 'lucide-react'
import { useCallback, useMemo, useState } from 'react'
import { Badge, Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
import { useUnifiedLogsPreview } from '../App/FeaturePreview/FeaturePreviewContext'
import { DatabaseInfrastructureSection } from './DatabaseInfrastructureSection'
import { OBSERVABILITY_DOCS_HREFS } from './Observability.constants'
import { useObservabilityOverviewData } from './ObservabilityOverview.utils'
import { ObservabilityOverviewFooter } from './ObservabilityOverviewFooter'
import { ServiceHealthTable } from './ServiceHealthTable'
import { useSlowQueriesCount } from './useSlowQueriesCount'
import { ReportHeader } from '@/components/interfaces/Reports/ReportHeader'
import { ReportPadding } from '@/components/interfaces/Reports/ReportPadding'
import {
buildUnifiedLogsUrl,
type UnifiedLogType,
} from '@/components/interfaces/UnifiedLogs/UnifiedLogs.utils'
import { DocsButton } from '@/components/ui/DocsButton'
import { ChartIntervalDropdown } from '@/components/ui/Logs/ChartIntervalDropdown'
import { CHART_INTERVALS } from '@/components/ui/Logs/logs.utils'
import { ShortcutTooltip } from '@/components/ui/ShortcutTooltip'
import { databaseKeys } from '@/data/database/keys'
import { useIsDataApiEnabled } from '@/hooks/misc/useIsDataApiEnabled'
import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { navigateToUrl } from '@/lib/navigation'
import { SHORTCUT_IDS } from '@/state/shortcuts/registry'
import { useShortcut } from '@/state/shortcuts/useShortcut'
const REPORT_TITLE = 'Overview'
type ChartIntervalKey = '1hr' | '1day' | '7day'
export const ObservabilityOverview = () => {
const navigate = useNavigate()
const { ref: projectRef } = useParams()
const { data: organization } = useSelectedOrganizationQuery()
const queryClient = useQueryClient()
const { isEnabled: isUnifiedLogsEnabled } = useUnifiedLogsPreview()
const { projectStorageAll: storageSupported } = useIsFeatureEnabled(['project_storage:all'])
const { isEnabled: isDataApiEnabled } = useIsDataApiEnabled({ projectRef })
const DEFAULT_INTERVAL: ChartIntervalKey = '1day'
const [interval, setInterval] = useState<ChartIntervalKey>(DEFAULT_INTERVAL)
const [refreshKey, setRefreshKey] = useState(0)
const [showIntervalDropdown, setShowIntervalDropdown] = useState(false)
const selectedInterval = CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1]
const { datetimeFormat } = useMemo(() => {
const format = selectedInterval.format || 'MMM D, ha'
return { datetimeFormat: format }
}, [selectedInterval])
const overviewData = useObservabilityOverviewData(projectRef!, interval, refreshKey)
const { slowQueriesCount, isLoading: slowQueriesLoading } = useSlowQueriesCount(
projectRef,
refreshKey
)
const handleRefresh = useCallback(() => {
setRefreshKey((prev) => prev + 1)
queryClient.invalidateQueries({ queryKey: ['projects', projectRef, 'service-health'] })
queryClient.invalidateQueries({ queryKey: ['project-metrics'] })
queryClient.invalidateQueries({ queryKey: ['infra-monitoring'] })
queryClient.invalidateQueries({ queryKey: databaseKeys.maxConnections(projectRef) })
}, [queryClient, projectRef])
useShortcut(SHORTCUT_IDS.OBSERVABILITY_REFRESH, handleRefresh)
useShortcut(SHORTCUT_IDS.OBSERVABILITY_TOGGLE_DATE_PICKER, () => {
setShowIntervalDropdown((open) => !open)
})
const getLogsUrl = useCallback(
(logType: UnifiedLogType, legacyLogsUrl: string) =>
isUnifiedLogsEnabled
? buildUnifiedLogsUrl({ projectRef: projectRef!, logType })
: `/project/${projectRef}${legacyLogsUrl}`,
[projectRef, isUnifiedLogsEnabled]
)
const serviceBase = useMemo(
() => [
{
key: 'data_api' as const,
name: 'API Gateway',
reportUrl: undefined,
logType: 'edge' as const,
logsUrl: getLogsUrl('edge', '/logs/edge-logs'),
enabled: isDataApiEnabled,
hasReport: false,
},
{
key: 'db' as const,
name: 'Database',
reportUrl: `/project/${projectRef}/observability/database`,
logType: 'postgres' as const,
logsUrl: getLogsUrl('postgres', '/logs/postgres-logs'),
enabled: true,
hasReport: true,
},
{
key: 'postgrest' as const,
name: 'PostgREST',
reportUrl: `/project/${projectRef}/observability/postgrest`,
logType: 'postgrest' as const,
logsUrl: getLogsUrl('postgrest', '/logs/postgrest-logs'),
enabled: true,
hasReport: true,
},
{
key: 'auth' as const,
name: 'Auth',
reportUrl: `/project/${projectRef}/observability/auth`,
logType: 'auth' as const,
logsUrl: getLogsUrl('auth', '/logs/auth-logs'),
enabled: true,
hasReport: true,
},
{
key: 'functions' as const,
name: 'Edge Functions',
reportUrl: `/project/${projectRef}/observability/edge-functions`,
logType: 'edge function' as const,
logsUrl: getLogsUrl('edge function', '/logs/edge-functions-logs'),
enabled: true,
hasReport: true,
},
{
key: 'storage' as const,
name: 'Storage',
reportUrl: `/project/${projectRef}/observability/storage`,
logType: 'storage' as const,
logsUrl: getLogsUrl('storage', '/logs/storage-logs'),
enabled: storageSupported,
hasReport: true,
},
{
key: 'realtime' as const,
name: 'Realtime',
reportUrl: `/project/${projectRef}/observability/realtime`,
logType: 'realtime' as const,
logsUrl: getLogsUrl('realtime', '/logs/realtime-logs'),
enabled: true,
hasReport: true,
},
],
[projectRef, storageSupported, isDataApiEnabled, getLogsUrl]
)
const enabledServices = serviceBase.filter((s) => s.enabled)
const dbServiceData = overviewData.services.db
// Navigate to the log view scoped to the clicked bar's bucket window
const handleBarClick = useCallback(
(service: { logType: UnifiedLogType; logsUrl: string }) => (datum: any) => {
if (!datum?.timestamp) return
// datum.timestamp is already the UTC-truncated bucket boundary from timestamp_trunc(),
// so use it directly to avoid local-timezone startOf() misalignment (e.g. UTC+5:30).
const unit = interval === '1hr' ? 'minute' : 'hour'
const start = datum.timestamp
const end = dayjs.utc(datum.timestamp).add(1, unit).toISOString()
if (isUnifiedLogsEnabled) {
navigateToUrl(
navigate,
buildUnifiedLogsUrl({ projectRef: projectRef!, logType: service.logType, start, end })
)
} else {
const queryParams = new URLSearchParams({ its: start, ite: end })
const separator = service.logsUrl.includes('?') ? '&' : '?'
navigateToUrl(navigate, `${service.logsUrl}${separator}${queryParams.toString()}`)
}
},
[navigate, interval, isUnifiedLogsEnabled, projectRef]
)
return (
<ReportPadding>
<div className="flex flex-row justify-between items-center">
<div className="flex items-center gap-3">
<ReportHeader title={REPORT_TITLE} />
<Tooltip>
<TooltipTrigger asChild>
<Badge variant="warning">Beta</Badge>
</TooltipTrigger>
<TooltipContent>
<p>This page is subject to change</p>
</TooltipContent>
</Tooltip>
</div>
<div className="flex items-center gap-2">
<DocsButton href={OBSERVABILITY_DOCS_HREFS.overview} topic={REPORT_TITLE} />
<ShortcutTooltip
shortcutId={SHORTCUT_IDS.OBSERVABILITY_REFRESH}
label="Refresh report"
side="bottom"
>
<Button variant="outline" icon={<RefreshCwIcon size={14} />} onClick={handleRefresh}>
Refresh
</Button>
</ShortcutTooltip>
<ChartIntervalDropdown
value={interval}
onChange={(interval) => setInterval(interval as ChartIntervalKey)}
organizationSlug={organization?.slug}
dropdownAlign="end"
tooltipSide="left"
open={showIntervalDropdown}
onOpenChange={setShowIntervalDropdown}
/>
</div>
</div>
<div className="space-y-12 mt-8">
<DatabaseInfrastructureSection
interval={interval}
refreshKey={refreshKey}
dbErrorRate={dbServiceData.errorRate}
isLoading={dbServiceData.isLoading}
slowQueriesCount={slowQueriesCount}
slowQueriesLoading={slowQueriesLoading}
/>
<ServiceHealthTable
services={enabledServices.map((service) => ({
key: service.key,
name: service.name,
description: '',
reportUrl: service.hasReport ? service.reportUrl : undefined,
logType: service.logType,
logsUrl: service.logsUrl,
}))}
serviceData={overviewData.services}
onBarClick={handleBarClick}
datetimeFormat={datetimeFormat}
/>
</div>
<ObservabilityOverviewFooter />
</ReportPadding>
)
}