The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Add high availability project creation controls (#48375)
Saxon Fletcherd2a3162bf15d
diff --git a/apps/studio/components/interfaces/Project/ResumeProjectButton.tsx b/apps/studio/components/interfaces/Project/ResumeProjectButton.tsxindex 0b78c9f0378..5053016ed39 100644--- a/apps/studio/components/interfaces/Project/ResumeProjectButton.tsx+++ b/apps/studio/components/interfaces/Project/ResumeProjectButton.tsx@@ -2,7 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useFlag, useParams } from 'common'import { useRouter } from 'next/router'-import { useMemo, useState, type ComponentPropsWithoutRef } from 'react'+import { useMemo, useRef, useState, type ComponentPropsWithoutRef } from 'react'import { useForm } from 'react-hook-form'import { AWS_REGIONS, CloudProvider } from 'shared-data'import { toast } from 'sonner'@@ -99,6 +99,7 @@ export const ResumeProjectButton = ({mode: 'onChange',defaultValues: { postgresVersionSelection: '' },})+ const lastValidPostgresVersionSelection = useRef('')const onSelectRestore = () => {if (project?.status !== PROJECT_STATUS.INACTIVE) {@@ -209,6 +210,7 @@ export const ResumeProjectButton = ({dbRegion={region?.displayName ?? ''}cloudProvider={(project?.cloud_provider ?? 'AWS') as CloudProvider}organizationSlug={selectedOrganization?.slug}+ lastValidSelectionRef={lastValidPostgresVersionSelection}/>)}/>diff --git a/apps/studio/components/interfaces/ProjectCreation/HighAvailabilityInput.tsx b/apps/studio/components/interfaces/ProjectCreation/HighAvailabilityInput.tsxindex fce289df274..93b8e7ad0f8 100644--- a/apps/studio/components/interfaces/ProjectCreation/HighAvailabilityInput.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/HighAvailabilityInput.tsx@@ -1,5 +1,7 @@+import { useEffect, useRef } from 'react'import { UseFormReturn } from 'react-hook-form'-import { FormControl, FormField, Switch } from 'ui'+import { type CloudProvider } from 'shared-data'+import { Badge, FormControl, FormField, Switch, useWatch } from 'ui'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { CreateProjectForm } from './ProjectCreation.schema'@@ -8,10 +10,86 @@ import { useCheckEntitlements } from '@/hooks/misc/useCheckEntitlements'interface HighAvailabilityInputProps {form: UseFormReturn<CreateProjectForm>+ // Derived from an org-wide regions query owned by the parent form, since fetching it+ // here would mean duplicating that query's slug/cloud-provider/instance-size context.+ highAvailabilityRegionName: string | undefined}-export const HighAvailabilityInput = ({ form }: HighAvailabilityInputProps) => {+export const HighAvailabilityInput = ({+ form,+ highAvailabilityRegionName,+}: HighAvailabilityInputProps) => {+ const { getValues, setValue } = formconst { hasAccess } = useCheckEntitlements('instances.high_availability')+ const highAvailability = useWatch({ control: form.control, name: 'highAvailability' })++ // Fields to revert to when toggling off HA, so previously selected values aren't lost.+ const beforeHighAvailability = useRef<{+ cloudProvider: CloudProvider | undefined+ postgresVersionSelection: string | undefined+ dbRegion: string | null+ }>({+ cloudProvider: undefined,+ postgresVersionSelection: undefined,+ dbRegion: null,+ })++ const handleHighAvailabilityChange = (checked: boolean) => {+ if (checked) {+ const currentCloudProvider = getValues('cloudProvider') as CloudProvider+ if (currentCloudProvider !== 'AWS_K8S') {+ beforeHighAvailability.current.cloudProvider = currentCloudProvider+ setValue('cloudProvider', 'AWS_K8S')+ }++ beforeHighAvailability.current.postgresVersionSelection = getValues(+ 'postgresVersionSelection'+ )+ setValue('useOrioleDb', false)++ const currentRegion = getValues('dbRegion')+ if (+ highAvailabilityRegionName !== undefined &&+ currentRegion !== highAvailabilityRegionName+ ) {+ beforeHighAvailability.current.dbRegion = currentRegion ?? null+ setValue('dbRegion', highAvailabilityRegionName)+ }+ } else {+ if (beforeHighAvailability.current.cloudProvider !== undefined) {+ setValue('cloudProvider', beforeHighAvailability.current.cloudProvider)+ beforeHighAvailability.current.cloudProvider = undefined+ }++ if (beforeHighAvailability.current.postgresVersionSelection !== undefined) {+ setValue(+ 'postgresVersionSelection',+ beforeHighAvailability.current.postgresVersionSelection+ )+ beforeHighAvailability.current.postgresVersionSelection = undefined+ }++ if (beforeHighAvailability.current.dbRegion !== null) {+ setValue('dbRegion', beforeHighAvailability.current.dbRegion)+ beforeHighAvailability.current.dbRegion = null+ }+ }+ }++ // Catches the case where highAvailabilityRegionName wasn't loaded yet at the moment the+ // toggle fired above (the org's available-regions query for AWS_K8S may still be in+ // flight). The region auto-fill effect in the parent form skips dirty fields, so a+ // manually chosen region would otherwise keep showing in the trigger — force it over+ // explicitly once the HA region becomes known.+ useEffect(() => {+ if (!highAvailability || highAvailabilityRegionName === undefined) return+ const currentRegion = getValues('dbRegion')+ if (currentRegion === highAvailabilityRegionName) return+ if (beforeHighAvailability.current.dbRegion === null) {+ beforeHighAvailability.current.dbRegion = currentRegion ?? null+ }+ setValue('dbRegion', highAvailabilityRegionName)+ }, [highAvailability, highAvailabilityRegionName, getValues, setValue])if (!hasAccess) return null@@ -22,12 +100,24 @@ export const HighAvailabilityInput = ({ form }: HighAvailabilityInputProps) => {name="highAvailability"render={({ field }) => (<FormItemLayout- label="High availability"- description="Horizontally scalable Postgres for highly available, globally distributed deployments while staying true to standard Postgres."+ label={+ <div className="flex items-center gap-x-2">+ <span>High availability</span>+ <Badge variant="warning">Alpha</Badge>+ </div>+ }+ description="Horizontally scalable Postgres for highly available deployments. Free during Alpha for up to 2 projects."layout="horizontal"><FormControl>- <Switch checked={field.value} onCheckedChange={field.onChange} />+ <Switch+ aria-label="Enable high availability"+ checked={field.value}+ onCheckedChange={(checked) => {+ handleHighAvailabilityChange(checked)+ field.onChange(checked)+ }}+ /></FormControl></FormItemLayout>)}diff --git a/apps/studio/components/interfaces/ProjectCreation/InternalOnlyConfiguration.tsx b/apps/studio/components/interfaces/ProjectCreation/InternalOnlyConfiguration.tsxindex e1c62c30d4d..3779c2912f7 100644--- a/apps/studio/components/interfaces/ProjectCreation/InternalOnlyConfiguration.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/InternalOnlyConfiguration.tsx@@ -1,7 +1,8 @@import { useParams } from 'common'+import { useRef } from 'react'import { UseFormReturn } from 'react-hook-form'import { type CloudProvider } from 'shared-data'-import { FormControl, FormField, Input } from 'ui'+import { FormControl, FormField, Input, useWatch } from 'ui'import { CollapsibleCardSection } from 'ui-patterns/CollapsibleCardSection'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'@@ -17,6 +18,10 @@ interface InternalOnlyConfigurationProps {export const InternalOnlyConfiguration = ({ form }: InternalOnlyConfigurationProps) => {const { slug } = useParams()const showNonProdFields = process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod'+ const highAvailability = useWatch({ control: form.control, name: 'highAvailability' })+ // Held here (outside the collapsible content) so the selector's last valid+ // selection survives the section being collapsed and reopened.+ const lastValidPostgresVersionSelection = useRef('')return (<Panel.Content>@@ -36,6 +41,8 @@ export const InternalOnlyConfiguration = ({ form }: InternalOnlyConfigurationProcloudProvider={form.getValues('cloudProvider') as CloudProvider}organizationSlug={slug}dbRegion={form.getValues('dbRegion')}+ disabled={highAvailability}+ lastValidSelectionRef={lastValidPostgresVersionSelection}/>)}/>@@ -49,21 +56,23 @@ export const InternalOnlyConfiguration = ({ form }: InternalOnlyConfigurationPro<div className="flex flex-col gap-y-4"><CloudProviderSelector form={form} />- <FormField- control={form.control}- name="postgresVersion"- render={({ field }) => (- <FormItemLayout- label="Custom Postgres version"- layout="horizontal"- description="Specify a custom version of Postgres (defaults to the latest)."- >- <FormControl>- <Input placeholder="e.g 17.6.1.104" {...field} autoComplete="off" />- </FormControl>- </FormItemLayout>- )}- />+ {!highAvailability && (+ <FormField+ control={form.control}+ name="postgresVersion"+ render={({ field }) => (+ <FormItemLayout+ label="Custom Postgres version"+ layout="horizontal"+ description="Specify a custom version of Postgres (defaults to the latest)."+ >+ <FormControl>+ <Input placeholder="e.g 17.6.1.104" {...field} autoComplete="off" />+ </FormControl>+ </FormItemLayout>+ )}+ />+ )}<FormFieldcontrol={form.control}diff --git a/apps/studio/components/interfaces/ProjectCreation/PostgresVersionSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/PostgresVersionSelector.tsxindex 1eae5e0d9ff..982dbbeaec0 100644--- a/apps/studio/components/interfaces/ProjectCreation/PostgresVersionSelector.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/PostgresVersionSelector.tsx@@ -26,9 +26,16 @@ interface PostgresVersionDetails {interface PostgresVersionSelectorProps {cloudProvider: CloudProviderdbRegion: string+ disabled?: booleanorganizationSlug?: stringfield: ControllerRenderProps<any, 'postgresVersionSelection'>form: UseFormReturn<any>+ /**+ * Owned by the form owner (not this component) so the last valid selection+ * survives this selector unmounting, e.g. when its collapsible section+ * closes. Create it with useRef('') alongside the form.+ */+ lastValidSelectionRef: { current: string }type?: 'create' | 'unpause'layout?: 'vertical' | 'horizontal'label?: string@@ -56,9 +63,11 @@ export const extractPostgresVersionDetails = (value: string): PostgresVersionDetexport const PostgresVersionSelector = ({cloudProvider,dbRegion,+ disabled = false,organizationSlug,field,form,+ lastValidSelectionRef,type = 'create',layout = 'horizontal',label = 'Postgres version',@@ -96,13 +105,32 @@ export const PostgresVersionSelector = ({name: 'postgresVersionSelection',})+ // react-hook-form intermittently drops this field's value when its Controller+ // remounts, so a one-shot "set the default once versions load" effect leaves+ // the select stuck empty. Instead this effect re-asserts off the watched value:+ // a selection present in the current list is kept (and remembered in the+ // owner-held lastValidSelectionRef), and when the value is missing or cleared+ // out from under us it restores the last valid selection, falling back to the+ // GA default.useEffect(() => {- if (availableVersions.length > 0) {- const gaVersion = availableVersions.find((x) => x.release_channel === 'ga')- const defaultValue = gaVersion ? formatValue(gaVersion) : formatValue(availableVersions[0])- form.setValue('postgresVersionSelection', defaultValue)+ if (availableVersions.length === 0) return+ const isSelectionAvailable = (selection: string) =>+ availableVersions.some((version) => formatValue(version) === selection)++ if (postgresVersionSelection && isSelectionAvailable(postgresVersionSelection)) {+ lastValidSelectionRef.current = postgresVersionSelection+ return+ }++ if (isSelectionAvailable(lastValidSelectionRef.current)) {+ form.setValue('postgresVersionSelection', lastValidSelectionRef.current)+ return}- }, [isSuccess, availableVersions, form])++ const gaVersion = availableVersions.find((x) => x.release_channel === 'ga')+ const defaultValue = gaVersion ? formatValue(gaVersion) : formatValue(availableVersions[0])+ form.setValue('postgresVersionSelection', defaultValue)+ }, [isSuccess, availableVersions, postgresVersionSelection, lastValidSelectionRef, form])return (<FormItemLayout id={field.name} label={label} layout={layout}>@@ -110,6 +138,7 @@ export const PostgresVersionSelector = ({value={postgresVersionSelection}onValueChange={field.onChange}disabled={+ disabled ||availableVersions.length === 0 ||(type === 'create' && isLoadingProjectCreateVersions) ||(type === 'unpause' && isLoadingProjectUnpauseVersions)diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.tsindex 2cdb36b8c86..fb6dcd1d258 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.constants.ts@@ -1,4 +1,11 @@-import { DesiredInstanceSize } from '@/data/projects/new-project.constants'+import type {+ DesiredInstanceSize,+ PostgresEngine,+ ReleaseChannel,+} from '@/data/projects/new-project.constants'++export const HIGH_AVAILABILITY_POSTGRES_ENGINE = '17' satisfies PostgresEngine+export const HIGH_AVAILABILITY_RELEASE_CHANNEL = 'ga' satisfies ReleaseChannel// [Joshen] Obtained from https://gist.github.com/tadast/8827699export const COUNTRY_LAT_LON = {diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.tsnew file mode 100644index 00000000000..cb820643b13--- /dev/null+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest'++import {+ HIGH_AVAILABILITY_POSTGRES_ENGINE,+ HIGH_AVAILABILITY_RELEASE_CHANNEL,+} from './ProjectCreation.constants'+import {+ filterHighAvailabilityRegions,+ getHighAvailabilityRegionCode,+} from './ProjectCreation.utils'++describe('High Availability project creation constraints', () => {+ it('pins the Alpha Postgres engine and release channel', () => {+ expect(HIGH_AVAILABILITY_POSTGRES_ENGINE).toBe('17')+ expect(HIGH_AVAILABILITY_RELEASE_CHANNEL).toBe('ga')+ })++ it.each([+ ['local', 'eu-central-1'],+ ['staging', 'us-east-1'],+ ['prod', undefined],+ ])('resolves the %s region restriction', (environment, expectedRegion) => {+ expect(getHighAvailabilityRegionCode(environment)).toBe(expectedRegion)+ })++ it.each([+ ['local', 'eu-central-1'],+ ['staging', 'us-east-1'],+ ['prod', undefined],+ ])('limits %s projects to the required region', (environment, expectedRegion) => {+ const regions = [{ code: 'us-east-1' }, { code: 'eu-central-1' }]++ expect(filterHighAvailabilityRegions(regions, true, environment)).toEqual(+ expectedRegion === undefined ? regions : [{ code: expectedRegion }]+ )+ expect(filterHighAvailabilityRegions(regions, false, environment)).toEqual(regions)+ })+})diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.tsindex 3b399505d9e..c77d48d680b 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts@@ -45,3 +45,22 @@ export const monthlyInstancePrice = (instance: string | undefined): number => {export const instanceLabel = (instance: string | undefined): string => {return instanceSizeSpecs[instance as DesiredInstanceSize]?.label || 'Micro'}++export const getHighAvailabilityRegionCode = (+ environment = process.env.NEXT_PUBLIC_ENVIRONMENT+) => {+ if (environment === 'local') return 'eu-central-1'+ if (environment === 'staging') return 'us-east-1'+ return undefined+}++export const filterHighAvailabilityRegions = <T extends { code: string }>(+ regions: T[],+ highAvailability: boolean,+ environment = process.env.NEXT_PUBLIC_ENVIRONMENT+) => {+ const regionCode = getHighAvailabilityRegionCode(environment)+ return highAvailability && regionCode !== undefined+ ? regions.filter((region) => region.code === regionCode)+ : regions+}diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsxindex 897ba9b4c8e..4aee33481c3 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx@@ -23,9 +23,14 @@ import { HighAvailabilityInput } from './HighAvailabilityInput'import { InternalOnlyConfiguration } from './InternalOnlyConfiguration'import { OrganizationSelector } from './OrganizationSelector'import { extractPostgresVersionDetails } from './PostgresVersionSelector'-import { sizes } from './ProjectCreation.constants'+import {+ HIGH_AVAILABILITY_POSTGRES_ENGINE,+ HIGH_AVAILABILITY_RELEASE_CHANNEL,+ sizes,+} from './ProjectCreation.constants'import { FormSchema } from './ProjectCreation.schema'import {+ getHighAvailabilityRegionCode,instanceLabel,monthlyInstancePrice,smartRegionToExactRegion,@@ -185,6 +190,7 @@ export const ProjectCreationForm = ({const { dirtyFields } = useFormState(form)const isDbRegionDirty = dirtyFields.dbRegionconst smartRegionEnabled = cloudProvider !== 'AWS_NIMBUS'+ const highAvailabilityRegionCode = getHighAvailabilityRegionCode()// Read dirty state during render rather than depending on form.formState in the// effect — form.formState is a Proxy that gets a new reference every render, which@@ -265,15 +271,24 @@ export const ProjectCreationForm = ({})+ const highAvailabilityRegion =+ highAvailability && highAvailabilityRegionCode !== undefined+ ? availableRegionsData?.all.specific.find(+ (region) => region.code === highAvailabilityRegionCode+ )+ : undefinedconst recommendedSmartRegion = smartRegionEnabled? availableRegionsData?.recommendations.smartGroup.name: ''const fixedDefaultRegion = PROVIDERS[selectedCloudProvider].default_region.displayNameconst regionError = smartRegionEnabled ? availableRegionsError : defaultRegionError- const defaultRegion = smartRegionEnabled- ? availableRegionsData?.recommendations.smartGroup.name- : (autoDefaultRegion ?? fixedDefaultRegion)+ const defaultRegion =+ highAvailability && highAvailabilityRegionCode !== undefined+ ? highAvailabilityRegion?.name+ : smartRegionEnabled+ ? recommendedSmartRegion+ : (autoDefaultRegion ?? fixedDefaultRegion)const canCreateProject = isAdmin && !freePlanWithExceedingLimits && !hasOutstandingInvoicesconst canConfigureGitHubOnCreate =@@ -381,7 +396,11 @@ export const ProjectCreationForm = ({shouldRunMigrations,} = values- if (postgresVersion && !postgresVersion.match(/1[2-9]\..*/)) {+ // HA projects never take a custom version — the API resolves the image from+ // postgresEngine + releaseChannel.+ const customPostgresVersion = highAvailability ? undefined : postgresVersion++ if (customPostgresVersion && !customPostgresVersion.match(/1[2-9]\..*/)) {return toast.error(`Invalid Postgres version, should start with a number between 12-19, a dot and additional characters, i.e. 15.2 or 15.2.0-3`)@@ -402,9 +421,19 @@ export const ProjectCreationForm = ({extractPostgresVersionDetails(postgresVersionSelection)const { smartGroup = [], specific = [] } = availableRegionsData?.all ?? {}- const selectedRegion = smartRegionEnabled- ? (smartGroup.find((x) => x.name === dbRegion) ?? specific.find((x) => x.name === dbRegion))- : undefined+ const selectedRegion =+ highAvailability && highAvailabilityRegionCode !== undefined+ ? specific.find((region) => region.code === highAvailabilityRegionCode)+ : smartRegionEnabled+ ? (smartGroup.find((x) => x.name === dbRegion) ??+ specific.find((x) => x.name === dbRegion))+ : undefined++ if (highAvailability && highAvailabilityRegionCode !== undefined && !selectedRegion) {+ return toast.error(+ `High Availability projects are not available in the required region (${highAvailabilityRegionCode})`+ )+ }const parsedGitHubRepositoryId =githubRepositoryId.length > 0 ? Number(githubRepositoryId) : undefinedconst shouldIncludeGitHubFields =@@ -449,8 +478,16 @@ export const ProjectCreationForm = ({dataApiExposedSchemas: !dataApi ? [] : undefined,dataApiUseApiSchema: false,dataApiRevokeDefaultPrivileges: dataApi && !dataApiDefaultPrivileges,- postgresEngine: useOrioleDb ? availableOrioleVersion?.postgres_engine : postgresEngine,- releaseChannel: useOrioleDb ? availableOrioleVersion?.release_channel : releaseChannel,+ postgresEngine: highAvailability+ ? HIGH_AVAILABILITY_POSTGRES_ENGINE+ : useOrioleDb+ ? availableOrioleVersion?.postgres_engine+ : postgresEngine,+ releaseChannel: highAvailability+ ? HIGH_AVAILABILITY_RELEASE_CHANNEL+ : useOrioleDb+ ? availableOrioleVersion?.release_channel+ : releaseChannel,...(smartRegionEnabled ? { regionSelection: selectedRegion } : { dbRegion }),...(shouldIncludeGitHubFields? {@@ -460,11 +497,11 @@ export const ProjectCreationForm = ({: {}),}- if (postgresVersion || instanceType) {+ if (customPostgresVersion || instanceType) {data['customSupabaseRequest'] = {ami: {- ...(postgresVersion && {- search_tags: { 'tag:postgresVersion': postgresVersion },+ ...(customPostgresVersion && {+ search_tags: { 'tag:postgresVersion': customPostgresVersion },}),...(instanceType && { instance_type: instanceType }),},@@ -510,24 +547,12 @@ export const ProjectCreationForm = ({}}, [defaultRegion, isDbRegionDirty, setValue])- useEffect(() => {- if (!isDbRegionDirty && recommendedSmartRegion) {- setValue('dbRegion', recommendedSmartRegion)- }- }, [recommendedSmartRegion, isDbRegionDirty, setValue])-useEffect(() => {if (regionError && fixedDefaultRegion) {resetField('dbRegion', { defaultValue: fixedDefaultRegion })}}, [regionError, resetField, fixedDefaultRegion])- useEffect(() => {- if (highAvailability && cloudProvider !== 'AWS_K8S') {- setValue('cloudProvider', 'AWS_K8S')- }- }, [highAvailability, cloudProvider, setValue])-useEffect(() => {if (watchedInstanceSize !== instanceSize) {setValue('instanceSize', instanceSize, {@@ -657,9 +682,12 @@ export const ProjectCreationForm = ({)}<ProjectNameInput form={form} />- {canChooseInstanceSize && <ComputeSizeSelector form={form} />}+ <HighAvailabilityInput+ form={form}+ highAvailabilityRegionName={highAvailabilityRegion?.name}+ />- <HighAvailabilityInput form={form} />+ {canChooseInstanceSize && <ComputeSizeSelector form={form} />}<DatabasePasswordInput form={form} />@@ -674,9 +702,9 @@ export const ProjectCreationForm = ({{showInternalOnlyConfiguration && <InternalOnlyConfiguration form={form} />}- {showAdvancedConfig && !!availableOrioleVersion && (- <AdvancedConfiguration form={form} />- )}+ {showAdvancedConfig &&+ !!availableOrioleVersion &&+ highAvailability !== true && <AdvancedConfiguration form={form} />}{shouldShowFreeProjectInfo ? (<Admonitiondiff --git a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsxindex 9352468a928..42119e81ffa 100644--- a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx@@ -1,4 +1,6 @@import { useFeatureFlags, useParams } from 'common'+import { Loader2 } from 'lucide-react'+import { useEffect, useRef } from 'react'import { UseFormReturn } from 'react-hook-form'import type { CloudProvider } from 'shared-data'import {@@ -17,12 +19,17 @@ import {Tooltip,TooltipContent,TooltipTrigger,+ useWatch,} from 'ui'import { Admonition } from 'ui-patterns/Admonition'import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'import { CreateProjectForm } from './ProjectCreation.schema'-import { getAvailableRegions } from './ProjectCreation.utils'+import {+ filterHighAvailabilityRegions,+ getAvailableRegions,+ getHighAvailabilityRegionCode,+} from './ProjectCreation.utils'import { AlertError } from '@/components/ui/AlertError'import { InlineLink } from '@/components/ui/InlineLink'import Panel from '@/components/ui/Panel'@@ -69,6 +76,9 @@ export const RegionSelector = ({}: RegionSelectorProps) => {const { slug } = useParams()const cloudProvider = form.getValues('cloudProvider') as CloudProvider+ const highAvailability = useWatch({ control: form.control, name: 'highAvailability' })+ const dbRegion = useWatch({ control: form.control, name: 'dbRegion' })+ const highAvailabilityRegionCode = getHighAvailabilityRegionCode()const { hasLoaded: flagsLoaded } = useFeatureFlags()const smartRegionEnabled = cloudProvider !== 'AWS_NIMBUS'@@ -91,8 +101,11 @@ export const RegionSelector = ({{ enabled: smartRegionEnabled, staleTime: 1000 * 60 * 5 } // 5 minutes)- const smartRegions = availableRegionsData?.all.smartGroup ?? []+ const allSmartRegions = availableRegionsData?.all.smartGroup ?? []const allRegions = availableRegionsData?.all.specific ?? []+ const restrictHighAvailabilityRegion =+ highAvailability && highAvailabilityRegionCode !== undefined+ const smartRegions = highAvailability ? [] : allSmartRegionsconst recommendedSmartRegions = new Set([availableRegionsData?.recommendations.smartGroup.code].filter(Boolean)@@ -111,7 +124,11 @@ export const RegionSelector = ({}})- const regionOptions = smartRegionEnabled ? allRegions : regionsArray+ const unfilteredRegionOptions = smartRegionEnabled ? allRegions : regionsArray+ const regionOptions = filterHighAvailabilityRegions(+ [...unfilteredRegionOptions],+ highAvailability+ )const isLoading = smartRegionEnabled ? isLoadingAvailableRegions : isLoadingDefaultRegionconst showNonProdFields =@@ -120,6 +137,32 @@ export const RegionSelector = ({const allSelectableRegions = [...smartRegions, ...regionOptions]+ // react-hook-form intermittently drops this field's value when its Controller+ // remounts (e.g. a sibling section mounting/unmounting in the same update, such as+ // toggling high availability), so a one-shot effect isn't enough. Instead this effect+ // re-asserts off the watched value: a region present in the current list is kept (and+ // remembered in lastValidRegionRef), and when it's missing or cleared out from under us+ // it restores the last valid region. allSelectableRegions is intentionally omitted from+ // deps — it's a new array every render, and comparing it by reference would defeat the+ // point of reacting to genuine content changes on every render where they occur.+ const lastValidRegionRef = useRef<string | undefined>(undefined)+ useEffect(() => {+ if (allSelectableRegions.length === 0) return+ const isRegionAvailable = (name: string | undefined) =>+ !!name && allSelectableRegions.some((region) => region.name === name)++ if (isRegionAvailable(dbRegion)) {+ lastValidRegionRef.current = dbRegion+ return+ }++ const lastValidRegion = lastValidRegionRef.current+ if (lastValidRegion !== undefined && isRegionAvailable(lastValidRegion)) {+ form.setValue('dbRegion', lastValidRegion)+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [dbRegion, form])+if (isErrorAvailableRegions) {return <AlertError subject="Error loading available regions" error={errorAvailableRegions} />}@@ -131,9 +174,16 @@ export const RegionSelector = ({name="dbRegion"render={({ field }) => {const selectedRegion = allSelectableRegions.find((region) => {- return !!region.name && region.name === field.value+ return !!region.name && region.name === dbRegion})+ const selectedRegionLabel = selectedRegion?.name+ ? getDisplayNameForSmartRegion(selectedRegion.name)+ : dbRegion+ const triggerLabel = isLoadingAvailableRegions+ ? 'Loading available regions...'+ : selectedRegionLabel+const affectingIncidents = incidents.filter((incident) => {const affectedRegions = incident.cache?.affected_regions ?? []if (affectedRegions.length === 0 || selectedRegion?.code === undefined) return false@@ -156,21 +206,28 @@ export const RegionSelector = ({description={<><p>Select the region closest to your users for the best performance.</p>- {showNonProdFields && (+ {restrictHighAvailabilityRegion ? (<div className="mt-2 text-warning">- <p>Only these regions are supported for local/staging projects:</p>- <ul className="list-disc list-inside mt-1">- <li>East US (North Virginia)</li>- <li>Central EU (Frankfurt)</li>- <li>Southeast Asia (Singapore)</li>- </ul>+ High Availability projects are currently limited to{' '}+ {regionOptions[0]?.name ?? highAvailabilityRegionCode}.</div>+ ) : (+ showNonProdFields && (+ <div className="mt-2 text-warning">+ <p>Only these regions are supported for local/staging projects:</p>+ <ul className="list-disc list-inside mt-1">+ <li>East US (North Virginia)</li>+ <li>Central EU (Frankfurt)</li>+ <li>Southeast Asia (Singapore)</li>+ </ul>+ </div>+ ))}</>}><FormControl>- <Select value={field.value} onValueChange={field.onChange} disabled={isLoading}>+ <Select value={dbRegion} onValueChange={field.onChange} disabled={isLoading}><SelectTriggerid="region"className="[&>:nth-child(1)]:w-full [&>:nth-child(1)]:flex [&>:nth-child(1)]:items-start"@@ -182,8 +239,11 @@ export const RegionSelector = ({: 'Select a region for your project..'}>- {field.value !== undefined && (+ {dbRegion !== undefined && (<div className="flex items-center gap-x-3">+ {isLoadingAvailableRegions && (+ <Loader2 size={14} className="animate-spin" />+ )}{selectedRegion?.code && (// For some reason, Safari considered the empty string alt text on this icon as misspelled (with VoiceOver)// Only way to fix it is to set the role. Not needed for the combobox options@@ -194,17 +254,13 @@ export const RegionSelector = ({src={`${BASE_PATH}/img/regions/${selectedRegion.code}.svg`}/>)}- <span className="text-foreground">- {selectedRegion?.name- ? getDisplayNameForSmartRegion(selectedRegion.name)- : field.value}- </span>+ <span className="text-foreground">{triggerLabel}</span></div>)}</SelectValue></SelectTrigger><SelectContent>- {smartRegionEnabled && (+ {smartRegionEnabled && !highAvailability && (<><SelectGroup><SelectLabel>General regions</SelectLabel>@@ -244,7 +300,9 @@ export const RegionSelector = ({)}<SelectGroup>- <SelectLabel>Specific regions</SelectLabel>+ <SelectLabel>+ {highAvailability ? 'High Availability Regions' : 'Specific regions'}+ </SelectLabel>{regionOptions.map((value) => {return (<SelectItemdiff --git a/apps/studio/tests/pages/new/[slug].test.tsx b/apps/studio/tests/pages/new/[slug].test.tsxindex 7579b282bb2..652b1f59c87 100644--- a/apps/studio/tests/pages/new/[slug].test.tsx+++ b/apps/studio/tests/pages/new/[slug].test.tsx@@ -102,6 +102,19 @@ const DEFAULT_AVAILABLE_REGIONS: RegionsInfo = {},}+const FRANKFURT = 'Central EU (Frankfurt)'++const AVAILABLE_REGIONS_WITH_FRANKFURT: RegionsInfo = {+ ...DEFAULT_AVAILABLE_REGIONS,+ all: {+ ...DEFAULT_AVAILABLE_REGIONS.all,+ specific: [+ ...DEFAULT_AVAILABLE_REGIONS.all.specific,+ { code: 'eu-central-1', name: FRANKFURT, provider: 'AWS', type: 'specific' },+ ],+ },+}+const DEFAULT_AVAILABLE_VERSIONS: { available_versions: AvailableVersion[] } = {available_versions: [{ postgres_engine: '15', release_channel: 'ga', version: 'supabase-postgres-15.6.1.139' },@@ -496,6 +509,28 @@ describe('project creation wizard', () => {})describe('postgres version and orioledb', () => {+ test('hides advanced configuration when orioledb is unavailable', async () => {+ mockWizardEndpoints()+ const onAvailableVersionsRequest = vi.fn()+ addAPIMock({+ method: 'post',+ path: '/platform/organizations/:slug/available-versions',+ response: () => {+ onAvailableVersionsRequest()+ return HttpResponse.json<{ available_versions: AvailableVersion[] }>({+ available_versions: DEFAULT_AVAILABLE_VERSIONS.available_versions.slice(0, 1),+ })+ },+ })++ await renderWizard()++ await waitFor(() => expect(onAvailableVersionsRequest).toHaveBeenCalled())+ expect(+ screen.queryByRole('button', { name: 'Advanced Configuration' })+ ).not.toBeInTheDocument()+ })+test('selecting orioledb shows the alpha warning and submits the oriole engine/channel', async () => {mockWizardEndpoints()const onRequest = vi.fn()@@ -520,7 +555,7 @@ describe('project creation wizard', () => {expect(body.release_channel).toBe('alpha')})- test('rejects high availability combined with orioledb', async () => {+ test('hides advanced configuration only while high availability is enabled', async () => {mockWizardEndpoints()const onRequest = vi.fn()mockCreateProject(onRequest)@@ -528,32 +563,101 @@ describe('project creation wizard', () => {await renderWizard()await fillProjectName('HA Oriole Project')+ await generateAndWaitForStrongPassword()await selectRegion(/Americas/)- // The high availability toggle is now a top-level field, gated only by the entitlement.- await user.click(await screen.findByRole('switch'))-fireEvent.click(await screen.findByRole('button', { name: 'Advanced Configuration' }))await user.click(await screen.findByRole('radio', { name: /Postgres with OrioleDB/ }))- await screen.findByText('High availability is not supported with OrioleDB images')- expect(onRequest).not.toHaveBeenCalled()+ const highAvailabilitySwitch = await screen.findByRole('switch')+ await user.click(highAvailabilitySwitch)++ expect(+ screen.queryByRole('button', { name: 'Advanced Configuration' })+ ).not.toBeInTheDocument()++ await user.click(highAvailabilitySwitch)+ expect(+ await screen.findByRole('button', { name: 'Advanced Configuration' })+ ).toBeInTheDocument()++ await user.click(highAvailabilitySwitch)+ fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))+ await waitFor(() => expect(onRequest).toHaveBeenCalled())+ expect(onRequest.mock.calls[0][0].postgres_engine).toBe('17')+ expect(onRequest.mock.calls[0][0].release_channel).toBe('ga')})- test('blocks submission with a toast when orioledb becomes unavailable after selection', async () => {- const FRANKFURT = 'Central EU (Frankfurt)'- mockWizardEndpoints({- availableRegions: {- ...DEFAULT_AVAILABLE_REGIONS,- all: {- ...DEFAULT_AVAILABLE_REGIONS.all,- specific: [- ...DEFAULT_AVAILABLE_REGIONS.all.specific,- { code: 'eu-central-1', name: FRANKFURT, provider: 'AWS', type: 'specific' },- ],- },+ test('keeps a manually selected Postgres version when available versions refetch', async () => {+ mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })+ const onAvailableVersionsRequest = vi.fn()+ addAPIMock({+ method: 'post',+ path: '/platform/organizations/:slug/available-versions',+ response: () => {+ onAvailableVersionsRequest()+ return HttpResponse.json<{ available_versions: AvailableVersion[] }>(+ DEFAULT_AVAILABLE_VERSIONS+ )},})++ await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })++ await fillProjectName('Sticky Version Project')+ await selectRegion(/Americas/)+ fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))++ // Auto-selects the GA default once versions load+ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')+ )++ await user.click(screen.getByLabelText('Postgres version'))+ await user.click(await screen.findByRole('option', { name: /17\.9\.9\.999/ }))+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')++ const requestsBeforeRegionChange = onAvailableVersionsRequest.mock.calls.length+ await selectRegion(/Frankfurt/)+ await waitFor(() =>+ expect(onAvailableVersionsRequest.mock.calls.length).toBeGreaterThan(+ requestsBeforeRegionChange+ )+ )++ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')+ })++ test('keeps a non-default Postgres version when the internal panel is collapsed and reopened', async () => {+ mockWizardEndpoints()++ await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })++ await screen.findByPlaceholderText('Project name')+ await selectRegion(/Americas/)+ const panelToggle = await screen.findByRole('button', {+ name: 'Internal-only Configuration',+ })+ fireEvent.click(panelToggle)++ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')+ )+ await user.click(screen.getByLabelText('Postgres version'))+ await user.click(await screen.findByRole('option', { name: /17\.9\.9\.999/ }))+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')++ fireEvent.click(panelToggle)+ await waitFor(() => expect(screen.queryByLabelText('Postgres version')).toBeNull())+ fireEvent.click(panelToggle)++ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')+ )+ })++ test('blocks submission with a toast when orioledb becomes unavailable after selection', async () => {+ mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })const onRequest = vi.fn()mockCreateProject(onRequest)@@ -593,13 +697,19 @@ describe('project creation wizard', () => {})describe('high availability', () => {- test('shows the high availability toggle from the entitlement, without the internal-only flag', async () => {+ test('shows the high availability toggle when the entitlement is enabled', async () => {mockWizardEndpoints()await renderWizard()expect(await screen.findByText('High availability')).toBeInTheDocument()- // The toggle must not depend on the internal-only configuration section.+ expect(screen.getByText('Alpha')).toBeInTheDocument()+ expect(screen.getByText(/Free during Alpha for up to 2 projects/)).toBeInTheDocument()+ expect(+ screen+ .getByText('High availability')+ .compareDocumentPosition(screen.getByText('Compute size'))+ ).toBe(Node.DOCUMENT_POSITION_FOLLOWING)expect(screen.queryByRole('button', { name: 'Internal-only Configuration' })).not.toBeInTheDocument()@@ -623,7 +733,43 @@ describe('project creation wizard', () => {expect(screen.queryByText('High availability')).not.toBeInTheDocument()})- test('enabling high availability submits the flag and forces the AWS_K8S cloud provider', async () => {+ test('removes the custom Postgres version field while high availability is enabled', async () => {+ mockWizardEndpoints()++ await renderWizard({+ flags: {+ newProjectInternalOnlyConfiguration: true,+ },+ })++ const highAvailabilitySwitch = await screen.findByRole('switch', {+ name: 'Enable high availability',+ })+ await user.click(highAvailabilitySwitch)+ fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))++ expect(screen.getByLabelText('Postgres version')).toBeDisabled()+ expect(screen.queryByPlaceholderText('e.g 17.6.1.104')).not.toBeInTheDocument()++ await user.click(highAvailabilitySwitch)++ expect(await screen.findByPlaceholderText('e.g 17.6.1.104')).toBeInTheDocument()+ })++ test('shows high availability regions in a dedicated group', async () => {+ mockWizardEndpoints()++ await renderWizard()++ await user.click(await screen.findByRole('switch', { name: 'Enable high availability' }))+ await user.click(getSelectTriggerByLabel('Region'))++ expect(await screen.findByText('High Availability Regions')).toBeInTheDocument()+ expect(screen.queryByText('General regions')).not.toBeInTheDocument()+ expect(screen.queryByText('Specific regions')).not.toBeInTheDocument()+ })++ test('enabling high availability submits the fixed engine and AWS_K8S provider without a custom version', async () => {mockWizardEndpoints()const onRequest = vi.fn()mockCreateProject(onRequest)@@ -633,7 +779,7 @@ describe('project creation wizard', () => {await fillProjectName('HA Project')await generateAndWaitForStrongPassword()await user.click(await screen.findByRole('switch'))- await selectRegion(/Americas/)+ await selectRegion(/East US/)fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))@@ -641,6 +787,151 @@ describe('project creation wizard', () => {const body = onRequest.mock.calls[0][0]expect(body.high_availability).toBe(true)expect(body.cloud_provider).toBe('AWS_K8S')+ expect(body.postgres_engine).toBe('17')+ expect(body.release_channel).toBe('ga')+ expect(body.custom_supabase_internal_requests).toBeUndefined()+ })++ test('forces the high availability region over a manually selected region and restores it', async () => {+ vi.stubEnv('NEXT_PUBLIC_ENVIRONMENT', 'staging')+ try {+ mockWizardEndpoints({ availableRegions: AVAILABLE_REGIONS_WITH_FRANKFURT })++ await renderWizard()++ await screen.findByPlaceholderText('Project name')+ await selectRegion(/Frankfurt/)+ expect(getSelectTriggerByLabel('Region')).toHaveTextContent(FRANKFURT)++ const highAvailabilitySwitch = await screen.findByRole('switch', {+ name: 'Enable high availability',+ })+ await user.click(highAvailabilitySwitch)++ await waitFor(() =>+ expect(getSelectTriggerByLabel('Region')).toHaveTextContent('East US (North Virginia)')+ )++ await user.click(highAvailabilitySwitch)++ await waitFor(() => expect(getSelectTriggerByLabel('Region')).toHaveTextContent(FRANKFURT))+ } finally {+ vi.unstubAllEnvs()+ }+ })++ test('restores the Postgres version selection when high availability is toggled off', async () => {+ mockWizardEndpoints()+ // Mirror staging: no versions offered for the standard provider, so the+ // selection only ever gets populated by the AWS_K8S list while HA is on.+ addAPIMock({+ method: 'post',+ path: '/platform/organizations/:slug/available-versions',+ response: async ({ request }) => {+ const { provider } = (await request.json()) as { provider: string }+ return HttpResponse.json<{ available_versions: AvailableVersion[] }>(+ provider === 'AWS_K8S' ? DEFAULT_AVAILABLE_VERSIONS : { available_versions: [] }+ )+ },+ })+ const onRequest = vi.fn()+ mockCreateProject(onRequest)++ await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })++ await fillProjectName('HA Selection Restore Project')+ await generateAndWaitForStrongPassword()+ await selectRegion(/Americas/)+ fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))++ const highAvailabilitySwitch = await screen.findByRole('switch', {+ name: 'Enable high availability',+ })+ await user.click(highAvailabilitySwitch)++ // The AWS_K8S versions load and auto-select a default while HA is on+ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')+ )++ await user.click(highAvailabilitySwitch)++ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent(+ 'Select a Postgres version for your project'+ )+ )++ fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))++ await waitFor(() => expect(onRequest).toHaveBeenCalled())+ const body = onRequest.mock.calls[0][0]+ expect(body.high_availability).toBe(false)+ expect(body.postgres_engine).toBeUndefined()+ expect(body.release_channel).toBeUndefined()+ expect(body.custom_supabase_internal_requests).toBeUndefined()+ })++ test('restores a manually selected Postgres version selection after HA toggle', async () => {+ mockWizardEndpoints()+ addAPIMock({+ method: 'post',+ path: '/platform/organizations/:slug/available-versions',+ response: async ({ request }) => {+ const { provider } = (await request.json()) as { provider: string }+ return HttpResponse.json<{ available_versions: AvailableVersion[] }>(+ provider === 'AWS_K8S'+ ? { available_versions: DEFAULT_AVAILABLE_VERSIONS.available_versions.slice(0, 1) }+ : DEFAULT_AVAILABLE_VERSIONS+ )+ },+ })++ await renderWizard({ flags: { newProjectInternalOnlyConfiguration: true } })++ await fillProjectName('Manual Selection Restore Project')+ await selectRegion(/Americas/)+ fireEvent.click(await screen.findByRole('button', { name: 'Internal-only Configuration' }))++ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('15.6.1.139')+ )+ await user.click(screen.getByLabelText('Postgres version'))+ await user.click(await screen.findByRole('option', { name: /17\.9\.9\.999/ }))+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')++ const highAvailabilitySwitch = await screen.findByRole('switch', {+ name: 'Enable high availability',+ })+ await user.click(highAvailabilitySwitch)+ await user.click(highAvailabilitySwitch)++ await waitFor(() =>+ expect(screen.getByLabelText('Postgres version')).toHaveTextContent('17.9.9.999')+ )+ })++ test('restores the standard Postgres configuration when high availability is disabled', async () => {+ mockWizardEndpoints()+ const onRequest = vi.fn()+ mockCreateProject(onRequest)++ await renderWizard()++ await fillProjectName('Standard Project')+ await generateAndWaitForStrongPassword()+ const highAvailabilitySwitch = await screen.findByRole('switch')+ await user.click(highAvailabilitySwitch)+ await user.click(highAvailabilitySwitch)++ fireEvent.click(screen.getByRole('button', { name: 'Create new project' }))++ await waitFor(() => expect(onRequest).toHaveBeenCalled())+ const body = onRequest.mock.calls[0][0]+ expect(body.high_availability).toBe(false)+ expect(body.cloud_provider).toBe('AWS')+ expect(body.postgres_engine).toBeUndefined()+ expect(body.custom_supabase_internal_requests).toBeUndefined()})})