Files
supabase/apps/studio/data/storage/buckets-query.ts
supabase-vercel-tedd[bot] f4b60922e4 fix(studio): stop retrying client errors in the storage buckets query (#53026)
## Problem

The storage buckets queries (`usePaginatedBucketsQuery`,
`useBucketQuery`) override the global retry rule with
`shouldRetryBucketsQuery`, which retried every error except 404 and two
specific messages. A permanent client error, such as a 402 returned when
a project's service is restricted, was retried 3 times with exponential
backoff. The Storage files page showed its loading skeleton for that
whole time instead of the error that `FilesBuckets` already renders.

## Solution

`shouldRetryBucketsQuery` now skips retries for any 4xx response except
429. This matches the global default in `data/query-client.ts`. The
existing checks for 404, "Missing tenant config" and "Project has no
active API keys" are kept, with 404 now covered by the 4xx rule. 5xx and
429 errors are still retried up to `MAX_RETRY_FAILURE_COUNT`.

The function is exported so it can be unit-tested, and
`data/storage/buckets-query.test.ts` covers the new behaviour.

Checks run:
- `pnpm exec vitest run data/storage/buckets-query.test.ts` (3 passed)
- `pnpm turbo run typecheck --filter='...[origin/master]'`
- `pnpm turbo run lint --filter='[origin/master]'`
- prettier `--check` on the changed files

## Review instructions

1. Open Storage > Files (`/project/<ref>/storage/files`) for a project
whose buckets request returns a 4xx (for example a 402 for a restricted
project). The "Failed to retrieve buckets" error with the API message
shows after one request, with no long loading state.
2. Open the same page for a healthy project. Buckets load and list as
before.

## Checklist

- [x] I have read
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
- [x] 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)


