The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(storage): add bucket object versioning form fields (FE-4161) (#49203)
Francesco Sansalvadore089133cc2cbb
diff --git a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsxindex e96829ffa56..8ee334b54b1 100644--- a/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx+++ b/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx@@ -1,4 +1,10 @@-import { FeatureFlagContext, LOCAL_STORAGE_KEYS, safeLocalStorage, useFlag } from 'common'+import {+ FeatureFlagContext,+ LOCAL_STORAGE_KEYS,+ safeLocalStorage,+ useFlag,+ useParams,+} from 'common'import { noop } from 'lodash'import { useQueryState } from 'nuqs'import {@@ -13,6 +19,7 @@ import {} from 'react'import { useFeaturePreviews } from './useFeaturePreviews'+import { useProjectStorageConfigQuery } from '@/data/config/project-storage-config-query'import { IS_PLATFORM } from '@/lib/constants'import { EMPTY_OBJ } from '@/lib/void'@@ -154,10 +161,18 @@ export const useIsExplorerEnabled = () => {return isExplorerEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_EXPLORER]}+/** Three gates: the ConfigCat kill switch, the project's capability, and the user's opt-in. */export const useIsStorageVersioningEnabled = () => {+ const { ref } = useParams()const { flags } = useFeaturePreviewContext()const isStorageVersioningEnabled = useFlag('storageVersioningPrivateAlpha')- return isStorageVersioningEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_STORAGE_VERSIONING]+ const { data } = useProjectStorageConfigQuery({ projectRef: ref })+ const isObjectVersioningAvailable = !!data?.capabilities?.object_versioning+ return (+ isStorageVersioningEnabled &&+ isObjectVersioningAvailable &&+ flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_STORAGE_VERSIONING]+ )}export const useFeaturePreviewModal = () => {diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningFields.schema.test.ts b/apps/studio/components/interfaces/Storage/BucketVersioningFields.schema.test.tsnew file mode 100644index 00000000000..36532b40582--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningFields.schema.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from 'vitest'+import { z } from 'zod'++import {+ bucketVersioningFormFields,+ S3_MAX_NONCURRENT_VERSIONS,+ superRefineBucketVersioning,+ type BucketVersioningFormValues,+} from './BucketVersioningFields.schema'++const values = (+ overrides: Partial<BucketVersioningFormValues> = {}+): BucketVersioningFormValues => ({+ enable_versioning: true,+ version_expiry_days: 30,+ max_noncurrent_versions: 10,+ expiration_mode: 'and',+ ...overrides,+})++const refine = (formValues: BucketVersioningFormValues) => {+ const result = z+ .custom<BucketVersioningFormValues>()+ .superRefine(superRefineBucketVersioning)+ .safeParse(formValues)++ if (result.success) return []+ return result.error.issues.map((issue) => ({+ path: issue.path.join('.'),+ message: issue.message,+ }))+}++describe('superRefineBucketVersioning', () => {+ it('accepts a valid policy', () => {+ expect(refine(values())).toEqual([])+ })++ it('skips validation entirely when versioning is off', () => {+ // Stale numbers must not block an unrelated bucket-settings save.+ expect(refine(values({ enable_versioning: false, version_expiry_days: -5 }))).toEqual([])+ })++ it('treats empty values as "no condition set" rather than zero', () => {+ expect(refine(values({ version_expiry_days: '', max_noncurrent_versions: '' }))).toEqual([])+ })++ it('rejects a retention window below one day', () => {+ expect(refine(values({ version_expiry_days: 0 })).map((i) => i.path)).toEqual([+ 'version_expiry_days',+ ])+ })++ it('rejects a version cap with no expiration age, which S3 will not accept', () => {+ const issues = refine(values({ version_expiry_days: '', max_noncurrent_versions: 10 }))+ expect(issues).toHaveLength(1)+ expect(issues[0].path).toBe('max_noncurrent_versions')+ expect(issues[0].message).toMatch(/expiration age/i)+ })++ it('rejects a version cap below one', () => {+ expect(refine(values({ max_noncurrent_versions: 0 })).map((i) => i.path)).toEqual([+ 'max_noncurrent_versions',+ ])+ })++ it('rejects exceeding the S3 ceiling of 100 versions', () => {+ const issues = refine(values({ max_noncurrent_versions: S3_MAX_NONCURRENT_VERSIONS + 1 }))+ expect(issues).toHaveLength(1)+ expect(issues[0].message).toContain(String(S3_MAX_NONCURRENT_VERSIONS))+ })++ it('accepts exactly the S3 ceiling', () => {+ expect(refine(values({ max_noncurrent_versions: S3_MAX_NONCURRENT_VERSIONS }))).toEqual([])+ })++ it('reports both fields independently', () => {+ const issues = refine(values({ version_expiry_days: 0, max_noncurrent_versions: 0 }))+ expect(issues.map((i) => i.path).sort()).toEqual([+ 'max_noncurrent_versions',+ 'version_expiry_days',+ ])+ })+})++describe('bucketVersioningFormFields', () => {+ const schema = z.object(bucketVersioningFormFields)++ it('defaults to versioning off with no conditions set', () => {+ expect(schema.parse({})).toEqual({+ enable_versioning: false,+ version_expiry_days: '',+ max_noncurrent_versions: '',+ expiration_mode: 'and',+ })+ })++ it('coerces numeric strings from the input element', () => {+ const parsed = schema.parse({ version_expiry_days: '45', max_noncurrent_versions: '5' })+ expect(parsed.version_expiry_days).toBe(45)+ expect(parsed.max_noncurrent_versions).toBe(5)+ })++ it('preserves the empty sentinel instead of coercing it to zero', () => {+ // `Number('')` is 0, so a bare coercion would turn "no condition" into "expire immediately".+ expect(schema.parse({ version_expiry_days: '' }).version_expiry_days).toBe('')+ })++ it('rejects a fractional retention window', () => {+ expect(schema.safeParse({ version_expiry_days: 1.5 }).success).toBe(false)+ })++ it('rejects an unknown expiration mode', () => {+ expect(schema.safeParse({ expiration_mode: 'xor' }).success).toBe(false)+ })+})diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningFields.schema.ts b/apps/studio/components/interfaces/Storage/BucketVersioningFields.schema.tsnew file mode 100644index 00000000000..9812a81cfc1--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningFields.schema.ts@@ -0,0 +1,65 @@+import { z } from 'zod'++import type { ExpirationMode } from './StorageVersioning.constants'++/** Empty drops the condition from the policy, which is distinct from zero. */+const versioningNumberField = z.union([z.literal(''), z.coerce.number().int()])++export const S3_MAX_NONCURRENT_VERSIONS = 100++export const bucketVersioningFormFields = {+ enable_versioning: z.boolean().default(false),+ version_expiry_days: versioningNumberField.default(''),+ max_noncurrent_versions: versioningNumberField.default(''),+ expiration_mode: z.enum(['and', 'or']).default('and'),+}++export interface BucketVersioningFormValues {+ enable_versioning: boolean+ version_expiry_days: '' | number+ max_noncurrent_versions: '' | number+ expiration_mode: ExpirationMode+}++export const superRefineBucketVersioning = (+ data: BucketVersioningFormValues,+ ctx: z.RefinementCtx+) => {+ if (!data.enable_versioning) return++ const { version_expiry_days: days, max_noncurrent_versions: versions } = data++ if (days !== '' && days < 1) {+ ctx.addIssue({+ path: ['version_expiry_days'],+ code: z.ZodIssueCode.custom,+ message: 'Must be at least 1 day',+ })+ }++ if (versions === '') return++ // S3 only accepts a noncurrent-count condition alongside a noncurrent-days one+ if (days === '') {+ ctx.addIssue({+ path: ['max_noncurrent_versions'],+ code: z.ZodIssueCode.custom,+ message: 'Requires an expiration age to be set',+ })+ return+ }++ if (versions < 1) {+ ctx.addIssue({+ path: ['max_noncurrent_versions'],+ code: z.ZodIssueCode.custom,+ message: 'Must be at least 1 version or empty to disable',+ })+ } else if (versions > S3_MAX_NONCURRENT_VERSIONS) {+ ctx.addIssue({+ path: ['max_noncurrent_versions'],+ code: z.ZodIssueCode.custom,+ message: `Cannot exceed ${S3_MAX_NONCURRENT_VERSIONS} versions`,+ })+ }+}diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningFields.test.tsx b/apps/studio/components/interfaces/Storage/BucketVersioningFields.test.tsxnew file mode 100644index 00000000000..b863797eb3a--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningFields.test.tsx@@ -0,0 +1,281 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { screen, waitForElementToBeRemoved, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { useForm } from 'react-hook-form'+import { Form } from 'ui'+import { describe, expect, test } from 'vitest'+import { z } from 'zod'++import { BucketVersioningFields } from './BucketVersioningFields'+import {+ bucketVersioningFormFields,+ superRefineBucketVersioning,+ type BucketVersioningFormValues,+} from './BucketVersioningFields.schema'+import type { BucketVersioningState } from './StorageVersioning.constants'+import { customRender } from '@/tests/lib/custom-render'+import { addAPIMock } from '@/tests/lib/msw'++const FormSchema = z.object(bucketVersioningFormFields).superRefine(superRefineBucketVersioning)++const DEFAULT_VALUES: BucketVersioningFormValues = {+ enable_versioning: false,+ version_expiry_days: 30,+ max_noncurrent_versions: 10,+ expiration_mode: 'and',+}++const Harness = ({+ defaultValues,+ ...props+}: {+ defaultValues?: Partial<BucketVersioningFormValues>+ initialVersioningState?: BucketVersioningState+ initialRetentionDays?: number | null+ initialMaxVersions?: number | null+ isPublicBucket?: boolean+ isLoadingPolicy?: boolean+ isUnsupportedPolicy?: boolean+ policyError?: { message: string } | null+}) => {+ const form = useForm<BucketVersioningFormValues>({+ resolver: zodResolver(FormSchema),+ defaultValues: { ...DEFAULT_VALUES, ...defaultValues },+ mode: 'onChange',+ })++ return (+ <Form {...form}>+ <form>+ <BucketVersioningFields {...props} />+ </form>+ </Form>+ )+}++const renderFields = (props: Parameters<typeof Harness>[0] = {}) =>+ customRender(<Harness {...props} />)++const getVersioningSwitch = () => screen.getByRole('switch')+const getDaysInput = () =>+ screen.getByRole('spinbutton', { name: /noncurrent version expiration/i })+const getVersionsInput = () =>+ screen.getByRole('spinbutton', { name: /retained noncurrent versions/i })++describe('BucketVersioningFields', () => {+ test('hides the lifecycle policy until versioning is turned on', async () => {+ renderFields()++ expect(screen.getByText('Object versioning')).toBeInTheDocument()+ expect(screen.queryByText('Lifecycle policy')).not.toBeInTheDocument()++ await userEvent.click(getVersioningSwitch())++ expect(await screen.findByText('Lifecycle policy')).toBeInTheDocument()+ expect(screen.getByText('Noncurrent version expiration')).toBeInTheDocument()+ expect(screen.getByText('Retained noncurrent versions')).toBeInTheDocument()+ })++ test('rejects a version cap above the S3 ceiling', async () => {+ renderFields({ defaultValues: { enable_versioning: true } })++ const versionsInput = getVersionsInput()+ await userEvent.clear(versionsInput)+ await userEvent.type(versionsInput, '150')++ expect(await screen.findByText(/Cannot exceed 100 versions/)).toBeInTheDocument()+ })++ test('disables the version cap until an expiration age is set', async () => {+ renderFields({+ defaultValues: { enable_versioning: true, version_expiry_days: '' },+ })++ expect(getVersionsInput()).toBeDisabled()+ expect(screen.getByText('Requires an expiration age to be set.')).toBeInTheDocument()++ await userEvent.type(getDaysInput(), '30')++ expect(getVersionsInput()).toBeEnabled()+ })++ test('clears an orphaned version cap when the expiration age is removed', async () => {+ // S3 rejects a noncurrent-count rule with no noncurrent-days condition.+ renderFields({+ defaultValues: {+ enable_versioning: true,+ version_expiry_days: 30,+ max_noncurrent_versions: 10,+ },+ })++ expect(getVersionsInput()).toHaveValue(10)++ await userEvent.clear(getDaysInput())++ expect(getVersionsInput()).toHaveValue(null)+ expect(getVersionsInput()).toBeDisabled()+ })++ test('offers the and/or mode only while both conditions are set', async () => {+ renderFields({ defaultValues: { enable_versioning: true } })++ expect(screen.getByText('Expire a noncurrent version when')).toBeInTheDocument()++ // The section animates out, so it lingers in the DOM until the exit transition finishes.+ await userEvent.clear(getVersionsInput())++ await waitForElementToBeRemoved(() => screen.queryByText('Expire a noncurrent version when'))+ })++ test('warns when neither lifecycle condition is set', async () => {+ renderFields({+ defaultValues: {+ enable_versioning: true,+ version_expiry_days: '',+ max_noncurrent_versions: '',+ },+ })++ expect(screen.getByText('No lifecycle policy')).toBeInTheDocument()+ })++ test('warns that a public bucket serves every version', () => {+ renderFields({ defaultValues: { enable_versioning: true }, isPublicBucket: true })++ expect(screen.getByText('A public bucket serves every version')).toBeInTheDocument()+ })++ test('does not warn about public exposure for a private bucket', () => {+ renderFields({ defaultValues: { enable_versioning: true }, isPublicBucket: false })++ expect(screen.getByText('Lifecycle policy')).toBeInTheDocument()+ expect(screen.queryByText('A public bucket serves every version')).not.toBeInTheDocument()+ })++ test('explains that turning the switch off suspends rather than disables', async () => {+ renderFields({+ defaultValues: { enable_versioning: true },+ initialVersioningState: 'enabled',+ })++ await userEvent.click(getVersioningSwitch())++ expect(await screen.findByText('Saving will suspend versioning')).toBeInTheDocument()+ await waitForElementToBeRemoved(() => screen.queryByText('Lifecycle policy'))+ })++ test('warns before tightening the retention window on an already-versioned bucket', async () => {+ renderFields({+ defaultValues: { enable_versioning: true, version_expiry_days: 30 },+ initialVersioningState: 'enabled',+ initialRetentionDays: 30,+ initialMaxVersions: 10,+ })++ const daysInput = getDaysInput()+ await userEvent.clear(daysInput)+ await userEvent.type(daysInput, '7')++ const warning = await screen.findByText('Tightening retention expires some versions')+ expect(+ within(warning.parentElement!).getByText(/past the retention window/)+ ).toBeInTheDocument()+ })++ test('shows a loading state instead of claiming there is no policy, while one is loading', () => {+ renderFields({+ defaultValues: {+ enable_versioning: true,+ version_expiry_days: '',+ max_noncurrent_versions: '',+ },+ initialVersioningState: 'enabled',+ isLoadingPolicy: true,+ })++ expect(screen.getByLabelText('Loading lifecycle policy')).toBeInTheDocument()+ // The bucket may well have a policy; the fetch just hasn't said so yet.+ expect(screen.queryByText('No lifecycle policy')).not.toBeInTheDocument()+ expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()+ })++ test('shows the policy fields once it has resolved', () => {+ renderFields({+ defaultValues: {+ enable_versioning: true,+ version_expiry_days: '',+ max_noncurrent_versions: '',+ },+ initialVersioningState: 'enabled',+ isLoadingPolicy: false,+ })++ expect(screen.queryByLabelText('Loading lifecycle policy')).not.toBeInTheDocument()+ expect(getDaysInput()).toBeInTheDocument()+ expect(screen.getByText('No lifecycle policy')).toBeInTheDocument()+ })++ test('reports a policy it failed to read instead of showing empty fields', () => {+ // The alert's support link reads the project it would report against.+ addAPIMock({+ method: 'get',+ path: '/platform/projects/:ref',+ // @ts-expect-error minimal project shape for useSelectedProject+ response: { id: 1, ref: 'default', name: 'Default Project', status: 'ACTIVE_HEALTHY' },+ })++ renderFields({+ defaultValues: {+ enable_versioning: true,+ version_expiry_days: '',+ max_noncurrent_versions: '',+ },+ initialVersioningState: 'enabled',+ policyError: { message: 'Failed to retrieve bucket lifecycle' },+ })++ expect(screen.getByText('Failed to retrieve the lifecycle policy')).toBeInTheDocument()+ // The bucket may well have a policy; the fetch failed before saying so.+ expect(screen.queryByText('No lifecycle policy')).not.toBeInTheDocument()+ expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()+ })++ test('leaves a policy it cannot represent alone instead of offering to edit it', () => {+ renderFields({+ defaultValues: { enable_versioning: true },+ initialVersioningState: 'enabled',+ initialRetentionDays: 30,+ initialMaxVersions: 10,+ isUnsupportedPolicy: true,+ })++ expect(screen.getByText('Lifecycle policy set outside the dashboard')).toBeInTheDocument()+ expect(screen.queryByRole('spinbutton')).not.toBeInTheDocument()+ expect(screen.queryByText('No lifecycle policy')).not.toBeInTheDocument()+ })++ test('does not warn about tightening a policy it only partly read', async () => {+ renderFields({+ defaultValues: { enable_versioning: true, version_expiry_days: 7 },+ initialVersioningState: 'enabled',+ initialRetentionDays: 30,+ initialMaxVersions: 10,+ isUnsupportedPolicy: true,+ })++ expect(screen.queryByText('Tightening retention expires some versions')).not.toBeInTheDocument()+ })++ test('does not warn about tightening when enabling versioning for the first time', async () => {+ renderFields({ initialVersioningState: 'disabled', initialRetentionDays: null })++ await userEvent.click(getVersioningSwitch())++ const daysInput = getDaysInput()+ await userEvent.clear(daysInput)+ await userEvent.type(daysInput, '7')++ expect(screen.queryByText('Tightening retention expires some versions')).not.toBeInTheDocument()+ })+})diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningFields.tsx b/apps/studio/components/interfaces/Storage/BucketVersioningFields.tsxnew file mode 100644index 00000000000..d3f01ef04bf--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningFields.tsx@@ -0,0 +1,162 @@+import { AnimatePresence } from 'framer-motion'+import { useFormContext, useWatch } from 'react-hook-form'+import { Badge, DialogSection, DialogSectionSeparator, FormControl, FormField, Switch } from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'++import { type BucketVersioningFormValues } from './BucketVersioningFields.schema'+import {+ getRetentionTightening,+ RETENTION_TIGHTENING_DESCRIPTION,+ toNullableNumber,+} from './BucketVersioningFields.utils'+import { LifecyclePolicySection } from './LifecyclePolicySection'+import type { BucketVersioningState, ExpirationMode } from './StorageVersioning.constants'+import { FormSectionCollapse } from '@/components/ui/FormSectionCollapse'++interface BucketVersioningFieldsProps {+ initialVersioningState?: BucketVersioningState+ initialRetentionDays?: number | null+ initialMaxVersions?: number | null+ isPublicBucket?: boolean+ /** The bucket's stored lifecycle policy is still being fetched. */+ isLoadingPolicy?: boolean+ /** The stored policy holds rules these fields cannot represent, so it is left alone. */+ isUnsupportedPolicy?: boolean+ /** The bucket's stored lifecycle policy could not be fetched. */+ policyError?: { message: string } | null+}++export const BucketVersioningFields = ({+ initialVersioningState = 'disabled',+ initialRetentionDays,+ initialMaxVersions,+ isPublicBucket = false,+ isLoadingPolicy = false,+ isUnsupportedPolicy = false,+ policyError,+}: BucketVersioningFieldsProps) => {+ const { control, setValue } = useFormContext<BucketVersioningFormValues>()++ const isVersioningEnabled = useWatch({ control, name: 'enable_versioning' })+ const retentionDays = useWatch({ control, name: 'version_expiry_days' })+ const maxVersions = useWatch({ control, name: 'max_noncurrent_versions' })+ const expirationMode = useWatch({ control, name: 'expiration_mode' })++ // Turning the switch off suspends rather than disables, so this is a heads-up.+ const isSuspending = !isVersioningEnabled && initialVersioningState !== 'disabled'++ // A bound nobody has read, or that the fields only partly represent, can't be compared against.+ const hasKnownBounds = !isLoadingPolicy && !isUnsupportedPolicy && !policyError++ const tightening = getRetentionTightening({+ initialVersioningState,+ isVersioningEnabled,+ initialRetentionDays: hasKnownBounds ? initialRetentionDays : undefined,+ initialMaxVersions: hasKnownBounds ? initialMaxVersions : undefined,+ nextRetentionDays: toNullableNumber(retentionDays),+ nextMaxVersions: toNullableNumber(maxVersions),+ })++ const hasDays = typeof retentionDays === 'number' && retentionDays > 0+ const hasVersions = typeof maxVersions === 'number' && maxVersions > 0++ const handleModeChange = (mode: ExpirationMode) => {+ setValue('expiration_mode', mode, { shouldDirty: true })+ }++ return (+ <>+ <DialogSectionSeparator />++ <DialogSection className="space-y-3">+ <FormField+ name="enable_versioning"+ control={control}+ render={({ field }) => (+ <FormItemLayout+ hideMessage+ name="enable_versioning"+ label={+ <span className="flex items-center gap-x-2">+ Object versioning+ <Badge variant="warning">Private Alpha</Badge>+ </span>+ }+ description="Retains previous versions of an object when it is overwritten or deleted"+ layout="flex"+ >+ <FormControl>+ <Switch+ // Matches the field name, which is what the layout's label points at.+ id="enable_versioning"+ aria-label="Object versioning"+ size="large"+ checked={field.value}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItemLayout>+ )}+ />++ <AnimatePresence initial={false}>+ {isSuspending && (+ <FormSectionCollapse key="suspension-notice">+ <Admonition+ type="default"+ title={+ initialVersioningState === 'enabled'+ ? 'Saving will suspend versioning'+ : 'Versioning is suspended on this bucket'+ }+ description="Existing versions stay put. Re-enable versioning at any time."+ />+ </FormSectionCollapse>+ )}++ {isVersioningEnabled && isPublicBucket && (+ <FormSectionCollapse key="public-bucket-warning">+ <Admonition+ type="warning"+ title="A public bucket serves every version"+ description={+ <>+ Anyone with a version ID can fetch a noncurrent version of a public object. To+ hide noncurrent versions, add an RLS policy on <code>storage.objects</code> that+ filters on <code>metadata->>'isCurrent' = 'true'</code>.+ </>+ }+ />+ </FormSectionCollapse>+ )}++ {isVersioningEnabled && tightening !== 'none' && (+ <FormSectionCollapse key="tightening-warning">+ <Admonition+ type="warning"+ title="Tightening retention expires some versions"+ description={RETENTION_TIGHTENING_DESCRIPTION[tightening]}+ />+ </FormSectionCollapse>+ )}++ {isVersioningEnabled && (+ <FormSectionCollapse key="lifecycle-policy">+ <LifecyclePolicySection+ control={control}+ hasDays={hasDays}+ hasVersions={hasVersions}+ mode={expirationMode}+ onModeChange={handleModeChange}+ isLoading={isLoadingPolicy}+ isUnsupported={isUnsupportedPolicy}+ error={policyError}+ />+ </FormSectionCollapse>+ )}+ </AnimatePresence>+ </DialogSection>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningFields.utils.test.ts b/apps/studio/components/interfaces/Storage/BucketVersioningFields.utils.test.tsnew file mode 100644index 00000000000..4adf9c4182f--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningFields.utils.test.ts@@ -0,0 +1,129 @@+import { describe, expect, it } from 'vitest'++import {+ getRetentionTightening,+ RETENTION_TIGHTENING_DESCRIPTION,+ toNullableNumber,+} from './BucketVersioningFields.utils'++const params = (overrides: Partial<Parameters<typeof getRetentionTightening>[0]> = {}) => ({+ initialVersioningState: 'enabled' as const,+ isVersioningEnabled: true,+ initialRetentionDays: 30,+ initialMaxVersions: 10,+ nextRetentionDays: 30,+ nextMaxVersions: 10,+ ...overrides,+})++describe('getRetentionTightening', () => {+ it('reports no tightening when nothing changed', () => {+ expect(getRetentionTightening(params())).toBe('none')+ })++ it('detects a shorter retention window', () => {+ expect(getRetentionTightening(params({ nextRetentionDays: 7 }))).toBe('days')+ })++ it('detects a lower version cap', () => {+ expect(getRetentionTightening(params({ nextMaxVersions: 3 }))).toBe('versions')+ })++ it('detects both bounds tightening at once', () => {+ expect(getRetentionTightening(params({ nextRetentionDays: 7, nextMaxVersions: 3 }))).toBe(+ 'both'+ )+ })++ it('does not warn when a bound is raised', () => {+ expect(getRetentionTightening(params({ nextRetentionDays: 90, nextMaxVersions: 20 }))).toBe(+ 'none'+ )+ })++ it('does not warn when a bound is cleared, which retains more rather than less', () => {+ expect(getRetentionTightening(params({ nextRetentionDays: null, nextMaxVersions: null }))).toBe(+ 'none'+ )+ })++ it('warns when a bound is newly added where none existed, which was keeping them forever', () => {+ expect(+ getRetentionTightening(params({ initialRetentionDays: null, nextRetentionDays: 7 }))+ ).toBe('days')+ })++ it('warns when a cap is newly added where none existed', () => {+ expect(getRetentionTightening(params({ initialMaxVersions: null, nextMaxVersions: 3 }))).toBe(+ 'versions'+ )+ })++ it('does not warn when both bounds stay unbounded', () => {+ expect(+ getRetentionTightening(+ params({+ initialRetentionDays: null,+ initialMaxVersions: null,+ nextRetentionDays: null,+ nextMaxVersions: null,+ })+ )+ ).toBe('none')+ })++ it('does not warn while the initial bounds are still loading', () => {+ expect(+ getRetentionTightening(+ params({ initialRetentionDays: undefined, initialMaxVersions: undefined })+ )+ ).toBe('none')+ })++ it('does not warn when versioning is being turned off', () => {+ // Suspending never expires what is already retained, so there is nothing to lose.+ expect(+ getRetentionTightening(params({ isVersioningEnabled: false, nextRetentionDays: 7 }))+ ).toBe('none')+ })++ it('does not warn when versioning is being enabled for the first time', () => {+ expect(+ getRetentionTightening(+ params({+ initialVersioningState: 'disabled',+ initialRetentionDays: null,+ initialMaxVersions: null,+ nextRetentionDays: 7,+ })+ )+ ).toBe('none')+ })++ it('does not warn when re-enabling a suspended bucket', () => {+ // A suspended bucket's stored bounds are cleared, so there is nothing to tighten from.+ expect(+ getRetentionTightening(params({ initialVersioningState: 'suspended', nextRetentionDays: 7 }))+ ).toBe('none')+ })++ it('has a description for every tightening kind it can report', () => {+ for (const kind of ['days', 'versions', 'both'] as const) {+ expect(RETENTION_TIGHTENING_DESCRIPTION[kind], kind).toBeTruthy()+ }+ })+})++describe('toNullableNumber', () => {+ it('maps the empty sentinel to null', () => {+ expect(toNullableNumber('')).toBeNull()+ })++ it('preserves zero rather than treating it as empty', () => {+ expect(toNullableNumber(0)).toBe(0)+ })++ it('passes numbers through', () => {+ expect(toNullableNumber(30)).toBe(30)+ })+})diff --git a/apps/studio/components/interfaces/Storage/BucketVersioningFields.utils.ts b/apps/studio/components/interfaces/Storage/BucketVersioningFields.utils.tsnew file mode 100644index 00000000000..90f579fadcc--- /dev/null+++ b/apps/studio/components/interfaces/Storage/BucketVersioningFields.utils.ts@@ -0,0 +1,51 @@+import type { BucketVersioningState } from './StorageVersioning.constants'++export type RetentionTightening = 'none' | 'days' | 'versions' | 'both'++interface GetRetentionTighteningParams {+ initialVersioningState: BucketVersioningState+ isVersioningEnabled: boolean+ initialRetentionDays: number | null | undefined+ initialMaxVersions: number | null | undefined+ nextRetentionDays: number | null+ nextMaxVersions: number | null+}++/**+ * `null` is an unbounded bound, so introducing one expires versions that were being+ * kept forever. `undefined` is the bound still loading, which says nothing either way.+ */+const isTightening = (initial: number | null | undefined, next: number | null) =>+ initial !== undefined && next !== null && (initial === null || next < initial)++/** Only an already-enabled bucket can lose data to a tightened policy. */+export const getRetentionTightening = ({+ initialVersioningState,+ isVersioningEnabled,+ initialRetentionDays,+ initialMaxVersions,+ nextRetentionDays,+ nextMaxVersions,+}: GetRetentionTighteningParams): RetentionTightening => {+ if (initialVersioningState !== 'enabled' || !isVersioningEnabled) return 'none'++ const isTighteningDays = isTightening(initialRetentionDays, nextRetentionDays)+ const isTighteningVersions = isTightening(initialMaxVersions, nextMaxVersions)++ if (isTighteningDays && isTighteningVersions) return 'both'+ if (isTighteningDays) return 'days'+ if (isTighteningVersions) return 'versions'+ return 'none'+}++export const RETENTION_TIGHTENING_DESCRIPTION: Record<+ Exclude<RetentionTightening, 'none'>,+ string+> = {+ both: 'Saving permanently deletes noncurrent versions past the retention window, and any beyond the per-object cap.',+ days: 'Saving permanently deletes noncurrent versions past the retention window.',+ versions: 'Saving permanently deletes noncurrent versions beyond the per-object cap.',+}++export const toNullableNumber = (value: '' | number): number | null =>+ typeof value === 'number' ? value : nulldiff --git a/apps/studio/components/interfaces/Storage/ExpirationModeToggle.tsx b/apps/studio/components/interfaces/Storage/ExpirationModeToggle.tsxnew file mode 100644index 00000000000..72a2123adfe--- /dev/null+++ b/apps/studio/components/interfaces/Storage/ExpirationModeToggle.tsx@@ -0,0 +1,35 @@+import { RadioGroupStacked, RadioGroupStackedItem } from 'ui'++import type { ExpirationMode } from './StorageVersioning.constants'++interface ExpirationModeToggleProps {+ mode: ExpirationMode+ onModeChange: (mode: ExpirationMode) => void+}++export const ExpirationModeToggle = ({ mode, onModeChange }: ExpirationModeToggleProps) => (+ <div className="mt-2 flex w-full flex-col gap-y-2">+ <label htmlFor="expiration_mode" className="text-sm text-foreground">+ Expire a noncurrent version when+ </label>+ <RadioGroupStacked+ id="expiration_mode"+ className="w-full"+ value={mode}+ onValueChange={(value: ExpirationMode) => {+ if (value) onModeChange(value)+ }}+ >+ <RadioGroupStackedItem+ value="and"+ label="Both conditions are met"+ description="It exceeds both the age limit and the retained-versions cap."+ />+ <RadioGroupStackedItem+ value="or"+ label="Either condition is met"+ description="It exceeds either the age limit or the retained-versions cap."+ />+ </RadioGroupStacked>+ </div>+)diff --git a/apps/studio/components/interfaces/Storage/LifecyclePolicySection.tsx b/apps/studio/components/interfaces/Storage/LifecyclePolicySection.tsxnew file mode 100644index 00000000000..cf6e4da5035--- /dev/null+++ b/apps/studio/components/interfaces/Storage/LifecyclePolicySection.tsx@@ -0,0 +1,191 @@+import { useParams } from 'common'+import { AnimatePresence } from 'framer-motion'+import { useEffect, useRef } from 'react'+import { useFormContext, type Control } from 'react-hook-form'+import {+ FormControl,+ FormField,+ FormInputGroupInput,+ InputGroup,+ InputGroupAddon,+ InputGroupText,+} from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'++import type { BucketVersioningFormValues } from './BucketVersioningFields.schema'+import { ExpirationModeToggle } from './ExpirationModeToggle'+import type { ExpirationMode } from './StorageVersioning.constants'+import { AlertError } from '@/components/ui/AlertError'+import { FormSectionCollapse } from '@/components/ui/FormSectionCollapse'++const toFieldValue = (rawInput: string): '' | number => {+ const digits = rawInput.replace(/[^0-9]/g, '')+ return digits === '' ? '' : Number(digits)+}++const SectionHeading = () => (+ <div className="flex flex-col gap-y-0.5">+ <p className="text-sm font-medium text-foreground">Lifecycle policy</p>+ <p className="text-sm text-foreground-lighter">Automatically expire noncurrent versions</p>+ </div>+)++interface LifecyclePolicySectionProps {+ control: Control<BucketVersioningFormValues>+ hasDays: boolean+ hasVersions: boolean+ mode: ExpirationMode+ onModeChange: (mode: ExpirationMode) => void+ /** The stored policy is still in flight, so there is nothing truthful to show yet. */+ isLoading?: boolean+ /** The stored policy holds rules these fields cannot represent, let alone round-trip. */+ isUnsupported?: boolean+ /** The stored policy could not be read, so the fields would be showing a guess. */+ error?: { message: string } | null+}++export const LifecyclePolicySection = ({+ control,+ hasDays,+ hasVersions,+ mode,+ onModeChange,+ isLoading = false,+ isUnsupported = false,+ error,+}: LifecyclePolicySectionProps) => {+ const { ref } = useParams()+ const { setValue } = useFormContext<BucketVersioningFormValues>()+ const hasNoPolicy = !hasDays && !hasVersions+ const hasBothConditions = hasDays && hasVersions++ // S3 requires a noncurrent-days condition on any noncurrent-count rule. Only on the+ // actual flip, not on mount, so a bucket opened with a stale cap doesn't silently lose it.+ const prevHasDaysRef = useRef(hasDays)+ useEffect(() => {+ const wasSet = prevHasDaysRef.current+ prevHasDaysRef.current = hasDays+ if (wasSet && !hasDays) setValue('max_noncurrent_versions', '', { shouldDirty: true })+ }, [hasDays, setValue])++ if (isLoading) {+ return (+ <div className="flex flex-col gap-y-2" aria-busy="true" aria-label="Loading lifecycle policy">+ <SectionHeading />+ <ShimmeringLoader className="h-9 py-0" />+ <ShimmeringLoader className="h-9 py-0" delayIndex={1} />+ </div>+ )+ }++ if (error) {+ return (+ <div className="flex flex-col gap-y-2">+ <SectionHeading />+ <AlertError+ error={error}+ subject="Failed to retrieve the lifecycle policy"+ projectRef={ref}+ />+ </div>+ )+ }++ if (isUnsupported) {+ return (+ <div className="flex flex-col gap-y-2">+ <SectionHeading />+ <Admonition+ type="default"+ title="Lifecycle policy set outside the dashboard"+ description="It uses rules the dashboard cannot show, so saving leaves the policy as it is. Manage it with the S3 or Storage API."+ />+ </div>+ )+ }++ return (+ <div className="flex flex-col gap-y-2">+ <SectionHeading />++ <FormField+ name="version_expiry_days"+ control={control}+ render={({ field }) => (+ <FormItemLayout label="Noncurrent version expiration" layout="flex-row-reverse">+ <FormControl>+ <InputGroup>+ <FormInputGroupInput+ name={field.name}+ ref={field.ref}+ onBlur={field.onBlur}+ type="number"+ inputMode="numeric"+ placeholder="—"+ value={field.value}+ onChange={(e) => field.onChange(toFieldValue(e.target.value))}+ />+ <InputGroupAddon align="inline-end">+ <InputGroupText>days</InputGroupText>+ </InputGroupAddon>+ </InputGroup>+ </FormControl>+ </FormItemLayout>+ )}+ />++ <FormField+ name="max_noncurrent_versions"+ control={control}+ render={({ field }) => (+ <FormItemLayout+ label="Retained noncurrent versions"+ description={hasDays ? undefined : 'Requires an expiration age to be set.'}+ layout="flex-row-reverse"+ className={hasDays ? undefined : 'opacity-60'}+ >+ <FormControl>+ <InputGroup>+ <FormInputGroupInput+ name={field.name}+ ref={field.ref}+ onBlur={field.onBlur}+ type="number"+ inputMode="numeric"+ placeholder="—"+ disabled={!hasDays}+ value={field.value}+ onChange={(e) => field.onChange(toFieldValue(e.target.value))}+ />+ <InputGroupAddon align="inline-end">+ <InputGroupText>versions</InputGroupText>+ </InputGroupAddon>+ </InputGroup>+ </FormControl>+ </FormItemLayout>+ )}+ />++ <AnimatePresence initial={false}>+ {hasBothConditions && (+ <FormSectionCollapse key="mode">+ <ExpirationModeToggle mode={mode} onModeChange={onModeChange} />+ </FormSectionCollapse>+ )}++ {hasNoPolicy && (+ <FormSectionCollapse key="no-policy">+ <Admonition+ type="warning"+ className="mt-2"+ title="No lifecycle policy"+ description="Lifecycle policies are recommended to manage and reduce storage costs for noncurrent versions."+ />+ </FormSectionCollapse>+ )}+ </AnimatePresence>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Storage/StorageVersioning.constants.ts b/apps/studio/components/interfaces/Storage/StorageVersioning.constants.tsnew file mode 100644index 00000000000..c9c998be1f3--- /dev/null+++ b/apps/studio/components/interfaces/Storage/StorageVersioning.constants.ts@@ -0,0 +1,26 @@+import type { Bucket } from '@/data/storage/buckets-query'++export type BucketVersioningState = 'enabled' | 'suspended' | 'disabled'+export type ExpirationMode = 'and' | 'or'++export const PROJECT_VERSIONING_DEFAULTS = {+ versionExpiryDays: 30,+ maxNoncurrentVersions: 10,+} as const++export const getBucketVersioningState = (bucket?: Bucket): BucketVersioningState => {+ switch (bucket?.versioning_status) {+ case 'ENABLED':+ return 'enabled'+ case 'SUSPENDED':+ return 'suspended'+ default:+ return 'disabled'+ }+}++export const isBucketVersioned = (bucket?: Bucket) => getBucketVersioningState(bucket) === 'enabled'++/** A suspended bucket can still be retaining versions. */+export const hasVersioningHistory = (bucket?: Bucket) =>+ getBucketVersioningState(bucket) !== 'disabled'diff --git a/apps/studio/components/ui/FormSectionCollapse.tsx b/apps/studio/components/ui/FormSectionCollapse.tsxnew file mode 100644index 00000000000..9bf0a6818cc--- /dev/null+++ b/apps/studio/components/ui/FormSectionCollapse.tsx@@ -0,0 +1,23 @@+import { motion } from 'framer-motion'+import type { ReactNode } from 'react'++/** Wrap the parent in `<AnimatePresence initial={false}>` to avoid animating on first paint. */+export const FormSectionCollapse = ({ children }: { children: ReactNode }) => (+ <motion.div+ initial="collapsed"+ animate="open"+ exit="collapsed"+ variants={{+ collapsed: { opacity: 0, height: 0, overflow: 'hidden' },+ open: {+ opacity: 1,+ height: 'auto',+ overflow: 'hidden',+ transitionEnd: { overflow: 'visible' },+ },+ }}+ transition={{ duration: 0.18, ease: [0.4, 0, 0.2, 1] }}+ >+ {children}+ </motion.div>+)diff --git a/apps/studio/data/config/project-storage-config-query.ts b/apps/studio/data/config/project-storage-config-query.tsindex 6feab9f74ff..95c10cff8cf 100644--- a/apps/studio/data/config/project-storage-config-query.ts+++ b/apps/studio/data/config/project-storage-config-query.ts@@ -60,9 +60,12 @@ export const useIsAnalyticsBucketsEnabled = ({ projectRef }: { projectRef?: stri}export const useIsVectorBucketsEnabled = ({ projectRef }: { projectRef?: string }) => {- const { data } = useProjectStorageConfigQuery({ projectRef })+ const { data: isVectorBucketsEnabledData } = useProjectStorageConfigQuery(+ { projectRef },+ { select: (data) => data?.features.vectorBuckets?.enabled }+ )const { isCli, isPlatform } = useDeploymentMode()- const isVectorBucketsEnabled = isCli || (isPlatform && !!data?.features.vectorBuckets?.enabled)+ const isVectorBucketsEnabled = isCli || (isPlatform && !!isVectorBucketsEnabledData)return isVectorBucketsEnabled}