Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat/rr-functionality (#19466)

Joshen Lim539c2bbace61
diff --git a/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx b/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
index b3db18a8ed6..790bddce705 100644
--- a/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
+++ b/apps/studio/components/interfaces/Database/Backups/PITR/PITRSelection.tsx
@@ -6,7 +6,19 @@ import dayjs from 'dayjs'
import { useRouter } from 'next/router'
import { useState } from 'react'
import DatePicker from 'react-datepicker'
-import { Alert, Button, IconChevronLeft, IconChevronRight, IconHelpCircle, Modal } from 'ui'
+import {
+ Alert,
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ IconAlertTriangle,
+ IconChevronLeft,
+ IconChevronRight,
+ IconExternalLink,
+ IconHelpCircle,
+ Modal,
+} from 'ui'
import { FormHeader, FormPanel } from 'components/ui/Forms'
import InformationBox from 'components/ui/InformationBox'
@@ -25,6 +37,8 @@ import {
import PITRStatus from './PITRStatus'
import TimeInput from './TimeInput'
import TimezoneSelection from './TimezoneSelection'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import Link from 'next/link'
const PITRSelection = () => {
const router = useRouter()
@@ -32,10 +46,13 @@ const PITRSelection = () => {
const queryClient = useQueryClient()
const { data: backups } = useBackupsQuery({ projectRef: ref })
+ const { data: databases } = useReadReplicasQuery({ projectRef: ref })
const [showConfiguration, setShowConfiguration] = useState(false)
const [showConfirmation, setShowConfirmation] = useState(false)
const [selectedTimezone, setSelectedTimezone] = useState<Timezone>(getClientTimezone())
+ const hasReadReplicas = (databases ?? []).length > 1
+
const {
mutate: restoreFromPitr,
isLoading: isRestoring,
@@ -126,6 +143,29 @@ const PITRSelection = () => {
<BackupsEmpty />
) : (
<>
+ {hasReadReplicas && (
+ <Alert_Shadcn_ variant="warning">
+ <IconAlertTriangle strokeWidth={2} />
+ <AlertTitle_Shadcn_>
+ Unable to restore from PITR as project has read replicas enabled
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ You will need to remove all read replicas first from your project's infrastructure
+ settings prior to starting a PITR restore.
+ </AlertDescription_Shadcn_>
+ <div className="flex items-center gap-x-2 mt-2">
+ {/* [Joshen] Ideally we have some links to a docs to explain why so */}
+ {/* <Button type="default" icon={<IconExternalLink strokeWidth={1.5} />}>
+ Documentation
+ </Button> */}
+ <Button type="default">
+ <Link href={`/project/${ref}/settings/infrastructure`}>
+ Infrastructure settings
+ </Link>
+ </Button>
+ </div>
+ </Alert_Shadcn_>
+ )}
{!showConfiguration ? (
<PITRStatus
selectedTimezone={selectedTimezone}
diff --git a/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx b/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx
index ee21d400d03..09bb66c3363 100644
--- a/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx
+++ b/apps/studio/components/interfaces/Database/Backups/PITR/PITRStatus.tsx
@@ -10,6 +10,7 @@ import { useBackupsQuery } from 'data/database/backups-query'
import { useCheckPermissions } from 'hooks'
import { Timezone } from './PITR.types'
import TimezoneSelection from './TimezoneSelection'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
interface PITRStatusProps {
selectedTimezone: Timezone
@@ -24,6 +25,9 @@ const PITRStatus = ({
}: PITRStatusProps) => {
const { ref } = useParams()
const { data: backups } = useBackupsQuery({ projectRef: ref })
+ const { data: databases } = useReadReplicasQuery({ projectRef: ref })
+
+ const hasReadReplicas = (databases ?? []).length > 1
const { earliestPhysicalBackupDateUnix, latestPhysicalBackupDateUnix } =
backups?.physicalBackupData ?? {}
@@ -57,7 +61,10 @@ const PITRStatus = ({
</div>
<Tooltip.Root delayDuration={0}>
<Tooltip.Trigger asChild>
- <Button disabled={!canTriggerPhysicalBackup} onClick={() => onSetConfiguration()}>
+ <Button
+ disabled={hasReadReplicas || !canTriggerPhysicalBackup}
+ onClick={() => onSetConfiguration()}
+ >
Start a restore
</Button>
</Tooltip.Trigger>
diff --git a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
index ad1fe27149e..e5d3b0e688d 100644
--- a/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/SQLEditor.tsx
@@ -66,6 +66,8 @@ import {
getDiffTypeDropdownLabel,
} from './SQLEditor.utils'
import UtilityPanel from './UtilityPanel/UtilityPanel'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import toast from 'react-hot-toast'
// Load the monaco editor client-side only (does not behave well server-side)
const MonacoEditor = dynamic(() => import('./MonacoEditor'), { ssr: false })
@@ -119,6 +121,9 @@ const SQLEditor = () => {
const supabaseAIEnabled = useFlag('sqlEditorSupabaseAI')
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
+ const { data: databases, isSuccess: isSuccessReadReplicas } = useReadReplicasQuery({
+ projectRef: ref,
+ })
// Customers on HIPAA plans should not have access to Supabase AI
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
@@ -150,6 +155,13 @@ const SQLEditor = () => {
setIsFirstRender(false)
}, [])
+ useEffect(() => {
+ if (isSuccessReadReplicas) {
+ const primaryDatabase = databases.find((db) => db.identifier === ref)
+ snap.setSelectedDatabaseId(primaryDatabase?.identifier)
+ }
+ }, [isSuccessReadReplicas])
+
const { data, refetch: refetchEntityDefinitions } = useEntityDefinitionsQuery(
{
projectRef: selectedProject?.ref,
@@ -310,9 +322,16 @@ const SQLEditor = () => {
setLineHighlights([])
}
+ const connectionString = databases?.find(
+ (db) => db.identifier === snap.selectedDatabaseId
+ )?.connectionString
+ if (!connectionString) {
+ return toast.error('Unable to run query: Connection string is missing')
+ }
+
execute({
projectRef: project.ref,
- connectionString: project.connectionString,
+ connectionString: connectionString,
sql: wrapWithRoleImpersonation(sql, {
projectRef: project.ref,
role: getImpersonatedRole(),
diff --git a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
index d4c6130beb3..2deb45d696c 100644
--- a/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
+++ b/apps/studio/components/interfaces/SQLEditor/UtilityPanel/UtilityActions.tsx
@@ -9,6 +9,7 @@ import { useFlag } from 'hooks'
import { useState } from 'react'
import FavoriteButton from './FavoriteButton'
import SavingIndicator from './SavingIndicator'
+import { useSqlEditorStateSnapshot } from 'state/sql-editor'
export type UtilityActionsProps = {
id: string
@@ -28,9 +29,9 @@ const UtilityActions = ({
executeQuery,
}: UtilityActionsProps) => {
const os = detectOS()
+ const snap = useSqlEditorStateSnapshot()
const readReplicasEnabled = useFlag('readReplicas')
const roleImpersonationEnabledFlag = useFlag('roleImpersonation')
- const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>('1')
return (
<>
@@ -67,16 +68,20 @@ const UtilityActions = ({
</Tooltip.Root>
<div className="flex items-center justify-between gap-x-2 mx-2">
- {readReplicasEnabled && (
- <DatabaseSelector
- selectedDatabaseId={selectedDatabaseId}
- onChangeDatabaseId={setSelectedDatabaseId}
- />
- )}
-
<div className="flex items-center">
+ {readReplicasEnabled && (
+ <DatabaseSelector
+ variant="connected-on-right"
+ selectedDatabaseId={snap.selectedDatabaseId}
+ onChangeDatabaseId={snap.setSelectedDatabaseId}
+ />
+ )}
+
{roleImpersonationEnabledFlag && (
- <RoleImpersonationPopover serviceRoleLabel="postgres" variant="connected-on-right" />
+ <RoleImpersonationPopover
+ serviceRoleLabel="postgres"
+ variant={readReplicasEnabled ? 'connected-on-both' : 'connected-on-right'}
+ />
)}
<Button
diff --git a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx
index d0e23af4c2a..f320ccb2493 100644
--- a/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/DatabaseSettings/DatabaseSettings.tsx
@@ -18,12 +18,12 @@ import DatabaseSelector from 'components/ui/DatabaseSelector'
import Panel from 'components/ui/Panel'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
import { useProjectSettingsQuery } from 'data/config/project-settings-query'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
import { useResourceWarningsQuery } from 'data/usage/resource-warnings-query'
import { useFlag, useSelectedOrganization } from 'hooks'
import { pluckObjectFields } from 'lib/helpers'
import Telemetry from 'lib/telemetry'
-import { MOCK_DATABASES } from '../../Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants'
import ConfirmDisableReadOnlyModeModal from './ConfirmDisableReadOnlyModal'
import ResetDbPassword from './ResetDbPassword'
@@ -37,17 +37,31 @@ const DatabaseSettings = () => {
const readReplicasEnabled = useFlag('readReplicas')
const connectionStringsRef = useRef<HTMLDivElement>(null)
- const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>('1')
+ const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>(projectRef ?? '')
const [showConfirmationModal, setShowConfirmationModal] = useState(false)
- // [Joshen] Read replicas mock UI stuff
- const [open, setOpen] = useState(false)
- const databases = MOCK_DATABASES
- const selectedDatabase = databases.find((db) => db.id.toString() === selectedDatabaseId)
-
- const { data, error, isLoading, isError, isSuccess } = useProjectSettingsQuery({ projectRef })
const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })
+ const {
+ data,
+ error: projectSettingsError,
+ isLoading: isLoadingProjectSettings,
+ isError: isErrorProjectSettings,
+ isSuccess: isSuccessProjectSettings,
+ } = useProjectSettingsQuery({ projectRef })
const { data: resourceWarnings } = useResourceWarningsQuery()
+ const {
+ data: databases,
+ error: readReplicasError,
+ isLoading: isLoadingReadReplicas,
+ isError: isErrorReadReplicas,
+ isSuccess: isSuccessReadReplicas,
+ } = useReadReplicasQuery({ projectRef })
+ const error = readReplicasEnabled ? readReplicasError : projectSettingsError
+ const isLoading = readReplicasEnabled ? isLoadingReadReplicas : isLoadingProjectSettings
+ const isError = readReplicasEnabled ? isErrorReadReplicas : isErrorProjectSettings
+ const isSuccess = readReplicasEnabled ? isSuccessReadReplicas : isSuccessProjectSettings
+
+ const selectedDatabase = (databases ?? []).find((db) => db.identifier === selectedDatabaseId)
const isReadOnlyMode =
(resourceWarnings ?? [])?.find((warning) => warning.project === projectRef)
@@ -55,10 +69,10 @@ const DatabaseSettings = () => {
const { project } = data ?? {}
const DB_FIELDS = ['db_host', 'db_name', 'db_port', 'db_user', 'inserted_at']
- const connectionInfo =
- project !== undefined
- ? pluckObjectFields(project, DB_FIELDS)
- : { db_user: '', db_host: '', db_port: '', db_name: '' }
+ const emptyState = { db_user: '', db_host: '', db_port: '', db_name: '' }
+ const connectionInfo = readReplicasEnabled
+ ? pluckObjectFields(selectedDatabase || emptyState, DB_FIELDS)
+ : pluckObjectFields(project || emptyState, DB_FIELDS)
const handleCopy = (labelValue?: string) =>
Telemetry.sendEvent(
@@ -152,9 +166,17 @@ const DatabaseSettings = () => {
<Panel
title={
- <h5 key="panel-title" className="mb-0">
- Connection info
- </h5>
+ <div className="w-full flex items-center justify-between">
+ <h5 key="panel-title" className="mb-0">
+ Connection info
+ </h5>
+ {readReplicasEnabled && (
+ <DatabaseSelector
+ selectedDatabaseId={selectedDatabaseId}
+ onChangeDatabaseId={setSelectedDatabaseId}
+ />
+ )}
+ </div>
}
className="!m-0"
>
@@ -169,9 +191,7 @@ const DatabaseSettings = () => {
<ShimmeringLoader className="h-8 w-full col-span-8" delayIndex={i} />
</div>
))}
- {isError && (
- <AlertError error={error} subject="Failed to retrieve database settings" />
- )}
+ {isError && <AlertError error={error} subject="Failed to retrieve databases" />}
{isSuccess && (
<>
<Input
@@ -222,7 +242,11 @@ const DatabaseSettings = () => {
layout="horizontal"
disabled
readOnly
- value={'[The password you provided when you created this project]'}
+ value={
+ selectedDatabaseId !== projectRef
+ ? '[The password for your primary database]'
+ : '[The password you provided when you created this project]'
+ }
label="Password"
/>
</>
@@ -231,8 +255,6 @@ const DatabaseSettings = () => {
</Panel>
</section>
- <ResetDbPassword disabled={isLoading || isError} />
-
<section className="space-y-6">
<Panel
title={
@@ -374,6 +396,8 @@ const DatabaseSettings = () => {
</Panel.Content>
</Panel>
</section>
+
+ <ResetDbPassword disabled={isLoading || isError} />
</div>
<ConfirmDisableReadOnlyModeModal
diff --git a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
index 048babf74f9..81050b91d0b 100644
--- a/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Database/SSLConfiguration.tsx
@@ -131,41 +131,43 @@ const SSLConfiguration = () => {
{(isLoading || isSubmitting) && (
<IconLoader className="animate-spin" strokeWidth={1.5} size={16} />
)}
- <Tooltip.Root delayDuration={0}>
- <Tooltip.Trigger>
- <Toggle
- checked={isEnforced}
- disabled={
- isLoading ||
- isSubmitting ||
- !canUpdateSSLEnforcement ||
- !hasAccessToSSLEnforcement
- }
- onChange={toggleSSLEnforcement}
- />
- </Tooltip.Trigger>
- {(!canUpdateSSLEnforcement || !hasAccessToSSLEnforcement) && (
- <Tooltip.Portal>
- <Tooltip.Content align="center" side="bottom">
- <Tooltip.Arrow className="radix-tooltip-arrow" />
- <div
- className={[
- 'rounded bg-alternative py-1 px-2 leading-none shadow',
- 'border border-background w-[250px]',
- ].join(' ')}
- >
- <span className="text-xs text-foreground text-center flex items-center justify-center">
- {!canUpdateSSLEnforcement
- ? 'You need additional permissions to update SSL enforcement for your project'
- : !hasAccessToSSLEnforcement
- ? 'Your project does not have access to SSL enforcement'
- : ''}
- </span>
- </div>
- </Tooltip.Content>
- </Tooltip.Portal>
- )}
- </Tooltip.Root>
+ {isSuccess && (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger>
+ <Toggle
+ checked={isEnforced}
+ disabled={
+ isLoading ||
+ isSubmitting ||
+ !canUpdateSSLEnforcement ||
+ !hasAccessToSSLEnforcement
+ }
+ onChange={toggleSSLEnforcement}
+ />
+ </Tooltip.Trigger>
+ {(!canUpdateSSLEnforcement || !hasAccessToSSLEnforcement) && (
+ <Tooltip.Portal>
+ <Tooltip.Content align="center" side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-alternative py-1 px-2 leading-none shadow',
+ 'border border-background w-[250px]',
+ ].join(' ')}
+ >
+ <span className="text-xs text-foreground text-center flex items-center justify-center">
+ {!canUpdateSSLEnforcement
+ ? 'You need additional permissions to update SSL enforcement for your project'
+ : !hasAccessToSSLEnforcement
+ ? 'Your project does not have access to SSL enforcement'
+ : ''}
+ </span>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ )}
+ </Tooltip.Root>
+ )}
</div>
</FormSectionContent>
</FormSection>
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureActivity.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureActivity.tsx
index 9521c9ca9a4..276f0270476 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureActivity.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureActivity.tsx
@@ -35,8 +35,9 @@ const InfrastructureActivity = () => {
const { ref: projectRef } = useParams()
const organization = useSelectedOrganization()
const [dateRange, setDateRange] = useState<any>()
- const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>('1')
+ // [Joshen] Not for first iteration of read replicas
+ const [selectedDatabaseId, setSelectedDatabaseId] = useState<string>('1')
const readReplicasEnabled = useFlag('readReplicas')
const { data: subscription, isLoading: isLoadingSubscription } = useOrgSubscriptionQuery({
@@ -187,12 +188,12 @@ const InfrastructureActivity = () => {
</ScaffoldContainer>
<ScaffoldContainer className="sticky top-0 py-6 border-b bg-background z-10">
<div className="flex items-center gap-x-4">
- {readReplicasEnabled && (
+ {/* {readReplicasEnabled && (
<DatabaseSelector
selectedDatabaseId={selectedDatabaseId}
onChangeDatabaseId={setSelectedDatabaseId}
/>
- )}
+ )} */}
{!isLoadingSubscription && (
<>
<DateRangePicker
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx
index 9f157d34638..4413d7677b5 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx
@@ -1,41 +1,85 @@
import { useParams } from 'common'
import { useEffect, useState } from 'react'
-import { Listbox, SidePanel } from 'ui'
+import toast from 'react-hot-toast'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ Button,
+ IconAlertCircle,
+ Listbox,
+ SidePanel,
+} from 'ui'
+import { Region, useReadReplicaSetUpMutation } from 'data/read-replicas/replica-setup-mutation'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
-import { AVAILABLE_REPLICA_REGIONS } from './InstanceConfiguration.constants'
import { AWS_REGIONS, AWS_REGIONS_DEFAULT, AWS_REGIONS_KEYS, BASE_PATH } from 'lib/constants'
+import { AVAILABLE_REPLICA_REGIONS, AWS_REGIONS_VALUES } from './InstanceConfiguration.constants'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import Link from 'next/link'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useSelectedOrganization } from 'hooks'
// [Joshen] FYI this is purely for AWS only, need to update to support Fly eventually
interface DeployNewReplicaPanelProps {
visible: boolean
selectedDefaultRegion?: AWS_REGIONS_KEYS
+ onSuccess: () => void
onClose: () => void
}
const DeployNewReplicaPanel = ({
visible,
selectedDefaultRegion,
+ onSuccess,
onClose,
}: DeployNewReplicaPanelProps) => {
const { ref: projectRef } = useParams()
+ const org = useSelectedOrganization()
+ const { data } = useReadReplicasQuery({ projectRef })
const { data: addons, isSuccess } = useProjectAddonsQuery({ projectRef })
+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: org?.slug })
+ const { mutate: setUpReplica, isLoading: isSettingUp } = useReadReplicaSetUpMutation({
+ onSuccess: () => {
+ const region = AVAILABLE_REPLICA_REGIONS.find((r) => r.key === selectedRegion)?.name
+ toast.success(`Spinning up new replica in ${region ?? ' Unknown'}...`)
+ onSuccess()
+ onClose()
+ },
+ })
+
+ const isFreePlan = subscription?.plan.id === 'free'
+ const currentComputeAddon = addons?.selected_addons.find(
+ (addon) => addon.type === 'compute_instance'
+ )
+ const currentPitrAddon = addons?.selected_addons.find((addon) => addon.type === 'pitr')
+ const canDeployReplica =
+ !isFreePlan && currentComputeAddon !== undefined && currentPitrAddon !== undefined
+
const computeAddons =
addons?.available_addons.find((addon) => addon.type === 'compute_instance')?.variants ?? []
// Opting for useState temporarily as Listbox doesn't seem to work with react-hook-form yet
- const [defaultRegion] =
- Object.entries(AWS_REGIONS).find(([key, name]) => name === AWS_REGIONS_DEFAULT) ?? []
- const defaultCompute = computeAddons.find((option) => option.name === 'Small')?.identifier
+ const [defaultRegion] = Object.entries(AWS_REGIONS).find(
+ ([_, name]) => name === AWS_REGIONS_DEFAULT
+ ) ?? ['ap-southeast-1']
+ // Will be following the primary's instance size for the time being
+ const defaultCompute =
+ addons?.selected_addons.find((addon) => addon.type === 'compute_instance')?.variant
+ .identifier ?? 'ci_small'
- const [selectedRegion, setSelectedRegion] = useState(defaultRegion)
+ const [selectedRegion, setSelectedRegion] = useState<string>(defaultRegion)
const [selectedCompute, setSelectedCompute] = useState(defaultCompute)
const selectedComputeMeta = computeAddons.find((addon) => addon.identifier === selectedCompute)
const onSubmit = async () => {
- console.log('Deploy', { selectedRegion, selectedCompute })
- onClose()
+ const regionKey = AWS_REGIONS_VALUES[selectedRegion]
+ if (!projectRef) return console.error('Project is required')
+ if (!regionKey) return toast.error('Unable to deploy replica: Unsupported region selected')
+
+ const primary = data?.find((db) => db.identifier === projectRef)
+ setUpReplica({ projectRef, region: regionKey as Region, size: primary?.size ?? 't4g.small' })
}
useEffect(() => {
@@ -52,15 +96,57 @@ const DeployNewReplicaPanel = ({
return (
<SidePanel
visible={visible}
+ loading={isSettingUp}
onCancel={onClose}
onConfirm={() => onSubmit()}
+ confirmText="Deploy replica"
+ disabled={!canDeployReplica}
header="Deploy a new read replica"
>
<SidePanel.Content className="flex flex-col py-4 gap-y-8">
+ {!canDeployReplica && (
+ <Alert_Shadcn_>
+ <IconAlertCircle strokeWidth={2} />
+ <AlertTitle_Shadcn_>
+ Point in time recovery is required to deploy replicas
+ </AlertTitle_Shadcn_>
+ {isFreePlan ? (
+ <AlertDescription_Shadcn_>
+ To enable PITR, you may first upgrade your organization's plan to at least Pro, then
+ purchase the PITR add on for your project via the{' '}
+ <Link
+ href={`/project/${projectRef}/settings/addons?panel=pitr`}
+ className="text-brand"
+ >
+ project settings
+ </Link>
+ .
+ </AlertDescription_Shadcn_>
+ ) : (
+ <AlertDescription_Shadcn_>
+ Enable the add-on in your project's settings first before deploying read replicas.
+ </AlertDescription_Shadcn_>
+ )}
+ <AlertDescription_Shadcn_ className="mt-2">
+ <Button type="default">
+ <Link
+ href={
+ isFreePlan
+ ? `/org/${org?.slug}/billing?panel=subscriptionPlan`
+ : `/project/${projectRef}/settings/addons?panel=pitr`
+ }
+ >
+ {isFreePlan ? 'Upgrade to Pro' : 'Enable PITR add-on'}
+ </Link>
+ </Button>
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )}
<Listbox
size="small"
id="region"
name="region"
+ disabled={!canDeployReplica}
value={selectedRegion}
onChange={setSelectedRegion}
label="Select a region to deploy your read replica in"
@@ -84,12 +170,14 @@ const DeployNewReplicaPanel = ({
</Listbox>
<Listbox
+ disabled
size="small"
id="compute"
name="compute"
value={selectedCompute}
onChange={setSelectedCompute}
label="Select the instance size for your read replica"
+ descriptionText="Read replicas will be on the same instance size as your primary"
>
{computeAddons.map((option) => (
<Listbox.Option key={option.identifier} label={option.name} value={option.identifier}>
@@ -98,9 +186,9 @@ const DeployNewReplicaPanel = ({
))}
</Listbox>
- <p className="text-xs text-foreground-light">
+ {/* <p className="text-xs text-foreground-light">
Show some preview info on cost for deploying this replica here
- </p>
+ </p> */}
</SidePanel.Content>
</SidePanel>
)
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DropReplicaConfirmationModal.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DropReplicaConfirmationModal.tsx
new file mode 100644
index 00000000000..9a9dcb09ccf
--- /dev/null
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DropReplicaConfirmationModal.tsx
@@ -0,0 +1,76 @@
+import { useParams } from 'common'
+import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { useReadReplicaRemoveMutation } from 'data/read-replicas/replica-remove-mutation'
+import { Database } from 'data/read-replicas/replicas-query'
+import { formatDatabaseID } from 'data/read-replicas/replicas.utils'
+import toast from 'react-hot-toast'
+import {
+ AlertDescription_Shadcn_,
+ AlertTitle_Shadcn_,
+ Alert_Shadcn_,
+ IconAlertTriangle,
+ Modal,
+} from 'ui'
+
+interface DropReplicaConfirmationModalProps {
+ selectedReplica?: Database
+ onSuccess: () => void
+ onCancel: () => void
+}
+
+const DropReplicaConfirmationModal = ({
+ selectedReplica,
+ onSuccess,
+ onCancel,
+}: DropReplicaConfirmationModalProps) => {
+ const { ref: projectRef } = useParams()
+ const formattedId = formatDatabaseID(selectedReplica?.identifier ?? '')
+ const { mutateAsync: removeReadReplica } = useReadReplicaRemoveMutation({
+ onSuccess: () => {
+ toast.success(`Successfully removed read replica (ID: ${formattedId})`)
+ onSuccess()
+ onCancel()
+ },
+ })
+
+ const onConfirmRemove = async () => {
+ if (!projectRef) return console.error('Project is required')
+ if (selectedReplica === undefined) return toast.error('No replica selected')
+
+ await removeReadReplica({ projectRef, identifier: selectedReplica.identifier })
+ }
+
+ return (
+ <ConfirmationModal
+ danger
+ size="medium"
+ visible={selectedReplica !== undefined}
+ header={`Confirm to drop selected replica? (ID: ${formattedId})`}
+ buttonLabel="Drop replica"
+ buttonLoadingLabel="Dropping replica"
+ onSelectCancel={() => onCancel()}
+ onSelectConfirm={() => onConfirmRemove()}
+ >
+ <Modal.Content className="py-3">
+ <Alert_Shadcn_ variant="warning">
+ <IconAlertTriangle strokeWidth={2} />
+ <AlertTitle_Shadcn_>This action cannot be undone</AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ You may still deploy a new replica in this region thereafter
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ <div className="text-sm px-1 pt-4">
+ <p>Before deleting this replica, consider:</p>
+ <ul className="text-foreground-light py-1 list-disc mx-4 space-y-1">
+ <li>
+ Network traffic from this region may slow down, especially if you have no other
+ replicas in this region
+ </li>
+ </ul>
+ </div>
+ </Modal.Content>
+ </ConfirmationModal>
+ )
+}
+
+export default DropReplicaConfirmationModal
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts
index b784243d424..024ee86c02e 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants.ts
@@ -1,15 +1,5 @@
import { AWS_REGIONS, AWS_REGIONS_KEYS } from 'lib/constants'
-export interface DatabaseConfiguration {
- id: number
- type: 'PRIMARY' | 'READ_REPLICA'
- cloud_provider: 'AWS' | 'FLY'
- region: string
- size: string
- status: string
- inserted_at: string
-}
-
export interface Region {
key: AWS_REGIONS_KEYS
name: string
@@ -18,85 +8,10 @@ export interface Region {
}
// ReactFlow is scaling everything by the factor of 2
-export const NODE_WIDTH = 560
+export const NODE_WIDTH = 660
export const NODE_ROW_HEIGHT = 50
export const NODE_SEP = 20
-export const MOCK_DATABASES: DatabaseConfiguration[] = [
- {
- id: 1,
- type: 'PRIMARY',
- cloud_provider: 'AWS',
- region: 'ap-southeast-1b',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 2,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'ap-northeast-1',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 3,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'ap-southeast-1b',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 4,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'ap-northeast-2',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 5,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'eu-central-1',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 6,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'eu-central-1',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 7,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'ap-southeast-1',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
- {
- id: 8,
- type: 'READ_REPLICA',
- cloud_provider: 'AWS',
- region: 'ap-southeast-1',
- size: 't4g.micro',
- status: 'ACTIVE_HEALTHY',
- inserted_at: '2023-11-01 06:47:46.837002',
- },
-]
-
// [Joshen] Coordinates from https://github.com/jsonmaur/aws-regions/issues/11
const AWS_REGIONS_COORDINATES: { [key: string]: [number, number] } = {
SOUTHEAST_ASIA: [103.8, 1.37],
@@ -113,7 +28,7 @@ const AWS_REGIONS_COORDINATES: { [key: string]: [number, number] } = {
SOUTH_AMERICA: [-46.38, -23.34],
}
-const AWS_REGIONS_VALUES: { [key: string]: string } = {
+export const AWS_REGIONS_VALUES: { [key: string]: string } = {
SOUTHEAST_ASIA: 'ap-southeast-1',
NORTHEAST_ASIA: 'ap-northeast-1',
NORTHEAST_ASIA_2: 'ap-northeast-2',
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
index 7c3b21a30c6..539f54aeaa1 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.tsx
@@ -1,27 +1,21 @@
import { useParams } from 'common'
-import { partition } from 'lodash'
-import { Globe2, Network } from 'lucide-react'
+import { isEqual, partition } from 'lodash'
+import { Globe2, Loader2, Network } from 'lucide-react'
import { useTheme } from 'next-themes'
-import { useMemo, useState } from 'react'
+import { useEffect, useMemo, useRef, useState } from 'react'
import ReactFlow, { Background, Edge, ReactFlowProvider, useReactFlow } from 'reactflow'
import 'reactflow/dist/style.css'
-import {
- AlertDescription_Shadcn_,
- AlertTitle_Shadcn_,
- Alert_Shadcn_,
- Button,
- IconAlertTriangle,
- Modal,
-} from 'ui'
-
-import ConfirmationModal from 'components/ui/ConfirmationModal'
+import { Button } from 'ui'
+
+import AlertError from 'components/ui/AlertError'
+import { Database, useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import { useReadReplicasStatusesQuery } from 'data/read-replicas/replicas-status-query'
import { AWS_REGIONS_KEYS } from 'lib/constants'
import DeployNewReplicaPanel from './DeployNewReplicaPanel'
-import { DatabaseConfiguration, MOCK_DATABASES } from './InstanceConfiguration.constants'
+import DropReplicaConfirmationModal from './DropReplicaConfirmationModal'
import { addRegionNodes, generateNodes, getDagreGraphLayout } from './InstanceConfiguration.utils'
import { PrimaryNode, RegionNode, ReplicaNode } from './InstanceNode'
import MapView from './MapView'
-import ResizeReplicaPanel from './ResizeReplicaPanel'
// [Joshen] Just FYI, UI assumes single provider for primary + replicas
// [Joshen] Idea to visualize grouping based on region: https://reactflow.dev/examples/layout/sub-flows
@@ -31,30 +25,67 @@ const InstanceConfigurationUI = () => {
const reactFlow = useReactFlow()
const { resolvedTheme } = useTheme()
const { ref: projectRef } = useParams()
+ const numComingUp = useRef<number>()
const [view, setView] = useState<'flow' | 'map'>('flow')
const [showNewReplicaPanel, setShowNewReplicaPanel] = useState(false)
+ const [refetchInterval, setRefetchInterval] = useState<number | boolean>(10000)
const [newReplicaRegion, setNewReplicaRegion] = useState<AWS_REGIONS_KEYS>()
- const [selectedReplicaToResize, setSelectedReplicaToResize] = useState<DatabaseConfiguration>()
- const [selectedReplicaToDrop, setSelectedReplicaToDrop] = useState<DatabaseConfiguration>()
- const [selectedReplicaToRestart, setSelectedReplicaToRestart] = useState<DatabaseConfiguration>()
+ const [selectedReplicaToResize, setSelectedReplicaToResize] = useState<Database>()
+ const [selectedReplicaToDrop, setSelectedReplicaToDrop] = useState<Database>()
+ const [selectedReplicaToRestart, setSelectedReplicaToRestart] = useState<Database>()
+
+ const { data, error, refetch, isLoading, isError, isSuccess } = useReadReplicasQuery({
+ projectRef,
+ })
+ const [[primary], replicas] = useMemo(
+ () => partition(data ?? [], (db) => db.identifier === projectRef),
+ [data, projectRef]
+ )
+
+ useReadReplicasStatusesQuery(
+ { projectRef },
+ {
+ refetchInterval: refetchInterval as any,
+ refetchOnWindowFocus: false,
+ onSuccess: (data) => {
+ const comingUpReplicas = data.filter((db) => db.status === 'COMING_UP')
+ const hasTransientStatus = comingUpReplicas.length > 0
+
+ // If any replica's status has changed, refetch databases
+ if (numComingUp.current !== comingUpReplicas.length) {
+ numComingUp.current = comingUpReplicas.length
+ refetch()
+ }
+
+ // If all replicas are active healthy, stop fetching statuses
+ if (!hasTransientStatus) {
+ setRefetchInterval(false)
+ }
+ },
+ }
+ )
const backgroundPatternColor =
resolvedTheme === 'dark' ? 'rgba(255, 255, 255, 0.3)' : 'rgba(0, 0, 0, 0.4)'
- const [[primary], replicas] = partition(MOCK_DATABASES, (database) => database.type === 'PRIMARY')
-
- const nodes = generateNodes(MOCK_DATABASES, {
- onSelectRestartReplica: setSelectedReplicaToRestart,
- onSelectResizeReplica: setSelectedReplicaToResize,
- onSelectDropReplica: setSelectedReplicaToDrop,
- })
+ const nodes = useMemo(
+ () =>
+ isSuccess
+ ? generateNodes(primary, replicas, {
+ onSelectRestartReplica: setSelectedReplicaToRestart,
+ onSelectResizeReplica: setSelectedReplicaToResize,
+ onSelectDropReplica: setSelectedReplicaToDrop,
+ })
+ : [],
+ [isSuccess, primary, replicas]
+ )
const edges: Edge[] = replicas.map((database) => {
return {
- id: `${primary.id}-${database.id}`,
- source: `database-${primary.id}`,
- target: `database-${database.id}`,
+ id: `${primary.identifier}-${database.identifier}`,
+ source: primary.identifier,
+ target: database.identifier,
type: 'smoothstep',
animated: true,
}
@@ -73,115 +104,113 @@ const InstanceConfigurationUI = () => {
console.log('Restart replica', selectedReplicaToRestart)
}
+ // [Joshen] Just FYI this block is oddly triggering whenever we refocus on the viewport
+ // even if I change the dependency array to just data. Not blocker, just an area to optimize
+ useEffect(() => {
+ if (replicas.length > 0) {
+ const graph = getDagreGraphLayout(nodes, edges)
+ const { nodes: updatedNodes } = addRegionNodes(graph.nodes, graph.edges)
+ reactFlow.setNodes(updatedNodes)
+ reactFlow.setEdges(graph.edges)
+ }
+ }, [replicas])
+
return (
<>
- <div className="h-[500px] w-full relative">
- <div className="z-10 absolute top-4 right-4 flex items-center justify-center gap-x-2">
- <Button type="default" onClick={() => setShowNewReplicaPanel(true)}>
- Deploy a new replica
- </Button>
- <div className="flex items-center justify-center">
- <Button
- type="default"
- icon={<Network size={15} />}
- className={`rounded-r-none transition ${
- view === 'flow' ? 'opacity-100' : 'opacity-50'
- }`}
- onClick={() => setView('flow')}
- />
- <Button
- type="default"
- icon={<Globe2 size={15} />}
- className={`rounded-l-none transition ${
- view === 'map' ? 'opacity-100' : 'opacity-50'
- }`}
- onClick={() => setView('map')}
- />
- </div>
- </div>
- {view === 'flow' ? (
- <ReactFlow
- fitView
- fitViewOptions={{ minZoom: 0.9, maxZoom: 1 }}
- className="instance-configuration"
- zoomOnPinch={false}
- nodesDraggable={false}
- nodesConnectable={false}
- zoomOnDoubleClick={false}
- edgesFocusable={false}
- edgesUpdatable={false}
- defaultNodes={[]}
- defaultEdges={[]}
- nodeTypes={nodeTypes}
- onInit={() => {
- const graph = getDagreGraphLayout(nodes, edges)
- const xxx = addRegionNodes(graph.nodes, graph.edges)
- reactFlow.setNodes(xxx.nodes)
- reactFlow.setEdges(graph.edges)
- }}
- proOptions={{ hideAttribution: true }}
- >
- <Background color={backgroundPatternColor} />
- </ReactFlow>
- ) : (
- <MapView
- onSelectDeployNewReplica={(region) => {
- setNewReplicaRegion(region)
- setShowNewReplicaPanel(true)
- }}
- onSelectRestartReplica={setSelectedReplicaToRestart}
- onSelectResizeReplica={setSelectedReplicaToResize}
- onSelectDropReplica={setSelectedReplicaToDrop}
- />
+ <div
+ className={`h-[500px] w-full relative ${
+ isSuccess ? '' : 'flex items-center justify-center px-28'
+ }`}
+ >
+ {isLoading && <Loader2 className="animate-spin text-foreground-light" />}
+ {isError && <AlertError error={error} subject="Failed to retrieve replicas" />}
+ {isSuccess && (
+ <>
+ <div className="z-10 absolute top-4 right-4 flex items-center justify-center gap-x-2">
+ <Button type="default" onClick={() => setShowNewReplicaPanel(true)}>
+ Deploy a new replica
+ </Button>
+ <div className="flex items-center justify-center">
+ <Button
+ type="default"
+ icon={<Network size={15} />}
+ className={`rounded-r-none transition ${
+ view === 'flow' ? 'opacity-100' : 'opacity-50'
+ }`}
+ onClick={() => setView('flow')}
+ />
+ <Button
+ type="default"
+ icon={<Globe2 size={15} />}
+ className={`rounded-l-none transition ${
+ view === 'map' ? 'opacity-100' : 'opacity-50'
+ }`}
+ onClick={() => setView('map')}
+ />
+ </div>
+ </div>
+ {view === 'flow' ? (
+ <ReactFlow
+ fitView
+ fitViewOptions={{ minZoom: 0.9, maxZoom: 1 }}
+ className="instance-configuration"
+ zoomOnPinch={false}
+ nodesDraggable={false}
+ nodesConnectable={false}
+ zoomOnDoubleClick={false}
+ edgesFocusable={false}
+ edgesUpdatable={false}
+ defaultNodes={[]}
+ defaultEdges={[]}
+ nodeTypes={nodeTypes}
+ onInit={() => {
+ const graph = getDagreGraphLayout(nodes, edges)
+ const { nodes: updatedNodes } = addRegionNodes(graph.nodes, graph.edges)
+ reactFlow.setNodes(updatedNodes)
+ reactFlow.setEdges(graph.edges)
+ }}
+ proOptions={{ hideAttribution: true }}
+ >
+ <Background color={backgroundPatternColor} />
+ </ReactFlow>
+ ) : (
+ <MapView
+ onSelectDeployNewReplica={(region) => {
+ setNewReplicaRegion(region)
+ setShowNewReplicaPanel(true)
+ }}
+ onSelectRestartReplica={setSelectedReplicaToRestart}
+ onSelectResizeReplica={setSelectedReplicaToResize}
+ onSelectDropReplica={setSelectedReplicaToDrop}
+ />
+ )}
+ </>
)}
</div>
<DeployNewReplicaPanel
visible={showNewReplicaPanel}
selectedDefaultRegion={newReplicaRegion}
+ onSuccess={() => setRefetchInterval(10000)}
onClose={() => {
setNewReplicaRegion(undefined)
setShowNewReplicaPanel(false)
}}
/>
- <ResizeReplicaPanel
+ <DropReplicaConfirmationModal
+ selectedReplica={selectedReplicaToDrop}
+ onSuccess={() => setRefetchInterval(10000)}
+ onCancel={() => setSelectedReplicaToDrop(undefined)}
+ />
+
+ {/* <ResizeReplicaPanel
visible={selectedReplicaToResize !== undefined}
selectedReplica={selectedReplicaToResize}
onClose={() => setSelectedReplicaToResize(undefined)}
- />
-
- <ConfirmationModal
- danger
- size="medium"
- visible={selectedReplicaToDrop !== undefined}
- header="Confirm to drop selected replica?"
- buttonLabel="Drop replica"
- buttonLoadingLabel="Dropping replica"
- onSelectCancel={() => setSelectedReplicaToDrop(undefined)}
- onSelectConfirm={() => onConfirmDropReplica()}
- >
- <Modal.Content className="py-3">
- <Alert_Shadcn_ variant="warning">
- <IconAlertTriangle strokeWidth={2} />
- <AlertTitle_Shadcn_>This action cannot be undone</AlertTitle_Shadcn_>
- <AlertDescription_Shadcn_>
- You may still deploy a new replica in this region thereafter
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- <div className="text-sm px-1 pt-4">
- <p>Before deleting this replica, consider:</p>
- <ul className="text-foreground-light py-1 list-disc mx-4 space-y-1">
- <li>
- Network traffic from this region may slow down, especially if you have no other
- replicas in this region
- </li>
- </ul>
- </div>
- </Modal.Content>
- </ConfirmationModal>
+ /> */}
- <ConfirmationModal
+ {/* <ConfirmationModal
size="medium"
visible={selectedReplicaToRestart !== undefined}
header="Confirm to restart selected replica?"
@@ -202,7 +231,7 @@ const InstanceConfigurationUI = () => {
Are you sure you want to restart this replica (ID: {selectedReplicaToRestart?.id}) now?{' '}
</p>
</Modal.Content>
- </ConfirmationModal>
+ </ConfirmationModal> */}
</>
)
}
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
index c470ef8063a..0d9a01277f5 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.utils.ts
@@ -3,33 +3,52 @@ import { Edge, Node, Position } from 'reactflow'
import {
AVAILABLE_REPLICA_REGIONS,
- DatabaseConfiguration,
NODE_ROW_HEIGHT,
NODE_SEP,
NODE_WIDTH,
} from './InstanceConfiguration.constants'
import { groupBy } from 'lodash'
+import { Database } from 'data/read-replicas/replicas-query'
export const generateNodes = (
- databases: DatabaseConfiguration[],
+ primary: Database,
+ replicas: Database[],
{
onSelectRestartReplica,
onSelectResizeReplica,
onSelectDropReplica,
}: {
- onSelectRestartReplica: (database: DatabaseConfiguration) => void
- onSelectResizeReplica: (database: DatabaseConfiguration) => void
- onSelectDropReplica: (database: DatabaseConfiguration) => void
+ onSelectRestartReplica: (database: Database) => void
+ onSelectResizeReplica: (database: Database) => void
+ onSelectDropReplica: (database: Database) => void
}
): Node[] => {
const position = { x: 0, y: 0 }
- const replicas = databases.filter((d) => d.type === 'READ_REPLICA')
const regions = groupBy(replicas, (d) => {
const region = AVAILABLE_REPLICA_REGIONS.find((region) => d.region.includes(region.region))
return region?.key
})
- const databaseNodes: Node[] = databases
+ const primaryRegion = AVAILABLE_REPLICA_REGIONS.find((region) =>
+ primary.region.includes(region.region)
+ )
+ const primaryNode: Node = {
+ position,
+ id: primary.identifier,
+ type: 'PRIMARY',
+ data: {
+ id: primary.identifier,
+ region: primaryRegion,
+ provider: primary.cloud_provider,
+ inserted_at: primary.inserted_at,
+ computeSize: primary.size,
+ status: primary.status,
+ numReplicas: replicas.length,
+ numRegions: Object.keys(regions).length,
+ },
+ }
+
+ const replicaNodes: Node[] = replicas
.sort((a, b) => (a.region > b.region ? 1 : -1))
.map((database) => {
const region = AVAILABLE_REPLICA_REGIONS.find((region) =>
@@ -38,33 +57,23 @@ export const generateNodes = (
return {
position,
- id: `database-${database.id}`,
- type: database.type,
+ id: database.identifier,
+ type: 'READ_REPLICA',
data: {
- id: database.id,
+ id: database.identifier,
region,
- label: database.type === 'PRIMARY' ? 'Primary Database' : 'Read Replica',
provider: database.cloud_provider,
inserted_at: database.inserted_at,
computeSize: database.size,
- ...(database.type === 'READ_REPLICA'
- ? {
- onSelectRestartReplica: () => onSelectRestartReplica(database),
- onSelectResizeReplica: () => onSelectResizeReplica(database),
- onSelectDropReplica: () => onSelectDropReplica(database),
- }
- : {}),
- ...(database.type === 'PRIMARY'
- ? {
- numReplicas: replicas.length,
- numRegions: Object.keys(regions).length,
- }
- : {}),
+ status: database.status,
+ onSelectRestartReplica: () => onSelectRestartReplica(database),
+ onSelectResizeReplica: () => onSelectResizeReplica(database),
+ onSelectDropReplica: () => onSelectDropReplica(database),
},
}
})
- return [...databaseNodes]
+ return [primaryNode, ...replicaNodes]
}
export const getDagreGraphLayout = (nodes: Node[], edges: Edge[]) => {
@@ -123,7 +132,7 @@ export const addRegionNodes = (nodes: Node[], edges: Edge[]) => {
const regionNode: Node = {
id: key,
position: { x: minX - 10, y: minY - 10 },
- width: maxX - minX,
+ width: maxX - minX + NODE_WIDTH / 2,
type: 'REGION',
data: { region, numReplicas: value.length },
}
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx
index 984820f9c75..1eba1d214fb 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceNode.tsx
@@ -13,15 +13,16 @@ import {
IconMoreVertical,
} from 'ui'
-import { BASE_PATH } from 'lib/constants'
+import { BASE_PATH, PROJECT_STATUS } from 'lib/constants'
import { NODE_SEP, NODE_WIDTH, Region } from './InstanceConfiguration.constants'
+import { formatDatabaseID } from 'data/read-replicas/replicas.utils'
interface NodeData {
id: string
- label: string
provider: string
region: Region
computeSize: string
+ status: string
inserted_at: string
}
@@ -37,7 +38,7 @@ interface ReplicaNodeData extends NodeData {
}
export const PrimaryNode = ({ data }: NodeProps<PrimaryNodeData>) => {
- const { label, provider, region, computeSize, numReplicas, numRegions } = data
+ const { provider, region, computeSize, numReplicas, numRegions } = data
return (
<>
@@ -51,7 +52,7 @@ export const PrimaryNode = ({ data }: NodeProps<PrimaryNodeData>) => {
<Database size={16} />
</div>
<div className="flex flex-col gap-y-0.5">
- <p className="text-sm">{label}</p>
+ <p className="text-sm">Primary Database</p>
<p className="flex items-center gap-x-1">
<span className="text-xs text-foreground-light">{region.name}</span>
</p>
@@ -71,18 +72,25 @@ export const PrimaryNode = ({ data }: NodeProps<PrimaryNodeData>) => {
{numReplicas > 0 && (
<div className="border-t p-3 py-2">
<p className="text-sm text-foreground-light">
- <span className="text-foreground">{numReplicas} replicas</span> deployed across{' '}
- <span className="text-foreground">{numRegions} regions</span>
+ <span className="text-foreground">
+ {numReplicas} replica{numReplicas > 1 ? 's' : ''}
+ </span>{' '}
+ deployed across{' '}
+ <span className="text-foreground">
+ {numRegions} region{numRegions > 1 ? 's' : ''}
+ </span>
</p>
</div>
)}
</div>
- <Handle
- type="source"
- id="handle-b"
- position={Position.Bottom}
- style={{ background: 'transparent' }}
- />
+ {numReplicas > 0 && (
+ <Handle
+ type="source"
+ id="handle-b"
+ position={Position.Bottom}
+ style={{ background: 'transparent' }}
+ />
+ )}
</>
)
}
@@ -90,10 +98,10 @@ export const PrimaryNode = ({ data }: NodeProps<PrimaryNodeData>) => {
export const ReplicaNode = ({ data }: NodeProps<ReplicaNodeData>) => {
const {
id,
- label,
provider,
region,
computeSize,
+ status,
inserted_at,
onSelectRestartReplica,
onSelectResizeReplica,
@@ -120,16 +128,19 @@ export const ReplicaNode = ({ data }: NodeProps<ReplicaNodeData>) => {
</div>
<div className="flex flex-col gap-y-0.5">
<div className="flex items-center gap-x-2">
- <p className="text-sm">
- {label} {id}
+ <p className="text-sm truncate">
+ Replica {id.length > 0 && `(ID: ${formatDatabaseID(id)})`}
</p>
- {/* [Joshen] Some status indication perhaps */}
- <Badge color="green">Healthy</Badge>
+ {status === PROJECT_STATUS.ACTIVE_HEALTHY ? (
+ <Badge color="green">Healthy</Badge>
+ ) : status === PROJECT_STATUS.COMING_UP ? (
+ <Badge color="slate">Coming up</Badge>
+ ) : (
+ <Badge color="amber">Unhealthy</Badge>
+ )}
</div>
<div className="my-0.5">
- <p className="flex text-xs text-foreground-light items-center gap-x-1">
- {region.name}
- </p>
+ <p className="text-xs text-foreground-light">{region.name}</p>
<p className="flex text-xs text-foreground-light items-center gap-x-1">
<span>{provider}</span>
<span>•</span>
@@ -150,12 +161,12 @@ export const ReplicaNode = ({ data }: NodeProps<ReplicaNodeData>) => {
View connection string
</Link>
</DropdownMenuItem>
- <DropdownMenuItem className="gap-x-2" onClick={() => onSelectRestartReplica()}>
+ {/* <DropdownMenuItem className="gap-x-2" onClick={() => onSelectRestartReplica()}>
Restart replica
- </DropdownMenuItem>
- <DropdownMenuItem className="gap-x-2" onClick={() => onSelectResizeReplica()}>
+ </DropdownMenuItem> */}
+ {/* <DropdownMenuItem className="gap-x-2" onClick={() => onSelectResizeReplica()}>
Resize replica
- </DropdownMenuItem>
+ </DropdownMenuItem> */}
<div className="border-t" />
<DropdownMenuItem className="gap-x-2" onClick={() => onSelectDropReplica()}>
Drop replica
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx
index 023cdf06b62..15573e726f2 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/MapView.tsx
@@ -22,21 +22,19 @@ import {
ScrollArea,
} from 'ui'
-import { AWS_REGIONS_KEYS, BASE_PATH } from 'lib/constants'
-import {
- AVAILABLE_REPLICA_REGIONS,
- DatabaseConfiguration,
- MOCK_DATABASES,
-} from './InstanceConfiguration.constants'
+import { AWS_REGIONS_KEYS, BASE_PATH, PROJECT_STATUS } from 'lib/constants'
+import { AVAILABLE_REPLICA_REGIONS } from './InstanceConfiguration.constants'
import GeographyData from './MapData.json'
+import { Database, useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import { formatDatabaseID } from 'data/read-replicas/replicas.utils'
// [Joshen] Foresee that we'll skip this view for initial launch
interface MapViewProps {
onSelectDeployNewReplica: (region: AWS_REGIONS_KEYS) => void
- onSelectRestartReplica: (database: DatabaseConfiguration) => void
- onSelectResizeReplica: (database: DatabaseConfiguration) => void
- onSelectDropReplica: (database: DatabaseConfiguration) => void
+ onSelectRestartReplica: (database: Database) => void
+ onSelectResizeReplica: (database: Database) => void
+ onSelectDropReplica: (database: Database) => void
}
const MapView = ({
@@ -47,7 +45,7 @@ const MapView = ({
}: MapViewProps) => {
const { ref } = useParams()
const [mount, setMount] = useState(false)
- const [zoom, setZoom] = useState<number>(1)
+ const [zoom, setZoom] = useState<number>(1.5)
const [center, setCenter] = useState<[number, number]>([14, 7])
const [tooltip, setTooltip] = useState<{
x: number
@@ -56,7 +54,10 @@ const MapView = ({
network?: any
}>()
- const [[primary], replicas] = partition(MOCK_DATABASES, (database) => database.type === 'PRIMARY')
+ const { data } = useReadReplicasQuery({ projectRef: ref })
+ const databases = data ?? []
+ const [[primary], replicas] = partition(databases, (db) => db.identifier === ref)
+
const primaryCoordinates = AVAILABLE_REPLICA_REGIONS.find((region) =>
primary.region.includes(region.region)
)?.coordinates ?? [0, 0]
@@ -66,16 +67,17 @@ const MapView = ({
const selectedRegionKey =
AVAILABLE_REPLICA_REGIONS.find((region) => region.coordinates === center)?.region ?? ''
- const showRegionDetails = zoom === 1.5 && selectedRegionKey !== undefined
+ const showRegionDetails = zoom === 2.0 && selectedRegionKey !== undefined
const selectedRegion = AVAILABLE_REPLICA_REGIONS.find(
(region) => region.region === selectedRegionKey
)
const databasesInSelectedRegion = useMemo(
() =>
- MOCK_DATABASES.filter((database) => database.region.includes(selectedRegionKey))
- .sort((a, b) => (a.id > b.id ? 1 : 0))
- .sort((database) => (database.type === 'PRIMARY' ? -1 : 0)),
- [selectedRegionKey]
+ databases
+ .filter((database) => database.region.includes(selectedRegionKey))
+ .sort((a, b) => (a.inserted_at > b.inserted_at ? 1 : 0))
+ .sort((database) => (database.identifier === ref ? -1 : 0)),
+ [ref, selectedRegionKey]
)
useEffect(() => {
@@ -83,14 +85,14 @@ const MapView = ({
}, [])
return (
- <div className="bg-background">
- <ComposableMap projectionConfig={{ scale: 140 }} height={354}>
+ <div className="bg-background h-[500px]">
+ <ComposableMap projectionConfig={{ scale: 155 }} className="w-full h-full">
<ZoomableGroup
className={mount ? 'transition-all duration-300' : ''}
center={center}
zoom={zoom}
- minZoom={1}
- maxZoom={1.5}
+ minZoom={1.5}
+ maxZoom={2.0}
filterZoomEvent={({ constructor: { name } }) =>
!['MouseEvent', 'WheelEvent'].includes(name)
}
@@ -117,7 +119,7 @@ const MapView = ({
if (coordinates !== primaryCoordinates) {
return (
<Line
- key={`line-${database.id}-${primary.id}`}
+ key={`line-${database.identifier}-${primary.identifier}`}
from={coordinates}
to={primaryCoordinates}
stroke="white"
@@ -134,15 +136,15 @@ const MapView = ({
})}
{AVAILABLE_REPLICA_REGIONS.map((region) => {
- const databases =
- MOCK_DATABASES.filter((database) => database.region.includes(region.region)) ?? []
+ const dbs =
+ databases.filter((database) => database.region.includes(region.region)) ?? []
const coordinates = AVAILABLE_REPLICA_REGIONS.find(
(r) => r.region === region.region
)?.coordinates
- const hasNoDatabases = databases.length === 0
- const hasPrimary = databases.some((database) => database.type === 'PRIMARY')
- const replicas = databases.filter((database) => database.type === 'READ_REPLICA') ?? []
+ const hasNoDatabases = dbs.length === 0
+ const hasPrimary = dbs.some((database) => database.identifier === ref)
+ const replicas = dbs.filter((database) => database.identifier !== ref) ?? []
return (
<Marker
@@ -151,7 +153,7 @@ const MapView = ({
onMouseEnter={(event) =>
setTooltip({
x: event.clientX,
- y: event.clientY,
+ y: event.clientY + 20,
region: {
key: region.key,
country: region.name,
@@ -159,7 +161,9 @@ const MapView = ({
? undefined
: hasPrimary
? `Primary Database${
- replicas.length > 0 ? ` + ${replicas.length} replicas` : ''
+ replicas.length > 0
+ ? ` + ${replicas.length} replica${replicas.length > 1 ? 's' : ''} `
+ : ''
}`
: `${replicas.length} Read Replica${
replicas.length > 1 ? 's' : ''
@@ -171,7 +175,7 @@ const MapView = ({
onClick={() => {
if (coordinates) {
setCenter(coordinates)
- setZoom(1.5)
+ setZoom(2.0)
}
}}
>
@@ -247,22 +251,31 @@ const MapView = ({
return (
<li
- key={database.id}
+ key={database.identifier}
className="text-sm px-4 py-2 flex items-center justify-between"
>
<div className="flex flex-col gap-y-1">
<p className="flex items-center gap-x-2">
- {database.type === 'PRIMARY'
+ {database.identifier === ref
? 'Primary Database'
- : `Read Replica (ID: ${database.id})`}
- {database.type === 'READ_REPLICA' && <Badge color="green">Healthy</Badge>}
+ : `Read Replica ${
+ database.identifier.length > 0 &&
+ `(ID: ${formatDatabaseID(database.identifier)})`
+ }`}
+ {database.status === PROJECT_STATUS.ACTIVE_HEALTHY ? (
+ <Badge color="green">Healthy</Badge>
+ ) : database.status === PROJECT_STATUS.COMING_UP ? (
+ <Badge color="slate">Coming up</Badge>
+ ) : (
+ <Badge color="amber">Unhealthy</Badge>
+ )}
</p>
<p className="text-xs text-foreground-light">AWS • {database.size}</p>
- {database.type === 'READ_REPLICA' && (
+ {database.identifier !== ref && (
<p className="text-xs text-foreground-light">Created on: {created}</p>
)}
</div>
- {database.type === 'READ_REPLICA' && (
+ {database.identifier !== ref && (
<DropdownMenu modal={false}>
<DropdownMenuTrigger asChild>
<Button type="text" icon={<IconMoreVertical />} className="px-1" />
@@ -270,12 +283,12 @@ const MapView = ({
<DropdownMenuContent className="p-0 w-40" side="bottom" align="end">
<DropdownMenuItem className="gap-x-2">
<Link
- href={`/project/${ref}/settings/database?connectionString=${database.id}`}
+ href={`/project/${ref}/settings/database?connectionString=${database.identifier}`}
>
View connection string
</Link>
</DropdownMenuItem>
- <DropdownMenuItem
+ {/* <DropdownMenuItem
className="gap-x-2"
onClick={() => onSelectRestartReplica(database)}
>
@@ -286,7 +299,7 @@ const MapView = ({
onClick={() => onSelectResizeReplica(database)}
>
Resize replica
- </DropdownMenuItem>
+ </DropdownMenuItem> */}
<div className="border-t" />
<DropdownMenuItem
className="gap-x-2"
@@ -316,7 +329,7 @@ const MapView = ({
type="default"
onClick={() => {
setCenter([14, 7])
- setZoom(1)
+ setZoom(1.5)
}}
>
Close
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/ResizeReplicaPanel.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/ResizeReplicaPanel.tsx
index 5de1b1f91c6..85042b224ce 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/ResizeReplicaPanel.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/ResizeReplicaPanel.tsx
@@ -3,14 +3,15 @@ import { useEffect, useState } from 'react'
import { Listbox, SidePanel } from 'ui'
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
-import { AVAILABLE_REPLICA_REGIONS, DatabaseConfiguration } from './InstanceConfiguration.constants'
+import { AVAILABLE_REPLICA_REGIONS } from './InstanceConfiguration.constants'
import { AWS_REGIONS, AWS_REGIONS_DEFAULT, AWS_REGIONS_KEYS, BASE_PATH } from 'lib/constants'
+import { Database } from 'data/read-replicas/replicas-query'
// [Joshen] FYI this is purely for AWS only, need to update to support Fly eventually
interface ResizeReplicaPanelProps {
visible: boolean
- selectedReplica?: DatabaseConfiguration
+ selectedReplica?: Database
onClose: () => void
}
@@ -43,7 +44,7 @@ const ResizeReplicaPanel = ({ visible, selectedReplica, onClose }: ResizeReplica
visible={visible}
onCancel={onClose}
onConfirm={() => onSubmit()}
- header={`Resize read replica (ID: ${selectedReplica?.id})`}
+ header={`Resize read replica (ID: ${selectedReplica?.identifier})`}
>
<SidePanel.Content className="flex flex-col py-4 gap-y-8">
<div className="flex flex-col gap-y-1">
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
index 1065e685a1e..dffbeb86837 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureInfo.tsx
@@ -13,6 +13,7 @@ import {
import AlertError from 'components/ui/AlertError'
import { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
import { useProjectUpgradeEligibilityQuery } from 'data/config/project-upgrade-eligibility-query'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
import { useFlag, useIsFeatureEnabled } from 'hooks'
import {
AlertDescription_Shadcn_,
@@ -40,6 +41,7 @@ const InfrastructureInfo = () => {
} = useProjectUpgradeEligibilityQuery({
projectRef: ref,
})
+ const { data: databases } = useReadReplicasQuery({ projectRef: ref })
const { current_app_version, latest_app_version, requires_manual_intervention } = data || {}
const isOnLatestVersion = current_app_version === latest_app_version
const currentPgVersion = (current_app_version ?? '').split('supabase-postgres-')[1]
@@ -47,6 +49,7 @@ const InfrastructureInfo = () => {
const showDbUpgrades = useFlag('databaseUpgrades')
const readReplicasEnabled = useFlag('readReplicas')
+ const hasReadReplicas = (databases ?? []).length > 1
const subject = 'Request%20for%20Postgres%20upgrade%20for%20project'
const message = `Upgrade information:%0A• Manual intervention reason: ${requires_manual_intervention}`
@@ -145,7 +148,18 @@ const InfrastructureInfo = () => {
),
]}
/>
- {showDbUpgrades && data?.eligible && <ProjectUpgradeAlert />}
+ {showDbUpgrades && data?.eligible && !hasReadReplicas && <ProjectUpgradeAlert />}
+ {showDbUpgrades && data.eligible && hasReadReplicas && (
+ <Alert_Shadcn_>
+ <AlertTitle_Shadcn_>
+ A new version of Postgres is available for your project
+ </AlertTitle_Shadcn_>
+ <AlertDescription_Shadcn_>
+ You will need to remove all read replicas first prior to upgrading your
+ Postgrest version to the latest available ({latestPgVersion}).
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+ )}
{showDbUpgrades && !data?.eligible && data?.requires_manual_intervention && (
<Alert_Shadcn_ title="A new version of Postgres is available for your project">
<AlertTitle_Shadcn_>
diff --git a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/BreadcrumbsView.tsx b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/BreadcrumbsView.tsx
index 9e75f465172..7b0dcd2302a 100644
--- a/apps/studio/components/layouts/ProjectLayout/LayoutHeader/BreadcrumbsView.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/LayoutHeader/BreadcrumbsView.tsx
@@ -9,24 +9,8 @@ const BreadcrumbsView = ({ defaultValue: breadcrumbs }: BreadcrumbsViewProps) =>
return (
<>
{breadcrumbs?.length
- ? breadcrumbs.map((breadcrumb: any) => (
+ ? breadcrumbs.map((breadcrumb: any, idx: number) => (
<Fragment key={breadcrumb.key}>
- <span className="text-border-stronger">
- <svg
- viewBox="0 0 24 24"
- width="16"
- height="16"
- stroke="currentColor"
- strokeWidth="1"
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- shapeRendering="geometricPrecision"
- >
- <path d="M16 3.549L7.12 20.600"></path>
- </svg>
- </span>
-
<a
onClick={breadcrumb.onClick || (() => {})}
className={`text-gray-1100 block px-2 py-1 text-xs leading-5 focus:bg-gray-100 focus:text-gray-900 focus:outline-none ${
@@ -35,6 +19,23 @@ const BreadcrumbsView = ({ defaultValue: breadcrumbs }: BreadcrumbsViewProps) =>
>
{breadcrumb.label}
</a>
+ {idx !== breadcrumbs.length - 1 && (
+ <span className="text-border-stronger">
+ <svg
+ viewBox="0 0 24 24"
+ width="16"
+ height="16"
+ stroke="currentColor"
+ strokeWidth="1"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ shapeRendering="geometricPrecision"
+ >
+ <path d="M16 3.549L7.12 20.600"></path>
+ </svg>
+ </span>
+ )}
</Fragment>
))
: null}
diff --git a/apps/studio/components/ui/DatabaseSelector.tsx b/apps/studio/components/ui/DatabaseSelector.tsx
index 1933566f343..8ce9635066f 100644
--- a/apps/studio/components/ui/DatabaseSelector.tsx
+++ b/apps/studio/components/ui/DatabaseSelector.tsx
@@ -1,28 +1,41 @@
-import { MOCK_DATABASES } from 'components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants'
+import { useParams } from 'common'
import { useState } from 'react'
import {
- Popover_Shadcn_,
- PopoverTrigger_Shadcn_,
Button,
- IconChevronDown,
- PopoverContent_Shadcn_,
- Command_Shadcn_,
- CommandList_Shadcn_,
CommandGroup_Shadcn_,
- ScrollArea,
CommandItem_Shadcn_,
+ CommandList_Shadcn_,
+ Command_Shadcn_,
IconCheck,
+ IconChevronDown,
+ PopoverContent_Shadcn_,
+ PopoverTrigger_Shadcn_,
+ Popover_Shadcn_,
+ ScrollArea,
+ cn,
} from 'ui'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import { formatDatabaseID, formatDatabaseRegion } from 'data/read-replicas/replicas.utils'
+
interface DatabaseSelectorProps {
- selectedDatabaseId: string
+ selectedDatabaseId?: string
+ variant?: 'regular' | 'connected-on-right' | 'connected-on-left' | 'connected-on-both'
onChangeDatabaseId: (id: string) => void
}
-const DatabaseSelector = ({ selectedDatabaseId, onChangeDatabaseId }: DatabaseSelectorProps) => {
+const DatabaseSelector = ({
+ selectedDatabaseId,
+ variant = 'regular',
+ onChangeDatabaseId,
+}: DatabaseSelectorProps) => {
+ const { ref: projectRef } = useParams()
const [open, setOpen] = useState(false)
- const databases = MOCK_DATABASES.sort((a, b) => (a.id > b.id ? 1 : -1))
- const selectedDatabase = databases.find((db) => db.id.toString() === selectedDatabaseId)
+ const { data } = useReadReplicasQuery({ projectRef })
+ const databases = data ?? []
+ const selectedDatabase = databases.find((db) => db.identifier === selectedDatabaseId)
+ const selectedDatabaseRegion = formatDatabaseRegion(selectedDatabase?.region ?? '')
+ const formattedDatabaseId = formatDatabaseID(selectedDatabaseId ?? '')
return (
<Popover_Shadcn_ open={open} onOpenChange={setOpen} modal={false}>
@@ -30,47 +43,58 @@ const DatabaseSelector = ({ selectedDatabaseId, onChangeDatabaseId }: DatabaseSe
<div className="flex items-center space-x-2 cursor-pointer">
<Button
type="default"
- className="pr-2"
+ className={cn(
+ 'pr-2',
+ variant === 'connected-on-right' && 'rounded-r-none',
+ variant === 'connected-on-left' && 'rounded-l-none border-l-0',
+ variant === 'connected-on-both' && 'rounded-none border-x-0'
+ )}
iconRight={
<IconChevronDown className="text-foreground-light" strokeWidth={2} size={12} />
}
>
Source:{' '}
<span className="capitalize">
- {(selectedDatabase?.type ?? '').split('_').join(' ').toLowerCase()}
- {selectedDatabase?.type === 'PRIMARY' && ' database'}
+ {selectedDatabase?.identifier === projectRef ? 'Primary database' : 'Read replica'}
</span>{' '}
- {selectedDatabase?.type === 'READ_REPLICA' && <span>(ID: {selectedDatabase?.id})</span>}
+ {selectedDatabase?.identifier !== projectRef && (
+ <span>
+ ({selectedDatabaseRegion} - {formattedDatabaseId})
+ </span>
+ )}
</Button>
</div>
</PopoverTrigger_Shadcn_>
- <PopoverContent_Shadcn_ className="p-0 w-48" side="bottom" align="end">
+ <PopoverContent_Shadcn_ className="p-0 w-64" side="bottom" align="end">
<Command_Shadcn_>
<CommandList_Shadcn_>
<CommandGroup_Shadcn_>
<ScrollArea className={(databases || []).length > 7 ? 'h-[210px]' : ''}>
{databases?.map((database) => {
+ const region = formatDatabaseRegion(database.region)
+ const id = formatDatabaseID(database.identifier)
+
return (
<CommandItem_Shadcn_
- key={database.id}
- value={database.id.toString()}
+ key={database.identifier}
+ value={database.identifier}
className="cursor-pointer w-full"
onSelect={() => {
- onChangeDatabaseId(database.id.toString())
+ onChangeDatabaseId(database.identifier)
setOpen(false)
}}
onClick={() => {
- onChangeDatabaseId(database.id.toString())
+ onChangeDatabaseId(database.identifier)
setOpen(false)
}}
>
<div className="w-full flex items-center justify-between">
<p>
- {database.type === 'PRIMARY'
+ {database.identifier === projectRef
? 'Primary database'
- : `Read replica (ID: ${database.id})`}
+ : `Read replica (${region} - ${id})`}
</p>
- {database.id.toString() === selectedDatabaseId && <IconCheck />}
+ {database.identifier === selectedDatabaseId && <IconCheck />}
</div>
</CommandItem_Shadcn_>
)
diff --git a/apps/studio/data/api.d.ts b/apps/studio/data/api.d.ts
index 99b8f213e87..b83418de24d 100644
--- a/apps/studio/data/api.d.ts
+++ b/apps/studio/data/api.d.ts
@@ -467,6 +467,14 @@ export interface paths {
/** Gets daily project stats */
get: operations['DailyStatsController_getDailyStats']
}
+ '/platform/projects/{ref}/databases': {
+ /** Gets non-removed databases of a specified project */
+ get: operations['DatabasesController_getDatabases']
+ }
+ '/platform/projects/{ref}/databases-statuses': {
+ /** Gets status of all databases within a project */
+ get: operations['DatabasesStatusesController_getStatus']
+ }
'/platform/projects/{ref}/db-password': {
/** Updates the database password */
patch: operations['DbPasswordController_updatePassword']
@@ -1213,6 +1221,14 @@ export interface paths {
/** Gets daily project stats */
get: operations['DailyStatsController_getDailyStats']
}
+ '/v0/projects/{ref}/databases': {
+ /** Gets non-removed databases of a specified project */
+ get: operations['DatabasesController_getDatabases']
+ }
+ '/v0/projects/{ref}/databases-statuses': {
+ /** Gets status of all databases within a project */
+ get: operations['DatabasesStatusesController_getStatus']
+ }
'/v0/projects/{ref}/db-password': {
/** Updates the database password */
patch: operations['DbPasswordController_updatePassword']
@@ -3549,6 +3565,45 @@ export interface components {
content?: Record<string, never>
owner_id?: number
}
+ DatabaseDetailResponse: {
+ db_port: number
+ db_name: string
+ db_user: string
+ restUrl: string
+ db_host: string
+ connectionString: string
+ identifier: string
+ inserted_at: string
+ /** @enum {string} */
+ status:
+ | 'ACTIVE_HEALTHY'
+ | 'ACTIVE_UNHEALTHY'
+ | 'COMING_UP'
+ | 'GOING_DOWN'
+ | 'INIT_FAILED'
+ | 'REMOVED'
+ | 'RESTORING'
+ | 'UNKNOWN'
+ | 'UPGRADING'
+ size: string
+ region: string
+ /** @enum {string} */
+ cloud_provider: 'AWS' | 'FLY'
+ }
+ DatabaseStatusResponse: {
+ identifier: string
+ /** @enum {string} */
+ status:
+ | 'ACTIVE_HEALTHY'
+ | 'ACTIVE_UNHEALTHY'
+ | 'COMING_UP'
+ | 'GOING_DOWN'
+ | 'INIT_FAILED'
+ | 'REMOVED'
+ | 'RESTORING'
+ | 'UNKNOWN'
+ | 'UPGRADING'
+ }
UpdatePasswordBody: {
password: string
}
@@ -8408,6 +8463,42 @@ export interface operations {
}
}
}
+ /** Gets non-removed databases of a specified project */
+ DatabasesController_getDatabases: {
+ parameters: {
+ path: {
+ /** @description Project ref */
+ ref: string
+ }
+ }
+ responses: {
+ 200: {
+ content: {
+ 'application/json': components['schemas']['DatabaseDetailResponse'][]
+ }
+ }
+ }
+ }
+ /** Gets status of all databases within a project */
+ DatabasesStatusesController_getStatus: {
+ parameters: {
+ path: {
+ /** @description Project ref */
+ ref: string
+ }
+ }
+ responses: {
+ 200: {
+ content: {
+ 'application/json': components['schemas']['DatabaseStatusResponse'][]
+ }
+ }
+ /** @description Failed to get project's status */
+ 500: {
+ content: never
+ }
+ }
+ }
/** Updates the database password */
DbPasswordController_updatePassword: {
parameters: {
diff --git a/apps/studio/data/read-replicas/keys.ts b/apps/studio/data/read-replicas/keys.ts
new file mode 100644
index 00000000000..1af4e2a04f2
--- /dev/null
+++ b/apps/studio/data/read-replicas/keys.ts
@@ -0,0 +1,5 @@
+export const replicaKeys = {
+ list: (projectRef: string | undefined) => ['project', projectRef, 'replicas'] as const,
+ statuses: (projectRef: string | undefined) =>
+ ['project', projectRef, 'replicas-statuses'] as const,
+}
diff --git a/apps/studio/data/read-replicas/replica-remove-mutation.ts b/apps/studio/data/read-replicas/replica-remove-mutation.ts
new file mode 100644
index 00000000000..4c8d016d98d
--- /dev/null
+++ b/apps/studio/data/read-replicas/replica-remove-mutation.ts
@@ -0,0 +1,66 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { replicaKeys } from './keys'
+import { Database } from './replicas-query'
+
+export type ReadReplicaRemoveVariables = {
+ projectRef: string
+ identifier: string
+}
+
+export async function removeReadReplica({ projectRef, identifier }: ReadReplicaRemoveVariables) {
+ const { data, error } = await post('/v1/projects/{ref}/read-replicas/remove', {
+ params: {
+ path: { ref: projectRef },
+ },
+ body: {
+ database_identifier: identifier,
+ },
+ })
+
+ if (error) throw error
+ return data
+}
+
+type ReadReplicaRemoveData = Awaited<ReturnType<typeof removeReadReplica>>
+
+export const useReadReplicaRemoveMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<ReadReplicaRemoveData, ResponseError, ReadReplicaRemoveVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+ return useMutation<ReadReplicaRemoveData, ResponseError, ReadReplicaRemoveVariables>(
+ (vars) => removeReadReplica(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef, identifier } = variables
+
+ // [Joshen] Just FYI, will remove this once API changes to remove the need for optimistic rendering
+ queryClient.setQueriesData<any>(replicaKeys.list(projectRef), (old: any) => {
+ return old.filter((db: Database) => db.identifier !== identifier)
+ })
+
+ setTimeout(async () => {
+ await queryClient.invalidateQueries(replicaKeys.list(projectRef))
+ }, 5000)
+
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to remove read replica: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/read-replicas/replica-setup-mutation.ts b/apps/studio/data/read-replicas/replica-setup-mutation.ts
new file mode 100644
index 00000000000..157ffd06023
--- /dev/null
+++ b/apps/studio/data/read-replicas/replica-setup-mutation.ts
@@ -0,0 +1,96 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+import { toast } from 'react-hot-toast'
+
+import { post } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { replicaKeys } from './keys'
+import { Database } from './replicas-query'
+
+export type Region =
+ | 'us-east-1'
+ | 'us-west-1'
+ | 'us-west-2'
+ | 'ap-southeast-1'
+ | 'ap-northeast-1'
+ | 'ap-northeast-2'
+ | 'ap-southeast-2'
+ | 'eu-west-1'
+ | 'eu-west-2'
+ | 'eu-west-3'
+ | 'eu-central-1'
+ | 'ca-central-1'
+ | 'ap-south-1'
+ | 'sa-east-1'
+
+export type ReadReplicaSetUpVariables = {
+ projectRef: string
+ region: Region
+ size: string // Not used in API yet, purely for UI atm
+}
+
+export async function setUpReadReplica({ projectRef, region }: ReadReplicaSetUpVariables) {
+ const { data, error } = await post('/v1/projects/{ref}/read-replicas/setup', {
+ params: {
+ path: { ref: projectRef },
+ },
+ body: {
+ read_replica_region: region,
+ },
+ })
+ if (error) throw error
+ return data
+}
+
+type ReadReplicaSetUpData = Awaited<ReturnType<typeof setUpReadReplica>>
+
+export const useReadReplicaSetUpMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseMutationOptions<ReadReplicaSetUpData, ResponseError, ReadReplicaSetUpVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+ return useMutation<ReadReplicaSetUpData, ResponseError, ReadReplicaSetUpVariables>(
+ (vars) => setUpReadReplica(vars),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef, region, size } = variables
+
+ // [Joshen] Just FYI, will remove this once API changes to remove the need for optimistic rendering
+ queryClient.setQueriesData<any>(replicaKeys.list(projectRef), (old: any) => {
+ const scaffoldNewDatabase: Database = {
+ db_port: 5432,
+ db_name: 'postgres',
+ db_user: 'postgres',
+ restUrl: '',
+ db_host: '',
+ connectionString: '',
+ identifier: `${projectRef}-rr-${region}-None`,
+ size,
+ region,
+ inserted_at: new Date().toISOString(),
+ status: 'COMING_UP',
+ cloud_provider: 'AWS',
+ }
+ return [...old, scaffoldNewDatabase]
+ })
+
+ setTimeout(async () => {
+ await queryClient.invalidateQueries(replicaKeys.list(projectRef))
+ }, 5000)
+
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to set up read replica: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ },
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/read-replicas/replicas-query.ts b/apps/studio/data/read-replicas/replicas-query.ts
new file mode 100644
index 00000000000..c7efd05fc55
--- /dev/null
+++ b/apps/studio/data/read-replicas/replicas-query.ts
@@ -0,0 +1,39 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { replicaKeys } from './keys'
+import { components } from 'data/api'
+import { useFlag } from 'hooks'
+
+export type ReadReplicasVariables = {
+ projectRef?: string
+}
+
+export type Database = components['schemas']['DatabaseDetailResponse']
+
+export async function getReadReplicas({ projectRef }: ReadReplicasVariables, signal?: AbortSignal) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ const { data, error } = await get(`/platform/projects/{ref}/databases`, {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ if (error) throw error
+ return data
+}
+
+export type ReadReplicasData = Awaited<ReturnType<typeof getReadReplicas>>
+export type ReadReplicasError = ResponseError
+
+export const useReadReplicasQuery = <TData = ReadReplicasData>(
+ { projectRef }: ReadReplicasVariables,
+ { enabled = true, ...options }: UseQueryOptions<ReadReplicasData, ReadReplicasError, TData> = {}
+) => {
+ const readReplicasEnabled = useFlag('readReplicas')
+ return useQuery<ReadReplicasData, ReadReplicasError, TData>(
+ replicaKeys.list(projectRef),
+ ({ signal }) => getReadReplicas({ projectRef }, signal),
+ { enabled: enabled && readReplicasEnabled && typeof projectRef !== 'undefined', ...options }
+ )
+}
diff --git a/apps/studio/data/read-replicas/replicas-status-query.ts b/apps/studio/data/read-replicas/replicas-status-query.ts
new file mode 100644
index 00000000000..64aba5d293a
--- /dev/null
+++ b/apps/studio/data/read-replicas/replicas-status-query.ts
@@ -0,0 +1,42 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import { get } from 'data/fetchers'
+import { ResponseError } from 'types'
+import { replicaKeys } from './keys'
+import { useFlag } from 'hooks'
+
+export type ReadReplicasStatusesVariables = {
+ projectRef?: string
+}
+
+export async function getReadReplicasStatuses(
+ { projectRef }: ReadReplicasStatusesVariables,
+ signal?: AbortSignal
+) {
+ if (!projectRef) throw new Error('Project ref is required')
+
+ const { data, error } = await get(`/platform/projects/{ref}/databases-statuses`, {
+ params: { path: { ref: projectRef } },
+ signal,
+ })
+
+ if (error) throw error
+ return data
+}
+
+export type ReadReplicasStatusesData = Awaited<ReturnType<typeof getReadReplicasStatuses>>
+export type ReadReplicasStatusesError = ResponseError
+
+export const useReadReplicasStatusesQuery = <TData = ReadReplicasStatusesData>(
+ { projectRef }: ReadReplicasStatusesVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<ReadReplicasStatusesData, ReadReplicasStatusesError, TData> = {}
+) => {
+ const readReplicasEnabled = useFlag('readReplicas')
+ useQuery<ReadReplicasStatusesData, ReadReplicasStatusesError, TData>(
+ replicaKeys.statuses(projectRef),
+ ({ signal }) => getReadReplicasStatuses({ projectRef }, signal),
+ { enabled: enabled && readReplicasEnabled && typeof projectRef !== 'undefined', ...options }
+ )
+}
diff --git a/apps/studio/data/read-replicas/replicas.utils.ts b/apps/studio/data/read-replicas/replicas.utils.ts
new file mode 100644
index 00000000000..c80bc0454a1
--- /dev/null
+++ b/apps/studio/data/read-replicas/replicas.utils.ts
@@ -0,0 +1,7 @@
+import { AVAILABLE_REPLICA_REGIONS } from 'components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/InstanceConfiguration.constants'
+import { last } from 'lodash'
+
+export const formatDatabaseID = (id: string) => last(id.split('-') ?? [])
+
+export const formatDatabaseRegion = (region: string) =>
+ last(AVAILABLE_REPLICA_REGIONS.find((r) => r.region === region)?.name.split('('))?.split(')')[0]
diff --git a/apps/studio/state/sql-editor.ts b/apps/studio/state/sql-editor.ts
index fdc98e1b0ab..20abda4abab 100644
--- a/apps/studio/state/sql-editor.ts
+++ b/apps/studio/state/sql-editor.ts
@@ -36,6 +36,11 @@ export const sqlEditorState = proxy({
[key: string]: 'IDLE' | 'UPDATING' | 'UPDATING_FAILED'
},
+ selectedDatabaseId: undefined as string | undefined,
+ setSelectedDatabaseId: (value?: string) => {
+ sqlEditorState.selectedDatabaseId = value
+ },
+
orderSnippets: (snippets: SqlSnippet[]) => {
return (
snippets