[FE-4925](https://linear.app/supabase/issue/FE-4925/storage-loads-endlessly-without-showing-error-message-if-organization)

Co-authored-by: supabase-vercel-tedd[bot] <336548405+supabase-vercel-tedd[bot]@users.noreply.github.com>
2026-11-05 07:45:16 -06:00

247 lines
7.3 KiB
TypeScript

import {
InfiniteData,
keepPreviousData,
useInfiniteQuery,
useQuery,
useQueryClient,
} from '@tanstack/react-query'
import { components } from 'api-types'
import { useMemo } from 'react'
import { getBucketNumberEstimate, getBucketNumberEstimateKey } from './buckets-max-size-limit-query'
import { storageKeys } from './keys'
import { get, handleError } from '@/data/fetchers'
import { MAX_RETRY_FAILURE_COUNT } from '@/data/query-client'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { PROJECT_STATUS } from '@/lib/constants'
import type { StudioError } from '@/lib/errors/studio-errors'
import { isStudioError } from '@/lib/errors/studio-errors'
import { type UseCustomInfiniteQueryOptions, type UseCustomQueryOptions } from '@/types'
export type BucketsVariables = { projectRef?: string }
export type Bucket = components['schemas']['StorageBucketResponse_Output']
export type BucketType = Bucket['type']
type GetBucketParams = {
projectRef?: string
bucketId?: string
}
async function getBucket({ projectRef, bucketId }: GetBucketParams, signal?: AbortSignal) {
if (!projectRef) throw new Error('projectRef is required')
if (!bucketId) throw new Error('bucketId is required')
const { data, error } = await get('/platform/storage/{ref}/buckets/{id}', {
params: {
path: { ref: projectRef, id: bucketId },
},
signal,
})
if (error) handleError(error)
return data
}
export async function getBuckets({ projectRef }: BucketsVariables, signal?: AbortSignal) {
if (!projectRef) throw new Error('projectRef is required')
const { data, error } = await get('/platform/storage/{ref}/buckets', {
params: {
path: { ref: projectRef },
},
signal,
})
if (error) handleError(error)
return data
}
type BucketSortColumn = 'id' | 'name' | 'updated_at' | 'created_at'
type BucketSortOrder = 'asc' | 'desc'
type BucketListPagination = {
page?: number
limit?: number
sortColumn?: BucketSortColumn
sortOrder?: BucketSortOrder
search?: string
}
export type BucketsListPaginatedVariables = BucketsVariables & BucketListPagination
const DEFAULT_PAGE_SIZE = 100
const DEFAULT_SORT_COLUMN: BucketSortColumn = 'created_at'
const DEFAULT_SORT_ORDER: BucketSortOrder = 'desc'
const getBucketsPaginated = async (
{
projectRef,
page = 0,
limit = DEFAULT_PAGE_SIZE,
sortColumn = DEFAULT_SORT_COLUMN,
sortOrder = DEFAULT_SORT_ORDER,
search,
}: BucketsListPaginatedVariables,
signal?: AbortSignal
) => {
if (!projectRef) throw new Error('projectRef is required')
const offset = page * limit
const trimmedSearch = search?.trim()
const resolvedSearch = !!trimmedSearch && trimmedSearch.length > 0 ? trimmedSearch : undefined
const { data, error } = await get('/platform/storage/{ref}/buckets', {
params: {
path: { ref: projectRef },
query: {
limit,
offset,
sortColumn,
sortOrder,
search: resolvedSearch,
},
},
signal,
})
if (error) handleError(error)
return data
}
type BucketData = Awaited<ReturnType<typeof getBucket>>
export type BucketsData = Awaited<ReturnType<typeof getBuckets>>
export type BucketsWithPaginationData = Awaited<ReturnType<typeof getBucketsPaginated>>
export type BucketsError = StudioError
export const useBucketQuery = <TData = BucketData>(
{ projectRef, bucketId }: GetBucketParams,
{ enabled = true, ...options }: UseCustomQueryOptions<BucketData, BucketsError, TData>
) => {
const { data: project } = useSelectedProjectQuery()
const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY
return useQuery<BucketData, BucketsError, TData>({
queryKey: storageKeys.bucket(projectRef, bucketId),
queryFn: ({ signal }) => getBucket({ projectRef, bucketId }, signal),
enabled: enabled && !!bucketId && isActive,
...options,
retry: shouldRetryBucketsQuery,
})
}
export const useBucketNumberEstimateQuery = (
{ projectRef }: BucketsVariables,
{ enabled = true, ...options }: UseCustomQueryOptions<number | undefined, StudioError> = {}
) => {
const { data: project } = useSelectedProjectQuery()
const connectionString = project?.connectionString
return useQuery<number | undefined, StudioError>({
// Query remains functionally the same even if connectionString changes
queryKey: getBucketNumberEstimateKey(projectRef),
queryFn: () =>
getBucketNumberEstimate({
projectRef,
connectionString,
}),
enabled: enabled && !!projectRef,
...options,
})
}
export const usePaginatedBucketsQuery = <TData = BucketsWithPaginationData>(
{ projectRef, ...params }: Omit<BucketsListPaginatedVariables, 'page'>,
{
enabled = true,
...options
}: UseCustomInfiniteQueryOptions<
BucketsWithPaginationData,
BucketsError,
InfiniteData<TData>,
readonly unknown[],
number
> = {}
) => {
const { data: project } = useSelectedProjectQuery()
const isActive = project?.status === PROJECT_STATUS.ACTIVE_HEALTHY
const { placeholderData, ...restOptions } = options
const resolvedPlaceholderData = placeholderData ?? keepPreviousData
return useInfiniteQuery({
queryKey: storageKeys.bucketsList(projectRef, params),
queryFn: ({ signal, pageParam }) =>
getBucketsPaginated({ projectRef, page: pageParam, ...params }, signal),
enabled: enabled && typeof projectRef !== 'undefined' && isActive,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => {
const nextPageNumber = pages.length
const limit = params.limit ?? DEFAULT_PAGE_SIZE
const lastPageCount = lastPage.length
if (lastPageCount < limit) return undefined
return nextPageNumber
},
...restOptions,
placeholderData: resolvedPlaceholderData,
retry: shouldRetryBucketsQuery,
})
}
/**
* Tries to get the bucket info from the cache first. If not found, fetches
* from remote by name.
*/
export const useBucketInfoQueryPreferCached = (bucketId?: string, projectRef?: string) => {
const queryClient = useQueryClient()
const cachedBucketInfo = useMemo(() => {
if (!bucketId) return undefined
const bucketsPages = queryClient.getQueryData(storageKeys.bucketsList(projectRef)) as
| InfiniteData<Bucket[]>
| undefined
const buckets = bucketsPages?.pages.flatMap((page) => page) ?? []
return buckets.find((b) => b.name === bucketId)
}, [bucketId, projectRef, queryClient])
const shouldFetchBucketInfo = !!bucketId && !cachedBucketInfo
const { data: remoteBucketInfo } = useBucketQuery(
{
projectRef,
bucketId,
},
{
enabled: shouldFetchBucketInfo,
}
)
if (!bucketId) return undefined
return cachedBucketInfo ?? remoteBucketInfo
}
export const shouldRetryBucketsQuery = (failureCount: number, error: unknown) => {
if (isStudioError(error)) {
// Client errors (e.g. 402 for a restricted project, 404 for a deleted bucket) will never
// succeed on retry. Rate limits (429) are still retried.
if (error.code !== undefined && error.code >= 400 && error.code < 500 && error.code !== 429) {
return false
}
if (
error.message.includes('Missing tenant config') ||
error.message.includes('Project has no active API keys')
) {
return false
}
}
if (failureCount < MAX_RETRY_FAILURE_COUNT) {
return true
}
return false
}