mirror of
https://github.com/supabase/supabase.git
synced 2026-12-04 07:29:16 +00:00
## Problem Follow-up to #52730. Resolves part of FE-4772. Fetch failures and aborts were classified as `UnexpectedError`, and HTTP error responses with empty, HTML, or plain-text bodies did too. ## Solution **Network failures and aborts keep their classification.** `fetchHandler` used to rewrite `Failed to fetch` into a plain `Error`, so openapi-fetch network failures were classified as `UnexpectedError`. It now throws `classifyError(err, { endpoint, method })`, giving `NetworkUnreachable` (same user-facing message, original error as `cause`) or `RequestAborted`. The endpoint comes from `schemaPath`, recorded in `onRequest`. Tagged aborts are no longer named `AbortError`, so `isRequestAborted()` checks for both. `state/storage-explorer.tsx` uses it, so cancelling a folder load no longer shows an error toast. **One place reads error responses.** `readResponseError` in `data/error-classification.ts` turns an HTTP error response into a `RawResponseError`. It reads the status, `Retry-After`, the message from a JSON body or a short `text/plain` body (never HTML), plus `requestId`, `endpoint`, and `method`. The openapi-fetch middleware serializes its result into the error body. openapi-fetch builds `error` only from the response body, so that step can't be skipped. `parseResponseErrorBody` now only checks the shape. Empty, HTML, and plain-text error bodies now classify by status. Before, they became `UnexpectedError`. `fetchGet`/`fetchPost`/`fetchHeadWithTimeout` (Studio's own `/api` routes) use the same helper. This also fixes a non-JSON error body making them reject with a `SyntaxError`. **`requestPathname` is replaced by `endpoint`.** The no-retry list and the statement-timeout check in `query-client.ts` match OpenAPI patterns exactly. Critical error messages in `lib/error-reporting.ts` use the pattern, so concrete project refs stay out of them. `path-to-regexp` is no longer used, so it's removed. ## Review instructions 1. From `apps/studio`, run `vitest run data lib components/interfaces/ErrorHandling state`. Expect 4,034 passing tests. 2. Review `readResponseError` in `data/error-classification.ts` and its use in `data/fetchers.ts`. ## Additional context ### Notes - Critical error messages now read `endpoint … w/ message: …`. This regroups those Sentry issues. - A JSON body's `error` string is now accepted as a message for API responses. Before, only the `/api` route path read it. ### Testing - New `data/fetchers-errors.test.ts` covers network failure, abort, empty/HTML/plain-text/JSON error bodies, service derivation, and `/api` route non-JSON bodies. - Unit tests for `readResponseError`, `isRequestAborted`, and the no-retry endpoint set. - `vitest run data lib components/interfaces/ErrorHandling state`: 4,034 pass. ## Checklist Check all before review: - [ ] I have read [CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md) - [ ] If I wrote a new docs topic or edited an existing topic, I used the `/write-the-docs` or `/edit-the-docs` skill, which applies the docs [style guide](https://github.com/supabase/supabase/tree/master/apps/docs/style-guide)
115 lines
4.0 KiB
TypeScript
115 lines
4.0 KiB
TypeScript
import { MutationCache, onlineManager, QueryCache, QueryClient } from '@tanstack/react-query'
|
|
import { useState } from 'react'
|
|
|
|
import { IS_PLATFORM } from '@/lib/constants'
|
|
import { reportQueryError } from '@/lib/errors/report-studio-error'
|
|
import { isStudioError } from '@/lib/errors/studio-errors'
|
|
|
|
// When running locally we don't need the internet
|
|
// so we can pretend we're online all the time
|
|
if (!IS_PLATFORM) {
|
|
onlineManager.setOnline(true)
|
|
}
|
|
|
|
// OpenAPI path patterns, as set on `error.endpoint`
|
|
const PG_META_QUERY_ENDPOINT = '/platform/pg-meta/{ref}/query'
|
|
export const SKIP_RETRY_ENDPOINTS = new Set([
|
|
'/platform/projects/{ref}/run-lints',
|
|
'/platform/organizations/{slug}/usage',
|
|
PG_META_QUERY_ENDPOINT,
|
|
'/v1/projects/{ref}/analytics/endpoints/logs.all',
|
|
])
|
|
|
|
export const MAX_RETRY_FAILURE_COUNT = 3
|
|
|
|
function isQueryEndpointStatementTimeout(error: unknown) {
|
|
return (
|
|
isStudioError(error) &&
|
|
error.endpoint === PG_META_QUERY_ENDPOINT &&
|
|
!!error.message?.includes('canceling statement due to statement timeout')
|
|
)
|
|
}
|
|
|
|
let queryClient: QueryClient | undefined
|
|
|
|
export function getQueryClient() {
|
|
const _queryClient =
|
|
queryClient ??
|
|
new QueryClient({
|
|
// Report once per failed fetch, after retries are exhausted
|
|
queryCache: new QueryCache({ onError: (error) => reportQueryError(error) }),
|
|
mutationCache: new MutationCache({ onError: (error) => reportQueryError(error) }),
|
|
defaultOptions: {
|
|
queries: {
|
|
staleTime: 60 * 1000, // 1 minute
|
|
retry(failureCount, error) {
|
|
// Don't retry on 4xx errors
|
|
if (
|
|
isStudioError(error) &&
|
|
error.code !== undefined &&
|
|
error.code >= 400 &&
|
|
error.code < 500 &&
|
|
// Still retry on 429s (rate limit)
|
|
error.code !== 429
|
|
) {
|
|
return false
|
|
}
|
|
|
|
// Skip retries for specific endpoints to avoid unnecessary load
|
|
// CRITICAL: We must still retry 429 (rate limit) errors even on these endpoints.
|
|
// Without this exception, queries fail immediately on rate limits, causing the
|
|
// frontend to issue fresh requests (via refetch/user actions), which amplifies
|
|
// the rate limiting problem. By retrying 429s with proper backoff (using the
|
|
// retryAfter header below), we respect rate limits and prevent request storms.
|
|
if (
|
|
isStudioError(error) &&
|
|
error.endpoint !== undefined &&
|
|
SKIP_RETRY_ENDPOINTS.has(error.endpoint) &&
|
|
error.code !== 429
|
|
) {
|
|
return false
|
|
}
|
|
|
|
if (failureCount < MAX_RETRY_FAILURE_COUNT) {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
},
|
|
retryDelay(failureCount, error) {
|
|
if (isStudioError(error) && error.retryAfter) {
|
|
return error.retryAfter * 1000
|
|
}
|
|
|
|
// react-query default: doubles, starting at 1000ms, with each attempt, but will not exceed 30 seconds
|
|
return Math.min(1000 * 2 ** failureCount, 30000)
|
|
},
|
|
refetchOnWindowFocus(query) {
|
|
// [Joshen] Opting to not refetch a /query request that failed due to a statement
|
|
// timeout, presumably that it'll just run into the same issue. Can however be overriden
|
|
// on a per case basis on each individual query hook
|
|
if (isQueryEndpointStatementTimeout(query.state.error)) return false
|
|
return true
|
|
},
|
|
refetchOnReconnect(query) {
|
|
if (isQueryEndpointStatementTimeout(query.state.error)) return false
|
|
return true
|
|
},
|
|
},
|
|
},
|
|
})
|
|
|
|
// For SSG and SSR always create a new queryClient
|
|
if (typeof window === 'undefined') return _queryClient
|
|
// Create the queryClient once in the client
|
|
if (!queryClient) queryClient = _queryClient
|
|
|
|
return queryClient
|
|
}
|
|
|
|
export function useRootQueryClient() {
|
|
const [_queryClient] = useState(() => getQueryClient())
|
|
|
|
return _queryClient
|
|
}
|