Skip to content

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

Feat/compute and disk (#30068)

Jonathan Summers-Muir9f420962e10a
diff --git a/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsx b/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsx
index e20ff03294c..a8447a40d3a 100644
--- a/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsx
+++ b/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsx
@@ -29,6 +29,7 @@ export const FormFooterChangeBadge = ({ formState }: FormFooterChangeBadgeProps)
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.9 }}
transition={{ duration: 0.1 }}
+ className="text-sm"
>
{Object.keys(formState.dirtyFields).length === 1
? '1 change to review'
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskCountdownRadial.tsx b/apps/studio/components/interfaces/DiskManagement/DiskCountdownRadial.tsx
deleted file mode 100644
index 3905780b1df..00000000000
--- a/apps/studio/components/interfaces/DiskManagement/DiskCountdownRadial.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { AnimatePresence, motion } from 'framer-motion'
-
-import { COOLDOWN_DURATION } from 'data/config/disk-attributes-update-mutation'
-import { Card, CardContent } from 'ui'
-import CountdownTimerRadial from '../../ui/CountdownTimer/CountdownTimerRadial'
-import CountdownTimerSpan from '../../ui/CountdownTimer/CountdownTimerSpan'
-
-export function DiskCountdownRadial({ remainingTime }: { remainingTime: number }) {
- const progressPercentage = (remainingTime / COOLDOWN_DURATION) * 100
-
- return (
- <AnimatePresence>
- {remainingTime !== 0 && (
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: 'auto' }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- >
- <Card className="px-2 rounded-none">
- <CardContent className="py-3 flex gap-3 px-3 items-center">
- <CountdownTimerRadial progress={progressPercentage} />
- <div className="flex flex-col">
- <p className="text-foreground-lighter text-sm p-0">
- 6-hour wait period between disk modifications
- </p>
- <CountdownTimerSpan seconds={remainingTime} />
- </div>
- </CardContent>
- </Card>
- </motion.div>
- )}
- </AnimatePresence>
- )
-}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts
new file mode 100644
index 00000000000..1b9237b29e8
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts
@@ -0,0 +1,169 @@
+import { z } from 'zod'
+import {
+ calculateDiskSizeRequiredForIopsWithGp3,
+ calculateDiskSizeRequiredForIopsWithIo2,
+ calculateIopsRequiredForThroughput,
+ calculateMaxIopsAllowedForDiskSizeWithGp3,
+ calculateMaxIopsAllowedForDiskSizeWithio2,
+ formatNumber,
+} from './DiskManagement.utils'
+import { ComputeInstanceAddonVariantId } from './DiskManagement.types'
+import { DISK_LIMITS, DiskType, IOPS_RANGE, THROUGHPUT_RANGE } from './ui/DiskManagement.constants'
+
+const baseSchema = z.object({
+ storageType: z.enum(['io2', 'gp3']).describe('Type of storage: io2 or gp3'),
+ totalSize: z
+ .number()
+ .min(8, { message: 'Allocated disk size must be at least 8 GB.' })
+ .describe('Allocated disk size in GB'),
+ provisionedIOPS: z.number().describe('Provisioned IOPS for storage type'),
+ throughput: z.number().optional().describe('Throughput in MB/s for gp3'),
+ computeSize: z
+ .custom<ComputeInstanceAddonVariantId>((val): val is ComputeInstanceAddonVariantId => true)
+ .describe('Compute size'),
+})
+
+export const CreateDiskStorageSchema = (defaultTotalSize: number) => {
+ const schema = baseSchema.superRefine((data, ctx) => {
+ const { storageType, totalSize, provisionedIOPS, throughput, computeSize } = data
+
+ if (totalSize < defaultTotalSize) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Disk size cannot be reduced in size. Must be at least ${formatNumber(defaultTotalSize)} GB.`,
+ path: ['totalSize'],
+ })
+ }
+
+ if (storageType === 'io2') {
+ // Validation rules for io2
+
+ if (provisionedIOPS > IOPS_RANGE[DiskType.IO2].max) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `IOPS can not exceed ${formatNumber(IOPS_RANGE[DiskType.IO2].max)} for io2 Disk type. Please reach out to support if you need higher IOPS than this.`,
+ path: ['provisionedIOPS'],
+ })
+ }
+
+ const maxIOPSforDiskSizeWithio2 = calculateMaxIopsAllowedForDiskSizeWithio2(totalSize)
+
+ if (provisionedIOPS < IOPS_RANGE[DiskType.IO2].min) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Provisioned IOPS must be at least ${formatNumber(IOPS_RANGE[DiskType.IO2].min)}`,
+ path: ['provisionedIOPS'],
+ })
+ } else if (provisionedIOPS > maxIOPSforDiskSizeWithio2) {
+ if (totalSize >= 8) {
+ const diskSizeRequiredForIopsWithIo2 =
+ calculateDiskSizeRequiredForIopsWithIo2(provisionedIOPS)
+
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Larger Disk size of at least ${formatNumber(diskSizeRequiredForIopsWithIo2)} GB required. Current max is ${formatNumber(maxIOPSforDiskSizeWithio2)} IOPS.`,
+ path: ['provisionedIOPS'],
+ })
+ } else {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Invalid IOPS value due to small disk size`,
+ path: ['provisionedIOPS'],
+ })
+ }
+ }
+
+ if (throughput !== undefined) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'Throughput is not configurable for io2.',
+ path: ['throughput'],
+ })
+ }
+
+ if (totalSize > DISK_LIMITS[DiskType.IO2].maxStorage) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Allocated disksize must not exceed ${formatNumber(DISK_LIMITS[DiskType.IO2].maxStorage)} GB `,
+ path: ['totalSize'],
+ })
+ }
+ }
+
+ if (storageType === 'gp3') {
+ const maxIopsAllowedForDiskSizeWithGp3 = calculateMaxIopsAllowedForDiskSizeWithGp3(totalSize)
+
+ if (provisionedIOPS > IOPS_RANGE[DiskType.GP3].max) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `IOPS can not exceed ${formatNumber(IOPS_RANGE[DiskType.GP3].max)} for GP3 Disk. Change the Disk type to io2 for higher IOPS support.`,
+ path: ['provisionedIOPS'],
+ })
+ }
+
+ if (provisionedIOPS < IOPS_RANGE[DiskType.GP3].min) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `IOPS must be at least ${formatNumber(IOPS_RANGE[DiskType.GP3].min)}`,
+ path: ['provisionedIOPS'],
+ })
+ } else if (provisionedIOPS > maxIopsAllowedForDiskSizeWithGp3) {
+ if (totalSize >= 8) {
+ const diskSizeRequiredForIopsWithGp3 =
+ calculateDiskSizeRequiredForIopsWithGp3(provisionedIOPS)
+
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Larger Disk size of at least ${formatNumber(diskSizeRequiredForIopsWithGp3)} GB required. Current max is ${formatNumber(maxIopsAllowedForDiskSizeWithGp3)} IOPS.`,
+ path: ['provisionedIOPS'],
+ })
+ } else {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Invalid IOPS value due to invalid disk size`,
+ path: ['provisionedIOPS'],
+ })
+ }
+ }
+
+ if (throughput !== undefined) {
+ const maxThroughput = Math.min(0.25 * provisionedIOPS, 1000)
+
+ if (throughput > THROUGHPUT_RANGE['gp3'].max) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Throughput can not exceed ${formatNumber(maxThroughput)} MiB/s`,
+ path: ['throughput'],
+ })
+ }
+ if (throughput > maxThroughput) {
+ const iopsRequiredForThroughput = calculateIopsRequiredForThroughput(throughput)
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Need at least ${formatNumber(iopsRequiredForThroughput)} IOPS to support ${formatNumber(throughput)} MiB/s.`,
+ path: ['throughput'],
+ })
+ }
+ if (throughput < THROUGHPUT_RANGE[DiskType.GP3].min) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Throughput must be at least ${formatNumber(THROUGHPUT_RANGE[DiskType.GP3].min)} MiB/s`,
+ path: ['throughput'],
+ })
+ }
+ }
+
+ if (totalSize > DISK_LIMITS[DiskType.GP3].maxStorage) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: `Allocated disksize must not exceed ${formatNumber(DISK_LIMITS[DiskType.GP3].maxStorage)} GB`,
+ path: ['totalSize'],
+ })
+ }
+ }
+ })
+
+ return schema
+}
+
+export type DiskStorageSchemaType = z.infer<ReturnType<typeof CreateDiskStorageSchema>>
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.ts
index c89eaeb2be7..ee6317d6ac7 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.ts
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.ts
@@ -1,5 +1,5 @@
import { describe, test, expect } from 'vitest'
-import { DiskType } from './DiskManagement.constants'
+import { DiskType } from './ui/DiskManagement.constants'
import {
calculateDiskSizePrice,
calculateIOPSPrice,
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.types.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.types.ts
new file mode 100644
index 00000000000..8b56b456fb1
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.types.ts
@@ -0,0 +1,48 @@
+import { AddonVariantId, ProjectAddonVariantMeta } from 'data/subscriptions/types'
+
+export type ComputeInstanceAddonVariantId =
+ | Extract<
+ AddonVariantId,
+ | 'ci_micro'
+ | 'ci_small'
+ | 'ci_medium'
+ | 'ci_large'
+ | 'ci_xlarge'
+ | 'ci_2xlarge'
+ | 'ci_4xlarge'
+ | 'ci_8xlarge'
+ | 'ci_12xlarge'
+ | 'ci_16xlarge'
+ >
+ | 'ci_nano'
+
+export type ComputeInstanceSize =
+ | 'Nano'
+ | 'Micro'
+ | 'Small'
+ | 'Medium'
+ | 'Large'
+ | 'XL'
+ | '2XL'
+ | '4XL'
+ | '8XL'
+ | '12XL'
+ | '16XL'
+
+export type InfraInstanceSize =
+ | 'nano'
+ | 'micro'
+ | 'small'
+ | 'medium'
+ | 'large'
+ | 'xlarge'
+ | '2xlarge'
+ | '4xlarge'
+ | '8xlarge'
+ | '12xlarge'
+ | '16xlarge'
+
+export interface DiskManagementMessage {
+ message: string
+ type: 'error' | 'success'
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.ts
index a219ad188f5..dc743688d7a 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.ts
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.ts
@@ -1,4 +1,18 @@
-import { DISK_LIMITS, DISK_PRICING, DiskType, PLAN_DETAILS } from './DiskManagement.constants'
+import { ProjectDetail } from 'data/projects/project-detail-query'
+import { PlanId, ProjectAddonVariantMeta } from 'data/subscriptions/types'
+import { INSTANCE_MICRO_SPECS, INSTANCE_NANO_SPECS } from 'lib/constants'
+import {
+ ComputeInstanceAddonVariantId,
+ ComputeInstanceSize,
+ InfraInstanceSize,
+} from './DiskManagement.types'
+import {
+ COMPUTE_BASELINE_IOPS,
+ DISK_LIMITS,
+ DISK_PRICING,
+ DiskType,
+ PLAN_DETAILS,
+} from './ui/DiskManagement.constants'
// Included disk size only applies to primary, not replicas
export const calculateDiskSizePrice = ({
@@ -18,7 +32,7 @@ export const calculateDiskSizePrice = ({
}) => {
const oldPricePerGB = DISK_PRICING[oldStorageType]?.storage ?? 0
const newPricePerGB = DISK_PRICING[newStorageType]?.storage ?? 0
- const { includedDiskGB } = PLAN_DETAILS?.[planId as keyof typeof PLAN_DETAILS] ?? {}
+ const { includedDiskGB } = PLAN_DETAILS?.[planId as keyof typeof PLAN_DETAILS]
const oldPrice = Math.max(oldSize - includedDiskGB[oldStorageType], 0) * oldPricePerGB
const oldPriceReplica = oldSize * 1.25 * oldPricePerGB
@@ -31,6 +45,42 @@ export const calculateDiskSizePrice = ({
}
}
+export const calculateComputeSizePrice = ({
+ availableOptions,
+ oldComputeSize,
+ newComputeSize,
+ plan,
+}: {
+ availableOptions: {
+ identifier: string
+ price: number
+ }[]
+ oldComputeSize: string
+ newComputeSize: string
+ plan: PlanId
+}) => {
+ let _oldComputeSize = oldComputeSize
+
+ if (plan !== 'free' && oldComputeSize === 'ci_nano') {
+ /**
+ * override the old compute size to micro if the plan is not free
+ * this is to handle the case in which nano compute is a paid entity
+ */
+ _oldComputeSize = 'ci_micro'
+ }
+
+ const oldPrice = availableOptions?.find((x) => x.identifier === _oldComputeSize)?.price ?? 0
+ const newPrice = availableOptions?.find((x) => x.identifier === newComputeSize)?.price ?? 0
+
+ const oldPriceMonthly = oldPrice * 720
+ const newPriceMonthly = newPrice * 720
+
+ return {
+ oldPrice: oldPriceMonthly.toFixed(2),
+ newPrice: newPriceMonthly.toFixed(2),
+ }
+}
+
// Included IOPS applies to both primary and replicas
export const calculateIOPSPrice = ({
oldStorageType,
@@ -109,3 +159,179 @@ export const calculateThroughputPrice = ({
}
return { oldPrice: '0.00', newPrice: '0.00' }
}
+
+export function getAvailableComputeOptions(availableAddons: any[], projectCloudProvider?: string) {
+ const computeOptions =
+ availableAddons
+ .find((addon) => addon.type === 'compute_instance')
+ ?.variants.filter((option: { [key: string]: any }) => {
+ if (!projectCloudProvider) {
+ return true
+ }
+
+ const meta = option.meta as ProjectAddonVariantMeta
+
+ return (
+ !meta.supported_cloud_providers ||
+ meta.supported_cloud_providers.includes(projectCloudProvider)
+ )
+ }) ?? []
+
+ function hasMicroOptionFromApi() {
+ return (
+ availableAddons.find((addon) => addon.type === 'compute_instance')?.variants ?? []
+ ).some((variant: any) => variant.identifier === 'ci_micro')
+ }
+
+ // Backwards comp until API is deployed
+ if (!hasMicroOptionFromApi) {
+ // Unshift to push to start of array
+ computeOptions.unshift({
+ identifier: 'ci_micro',
+ name: 'Micro',
+ price_description: '$0.01344/hour (~$10/month)',
+ price: 0.01344,
+ price_interval: 'hourly',
+ price_type: 'usage',
+ meta: {
+ cpu_cores: INSTANCE_MICRO_SPECS.cpu_cores,
+ cpu_dedicated: INSTANCE_MICRO_SPECS.cpu_dedicated,
+ memory_gb: INSTANCE_MICRO_SPECS.memory_gb,
+ baseline_disk_io_mbs: INSTANCE_MICRO_SPECS.baseline_disk_io_mbs,
+ max_disk_io_mbs: INSTANCE_MICRO_SPECS.max_disk_io_mbs,
+ connections_direct: INSTANCE_MICRO_SPECS.connections_direct,
+ connections_pooler: INSTANCE_MICRO_SPECS.connections_pooler,
+ } as ProjectAddonVariantMeta,
+ })
+ }
+
+ computeOptions.unshift({
+ identifier: 'ci_nano',
+ name: 'Nano',
+ price_description: '$0/hour (~$0/month)',
+ price: 0,
+ price_interval: 'hourly',
+ price_type: 'usage',
+ // @ts-ignore API types it as Record<string, never>
+ meta: {
+ cpu_cores: INSTANCE_NANO_SPECS.cpu_cores,
+ cpu_dedicated: INSTANCE_NANO_SPECS.cpu_dedicated,
+ memory_gb: INSTANCE_NANO_SPECS.memory_gb,
+ baseline_disk_io_mbs: INSTANCE_NANO_SPECS.baseline_disk_io_mbs,
+ max_disk_io_mbs: INSTANCE_NANO_SPECS.max_disk_io_mbs,
+ connections_direct: INSTANCE_NANO_SPECS.connections_direct,
+ connections_pooler: INSTANCE_NANO_SPECS.connections_pooler,
+ } as ProjectAddonVariantMeta,
+ })
+
+ return computeOptions
+}
+
+export const calculateMaxIopsAllowedForDiskSizeWithGp3 = (totalSize: number) => {
+ return Math.min(3000 * totalSize, 16000)
+}
+
+export const calculateDiskSizeRequiredForIopsWithGp3 = (iops: number) => {
+ return Math.max(1, Math.ceil(iops / 500))
+}
+
+export const calculateMaxIopsAllowedForDiskSizeWithio2 = (totalSize: number) => {
+ return Math.min(500 * totalSize, 256000)
+}
+
+export const calculateDiskSizeRequiredForIopsWithIo2 = (iops: number) => {
+ return Math.max(4, Math.ceil(iops / 1000))
+}
+
+export const calculateMaxThroughput = (iops: number) => {
+ return Math.min(0.256 * iops, 1000)
+}
+
+export const calculateIopsRequiredForThroughput = (throughput: number) => {
+ return Math.max(125, Math.ceil(throughput / 0.256))
+}
+
+export const calculateMaxIopsAllowedForComputeSize = (computeSize: string): number => {
+ return COMPUTE_BASELINE_IOPS[computeSize as keyof typeof COMPUTE_BASELINE_IOPS] || 0
+}
+
+export const calculateComputeSizeRequiredForIops = (
+ iops: number
+): ComputeInstanceAddonVariantId | undefined => {
+ const computeSizes = Object.entries(COMPUTE_BASELINE_IOPS).sort((a, b) => a[1] - b[1])
+ for (const [size, baselineIops] of computeSizes) {
+ if (iops <= baselineIops) {
+ return size as ComputeInstanceAddonVariantId
+ }
+ }
+
+ // fallback to largest compute size - this should never happen though :-/
+ return computeSizes[computeSizes.length - 1][0] as ComputeInstanceAddonVariantId
+}
+
+export const calculateDiskSizeRequiredForIops = (provisionedIOPS: number): number | undefined => {
+ if (!provisionedIOPS) {
+ console.error('IOPS is required')
+ return undefined
+ }
+
+ if (isNaN(provisionedIOPS) || provisionedIOPS < 0) {
+ console.error('IOPS must be a non-negative number')
+ return undefined
+ }
+
+ if (provisionedIOPS > 256000) {
+ console.error('Maximum allowed IOPS is 256000')
+ return undefined
+ }
+
+ return Math.max(1, Math.ceil(provisionedIOPS / 1000))
+}
+
+export const formatComputeName = (compute: string) => {
+ return compute.toUpperCase().replace('CI_', '')
+}
+
+export const mapComputeSizeNameToAddonVariantId = (
+ computeSize: ProjectDetail['infra_compute_size']
+): ComputeInstanceAddonVariantId => {
+ return {
+ nano: 'ci_nano',
+ micro: 'ci_micro',
+ small: 'ci_small',
+ medium: 'ci_medium',
+ large: 'ci_large',
+ xlarge: 'ci_xlarge',
+ '2xlarge': 'ci_2xlarge',
+ '4xlarge': 'ci_4xlarge',
+ '8xlarge': 'ci_8xlarge',
+ '12xlarge': 'ci_12xlarge',
+ '16xlarge': 'ci_16xlarge',
+ }[computeSize ?? 'nano'] as ComputeInstanceAddonVariantId
+}
+
+export const mapAddOnVariantIdToComputeSize = (
+ addonVariantId: ComputeInstanceAddonVariantId = 'ci_nano'
+): ComputeInstanceSize => {
+ return {
+ ci_nano: 'Nano',
+ ci_micro: 'Micro',
+ ci_small: 'Small',
+ ci_medium: 'Medium',
+ ci_large: 'Large',
+ ci_xlarge: 'XL',
+ ci_2xlarge: '2XL',
+ ci_4xlarge: '4XL',
+ ci_8xlarge: '8XL',
+ ci_12xlarge: '12XL',
+ ci_16xlarge: '16XL',
+ }[addonVariantId] as ComputeInstanceSize
+}
+
+export const formatNumber = (num: number): string => {
+ return num.toLocaleString('en-US')
+}
+
+export const showMicroUpgrade = (plan: PlanId, infraComputeSize: InfraInstanceSize): boolean => {
+ return plan !== 'free' && infraComputeSize === 'nano'
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx
new file mode 100644
index 00000000000..818a3d88e4f
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx
@@ -0,0 +1,409 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { PermissionAction } from '@supabase/shared-types/out/constants'
+import { useQueryClient } from '@tanstack/react-query'
+import { AnimatePresence, motion } from 'framer-motion'
+import { ChevronRight } from 'lucide-react'
+import Link from 'next/link'
+import { useEffect, useState } from 'react'
+import { useForm } from 'react-hook-form'
+import { toast } from 'sonner'
+
+import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { MAX_WIDTH_CLASSES, PADDING_CLASSES, ScaffoldContainer } from 'components/layouts/Scaffold'
+import {
+ useDiskAttributesQuery,
+ useRemainingDurationForDiskAttributeUpdate,
+} from 'data/config/disk-attributes-query'
+import { useUpdateDiskAttributesMutation } from 'data/config/disk-attributes-update-mutation'
+import { useDiskUtilizationQuery } from 'data/config/disk-utilization-query'
+import { setProjectStatus } from 'data/projects/projects-query'
+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useProjectAddonUpdateMutation } from 'data/subscriptions/project-addon-update-mutation'
+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
+import { AddonVariantId } from 'data/subscriptions/types'
+import { useCheckPermissions, usePermissionsLoaded } from 'hooks/misc/useCheckPermissions'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { PROJECT_STATUS } from 'lib/constants'
+import {
+ Button,
+ cn,
+ Collapsible_Shadcn_,
+ CollapsibleContent_Shadcn_,
+ CollapsibleTrigger_Shadcn_,
+ Form_Shadcn_,
+ Separator,
+} from 'ui'
+import { FormFooterChangeBadge } from '../DataWarehouse/FormFooterChangeBadge'
+import { CreateDiskStorageSchema, DiskStorageSchemaType } from './DiskManagement.schema'
+import { mapComputeSizeNameToAddonVariantId, showMicroUpgrade } from './DiskManagement.utils'
+import { DiskMangementRestartRequiredSection } from './DiskManagementRestartRequiredSection'
+import { DiskManagementReviewAndSubmitDialog } from './DiskManagementReviewAndSubmitDialog'
+import { ComputeSizeField } from './fields/ComputeSizeField'
+import { DiskSizeField } from './fields/DiskSizeField'
+import { IOPSField } from './fields/IOPSField'
+import { StorageTypeField } from './fields/StorageTypeField'
+import { ThroughputField } from './fields/ThroughputField'
+import { DiskCountdownRadial } from './ui/DiskCountdownRadial'
+import {
+ DiskType,
+ IOPS_RANGE,
+ RESTRICTED_COMPUTE_FOR_THROUGHPUT_ON_GP3,
+} from './ui/DiskManagement.constants'
+import { NoticeBar } from './ui/NoticeBar'
+import { SpendCapDisabledSection } from './ui/SpendCapDisabledSection'
+import { DiskManagementMessage } from './DiskManagement.types'
+
+export function DiskManagementForm() {
+ const {
+ project,
+ // isLoading is used to avoid a useCheckPermissions() race condition
+ isLoading: isProjectLoading,
+ } = useProjectContext()
+ const org = useSelectedOrganization()
+ const { ref: projectRef } = useParams()
+ const queryClient = useQueryClient()
+
+ /**
+ * Permissions
+ */
+ const isPermissionsLoaded = usePermissionsLoaded()
+ const canUpdateDiskConfiguration = useCheckPermissions(PermissionAction.UPDATE, 'projects', {
+ resource: {
+ project_id: project?.id,
+ },
+ })
+
+ /**
+ * Component States
+ */
+ const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false)
+ const [refetchInterval, setRefetchInterval] = useState<number | false>(false)
+ const [message, setMessageState] = useState<DiskManagementMessage | null>(null)
+ const [advancedSettingsOpen, setAdvancedSettingsOpenState] = useState(false)
+
+ /**
+ * Fetch form data
+ */
+ const {
+ data: databases,
+ // isLoading: isReadReplicasLoading,
+ // error: readReplicasError,
+ isSuccess: isReadReplicasSuccess,
+ } = useReadReplicasQuery({ projectRef })
+ const {
+ data,
+ // isLoading: isDiskAttributesLoading,
+ // error: diskAttributesError,
+ isSuccess: isDiskAttributesSuccess,
+ } = useDiskAttributesQuery(
+ { projectRef },
+ {
+ refetchInterval,
+ refetchOnWindowFocus: false,
+ onSuccess: (data) => {
+ // @ts-ignore
+ const { type, iops, throughput_mbps, size_gb } = data?.attributes ?? { size_gb: 0 }
+ const formValues = {
+ storageType: type,
+ provisionedIOPS: iops,
+ throughput: throughput_mbps,
+ totalSize: size_gb,
+ }
+
+ if (!('requested_modification' in data)) {
+ if (refetchInterval !== false) {
+ form.reset(formValues)
+ setRefetchInterval(false)
+ toast.success('Disk configuration changes have been successfully applied!')
+ }
+ }
+ },
+ }
+ )
+ const { isSuccess: isAddonsSuccess } = useProjectAddonsQuery({ projectRef })
+ const { isWithinCooldownWindow, isSuccess: isCooldownSuccess } =
+ useRemainingDurationForDiskAttributeUpdate({
+ projectRef,
+ })
+ const { isSuccess: isDiskUtilizationSuccess } = useDiskUtilizationQuery({
+ projectRef,
+ })
+ const { data: subscription, isSuccess: isSubscriptionSuccess } = useOrgSubscriptionQuery({
+ orgSlug: org?.slug,
+ })
+
+ /**
+ * Handle default values
+ */
+ // @ts-ignore [Joshen TODO] check whats happening here
+ const { type, iops, throughput_mbps, size_gb } = data?.attributes ?? { size_gb: 0 }
+ const defaultValues = {
+ storageType: type ?? DiskType.GP3,
+ provisionedIOPS: iops,
+ throughput: throughput_mbps,
+ totalSize: size_gb,
+ computeSize: project?.infra_compute_size
+ ? mapComputeSizeNameToAddonVariantId(project?.infra_compute_size)
+ : undefined,
+ }
+
+ const form = useForm<DiskStorageSchemaType>({
+ resolver: zodResolver(CreateDiskStorageSchema(defaultValues.totalSize)),
+ defaultValues,
+ mode: 'onBlur',
+ reValidateMode: 'onChange',
+ })
+
+ /**
+ * State handling
+ */
+
+ const isSuccess =
+ isAddonsSuccess &&
+ isDiskAttributesSuccess &&
+ isDiskUtilizationSuccess &&
+ isReadReplicasSuccess &&
+ isSubscriptionSuccess &&
+ isCooldownSuccess
+
+ const isRequestingChanges = data?.requested_modification !== undefined
+ const readReplicas = (databases ?? []).filter((db) => db.identifier !== projectRef)
+ const isPlanUpgradeRequired = subscription?.plan.id === 'free'
+
+ const { formState } = form
+
+ const isFlyArchitecture = project?.cloud_provider === 'FLY'
+
+ const disableDiskInputs =
+ isRequestingChanges ||
+ isPlanUpgradeRequired ||
+ isWithinCooldownWindow ||
+ !canUpdateDiskConfiguration ||
+ isFlyArchitecture
+
+ const disableComputeInputs = isPlanUpgradeRequired
+
+ useEffect(() => {
+ // Initialize field values properly when data has been loaded, preserving any user changes
+ if (isSuccess) {
+ form.reset(defaultValues, {})
+ }
+ }, [isSuccess])
+
+ const isDirty = !!Object.keys(form.formState.dirtyFields).length
+ const isProjectResizing = project?.status === PROJECT_STATUS.RESIZING
+ const isProjectRequestingDiskChanges = isRequestingChanges && !isProjectResizing
+ const noPermissions = isPermissionsLoaded && !canUpdateDiskConfiguration && !isProjectLoading
+
+ const { mutateAsync: updateDiskConfiguration, isLoading: isUpdatingDisk } =
+ useUpdateDiskAttributesMutation({
+ // this is to suppress to toast message
+ onError: () => {},
+ })
+ const { mutateAsync: updateSubscriptionAddon, isLoading: isUpdatingCompute } =
+ useProjectAddonUpdateMutation({
+ // this is to suppress to toast message
+ onError: () => {},
+ onSuccess: () => {
+ /**
+ * Manually set project status to RESIZING
+ * Project status should be RESIZING on next project status request.
+ */
+ setProjectStatus(queryClient, projectRef!, PROJECT_STATUS.RESIZING)
+ },
+ })
+
+ const isUpdatingConfig = isUpdatingDisk || isUpdatingCompute
+
+ const onSubmit = async (data: DiskStorageSchemaType) => {
+ let payload = data
+ setMessageState(null)
+ try {
+ if (
+ payload.storageType !== form.formState.defaultValues?.storageType ||
+ payload.provisionedIOPS !== form.formState.defaultValues?.provisionedIOPS ||
+ payload.throughput !== form.formState.defaultValues?.throughput ||
+ payload.totalSize !== form.formState.defaultValues?.totalSize
+ ) {
+ if (RESTRICTED_COMPUTE_FOR_THROUGHPUT_ON_GP3.includes(payload.computeSize)) {
+ payload.provisionedIOPS = IOPS_RANGE[DiskType.GP3].min
+ }
+
+ await updateDiskConfiguration({
+ ref: projectRef,
+ provisionedIOPS: payload.provisionedIOPS,
+ storageType: payload.storageType,
+ totalSize: payload.totalSize,
+ throughput: payload.throughput,
+ })
+ }
+
+ if (payload.computeSize !== form.formState.defaultValues?.computeSize) {
+ await updateSubscriptionAddon({
+ projectRef: projectRef,
+ // cast variant to AddonVariantId to satisfy type
+ variant: payload.computeSize as AddonVariantId,
+ type: 'compute_instance',
+ suppressToast: true,
+ })
+ }
+
+ setIsDialogOpen(false)
+ form.reset(data as DiskStorageSchemaType)
+ } catch (error: unknown) {
+ setMessageState({
+ message: error instanceof Error ? error.message : 'An unknown error occurred',
+ type: 'error',
+ })
+ }
+ }
+
+ return (
+ <Form_Shadcn_ {...form}>
+ <form onSubmit={form.handleSubmit(onSubmit)} className="flex flex-col gap-8">
+ <ScaffoldContainer className="relative flex flex-col gap-10" bottomPadding>
+ <NoticeBar
+ type="default"
+ visible={isPlanUpgradeRequired}
+ title="Compute and Disk configuration is not available on the Free Plan"
+ actions={
+ <Button type="default" asChild>
+ <Link href={`/org/${org?.slug}/billing?panel=subscriptionPlan`}>Upgrade plan</Link>
+ </Button>
+ }
+ description="You will need to upgrade to at least the Pro Plan to configure compute and disk"
+ />
+
+ {isProjectResizing || isProjectRequestingDiskChanges || noPermissions ? (
+ <div className="relative flex flex-col gap-10">
+ <DiskMangementRestartRequiredSection
+ visible={isProjectResizing}
+ title="Your project will now automatically restart."
+ description="Your project will be unavailable for up to 2 mins."
+ />
+ <NoticeBar
+ type="default"
+ visible={isProjectRequestingDiskChanges}
+ title="Disk configuration changes have been requested"
+ description="The requested changes will be applied to your disk shortly"
+ />
+ <NoticeBar
+ type="default"
+ visible={noPermissions}
+ title="You do not have permission to update disk configuration"
+ description="Please contact your organization administrator to update your disk configuration"
+ />
+ </div>
+ ) : null}
+ <Separator />
+ <ComputeSizeField form={form} disabled={disableComputeInputs} />
+ <Separator />
+ <DiskCountdownRadial />
+ <SpendCapDisabledSection />
+ <NoticeBar
+ type="default"
+ visible={isFlyArchitecture}
+ title="Disk configuration is not available on Fly Postgres"
+ description="Please contact Fly support if you need to update your disk configuration"
+ />
+ {!isFlyArchitecture && (
+ <>
+ <DiskSizeField
+ form={form}
+ disableInput={disableDiskInputs}
+ setAdvancedSettingsOpenState={setAdvancedSettingsOpenState}
+ />
+ <Separator />
+ <Collapsible_Shadcn_
+ // TO DO: wrap component into pattern
+ className="-space-y-px"
+ open={advancedSettingsOpen}
+ onOpenChange={() => setAdvancedSettingsOpenState((prev) => !prev)}
+ >
+ <CollapsibleTrigger_Shadcn_ className="px-8 py-3 w-full border flex items-center gap-6 rounded-t data-[state=closed]:rounded-b group justify-between">
+ <div className="flex flex-col items-start">
+ <span className="text-sm text-foreground">Advanced disk settings</span>
+ <span className="text-sm text-foreground-light">
+ Specify additional settings for your disk, including IOPS, throughput, and
+ disk type.
+ </span>
+ </div>
+ <ChevronRight
+ size={16}
+ className="text-foreground-light transition-all group-data-[state=open]:rotate-90"
+ strokeWidth={1}
+ />
+ </CollapsibleTrigger_Shadcn_>
+ <CollapsibleContent_Shadcn_ className="data-[state=open]:border flex flex-col gap-8 px-8 py-8 transition-all data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">
+ <StorageTypeField form={form} disableInput={disableDiskInputs} />
+ <NoticeBar
+ type="default"
+ visible={
+ RESTRICTED_COMPUTE_FOR_THROUGHPUT_ON_GP3.includes(
+ form.watch('computeSize')
+ ) && subscription?.plan.id !== 'free'
+ }
+ title={`IOPS ${form.getValues('storageType') === 'gp3' ? 'and Throughput ' : ''}configuration requires LARGE Compute size or above`}
+ actions={
+ <Button
+ type="default"
+ onClick={() => {
+ form.setValue('computeSize', 'ci_large')
+ }}
+ >
+ Change to LARGE Compute
+ </Button>
+ }
+ />
+ <IOPSField form={form} disableInput={disableDiskInputs} />
+ <ThroughputField form={form} disableInput={disableDiskInputs} />
+ </CollapsibleContent_Shadcn_>
+ </Collapsible_Shadcn_>
+ </>
+ )}
+ </ScaffoldContainer>
+ <AnimatePresence>
+ {isDirty ? (
+ <motion.div
+ initial={{ opacity: 0, y: 20 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: 20 }}
+ transition={{ duration: 0.1, delay: 0.2 }}
+ className="z-10 w-full left-0 right-0 sticky bottom-0 bg-surface-100 border-t h-16 items-center flex"
+ >
+ <div
+ className={cn(
+ MAX_WIDTH_CLASSES,
+ PADDING_CLASSES,
+ 'flex items-center gap-3 justify-end'
+ )}
+ >
+ <FormFooterChangeBadge formState={formState} />
+ <Button
+ type="default"
+ onClick={() => form.reset()}
+ disabled={!isDirty}
+ size="medium"
+ >
+ Cancel
+ </Button>
+ <DiskManagementReviewAndSubmitDialog
+ loading={isUpdatingConfig}
+ disabled={noPermissions}
+ form={form}
+ numReplicas={readReplicas.length}
+ isDialogOpen={isDialogOpen}
+ onSubmit={onSubmit}
+ setIsDialogOpen={setIsDialogOpen}
+ message={message}
+ />
+ </div>
+ </motion.div>
+ ) : null}
+ </AnimatePresence>
+ </form>
+ </Form_Shadcn_>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx
index 72ae54efdc9..5ea06ca484a 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx
@@ -8,7 +8,7 @@ import { useForm } from 'react-hook-form'
import { toast } from 'sonner'
import { useParams } from 'common'
-import DiskSpaceBar from 'components/interfaces/DiskManagement/DiskSpaceBar'
+import DiskSpaceBar from 'components/interfaces/DiskManagement/ui/DiskSpaceBar'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { DocsButton } from 'components/ui/DocsButton'
import { FormHeader } from 'components/ui/Forms/FormHeader'
@@ -23,6 +23,7 @@ import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-que
import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { useFlag } from 'hooks/ui/useFlag'
import { GB } from 'lib/constants'
import {
Alert_Shadcn_,
@@ -48,34 +49,37 @@ import { Admonition } from 'ui-patterns'
import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
import { FormFooterChangeBadge } from '../DataWarehouse/FormFooterChangeBadge'
import { Markdown } from '../Markdown'
-import BillingChangeBadge from './BillingChangeBadge'
-import { DiskCountdownRadial } from './DiskCountdownRadial'
-import {
- COMPUTE_SIZE_MAX_IOPS,
- COMPUTE_SIZE_MAX_THROUGHPUT,
- DiskType,
- IOPS_RANGE,
- PLAN_DETAILS,
- THROUGHPUT_RANGE,
-} from './DiskManagement.constants'
+import { CreateDiskStorageSchema, DiskStorageSchemaType } from './DiskManagement.schema'
import {
calculateDiskSizePrice,
calculateIOPSPrice,
calculateThroughputPrice,
} from './DiskManagement.utils'
-import { DiskStorageSchemaType, getDiskStorageSchema } from './DiskManagementPanelSchema'
-import { DiskManagementPlanUpgradeRequired } from './DiskManagementPlanUpgradeRequired'
+import { getDiskStorageSchema } from './DiskManagementPanelSchema'
+import { DiskManagementReviewAndSubmitDialog } from './DiskManagementReviewAndSubmitDialog'
+import { BillingChangeBadge } from './ui/BillingChangeBadge'
+import { DiskCountdownRadial } from './ui/DiskCountdownRadial'
+import {
+ COMPUTE_MAX_IOPS,
+ COMPUTE_MAX_THROUGHPUT,
+ DiskType,
+ IOPS_RANGE,
+ PLAN_DETAILS,
+ THROUGHPUT_RANGE,
+} from './ui/DiskManagement.constants'
import {
DiskManagementDiskSizeReadReplicas,
DiskManagementIOPSReadReplicas,
DiskManagementThroughputReadReplicas,
-} from './DiskManagementReadReplicas'
-import { DiskManagementReviewAndSubmitDialog } from './DiskManagementReviewAndSubmitDialog'
+} from './ui/DiskManagementReadReplicas'
+import { NoticeBar } from './ui/NoticeBar'
+import { SpendCapDisabledSection } from './ui/SpendCapDisabledSection'
export function DiskManagementPanelForm() {
const { project } = useProjectContext()
const org = useSelectedOrganization()
const { ref: projectRef } = useParams()
+ const diskAndComputeFormEnabled = useFlag('diskAndComputeForm')
const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false)
const [remainingTime, setRemainingTime] = useState(0)
@@ -129,10 +133,10 @@ export function DiskManagementPanelForm() {
(x: { type: string }) => x.type === 'compute_instance'
)?.variant
const maxIopsBasedOnCompute =
- COMPUTE_SIZE_MAX_IOPS[(currentCompute?.identifier ?? '') as keyof typeof COMPUTE_SIZE_MAX_IOPS]
+ COMPUTE_MAX_IOPS[(currentCompute?.identifier ?? '') as keyof typeof COMPUTE_MAX_IOPS]
const maxThroughputBasedOnCompute =
- COMPUTE_SIZE_MAX_THROUGHPUT[
- (currentCompute?.identifier ?? '') as keyof typeof COMPUTE_SIZE_MAX_THROUGHPUT
+ COMPUTE_MAX_THROUGHPUT[
+ (currentCompute?.identifier ?? '') as keyof typeof COMPUTE_MAX_THROUGHPUT
]
const { data: subscription } = useOrgSubscriptionQuery({
@@ -163,10 +167,11 @@ export function DiskManagementPanelForm() {
provisionedIOPS: iops,
throughput: throughput_mbps,
totalSize: size_gb,
+ computeSize: undefined,
}
const DiskStorageSchema = getDiskStorageSchema(size_gb)
const form = useForm<DiskStorageSchemaType>({
- resolver: zodResolver(DiskStorageSchema),
+ resolver: zodResolver(CreateDiskStorageSchema(defaultValues.totalSize)),
defaultValues,
mode: 'onBlur',
reValidateMode: 'onChange',
@@ -267,6 +272,30 @@ export function DiskManagementPanelForm() {
return () => clearInterval(timer)
}, [remainingTime])
+ if (diskAndComputeFormEnabled) {
+ return (
+ <div id="disk-management">
+ <FormHeader
+ title="Disk Management"
+ docsUrl="https://supabase.com/docs/guides/platform/database-size#disk-management"
+ />
+ <NoticeBar
+ visible={true}
+ type="default"
+ title="Disk Management has moved"
+ description="Disk configuration is now managed alongside Project Compute on the new Compute and Disk page."
+ actions={
+ <Button type="default" asChild>
+ <Link href={`/project/${projectRef}/settings/compute-and-disk`}>
+ Go to Compute and Disk
+ </Link>
+ </Button>
+ }
+ />
+ </div>
+ )
+ }
+
if (planId === 'free') {
return (
<div id="disk-management">
@@ -703,18 +732,13 @@ export function DiskManagementPanelForm() {
</FormItemLayout>
)}
/>
- <div className="grid grid-cols-12 gap-3">
+ <div className="grid grid-cols-12 gap-10">
{/* You can add additional content in the remaining 4 columns if needed */}
<div className="col-span-4">
{/* Additional content or information can go here */}
</div>
<div className="col-span-8 space-y-6 mt-6">
- <DiskSpaceBar
- showNewBar={form.formState.dirtyFields.totalSize !== undefined}
- totalSize={size_gb}
- usedSize={mainDiskUsed}
- newTotalSize={watchedTotalSize}
- />
+ <DiskSpaceBar form={form} />
<DiskManagementDiskSizeReadReplicas
isDirty={form.formState.dirtyFields.totalSize !== undefined}
totalSize={size_gb * 1.25}
@@ -742,10 +766,10 @@ export function DiskManagementPanelForm() {
</CardContent>
</Card>
) : (
- <DiskCountdownRadial remainingTime={remainingTime} />
+ <DiskCountdownRadial />
)}
- {isPlanUpgradeRequired && <DiskManagementPlanUpgradeRequired />}
+ <SpendCapDisabledSection />
<Card className="bg-surface-100 rounded-t-none">
<CardContent className="flex items-center pb-0 py-3 px-8 gap-3 justify-end">
@@ -763,9 +787,10 @@ export function DiskManagementPanelForm() {
form={form}
numReplicas={readReplicas.length}
isDialogOpen={isDialogOpen}
- isWithinCooldown={disableInput}
+ disabled={disableInput}
onSubmit={onSubmit}
setIsDialogOpen={setIsDialogOpen}
+ buttonSize={'tiny'}
/>
</div>
</CardContent>
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.ts
index 37bf8f73fb9..08ce44c51a1 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.ts
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.ts
@@ -1,5 +1,5 @@
import { z } from 'zod'
-import { DISK_LIMITS, DiskType } from './DiskManagement.constants'
+import { DISK_LIMITS, DiskType } from './ui/DiskManagement.constants'
const baseSchema = z.object({
storageType: z.enum(['io2', 'gp3']).describe('Type of storage: io2 or gp3'),
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPlanUpgradeRequired.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementPlanUpgradeRequired.tsx
deleted file mode 100644
index 6e347ddafc2..00000000000
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementPlanUpgradeRequired.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import { AnimatePresence, motion } from 'framer-motion'
-import Link from 'next/link'
-
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import {
- Alert_Shadcn_ as Alert,
- AlertDescription_Shadcn_ as AlertDescription,
- AlertTitle_Shadcn_ as AlertTitle,
- buttonVariants,
- cn,
- InfoIcon,
-} from 'ui'
-
-export function DiskManagementPlanUpgradeRequired() {
- const org = useSelectedOrganization()
-
- return (
- <AnimatePresence>
- <motion.div
- initial={{ opacity: 0, height: 0 }}
- animate={{ opacity: 1, height: 'auto' }}
- exit={{ opacity: 0, height: 0 }}
- transition={{ duration: 0.2 }}
- >
- <Alert variant="default" className="px-6 py-4 rounded-none [&_svg]:left-8 pl-10">
- <InfoIcon className="w-4 h-4" />
- <AlertTitle>Disable spend cap to manage your disk</AlertTitle>
- <AlertDescription>
- To access advanced disk management features, you need to disable your spend cap. These
- features offer more flexibility and control over your database disk size.
- </AlertDescription>
- <div className="mt-3">
- <Link
- href={`/org/${org?.slug}/billing?panel=costControl`}
- className={cn(buttonVariants({ type: 'default', size: 'tiny' }))}
- >
- Disable spend cap
- </Link>
- </div>
- </Alert>
- </motion.div>
- </AnimatePresence>
- )
-}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementRestartRequiredSection.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementRestartRequiredSection.tsx
new file mode 100644
index 00000000000..13d935d535d
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementRestartRequiredSection.tsx
@@ -0,0 +1,42 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { RotateCcw } from 'lucide-react'
+
+import { DialogSection, WarningIcon } from 'ui'
+
+interface DiskMangementRestartRequiredSectionProps {
+ visible: boolean
+ title: string
+ description: string
+}
+
+export const DiskMangementRestartRequiredSection = ({
+ visible,
+ title,
+ description,
+}: DiskMangementRestartRequiredSectionProps) => {
+ return (
+ <AnimatePresence>
+ {visible && (
+ <motion.div
+ initial={{ opacity: 1, height: 'auto' }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.15 }}
+ className="w-full"
+ >
+ <DialogSection className="bg-surface-100 text-sm text-foreground-light flex items-center gap-4 relative w-full rounded-md border-spacing-0 border">
+ <div className="w-12 h-12">
+ <div className="relative w-10 h-10 m-1 bg-alternative text-foreground border rounded-full flex items-center justify-center">
+ <RotateCcw strokeWidth={1} />
+ <WarningIcon className="absolute -right-1.5 -top-1.5" />
+ </div>
+ </div>
+ <div className="flex flex-col gap-0 flex-grow">
+ <p className="text-sm text-foreground">{title}</p>
+ <p className="text-sm text-foreground-light">{description}</p>
+ </div>
+ </DialogSection>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx
index 4ac8bd80fbb..536403d8694 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx
@@ -1,20 +1,27 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { ChevronRight } from 'lucide-react'
+import { useMemo } from 'react'
import { UseFormReturn } from 'react-hook-form'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
import { formatCurrency } from 'lib/helpers'
import {
+ Alert_Shadcn_,
+ AlertTitle_Shadcn_,
Badge,
Button,
+ ButtonProps,
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
+ DialogSection,
DialogSectionSeparator,
DialogTitle,
DialogTrigger,
@@ -24,17 +31,22 @@ import {
TableHead,
TableHeader,
TableRow,
+ WarningIcon,
} from 'ui'
-import BillingChangeBadge from './BillingChangeBadge'
-import { DiskType } from './DiskManagement.constants'
+import { DiskStorageSchemaType } from './DiskManagement.schema'
+import { DiskManagementMessage } from './DiskManagement.types'
import {
+ calculateComputeSizePrice,
calculateDiskSizePrice,
calculateIOPSPrice,
calculateThroughputPrice,
+ getAvailableComputeOptions,
+ mapAddOnVariantIdToComputeSize,
} from './DiskManagement.utils'
-import { DiskMangementCoolDownSection } from './DiskManagementCoolDownSection'
-import { DiskStorageSchemaType } from './DiskManagementPanelSchema'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { DiskMangementRestartRequiredSection } from './DiskManagementRestartRequiredSection'
+import { BillingChangeBadge } from './ui/BillingChangeBadge'
+import { DiskType } from './ui/DiskManagement.constants'
+import { DiskMangementCoolDownSection } from './ui/DiskManagementCoolDownSection'
const TableHeaderRow = () => (
<TableRow>
@@ -54,6 +66,7 @@ interface TableDataRowProps {
afterPrice: number
hidePrice?: boolean
priceTooltip?: string
+ upgradeIncluded?: boolean
}
const TableDataRow = ({
@@ -65,6 +78,7 @@ const TableDataRow = ({
afterPrice,
hidePrice = false,
priceTooltip,
+ upgradeIncluded = false,
}: TableDataRowProps) => (
<TableRow>
<TableCell className="pl-5">
@@ -76,9 +90,11 @@ const TableDataRow = ({
{defaultValue !== newValue ? (
<Badge variant="default" className="bg-alternative bg-opacity-100">
<div className="flex items-center gap-1">
- <span className="text-xs font-mono text-foreground-muted">{defaultValue}</span>
+ <span className="text-xs font-mono text-foreground-muted">
+ {defaultValue.toString()}
+ </span>
<ChevronRight size={12} strokeWidth={2} className="text-foreground-muted" />
- <span className="text-xs font-mono text-foreground">{newValue}</span>
+ <span className="text-xs font-mono text-foreground">{newValue.toString()}</span>
</div>
</Badge>
) : (
@@ -90,14 +106,15 @@ const TableDataRow = ({
</TableCell>
<TableCell className="text-xs font-mono">{unit}</TableCell>
<TableCell className="text-right pr-5">
- {hidePrice ? (
+ {!upgradeIncluded && hidePrice ? (
<span className="text-xs font-mono">-</span>
- ) : beforePrice !== afterPrice ? (
+ ) : beforePrice !== afterPrice || upgradeIncluded ? (
<BillingChangeBadge
show={true}
beforePrice={beforePrice}
afterPrice={afterPrice}
tooltip={priceTooltip}
+ free={upgradeIncluded}
/>
) : (
<span className="text-xs font-mono">{formatCurrency(beforePrice)}</span>
@@ -111,23 +128,29 @@ interface DiskSizeMeterProps {
form: UseFormReturn<DiskStorageSchemaType>
numReplicas: number
isDialogOpen: boolean
- isWithinCooldown: boolean
+ disabled?: boolean
setIsDialogOpen: (isOpen: boolean) => void
onSubmit: (values: DiskStorageSchemaType) => Promise<void>
+
+ buttonSize?: ButtonProps['size']
+ message?: DiskManagementMessage | null
}
export const DiskManagementReviewAndSubmitDialog = ({
isDialogOpen,
setIsDialogOpen,
- isWithinCooldown,
+ disabled,
form,
numReplicas,
loading,
onSubmit,
+ message,
+ buttonSize = 'medium',
}: DiskSizeMeterProps) => {
const { project } = useProjectContext()
const org = useSelectedOrganization()
- const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: org?.slug })
+
+ const { formState, getValues } = form
const canUpdateDiskConfiguration = useCheckPermissions(PermissionAction.UPDATE, 'projects', {
resource: {
@@ -135,20 +158,43 @@ export const DiskManagementReviewAndSubmitDialog = ({
},
})
- const planId = subscription?.plan.id ?? ''
- const isDirty = Object.keys(form.formState.dirtyFields).length > 0
+ /**
+ * Queries
+ * */
+ const {
+ data: subscription,
+ // request deps in Form handle errors and loading
+ } = useOrgSubscriptionQuery({ orgSlug: org?.slug })
+ const {
+ data: addons,
+ // request deps in Form handle errors and loading
+ } = useProjectAddonsQuery({ projectRef: project?.ref })
+ const planId = subscription?.plan.id ?? 'free'
+ const isDirty = !!Object.keys(form.formState.dirtyFields).length
const replicaTooltipText = `Price change includes primary database and ${numReplicas} replica${numReplicas > 1 ? 's' : ''}`
+ const availableAddons = useMemo(() => {
+ return addons?.available_addons ?? []
+ }, [addons])
+ const availableOptions = useMemo(() => {
+ return getAvailableComputeOptions(availableAddons, project?.cloud_provider)
+ }, [availableAddons, project?.cloud_provider])
+
+ const computeSizePrice = calculateComputeSizePrice({
+ availableOptions,
+ oldComputeSize: form.formState.defaultValues?.computeSize || 'ci_micro',
+ newComputeSize: form.getValues('computeSize'),
+ plan: subscription?.plan.id ?? 'free',
+ })
const diskSizePrice = calculateDiskSizePrice({
- planId,
- oldSize: form.formState.defaultValues?.totalSize || 0,
- oldStorageType: form.formState.defaultValues?.storageType as DiskType,
- newSize: form.getValues('totalSize'),
- newStorageType: form.getValues('storageType') as DiskType,
+ planId: planId,
+ oldSize: formState.defaultValues?.totalSize || 0,
+ oldStorageType: formState.defaultValues?.storageType as DiskType,
+ newSize: getValues('totalSize'),
+ newStorageType: getValues('storageType') as DiskType,
numReplicas,
})
-
const iopsPrice = calculateIOPSPrice({
oldStorageType: form.formState.defaultValues?.storageType as DiskType,
oldProvisionedIOPS: form.formState.defaultValues?.provisionedIOPS || 0,
@@ -156,7 +202,6 @@ export const DiskManagementReviewAndSubmitDialog = ({
newProvisionedIOPS: form.getValues('provisionedIOPS'),
numReplicas,
})
-
const throughputPrice = calculateThroughputPrice({
storageType: form.getValues('storageType') as DiskType,
newThroughput: form.getValues('throughput') || 0,
@@ -164,10 +209,17 @@ export const DiskManagementReviewAndSubmitDialog = ({
numReplicas,
})
+ const hasDiskConfigChanges =
+ form.formState.defaultValues?.provisionedIOPS !== form.getValues('provisionedIOPS') ||
+ (form.formState.defaultValues?.throughput !== form.getValues('throughput') &&
+ form.getValues('storageType') === 'gp3') ||
+ form.formState.defaultValues?.totalSize !== form.getValues('totalSize')
+
return (
<Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
<DialogTrigger asChild>
<ButtonTooltip
+ size={buttonSize}
htmlType="submit"
type="primary"
onClick={async (e) => {
@@ -175,14 +227,14 @@ export const DiskManagementReviewAndSubmitDialog = ({
const isValid = await form.trigger()
if (isValid) setIsDialogOpen(true)
}}
- disabled={isWithinCooldown || !isDirty}
+ disabled={disabled || !isDirty}
tooltip={{
content: {
side: 'bottom',
text: !canUpdateDiskConfiguration
? 'You need additional permissions to update disk configuration'
- : isWithinCooldown
- ? 'Currently within cooldown period from previous disk change'
+ : disabled
+ ? 'Current form values are invalid'
: undefined,
},
}}
@@ -190,86 +242,102 @@ export const DiskManagementReviewAndSubmitDialog = ({
Review changes
</ButtonTooltip>
</DialogTrigger>
- <DialogContent size="large">
+ <DialogContent className="min-w-[620px]">
<DialogHeader>
<DialogTitle>Review changes</DialogTitle>
- <DialogDescription>
- Disk configuration changes will be applied shortly once confirmed.
- </DialogDescription>
+ <DialogDescription>Changes will be applied shortly once confirmed.</DialogDescription>
</DialogHeader>
<DialogSectionSeparator />
-
+ <div className="flex flex-col gap-2 p-5">
+ <DiskMangementRestartRequiredSection
+ visible={form.formState.defaultValues?.computeSize !== form.getValues('computeSize')}
+ title="Resizing your Compute will trigger a project restart"
+ description="Project will restart automatically on confirmation."
+ />
+ <DiskMangementCoolDownSection visible={hasDiskConfigChanges} />
+ </div>
+ <DialogSectionSeparator />
<Table>
<TableHeader className="font-mono uppercase text-xs [&_th]:h-auto [&_th]:pb-2 [&_th]:pt-4">
<TableHeaderRow />
</TableHeader>
<TableBody className="[&_td]:py-0 [&_tr]:h-[50px] [&_tr]:border-dotted">
- <TableDataRow
- hidePrice
- attribute="Storage Type"
- defaultValue={form.formState.defaultValues?.storageType ?? ''}
- newValue={form.getValues('storageType')}
- unit="-"
- beforePrice={0}
- afterPrice={0}
- />
- <TableDataRow
- attribute="IOPS"
- defaultValue={form.formState.defaultValues?.provisionedIOPS?.toLocaleString() ?? 0}
- newValue={form.getValues('provisionedIOPS')?.toLocaleString()}
- unit="IOPS"
- beforePrice={Number(iopsPrice.oldPrice)}
- afterPrice={Number(iopsPrice.newPrice)}
- priceTooltip={numReplicas > 0 ? replicaTooltipText : undefined}
- />
- {form.getValues('storageType') === 'gp3' ? (
+ {form.formState.defaultValues?.computeSize !== form.getValues('computeSize') && (
<TableDataRow
- attribute="Throughput"
- defaultValue={form.formState.defaultValues?.throughput?.toLocaleString() ?? 0}
- newValue={form.getValues('throughput')?.toLocaleString() ?? 0}
- unit="MB/s"
- beforePrice={Number(throughputPrice.oldPrice)}
- afterPrice={Number(throughputPrice.newPrice)}
+ attribute="Compute size"
+ defaultValue={mapAddOnVariantIdToComputeSize(
+ form.formState.defaultValues?.computeSize ?? 'ci_nano'
+ )}
+ newValue={mapAddOnVariantIdToComputeSize(form.getValues('computeSize'))}
+ unit="-"
+ beforePrice={Number(computeSizePrice.oldPrice)}
+ afterPrice={Number(computeSizePrice.newPrice)}
+ upgradeIncluded={
+ subscription?.plan.id !== 'free' &&
+ project?.infra_compute_size === 'nano' &&
+ form.getValues('computeSize') === 'ci_micro'
+ }
+ />
+ )}
+ {form.formState.defaultValues?.storageType !== form.getValues('storageType') && (
+ <TableDataRow
+ hidePrice
+ attribute="Storage Type"
+ defaultValue={form.formState.defaultValues?.storageType ?? ''}
+ newValue={form.getValues('storageType')}
+ unit="-"
+ beforePrice={0}
+ afterPrice={0}
+ />
+ )}
+ {form.formState.defaultValues?.provisionedIOPS !==
+ form.getValues('provisionedIOPS') && (
+ <TableDataRow
+ attribute="IOPS"
+ defaultValue={form.formState.defaultValues?.provisionedIOPS?.toLocaleString() ?? 0}
+ newValue={form.getValues('provisionedIOPS')?.toLocaleString()}
+ unit="IOPS"
+ beforePrice={Number(iopsPrice.oldPrice)}
+ afterPrice={Number(iopsPrice.newPrice)}
+ priceTooltip={numReplicas > 0 ? replicaTooltipText : undefined}
+ />
+ )}
+ {form.formState.defaultValues?.throughput !== form.getValues('throughput') &&
+ form.getValues('storageType') === 'gp3' && (
+ <TableDataRow
+ attribute="Throughput"
+ defaultValue={form.formState.defaultValues?.throughput?.toLocaleString() ?? 0}
+ newValue={form.getValues('throughput')?.toLocaleString() ?? 0}
+ unit="MiB/s"
+ beforePrice={Number(throughputPrice.oldPrice)}
+ afterPrice={Number(throughputPrice.newPrice)}
+ priceTooltip={numReplicas > 0 ? replicaTooltipText : undefined}
+ />
+ )}
+ {form.formState.defaultValues?.totalSize !== form.getValues('totalSize') && (
+ <TableDataRow
+ attribute="Disk size"
+ defaultValue={form.formState.defaultValues?.totalSize?.toLocaleString() ?? 0}
+ newValue={form.getValues('totalSize')?.toLocaleString()}
+ unit="GB"
+ beforePrice={Number(diskSizePrice.oldPrice)}
+ afterPrice={Number(diskSizePrice.newPrice)}
priceTooltip={numReplicas > 0 ? replicaTooltipText : undefined}
/>
- ) : (
- <TableRow>
- <TableCell className="pl-5">
- <div className="flex flex-row gap-2 items-center">
- <span>Throughput</span>
- </div>
- </TableCell>
- <TableCell colSpan={3}>
- <p className="text-foreground-lighter text-xs text-center">
- Throughput is not configurable for io2 storage type
- </p>
- </TableCell>
- </TableRow>
)}
- <TableDataRow
- attribute="Disk size"
- defaultValue={form.formState.defaultValues?.totalSize?.toLocaleString() ?? 0}
- newValue={form.getValues('totalSize')?.toLocaleString()}
- unit="GB"
- beforePrice={Number(diskSizePrice.oldPrice)}
- afterPrice={Number(diskSizePrice.newPrice)}
- priceTooltip={numReplicas > 0 ? replicaTooltipText : undefined}
- />
</TableBody>
</Table>
- <DialogSectionSeparator />
-
- <DiskMangementCoolDownSection />
+ {/* <DialogSectionSeparator /> */}
<DialogFooter>
- <Button block size="small" type="default" onClick={() => setIsDialogOpen(false)}>
+ <Button block size="large" type="default" onClick={() => setIsDialogOpen(false)}>
Cancel
</Button>
-
<Button
block
- size="small"
+ type={'warning'}
+ size="large"
htmlType="submit"
loading={loading}
onClick={async () => {
@@ -279,6 +347,20 @@ export const DiskManagementReviewAndSubmitDialog = ({
Confirm changes
</Button>
</DialogFooter>
+ {message && (
+ <>
+ <DialogSectionSeparator />
+ <DialogSection>
+ <Alert_Shadcn_
+ variant={message.type === 'error' ? 'destructive' : 'default'}
+ className=""
+ >
+ <WarningIcon />
+ <AlertTitle_Shadcn_>{message.message}</AlertTitle_Shadcn_>
+ </Alert_Shadcn_>
+ </DialogSection>
+ </>
+ )}
</DialogContent>
</Dialog>
)
diff --git a/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx b/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx
new file mode 100644
index 00000000000..1c001ad2d9d
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/fields/ComputeSizeField.tsx
@@ -0,0 +1,265 @@
+import { CpuIcon, Lock, Microchip } from 'lucide-react'
+import { useMemo } from 'react'
+import { UseFormReturn } from 'react-hook-form'
+
+import { components } from 'api-types'
+import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useProjectAddonsQuery } from 'data/subscriptions/project-addons-query'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { getCloudProviderArchitecture } from 'lib/cloudprovider-utils'
+import { cn, FormField_Shadcn_, RadioGroupCard, RadioGroupCardItem, Skeleton } from 'ui'
+import { ComputeBadge } from 'ui-patterns'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import { ComputeInstanceAddonVariantId } from '../DiskManagement.types'
+import {
+ calculateComputeSizePrice,
+ getAvailableComputeOptions,
+ showMicroUpgrade,
+} from '../DiskManagement.utils'
+import { BillingChangeBadge } from '../ui/BillingChangeBadge'
+import FormMessage from '../ui/FormMessage'
+import { NoticeBar } from '../ui/NoticeBar'
+import { InstanceSpecs } from 'lib/constants'
+
+/**
+ * to do: this could be a type from api-types
+ */
+type ComputeOption = {
+ identifier: ComputeInstanceAddonVariantId
+ name: string
+ price: number
+ price_interval: 'monthly' | 'hourly'
+ meta?: InstanceSpecs
+}
+
+type ComputeSizeFieldProps = {
+ form: UseFormReturn<DiskStorageSchemaType>
+ disabled?: boolean
+}
+
+export function ComputeSizeField({ form, disabled }: ComputeSizeFieldProps) {
+ const { ref } = useParams()
+ const org = useSelectedOrganization()
+ const { control, formState, setValue, trigger } = form
+
+ const {
+ /**
+ * no error/isError states handled here, as a parent component handles them
+ */
+ data: subscription,
+ } = useOrgSubscriptionQuery({ orgSlug: org?.slug })
+
+ const {
+ /**
+ * projectContext is used for:
+ * - cloud provider
+ * - infra_compute_size
+ */
+ project,
+ /**
+ * isLoading is used to avoid a useCheckPermissions() race condition
+ */
+ isLoading: isProjectLoading,
+ /**
+ * to do: there is no error/isError variables available for useProjectContext
+ */
+ } = useProjectContext()
+ const {
+ data: addons,
+ isLoading: isAddonsLoading,
+ error: addonsError,
+ } = useProjectAddonsQuery({ projectRef: ref })
+
+ const isLoading = isProjectLoading || isAddonsLoading
+
+ const availableAddons = useMemo(() => {
+ return addons?.available_addons ?? []
+ }, [addons])
+ const availableOptions = useMemo(() => {
+ /**
+ * Returns the available compute options for the project
+ * Also handles backwards compatibility for older API versions
+ * Also handles a case in which Nano is not available from the API
+ */
+ return getAvailableComputeOptions(availableAddons, project?.cloud_provider)
+ }, [availableAddons, project?.cloud_provider])
+
+ const computeSizePrice = calculateComputeSizePrice({
+ availableOptions: availableOptions,
+ oldComputeSize: form.formState.defaultValues?.computeSize || 'ci_micro',
+ newComputeSize: form.getValues('computeSize'),
+ plan: subscription?.plan.id ?? 'free',
+ })
+
+ const showUpgradeBadge = showMicroUpgrade(
+ subscription?.plan.id ?? 'free',
+ project?.infra_compute_size ?? 'nano'
+ )
+
+ return (
+ <FormField_Shadcn_
+ name="computeSize"
+ control={control}
+ render={({ field }) => (
+ <RadioGroupCard
+ {...field}
+ onValueChange={(value: ComputeInstanceAddonVariantId) => {
+ setValue('computeSize', value, {
+ shouldDirty: true,
+ shouldValidate: true,
+ })
+ trigger('provisionedIOPS')
+ trigger('throughput')
+ }}
+ defaultValue={field.value}
+ disabled={disabled}
+ >
+ <FormItemLayout
+ layout="horizontal"
+ label={'Compute size'}
+ id={field.name}
+ labelOptional={
+ <>
+ <BillingChangeBadge
+ className={'mb-2'}
+ show={
+ formState.isDirty &&
+ formState.dirtyFields.computeSize &&
+ !formState.errors.computeSize
+ }
+ beforePrice={Number(computeSizePrice.oldPrice)}
+ afterPrice={Number(computeSizePrice.newPrice)}
+ free={showUpgradeBadge && form.watch('computeSize') === 'ci_micro' ? true : false}
+ />
+ <p className="text-foreground-lighter">
+ Hardware resources allocated to your postgres database
+ </p>
+ <NoticeBar
+ showIcon={false}
+ type="default"
+ className="mt-3 border-violet-900 bg-violet-200 [&_h5]:text-violet-1100"
+ visible={showUpgradeBadge && form.watch('computeSize') === 'ci_nano'}
+ title={'Upgrade to Micro Compute at no additional charge'}
+ description="This Project is already paying for Micro Compute. You can upgrade to Micro Compute at any time when convenient."
+ />
+ </>
+ }
+ >
+ <div className={!addonsError ? 'grid grid-cols-2 xl:grid-cols-3 flex-wrap gap-3' : ''}>
+ {isLoading ? (
+ Array(10)
+ .fill(0)
+ .map((_, i) => <Skeleton key={i} className="w-full h-[110px] rounded-md" />)
+ ) : addonsError ? (
+ <FormMessage message={'Failed to load Compute size options'} type="error">
+ <p>{addonsError?.message}</p>
+ </FormMessage>
+ ) : (
+ availableOptions.map((compute: ComputeOption) => {
+ const cpuArchitecture = getCloudProviderArchitecture(project?.cloud_provider)
+
+ const lockedOption =
+ subscription?.plan.id !== 'free' &&
+ project?.infra_compute_size !== 'nano' &&
+ compute.identifier === 'ci_nano'
+
+ const price =
+ subscription?.plan.id !== 'free' &&
+ project?.infra_compute_size === 'nano' &&
+ compute.identifier === 'ci_nano'
+ ? availableOptions.find(
+ (option: ComputeOption) => option.identifier === 'ci_micro'
+ )?.price
+ : compute.price
+
+ return (
+ <RadioGroupCardItem
+ id={compute.identifier}
+ key={compute.identifier}
+ showIndicator={false}
+ value={compute.identifier}
+ className={cn(
+ 'relative text-sm text-left flex flex-col gap-0 px-0 py-3 [&_label]:w-full group] w-full h-[110px]',
+ lockedOption && 'opacity-50'
+ )}
+ disabled={disabled || lockedOption}
+ // @ts-expect-error
+ label={
+ <>
+ {showUpgradeBadge && compute.identifier === 'ci_micro' && (
+ <div className="absolute -top-4 -right-3 text-violet-1100 flex items-center gap-1 bg-surface-75 py-0.5 px-2 rounded-full border border-violet-900">
+ <span>No additional charge</span>
+ </div>
+ )}
+ <div className="w-full flex flex-col gap-3 justify-between">
+ <div className="relative px-3 opacity-50 group-data-[state=checked]:opacity-100 flex justify-between">
+ <ComputeBadge
+ className="inline-flex font-semibold"
+ infraComputeSize={
+ compute.name as components['schemas']['DbInstanceSize']
+ }
+ />
+ <div className="flex items-center space-x-1">
+ {lockedOption ? (
+ <div className="bg border rounded-lg h-7 w-7 flex items-center justify-center">
+ <Lock size={14} />
+ </div>
+ ) : (
+ <>
+ <span className="text-foreground text-sm font-semibold">
+ ${price}
+ </span>
+ <span className="text-foreground-light translate-y-[1px]">
+ {' '}
+ / {compute.price_interval === 'monthly' ? 'month' : 'hour'}
+ </span>
+ </>
+ )}
+ </div>
+ </div>
+
+ <div className="w-full">
+ <div className="px-3 text-sm flex flex-col gap-1">
+ <div className="text-foreground-light flex gap-2 items-center">
+ <Microchip
+ strokeWidth={1}
+ size={14}
+ className="text-foreground-lighter"
+ />
+ <span>
+ {compute.identifier === 'ci_nano' && 'Up to '}
+ {compute.meta?.memory_gb ?? 0} GB memory
+ </span>
+ </div>
+ <div className="text-foreground-light flex gap-2 items-center">
+ <CpuIcon
+ strokeWidth={1}
+ size={14}
+ className="text-foreground-lighter"
+ />
+ <span>
+ {compute.meta?.cpu_cores ?? 0}
+ {compute.meta?.cpu_cores !== 'Shared' &&
+ `-core ${cpuArchitecture}`}{' '}
+ CPU
+ </span>
+ </div>
+ </div>
+ </div>
+ </div>
+ </>
+ }
+ />
+ )
+ })
+ )}
+ </div>
+ </FormItemLayout>
+ </RadioGroupCard>
+ )}
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/fields/DiskSizeField.tsx b/apps/studio/components/interfaces/DiskManagement/fields/DiskSizeField.tsx
new file mode 100644
index 00000000000..7016c604824
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/fields/DiskSizeField.tsx
@@ -0,0 +1,188 @@
+import { UseFormReturn } from 'react-hook-form'
+
+import { InputVariants } from '@ui/components/shadcn/ui/input'
+import { useParams } from 'common'
+import { useDiskAttributesQuery } from 'data/config/disk-attributes-query'
+import { useDiskUtilizationQuery } from 'data/config/disk-utilization-query'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { GB } from 'lib/constants'
+import { Button, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_, Skeleton, cn } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import { calculateDiskSizePrice } from '../DiskManagement.utils'
+import { BillingChangeBadge } from '../ui/BillingChangeBadge'
+import { DiskType, PLAN_DETAILS } from '../ui/DiskManagement.constants'
+import { DiskManagementDiskSizeReadReplicas } from '../ui/DiskManagementReadReplicas'
+import DiskSpaceBar from '../ui/DiskSpaceBar'
+import { DiskTypeReccomendationSection } from '../ui/DiskTypeRecommendationSection'
+import FormMessage from '../ui/FormMessage'
+import { InputPostTab } from '../ui/InputPostTab'
+import { InputResetButton } from '../ui/InputResetButton'
+
+type DiskSizeFieldProps = {
+ form: UseFormReturn<DiskStorageSchemaType>
+ disableInput: boolean
+ setAdvancedSettingsOpenState: (state: boolean) => void
+}
+
+export function DiskSizeField({
+ form,
+ disableInput,
+ setAdvancedSettingsOpenState,
+}: DiskSizeFieldProps) {
+ const { ref: projectRef } = useParams()
+ const { control, formState, setValue, trigger, getValues, resetField, watch } = form
+ const org = useSelectedOrganization()
+
+ const {
+ isLoading: isLoadingDiskAttributes,
+ error: diskAttributesError,
+ isError: isDiskAttributesError,
+ } = useDiskAttributesQuery({ projectRef })
+ const {
+ data: subscription,
+ isLoading: isSubscriptionLoading,
+ error: subscriptionError,
+ isError: isSubscriptionError,
+ } = useOrgSubscriptionQuery({
+ orgSlug: org?.slug,
+ })
+ const {
+ data: diskUtil,
+ isLoading: isDiskUtilizationLoading,
+ error: diskUtilError,
+ isError: isDiskUtilizationError,
+ } = useDiskUtilizationQuery({
+ projectRef: projectRef,
+ })
+
+ const isLoading = isSubscriptionLoading || isDiskUtilizationLoading || isLoadingDiskAttributes
+ const error = subscriptionError || diskUtilError || diskAttributesError
+ const isError = isSubscriptionError || isDiskUtilizationError || isDiskAttributesError
+
+ const watchedStorageType = watch('storageType')
+ const watchedTotalSize = watch('totalSize')
+
+ const planId = subscription?.plan.id ?? 'free'
+
+ const { includedDiskGB: includedDiskGBMeta } =
+ PLAN_DETAILS?.[planId as keyof typeof PLAN_DETAILS] ?? {}
+ const includedDiskGB = includedDiskGBMeta[watchedStorageType]
+
+ const diskSizePrice = calculateDiskSizePrice({
+ planId,
+ oldSize: formState.defaultValues?.totalSize || 0,
+ oldStorageType: formState.defaultValues?.storageType as DiskType,
+ newSize: getValues('totalSize'),
+ newStorageType: getValues('storageType') as DiskType,
+ })
+
+ const isAllocatedStorageDirty = !!formState.dirtyFields.totalSize
+ const mainDiskUsed = Math.round(((diskUtil?.metrics.fs_used_bytes ?? 0) / GB) * 100) / 100
+
+ return (
+ <div className="grid grid-cols-12 gap-5">
+ <div className="col-span-4">
+ <FormField_Shadcn_
+ name="totalSize"
+ control={control}
+ render={({ field }) => (
+ <FormItemLayout label="Disk Size" layout="vertical" id={field.name}>
+ <div className="relative flex gap-2 items-center">
+ <InputPostTab label="GB">
+ {isLoading ? (
+ <div
+ className={cn(
+ InputVariants({ size: 'small' }),
+ 'w-32 font-mono rounded-r-none'
+ )}
+ >
+ <Skeleton className="w-10 h-4" />
+ </div>
+ ) : (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ type="number"
+ id={field.name}
+ {...field}
+ disabled={disableInput || isError}
+ className="w-32 font-mono rounded-r-none"
+ onWheel={(e) => e.currentTarget.blur()}
+ onChange={(e) => {
+ setValue('totalSize', e.target.valueAsNumber, {
+ shouldDirty: true,
+ shouldValidate: true,
+ })
+ trigger('provisionedIOPS')
+ trigger('throughput')
+ }}
+ min={includedDiskGB}
+ />
+ </FormControl_Shadcn_>
+ )}
+ </InputPostTab>
+ <InputResetButton
+ isDirty={isAllocatedStorageDirty}
+ onClick={() => {
+ resetField('totalSize')
+ trigger('provisionedIOPS')
+ }}
+ />
+ </div>
+ </FormItemLayout>
+ )}
+ />
+ <div className="flex flex-col gap-1">
+ <BillingChangeBadge
+ className="mt-1"
+ beforePrice={Number(diskSizePrice.oldPrice)}
+ afterPrice={Number(diskSizePrice.newPrice)}
+ show={
+ formState.isDirty &&
+ !formState.errors.totalSize &&
+ diskSizePrice.oldPrice !== diskSizePrice.newPrice
+ }
+ />
+ <span className="text-foreground-lighter text-sm">
+ {includedDiskGB > 0 &&
+ subscription?.plan.id &&
+ `Your plan includes ${includedDiskGB} GB of disk size for ${watchedStorageType}.`}
+ </span>
+ <DiskTypeReccomendationSection
+ form={form}
+ actions={
+ <Button
+ type="default"
+ onClick={() => {
+ setValue('storageType', 'io2')
+ trigger('provisionedIOPS')
+ trigger('totalSize')
+ setAdvancedSettingsOpenState(true)
+ }}
+ >
+ Change to High Performance SSD
+ </Button>
+ }
+ />
+ </div>
+ </div>
+ <div className="col-span-8">
+ <DiskSpaceBar form={form} />
+ {error && (
+ <FormMessage message="Failed to load disk size data" type="error">
+ {error?.message}
+ </FormMessage>
+ )}
+ <DiskManagementDiskSizeReadReplicas
+ isDirty={formState.dirtyFields.totalSize !== undefined}
+ totalSize={(formState.defaultValues?.totalSize || 0) * 1.25}
+ usedSize={mainDiskUsed}
+ newTotalSize={watchedTotalSize * 1.25}
+ oldStorageType={formState.defaultValues?.storageType as DiskType}
+ newStorageType={getValues('storageType') as DiskType}
+ />
+ </div>
+ </div>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/fields/IOPSField.tsx b/apps/studio/components/interfaces/DiskManagement/fields/IOPSField.tsx
new file mode 100644
index 00000000000..69d369dd9a1
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/fields/IOPSField.tsx
@@ -0,0 +1,145 @@
+import { UseFormReturn } from 'react-hook-form'
+
+import { InputVariants } from '@ui/components/shadcn/ui/input'
+import { useParams } from 'common'
+import { useDiskAttributesQuery } from 'data/config/disk-attributes-query'
+import { Button, cn, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_, Skeleton } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import {
+ calculateComputeSizeRequiredForIops,
+ calculateIOPSPrice,
+ mapAddOnVariantIdToComputeSize,
+} from '../DiskManagement.utils'
+import { BillingChangeBadge } from '../ui/BillingChangeBadge'
+import { ComputeSizeRecommendationSection } from '../ui/ComputeSizeRecommendationSection'
+import {
+ COMPUTE_BASELINE_IOPS,
+ DISK_LIMITS,
+ DiskType,
+ RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3,
+} from '../ui/DiskManagement.constants'
+import { DiskManagementIOPSReadReplicas } from '../ui/DiskManagementReadReplicas'
+import FormMessage from '../ui/FormMessage'
+import { InputPostTab } from '../ui/InputPostTab'
+
+type IOPSFieldProps = {
+ form: UseFormReturn<DiskStorageSchemaType>
+ disableInput: boolean
+}
+
+export function IOPSField({ form, disableInput }: IOPSFieldProps) {
+ const { ref: projectRef } = useParams()
+ const { control, formState, setValue, trigger, getValues, watch } = form
+
+ const watchedStorageType = watch('storageType')
+ const watchedComputeSize = watch('computeSize')
+ const watchedIOPS = watch('provisionedIOPS') ?? 0
+
+ const { isLoading, error, isError } = useDiskAttributesQuery({ projectRef })
+
+ const iopsPrice = calculateIOPSPrice({
+ oldStorageType: formState.defaultValues?.storageType as DiskType,
+ oldProvisionedIOPS: formState.defaultValues?.provisionedIOPS || 0,
+ newStorageType: getValues('storageType') as DiskType,
+ newProvisionedIOPS: getValues('provisionedIOPS'),
+ })
+
+ const disableIopsInput =
+ RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3.includes(watchedComputeSize) && watchedStorageType === 'gp3'
+
+ return (
+ <FormField_Shadcn_
+ control={control}
+ name="provisionedIOPS"
+ render={({ field }) => {
+ const reccomendedComputeSize = calculateComputeSizeRequiredForIops(watchedIOPS)
+ return (
+ <FormItemLayout
+ layout="horizontal"
+ label="IOPS"
+ id={field.name}
+ description={
+ <span className="flex flex-col gap-y-2">
+ <p>Use higher IOPS for high-throughput apps.</p>
+ <ComputeSizeRecommendationSection
+ form={form}
+ actions={
+ <Button
+ type="default"
+ onClick={() => {
+ setValue('computeSize', reccomendedComputeSize ?? 'ci_nano')
+ trigger('provisionedIOPS')
+ }}
+ >
+ Update to {mapAddOnVariantIdToComputeSize(reccomendedComputeSize)}
+ </Button>
+ }
+ />
+ {!formState.errors.provisionedIOPS && (
+ <DiskManagementIOPSReadReplicas
+ isDirty={formState.dirtyFields.provisionedIOPS !== undefined}
+ oldIOPS={formState.defaultValues?.provisionedIOPS ?? 0}
+ newIOPS={field.value}
+ oldStorageType={formState.defaultValues?.storageType as DiskType}
+ newStorageType={getValues('storageType') as DiskType}
+ />
+ )}
+ </span>
+ }
+ labelOptional={
+ <>
+ <BillingChangeBadge
+ show={
+ (watchedStorageType !== formState.defaultValues?.storageType ||
+ (watchedStorageType === 'gp3' &&
+ field.value !== formState.defaultValues?.provisionedIOPS)) &&
+ !formState.errors.provisionedIOPS &&
+ !disableIopsInput
+ }
+ beforePrice={Number(iopsPrice.oldPrice)}
+ afterPrice={Number(iopsPrice.newPrice)}
+ className="mb-2"
+ />
+ <p className="text-foreground-lighter">Input/output operations per second.</p>
+ </>
+ }
+ >
+ <InputPostTab label="IOPS">
+ {isLoading ? (
+ <div
+ className={cn(InputVariants({ size: 'small' }), 'w-32 font-mono rounded-r-none')}
+ >
+ <Skeleton className="w-10 h-4" />
+ </div>
+ ) : (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ type="number"
+ className="flex-grow font-mono rounded-r-none max-w-32"
+ {...field}
+ value={
+ disableIopsInput
+ ? COMPUTE_BASELINE_IOPS[
+ watchedComputeSize as keyof typeof COMPUTE_BASELINE_IOPS
+ ]
+ : field.value
+ }
+ disabled={disableInput || disableIopsInput || isError}
+ onChange={(e) => {
+ setValue('provisionedIOPS', e.target.valueAsNumber, {
+ shouldDirty: true,
+ shouldValidate: true,
+ })
+ }}
+ />
+ </FormControl_Shadcn_>
+ )}
+ </InputPostTab>
+ {error && <FormMessage type="error" message={error.message} />}
+ </FormItemLayout>
+ )
+ }}
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/fields/StorageTypeField.tsx b/apps/studio/components/interfaces/DiskManagement/fields/StorageTypeField.tsx
new file mode 100644
index 00000000000..cc9f89b5a25
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/fields/StorageTypeField.tsx
@@ -0,0 +1,108 @@
+import { UseFormReturn } from 'react-hook-form'
+
+import { useParams } from 'common'
+import { useDiskAttributesQuery } from 'data/config/disk-attributes-query'
+import {
+ Badge,
+ buttonVariants,
+ cn,
+ FormControl_Shadcn_,
+ FormField_Shadcn_,
+ Select_Shadcn_,
+ SelectContent_Shadcn_,
+ SelectItem_Shadcn_,
+ SelectTrigger_Shadcn_,
+ SelectValue_Shadcn_,
+ Skeleton,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import { DISK_LIMITS, DISK_TYPE_OPTIONS, DiskType } from '../ui/DiskManagement.constants'
+import FormMessage from '../ui/FormMessage'
+
+type StorageTypeFieldProps = {
+ form: UseFormReturn<DiskStorageSchemaType>
+ disableInput: boolean
+}
+
+export function StorageTypeField({ form, disableInput }: StorageTypeFieldProps) {
+ const { ref: projectRef } = useParams()
+ const { control, trigger } = form
+
+ const { isLoading, error, isError } = useDiskAttributesQuery({ projectRef })
+
+ return (
+ <FormField_Shadcn_
+ name="storageType"
+ control={control}
+ render={({ field }) => (
+ <FormItemLayout layout="horizontal" label="Storage type">
+ <Select_Shadcn_
+ {...field}
+ onValueChange={async (e: DiskType) => {
+ field.onChange(e)
+
+ /**
+ * Set default IOPS if not dirty
+ * This is to ensure that the IOPS is set to the minimum value if the user has not changed it
+ */
+ if (e === 'gp3') {
+ if (!form.getFieldState('provisionedIOPS').isDirty) {
+ form.setValue('provisionedIOPS', DISK_LIMITS[DiskType.GP3].minIops)
+ }
+ } else {
+ if (!form.getFieldState('provisionedIOPS').isDirty) {
+ form.setValue('provisionedIOPS', DISK_LIMITS[DiskType.IO2].minIops)
+ }
+ }
+
+ // trigger other fields to validate
+ await trigger('provisionedIOPS')
+ await trigger('totalSize')
+ }}
+ defaultValue={field.value}
+ disabled={disableInput || isError}
+ >
+ {isLoading ? (
+ <Skeleton
+ className={cn(
+ buttonVariants({ size: 'small' }),
+ 'h-14 min-w-[420px] duration-[2s]'
+ )}
+ />
+ ) : (
+ <FormControl_Shadcn_>
+ <SelectTrigger_Shadcn_ className="h-14 max-w-[420px]">
+ <SelectValue_Shadcn_ />
+ </SelectTrigger_Shadcn_>
+ </FormControl_Shadcn_>
+ )}
+ <SelectContent_Shadcn_>
+ <>
+ {DISK_TYPE_OPTIONS.map((item) => (
+ <SelectItem_Shadcn_ key={item.type} disabled={disableInput} value={item.type}>
+ <div className="flex flex-col gap-0 items-start">
+ <div className="flex gap-3 items-center">
+ <span className="text-sm text-foreground">{item.name}</span>{' '}
+ <div>
+ <Badge
+ variant={'outline'}
+ className="font-mono bg-alternative bg-opacity-100"
+ >
+ {item.type}
+ </Badge>
+ </div>
+ </div>
+ <p className="text-foreground-light">{item.description}</p>
+ </div>
+ </SelectItem_Shadcn_>
+ ))}
+ </>
+ </SelectContent_Shadcn_>
+ </Select_Shadcn_>
+ {error && <FormMessage type="error" message={error.message} />}
+ </FormItemLayout>
+ )}
+ />
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/fields/ThroughputField.tsx b/apps/studio/components/interfaces/DiskManagement/fields/ThroughputField.tsx
new file mode 100644
index 00000000000..1a9089bba5d
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/fields/ThroughputField.tsx
@@ -0,0 +1,155 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { useEffect } from 'react'
+import { UseFormReturn } from 'react-hook-form'
+
+import { InputVariants } from '@ui/components/shadcn/ui/input'
+import { useParams } from 'common'
+import { useDiskAttributesQuery } from 'data/config/disk-attributes-query'
+import { cn, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_, Skeleton } from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import { calculateThroughputPrice } from '../DiskManagement.utils'
+import { BillingChangeBadge } from '../ui/BillingChangeBadge'
+import {
+ COMPUTE_BASELINE_THROUGHPUT,
+ DiskType,
+ RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3,
+ THROUGHPUT_RANGE,
+} from '../ui/DiskManagement.constants'
+import { DiskManagementThroughputReadReplicas } from '../ui/DiskManagementReadReplicas'
+import FormMessage from '../ui/FormMessage'
+import { InputPostTab } from '../ui/InputPostTab'
+
+type ThroughputFieldProps = {
+ form: UseFormReturn<DiskStorageSchemaType>
+ disableInput: boolean
+}
+
+export function ThroughputField({ form, disableInput }: ThroughputFieldProps) {
+ const { ref: projectRef } = useParams()
+
+ const { control, formState, setValue, getValues, watch } = form
+
+ const watchedStorageType = watch('storageType')
+ const watchedTotalSize = watch('totalSize')
+ const watchedComputeSize = watch('computeSize')
+ const throughput_mbps = formState.defaultValues?.throughput
+
+ const { isLoading, error } = useDiskAttributesQuery({ projectRef })
+
+ const throughputPrice = calculateThroughputPrice({
+ storageType: form.getValues('storageType') as DiskType,
+ newThroughput: form.getValues('throughput') || 0,
+ oldThroughput: form.formState.defaultValues?.throughput || 0,
+ })
+
+ const disableIopsInput =
+ RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3.includes(watchedComputeSize) && watchedStorageType === 'gp3'
+
+ // Watch storageType and allocatedStorage to adjust constraints dynamically
+ useEffect(() => {
+ if (watchedStorageType === 'io2') {
+ setValue('throughput', undefined) // Throughput is not configurable for 'io2'
+ } else if (watchedStorageType === 'gp3') {
+ // Ensure throughput is within the allowed range if it's greater than or equal to 400 GB
+ const currentThroughput = form.getValues('throughput')
+ const { min, max } = THROUGHPUT_RANGE[DiskType.GP3]
+ if (!currentThroughput || currentThroughput < min || currentThroughput > max) {
+ setValue('throughput', min) // Reset to default if undefined or out of bounds
+ }
+ }
+ }, [watchedStorageType, watchedTotalSize, setValue, form])
+
+ return (
+ <AnimatePresence initial={false}>
+ {getValues('storageType') === 'gp3' && (
+ <motion.div
+ key="throughPutContainer"
+ initial={{ opacity: 0, x: -4, height: 0 }}
+ animate={{ opacity: 1, x: 0, height: 'auto' }}
+ exit={{ opacity: 0, x: -4, height: 0 }}
+ transition={{ duration: 0.1 }}
+ style={{ overflow: 'hidden' }}
+ >
+ <FormField_Shadcn_
+ name="throughput"
+ control={control}
+ render={({ field }) => (
+ <FormItemLayout
+ label="Throughput"
+ layout="horizontal"
+ description={
+ <span className="flex flex-col gap-y-2">
+ <p>Higher throughput suits applications with high data transfer needs.</p>
+ {!formState.errors.throughput && (
+ <DiskManagementThroughputReadReplicas
+ isDirty={formState.dirtyFields.throughput !== undefined}
+ oldThroughput={throughput_mbps ?? 0}
+ newThroughput={field.value ?? 0}
+ oldStorageType={formState.defaultValues?.storageType as DiskType}
+ newStorageType={getValues('storageType') as DiskType}
+ />
+ )}
+ </span>
+ }
+ labelOptional={
+ <>
+ <BillingChangeBadge
+ show={
+ formState.isDirty &&
+ formState.dirtyFields.throughput &&
+ !formState.errors.throughput
+ }
+ beforePrice={Number(throughputPrice.oldPrice)}
+ afterPrice={Number(throughputPrice.newPrice)}
+ className="mb-2"
+ />
+ <p className="text-foreground-lighter">
+ Amount of data read/written per second.
+ </p>
+ </>
+ }
+ >
+ <InputPostTab label="MiB/s">
+ {isLoading ? (
+ <div
+ className={cn(
+ InputVariants({ size: 'small' }),
+ 'w-32 font-mono rounded-r-none'
+ )}
+ >
+ <Skeleton className="w-10 h-4" />
+ </div>
+ ) : (
+ <FormControl_Shadcn_>
+ <Input_Shadcn_
+ type="number"
+ {...field}
+ value={
+ disableIopsInput
+ ? COMPUTE_BASELINE_THROUGHPUT[
+ watchedComputeSize as keyof typeof COMPUTE_BASELINE_THROUGHPUT
+ ]
+ : field.value
+ }
+ onChange={(e) => {
+ setValue('throughput', e.target.valueAsNumber, {
+ shouldDirty: true,
+ shouldValidate: true,
+ })
+ }}
+ className="flex-grow font-mono rounded-r-none max-w-32"
+ disabled={disableInput || disableIopsInput || watchedStorageType === 'io2'}
+ />
+ </FormControl_Shadcn_>
+ )}
+ </InputPostTab>
+ {error && <FormMessage type="error" message={error.message} />}
+ </FormItemLayout>
+ )}
+ />
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/BillingChangeBadge.tsx b/apps/studio/components/interfaces/DiskManagement/ui/BillingChangeBadge.tsx
similarity index 50%
rename from apps/studio/components/interfaces/DiskManagement/BillingChangeBadge.tsx
rename to apps/studio/components/interfaces/DiskManagement/ui/BillingChangeBadge.tsx
index 231d94551f8..a1d955945a1 100644
--- a/apps/studio/components/interfaces/DiskManagement/BillingChangeBadge.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/ui/BillingChangeBadge.tsx
@@ -1,13 +1,16 @@
import { AnimatePresence, motion } from 'framer-motion'
-import { formatCurrency } from 'lib/helpers'
import { ChevronRight } from 'lucide-react'
-import { Badge, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'
+
+import { formatCurrency } from 'lib/helpers'
+import { Badge, cn, Tooltip_Shadcn_, TooltipContent_Shadcn_, TooltipTrigger_Shadcn_ } from 'ui'
interface BillingChangeBadgeProps {
beforePrice?: number
afterPrice?: number
show: boolean | undefined
tooltip?: string
+ className?: string
+ free?: boolean
}
const BillingChangeBadge = ({
@@ -15,17 +18,26 @@ const BillingChangeBadge = ({
afterPrice,
show,
tooltip,
+ className,
+ free,
}: BillingChangeBadgeProps) => {
return (
<AnimatePresence>
{beforePrice !== undefined && afterPrice !== undefined && show && (
<motion.div
- initial={{ opacity: 0, x: -4 }}
- animate={{ opacity: 1, x: 0 }}
- exit={{ opacity: 0, x: -4 }}
- transition={{ duration: 0.15 }}
+ initial={{ opacity: 0, x: -4, height: 0 }}
+ animate={{ opacity: 1, x: 0, height: 'auto' }}
+ exit={{ opacity: 0, x: -4, height: 0 }}
+ transition={{ type: 'spring', stiffness: 800, damping: 40, duration: 0.3 }}
>
- <Badge variant="default" className="bg-alternative bg-opacity-100">
+ <Badge
+ variant="default"
+ className={cn(
+ !free ? `bg-alternative` : `bg-violet-200 border-violet-900 text-violet-1100`,
+ `bg-opacity-100 text-warning`,
+ className
+ )}
+ >
<Tooltip_Shadcn_>
<TooltipTrigger_Shadcn_ asChild>
<div className="flex items-center gap-1">
@@ -33,9 +45,17 @@ const BillingChangeBadge = ({
{formatCurrency(beforePrice)}
</span>
<ChevronRight size={12} strokeWidth={2} className="text-foreground-muted" />
- <span className="text-xs font-mono text-foreground">
- {formatCurrency(afterPrice)}
- </span>
+ <motion.span
+ key={afterPrice} // This key will change whenever any form value changes
+ className={cn(
+ free ? 'text-violet-1100' : 'text-foreground',
+ 'text-xs font-mono'
+ )}
+ animate={{ scale: [1, 1.1, 1] }}
+ transition={{ duration: 0.12 }}
+ >
+ {`${formatCurrency(afterPrice)}/month`}
+ </motion.span>
</div>
</TooltipTrigger_Shadcn_>
{tooltip !== undefined && (
@@ -49,4 +69,4 @@ const BillingChangeBadge = ({
)
}
-export default BillingChangeBadge
+export { BillingChangeBadge }
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx b/apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
new file mode 100644
index 00000000000..b07bcc22ae8
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/ComputeSizeRecommendationSection.tsx
@@ -0,0 +1,65 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { ReactNode } from 'react'
+import { UseFormReturn } from 'react-hook-form'
+
+import { Admonition } from 'ui-patterns/admonition'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import {
+ calculateComputeSizeRequiredForIops,
+ calculateMaxIopsAllowedForComputeSize,
+ mapAddOnVariantIdToComputeSize,
+} from '../DiskManagement.utils'
+import {
+ COMPUTE_BASELINE_IOPS,
+ RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3,
+} from './DiskManagement.constants'
+
+interface ComputeSizeRecommendationSectionProps {
+ actions?: ReactNode
+ form: UseFormReturn<DiskStorageSchemaType>
+}
+
+export function ComputeSizeRecommendationSection({
+ actions,
+ form,
+}: ComputeSizeRecommendationSectionProps) {
+ const { watch } = form
+ const computeSize = watch('computeSize')
+ const iops = watch('provisionedIOPS')
+
+ const computeSizeRecommendedForIops = calculateComputeSizeRequiredForIops(iops)
+ const maxIOPSforComputeSize = calculateMaxIopsAllowedForComputeSize(computeSize ?? 'ci_micro')
+ const isVisible =
+ iops > maxIOPSforComputeSize && !RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3.includes(computeSize)
+
+ return (
+ <AnimatePresence initial={false}>
+ {isVisible && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: 'auto' }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.15 }}
+ >
+ <Admonition
+ type="default"
+ title={`Your Compute size can only support a baseline IOPS of ${COMPUTE_BASELINE_IOPS[computeSize]}`}
+ >
+ <div className="flex flex-col gap-2">
+ <div>
+ <p className="text-sm text-foreground-light">
+ To achieve sustained IOPS performance we recommend using the{' '}
+ <span className="text-foreground">
+ {mapAddOnVariantIdToComputeSize(computeSizeRecommendedForIops)}
+ </span>{' '}
+ compute size.
+ </p>
+ </div>
+ {actions && <div>{actions}</div>}
+ </div>
+ </Admonition>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/DiskCountdownRadial.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskCountdownRadial.tsx
new file mode 100644
index 00000000000..3f4b6389d2a
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskCountdownRadial.tsx
@@ -0,0 +1,71 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { useEffect, useState } from 'react'
+
+import { useParams } from 'common'
+import CountdownTimerRadial from 'components/ui/CountdownTimer/CountdownTimerRadial'
+import CountdownTimerSpan from 'components/ui/CountdownTimer/CountdownTimerSpan'
+import { useRemainingDurationForDiskAttributeUpdate } from 'data/config/disk-attributes-query'
+import { COOLDOWN_DURATION } from 'data/config/disk-attributes-update-mutation'
+import { Card, CardContent } from 'ui'
+import FormMessage from './FormMessage'
+
+export function DiskCountdownRadial() {
+ const { ref } = useParams()
+ const [remainingTime, setRemainingTime] = useState(0)
+
+ const {
+ remainingDuration: initialRemainingTime,
+ error,
+ isSuccess,
+ } = useRemainingDurationForDiskAttributeUpdate({
+ projectRef: ref,
+ })
+
+ const progressPercentage = (remainingTime / COOLDOWN_DURATION) * 100
+
+ useEffect(() => {
+ if (initialRemainingTime > 0) setRemainingTime(initialRemainingTime)
+ }, [initialRemainingTime])
+
+ useEffect(() => {
+ if (remainingTime <= 0) return
+
+ const timer = setInterval(() => {
+ setRemainingTime(Math.max(0, remainingTime - 1))
+ }, 1000)
+
+ return () => clearInterval(timer)
+ }, [remainingTime])
+
+ return (
+ <AnimatePresence>
+ {remainingTime > 0 && isSuccess && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: 'auto' }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.2 }}
+ >
+ <Card className="px-2 rounded bg-surface-100">
+ <CardContent className="py-3 flex gap-3 px-3 items-start">
+ <CountdownTimerRadial progress={progressPercentage} />
+ <div className="flex flex-col gap-2">
+ <div>
+ <p className="text-foreground text-sm p-0">
+ 6-hour cooldown period is in progress
+ </p>
+ <p className="text-foreground-lighter text-sm p-0">
+ You can't modify your disk configuration again until the 6-hour cool down period
+ ends.
+ </p>
+ </div>
+ <CountdownTimerSpan seconds={remainingTime} />
+ </div>
+ </CardContent>
+ </Card>
+ </motion.div>
+ )}
+ {error && <FormMessage message={error.message} type="error" />}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.constants.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx
similarity index 58%
rename from apps/studio/components/interfaces/DiskManagement/DiskManagement.constants.tsx
rename to apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx
index bbb36e62d9c..e016f1a7a09 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagement.constants.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx
@@ -66,11 +66,25 @@ export const PLAN_DETAILS: Record<PlanType, PlanDetails> = {
enterprise: { includedDiskGB: { gp3: 8, io2: 0 } },
}
-export const COMPUTE_SIZE_MAX_IOPS = {
+export const COMPUTE_BASELINE_IOPS = {
+ ci_nano: 250,
+ ci_micro: 500,
+ ci_small: 1000,
+ ci_medium: 2000,
+ ci_large: 3600,
+ ci_xlarge: 6000,
+ ci_2xlarge: 12000,
+ ci_4xlarge: 20000,
+ ci_8xlarge: 40000,
+ ci_12xlarge: 50000,
+ ci_16xlarge: 80000,
+}
+export const COMPUTE_MAX_IOPS = {
+ ci_nano: 11800,
ci_micro: 11800,
ci_small: 11800,
ci_medium: 11800,
- ci_large: 4750,
+ ci_large: 20000,
ci_xlarge: 20000,
ci_2xlarge: 20000,
ci_4xlarge: 20000,
@@ -78,16 +92,51 @@ export const COMPUTE_SIZE_MAX_IOPS = {
ci_12xlarge: 50000,
ci_16xlarge: 80000,
}
-
-export const COMPUTE_SIZE_MAX_THROUGHPUT = {
- ci_micro: 260.625,
- ci_small: 260.625,
- ci_medium: 260.625,
- ci_large: 593.75,
- ci_xlarge: 593.75,
- ci_2xlarge: 593.75,
- ci_4xlarge: 593.75,
- ci_8xlarge: 1187.5,
- ci_12xlarge: 1781.25,
- ci_16xlarge: 2375,
+export const COMPUTE_BASELINE_THROUGHPUT = {
+ ci_nano: 43,
+ ci_micro: 87,
+ ci_small: 174,
+ ci_medium: 347,
+ ci_large: 630,
+ ci_xlarge: 1188,
+ ci_2xlarge: 2375,
+ ci_4xlarge: 4750,
+ ci_8xlarge: 9500,
+ ci_12xlarge: 14250,
+ ci_16xlarge: 19000,
}
+export const COMPUTE_MAX_THROUGHPUT = {
+ ci_nano: 2085,
+ ci_micro: 2085,
+ ci_small: 2085,
+ ci_medium: 2085,
+ ci_large: 4750,
+ ci_xlarge: 4750,
+ ci_2xlarge: 4750,
+ ci_4xlarge: 4750,
+ ci_8xlarge: 9500,
+ ci_12xlarge: 14250,
+ ci_16xlarge: 19000,
+}
+
+export const RESTRICTED_COMPUTE_FOR_IOPS_ON_GP3 = ['ci_nano', 'ci_micro', 'ci_small', 'ci_medium']
+
+export const RESTRICTED_COMPUTE_FOR_THROUGHPUT_ON_GP3 = [
+ 'ci_nano',
+ 'ci_micro',
+ 'ci_small',
+ 'ci_medium',
+]
+
+export const DISK_TYPE_OPTIONS = [
+ {
+ type: 'gp3',
+ name: 'General Purpose SSD',
+ description: 'Balance between price and performance',
+ },
+ {
+ type: 'io2',
+ name: 'High Performance SSD',
+ description: 'High performance for mission critical applications',
+ },
+]
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementCoolDownSection.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagementCoolDownSection.tsx
similarity index 74%
rename from apps/studio/components/interfaces/DiskManagement/DiskManagementCoolDownSection.tsx
rename to apps/studio/components/interfaces/DiskManagement/ui/DiskManagementCoolDownSection.tsx
index 2ca83f4cccb..c6d2349e0f3 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementCoolDownSection.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagementCoolDownSection.tsx
@@ -1,15 +1,13 @@
import { AnimatePresence, motion } from 'framer-motion'
-import { X } from 'lucide-react'
-import React, { useEffect, useState } from 'react'
+import { useEffect, useState } from 'react'
+import CountdownTimerRadial from 'components/ui/CountdownTimer/CountdownTimerRadial'
import { DialogSection } from 'ui'
-import CountdownTimerRadial from '../../ui/CountdownTimer/CountdownTimerRadial'
-export const DiskMangementCoolDownSection: React.FC = () => {
+export const DiskMangementCoolDownSection = ({ visible }: { visible: boolean }) => {
const [progress, setProgress] = useState(100)
const [showCountdown, setShowCountdown] = useState(false)
const [isJumping, setIsJumping] = useState(false)
- const [isVisible, setIsVisible] = useState(true)
useEffect(() => {
const startCountdown = () => {
@@ -41,14 +39,15 @@ export const DiskMangementCoolDownSection: React.FC = () => {
return (
<AnimatePresence>
- {isVisible && (
+ {visible && (
<motion.div
initial={{ opacity: 1, height: 'auto' }}
exit={{ opacity: 0, height: 0 }}
transition={{ duration: 0.15 }}
+ className="w-full"
>
- <DialogSection className="bg-surface-100 text-sm text-foreground-light flex items-center gap-4 relative">
- <div className="w-12 h-12 opacity-75">
+ <DialogSection className="bg-surface-100 text-sm text-foreground-light flex items-center gap-4 relative w-full border rounded-md">
+ <div className="w-12 h-12">
<AnimatePresence>
{showCountdown && (
<motion.div
@@ -73,19 +72,12 @@ export const DiskMangementCoolDownSection: React.FC = () => {
</div>
<div className="flex flex-col gap-0 flex-grow">
<p className="text-sm text-foreground">
- For 6 hours you will not be able to make further changes.
+ For 6 hours you will not be able to change any disk attributes.
</p>
<p className="text-sm text-foreground-light">
- Due to a cooldown period between disk changes.
+ There is a cooldown period enforced for any disk attribute modifications
</p>
</div>
- <button
- type="button"
- className="text-foreground-lighter hover:text-foreground-light transition-colors self-start p-1"
- onClick={() => setIsVisible(false)}
- >
- <X size={14} />
- </button>
</DialogSection>
</motion.div>
)}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementReadReplicas.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagementReadReplicas.tsx
similarity index 98%
rename from apps/studio/components/interfaces/DiskManagement/DiskManagementReadReplicas.tsx
rename to apps/studio/components/interfaces/DiskManagement/ui/DiskManagementReadReplicas.tsx
index e892266f0ce..ebb9d10ea07 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementReadReplicas.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagementReadReplicas.tsx
@@ -1,5 +1,4 @@
import { AnimatePresence, motion } from 'framer-motion'
-import { useState } from 'react'
import { useParams } from 'common'
import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
@@ -10,7 +9,7 @@ import {
AlertTitle_Shadcn_ as AlertTitle,
InfoIcon,
} from 'ui'
-import BillingChangeBadge from './BillingChangeBadge'
+import { BillingChangeBadge } from './BillingChangeBadge'
import { DISK_LIMITS, DISK_PRICING, DiskType } from './DiskManagement.constants'
interface DiskManagementDiskSizeReadReplicasProps {
@@ -31,7 +30,6 @@ export const DiskManagementDiskSizeReadReplicas = ({
newStorageType,
}: DiskManagementDiskSizeReadReplicasProps) => {
const { ref: projectRef } = useParams()
- const [isOpen, setIsOpen] = useState(false)
const { data: databases } = useReadReplicasQuery({ projectRef })
const readReplicas = (databases ?? []).filter((db) => db.identifier !== projectRef)
@@ -155,7 +153,7 @@ export const DiskManagementIOPSReadReplicas = ({
if (readReplicas.length === 0) return null
return (
- <AnimatePresence>
+ <AnimatePresence initial={false}>
{isDirty && (
<motion.div
initial={{ opacity: 0, height: 0 }}
@@ -218,7 +216,7 @@ export const DiskManagementThroughputReadReplicas = ({
if (readReplicas.length === 0) return null
return (
- <AnimatePresence>
+ <AnimatePresence initial={false}>
{isDirty && (
<motion.div
initial={{ opacity: 0, height: 0 }}
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskSpaceBar.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsx
similarity index 80%
rename from apps/studio/components/interfaces/DiskManagement/DiskSpaceBar.tsx
rename to apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsx
index 4c588d05af4..6e4ee124f96 100644
--- a/apps/studio/components/interfaces/DiskManagement/DiskSpaceBar.tsx
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsx
@@ -1,6 +1,14 @@
import { AnimatePresence, motion } from 'framer-motion'
+import { Info } from 'lucide-react'
import MotionNumber from 'motion-number'
+import { UseFormReturn } from 'react-hook-form'
+import { useParams } from 'common'
+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
+import { useDiskUtilizationQuery } from 'data/config/disk-utilization-query'
+import { useDatabaseSizeQuery } from 'data/database/database-size-query'
+import { GB } from 'lib/constants'
+import { formatBytes } from 'lib/helpers'
import {
badgeVariants,
cn,
@@ -8,25 +16,29 @@ import {
TooltipContent_Shadcn_,
TooltipTrigger_Shadcn_,
} from 'ui'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
import { AUTOSCALING_THRESHOLD } from './DiskManagement.constants'
-import { Info } from 'lucide-react'
-import { formatBytes } from 'lib/helpers'
-import { useDatabaseSizeQuery } from 'data/database/database-size-query'
-import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
interface DiskSpaceBarProps {
- showNewBar: boolean
- totalSize: number
- usedSize: number
- newTotalSize: number
+ form: UseFormReturn<DiskStorageSchemaType>
}
-export default function DiskSpaceBar({
- showNewBar,
- totalSize,
- usedSize,
- newTotalSize,
-}: DiskSpaceBarProps) {
+export default function DiskSpaceBar({ form }: DiskSpaceBarProps) {
+ const { ref } = useParams()
+ const { formState, watch } = form
+
+ const {
+ data: diskUtil,
+ // to do, error handling
+ } = useDiskUtilizationQuery({
+ projectRef: ref,
+ })
+
+ const usedSize = Math.round(((diskUtil?.metrics.fs_used_bytes ?? 0) / GB) * 100) / 100
+ const totalSize = formState.defaultValues?.totalSize || 0
+ const show = formState.dirtyFields.totalSize !== undefined && usedSize
+ const newTotalSize = watch('totalSize')
+
const usedPercentage = (usedSize / totalSize) * 100
const resizePercentage = AUTOSCALING_THRESHOLD * 100
@@ -44,7 +56,8 @@ export default function DiskSpaceBar({
<div className="flex flex-col gap-2">
<div className="flex items-center h-6 gap-3">
<span className="text-foreground-light text-sm font-mono flex items-center gap-2">
- {usedSize.toFixed(2)} GB used of{' '}
+ {usedSize.toFixed(2)}
+ <span>GB used of </span>
<span className="text-foreground font-semibold -mt-[2px]">
<MotionNumber
value={newTotalSize}
@@ -61,12 +74,12 @@ export default function DiskSpaceBar({
<div className="relative">
<div
className={cn(
- 'h-[34px] relative border rounded-sm w-full transition',
- showNewBar ? 'bg-selection border border-brand-button' : 'bg-surface-300'
+ 'h-[35px] relative border rounded-sm w-full transition',
+ show ? 'bg-selection border border-brand-button' : 'bg-surface-300'
)}
>
<AnimatePresence>
- {!showNewBar ? (
+ {!show ? (
<motion.div
key="currentBar"
initial={{ rotateY: 90, zIndex: 2 }}
@@ -133,7 +146,7 @@ export default function DiskSpaceBar({
)}
</AnimatePresence>
<AnimatePresence>
- {showNewBar && (
+ {show && (
<motion.span
initial={{ opacity: 0, x: 4 }}
animate={{ opacity: 1, x: 0 }}
@@ -149,8 +162,8 @@ export default function DiskSpaceBar({
)}
</AnimatePresence>
</div>
- <AnimatePresence mode="wait">
- {!showNewBar && (
+ <AnimatePresence initial={true}>
+ {!show && (
<motion.div
key="currentSize"
initial={{ opacity: 0, y: -10 }}
@@ -161,7 +174,7 @@ export default function DiskSpaceBar({
>
<div
className="absolute top-0 -left-0 h-full flex items-center transition-all duration-500 ease-in-out"
- style={{ left: `${showNewBar ? newResizePercentage : resizePercentage}%` }}
+ style={{ left: `${show ? newResizePercentage : resizePercentage}%` }}
>
<Tooltip_Shadcn_>
<TooltipTrigger_Shadcn_ asChild>
@@ -187,17 +200,19 @@ export default function DiskSpaceBar({
)}
</AnimatePresence>
</div>
- <div className="flex items-center space-x-4 text-xs text-foreground-lighter">
- <div className="flex items-center">
- <div className="w-2 h-2 rounded-full bg-foreground mr-2" />
- <span>Used Space</span>
- </div>
- <div className="flex items-center">
- <div className="w-2 h-2 rounded-full bg-border border border-strong mr-2" />
- <span>Available space</span>
+ {!show && (
+ <div className="flex items-center space-x-4 text-xs text-foreground-lighter">
+ <div className="flex items-center">
+ <div className="w-2 h-2 rounded-full bg-foreground mr-2" />
+ <span>Used Space</span>
+ </div>
+ <div className="flex items-center">
+ <div className="w-2 h-2 rounded-full bg-border border border-strong mr-2" />
+ <span>Available space</span>
+ </div>
</div>
- </div>
- <p className="text-xs text-foreground-lighter mt-4">
+ )}
+ <p className="text-xs text-foreground-lighter my-4">
<span className="font-semibold">Note:</span> Disk Size refers to the total space your
project occupies on disk, including the database itself (currently{' '}
<span>{formatBytes(databaseSizeBytes, 2, 'GB')}</span>), additional files like the
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/DiskTypeRecommendationSection.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskTypeRecommendationSection.tsx
new file mode 100644
index 00000000000..b637daf3489
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskTypeRecommendationSection.tsx
@@ -0,0 +1,42 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { ReactNode } from 'react'
+import { UseFormReturn } from 'react-hook-form'
+
+import { Admonition } from 'ui-patterns/admonition'
+import { DiskStorageSchemaType } from '../DiskManagement.schema'
+import { DISK_LIMITS, DISK_TYPE_OPTIONS, DiskType } from './DiskManagement.constants'
+
+export function DiskTypeReccomendationSection({
+ actions,
+ form,
+}: {
+ actions?: ReactNode
+ form: UseFormReturn<DiskStorageSchemaType>
+}) {
+ const { watch } = form
+
+ const totalSize = watch('totalSize')
+ const storageType = watch('storageType')
+ const isVisible = storageType === DiskType.GP3 && totalSize > DISK_LIMITS[DiskType.GP3].maxStorage
+ const io2Option = DISK_TYPE_OPTIONS.find((option) => option.type === DiskType.IO2)
+
+ return (
+ <AnimatePresence initial={false}>
+ {isVisible && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: 'auto' }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.15 }}
+ >
+ <Admonition
+ type="default"
+ title={`You will need to use ${io2Option?.name} to use a larger Disk size`}
+ >
+ <div className="flex flex-col gap-2">{actions && <div>{actions}</div>}</div>
+ </Admonition>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/FormMessage.tsx b/apps/studio/components/interfaces/DiskManagement/ui/FormMessage.tsx
new file mode 100644
index 00000000000..99c9ddf5d65
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/FormMessage.tsx
@@ -0,0 +1,32 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { Admonition } from 'ui-patterns'
+
+interface FormMessageProps {
+ message: string
+ type?: 'error' | 'success'
+ children?: React.ReactNode
+}
+
+function FormMessage({ message = 'error', type, children }: FormMessageProps) {
+ return (
+ <AnimatePresence>
+ {message && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: 'auto' }}
+ exit={{ opacity: 0, height: 0 }}
+ >
+ <Admonition
+ type={type === 'error' ? 'destructive' : 'default'}
+ className="mt-2"
+ title={message}
+ >
+ {children}
+ </Admonition>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
+
+export default FormMessage
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/InputPostTab.tsx b/apps/studio/components/interfaces/DiskManagement/ui/InputPostTab.tsx
new file mode 100644
index 00000000000..a295b3c5efb
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/InputPostTab.tsx
@@ -0,0 +1,21 @@
+import { forwardRef, ReactNode } from 'react'
+
+interface InputPostTabProps {
+ children: ReactNode
+ label: string
+}
+
+export const InputPostTab = forwardRef<HTMLDivElement, InputPostTabProps>(
+ ({ children, label }, ref) => {
+ return (
+ <div ref={ref} className="flex -space-x-px">
+ {children}
+ <div className="border border-strong bg-surface-300 rounded-r-md px-3 flex items-center justify-center">
+ <span className="text-foreground-lighter text-xs font-mono">{label}</span>
+ </div>
+ </div>
+ )
+ }
+)
+
+InputPostTab.displayName = 'InputPostTab'
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/InputResetButton.tsx b/apps/studio/components/interfaces/DiskManagement/ui/InputResetButton.tsx
new file mode 100644
index 00000000000..3833b286a73
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/InputResetButton.tsx
@@ -0,0 +1,32 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { RotateCcw } from 'lucide-react'
+
+import { Button } from 'ui'
+
+function InputResetButton({ isDirty, onClick }: { isDirty: boolean; onClick: () => void }) {
+ return (
+ <AnimatePresence initial={false}>
+ {isDirty && (
+ <motion.div
+ key="reset-disksize"
+ initial={{ opacity: 0, scale: 0.95, x: -2 }}
+ animate={{ opacity: 1, scale: 1, x: 0 }}
+ exit={{ opacity: 0, scale: 0.95, x: -2 }}
+ transition={{ duration: 0.12 }}
+ >
+ <Button
+ htmlType="button"
+ type="default"
+ size="small"
+ className="px-2 text-foreground-light"
+ onClick={onClick}
+ >
+ <RotateCcw className="h-4 w-4" aria-hidden="true" />
+ </Button>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
+
+export { InputResetButton }
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/NoticeBar.tsx b/apps/studio/components/interfaces/DiskManagement/ui/NoticeBar.tsx
new file mode 100644
index 00000000000..89ce0071671
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/NoticeBar.tsx
@@ -0,0 +1,34 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import { LucideIcon } from 'lucide-react'
+import { ComponentProps } from 'react'
+
+import { Admonition } from 'ui-patterns'
+
+interface NoticeBarProps extends Omit<ComponentProps<typeof Admonition>, 'description'> {
+ title?: string
+ description?: string
+ icon?: LucideIcon
+ visible: boolean
+ actions?: React.ReactNode
+}
+export function NoticeBar({ visible, description, actions, ...props }: NoticeBarProps) {
+ return (
+ <AnimatePresence>
+ {visible && (
+ <motion.div
+ initial={{ opacity: 0, height: 0, y: 4 }}
+ animate={{ opacity: 1, height: 'auto', y: 0 }}
+ exit={{ opacity: 0, height: 0, y: 4 }}
+ transition={{ duration: 0.15 }}
+ >
+ <Admonition {...props}>
+ {description}
+ <div className="flex flex-col gap-2">
+ {actions && <div className="mt-2">{actions}</div>}
+ </div>
+ </Admonition>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/DiskManagement/ui/SpendCapDisabledSection.tsx b/apps/studio/components/interfaces/DiskManagement/ui/SpendCapDisabledSection.tsx
new file mode 100644
index 00000000000..35a56a77b87
--- /dev/null
+++ b/apps/studio/components/interfaces/DiskManagement/ui/SpendCapDisabledSection.tsx
@@ -0,0 +1,62 @@
+import { AnimatePresence, motion } from 'framer-motion'
+import Link from 'next/link'
+
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import {
+ AlertDescription_Shadcn_ as AlertDescription,
+ AlertTitle_Shadcn_ as AlertTitle,
+ buttonVariants,
+ cn,
+} from 'ui'
+import { Admonition } from 'ui-patterns/admonition'
+import { useSelectedProject } from 'hooks/misc/useSelectedProject'
+
+export function SpendCapDisabledSection() {
+ const org = useSelectedOrganization()
+ const project = useSelectedProject()
+
+ const {
+ data,
+ // no error/isError states handled here, as a parent component handles them
+ // we rely on this to check if the subscription has loaded
+ isSuccess,
+ } = useOrgSubscriptionQuery({
+ orgSlug: org?.slug,
+ })
+
+ const isSpendCapEnabled =
+ isSuccess &&
+ data?.plan.id !== 'free' &&
+ !data?.usage_billing_enabled &&
+ project?.cloud_provider !== 'FLY'
+
+ return (
+ <AnimatePresence>
+ {isSpendCapEnabled && (
+ <motion.div
+ initial={{ opacity: 0, height: 0 }}
+ animate={{ opacity: 1, height: 'auto' }}
+ exit={{ opacity: 0, height: 0 }}
+ transition={{ duration: 0.2 }}
+ >
+ <Admonition type="default">
+ <AlertTitle>Disable spend cap to manage Disk configuration</AlertTitle>
+ <AlertDescription>
+ To access disk management features, you need to disable your spend cap. These features
+ offer more flexibility and control over your database disk size.
+ </AlertDescription>
+ <div className="mt-3">
+ <Link
+ href={`/org/${org?.slug}/billing?panel=costControl`}
+ className={cn(buttonVariants({ type: 'default', size: 'tiny' }))}
+ >
+ Disable spend cap
+ </Link>
+ </div>
+ </Admonition>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Addons/Addons.tsx b/apps/studio/components/interfaces/Settings/Addons/Addons.tsx
index f695cfff4c0..cb1234b3e88 100644
--- a/apps/studio/components/interfaces/Settings/Addons/Addons.tsx
+++ b/apps/studio/components/interfaces/Settings/Addons/Addons.tsx
@@ -43,6 +43,7 @@ import ComputeInstanceSidePanel from './ComputeInstanceSidePanel'
import CustomDomainSidePanel from './CustomDomainSidePanel'
import IPv4SidePanel from './IPv4SidePanel'
import PITRSidePanel from './PITRSidePanel'
+import { NoticeBar } from 'components/interfaces/DiskManagement/ui/NoticeBar'
const Addons = () => {
const { resolvedTheme } = useTheme()
@@ -59,6 +60,7 @@ const Addons = () => {
const computeSizeChangesDisabled = useFlag('disableComputeSizeChanges')
const projectUpdateDisabled = useFlag('disableProjectCreationAndUpdate')
+ const diskAndComputeFormEnabled = useFlag('diskAndComputeForm')
const hasHipaaAddon = subscriptionHasHipaaAddon(subscription)
@@ -230,25 +232,42 @@ const Addons = () => {
/>
</div>
)}
- <ProjectUpdateDisabledTooltip
- projectUpdateDisabled={projectUpdateDisabled || computeSizeChangesDisabled}
- projectNotActive={!isProjectActive}
- tooltip="Compute size changes are currently disabled. Our engineers are working on a fix."
- >
- <Button
+
+ {true ? (
+ <ProjectUpdateDisabledTooltip
+ projectUpdateDisabled={projectUpdateDisabled || computeSizeChangesDisabled}
+ projectNotActive={!isProjectActive}
+ tooltip="Compute size changes are currently disabled. Our engineers are working on a fix."
+ >
+ <Button
+ type="default"
+ className="mt-2 pointer-events-auto"
+ onClick={() => setPanel('computeInstance')}
+ disabled={
+ isBranch ||
+ !isProjectActive ||
+ projectUpdateDisabled ||
+ computeSizeChangesDisabled
+ }
+ >
+ Change compute size
+ </Button>
+ </ProjectUpdateDisabledTooltip>
+ ) : (
+ <NoticeBar
+ visible={true}
type="default"
- className="mt-2 pointer-events-auto"
- onClick={() => setPanel('computeInstance')}
- disabled={
- isBranch ||
- !isProjectActive ||
- projectUpdateDisabled ||
- computeSizeChangesDisabled
+ title="Compute size has moved"
+ description="Compute size is now managed alongside Disk configuration on the new Compute and Disk page."
+ actions={
+ <Button type="default" asChild>
+ <Link href={`/project/${projectRef}/settings/compute-and-disk`}>
+ Go to Compute and Disk
+ </Link>
+ </Button>
}
- >
- Change compute size
- </Button>
- </ProjectUpdateDisabledTooltip>
+ />
+ )}
{Number(mostRecentRemainingIOBudget?.disk_io_budget) === 0 ? (
<Alert
@@ -286,7 +305,6 @@ const Addons = () => {
</p>
</Alert>
) : null}
-
<div className="mt-2 w-full flex items-center justify-between border-b py-2">
<Link href={`/project/${projectRef}/settings/infrastructure#ram`}>
<div className="group flex items-center space-x-2">
diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx
index 481ee72fe98..968360b5846 100644
--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx
+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx
@@ -7,7 +7,7 @@ import { useParams } from 'common'
import {
DISK_PRICING,
DiskType,
-} from 'components/interfaces/DiskManagement/DiskManagement.constants'
+} from 'components/interfaces/DiskManagement/ui/DiskManagement.constants'
import {
calculateIOPSPrice,
calculateThroughputPrice,
@@ -72,6 +72,7 @@ const DeployNewReplicaPanel = ({
const project = useSelectedProject()
const org = useSelectedOrganization()
const diskManagementV2 = useFlag('diskManagementV2')
+ const diskAndComputeFormEnabled = useFlag('diskAndComputeForm')
const { data } = useReadReplicasQuery({ projectRef })
const { data: addons, isSuccess } = useProjectAddonsQuery({ projectRef })
@@ -298,7 +299,9 @@ const DeployNewReplicaPanel = ({
href={
isFreePlan
? `/org/${org?.slug}/billing?panel=subscriptionPlan`
- : `/project/${projectRef}/settings/addons?panel=computeInstance`
+ : diskAndComputeFormEnabled
+ ? `/project/${projectRef}/settings/compute-and-disk`
+ : `/project/${projectRef}/settings/addons?panel=computeInstance`
}
>
{isFreePlan ? 'Upgrade to Pro' : 'Change compute size'}
@@ -395,7 +398,9 @@ const DeployNewReplicaPanel = ({
href={
isFreePlan
? `/org/${org?.slug}/billing?panel=subscriptionPlan`
- : `/project/${projectRef}/settings/addons?panel=computeInstance`
+ : diskAndComputeFormEnabled
+ ? `/project/${projectRef}/settings/compute-and-disk`
+ : `/project/${projectRef}/settings/addons?panel=computeInstance`
}
>
Upgrade compute size
diff --git a/apps/studio/components/layouts/ProjectLayout/ResizingState.tsx b/apps/studio/components/layouts/ProjectLayout/ResizingState.tsx
index d5bc190f251..9a2d96d34e5 100644
--- a/apps/studio/components/layouts/ProjectLayout/ResizingState.tsx
+++ b/apps/studio/components/layouts/ProjectLayout/ResizingState.tsx
@@ -24,13 +24,15 @@ export const ResizingState = () => {
<div className="space-y-6 py-6">
<div className="flex px-8 space-x-8">
<div className="mt-1">
- <Loader2 className="animate-spin" size={18} />
+ <Loader2 className="animate-spin text-foreground-light" size={18} />
</div>
- <div className="space-y-1">
- <p>Resizing project...</p>
+ <div className="flex flex-col gap-1">
+ <p>Resizing Project Compute size</p>
<p className="text-sm text-foreground-light">
- Your project is being restarted to apply compute size changes. It can take a few
- minutes. Your project will be offline while it is being restarted.
+ Your project is being restarted to apply compute size changes.
+ </p>
+ <p className="text-sm text-foreground-light">
+ This can take a few minutes. Project will be offline while it is being restarted.
</p>
</div>
</div>
diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsLayout.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsLayout.tsx
index cffd833fddb..8b5bdd929e3 100644
--- a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsLayout.tsx
+++ b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsLayout.tsx
@@ -48,6 +48,7 @@ const SettingsLayout = ({ title, children }: PropsWithChildren<SettingsLayoutPro
const warehouseEnabled = useFlag('warehouse')
const logDrainsEnabled = useFlag('logdrains')
+ const diskAndComputeEnabled = useFlag('diskAndComputeForm')
const menuRoutes = generateSettingsMenu(ref, project, organization, {
auth: authEnabled,
@@ -56,6 +57,7 @@ const SettingsLayout = ({ title, children }: PropsWithChildren<SettingsLayoutPro
invoices: invoicesEnabled,
warehouse: warehouseEnabled,
logDrains: logDrainsEnabled,
+ diskAndCompute: diskAndComputeEnabled,
})
return (
diff --git a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
index 768c38a20c1..5858276ab0e 100644
--- a/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
+++ b/apps/studio/components/layouts/ProjectSettingsLayout/SettingsMenu.utils.tsx
@@ -3,6 +3,7 @@ import type { Project } from 'data/projects/project-detail-query'
import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
import type { Organization } from 'types'
import { ArrowUpRight } from 'lucide-react'
+import { useFlag } from 'hooks/ui/useFlag'
export const generateSettingsMenu = (
ref?: string,
@@ -15,6 +16,7 @@ export const generateSettingsMenu = (
invoices?: boolean
warehouse?: boolean
logDrains?: boolean
+ diskAndCompute?: boolean
}
): ProductMenuGroup[] => {
const isProjectBuilding = project?.status === PROJECT_STATUS.COMING_UP
@@ -36,6 +38,16 @@ export const generateSettingsMenu = (
url: `/project/${ref}/settings/general`,
items: [],
},
+ ...(IS_PLATFORM && features?.diskAndCompute
+ ? [
+ {
+ name: 'Compute and Disk',
+ key: 'compute-and-disk',
+ url: `/project/${ref}/settings/compute-and-disk`,
+ items: [],
+ },
+ ]
+ : []),
{
name: 'Infrastructure',
key: 'infrastructure',
@@ -52,14 +64,12 @@ export const generateSettingsMenu = (
},
]
: []),
- ...[
- {
- name: 'Add Ons',
- key: 'addons',
- url: `/project/${ref}/settings/addons`,
- items: [],
- },
- ],
+ {
+ name: 'Add Ons',
+ key: 'addons',
+ url: `/project/${ref}/settings/addons`,
+ items: [],
+ },
{
name: 'Vault',
key: 'vault',
diff --git a/apps/studio/components/layouts/Scaffold.tsx b/apps/studio/components/layouts/Scaffold.tsx
index 9497e4a1115..06943794c26 100644
--- a/apps/studio/components/layouts/Scaffold.tsx
+++ b/apps/studio/components/layouts/Scaffold.tsx
@@ -1,9 +1,9 @@
import React from 'react'
import { cn } from 'ui'
-const maxWidthClasses = 'mx-auto w-full max-w-[1200px]'
-const paddingClasses = 'px-6 lg:px-14 xl:px-24 2xl:px-32'
-const maxWidthClassesColumn = 'min-w-[420px]'
+export const MAX_WIDTH_CLASSES = 'mx-auto w-full max-w-[1200px]'
+export const PADDING_CLASSES = 'px-6 lg:px-14 xl:px-24 2xl:px-32'
+export const MAX_WIDTH_CLASSES_COLUMN = 'min-w-[420px]'
const ScaffoldHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
({ className, ...props }, ref) => {
@@ -39,7 +39,7 @@ const ScaffoldContainer = React.forwardRef<
<div
ref={ref}
{...props}
- className={cn(maxWidthClasses, paddingClasses, bottomPadding && 'pb-16', className)}
+ className={cn(MAX_WIDTH_CLASSES, PADDING_CLASSES, bottomPadding && 'pb-16', className)}
/>
)
})
@@ -68,7 +68,7 @@ const ScaffoldColumn = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTM
<div
ref={ref}
{...props}
- className={cn('flex flex-col gap-3', maxWidthClassesColumn, className)}
+ className={cn('flex flex-col gap-3', MAX_WIDTH_CLASSES_COLUMN, className)}
/>
)
}
@@ -131,7 +131,7 @@ const ScaffoldContainerLegacy = React.forwardRef<
<div
ref={ref}
{...props}
- className={cn(maxWidthClasses, paddingClasses, 'my-8 flex flex-col gap-8', className)}
+ className={cn(MAX_WIDTH_CLASSES, PADDING_CLASSES, 'my-8 flex flex-col gap-8', className)}
/>
)
})
diff --git a/apps/studio/components/ui/ComputeBadgeWrapper.tsx b/apps/studio/components/ui/ComputeBadgeWrapper.tsx
index 511e9f4ccc6..145a3097a35 100644
--- a/apps/studio/components/ui/ComputeBadgeWrapper.tsx
+++ b/apps/studio/components/ui/ComputeBadgeWrapper.tsx
@@ -11,6 +11,7 @@ import { INSTANCE_MICRO_SPECS } from 'lib/constants'
import { Button, HoverCard, HoverCardContent, HoverCardTrigger, Separator } from 'ui'
import { ComputeBadge } from 'ui-patterns/ComputeBadge'
import ShimmeringLoader from './ShimmeringLoader'
+import { useFlag } from 'hooks/ui/useFlag'
const Row = ({ label, stat }: { label: string; stat: React.ReactNode | string }) => {
return (
@@ -36,6 +37,8 @@ export const ComputeBadgeWrapper = ({ project }: ComputeBadgeWrapperProps) => {
// once open it will fetch the addons
const [open, setOpenState] = useState(false)
+ const diskAndComputeFormEnabled = useFlag('diskAndComputeForm')
+
// returns hardcoded values for infra
const cpuArchitecture = getCloudProviderArchitecture(project.cloud_provider)
@@ -49,12 +52,13 @@ export const ComputeBadgeWrapper = ({ project }: ComputeBadgeWrapperProps) => {
const selectedAddons = addons?.selected_addons ?? []
const { computeInstance } = getAddons(selectedAddons)
+ const computeInstanceMeta = computeInstance?.variant?.meta
- let meta = computeInstance?.variant?.meta as ProjectAddonVariantMeta | undefined
- // some older instances on micro compute are missing metadata
- if (meta === undefined && project.infra_compute_size === 'micro') {
- meta = INSTANCE_MICRO_SPECS
- }
+ const meta = (
+ computeInstanceMeta === undefined && project.infra_compute_size === 'micro'
+ ? INSTANCE_MICRO_SPECS
+ : computeInstanceMeta
+ ) as ProjectAddonVariantMeta
const availableCompute = addons?.available_addons.find(
(addon) => addon.name === 'Compute Instance'
@@ -66,7 +70,11 @@ export const ComputeBadgeWrapper = ({ project }: ComputeBadgeWrapperProps) => {
e.preventDefault()
e.stopPropagation()
- router.push(`/project/${project?.ref}/settings/addons?panel=computeInstance`)
+ if (diskAndComputeFormEnabled) {
+ router.push(`/project/${project?.ref}/settings/compute-and-disk`)
+ } else {
+ router.push(`/project/${project?.ref}/settings/addons?panel=computeInstance`)
+ }
}
const highestComputeAvailable = availableCompute?.[availableCompute.length - 1].identifier
diff --git a/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsx b/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsx
index db91c93dec1..166e7818ae0 100644
--- a/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsx
+++ b/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsx
@@ -17,25 +17,27 @@ const CountdownTimerSpan = ({ seconds }: CountdownTimerSpanProps) => {
const formatValue = (value: number) => value.toString().padStart(2, '0')
return (
- <span className="text-foreground text-sm font-mono">
- <MotionNumber
- format={formatConfig}
- value={formatValue(hours)}
- transition={transitionConfig}
- />
- hr
- <MotionNumber
- format={formatConfig}
- value={formatValue(minutes)}
- transition={transitionConfig}
- />
- m
- <MotionNumber
- format={formatConfig}
- value={formatValue(remainingSeconds)}
- transition={transitionConfig}
- />
- s
+ <span className="inline-flex gap-2">
+ <span className="text-foreground-lighter text-sm p-0">Time remaining: </span>
+ <span className="text-foreground text-sm font-mono flex items-center gap-0">
+ <MotionNumber
+ format={formatConfig}
+ value={formatValue(hours)}
+ transition={transitionConfig}
+ />
+ hr
+ <MotionNumber
+ format={formatConfig}
+ value={formatValue(minutes)}
+ transition={transitionConfig}
+ />
+ m
+ <MotionNumber
+ format={formatConfig}
+ value={formatValue(remainingSeconds)}
+ transition={transitionConfig}
+ />
+ </span>
</span>
)
}
diff --git a/apps/studio/data/config/disk-attributes-query.ts b/apps/studio/data/config/disk-attributes-query.ts
index 450dd9cccf1..fec1924ca07 100644
--- a/apps/studio/data/config/disk-attributes-query.ts
+++ b/apps/studio/data/config/disk-attributes-query.ts
@@ -50,7 +50,7 @@ export const useRemainingDurationForDiskAttributeUpdate = ({
}: {
projectRef?: string
}) => {
- const { data } = useDiskAttributesQuery({ projectRef })
+ const { data, isLoading, isError, isSuccess, error } = useDiskAttributesQuery({ projectRef })
const lastModifiedAtString = dayjs(data?.last_modified_at ?? '').utc()
const secondsFromNow = Math.max(
@@ -65,7 +65,21 @@ export const useRemainingDurationForDiskAttributeUpdate = ({
}, [lastModifiedAtString])
if (data?.last_modified_at === undefined)
- return { remainingDuration: 0, isWithinCooldownWindow: false }
+ return {
+ remainingDuration: 0,
+ isWithinCooldownWindow: false,
+ isLoading,
+ isError,
+ error,
+ isSuccess,
+ }
- return { remainingDuration, isWithinCooldownWindow: remainingDuration > 0 }
+ return {
+ remainingDuration,
+ isWithinCooldownWindow: remainingDuration > 0,
+ isLoading,
+ isError,
+ error,
+ isSuccess,
+ }
}
diff --git a/apps/studio/data/config/disk-attributes-update-mutation.ts b/apps/studio/data/config/disk-attributes-update-mutation.ts
index 3b8ea297cb1..35c6ffcd49e 100644
--- a/apps/studio/data/config/disk-attributes-update-mutation.ts
+++ b/apps/studio/data/config/disk-attributes-update-mutation.ts
@@ -12,7 +12,7 @@ type UpdateIO2Body = components['schemas']['DiskRequestAttributesIO2']
export const COOLDOWN_DURATION = 60 * 60 * 6
export type UpdateDiskAttributesVariables = {
- ref: string
+ ref?: string
storageType: 'gp3' | 'io2'
provisionedIOPS: number
throughput?: number
@@ -27,6 +27,8 @@ export async function updateDiskAttributes({
throughput,
totalSize,
}: UpdateDiskAttributesVariables) {
+ if (!ref) throw new Error('ref is required')
+
const attributes =
storageType === 'gp3'
? ({
diff --git a/apps/studio/data/subscriptions/project-addon-update-mutation.ts b/apps/studio/data/subscriptions/project-addon-update-mutation.ts
index 257c088ad2c..4064770aeee 100644
--- a/apps/studio/data/subscriptions/project-addon-update-mutation.ts
+++ b/apps/studio/data/subscriptions/project-addon-update-mutation.ts
@@ -7,9 +7,10 @@ import { subscriptionKeys } from './keys'
import type { AddonVariantId, ProjectAddonType } from './types'
export type ProjectAddonUpdateVariables = {
- projectRef: string
+ projectRef?: string
variant: AddonVariantId
type: ProjectAddonType
+ suppressToast?: boolean
}
export async function updateSubscriptionAddon({
@@ -46,7 +47,7 @@ export const useProjectAddonUpdateMutation = ({
}: Omit<
UseMutationOptions<ProjectAddonUpdateData, ResponseError, ProjectAddonUpdateVariables>,
'mutationFn'
-> = {}) => {
+> & { suppressToast?: boolean } = {}) => {
const queryClient = useQueryClient()
return useMutation<ProjectAddonUpdateData, ResponseError, ProjectAddonUpdateVariables>(
diff --git a/apps/studio/hooks/misc/useCurrentOrgPlan.ts b/apps/studio/hooks/misc/useCurrentOrgPlan.ts
index 01a97d7b32f..8c93a16c6f0 100644
--- a/apps/studio/hooks/misc/useCurrentOrgPlan.ts
+++ b/apps/studio/hooks/misc/useCurrentOrgPlan.ts
@@ -10,12 +10,14 @@ export function useCurrentOrgPlan() {
if (isLoading) {
return {
plan: null,
+ usageBillingEnabled: null,
isLoading,
isSuccess: false,
}
} else {
return {
plan: data?.plan,
+ usageBillingEnabled: data?.usage_billing_enabled,
isLoading,
isSuccess,
}
diff --git a/apps/studio/lib/constants/infrastructure.ts b/apps/studio/lib/constants/infrastructure.ts
index 95b302c4289..5ef80c359a0 100644
--- a/apps/studio/lib/constants/infrastructure.ts
+++ b/apps/studio/lib/constants/infrastructure.ts
@@ -89,11 +89,11 @@ export const PASSWORD_STRENGTH_PERCENTAGE = {
export const DEFAULT_PROJECT_API_SERVICE_ID = 1
-type InstanceSpecs = {
+export type InstanceSpecs = {
baseline_disk_io_mbs: number
connections_direct: number
connections_pooler: number
- cpu_cores: number
+ cpu_cores: number | 'Shared'
cpu_dedicated: boolean
max_disk_io_mbs: number
memory_gb: number
@@ -103,7 +103,7 @@ export const INSTANCE_NANO_SPECS: InstanceSpecs = {
baseline_disk_io_mbs: 43,
connections_direct: 30,
connections_pooler: 200,
- cpu_cores: 2,
+ cpu_cores: 'Shared',
cpu_dedicated: false,
max_disk_io_mbs: 2085,
memory_gb: 0.5,
diff --git a/apps/studio/pages/project/[ref]/settings/compute-and-disk.tsx b/apps/studio/pages/project/[ref]/settings/compute-and-disk.tsx
new file mode 100644
index 00000000000..ec27c90d262
--- /dev/null
+++ b/apps/studio/pages/project/[ref]/settings/compute-and-disk.tsx
@@ -0,0 +1,28 @@
+import { DiskManagementForm } from 'components/interfaces/DiskManagement/DiskManagementForm'
+import SettingsLayout from 'components/layouts/ProjectSettingsLayout/SettingsLayout'
+import {
+ ScaffoldContainer,
+ ScaffoldDescription,
+ ScaffoldHeader,
+ ScaffoldTitle,
+} from 'components/layouts/Scaffold'
+import type { NextPageWithLayout } from 'types'
+
+const AuthSettings: NextPageWithLayout = () => {
+ return (
+ <>
+ <ScaffoldContainer>
+ <ScaffoldHeader>
+ <ScaffoldTitle>Compute and Disk</ScaffoldTitle>
+ <ScaffoldDescription>
+ Configure the compute and disk settings for your project.
+ </ScaffoldDescription>
+ </ScaffoldHeader>
+ </ScaffoldContainer>
+ <DiskManagementForm />
+ </>
+ )
+}
+
+AuthSettings.getLayout = (page) => <SettingsLayout>{page}</SettingsLayout>
+export default AuthSettings
diff --git a/apps/studio/pages/project/[ref]/settings/database.tsx b/apps/studio/pages/project/[ref]/settings/database.tsx
index 23d237dfb53..902109f8a29 100644
--- a/apps/studio/pages/project/[ref]/settings/database.tsx
+++ b/apps/studio/pages/project/[ref]/settings/database.tsx
@@ -19,6 +19,7 @@ import { useSelectedProject } from 'hooks/misc/useSelectedProject'
const ProjectSettings: NextPageWithLayout = () => {
const diskManagementV2 = useFlag('diskManagementV2')
+ const showDiskAndComputeForm = useFlag('diskAndComputeForm')
const project = useSelectedProject()
const showNewDiskManagementUI = diskManagementV2 && project?.cloud_provider === 'AWS'
@@ -40,7 +41,12 @@ const ProjectSettings: NextPageWithLayout = () => {
</div>
<SSLConfiguration />
- {showNewDiskManagementUI ? <DiskManagementPanelForm /> : <DiskSizeConfiguration />}
+ {showNewDiskManagementUI ? (
+ // This form is hidden if Disk and Compute form is enabled, new form is on ./settings/compute-and-disk
+ <DiskManagementPanelForm />
+ ) : (
+ <DiskSizeConfiguration />
+ )}
<NetworkRestrictions />
<BannedIPs />
</div>
diff --git a/packages/ui-patterns/admonition.tsx b/packages/ui-patterns/admonition.tsx
index eb4943d35b2..9380a6056a0 100644
--- a/packages/ui-patterns/admonition.tsx
+++ b/packages/ui-patterns/admonition.tsx
@@ -134,10 +134,7 @@ export const Admonition = forwardRef<
{children && (
<AlertDescription_Shadcn_
{...props.childProps?.description}
- className={cn(
- 'mt-3 [&_p]:mb-1.5 [&_p]:mt-0',
- props.childProps?.description?.className
- )}
+ className={cn('[&_p]:mb-1.5 [&_p]:mt-0', props.childProps?.description?.className)}
>
{children}
</AlertDescription_Shadcn_>
diff --git a/packages/ui-patterns/form/Layout/FormLayout.tsx b/packages/ui-patterns/form/Layout/FormLayout.tsx
index a6a720eb94d..2c3c8426f95 100644
--- a/packages/ui-patterns/form/Layout/FormLayout.tsx
+++ b/packages/ui-patterns/form/Layout/FormLayout.tsx
@@ -27,7 +27,7 @@ type Props = {
name?: string
}
-const ContainerVariants = cva('relative grid gap-2', {
+const ContainerVariants = cva('relative grid gap-10', {
variants: {
size: {
tiny: 'text-xs',
@@ -362,14 +362,15 @@ export const FormLayout = React.forwardRef<
<FormLabel_Shadcn_
className="flex gap-2 items-center break-all"
data-formlayout-id={'formLabel'}
+ htmlFor={props.name || id}
>
<LabelContents />
</FormLabel_Shadcn_>
) : (
<Label_Shadcn_
- htmlFor={props.name}
- data-formlayout-id={'label'}
className="flex gap-2 items-center break-all"
+ data-formlayout-id={'label'}
+ htmlFor={props.name || id}
>
<LabelContents />
</Label_Shadcn_>
diff --git a/packages/ui/src/components/radio-group-card.tsx b/packages/ui/src/components/radio-group-card.tsx
index b064842ebe2..234817b79cd 100644
--- a/packages/ui/src/components/radio-group-card.tsx
+++ b/packages/ui/src/components/radio-group-card.tsx
@@ -35,20 +35,20 @@ const RadioGroupCardItem = React.forwardRef<
'rounded-md',
'border',
'p-2',
- 'hover:bg-selection',
+ // 'hover:bg-selection',
'hover:border-foreground-muted',
'hover:z-[1] focus-visible:z-[1]',
'data-[state=checked]:z-[1]',
- 'data-[state=checked]:ring-1 data-[state=checked]:ring-border',
+ 'data-[state=checked]:ring-2 data-[state=checked]:ring-border',
'data-[state=checked]:bg-surface-200 dark:data-[state=checked]:bg-surface-300',
- 'data-[state=checked]:border-foreground-muted',
+ 'data-[state=checked]:border-foreground/50',
'transition-colors',
'group',
props.className
)}
>
{props.children}
- <div className="flex gap-2 w-full">
+ <label className="flex gap-2 w-full" id={props.id} htmlFor={props.value}>
{showIndicator && (
<div
className="
@@ -70,9 +70,9 @@ const RadioGroupCardItem = React.forwardRef<
</div>
)}
- <label
- htmlFor={props.value}
+ <div
className={cn(
+ 'w-full',
'text-xs transition-colors text-left',
'text-light',
'group-hover:text-foreground group-data-[state=checked]:text-foreground',
@@ -80,8 +80,8 @@ const RadioGroupCardItem = React.forwardRef<
)}
>
{label}
- </label>
- </div>
+ </div>
+ </label>
</RadioGroupPrimitive.Item>
)
})
diff --git a/packages/ui/src/components/shadcn/ui/input.tsx b/packages/ui/src/components/shadcn/ui/input.tsx
index 685b3dc684d..fc536af1aca 100644
--- a/packages/ui/src/components/shadcn/ui/input.tsx
+++ b/packages/ui/src/components/shadcn/ui/input.tsx
@@ -7,32 +7,24 @@ export interface InputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'size'>,
VariantProps<typeof InputVariants> {}
-const InputVariants = cva('aria-[]', {
- variants: {
- size: {
- ...SIZE_VARIANTS,
+export const InputVariants = cva(
+ 'aria-[] flex h-10 w-full rounded-md border border-control bg-foreground/[.026] px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-foreground-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-background-control focus-visible:ring-offset-2 focus-visible:ring-offset-foreground-muted disabled:cursor-not-allowed disabled:opacity-50 aria-[invalid=true]:bg-destructive-200 aria-[invalid=true]:border-destructive-400 aria-[invalid=true]:focus:border-destructive aria-[invalid=true]:focus-visible:border-destructive',
+ {
+ variants: {
+ size: {
+ ...SIZE_VARIANTS,
+ },
},
- },
- defaultVariants: {
- size: SIZE_VARIANTS_DEFAULT,
- },
-})
+ defaultVariants: {
+ size: SIZE_VARIANTS_DEFAULT,
+ },
+ }
+)
const Input = React.forwardRef<HTMLInputElement, InputProps>(
({ className, type, size = 'small', ...props }, ref) => {
return (
- <input
- type={type}
- ref={ref}
- {...props}
- className={cn(
- 'flex h-10 w-full rounded-md border border-control bg-foreground/[.026] px-3 py-2 text-sm file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-foreground-muted',
- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-background-control focus-visible:ring-offset-2 focus-visible:ring-offset-foreground-muted disabled:cursor-not-allowed disabled:opacity-50',
- 'aria-[invalid=true]:bg-destructive-200 aria-[invalid=true]:border-destructive-400 aria-[invalid=true]:focus:border-destructive aria-[invalid=true]:focus-visible:border-destructive',
- InputVariants({ size }),
- className
- )}
- />
+ <input type={type} ref={ref} {...props} className={cn(InputVariants({ size }), className)} />
)
}
)