Files
supabase/apps/studio/components/interfaces/App/FeaturePreview/FeaturePreviewContext.tsx
T
089133cc2c feat(storage): add bucket object versioning form fields (FE-4161) (#49203)
| # | Branch | Base |
| - | ------ | ---- |
| 1 | `feat/storage-versioning-private-alpha` — merged | `master` |
| 2 | `feat/storage-versioning/002-bucket-form-fields` ◀ | `master` |
| 3 | `feat/storage-versioning/003-bucket-modals` | 2 |
| 4 | `feat/storage-versioning/004-object-versions-data` | 3 |
| 5 | `feat/storage-versioning/005-file-preview-versions` | 4 |
| 6 | `feat/storage-versioning/006-billing-storage-retention` | 5 |
| 7 | `feat/storage-versioning/007-archived-objects-data` | 6 |
| 8 | `feat/storage-versioning/008-archived-rows` | 7 |
| 9 | `feat/storage-versioning/009-archived-preview-pane` | 8 |
| 10 | `feat/storage-versioning/010-replace-file` | 9 |

## [2/10] Storage object versioning: bucket form fields

The object versioning + lifecycle policy form section for the create and
edit bucket modals.
Mounted onto the ui in PR 3 #49205 

- `BucketVersioningFields` — the versioning switch and the suspension /
public-bucket / retention-tightening warnings
- `LifecyclePolicySection` — the retention window and version cap inputs
- `ExpirationModeToggle` — how the two conditions combine (and / or)
- `BucketVersioningFields.schema.ts` — zod fields the parent modals
spread into their own schema, plus `superRefineBucketVersioning`
- `BucketVersioningFields.utils.ts` — retention-tightening detection
- `StorageVersioning.constants.ts` — versioning state and expiration
mode types, the prefill defaults, and `getBucketVersioningState`

Note: a single s3 lifecycle policy expects both `version_expiry_days`
and `max_noncurrent_versions` and always evaluate the two fields within
the same policy with an AND logic. To enable both AND and OR/EITHER
logic, we save two distinct s3 policies so we can enforce the OR logic.

See demos and how to reproduce in #49205 

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

## Summary

* **New Features**
* Eligible projects with the preview enabled can configure object
versioning for storage buckets, including version expiration,
retained-version limits, and “and/or” lifecycle conditions.
* Settings default to 30 days and 10 retained versions, with validation
for retention values and requirements for setting a version limit.
* Notices highlight public buckets, missing lifecycle conditions,
suspending existing versioning, and changes that tighten retention
limits.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2026-10-06 14:24:50 +02:00

217 lines
7.2 KiB
TypeScript

import {
FeatureFlagContext,
LOCAL_STORAGE_KEYS,
safeLocalStorage,
useFlag,
useParams,
} from 'common'
import { noop } from 'lodash'
import { useQueryState } from 'nuqs'
import {
createContext,
useCallback,
useContext,
useEffect,
useEffectEvent,
useMemo,
useState,
type PropsWithChildren,
} 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'
type FeaturePreviewContextType = {
flags: { [key: string]: boolean }
isInitialized: boolean
onUpdateFlag: (key: string, value: boolean) => void
}
const FeaturePreviewContext = createContext<FeaturePreviewContextType>({
flags: EMPTY_OBJ,
isInitialized: false,
onUpdateFlag: noop,
})
export const useFeaturePreviewContext = () => useContext(FeaturePreviewContext)
export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren) => {
const { hasLoaded } = useContext(FeatureFlagContext)
const featurePreviews = useFeaturePreviews()
const [flags, setFlags] = useState(() =>
featurePreviews.reduce((a, b) => ({ ...a, [b.key]: false }), {})
)
// Tracks whether `flags` reflects the loaded feature flags (vs. the pre-load
// defaults). Only set true once `initializeFlags` runs with `hasLoaded`.
const [isInitialized, setIsInitialized] = useState(false)
const initializeFlags = useEffectEvent(() => {
setFlags(
featurePreviews.reduce((a, b) => {
// Platform-only previews can never be enabled outside the hosted platform
if (!IS_PLATFORM && b.isPlatformOnly) {
return { ...a, [b.key]: false }
}
// A forced preview has become the default behavior, so it's on whatever
// the user stored previously — including an explicit opt-out. Applied
// here rather than in the individual `useIsXEnabled` helpers so that the
// feature preview modal reflects it too.
if (b.isForced) {
return { ...a, [b.key]: true }
}
const defaultOptIn = b.isDefaultOptIn
const localStorageValue = safeLocalStorage.getItem(b.key)
return {
...a,
[b.key]: !localStorageValue ? defaultOptIn : localStorageValue === 'true',
}
}, {})
)
})
useEffect(() => {
if (typeof window !== 'undefined') {
initializeFlags()
// Defer marking initialized until the underlying flags have loaded, so
// flag-derived defaults (e.g. default opt-in) are reflected in `flags`.
if (hasLoaded) setIsInitialized(true)
}
}, [hasLoaded])
const value = {
flags,
isInitialized,
onUpdateFlag: (key: string, value: boolean) => {
safeLocalStorage.setItem(key, value ? 'true' : 'false')
setFlags((prevFlags) => ({ ...prevFlags, [key]: value }))
},
}
return <FeaturePreviewContext.Provider value={value}>{children}</FeaturePreviewContext.Provider>
}
// Helpers
export const useIsColumnLevelPrivilegesEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]
}
export const useUnifiedLogsPreview = () => {
const { flags, isInitialized, onUpdateFlag } = useFeaturePreviewContext()
const isLoading = !isInitialized
const isEnabled = IS_PLATFORM && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS]
const hasToggledPreview = !!safeLocalStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS)
const isDefaultOptIn = IS_PLATFORM && !hasToggledPreview
const enable = () => onUpdateFlag(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, true)
const disable = () => onUpdateFlag(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, false)
return { isEnabled, isLoading, isDefaultOptIn, enable, disable }
}
export const useIsPgDeltaDiffEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_PG_DELTA_DIFF]
}
export const useIsAdvisorRulesEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_ADVISOR_RULES]
}
export const useIsPlatformWebhooksEnabled = () => {
const { flags } = useFeaturePreviewContext()
const platformWebhooksEnabled = useFlag('platformWebhooks')
return platformWebhooksEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS]
}
export const useIsJitDbAccessEnabled = () => {
const { flags } = useFeaturePreviewContext()
const jitDbAccessEnabled = useFlag('jitDbAccess')
return jitDbAccessEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS]
}
/**
* Whether the SQL Editor saves snippets only on request. True when the user
* opted into the preview themselves *or* the `sqlEditorManualSaveForced` rollout
* has reached them — the preview's `isForced` flag folds the latter into `flags`.
*/
export const useIsSqlEditorManualSaveEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_MANUAL_SAVE]
}
export const useIsMarketplaceEnabled = () => {
const { flags } = useFeaturePreviewContext()
const isMarketplaceEnabled = useFlag('marketplaceIntegrations')
return isMarketplaceEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_MARKETPLACE]
}
export const useIsExplorerEnabled = () => {
const { flags } = useFeaturePreviewContext()
const isExplorerEnabled = useFlag('explorer')
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')
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 = () => {
const featurePreviews = useFeaturePreviews()
const [featurePreviewModal, setFeaturePreviewModal] = useQueryState('featurePreviewModal')
const selectedFeatureKeyFromQuery = featurePreviewModal?.trim() ?? null
const showFeaturePreviewModal = selectedFeatureKeyFromQuery !== null
const selectedFeatureKey = (
!selectedFeatureKeyFromQuery ? featurePreviews[0].key : selectedFeatureKeyFromQuery
) as (typeof featurePreviews)[number]['key']
const selectFeaturePreview = useCallback(
(featureKey: (typeof featurePreviews)[number]['key']) => {
setFeaturePreviewModal(featureKey)
},
[setFeaturePreviewModal]
)
const toggleFeaturePreviewModal = useCallback(
(value: boolean) => {
if (!value) {
setFeaturePreviewModal(null)
} else {
selectFeaturePreview(selectedFeatureKey)
}
},
[selectFeaturePreview, setFeaturePreviewModal, selectedFeatureKey]
)
return useMemo(
() => ({
showFeaturePreviewModal,
selectedFeatureKey,
selectFeaturePreview,
toggleFeaturePreviewModal,
}),
[showFeaturePreviewModal, selectedFeatureKey, selectFeaturePreview, toggleFeaturePreviewModal]
)
}