The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Joshenlim/fe 4465 experiment with best available region selection (#50851)
Joshen Lim0d3b73794bdb
diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.tsindex 344eaf59ad9..c7e1bc40e59 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.test.ts@@ -11,6 +11,7 @@ import {getAvailableRegions,getHighAvailabilityRegionCode,resolveDefaultDbRegion,+ resolveSelectedRegionOptionType,} from './ProjectCreation.utils'describe('resolveDefaultDbRegion', () => {@@ -69,6 +70,55 @@ describe('resolveDefaultDbRegion', () => {})})+describe('resolveSelectedRegionOptionType', () => {+ const smartGroupRegions = [{ name: 'Americas' }, { name: 'APAC' }]+ const specificRegions = [{ name: 'ap-southeast-1' }, { name: 'us-east-1' }]++ it('returns general when the "Best available region" shortcut was used', () => {+ expect(+ resolveSelectedRegionOptionType({+ isBestAvailableSelected: true,+ dbRegion: 'ap-southeast-1',+ smartGroupRegions,+ specificRegions,+ })+ ).toBe('general')+ })++ it('returns general when the region was picked from the smart group list', () => {+ expect(+ resolveSelectedRegionOptionType({+ isBestAvailableSelected: false,+ dbRegion: 'Americas',+ smartGroupRegions,+ specificRegions,+ })+ ).toBe('general')+ })++ it('returns specific when the region was picked from the specific regions list', () => {+ expect(+ resolveSelectedRegionOptionType({+ isBestAvailableSelected: false,+ dbRegion: 'ap-southeast-1',+ smartGroupRegions,+ specificRegions,+ })+ ).toBe('specific')+ })++ it('returns undefined when the region matches neither list', () => {+ expect(+ resolveSelectedRegionOptionType({+ isBestAvailableSelected: false,+ dbRegion: undefined,+ smartGroupRegions,+ specificRegions,+ })+ ).toBeUndefined()+ })+})+describe('getAvailableRegions', () => {it.each(['local', 'staging', 'prod'])('returns all AWS regions for AWS on %s', (environment) => {expect(getAvailableRegions('AWS', environment)).toEqual(AWS_REGIONS)diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.tsindex 92c3938925a..42fe8186721 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreation.utils.ts@@ -68,6 +68,26 @@ export function resolveDefaultDbRegion({: fixedDefaultRegion}+type ResolveSelectedRegionOptionTypeArgs = {+ isBestAvailableSelected: boolean+ dbRegion: string | undefined+ smartGroupRegions: Array<{ name: string }>+ specificRegions: Array<{ name: string }>+}++export function resolveSelectedRegionOptionType({+ isBestAvailableSelected,+ dbRegion,+ smartGroupRegions,+ specificRegions,+}: ResolveSelectedRegionOptionTypeArgs): 'general' | 'specific' | undefined {+ // The "Best available region" shortcut always resolves to a smart-group recommendation+ if (isBestAvailableSelected) return 'general'+ if (smartGroupRegions.some((region) => region.name === dbRegion)) return 'general'+ if (specificRegions.some((region) => region.name === dbRegion)) return 'specific'+ return undefined+}+/*** When launching new projects, they only get assigned a compute size once successfully launched,* this might assume wrong compute size, but only for projects being rapidly launched after one another on non-default compute sizes.diff --git a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsxindex 38654996b46..93424c1c414 100644--- a/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/ProjectCreationForm.tsx@@ -35,6 +35,7 @@ import {instanceLabel,monthlyInstancePrice,resolveDefaultDbRegion,+ resolveSelectedRegionOptionType,smartRegionToExactRegion,} from './ProjectCreation.utils'import { ProjectCreationFooter } from './ProjectCreationFooter'@@ -141,6 +142,15 @@ export const ProjectCreationForm = ({useFlag('newProjectInternalOnlyConfiguration') && !isVercelIntegrationFlowconst { getRegionRestriction } = useRegionRestriction()+ // [Joshen] Temp experiment - to clean up once completed+ const showBestAvailableRegionFeature = useIsFeatureEnabled(+ 'project_creation:show_best_available_region'+ )+ const showBestAvailableRegionFlag = useFlag('showBestAvailableRegion')+ const showBestAvailableRegionOption =+ showBestAvailableRegionFeature && showBestAvailableRegionFlag && isFreePlan+ const [isBestAvailableSelected, setIsBestAvailableSelected] = useState(false)+// Read the raw flag for telemetry — coerce-undefined-to-false would record false for// users whose flags haven't loaded yet. The raw value preserves undefined (omitted from// PostHog) so we only record an actual value (boolean true/false, or a variant string@@ -342,6 +352,15 @@ export const ProjectCreationForm = ({} = useProjectCreateMutation({onSuccess: (res) => {setProjectCreationError(undefined)+ const { smartGroup = [], specific = [] } = availableRegionsData?.all ?? {}+ const submittedDbRegion = form.getValues('dbRegion')+ const selectedRegionOption = isBestAvailableSelected ? 'best_available' : submittedDbRegion+ const selectedRegionOptionType = resolveSelectedRegionOptionType({+ isBestAvailableSelected,+ dbRegion: submittedDbRegion,+ smartGroupRegions: smartGroup,+ specificRegions: specific,+ })track('project_creation_simple_version_submitted',{@@ -354,6 +373,7 @@ export const ProjectCreationForm = ({...(dataApiRevokeOnCreateDefaultFlag !== undefined && {dataApiRevokeOnCreateDefaultEnabled: dataApiRevokeOnCreateDefaultFlag,}),+ ...(showBestAvailableRegionOption && { selectedRegionOption, selectedRegionOptionType }),},{project: res.ref,@@ -773,6 +793,9 @@ export const ProjectCreationForm = ({<RegionSelectorform={form}instanceSize={instanceSize as DesiredInstanceSize}+ showBestAvailableRegionOption={showBestAvailableRegionOption}+ isBestAvailableSelected={isBestAvailableSelected}+ onBestAvailableSelectedChange={setIsBestAvailableSelected}/>{isVercelIntegrationFlow && !!externalId && <DataSeeding form={form} />}diff --git a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsxindex 06796a2c4c0..1d2fbda58c0 100644--- a/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx+++ b/apps/studio/components/interfaces/ProjectCreation/RegionSelector.tsx@@ -1,5 +1,5 @@import { useFeatureFlags, useParams } from 'common'-import { Loader2 } from 'lucide-react'+import { Loader2, ThumbsUp } from 'lucide-react'import { useEffect, useRef } from 'react'import { UseFormReturn } from 'react-hook-form'import type { CloudProvider } from 'shared-data'@@ -45,6 +45,9 @@ interface RegionSelectorProps {form: UseFormReturn<CreateProjectForm>instanceSize?: DesiredInstanceSizelayout?: 'vertical' | 'horizontal'+ showBestAvailableRegionOption: boolean+ isBestAvailableSelected: boolean+ onBestAvailableSelectedChange: (value: boolean) => void}// [Joshen] Let's use a library to maintain the flag SVGs in the future@@ -73,10 +76,19 @@ const getDisplayNameForSmartRegion = (name: string): string => {const isLocal = process.env.NEXT_PUBLIC_ENVIRONMENT === 'local'+const BestAvailableRegionIcon = () => (+ <div className="w-5 border border-brand-500 h-4.5 rounded-[3px] bg-brand-300 flex items-center justify-center">+ <ThumbsUp size={10} className="text-brand" />+ </div>+)+export const RegionSelector = ({form,instanceSize,layout = 'horizontal',+ showBestAvailableRegionOption,+ isBestAvailableSelected,+ onBestAvailableSelectedChange,}: RegionSelectorProps) => {const { slug } = useParams()const cloudProvider = form.getValues('cloudProvider') as CloudProvider@@ -116,6 +128,33 @@ export const RegionSelector = ({const recommendedSmartRegions = new Set([availableRegionsData?.recommendations.smartGroup.code].filter(Boolean))+ const recommendedSmartRegion = smartRegions.find(+ (x) => x.code === recommendedSmartRegions.values().next().value+ )++ const isBestAvailableOptionShown = showBestAvailableRegionOption && !!recommendedSmartRegion+ const isBestAvailableActive = isBestAvailableSelected && isBestAvailableOptionShown++ // Defaults free orgs to the "Best available region" shortcut once the recommendation loads,+ // unless the user has already interacted with the region field themselves.+ const hasUserSelectedRegionRef = useRef(false)+ useEffect(() => {+ if (hasUserSelectedRegionRef.current) return+ if (isBestAvailableOptionShown) {+ onBestAvailableSelectedChange(true)+ }+ }, [isBestAvailableOptionShown, onBestAvailableSelectedChange])++ // Keeps dbRegion following the recommendation while "Best available" is active, so a+ // recommendation change (e.g. after a refetch) doesn't leave the form submitting a stale+ // region behind a label that still reads "Best available region".+ useEffect(() => {+ if (!isBestAvailableSelected || !recommendedSmartRegion) return+ if (dbRegion !== recommendedSmartRegion.name) {+ form.setValue('dbRegion', recommendedSmartRegion.name)+ }+ }, [isBestAvailableSelected, recommendedSmartRegion, dbRegion, form])+const recommendedSpecificRegions = new Set(availableRegionsData?.recommendations.specific.map((region) => region.code))@@ -196,7 +235,11 @@ export const RegionSelector = ({selectedRestriction !== undefined? getRegionRestrictionCopy(selectedRestriction): undefined- const triggerLabel = isLoading ? 'Loading available regions...' : selectedRegionLabel+ const triggerLabel = isLoading+ ? 'Loading available regions...'+ : isBestAvailableActive+ ? 'Best available region'+ : selectedRegionLabelconst affectingIncidents = incidents.filter((incident) => {const affectedRegions = incident.cache?.affected_regions ?? []@@ -247,8 +290,19 @@ export const RegionSelector = ({><FormControl><Select- value={dbRegion}- onValueChange={(value) => value !== '' && field.onChange(value)}+ value={isBestAvailableActive ? 'best_available' : dbRegion}+ onValueChange={(value) => {+ if (value === '') return+ hasUserSelectedRegionRef.current = true+ if (value === 'best_available') {+ if (!recommendedSmartRegion) return+ onBestAvailableSelectedChange(true)+ field.onChange(recommendedSmartRegion.name)+ } else {+ onBestAvailableSelectedChange(false)+ field.onChange(value)+ }+ }}disabled={isLoading}><SelectTrigger@@ -266,8 +320,12 @@ export const RegionSelector = ({{dbRegion !== undefined && (<div className="flex items-center gap-x-3">{isLoading && <Loader2 size={14} className="animate-spin" />}- {selectedRegion?.code && (- <RegionFlag className="w-5" region={selectedRegion.code} />+ {isBestAvailableActive ? (+ <BestAvailableRegionIcon />+ ) : (+ selectedRegion?.code && (+ <RegionFlag className="w-5" region={selectedRegion.code} />+ ))}<span className="text-foreground">{triggerLabel}</span></div>@@ -275,6 +333,25 @@ export const RegionSelector = ({</SelectValue></SelectTrigger><SelectContent>+ {isBestAvailableOptionShown && (+ <>+ <SelectGroup>+ <SelectLabel>Recommendation</SelectLabel>+ <SelectItem+ value="best_available"+ className="w-full [&>:nth-child(2)]:w-full"+ >+ <div className="flex flex-row items-center justify-between w-full">+ <div className="flex items-center gap-x-3">+ <BestAvailableRegionIcon />+ <span className="text-foreground">Best available region</span>+ </div>+ </div>+ </SelectItem>+ </SelectGroup>+ <SelectSeparator />+ </>+ )}{smartRegionEnabled && !highAvailability && (<><SelectGroup>@@ -295,11 +372,12 @@ export const RegionSelector = ({</div><div>- {recommendedSmartRegions.has(value.code) && (- <Badge variant="success" className="mr-1">- Recommended- </Badge>- )}+ {!isBestAvailableOptionShown &&+ recommendedSmartRegions.has(value.code) && (+ <Badge variant="success" className="mr-1">+ Recommended+ </Badge>+ )}</div></div></SelectItem>@@ -339,11 +417,13 @@ export const RegionSelector = ({</div></div>- {recommendedSpecificRegions.has(value.code) && (- <Badge variant="success" className="mr-1">- Recommended- </Badge>- )}+ {!isBestAvailableOptionShown &&+ recommendedSpecificRegions.has(value.code) && (+ <Badge variant="success" className="mr-1">+ Recommended+ </Badge>+ )}+{restrictionCopy !== undefined && (<Tooltip><TooltipTrigger>diff --git a/packages/common/enabled-features/enabled-features.json b/packages/common/enabled-features/enabled-features.jsonindex 49032592106..b5e17d977d6 100644--- a/packages/common/enabled-features/enabled-features.json+++ b/packages/common/enabled-features/enabled-features.json@@ -103,6 +103,7 @@"project_creation:show_advanced_config": true,"project_creation:show_high_availability": true,+ "project_creation:show_best_available_region": true,"project_homepage:show_instance_size": true,"project_homepage:show_examples": true,diff --git a/packages/common/enabled-features/enabled-features.schema.json b/packages/common/enabled-features/enabled-features.schema.jsonindex 9943d645c31..4ed500aa15c 100644--- a/packages/common/enabled-features/enabled-features.schema.json+++ b/packages/common/enabled-features/enabled-features.schema.json@@ -358,6 +358,10 @@"type": "boolean","description": "Show the high availability toggle in the project creation flow"},+ "project_creation:show_best_available_region": {+ "type": "boolean",+ "description": "Show the best available region option in the project creation region selector"+ },"project_homepage:show_instance_size": {"type": "boolean",diff --git a/packages/common/telemetry-constants.ts b/packages/common/telemetry-constants.tsindex 9eb2fcf31db..2523a72ad17 100644--- a/packages/common/telemetry-constants.ts+++ b/packages/common/telemetry-constants.ts@@ -449,6 +449,21 @@ export interface ProjectCreationSimpleVersionSubmittedEvent {* omitted = PostHog flags had not loaded at the time of project creation*/dataApiRevokeOnCreateDefaultEnabled?: boolean | string+ /**+ * Which region option was submitted. Only present when the "Best available region" option+ * was shown to the user (see `showBestAvailableRegionOption` in RegionSelector.tsx); omitted+ * entirely for users who never saw that option.+ * 'best_available' = the "Best available region" shortcut was used+ * otherwise = the name of the region that was directly selected (e.g. 'Americas', 'ap-southeast-1')+ */+ selectedRegionOption?: string+ /**+ * Which region list `selectedRegionOption` came from. Only present alongside `selectedRegionOption`.+ * 'general' = picked from the "General regions" (smart group) list, or the "Best available+ * region" shortcut was used (it always resolves to a general/smart region)+ * 'specific' = picked from the "Specific regions" list+ */+ selectedRegionOptionType?: 'general' | 'specific'}groups: TelemetryGroups}