The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Add disk autoscale configuration parameters in compute and disk settings (#32628)
Joshen Limc388cbe9d21e
diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.tsindex 217242a53ee..027d44fb0d7 100644--- a/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.schema.ts@@ -1,4 +1,5 @@import { z } from 'zod'+import { ComputeInstanceAddonVariantId } from './DiskManagement.types'import {calculateDiskSizeRequiredForIopsWithGp3,calculateDiskSizeRequiredForIopsWithIo2,@@ -7,7 +8,6 @@ import {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({@@ -21,11 +21,31 @@ const baseSchema = z.object({computeSize: z.custom<ComputeInstanceAddonVariantId>((val): val is ComputeInstanceAddonVariantId => true).describe('Compute size'),+ growthPercent: z+ .number()+ .int('Value must be an integer')+ .min(10, 'Growth percent must be at least 10%')+ .max(100, 'Growth percent cannot exceed 100%')+ .optional()+ .nullable(),+ minIncrementGb: z+ .number()+ .int('Value must be an integer')+ .min(1, 'Minimum increment must be at least 1 GB')+ .max(200, 'Minimum increment cannot exceed 200 GB')+ .optional()+ .nullable(),+ maxSizeGb: z+ .number()+ .int('Value must be an integer')+ .max(60000, 'Maximum size cannot exceed 60TB')+ .optional()+ .nullable(),})export const CreateDiskStorageSchema = (defaultTotalSize: number) => {const schema = baseSchema.superRefine((data, ctx) => {- const { storageType, totalSize, provisionedIOPS, throughput, computeSize } = data+ const { storageType, totalSize, provisionedIOPS, throughput, maxSizeGb } = dataif (totalSize < defaultTotalSize) {ctx.addIssue({@@ -35,6 +55,15 @@ export const CreateDiskStorageSchema = (defaultTotalSize: number) => {})}+ // Validate maxSizeGb cannot be lower than totalSize+ if (!!maxSizeGb && maxSizeGb < totalSize) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Max disk size cannot be lower than the current disk size. Must be at least ${formatNumber(totalSize)} GB.`,+ path: ['maxSizeGb'],+ })+ }+if (storageType === 'io2') {// Validation rules for io2diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsxindex 2080541b90b..84a224ed922 100644--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementForm.tsx@@ -18,6 +18,8 @@ import {useRemainingDurationForDiskAttributeUpdate,} from 'data/config/disk-attributes-query'import { useUpdateDiskAttributesMutation } from 'data/config/disk-attributes-update-mutation'+import { useDiskAutoscaleCustomConfigQuery } from 'data/config/disk-autoscale-config-query'+import { useUpdateDiskAutoscaleConfigMutation } from 'data/config/disk-autoscale-config-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'@@ -46,6 +48,7 @@ import { DiskManagementMessage } from './DiskManagement.types'import { mapComputeSizeNameToAddonVariantId } from './DiskManagement.utils'import { DiskMangementRestartRequiredSection } from './DiskManagementRestartRequiredSection'import { DiskManagementReviewAndSubmitDialog } from './DiskManagementReviewAndSubmitDialog'+import { AutoScaleFields } from './fields/AutoScaleFields'import { ComputeSizeField } from './fields/ComputeSizeField'import { DiskSizeField } from './fields/DiskSizeField'import { IOPSField } from './fields/IOPSField'@@ -61,11 +64,8 @@ import { NoticeBar } from './ui/NoticeBar'import { SpendCapDisabledSection } from './ui/SpendCapDisabledSection'export function DiskManagementForm() {- const {- project,- // isLoading is used to avoid a useCheckPermissions() race condition- isLoading: isProjectLoading,- } = useProjectContext()+ // isLoading is used to avoid a useCheckPermissions() race condition+ const { project, isLoading: isProjectLoading } = useProjectContext()const org = useSelectedOrganization()const { ref: projectRef } = useParams()const queryClient = useQueryClient()@@ -136,12 +136,15 @@ export function DiskManagementForm() {const { data: subscription, isSuccess: isSubscriptionSuccess } = useOrgSubscriptionQuery({orgSlug: org?.slug,})+ const { data: diskAutoscaleConfig, isSuccess: isDiskAutoscaleConfigSuccess } =+ useDiskAutoscaleCustomConfigQuery({ projectRef })/*** Handle default values*/// @ts-ignoreconst { type, iops, throughput_mbps, size_gb } = data?.attributes ?? { size_gb: 0 }+ const { growth_percent, max_size_gb, min_increment_gb } = diskAutoscaleConfig ?? {}const defaultValues = {storageType: type ?? DiskType.GP3,provisionedIOPS: iops,@@ -150,6 +153,9 @@ export function DiskManagementForm() {computeSize: project?.infra_compute_size? mapComputeSizeNameToAddonVariantId(project?.infra_compute_size): undefined,+ growthPercent: growth_percent,+ minIncrementGb: min_increment_gb,+ maxSizeGb: max_size_gb,}const form = useForm<DiskStorageSchemaType>({@@ -169,6 +175,7 @@ export function DiskManagementForm() {isDiskUtilizationSuccess &&isReadReplicasSuccess &&isSubscriptionSuccess &&+ isDiskAutoscaleConfigSuccess &&isCooldownSuccessconst isRequestingChanges = data?.requested_modification !== undefined@@ -181,6 +188,9 @@ export function DiskManagementForm() {const usedPercentage = (usedSize / totalSize) * 100const isFlyArchitecture = project?.cloud_provider === 'FLY'+ const disableIopsThroughputConfig =+ RESTRICTED_COMPUTE_FOR_THROUGHPUT_ON_GP3.includes(form.watch('computeSize')) &&+ subscription?.plan.id !== 'free'const disableDiskInputs =isRequestingChanges ||@@ -205,19 +215,23 @@ export function DiskManagementForm() {// this is to suppress to toast messageonError: () => {},onSuccess: () => {- /**- * Manually set project status to RESIZING- * Project status should be RESIZING on next project status request.- */+ //Manually set project status to RESIZING, Project status should be RESIZING on next project status request.setProjectStatus(queryClient, projectRef!, PROJECT_STATUS.RESIZING)},})+ const { mutateAsync: updateDiskAutoscaleConfig, isLoading: isUpdatingDiskAutoscaleConfig } =+ useUpdateDiskAutoscaleConfigMutation({+ // this is to suppress to toast message+ onError: () => {},+ })- const isUpdatingConfig = isUpdatingDisk || isUpdatingCompute+ const isUpdatingConfig = isUpdatingDisk || isUpdatingCompute || isUpdatingDiskAutoscaleConfigconst onSubmit = async (data: DiskStorageSchemaType) => {let payload = data+ let willUpdateDiskConfiguration = falsesetMessageState(null)+try {if (payload.storageType !== form.formState.defaultValues?.storageType ||@@ -225,6 +239,8 @@ export function DiskManagementForm() {payload.throughput !== form.formState.defaultValues?.throughput ||payload.totalSize !== form.formState.defaultValues?.totalSize) {+ willUpdateDiskConfiguration = true+if (RESTRICTED_COMPUTE_FOR_THROUGHPUT_ON_GP3.includes(payload.computeSize)) {payload.provisionedIOPS = IOPS_RANGE[DiskType.GP3].min}@@ -238,6 +254,19 @@ export function DiskManagementForm() {})}+ if (+ payload.growthPercent !== form.formState.defaultValues?.growthPercent ||+ payload.minIncrementGb !== form.formState.defaultValues?.minIncrementGb ||+ payload.maxSizeGb !== form.formState.defaultValues?.maxSizeGb+ ) {+ await updateDiskAutoscaleConfig({+ projectRef,+ growthPercent: payload.growthPercent,+ minIncrementGb: payload.minIncrementGb,+ maxSizeGb: payload.maxSizeGb,+ })+ }+if (payload.computeSize !== form.formState.defaultValues?.computeSize) {await updateSubscriptionAddon({projectRef: projectRef,@@ -250,6 +279,9 @@ export function DiskManagementForm() {setIsDialogOpen(false)form.reset(data as DiskStorageSchemaType)+ toast.success(+ `Successfully updated disk settings!${willUpdateDiskConfiguration ? ' The requested changes will be applied to your disk shortly.' : ''}`+ )} catch (error: unknown) {setMessageState({message: error instanceof Error ? error.message : 'An unknown error occurred',@@ -365,9 +397,9 @@ export function DiskManagementForm() {<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 className="text-sm text-foreground-light text-left">+ Specify additional settings for your disk, including autoscaling+ configuration, IOPS, throughput, and disk type.</span></div><ChevronRight@@ -378,32 +410,40 @@ export function DiskManagementForm() {</CollapsibleTrigger_Shadcn_><CollapsibleContent_Shadcn_className={cn(- 'flex flex-col gap-8 px-8 py-8 transition-all',+ 'flex flex-col gap-8 py-8 transition-all','data-[state=open]:border 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} />+ <div className="px-8 flex flex-col gap-y-8">+ <AutoScaleFields form={form} />+ </div>+ <Separator />+ <div className="px-8 flex flex-col gap-y-8">+ <StorageTypeField form={form} disableInput={disableDiskInputs} />+ <NoticeBar+ type="default"+ visible={disableIopsThroughputConfig}+ 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={disableIopsThroughputConfig || disableDiskInputs}+ />+ <ThroughputField+ form={form}+ disableInput={disableIopsThroughputConfig || disableDiskInputs}+ />+ </div></CollapsibleContent_Shadcn_></Collapsible_Shadcn_></>diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsxindex b898d8e009c..c8166b8933c 100644--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx@@ -74,6 +74,7 @@ import {import { NoticeBar } from './ui/NoticeBar'import { SpendCapDisabledSection } from './ui/SpendCapDisabledSection'+// [Joshen] Only used for non AWS projectsexport function DiskManagementPanelForm() {const { project } = useProjectContext()const org = useSelectedOrganization()diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsxindex 536403d8694..f909aba99b4 100644--- a/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx@@ -45,7 +45,7 @@ import {} from './DiskManagement.utils'import { DiskMangementRestartRequiredSection } from './DiskManagementRestartRequiredSection'import { BillingChangeBadge } from './ui/BillingChangeBadge'-import { DiskType } from './ui/DiskManagement.constants'+import { DISK_AUTOSCALE_CONFIG_DEFAULTS, DiskType } from './ui/DiskManagement.constants'import { DiskMangementCoolDownSection } from './ui/DiskManagementCoolDownSection'const TableHeaderRow = () => (@@ -209,6 +209,9 @@ export const DiskManagementReviewAndSubmitDialog = ({numReplicas,})+ const hasComputeChanges =+ form.formState.defaultValues?.computeSize !== form.getValues('computeSize')+const hasDiskConfigChanges =form.formState.defaultValues?.provisionedIOPS !== form.getValues('provisionedIOPS') ||(form.formState.defaultValues?.throughput !== form.getValues('throughput') &&@@ -248,15 +251,19 @@ export const DiskManagementReviewAndSubmitDialog = ({<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 />+ {(hasComputeChanges || hasDiskConfigChanges) && (+ <>+ <div className="flex flex-col gap-2 p-5">+ <DiskMangementRestartRequiredSection+ visible={hasComputeChanges}+ 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 />@@ -325,11 +332,56 @@ export const DiskManagementReviewAndSubmitDialog = ({priceTooltip={numReplicas > 0 ? replicaTooltipText : undefined}/>)}+ {form.formState.defaultValues?.growthPercent !== form.getValues('growthPercent') && (+ <TableDataRow+ attribute="Growth percent"+ defaultValue={+ form.formState.defaultValues?.growthPercent ??+ DISK_AUTOSCALE_CONFIG_DEFAULTS.growthPercent+ }+ newValue={+ form.getValues('growthPercent') ?? DISK_AUTOSCALE_CONFIG_DEFAULTS.growthPercent+ }+ unit="%"+ beforePrice={0}+ afterPrice={0}+ />+ )}+ {form.formState.defaultValues?.minIncrementGb !== form.getValues('minIncrementGb') && (+ <TableDataRow+ attribute="Min increment"+ defaultValue={+ form.formState.defaultValues?.minIncrementGb ??+ DISK_AUTOSCALE_CONFIG_DEFAULTS.minIncrementSize+ }+ newValue={+ form.getValues('minIncrementGb') ??+ DISK_AUTOSCALE_CONFIG_DEFAULTS.minIncrementSize+ }+ unit="GB"+ beforePrice={0}+ afterPrice={0}+ />+ )}+ {form.formState.defaultValues?.maxSizeGb !== form.getValues('maxSizeGb') && (+ <TableDataRow+ attribute="Max disk size"+ defaultValue={+ form.formState.defaultValues?.maxSizeGb?.toLocaleString() ??+ DISK_AUTOSCALE_CONFIG_DEFAULTS.maxSizeGb+ }+ newValue={+ form.getValues('maxSizeGb')?.toLocaleString() ??+ DISK_AUTOSCALE_CONFIG_DEFAULTS.maxSizeGb+ }+ unit="GB"+ beforePrice={0}+ afterPrice={0}+ />+ )}</TableBody></Table>- {/* <DialogSectionSeparator /> */}-<DialogFooter><Button block size="large" type="default" onClick={() => setIsDialogOpen(false)}>Canceldiff --git a/apps/studio/components/interfaces/DiskManagement/fields/AutoScaleFields.tsx b/apps/studio/components/interfaces/DiskManagement/fields/AutoScaleFields.tsxnew file mode 100644index 00000000000..1e8a6ba8b53--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/fields/AutoScaleFields.tsx@@ -0,0 +1,226 @@+import { UseFormReturn } from 'react-hook-form'++import { InputVariants } from '@ui/components/shadcn/ui/input'+import { useParams } from 'common'+import { useDiskAutoscaleCustomConfigQuery } from 'data/config/disk-autoscale-config-query'+import { cn, FormControl_Shadcn_, FormField_Shadcn_, Input_Shadcn_, Skeleton } from 'ui'+import { Admonition } from 'ui-patterns'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { DiskStorageSchemaType } from '../DiskManagement.schema'+import { DISK_AUTOSCALE_CONFIG_DEFAULTS } from '../ui/DiskManagement.constants'+import FormMessage from '../ui/FormMessage'+import { InputPostTab } from '../ui/InputPostTab'++type AutoScaleFieldProps = {+ form: UseFormReturn<DiskStorageSchemaType>+}++export const AutoScaleFields = ({ form }: AutoScaleFieldProps) => {+ const { ref: projectRef } = useParams()+ const {+ control,+ setValue,+ formState: { errors },+ } = form+ const { totalSize, growthPercent, maxSizeGb, minIncrementGb } = form.watch()++ const { error, isLoading, isError } = useDiskAutoscaleCustomConfigQuery({ projectRef })++ const _growthPercent = growthPercent ?? DISK_AUTOSCALE_CONFIG_DEFAULTS.growthPercent+ const _minIncrementGb = minIncrementGb ?? DISK_AUTOSCALE_CONFIG_DEFAULTS.minIncrementSize+ const _maxSizeGb = errors.maxSizeGb+ ? DISK_AUTOSCALE_CONFIG_DEFAULTS.maxSizeGb+ : maxSizeGb ?? DISK_AUTOSCALE_CONFIG_DEFAULTS.maxSizeGb++ const growthSize = Math.floor(totalSize * (_growthPercent / 100))+ const autoscaleGrowValue = Math.min(+ Math.max(Math.floor((totalSize * _growthPercent) / 100), _minIncrementGb),+ 200+ )++ const totalSizeAfterGrowth = autoscaleGrowValue + totalSize+ const formattedTotalSizeAfterGrowth =+ totalSizeAfterGrowth < _maxSizeGb ? totalSizeAfterGrowth : _maxSizeGb+ const formattedGrowValue = formattedTotalSizeAfterGrowth - totalSize++ return (+ <>+ <FormField_Shadcn_+ name="growthPercent"+ control={control}+ render={({ field }) => {+ return (+ <FormItemLayout+ layout="horizontal"+ label="Autoscale growth percent"+ id={field.name}+ labelOptional="Percentage of current disk size to grow"+ description={+ !errors.growthPercent+ ? `This amounts to ${growthSize} GB based on the current disk size of ${totalSize} GB`+ : undefined+ }+ className="[&>div>span]:text-foreground-lighter"+ >+ <InputPostTab label="%">+ {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_+ {...field}+ type="number"+ className="flex-grow font-mono rounded-r-none max-w-20"+ value={field.value ?? undefined}+ disabled={isError}+ onChange={(e) => {+ setValue(+ 'growthPercent',+ e.target.value === '' ? null : e.target.valueAsNumber,+ {+ shouldDirty: true,+ shouldValidate: true,+ }+ )+ }}+ placeholder={String(DISK_AUTOSCALE_CONFIG_DEFAULTS.growthPercent)}+ />+ </FormControl_Shadcn_>+ )}+ </InputPostTab>+ {error && <FormMessage type="error" message={error.message} />}+ </FormItemLayout>+ )+ }}+ />++ <FormField_Shadcn_+ name="minIncrementGb"+ control={control}+ render={({ field }) => {+ return (+ <FormItemLayout+ layout="horizontal"+ label="Minimum increment"+ id={field.name}+ labelOptional="Minimum value to autoscale disk size by"+ description={+ !!minIncrementGb && minIncrementGb > growthSize && !errors.minIncrementGb+ ? `This value takes precedence as the minimum increment is larger than the growth percent`+ : undefined+ }+ className="[&>div>span]:text-foreground-lighter"+ >+ <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_+ {...field}+ type="number"+ className="flex-grow font-mono rounded-r-none max-w-32"+ value={field.value ?? undefined}+ disabled={isError}+ onChange={(e) => {+ setValue(+ 'minIncrementGb',+ e.target.value === '' ? null : e.target.valueAsNumber,+ {+ shouldDirty: true,+ shouldValidate: true,+ }+ )+ }}+ placeholder={String(DISK_AUTOSCALE_CONFIG_DEFAULTS.minIncrementSize)}+ />+ </FormControl_Shadcn_>+ )}+ </InputPostTab>+ {error && <FormMessage type="error" message={error.message} />}+ </FormItemLayout>+ )+ }}+ />++ <FormField_Shadcn_+ name="maxSizeGb"+ control={control}+ render={({ field }) => {+ return (+ <FormItemLayout+ layout="horizontal"+ label="Maximum disk size"+ id={field.name}+ labelOptional="Maximum size that the disk can grow to"+ className="[&>div>span]:text-foreground-lighter"+ >+ <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_+ {...field}+ type="number"+ className="flex-grow font-mono rounded-r-none max-w-32"+ value={field.value ?? undefined}+ disabled={isError}+ onChange={(e) => {+ setValue(+ 'maxSizeGb',+ e.target.value === '' ? null : e.target.valueAsNumber,+ {+ shouldDirty: true,+ shouldValidate: true,+ }+ )+ }}+ placeholder={String(DISK_AUTOSCALE_CONFIG_DEFAULTS.maxSizeGb)}+ />+ </FormControl_Shadcn_>+ )}+ </InputPostTab>+ {error && <FormMessage type="error" message={error.message} />}+ </FormItemLayout>+ )+ }}+ />++ {+ <Admonition type="default" showIcon={false} className="[&>div]:text-foreground-light">+ Disk size will automatically be expanded by{' '}+ <span className="text-foreground">+ {String(formattedGrowValue).length > 4+ ? formattedGrowValue.toFixed(2)+ : formattedGrowValue}{' '}+ GB+ </span>{' '}+ to a total of <span className="text-foreground">{formattedTotalSizeAfterGrowth} GB</span>{' '}+ when the database reaches 90% of the disk size+ </Admonition>+ }+ </>+ )+}diff --git a/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsxindex e016f1a7a09..1b7d7f091c2 100644--- a/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskManagement.constants.tsx@@ -8,6 +8,13 @@ export enum DiskType {IO2 = 'io2',}+// [Joshen] As per https://github.com/supabase/infrastructure/pull/20478+export const DISK_AUTOSCALE_CONFIG_DEFAULTS = {+ growthPercent: 50,+ minIncrementSize: 4,+ maxSizeGb: 60000,+}+export const IOPS_RANGE = {[DiskType.GP3]: { min: 3000, max: 16000 },[DiskType.IO2]: { min: 100, max: 256000 },diff --git a/apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsx b/apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsxindex eaf93bf903d..6cc62c571ca 100644--- a/apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsx+++ b/apps/studio/components/interfaces/DiskManagement/ui/DiskSpaceBar.tsx@@ -1,13 +1,16 @@+import MotionNumber from '@number-flow/react'import { AnimatePresence, motion } from 'framer-motion'import { Info } from 'lucide-react'-import MotionNumber from '@number-flow/react'import { useTheme } from 'next-themes'import { UseFormReturn } from 'react-hook-form'import { useParams } from 'common'+import { useDiskBreakdownQuery } from 'data/config/disk-breakdown-query'import { useDiskUtilizationQuery } from 'data/config/disk-utilization-query'+import { useSelectedProject } from 'hooks/misc/useSelectedProject'import { GB } from 'lib/constants'import { formatBytes } from 'lib/helpers'+import { useMemo } from 'react'import {badgeVariants,cn,@@ -17,9 +20,6 @@ import {} from 'ui'import { DiskStorageSchemaType } from '../DiskManagement.schema'import { AUTOSCALING_THRESHOLD } from './DiskManagement.constants'-import { useDiskBreakdownQuery } from 'data/config/disk-breakdown-query'-import { useSelectedProject } from 'hooks/misc/useSelectedProject'-import { useMemo } from 'react'interface DiskSpaceBarProps {form: UseFormReturn<DiskStorageSchemaType>@@ -68,15 +68,17 @@ export default function DiskSpaceBar({ form }: DiskSpaceBarProps) {const usedTotalPercentage = Math.min((usedSizeTotal / totalSize) * 100, 100)const usedSizeDatabase = Math.round(((diskBreakdownBytes?.dbSizeBytes ?? 0) / GB) * 100) / 100- const usedPercentageDatabase = Math.min((usedSizeDatabase / totalSize) * 100, 100)+ const usedPercentageDatabase =+ totalSize === 0 ? 0 : Math.min((usedSizeDatabase / totalSize) * 100, 100)const newUsedPercentageDatabase = Math.min((usedSizeDatabase / newTotalSize) * 100, 100)const usedSizeWAL = Math.round(((diskBreakdownBytes?.walSizeBytes ?? 0) / GB) * 100) / 100- const usedPercentageWAL = Math.min((usedSizeWAL / totalSize) * 100, 100)+ const usedPercentageWAL = totalSize === 0 ? 0 : Math.min((usedSizeWAL / totalSize) * 100, 100)const newUsedPercentageWAL = Math.min((usedSizeWAL / newTotalSize) * 100, 100)const usedSizeSystem = Math.round(((diskBreakdownBytes?.systemBytes ?? 0) / GB) * 100) / 100- const usedPercentageSystem = Math.min((usedSizeSystem / totalSize) * 100, 100)+ const usedPercentageSystem =+ totalSize === 0 ? 0 : Math.min((usedSizeSystem / totalSize) * 100, 100)const newUsedPercentageSystem = Math.min((usedSizeSystem / newTotalSize) * 100, 100)const resizePercentage = AUTOSCALING_THRESHOLD * 100diff --git a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsxindex 8742185a30b..83f3adab5ad 100644--- a/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx+++ b/apps/studio/components/interfaces/Settings/Infrastructure/InfrastructureConfiguration/DeployNewReplicaPanel.tsx@@ -4,14 +4,14 @@ import { useEffect, useMemo, useState } from 'react'import { toast } from 'sonner'import { useParams } from 'common'-import {- DISK_PRICING,- DiskType,-} from 'components/interfaces/DiskManagement/ui/DiskManagement.constants'import {calculateIOPSPrice,calculateThroughputPrice,} from 'components/interfaces/DiskManagement/DiskManagement.utils'+import {+ DISK_PRICING,+ DiskType,+} from 'components/interfaces/DiskManagement/ui/DiskManagement.constants'import { DocsButton } from 'components/ui/DocsButton'import { useDiskAttributesQuery } from 'data/config/disk-attributes-query'import { useEnablePhysicalBackupsMutation } from 'data/database/enable-physical-backups-mutation'@@ -71,7 +71,6 @@ const DeployNewReplicaPanel = ({const { ref: projectRef } = useParams()const project = useSelectedProject()const org = useSelectedOrganization()- const diskManagementV2 = useFlag('diskManagementV2')const diskAndComputeFormEnabled = useFlag('diskAndComputeForm')const { data } = useReadReplicasQuery({ projectRef })@@ -102,7 +101,7 @@ const DeployNewReplicaPanel = ({// @ts-ignoreconst { size_gb, type, throughput_mbps, iops } = diskConfiguration?.attributes ?? {}- const showNewDiskManagementUI = diskManagementV2 && project?.cloud_provider === 'AWS'+ const showNewDiskManagementUI = project?.cloud_provider === 'AWS'const readReplicaDiskSizes = (size_gb ?? 0) * 1.25const additionalCostDiskSize =readReplicaDiskSizes * (DISK_PRICING[type as DiskType]?.storage ?? 0)diff --git a/apps/studio/data/config/disk-autoscale-config-query.ts b/apps/studio/data/config/disk-autoscale-config-query.tsnew file mode 100644index 00000000000..bde9263c2fc--- /dev/null+++ b/apps/studio/data/config/disk-autoscale-config-query.ts@@ -0,0 +1,42 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import { get, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { configKeys } from './keys'++export type DiskAutoscaleCustomConfigVariables = {+ projectRef?: string+}++// export type DiskAttribute = components['schemas']['DiskResponse']++export async function getDiskAutoscaleCustomConfig(+ { projectRef }: DiskAutoscaleCustomConfigVariables,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('Project ref is required')++ const { data, error } = await get(`/platform/projects/{ref}/disk/custom-config`, {+ params: { path: { ref: projectRef } },+ signal,+ })++ if (error) handleError(error)+ return data+}++export type DiskAutoscaleCustomConfigData = Awaited<ReturnType<typeof getDiskAutoscaleCustomConfig>>+export type DiskAutoscaleCustomConfigError = ResponseError++export const useDiskAutoscaleCustomConfigQuery = <TData = DiskAutoscaleCustomConfigData>(+ { projectRef }: DiskAutoscaleCustomConfigVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<DiskAutoscaleCustomConfigData, DiskAutoscaleCustomConfigError, TData> = {}+) =>+ useQuery<DiskAutoscaleCustomConfigData, DiskAutoscaleCustomConfigError, TData>(+ configKeys.diskAutoscaleConfig(projectRef),+ ({ signal }) => getDiskAutoscaleCustomConfig({ projectRef }, signal),+ { enabled: enabled && typeof projectRef !== 'undefined', ...options }+ )diff --git a/apps/studio/data/config/disk-autoscale-config-update-mutation.ts b/apps/studio/data/config/disk-autoscale-config-update-mutation.tsnew file mode 100644index 00000000000..02e26ab20c7--- /dev/null+++ b/apps/studio/data/config/disk-autoscale-config-update-mutation.ts@@ -0,0 +1,69 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { handleError, post } from 'data/fetchers'+import type { ResponseError } from 'types'+import { configKeys } from './keys'++export type UpdateDiskAutoscaleConfigVariables = {+ projectRef?: string+ growthPercent?: number | null+ maxSizeGb?: number | null+ minIncrementGb?: number | null+}++export async function updateDiskAutoscaleConfig({+ projectRef,+ growthPercent,+ maxSizeGb,+ minIncrementGb,+}: UpdateDiskAutoscaleConfigVariables) {+ if (!projectRef) throw new Error('projectRef is required')++ const { data, error } = await post('/platform/projects/{ref}/disk/custom-config', {+ params: { path: { ref: projectRef } },+ body: {+ growth_percent: growthPercent,+ max_size_gb: maxSizeGb,+ min_increment_gb: minIncrementGb,+ },+ })+ if (error) handleError(error)+ return data+}++type UpdateDiskAutoscaleConfigData = Awaited<ReturnType<typeof updateDiskAutoscaleConfig>>++export const useUpdateDiskAutoscaleConfigMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<+ UpdateDiskAutoscaleConfigData,+ ResponseError,+ UpdateDiskAutoscaleConfigVariables+ >,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()+ return useMutation<+ UpdateDiskAutoscaleConfigData,+ ResponseError,+ UpdateDiskAutoscaleConfigVariables+ >((vars) => updateDiskAutoscaleConfig(vars), {+ async onSuccess(data, variables, context) {+ const { projectRef } = variables+ await queryClient.invalidateQueries(configKeys.diskAutoscaleConfig(projectRef))+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update disk autoscale config: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ })+}diff --git a/apps/studio/data/config/keys.ts b/apps/studio/data/config/keys.tsindex e154ed65481..020ebe43270 100644--- a/apps/studio/data/config/keys.ts+++ b/apps/studio/data/config/keys.ts@@ -26,4 +26,6 @@ export const configKeys = {['projects', organizationSlug, cloudProvider, dbRegion, 'available-creation-versions'] as const,projectUnpausePostgresVersions: (projectRef: string | undefined) =>['projects', projectRef, 'available-unpause-versions'] as const,+ diskAutoscaleConfig: (projectRef: string | undefined) =>+ ['projects', projectRef, 'disk-autoscale-config'] as const,}diff --git a/apps/studio/pages/api/projects/[ref]/content/count.ts b/apps/studio/pages/api/projects/[ref]/content/count.tsindex 568bfd57a06..342b1a61326 100644--- a/apps/studio/pages/api/projects/[ref]/content/count.ts+++ b/apps/studio/pages/api/projects/[ref]/content/count.ts@@ -1,5 +1,5 @@-import { NextApiRequest, NextApiResponse } from 'next'import apiWrapper from 'lib/api/apiWrapper'+import { NextApiRequest, NextApiResponse } from 'next'import { extractResponse } from 'pages/api/constants'export default (req: NextApiRequest, res: NextApiResponse) => apiWrapper(req, res, handler)diff --git a/apps/studio/pages/project/[ref]/reports/database.tsx b/apps/studio/pages/project/[ref]/reports/database.tsxindex 1af4c8b2345..dd8f0ec985c 100644--- a/apps/studio/pages/project/[ref]/reports/database.tsx+++ b/apps/studio/pages/project/[ref]/reports/database.tsx@@ -1,3 +1,4 @@+import { PermissionAction } from '@supabase/shared-types/out/constants'import dayjs from 'dayjs'import { ArrowRight, ExternalLink } from 'lucide-react'import Link from 'next/link'@@ -5,7 +6,6 @@ import { useEffect, useState } from 'react'import { toast } from 'sonner'import { AlertDescription_Shadcn_, Alert_Shadcn_, Button } from 'ui'-import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import ReportHeader from 'components/interfaces/Reports/ReportHeader'import ReportPadding from 'components/interfaces/Reports/ReportPadding'@@ -22,7 +22,6 @@ import { useProjectDiskResizeMutation } from 'data/config/project-disk-resize-muimport { useDatabaseSizeQuery } from 'data/database/database-size-query'import { useDatabaseReport } from 'data/reports/database-report-query'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'-import { useFlag } from 'hooks/ui/useFlag'import { TIME_PERIODS_INFRA } from 'lib/constants/metrics'import { formatBytes } from 'lib/helpers'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'@@ -43,15 +42,12 @@ export default DatabaseReportconst DatabaseUsage = () => {const { db, chart, ref } = useParams()const { project } = useProjectContext()- const diskManagementV2 = useFlag('diskManagementV2')const state = useDatabaseSelectorStateSnapshot()const [dateRange, setDateRange] = useState<any>(undefined)const isReplicaSelected = state.selectedDatabaseId !== project?.ref- const showNewDiskManagementUI = diskManagementV2 && project?.cloud_provider === 'AWS'-const report = useDatabaseReport()const { data } = useDatabaseSizeQuery({projectRef: project?.ref,@@ -218,7 +214,7 @@ const DatabaseUsage = () => {</div><div className="col-span-8 text-right">- {showNewDiskManagementUI ? (+ {project?.cloud_provider === 'AWS' ? (<Button asChild type="default"><Link href={`/project/${ref}/settings/compute-and-disk`}>Increase disk sizediff --git a/apps/studio/pages/project/[ref]/settings/database.tsx b/apps/studio/pages/project/[ref]/settings/database.tsxindex a63155f4cbd..180d58743d6 100644--- a/apps/studio/pages/project/[ref]/settings/database.tsx+++ b/apps/studio/pages/project/[ref]/settings/database.tsx@@ -10,14 +10,11 @@ import SSLConfiguration from 'components/interfaces/Settings/Database/SSLConfiguimport SettingsLayout from 'components/layouts/ProjectSettingsLayout/SettingsLayout'import { ScaffoldContainer, ScaffoldHeader, ScaffoldTitle } from 'components/layouts/Scaffold'import { useSelectedProject } from 'hooks/misc/useSelectedProject'-import { useFlag } from 'hooks/ui/useFlag'import type { NextPageWithLayout } from 'types'const ProjectSettings: NextPageWithLayout = () => {- const diskManagementV2 = useFlag('diskManagementV2')const project = useSelectedProject()-- const showNewDiskManagementUI = diskManagementV2 && project?.cloud_provider === 'AWS'+ const showNewDiskManagementUI = project?.cloud_provider === 'AWS'return (<>