Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

fix(studio): rework global storage size validation (#41378)

Charis000c79e22bd8
diff --git a/apps/studio/components/interfaces/Storage/StorageSettings/StorageFileSizeLimitErrorMessage.tsx b/apps/studio/components/interfaces/Storage/StorageSettings/StorageFileSizeLimitErrorMessage.tsx
new file mode 100644
index 00000000000..9a3f9e8c315
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageSettings/StorageFileSizeLimitErrorMessage.tsx
@@ -0,0 +1,108 @@
+import Link from 'next/link'
+import { type FieldError } from 'react-hook-form'
+
+import { InlineLink } from 'components/ui/InlineLink'
+import { LARGEST_SIZE_LIMIT_BUCKETS_COUNT } from 'data/sql/queries/get-largest-size-limit-buckets'
+import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import {
+ decodeBucketLimitErrorMessage,
+ formatBytesForDisplay,
+ isBucketLimitErrorMessage,
+} from './StorageSettings.utils'
+
+interface StorageFileSizeLimitErrorMessageProps {
+ error?: FieldError
+ projectRef?: string
+}
+
+export const StorageFileSizeLimitErrorMessage = ({
+ error,
+ projectRef,
+}: StorageFileSizeLimitErrorMessageProps) => {
+ if (!error?.message) return null
+
+ const isBucketLimitError = isBucketLimitErrorMessage(error.message)
+ if (!isBucketLimitError) return <>{error.message}</>
+
+ const bucketLimitErrorBuckets = decodeBucketLimitErrorMessage(error.message)
+ if (bucketLimitErrorBuckets.length === 0) return null
+
+ const hasUnfetchedBuckets = bucketLimitErrorBuckets.length > LARGEST_SIZE_LIMIT_BUCKETS_COUNT
+
+ const [primaryBucket, ...remainingBuckets] = bucketLimitErrorBuckets
+ const otherBuckets = remainingBuckets.slice(0, LARGEST_SIZE_LIMIT_BUCKETS_COUNT - 1)
+
+ const primaryBucketLimit = formatBytesForDisplay(primaryBucket.limit)
+
+ const primaryBucketLink =
+ projectRef !== undefined ? (
+ <InlineLink
+ href={`/project/${projectRef}/storage/files/buckets/${primaryBucket.name}?edit=true`}
+ className={cn(
+ 'text-destructive decoration-destructive-500',
+ 'hover:text-destructive hover:decoration-destructive transition'
+ )}
+ >
+ {primaryBucket.name}
+ </InlineLink>
+ ) : (
+ <span className="text-destructive">{primaryBucket.name}</span>
+ )
+
+ const showOtherCount = otherBuckets.length > 0 && !hasUnfetchedBuckets
+
+ return (
+ <>
+ <p>Global limit must be greater than that of individual buckets.</p>
+ <p>
+ Remove or decrease the limit on {primaryBucketLink} ({primaryBucketLimit})
+ {otherBuckets.length > 0 && (
+ <>
+ {' '}
+ and{' '}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span
+ className={cn(
+ 'underline underline-offset-2',
+ 'decoration-dotted decoration-destructive-500',
+ 'hover:decoration-destructive transition',
+ 'cursor-default'
+ )}
+ >
+ {showOtherCount && `+${otherBuckets.length} `}other bucket
+ {otherBuckets.length > 1 ? 's' : ''}
+ </span>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <ul>
+ {otherBuckets.map(({ name, limit }) => {
+ const formattedLimit = formatBytesForDisplay(limit)
+ return (
+ <li key={name} className="hover:underline underline-offset-2">
+ {projectRef !== undefined ? (
+ <Link
+ href={`/project/${projectRef}/storage/files/buckets/${name}?edit=true`}
+ >
+ {name} ({formattedLimit})
+ </Link>
+ ) : (
+ <span>
+ {name} ({formattedLimit})
+ </span>
+ )}
+ </li>
+ )
+ })}
+ </ul>
+ {hasUnfetchedBuckets && <p>...and others</p>}
+ </TooltipContent>
+ </Tooltip>{' '}
+ first
+ </>
+ )}
+ .
+ </p>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.ValidateSizeLimit.tsx b/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.ValidateSizeLimit.tsx
new file mode 100644
index 00000000000..880144e1268
--- /dev/null
+++ b/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.ValidateSizeLimit.tsx
@@ -0,0 +1,179 @@
+import { useEffect, useReducer, useState } from 'react'
+import { useWatch, type FieldError } from 'react-hook-form'
+
+import {
+ THRESHOLD_FOR_AUTO_QUERYING_BUCKET_LIMITS,
+ type BucketWithSizeLimit,
+} from 'data/storage/buckets-max-size-limit-query'
+import { cn, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
+import { StorageFileSizeLimitErrorMessage } from './StorageFileSizeLimitErrorMessage'
+import { StorageSizeUnits } from './StorageSettings.constants'
+import { convertToBytes, encodeBucketLimitErrorMessage } from './StorageSettings.utils'
+
+type ValidationState =
+ | { status: 'initial' }
+ | { status: 'validating' }
+ | { status: 'valid' }
+ | { status: 'invalid'; failingBuckets: BucketWithSizeLimit[] }
+ | { status: 'error'; message: string }
+
+type ValidationAction =
+ | { type: 'start' }
+ | { type: 'success'; failingBuckets: BucketWithSizeLimit[] }
+ | { type: 'error'; message: string }
+ | { type: 'reset' }
+
+const validationStateReducer = (
+ state: ValidationState,
+ action: ValidationAction
+): ValidationState => {
+ switch (true) {
+ case (state.status === 'initial' || state.status === 'error') && action.type === 'start':
+ return { status: 'validating' }
+ case state.status === 'validating' && action.type === 'success':
+ return action.failingBuckets.length > 0
+ ? { status: 'invalid', failingBuckets: action.failingBuckets }
+ : { status: 'valid' }
+ case state.status === 'validating' && action.type === 'error':
+ return { status: 'error', message: action.message }
+ case action.type === 'reset':
+ return { status: 'initial' }
+ default:
+ console.warn(
+ `[StorageSettings.ValidateSizeLimit] Invalid transition in validationStateReducer: ${state.status} -> ${action.type}`
+ )
+ return state
+ }
+}
+
+type ValidateSizeLimitProps = {
+ onValidate: () => Promise<BucketWithSizeLimit[]>
+ projectRef?: string
+ isLoadingBucketEstimate?: boolean
+}
+
+export const ValidateSizeLimit = ({
+ onValidate,
+ projectRef,
+ isLoadingBucketEstimate = false,
+}: ValidateSizeLimitProps) => {
+ const fileSizeLimit: number = useWatch({ name: 'fileSizeLimit' })
+ const unit: StorageSizeUnits = useWatch({ name: 'unit' })
+
+ const [showModal, setShowModal] = useState(false)
+ const [validationState, dispatch] = useReducer(validationStateReducer, { status: 'initial' })
+
+ useEffect(() => {
+ dispatch({ type: 'reset' })
+ }, [fileSizeLimit, unit])
+
+ const handleValidate = async () => {
+ dispatch({ type: 'start' })
+ try {
+ const globalLimitInBytes = convertToBytes(fileSizeLimit, unit)
+ const buckets = await onValidate()
+ const failing = buckets.filter((bucket) => bucket.file_size_limit > globalLimitInBytes)
+
+ dispatch({ type: 'success', failingBuckets: failing })
+ } catch (error) {
+ console.error('Error validating bucket size limits: %O', error)
+ const message =
+ error instanceof Error && error.message.length > 0
+ ? error.message
+ : 'Unexpected error while validating bucket limits'
+
+ dispatch({ type: 'error', message })
+ } finally {
+ setShowModal(false)
+ }
+ }
+
+ const canTriggerRevalidation =
+ validationState.status === 'initial' || validationState.status === 'error'
+ const isValidating = validationState.status === 'validating'
+ const showValidationButton = canTriggerRevalidation || isValidating
+
+ const hasUnsuccessfulValidation = validationState.status === 'invalid'
+ const bucketLimitError: FieldError | undefined =
+ validationState.status === 'invalid'
+ ? {
+ type: 'manual',
+ message: encodeBucketLimitErrorMessage(
+ validationState.failingBuckets.map((bucket) => ({
+ name: bucket.name,
+ limit: bucket.file_size_limit,
+ }))
+ ),
+ }
+ : undefined
+ const hasSuccessfulValidation = validationState.status === 'valid'
+
+ const validationError = validationState.status === 'error' ? validationState.message : undefined
+
+ if (isLoadingBucketEstimate) {
+ // Avoid flashing manual validation UI before the estimate query resolves
+ return null
+ }
+
+ return (
+ <>
+ {showValidationButton && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <button
+ type="button"
+ className={cn(
+ 'mt-2 ml-auto text-foreground-lighter',
+ '!w-fit text-xs',
+ isValidating ? 'cursor-wait' : 'hover:text-foreground'
+ )}
+ onClick={() => setShowModal(true)}
+ disabled={isValidating}
+ >
+ {isValidating ? 'Validating...' : 'Validate size limit'}
+ </button>
+ </TooltipTrigger>
+ <TooltipContent side="bottom">
+ <p>Check that all existing buckets fit within this limit</p>
+ </TooltipContent>
+ </Tooltip>
+ )}
+
+ {hasUnsuccessfulValidation && (
+ <div className="mt-2 text-xs text-right text-destructive">
+ <StorageFileSizeLimitErrorMessage error={bucketLimitError} projectRef={projectRef} />
+ </div>
+ )}
+
+ {hasSuccessfulValidation && (
+ <p className="mt-2 text-xs text-right text-foreground-light">
+ All buckets fit within this limit.
+ </p>
+ )}
+
+ {validationError && (
+ <p className="mt-2 text-xs text-right text-destructive">
+ Failed to validate bucket limits: {validationError}
+ </p>
+ )}
+
+ <ConfirmationModal
+ visible={showModal}
+ loading={isValidating}
+ size="medium"
+ title="Validate bucket size limits"
+ description="Make sure no bucket-specific limit exceeds the new global limit."
+ confirmLabel="Run validation"
+ onCancel={() => setShowModal(false)}
+ onConfirm={handleValidate}
+ >
+ <p className="text-sm text-foreground-light">
+ Running this queries the <code className="text-code-inline">storage.buckets</code> table,
+ which may cause load on your database because you have more than{' '}
+ {THRESHOLD_FOR_AUTO_QUERYING_BUCKET_LIMITS.toLocaleString()} buckets.
+ </p>
+ </ConfirmationModal>
+ </>
+ )
+}
diff --git a/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.tsx b/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.tsx
index 47c8a6b1699..bd53ea5f3b7 100644
--- a/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.tsx
+++ b/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.tsx
@@ -1,6 +1,5 @@
import { zodResolver } from '@hookform/resolvers/zod'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import Link from 'next/link'
import { useEffect, useMemo, useState } from 'react'
import { SubmitHandler, useForm } from 'react-hook-form'
import { toast } from 'sonner'
@@ -14,10 +13,11 @@ import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { UpgradeToPro } from 'components/ui/UpgradeToPro'
import { useProjectStorageConfigQuery } from 'data/config/project-storage-config-query'
import { useProjectStorageConfigUpdateUpdateMutation } from 'data/config/project-storage-config-update-mutation'
-import { useBucketsQuery } from 'data/storage/buckets-query'
+import { useLargestBucketSizeLimitsCheck } from 'data/storage/buckets-max-size-limit-query'
import { useCheckEntitlements } from 'hooks/misc/useCheckEntitlements'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { DOCS_URL } from 'lib/constants'
import { formatBytes } from 'lib/helpers'
import {
@@ -36,13 +36,11 @@ import {
SelectValue_Shadcn_,
Select_Shadcn_,
Switch,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
} from 'ui'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { PageContainer } from 'ui-patterns/PageContainer'
import { PageSection, PageSectionContent } from 'ui-patterns/PageSection'
+import { StorageFileSizeLimitErrorMessage } from './StorageFileSizeLimitErrorMessage'
import {
StorageListV2MigratingCallout,
StorageListV2MigrationCallout,
@@ -52,7 +50,12 @@ import {
STORAGE_FILE_SIZE_LIMIT_MAX_BYTES_UNCAPPED,
StorageSizeUnits,
} from './StorageSettings.constants'
-import { convertFromBytes, convertToBytes } from './StorageSettings.utils'
+import {
+ convertFromBytes,
+ convertToBytes,
+ encodeBucketLimitErrorMessage,
+} from './StorageSettings.utils'
+import { ValidateSizeLimit } from './StorageSettings.ValidateSizeLimit'
const formId = 'storage-settings-form'
@@ -64,6 +67,8 @@ interface StorageSettingsState {
export const StorageSettings = () => {
const { ref: projectRef } = useParams()
+ const { data: project } = useSelectedProjectQuery()
+
const showMigrationCallout = useFlag('storageMigrationCallout')
const { can: canReadStorageSettings, isLoading: isLoadingPermissions } = useAsyncCheckPermissions(
@@ -87,6 +92,16 @@ export const StorageSettings = () => {
const isListV2Upgrading =
!!config && !config.capabilities.list_v2 && config.external.upstreamTarget === 'canary'
+ const {
+ runCondition: sizeLimitCheckCondition,
+ runQuery: sizeLimitCheckQuery,
+ isEstimatePending: isBucketEstimatePending,
+ } = useLargestBucketSizeLimitsCheck({
+ projectRef,
+ connectionString: project?.connectionString ?? undefined,
+ })
+ const shouldAutoValidateBucketLimits = sizeLimitCheckCondition === 'auto'
+
const { data: organization } = useSelectedOrganizationQuery()
const { getEntitlementNumericValue, isEntitlementUnlimited } =
useCheckEntitlements('storage.max_file_size')
@@ -94,17 +109,7 @@ export const StorageSettings = () => {
const isSpendCapOn =
organization?.plan.id === 'pro' && organization?.usage_billing_enabled === false
- const { data: buckets = [], isPending: isLoadingBuckets } = useBucketsQuery({ projectRef })
-
- // Calculate the minimum file size limit from existing buckets
- const minBucketFileSizeLimit = useMemo(() => {
- const bucketLimits = buckets
- .filter((bucket: any) => bucket.file_size_limit && bucket.file_size_limit > 0)
- .map((bucket: any) => bucket.file_size_limit!)
-
- return bucketLimits.length > 0 ? Math.min(...bucketLimits) : 0
- }, [buckets])
-
+ const [isUpdating, setIsUpdating] = useState(false)
const [initialValues, setInitialValues] = useState<StorageSettingsState>({
fileSizeLimit: 0,
unit: StorageSizeUnits.MB,
@@ -136,57 +141,71 @@ export const StorageSettings = () => {
path: ['fileSizeLimit'],
})
}
-
- // Validate that global limit is not smaller than any bucket's limit
- if (minBucketFileSizeLimit > 0 && !isLoadingBuckets && buckets.length > 0) {
- const { value: formattedMinBucketLimit } = convertFromBytes(minBucketFileSizeLimit, unit)
-
- if (fileSizeLimit < formattedMinBucketLimit) {
- // Get buckets that would be affected by this too-small global limit
- const affectedBuckets = buckets
- .filter((bucket) => bucket.file_size_limit && bucket.file_size_limit > 0)
- .filter(
- (bucket) => convertFromBytes(bucket.file_size_limit!, unit).value > fileSizeLimit
- )
- .sort((a, b) => (b.file_size_limit ?? 0) - (a.file_size_limit ?? 0))
-
- if (affectedBuckets.length > 0) {
- ctx.addIssue({
- code: z.ZodIssueCode.custom,
- message: `bucketLimit:${affectedBuckets.map((x) => x.name).join(',')}`,
- path: ['fileSizeLimit'],
- })
- }
- }
- }
})
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: initialValues,
+ mode: 'onSubmit',
+ reValidateMode: 'onSubmit',
})
const { unit: storageUnit } = form.watch()
- const { fileSizeLimit: fileSizeLimitError } = form.formState.errors
- const isBucketLimitError = !!fileSizeLimitError?.message?.startsWith('bucketLimit')
- const affectedBuckets = isBucketLimitError
- ? (fileSizeLimitError?.message ?? '').split(':')[1].split(',')
- : []
- const firstAffectBucketLimit = convertFromBytes(
- buckets.find((x) => x.name === affectedBuckets[0])?.file_size_limit ?? 0
- )
+ const fileSizeLimitError = form.formState.errors.fileSizeLimit
- const { mutate: updateStorageConfig, isPending: isUpdating } =
- useProjectStorageConfigUpdateUpdateMutation({
- onSuccess: () => {
- toast.success('Successfully updated storage settings')
- },
- })
+ const { mutate: updateStorageConfig } = useProjectStorageConfigUpdateUpdateMutation({
+ onSuccess: () => {
+ toast.success('Successfully updated storage settings')
+ setIsUpdating(false)
+ },
+ onError: (error) => {
+ toast.error(`Failed to update storage settings: ${error.message}`)
+ setIsUpdating(false)
+ },
+ })
const onSubmit: SubmitHandler<z.infer<typeof FormSchema>> = async (data) => {
if (!projectRef) return console.error('Project ref is required')
if (!config) return console.error('Storage config is required')
+ setIsUpdating(true)
+
+ if (shouldAutoValidateBucketLimits) {
+ try {
+ const buckets = await sizeLimitCheckQuery()
+ const globalLimitInBytes = convertToBytes(data.fileSizeLimit, data.unit)
+ const failingBuckets = buckets.filter(
+ (bucket) => bucket.file_size_limit > globalLimitInBytes
+ )
+
+ if (failingBuckets.length > 0) {
+ setIsUpdating(false)
+ form.setError('fileSizeLimit', {
+ type: 'manual',
+ message: encodeBucketLimitErrorMessage(
+ failingBuckets.map((bucket) => ({
+ name: bucket.name,
+ limit: bucket.file_size_limit,
+ }))
+ ),
+ })
+ return
+ }
+
+ form.clearErrors('fileSizeLimit')
+ } catch (error) {
+ setIsUpdating(false)
+ const message =
+ error instanceof Error && error.message.length > 0 ? error.message : 'Unexpected error'
+
+ form.setError('fileSizeLimit', {
+ type: 'manual',
+ message: `Failed to validate bucket limits automatically: ${message}`,
+ })
+ return
+ }
+ }
+
updateStorageConfig({
projectRef,
fileSizeLimit: convertToBytes(data.fileSizeLimit, data.unit),
@@ -216,6 +235,7 @@ export const StorageSettings = () => {
imageTransformationEnabled,
})
}
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, [isSuccess, config])
return (
@@ -298,15 +318,25 @@ export const StorageSettings = () => {
Learn more
</InlineLink>
.
+ {!shouldAutoValidateBucketLimits && (
+ <p>
+ Ensure that the global limit is greater than that of
+ individual buckets
+ </p>
+ )}
</>
}
>
<FormControl_Shadcn_>
- <div className="flex items-center">
+ <div className="flex items-center justify-end">
<Input_Shadcn_
type="number"
{...field}
- className="w-full rounded-r-none border-r-0"
+ onChange={(e) => {
+ field.onChange(e)
+ form.clearErrors('fileSizeLimit')
+ }}
+ className="w-32 rounded-r-none border-r-0"
disabled={isFreeTier || !canUpdateStorageSettings}
/>
<FormField_Shadcn_
@@ -315,10 +345,13 @@ export const StorageSettings = () => {
render={({ field: unitField }) => (
<Select_Shadcn_
value={unitField.value}
- onValueChange={unitField.onChange}
+ onValueChange={(val) => {
+ unitField.onChange(val)
+ form.clearErrors('fileSizeLimit')
+ }}
disabled={isFreeTier || !canUpdateStorageSettings}
>
- <SelectTrigger_Shadcn_ className="w-[180px] text-xs font-mono rounded-l-none bg-surface-300">
+ <SelectTrigger_Shadcn_ className="w-[90px] text-xs font-mono rounded-l-none bg-surface-300">
<SelectValue_Shadcn_ placeholder="Choose a prefix">
{storageUnit}
</SelectValue_Shadcn_>
@@ -339,70 +372,22 @@ export const StorageSettings = () => {
/>
</div>
</FormControl_Shadcn_>
+ {sizeLimitCheckCondition === 'confirm' && (
+ <ValidateSizeLimit
+ onValidate={sizeLimitCheckQuery}
+ projectRef={projectRef}
+ isLoadingBucketEstimate={isBucketEstimatePending}
+ />
+ )}
</FormItemLayout>
)}
/>
{fileSizeLimitError && (
<FormMessage_Shadcn_ className="ml-auto mt-2 text-right w-1/2">
- {isBucketLimitError ? (
- <>
- <p>
- Global limit must be greater than that of individual buckets.
- </p>
- <p>
- Remove or decrease the limit on{' '}
- <InlineLink
- href={`/project/${projectRef}/storage/files/buckets/${affectedBuckets[0]}`}
- className="text-destructive decoration-destructive-500 hover:decoration-destructive"
- >
- {affectedBuckets[0]}
- </InlineLink>{' '}
- ({firstAffectBucketLimit.value}
- {firstAffectBucketLimit.unit})
- {affectedBuckets.length > 1 && (
- <>
- {' '}
- and{' '}
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="underline underline-offset-2 decoration-dotted decoration-destructive-500 hover:decoration-destructive cursor-default">
- +{affectedBuckets.length - 1} other bucket
- {affectedBuckets.length > 2 ? 's' : ''}
- </span>
- </TooltipTrigger>
- <TooltipContent side="bottom">
- <ul>
- {affectedBuckets.slice(1).map((name) => {
- const bucket = buckets.find((x) => x.name === name)
- const formattedLimit = convertFromBytes(
- bucket?.file_size_limit ?? 0
- )
- return (
- <li
- key={name}
- className="hover:underline underline-offset-2"
- >
- <Link
- href={`/project/${projectRef}/storage/files/buckets/${name}`}
- >
- {bucket?.name} ({formattedLimit.value}
- {formattedLimit.unit})
- </Link>
- </li>
- )
- })}
- </ul>
- </TooltipContent>
- </Tooltip>{' '}
- first
- </>
- )}
- .
- </p>
- </>
- ) : (
- fileSizeLimitError.message
- )}
+ <StorageFileSizeLimitErrorMessage
+ error={fileSizeLimitError}
+ projectRef={projectRef}
+ />
</FormMessage_Shadcn_>
)}
</CardContent>
diff --git a/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.utils.ts b/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.utils.ts
index e0ec2e1eed6..9bb1b62cbf0 100644
--- a/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.utils.ts
+++ b/apps/studio/components/interfaces/Storage/StorageSettings/StorageSettings.utils.ts
@@ -2,6 +2,10 @@ import { StorageSizeUnits } from './StorageSettings.constants'
const k = 1024
+export const BUCKET_LIMIT_ERROR_PREFIX = 'bucketLimit:'
+
+type BucketLimitErrorBucket = { name: string; limit: number }
+
export const convertFromBytes = (bytes: number, unit?: StorageSizeUnits) => {
// Up to GB since that's our storage upload limit
if (bytes <= 0) return { value: 0, unit: StorageSizeUnits.BYTES }
@@ -50,3 +54,44 @@ export function getVectorURI(projectRef: string, protocol: string, endpoint?: st
url.pathname = '/storage/v1/vector'
return url.toString()
}
+
+export const formatBytesForDisplay = (bytes: number) => {
+ const { value, unit } = convertFromBytes(bytes)
+ return `${value.toLocaleString(undefined, { maximumFractionDigits: 2 })} ${unit}`
+}
+
+export const encodeBucketLimitErrorMessage = (buckets: BucketLimitErrorBucket[]) => {
+ const encodedBuckets = buckets
+ .map(({ name, limit }) => `${encodeURIComponent(name)}|${limit}`)
+ .join(',')
+ return `${BUCKET_LIMIT_ERROR_PREFIX}${encodedBuckets}`
+}
+
+export const isBucketLimitErrorMessage = (message?: string) => {
+ return message?.startsWith(BUCKET_LIMIT_ERROR_PREFIX)
+}
+
+export const decodeBucketLimitErrorMessage = (message?: string): BucketLimitErrorBucket[] => {
+ if (!isBucketLimitErrorMessage(message)) return []
+
+ const payload = message?.slice(BUCKET_LIMIT_ERROR_PREFIX.length) ?? ''
+ if (payload.length === 0) return []
+
+ return payload
+ .split(',')
+ .filter(Boolean)
+ .map((entry) => {
+ const parts = entry.split('|')
+ if (parts.length !== 2) return undefined
+
+ const name = decodeURIComponent(parts[0])
+ if (!name) return undefined
+
+ const limitString = parts[1]
+ const limit = Number(limitString ?? 0)
+ if (Number.isNaN(limit)) return undefined
+
+ return { name, limit }
+ })
+ .filter((entry) => entry !== undefined)
+}
diff --git a/apps/studio/data/sql/execute-sql-query.ts b/apps/studio/data/sql/execute-sql-query.ts
index cee39cfd3a0..cf58e425305 100644
--- a/apps/studio/data/sql/execute-sql-query.ts
+++ b/apps/studio/data/sql/execute-sql-query.ts
@@ -23,6 +23,11 @@ export type ExecuteSqlVariables = {
contextualInvalidation?: boolean
}
+/**
+ * Executes a SQL query against the user's instance.
+ *
+ * @throws {Error}
+ */
export async function executeSql<T = any>(
{
projectRef,
diff --git a/apps/studio/data/sql/queries/get-largest-size-limit-buckets.ts b/apps/studio/data/sql/queries/get-largest-size-limit-buckets.ts
new file mode 100644
index 00000000000..76248f2e789
--- /dev/null
+++ b/apps/studio/data/sql/queries/get-largest-size-limit-buckets.ts
@@ -0,0 +1,20 @@
+import { sqlKeys } from '../keys'
+
+export const LARGEST_SIZE_LIMIT_BUCKETS_COUNT = 50
+
+/**
+ * SQL to get the storage buckets with the largest file size limits.
+ *
+ * This query is unoptimized and should not be automatically called because
+ * there is no index on `file_size_limit` in the `storage.buckets` table.
+ */
+export const getLargestSizeLimitBucketsSqlUnoptimized = /* SQL */ `
+SELECT id, name, file_size_limit
+FROM storage.buckets
+WHERE file_size_limit IS NOT NULL
+ORDER BY file_size_limit DESC
+LIMIT ${LARGEST_SIZE_LIMIT_BUCKETS_COUNT + 1};
+`.trim()
+
+export const getLargestSizeLimitBucketsKey = (projectRef: string | undefined) =>
+ sqlKeys.query(projectRef, ['buckets-with-largest-size-limit'])
diff --git a/apps/studio/data/sql/queries/get-live-tuple-stats.ts b/apps/studio/data/sql/queries/get-live-tuple-stats.ts
new file mode 100644
index 00000000000..d96ab8cff41
--- /dev/null
+++ b/apps/studio/data/sql/queries/get-live-tuple-stats.ts
@@ -0,0 +1,19 @@
+import { literal } from '@supabase/pg-meta/src/pg-format'
+import { sqlKeys } from '../keys'
+
+export const getLiveTupleEstimate = (table: string, schema: string = 'public') => {
+ const sql = /* SQL */ `
+SELECT n_live_tup AS live_tuple_estimate
+FROM pg_stat_user_tables
+WHERE schemaname = ${literal(schema)}
+AND relname = ${literal(table)};
+`.trim()
+
+ return sql
+}
+
+export const getLiveTupleEstimateKey = (
+ projectRef: string | undefined,
+ table: string,
+ schema = 'public'
+) => sqlKeys.query(projectRef, ['live-tuple-estimate', schema, table])
diff --git a/apps/studio/data/storage/buckets-max-size-limit-query.ts b/apps/studio/data/storage/buckets-max-size-limit-query.ts
new file mode 100644
index 00000000000..033d027b7df
--- /dev/null
+++ b/apps/studio/data/storage/buckets-max-size-limit-query.ts
@@ -0,0 +1,135 @@
+import { useQuery, useQueryClient } from '@tanstack/react-query'
+import { useCallback } from 'react'
+
+import { executeSql } from 'data/sql/execute-sql-query'
+import {
+ getLargestSizeLimitBucketsKey,
+ getLargestSizeLimitBucketsSqlUnoptimized,
+} from 'data/sql/queries/get-largest-size-limit-buckets'
+import {
+ getLiveTupleEstimate,
+ getLiveTupleEstimateKey,
+} from 'data/sql/queries/get-live-tuple-stats'
+
+export const THRESHOLD_FOR_AUTO_QUERYING_BUCKET_LIMITS = 10_000
+
+type ConnectionVars = {
+ projectRef?: string
+ connectionString?: string
+}
+
+const getBucketNumberEstimateKey = (projectRef: string | undefined) =>
+ getLiveTupleEstimateKey(projectRef, 'buckets', 'storage')
+
+const getBucketNumberEstimate = async ({
+ projectRef,
+ connectionString,
+}: ConnectionVars): Promise<number | undefined> => {
+ if (!projectRef) throw new Error('Project reference is required')
+ if (!connectionString) throw new Error('Connection string is required')
+
+ const queryKey = getBucketNumberEstimateKey(projectRef)
+
+ try {
+ const sql = getLiveTupleEstimate('buckets', 'storage')
+ const { result } = await executeSql<{ live_tuple_estimate: number }[]>({
+ projectRef,
+ connectionString,
+ queryKey,
+ sql,
+ })
+ return result[0]?.live_tuple_estimate
+ } catch {
+ return undefined
+ }
+}
+
+export type BucketWithSizeLimit = {
+ id: string
+ name: string
+ file_size_limit: number
+}
+
+const getBucketsWithLargestSizeLimit = async ({
+ projectRef,
+ connectionString,
+}: ConnectionVars): Promise<BucketWithSizeLimit[]> => {
+ if (!projectRef) throw new Error('Project reference is required')
+ if (!connectionString) throw new Error('Connection string is required')
+
+ const key = getLargestSizeLimitBucketsKey(projectRef)
+
+ const sql = getLargestSizeLimitBucketsSqlUnoptimized
+ const { result } = await executeSql<{ id: string; name: string; file_size_limit: number }[]>({
+ projectRef,
+ connectionString,
+ queryKey: key,
+ sql,
+ })
+ return result
+}
+
+type UseLargestBucketSizeLimitsCheckParams = ConnectionVars
+type UseLargestBucketSizeLimitsCheckReturn = {
+ /**
+ * When the query for largest bucket size limits should be run.
+ *
+ * - `auto`: Run the query automatically.
+ * - `confirm`: Ask the user for confirmation before running the query.
+ */
+ runCondition: 'auto' | 'confirm'
+ /**
+ * Run query to get the buckets with the largest file size limits. Buckets
+ * are sorted in order of decreasing file size limit.
+ *
+ * @throws Error
+ */
+ runQuery: () => Promise<BucketWithSizeLimit[]>
+ /**
+ * Whether the bucket count estimate query is still running. Used by UI to
+ * avoid flashing validation controls before we know if auto-validation is
+ * safe.
+ */
+ isEstimatePending: boolean
+}
+
+export const useLargestBucketSizeLimitsCheck = ({
+ projectRef,
+ connectionString,
+}: UseLargestBucketSizeLimitsCheckParams): UseLargestBucketSizeLimitsCheckReturn => {
+ const queryClient = useQueryClient()
+
+ const estimateKey = getBucketNumberEstimateKey(projectRef)
+
+ const { data: estimatedRows, isPending: isEstimatePending } = useQuery<number | undefined>({
+ // Query is the same even if connectionString changes, and doesn't correctly
+ // track projectRef
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps
+ queryKey: estimateKey,
+ queryFn: () => getBucketNumberEstimate({ projectRef, connectionString }),
+ enabled: !!projectRef && !!connectionString,
+ })
+
+ const bucketLimitsKey = getLargestSizeLimitBucketsKey(projectRef)
+
+ const fetchLargestBucketLimits = useCallback(
+ () =>
+ queryClient.fetchQuery({
+ // Query is the same even if connectionString changes, and doesn't correctly
+ // track projectRef
+ // eslint-disable-next-line @tanstack/query/exhaustive-deps
+ queryKey: bucketLimitsKey,
+ queryFn: () => getBucketsWithLargestSizeLimit({ projectRef, connectionString }),
+ }),
+ [queryClient, projectRef, connectionString, bucketLimitsKey]
+ )
+
+ return {
+ runCondition:
+ estimatedRows !== undefined && estimatedRows <= THRESHOLD_FOR_AUTO_QUERYING_BUCKET_LIMITS
+ ? 'auto'
+ : 'confirm',
+ runQuery: fetchLargestBucketLimits,
+ isEstimatePending,
+ }
+}
diff --git a/apps/studio/tests/components/Storage/StorageSettings.utils.test.ts b/apps/studio/tests/components/Storage/StorageSettings.utils.test.ts
index 82bf4350f1d..6f0ac3e8f00 100644
--- a/apps/studio/tests/components/Storage/StorageSettings.utils.test.ts
+++ b/apps/studio/tests/components/Storage/StorageSettings.utils.test.ts
@@ -1,9 +1,13 @@
import { StorageSizeUnits } from 'components/interfaces/Storage/StorageSettings/StorageSettings.constants'
import {
+ BUCKET_LIMIT_ERROR_PREFIX,
convertFromBytes,
convertToBytes,
+ decodeBucketLimitErrorMessage,
+ encodeBucketLimitErrorMessage,
+ isBucketLimitErrorMessage,
} from 'components/interfaces/Storage/StorageSettings/StorageSettings.utils'
-import { describe, test, expect } from 'vitest'
+import { describe, expect, test } from 'vitest'
describe('StorageSettings.utils: convertFromBytes', () => {
test('should convert 1024 to 1KB', () => {
@@ -79,3 +83,53 @@ describe('StorageSettings.utils: convertToBytes', () => {
expect(output).toStrictEqual(0)
})
})
+
+describe('StorageSettings.utils: bucket limit error encoding', () => {
+ const bucketLists = [
+ {
+ description: 'multiple buckets with standard limits',
+ buckets: [
+ { name: 'images', limit: 1024 },
+ { name: 'avatars', limit: 2048 },
+ ],
+ },
+ {
+ description: 'single bucket with zero limit',
+ buckets: [{ name: 'avatars', limit: 0 }],
+ },
+ {
+ description: 'bucket names with spaces and punctuation and large limits',
+ buckets: [
+ { name: 'prod-images', limit: Number.MAX_SAFE_INTEGER },
+ { name: 'logs archive', limit: 987654321 },
+ ],
+ },
+ {
+ description: 'empty bucket list',
+ buckets: [],
+ },
+ {
+ description: 'bucket name with pipe/comma character (edge case)',
+ buckets: [
+ { name: 'data|backup', limit: 4096 },
+ { name: 'reports,2023', limit: 8192 },
+ ],
+ },
+ ]
+
+ bucketLists.forEach(({ description, buckets }) => {
+ test(`should round trip encode/decode for ${description}`, () => {
+ const encoded = encodeBucketLimitErrorMessage(buckets)
+ expect(encoded.startsWith(BUCKET_LIMIT_ERROR_PREFIX)).toBe(true)
+ expect(isBucketLimitErrorMessage(encoded)).toBe(true)
+
+ const decoded = decodeBucketLimitErrorMessage(encoded)
+ expect(decoded).toStrictEqual(buckets)
+ })
+ })
+
+ test('should return empty results for non bucket limit errors', () => {
+ expect(isBucketLimitErrorMessage('other:error')).toBe(false)
+ expect(decodeBucketLimitErrorMessage('other:error')).toStrictEqual([])
+ })
+})