RegionSelector.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import { useFlag, useParams } from 'common'
  2. import { UseFormReturn } from 'react-hook-form'
  3. import type { CloudProvider } from 'shared-data'
  4. import {
  5. Badge,
  6. cn,
  7. FormField,
  8. Select,
  9. SelectContent,
  10. SelectGroup,
  11. SelectItem,
  12. SelectLabel,
  13. SelectSeparator,
  14. SelectTrigger,
  15. SelectValue,
  16. Tooltip,
  17. TooltipContent,
  18. TooltipTrigger,
  19. } from 'ui'
  20. import { Admonition } from 'ui-patterns/admonition'
  21. import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
  22. import { CreateProjectForm } from './ProjectCreation.schema'
  23. import { getAvailableRegions } from './ProjectCreation.utils'
  24. import AlertError from '@/components/ui/AlertError'
  25. import { InlineLink } from '@/components/ui/InlineLink'
  26. import Panel from '@/components/ui/Panel'
  27. import { useDefaultRegionQuery } from '@/data/misc/get-default-region-query'
  28. import { useOrganizationAvailableRegionsQuery } from '@/data/organizations/organization-available-regions-query'
  29. import { useIncidentStatusQuery } from '@/data/platform/incident-status-query'
  30. import type { DesiredInstanceSize } from '@/data/projects/new-project.constants'
  31. import { BASE_PATH, PROVIDERS } from '@/lib/constants'
  32. interface RegionSelectorProps {
  33. form: UseFormReturn<CreateProjectForm>
  34. instanceSize?: DesiredInstanceSize
  35. layout?: 'vertical' | 'horizontal'
  36. }
  37. // [Joshen] Let's use a library to maintain the flag SVGs in the future
  38. // I tried using https://flagpack.xyz/docs/development/react/ but couldn't get it to render
  39. // ^ can try again next time
  40. // Maps smart region group codes to the specific-region code prefixes they contain.
  41. // Used to check whether an incident affecting specific regions also affects a smart region selection.
  42. const SMART_REGION_PREFIXES: Record<string, Array<string>> = {
  43. americas: ['us-', 'ca-', 'sa-'],
  44. emea: ['eu-', 'me-', 'af-'],
  45. apac: ['ap-'],
  46. }
  47. function smartRegionMatchesSpecific(smartCode: string, specificCode: string): boolean {
  48. return (SMART_REGION_PREFIXES[smartCode] ?? []).some((prefix) => specificCode.startsWith(prefix))
  49. }
  50. // Map backend region names to user-friendly display names
  51. const getDisplayNameForSmartRegion = (name: string): string => {
  52. if (name === 'APAC') {
  53. return 'Asia-Pacific'
  54. }
  55. return name
  56. }
  57. export const RegionSelector = ({
  58. form,
  59. instanceSize,
  60. layout = 'horizontal',
  61. }: RegionSelectorProps) => {
  62. const { slug } = useParams()
  63. const cloudProvider = form.getValues('cloudProvider') as CloudProvider
  64. const smartRegionEnabled = useFlag('enableSmartRegion')
  65. const { data: statusData } = useIncidentStatusQuery()
  66. const { incidents = [] } = statusData ?? {}
  67. const { isPending: isLoadingDefaultRegion } = useDefaultRegionQuery(
  68. { cloudProvider },
  69. { enabled: !smartRegionEnabled }
  70. )
  71. const {
  72. data: availableRegionsData,
  73. isPending: isLoadingAvailableRegions,
  74. isError: isErrorAvailableRegions,
  75. error: errorAvailableRegions,
  76. } = useOrganizationAvailableRegionsQuery(
  77. { slug, cloudProvider, desiredInstanceSize: instanceSize },
  78. { enabled: smartRegionEnabled, staleTime: 1000 * 60 * 5 } // 5 minutes
  79. )
  80. const smartRegions = availableRegionsData?.all.smartGroup ?? []
  81. const allRegions = availableRegionsData?.all.specific ?? []
  82. const recommendedSmartRegions = new Set(
  83. [availableRegionsData?.recommendations.smartGroup.code].filter(Boolean)
  84. )
  85. const recommendedSpecificRegions = new Set(
  86. availableRegionsData?.recommendations.specific.map((region) => region.code)
  87. )
  88. const availableRegions = getAvailableRegions(PROVIDERS[cloudProvider].id)
  89. const regionsArray = Object.entries(availableRegions).map(([_key, value]) => {
  90. return {
  91. code: value.code,
  92. name: value.displayName,
  93. provider: cloudProvider,
  94. status: undefined,
  95. }
  96. })
  97. const regionOptions = smartRegionEnabled ? allRegions : regionsArray
  98. const isLoading = smartRegionEnabled ? isLoadingAvailableRegions : isLoadingDefaultRegion
  99. const showNonProdFields =
  100. process.env.NEXT_PUBLIC_ENVIRONMENT === 'local' ||
  101. process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
  102. const allSelectableRegions = [...smartRegions, ...regionOptions]
  103. if (isErrorAvailableRegions) {
  104. return <AlertError subject="Error loading available regions" error={errorAvailableRegions} />
  105. }
  106. return (
  107. <Panel.Content>
  108. <FormField
  109. control={form.control}
  110. name="dbRegion"
  111. render={({ field }) => {
  112. const selectedRegion = allSelectableRegions.find((region) => {
  113. return !!region.name && region.name === field.value
  114. })
  115. const affectingIncidents = incidents.filter((incident) => {
  116. const affectedRegions = incident.cache?.affected_regions ?? []
  117. if (affectedRegions.length === 0 || selectedRegion?.code === undefined) return false
  118. // Specific region: direct code match
  119. if (affectedRegions.includes(selectedRegion.code)) return true
  120. // Smart region: match if any affected region falls within the smart group
  121. return affectedRegions.some((specificCode) =>
  122. smartRegionMatchesSpecific(selectedRegion.code, specificCode)
  123. )
  124. })
  125. return (
  126. <>
  127. <FormItemLayout
  128. layout={layout}
  129. label="Region"
  130. description={
  131. <>
  132. <p>Select the region closest to your users for the best performance.</p>
  133. {showNonProdFields && (
  134. <div className="mt-2 text-warning">
  135. <p>Only these regions are supported for local/staging projects:</p>
  136. <ul className="list-disc list-inside mt-1">
  137. <li>East US (North Virginia)</li>
  138. <li>Central EU (Frankfurt)</li>
  139. <li>Southeast Asia (Singapore)</li>
  140. </ul>
  141. </div>
  142. )}
  143. </>
  144. }
  145. >
  146. <Select value={field.value} onValueChange={field.onChange} disabled={isLoading}>
  147. <SelectTrigger className="[&>:nth-child(1)]:w-full [&>:nth-child(1)]:flex [&>:nth-child(1)]:items-start">
  148. <SelectValue
  149. placeholder={
  150. isLoading
  151. ? 'Loading available regions...'
  152. : 'Select a region for your project..'
  153. }
  154. >
  155. {field.value !== undefined && (
  156. <div className="flex items-center gap-x-3">
  157. {selectedRegion?.code && (
  158. <img
  159. alt="region icon"
  160. className="w-5 rounded-xs"
  161. src={`${BASE_PATH}/img/regions/${selectedRegion.code}.svg`}
  162. />
  163. )}
  164. <span className="text-foreground">
  165. {selectedRegion?.name
  166. ? getDisplayNameForSmartRegion(selectedRegion.name)
  167. : field.value}
  168. </span>
  169. </div>
  170. )}
  171. </SelectValue>
  172. </SelectTrigger>
  173. <SelectContent>
  174. {smartRegionEnabled && (
  175. <>
  176. <SelectGroup>
  177. <SelectLabel>General regions</SelectLabel>
  178. {smartRegions.map((value) => {
  179. return (
  180. <SelectItem
  181. key={value.code}
  182. value={value.name}
  183. className="w-full [&>:nth-child(2)]:w-full"
  184. >
  185. <div className="flex flex-row items-center justify-between w-full">
  186. <div className="flex items-center gap-x-3">
  187. <img
  188. alt="region icon"
  189. className="w-5 rounded-xs"
  190. src={`${BASE_PATH}/img/regions/${value.code}.svg`}
  191. />
  192. <span className="text-foreground">
  193. {getDisplayNameForSmartRegion(value.name)}
  194. </span>
  195. </div>
  196. <div>
  197. {recommendedSmartRegions.has(value.code) && (
  198. <Badge variant="success" className="mr-1">
  199. Recommended
  200. </Badge>
  201. )}
  202. </div>
  203. </div>
  204. </SelectItem>
  205. )
  206. })}
  207. </SelectGroup>
  208. <SelectSeparator />
  209. </>
  210. )}
  211. <SelectGroup>
  212. <SelectLabel>Specific regions</SelectLabel>
  213. {regionOptions.map((value) => {
  214. return (
  215. <SelectItem
  216. key={value.code}
  217. value={value.name}
  218. className={cn(
  219. 'w-full [&>:nth-child(2)]:w-full',
  220. value.status !== undefined && 'pointer-events-auto!'
  221. )}
  222. disabled={value.status !== undefined}
  223. >
  224. <div className="flex flex-row items-center justify-between w-full gap-x-2">
  225. <div className="flex items-center gap-x-3">
  226. <img
  227. alt="region icon"
  228. className="w-5 rounded-xs"
  229. src={`${BASE_PATH}/img/regions/${value.code}.svg`}
  230. />
  231. <div className="flex items-center gap-x-2">
  232. <span className="text-foreground">{value.name}</span>
  233. <span className="text-xs text-foreground-lighter font-mono">
  234. {value.code}
  235. </span>
  236. </div>
  237. </div>
  238. {recommendedSpecificRegions.has(value.code) && (
  239. <Badge variant="success" className="mr-1">
  240. Recommended
  241. </Badge>
  242. )}
  243. {value.status !== undefined && value.status === 'capacity' && (
  244. <Tooltip>
  245. <TooltipTrigger>
  246. <Badge variant="warning" className="mr-1">
  247. Unavailable
  248. </Badge>
  249. </TooltipTrigger>
  250. <TooltipContent>
  251. Temporarily unavailable due to this region being at capacity.
  252. </TooltipContent>
  253. </Tooltip>
  254. )}
  255. </div>
  256. </SelectItem>
  257. )
  258. })}
  259. </SelectGroup>
  260. </SelectContent>
  261. </Select>
  262. </FormItemLayout>
  263. {affectingIncidents.length > 0 && (
  264. <FormItemLayout layout="horizontal">
  265. <Admonition
  266. type="warning"
  267. title="Incident in progress for this region"
  268. description={
  269. <>
  270. We're currently investigating an issue that may impact projects in this
  271. region. Follow updates on{' '}
  272. <InlineLink href="https://status.supabase.com">
  273. status.supabase.com
  274. </InlineLink>
  275. .
  276. </>
  277. }
  278. className="mt-3"
  279. />
  280. </FormItemLayout>
  281. )}
  282. </>
  283. )
  284. }}
  285. />
  286. </Panel.Content>
  287. )
  288. }