The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Chore/disk attributes mangement (#29219)
Joshen Lim07699ad76b7a
diff --git a/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsx b/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsxnew file mode 100644index 00000000000..e20ff03294c--- /dev/null+++ b/apps/studio/components/interfaces/DataWarehouse/FormFooterChangeBadge.tsx@@ -0,0 +1,43 @@+import { AnimatePresence, motion } from 'framer-motion'+import { Badge } from 'ui'++interface FormFooterChangeBadgeProps {+ formState: {+ dirtyFields: Record<string, boolean>+ }+}+export const FormFooterChangeBadge = ({ formState }: FormFooterChangeBadgeProps) => {+ return (+ <AnimatePresence mode="wait">+ {Object.keys(formState.dirtyFields).length > 0 && (+ <motion.div+ initial={{ opacity: 0, scale: 0.9 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 0.9 }}+ transition={{ duration: 0.2 }}+ >+ <motion.div+ animate={{+ scale: [1, 1.05, 1],+ transition: { duration: 0.3 },+ }}+ >+ <Badge variant={'default'}>+ <motion.span+ key={Object.keys(formState.dirtyFields).length}+ initial={{ opacity: 0, scale: 0.9 }}+ animate={{ opacity: 1, scale: 1 }}+ exit={{ opacity: 0, scale: 0.9 }}+ transition={{ duration: 0.1 }}+ >+ {Object.keys(formState.dirtyFields).length === 1+ ? '1 change to review'+ : `${Object.keys(formState.dirtyFields).length} changes to review`}+ </motion.span>+ </Badge>+ </motion.div>+ </motion.div>+ )}+ </AnimatePresence>+ )+}diff --git a/apps/studio/components/interfaces/DiskManagement/BillingChangeBadge.tsx b/apps/studio/components/interfaces/DiskManagement/BillingChangeBadge.tsxnew file mode 100644index 00000000000..4b39ccbb227--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/BillingChangeBadge.tsx@@ -0,0 +1,36 @@+import { AnimatePresence, motion } from 'framer-motion'+import { ChevronRight } from 'lucide-react'+import { Badge } from 'ui'++interface BillingChangeBadgeProps {+ beforePrice?: number+ afterPrice?: number+ show: boolean | undefined+}++const BillingChangeBadge = ({ beforePrice, afterPrice, show }: 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 }}+ >+ <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">+ ${beforePrice.toFixed(2)}+ </span>+ <ChevronRight size={12} strokeWidth={2} className="text-foreground-muted" />+ <span className="text-xs font-mono text-foreground">${afterPrice.toFixed(2)}</span>+ </div>+ </Badge>+ </motion.div>+ )}+ </AnimatePresence>+ )+}++export default BillingChangeBadgediff --git a/apps/studio/components/interfaces/DiskManagement/DiskCountdownRadial.tsx b/apps/studio/components/interfaces/DiskManagement/DiskCountdownRadial.tsxnew file mode 100644index 00000000000..3905780b1df--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskCountdownRadial.tsx@@ -0,0 +1,35 @@+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.constants.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagement.constants.tsxnew file mode 100644index 00000000000..f92e8579637--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.constants.tsx@@ -0,0 +1,53 @@+import { PlanType } from 'data/subscriptions/org-subscription-query'++export enum DiskType {+ GP3 = 'gp3',+ IO2 = 'io2',+}++export const DISK_PRICING = {+ [DiskType.GP3]: {+ storage: 0.125, // per GB per month+ iops: 0.024, // per IOPS per month, charged after 3000 IOPS+ throughput: 0.095, // per MB/s per month, charged after 125 MB/s+ },+ [DiskType.IO2]: {+ storage: 0.195, // per GB per month+ iops: 0.119, // per IOPS per month+ },+}++export const DISK_LIMITS = {+ [DiskType.GP3]: {+ minStorage: 1,+ maxStorage: 16384,+ minIops: 3000,+ maxIops: 16000,+ minThroughput: 125,+ maxThroughput: 1000,+ includedIops: 3000,+ includedThroughput: 125,+ },+ [DiskType.IO2]: {+ minStorage: 4,+ maxStorage: 16384,+ minIops: 100,+ maxIops: 256000,+ },+}++export const DISK_TYPE_LABELS = {+ [DiskType.GP3]: 'General Purpose SSD (gp3)',+ [DiskType.IO2]: 'Provisioned IOPS SSD (io2)',+}++interface PlanDetails {+ includedDiskGB: { gp3: number; io2: number }+}++export const PLAN_DETAILS: Record<PlanType, PlanDetails> = {+ free: { includedDiskGB: { gp3: 1, io2: 0 } },+ pro: { includedDiskGB: { gp3: 8, io2: 0 } },+ team: { includedDiskGB: { gp3: 8, io2: 0 } },+ enterprise: { includedDiskGB: { gp3: 8, io2: 0 } },+}diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.tsnew file mode 100644index 00000000000..89909b4ce6b--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.test.ts@@ -0,0 +1,85 @@+import {+ calculateDiskSizePrice,+ calculateIOPSPrice,+ calculateThroughputPrice,+} from './DiskManagement.utils'+import { DiskType } from './DiskManagement.constants'++describe('DiskManagement.utils.ts:calculateDiskSizePrice', () => {+ test('GP3 with 8GB to GP3 with 10GB for pro plan', () => {+ const result = calculateDiskSizePrice({+ planId: 'pro',+ oldSize: 8,+ oldStorageType: DiskType.GP3,+ newSize: 10,+ newStorageType: DiskType.GP3,+ })+ expect(result.oldPrice).toBe('0.00')+ expect(result.newPrice).toBe('0.25')+ })+ test('IO2 with 8GB to IO2 with 10GB for pro plan', () => {+ const result = calculateDiskSizePrice({+ planId: 'pro',+ oldSize: 8,+ oldStorageType: DiskType.IO2,+ newSize: 10,+ newStorageType: DiskType.IO2,+ })+ expect(result.oldPrice).toBe('1.56')+ expect(result.newPrice).toBe('1.95')+ })+})++describe('DiskManagement.utils.ts:calculateIOPSPrice', () => {+ test('GP3 with 3000 to IO2 with 3000', () => {+ const result = calculateIOPSPrice({+ oldStorageType: DiskType.GP3,+ oldProvisionedIOPS: 3000,+ newStorageType: DiskType.IO2,+ newProvisionedIOPS: 3000,+ })+ expect(result.oldPrice).toBe('0.00')+ expect(result.newPrice).toBe('357.00')+ })+ test('GP3 with 3000 to GP3 with 5000', () => {+ const result = calculateIOPSPrice({+ oldStorageType: DiskType.GP3,+ oldProvisionedIOPS: 3000,+ newStorageType: DiskType.GP3,+ newProvisionedIOPS: 5000,+ })+ expect(result.oldPrice).toBe('0.00')+ expect(result.newPrice).toBe('48.00')+ })+ test('IO2 with 3000 to IO2 with 5000', () => {+ const result = calculateIOPSPrice({+ oldStorageType: DiskType.IO2,+ oldProvisionedIOPS: 3000,+ newStorageType: DiskType.IO2,+ newProvisionedIOPS: 5000,+ })+ expect(result.oldPrice).toBe('357.00')+ expect(result.newPrice).toBe('595.00')+ })+})++describe('DiskManagement.utils.ts:calculateThroughputPrice', () => {+ test('GP3 with 125 MiBps 150 MiBps', () => {+ const result = calculateThroughputPrice({+ storageType: DiskType.GP3,+ oldThroughput: 125,+ newThroughput: 150,+ })+ expect(result.oldPrice).toBe('0.00')+ expect(result.newPrice).toBe('2.38')+ })+ test('IO1 with 125 MiBps 150 MiBps', () => {+ const result = calculateThroughputPrice({+ storageType: DiskType.IO2,+ oldThroughput: 125,+ newThroughput: 150,+ })+ expect(result.oldPrice).toBe('0.00')+ expect(result.newPrice).toBe('0.00')+ })+})diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.tsnew file mode 100644index 00000000000..0d0235e41bf--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagement.utils.ts@@ -0,0 +1,89 @@+import { DISK_LIMITS, DISK_PRICING, DiskType, PLAN_DETAILS } from './DiskManagement.constants'++export const calculateDiskSizePrice = ({+ planId,+ oldSize,+ oldStorageType,+ newSize,+ newStorageType,+}: {+ planId: string+ oldSize: number+ oldStorageType: DiskType+ newSize: number+ newStorageType: DiskType+}) => {+ const oldPricePerGiB = DISK_PRICING[oldStorageType]?.storage ?? 0+ const newPricePerGiB = DISK_PRICING[newStorageType]?.storage ?? 0+ const { includedDiskGB } = PLAN_DETAILS?.[planId as keyof typeof PLAN_DETAILS] ?? {}++ const oldPrice = (Math.max(oldSize - includedDiskGB[oldStorageType], 0) * oldPricePerGiB).toFixed(+ 2+ )+ const newPrice = (Math.max(newSize - includedDiskGB[newStorageType], 0) * newPricePerGiB).toFixed(+ 2+ )++ return { oldPrice, newPrice }+}++export const calculateIOPSPrice = ({+ oldStorageType,+ oldProvisionedIOPS,+ newStorageType,+ newProvisionedIOPS,+}: {+ oldStorageType: DiskType+ oldProvisionedIOPS: number+ newStorageType: DiskType+ newProvisionedIOPS: number+}) => {+ if (newStorageType === DiskType.GP3) {+ const oldChargeableIOPS = Math.max(+ 0,+ oldProvisionedIOPS - DISK_LIMITS[DiskType.GP3].includedIops+ )+ const newChargeableIOPS = Math.max(+ 0,+ newProvisionedIOPS - DISK_LIMITS[DiskType.GP3].includedIops+ )+ const oldPrice = oldChargeableIOPS * DISK_PRICING[oldStorageType]?.iops ?? 0+ const newPrice = newChargeableIOPS * DISK_PRICING[newStorageType]?.iops ?? 0+ return { oldPrice: oldPrice.toFixed(2), newPrice: newPrice.toFixed(2) }+ } else {+ const oldPrice =+ oldStorageType === 'gp3'+ ? (oldProvisionedIOPS - DISK_LIMITS[oldStorageType].includedIops) *+ DISK_PRICING[oldStorageType].iops+ : oldProvisionedIOPS * DISK_PRICING[oldStorageType]?.iops ?? 0+ const newPrice = newProvisionedIOPS * DISK_PRICING[newStorageType]?.iops ?? 0+ return { oldPrice: oldPrice.toFixed(2), newPrice: newPrice.toFixed(2) }+ }+}++// This is only applicable for GP3 storage type, no need to consider IO2 at all+// Also assumes that disk size is > 400 GiB (separate requirement to update throughput)+export const calculateThroughputPrice = ({+ storageType,+ newThroughput,+ oldThroughput,+}: {+ storageType: DiskType+ newThroughput: number+ oldThroughput: number+}) => {+ if (storageType === DiskType.GP3 && newThroughput) {+ const oldChargeableThroughput = Math.max(+ 0,+ oldThroughput - DISK_LIMITS[DiskType.GP3].includedThroughput+ )+ const newChargeableThroughput = Math.max(+ 0,+ newThroughput - DISK_LIMITS[DiskType.GP3].includedThroughput+ )+ const oldPrice = (oldChargeableThroughput * DISK_PRICING[DiskType.GP3].throughput).toFixed(2)+ const newPrice = (newChargeableThroughput * DISK_PRICING[DiskType.GP3].throughput).toFixed(2)+ return { oldPrice, newPrice }+ }+ return { oldPrice: '0.00', newPrice: '0.00' }+}diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementCoolDownSection.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementCoolDownSection.tsxnew file mode 100644index 00000000000..2ca83f4cccb--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementCoolDownSection.tsx@@ -0,0 +1,94 @@+import { AnimatePresence, motion } from 'framer-motion'+import { X } from 'lucide-react'+import React, { useEffect, useState } from 'react'++import { DialogSection } from 'ui'+import CountdownTimerRadial from '../../ui/CountdownTimer/CountdownTimerRadial'++export const DiskMangementCoolDownSection: React.FC = () => {+ const [progress, setProgress] = useState(100)+ const [showCountdown, setShowCountdown] = useState(false)+ const [isJumping, setIsJumping] = useState(false)+ const [isVisible, setIsVisible] = useState(true)++ useEffect(() => {+ const startCountdown = () => {+ setShowCountdown(true)+ setProgress(100)+ const interval = setInterval(() => {+ setProgress((prevProgress) => {+ if (prevProgress <= 0) {+ clearInterval(interval)+ setIsJumping(true)+ setTimeout(() => {+ setIsJumping(false)+ setProgress(100)+ startCountdown() // Restart the countdown+ }, 300) // Duration of the jump animation+ return 0+ }+ return prevProgress - 1+ })+ }, 100)++ return () => clearInterval(interval)+ }++ const initialDelay = setTimeout(startCountdown, 1000)++ return () => clearTimeout(initialDelay)+ }, [])++ return (+ <AnimatePresence>+ {isVisible && (+ <motion.div+ initial={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.15 }}+ >+ <DialogSection className="bg-surface-100 text-sm text-foreground-light flex items-center gap-4 relative">+ <div className="w-12 h-12 opacity-75">+ <AnimatePresence>+ {showCountdown && (+ <motion.div+ key="countdown-timer"+ initial={{ scale: 0.8, opacity: 0, y: -8 }}+ animate={{+ scale: isJumping ? 1.2 : 1,+ opacity: 1,+ y: isJumping ? -8 : 0,+ }}+ exit={{ scale: 0.8, opacity: 0, y: -8 }}+ transition={{+ duration: isJumping ? 0.3 : 0.8,+ type: 'spring',+ bounce: 0.6,+ }}+ >+ <CountdownTimerRadial progress={progress} />+ </motion.div>+ )}+ </AnimatePresence>+ </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.+ </p>+ <p className="text-sm text-foreground-light">+ Due to a cooldown period between disk changes.+ </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>+ )}+ </AnimatePresence>+ )+}diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementDiskSizeReadReplicas.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementDiskSizeReadReplicas.tsxnew file mode 100644index 00000000000..4c1a817f9ac--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementDiskSizeReadReplicas.tsx@@ -0,0 +1,127 @@+import { AnimatePresence, motion } from 'framer-motion'+import { ChevronDown } from 'lucide-react'+import { useState } from 'react'++import { useParams } from 'common'+import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'+import { formatDatabaseID } from 'data/read-replicas/replicas.utils'+import {+ Alert_Shadcn_ as Alert,+ AlertDescription_Shadcn_ as AlertDescription,+ AlertTitle_Shadcn_ as AlertTitle,+ Collapsible_Shadcn_ as Collapsible,+ CollapsibleContent_Shadcn_ as CollapsibleContent,+ CollapsibleTrigger_Shadcn_ as CollapsibleTrigger,+ InfoIcon,+} from 'ui'+import BillingChangeBadge from './BillingChangeBadge'+import DiskSpaceBar from './DiskSpaceBar'++interface DiskManagementDiskSizeReadReplicasProps {+ isDirty: boolean+ totalSize: number+ usedSize: number+ newTotalSize: number+}++export const DiskManagementDiskSizeReadReplicas = ({+ isDirty,+ totalSize,+ usedSize,+ newTotalSize,+}: DiskManagementDiskSizeReadReplicasProps) => {+ const { ref: projectRef } = useParams()+ const [isOpen, setIsOpen] = useState(false)++ const { data: databases } = useReadReplicasQuery({ projectRef })+ const readReplicas = (databases ?? []).filter((db) => db.identifier !== projectRef)++ if (readReplicas.length === 0) return null++ return (+ <>+ <AnimatePresence>+ {isDirty && (+ <motion.div+ initial={{ opacity: 0, height: 0 }}+ animate={{ opacity: 1, height: 'auto' }}+ exit={{ opacity: 0, height: 0 }}+ transition={{ duration: 0.3 }}+ >+ <Alert variant="default" className="bg-transparent">+ <InfoIcon />+ <AlertTitle>An extra 25% disk space is provisioned for Read replicas.</AlertTitle>+ <AlertDescription>+ Each replica is billed separately+ <ul className="list-disc pl-4 my-3 flex flex-col gap-2">+ {readReplicas.map((replica, index) => (+ <li key={index} className="marker:text-foreground-light">+ <div className="flex items-center gap-2">+ <span>+ ID: {formatDatabaseID(replica.identifier)} ({replica.region}):+ </span>+ <BillingChangeBadge+ beforePrice={(totalSize * 0.25) / readReplicas.length}+ afterPrice={(newTotalSize * 0.25) / readReplicas.length}+ show={true}+ />+ </div>+ </li>+ ))}+ </ul>+ </AlertDescription>+ </Alert>+ </motion.div>+ )}+ </AnimatePresence>+ <Collapsible open={isOpen} onOpenChange={setIsOpen}>+ <CollapsibleTrigger asChild>+ <div className="flex items-center cursor-pointer rounded gap-2 mt-3 text-foreground-light hover:text-foreground data-[state=open]:text-foreground group">+ <h3 className="text-sm">Read replica disk size information</h3>+ <ChevronDown+ className={`h-4 w-4 transition-transform duration-200 group-data-[state=open]:transform group-data-[state=open]:rotate-180 group-data-[state=open]:text-foreground`}+ />+ </div>+ </CollapsibleTrigger>+ <AnimatePresence initial={false}>+ {isOpen && (+ <motion.div+ key="content"+ initial="collapsed"+ animate="open"+ exit="collapsed"+ variants={{+ open: { opacity: 1, height: 'auto' },+ collapsed: { opacity: 0, height: 0 },+ }}+ transition={{ duration: 0.3, ease: [0.04, 0.62, 0.23, 0.98] }}+ >+ <CollapsibleContent className="pt-3">+ <motion.div+ initial={{ opacity: 0 }}+ animate={{ opacity: 1 }}+ exit={{ opacity: 0 }}+ transition={{ duration: 0.2 }}+ >+ <p className="flex flex-col gap-y-1 text-sm text-foreground-light mb-3">+ <span>All read replicas are provisioned with the following:</span>+ <span className="text-foreground-lighter">+ Read replicas have 25% more disk size than the primary database to account for+ WAL files{' '}+ </span>+ </p>+ <DiskSpaceBar+ showNewBar={isDirty}+ totalSize={totalSize}+ usedSize={usedSize}+ newTotalSize={newTotalSize}+ />+ </motion.div>+ </CollapsibleContent>+ </motion.div>+ )}+ </AnimatePresence>+ </Collapsible>+ </>+ )+}diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsxnew file mode 100644index 00000000000..a165ca3741f--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelForm.tsx@@ -0,0 +1,607 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { AnimatePresence, motion } from 'framer-motion'+import { InfoIcon, RotateCcw } 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 DiskSpaceBar from 'components/interfaces/DiskManagement/DiskSpaceBar'+import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'+import { FormHeader } from 'components/ui/Forms/FormHeader'+import {+ useDiskAttributesQuery,+ useRemainingDurationForDiskAttributeUpdate,+} from 'data/config/disk-attributes-query'+import { useUpdateDiskAttributesMutation } from 'data/config/disk-attributes-update-mutation'+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import { GB } from 'lib/constants'+import {+ Alert_Shadcn_,+ AlertDescription_Shadcn_,+ AlertTitle_Shadcn_,+ Badge,+ Button,+ Card,+ CardContent,+ Form_Shadcn_,+ FormControl_Shadcn_,+ FormField_Shadcn_,+ FormItem_Shadcn_,+ Input_Shadcn_ as Input,+ RadioGroupCard,+ RadioGroupCardItem,+ Separator,+} from 'ui'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import { FormFooterChangeBadge } from '../DataWarehouse/FormFooterChangeBadge'+import BillingChangeBadge from './BillingChangeBadge'+import { DiskCountdownRadial } from './DiskCountdownRadial'+import { DiskType, PLAN_DETAILS } from './DiskManagement.constants'+import {+ calculateDiskSizePrice,+ calculateIOPSPrice,+ calculateThroughputPrice,+} from './DiskManagement.utils'+import { DiskManagementDiskSizeReadReplicas } from './DiskManagementDiskSizeReadReplicas'+import { DiskStorageSchema, DiskStorageSchemaType } from './DiskManagementPanelSchema'+import { DiskManagementPlanUpgradeRequired } from './DiskManagementPlanUpgradeRequired'+import { DiskManagementReviewAndSubmitDialog } from './DiskManagementReviewAndSubmitDialog'+import { useDiskUtilizationQuery } from 'data/config/disk-utilization-query'++export function DiskManagementPanelForm() {+ const org = useSelectedOrganization()+ const { project } = useProjectContext()+ const { ref: projectRef } = useParams()++ const [isDialogOpen, setIsDialogOpen] = useState<boolean>(false)+ const [remainingTime, setRemainingTime] = useState(0)+ const [refetchInterval, setRefetchInterval] = useState<number | false>(false)++ const { data, isSuccess } = 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!')+ }+ }+ },+ }+ )+ // @ts-ignore [Joshen TODO] check whats happening here+ const { type, iops, throughput_mbps, size_gb } = data?.attributes ?? { size_gb: 0 }+ const isRequestingChanges = data?.requested_modification !== undefined++ const { remainingDuration: initialRemainingTime, isWithinCooldownWindow } =+ useRemainingDurationForDiskAttributeUpdate({+ projectRef,+ })++ const { data: subscription } = useOrgSubscriptionQuery({+ orgSlug: org?.slug,+ })+ const planId = subscription?.plan.id ?? ''+ const isPlanUpgradeRequired =+ subscription?.plan.id === 'pro' && !subscription.usage_billing_enabled++ const { data: diskUtil } = useDiskUtilizationQuery({ projectRef })+ const mainDiskUsed = Math.round(((diskUtil?.metrics.fs_used_bytes ?? 0) / GB) * 100) / 100++ const { mutate: updateDiskConfigurationRQ, isLoading: isUpdatingDiskConfiguration } =+ useUpdateDiskAttributesMutation({+ onSuccess: (_, vars) => {+ toast.success(+ 'Successfully requested disk configuration changes! Your changes will be applied shortly'+ )+ const { ref, ...formData } = vars+ setIsDialogOpen(false)+ setRefetchInterval(3000)+ form.reset(formData as DiskStorageSchemaType)+ },+ })++ const defaultValues = {+ storageType: type,+ provisionedIOPS: iops,+ throughput: throughput_mbps,+ totalSize: size_gb,+ }+ const form = useForm<DiskStorageSchemaType>({+ resolver: zodResolver(DiskStorageSchema),+ defaultValues,+ mode: 'onBlur',+ reValidateMode: 'onChange',+ })++ const { watch, setValue, trigger, control, formState } = form+ const watchedStorageType = watch('storageType')+ const watchedTotalSize = watch('totalSize')+ const watchedIOPS = watch('provisionedIOPS')+ const { dirtyFields } = formState // Destructure dirtyFields from formState+ const isAllocatedStorageDirty = !!dirtyFields.totalSize // Check if 'allocatedStorage' is dirty+ const disableInput = isRequestingChanges || isPlanUpgradeRequired || isWithinCooldownWindow++ const { includedDiskGB: includedDiskGBMeta } =+ PLAN_DETAILS?.[planId as keyof typeof PLAN_DETAILS] ?? {}+ const includedDiskGB = includedDiskGBMeta[watchedStorageType]++ const maxIOPS =+ watchedStorageType === 'gp3'+ ? Math.min(500 * watchedTotalSize, 16000)+ : Math.min(1000 * watchedTotalSize, 256000)+ const maxThroughput =+ watchedStorageType === 'gp3' ? Math.min(0.25 * watchedIOPS, 1000) : undefined++ const onSubmit = async (data: DiskStorageSchemaType) => {+ if (projectRef === undefined) return console.error('Project ref is required')+ updateDiskConfigurationRQ({ ref: projectRef, ...data })+ }++ 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,+ })++ const iopsPrice = calculateIOPSPrice({+ oldStorageType: form.formState.defaultValues?.storageType as DiskType,+ oldProvisionedIOPS: form.formState.defaultValues?.provisionedIOPS || 0,+ newStorageType: form.getValues('storageType') as DiskType,+ newProvisionedIOPS: form.getValues('provisionedIOPS'),+ })++ const throughputPrice = calculateThroughputPrice({+ storageType: form.getValues('storageType') as DiskType,+ newThroughput: form.getValues('throughput') || 0,+ oldThroughput: form.formState.defaultValues?.throughput || 0,+ })++ useEffect(() => {+ // Initialize field values properly when data has been loaded+ if (isSuccess) form.reset(defaultValues)+ }, [isSuccess])++ // 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 GiB+ const currentThroughput = form.getValues('throughput')+ if (!currentThroughput || currentThroughput < 125 || currentThroughput > 1000) {+ setValue('throughput', 125) // Reset to default if undefined or out of bounds+ }+ }+ }, [watchedStorageType, watchedTotalSize, setValue, form])++ 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])++ if (planId === 'free') {+ return (+ <div id="disk-management">+ <FormHeader+ title="Disk Management"+ docsUrl="https://supabase.com/docs/guides/platform/database-size#disk-management"+ />+ <Alert_Shadcn_>+ <InfoIcon />+ <AlertTitle_Shadcn_>+ Disk size configuration is not available for projects on the Free Plan+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ <p>+ If you are intending to use more than 500MB of disk space, then you will need to+ upgrade to at least the Pro Plan.+ </p>+ <Button asChild type="default" className="mt-3">+ <Link+ target="_blank"+ rel="noreferrer"+ href={`/org/${org?.slug}/billing?panel=subscriptionPlan`}+ >+ Upgrade plan+ </Link>+ </Button>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+ </div>+ )+ }++ return (+ <div id="disk-management">+ <FormHeader+ title="Disk Management"+ docsUrl="https://supabase.com/docs/guides/platform/database-size#disk-management"+ />+ <Form_Shadcn_ {...form}>+ <form onSubmit={form.handleSubmit(onSubmit)}>+ <div className="-space-y-px">+ <Card className="bg-surface-100 rounded-b-none">+ <CardContent className="transition-all duration-500 ease-in-out py-10 flex flex-col gap-10 px-8">+ <FormField_Shadcn_+ name="storageType"+ control={form.control}+ render={({ field }) => (+ <FormItemLayout layout="horizontal" label="Storage type">+ <FormControl_Shadcn_>+ <RadioGroupCard+ className="flex flex-wrap gap-3"+ {...field}+ onValueChange={async (e) => {+ field.onChange(e)+ // only trigger provisionedIOPS due to other input being hidden+ await form.trigger('provisionedIOPS')+ }}+ defaultValue={field.value}+ disabled={disableInput}+ >+ <FormItem_Shadcn_ asChild>+ <FormControl_Shadcn_>+ <RadioGroupCardItem+ className="grow p-3 px-5"+ disabled={disableInput}+ value="gp3"+ showIndicator={false}+ // @ts-ignore+ label={+ <div className="flex flex-col gap-1">+ <div className="flex gap-3 items-center">+ <span className="text-sm">General Purpose SSD</span>{' '}+ <div>+ <Badge+ variant={'outline'}+ className="font-mono bg-alternative bg-opacity-100"+ >+ gp3+ </Badge>+ </div>+ </div>+ <p className="text-foreground-light">+ gp3 provides a balance between price and performance+ </p>+ </div>+ }+ />+ </FormControl_Shadcn_>+ </FormItem_Shadcn_>+ <FormItem_Shadcn_ asChild>+ <FormControl_Shadcn_>+ <RadioGroupCardItem+ className="grow p-3 px-5"+ disabled={disableInput}+ value="io2"+ showIndicator={false}+ // @ts-ignore+ label={+ <div className="flex flex-col gap-1">+ <div className="flex gap-3 items-center">+ <span className="text-sm">Provisioned IOPS SSD</span>{' '}+ <div>+ <Badge+ variant={'outline'}+ className="font-mono bg-alternative bg-opacity-100"+ >+ io2+ </Badge>+ </div>+ </div>+ <p className="text-foreground-light">+ io2 offers high IOPS for mission-critical applications.+ </p>+ </div>+ }+ />+ </FormControl_Shadcn_>+ </FormItem_Shadcn_>+ </RadioGroupCard>+ </FormControl_Shadcn_>+ </FormItemLayout>+ )}+ />+ <FormField_Shadcn_+ control={form.control}+ name="provisionedIOPS"+ render={({ field }) => (+ <FormItemLayout+ layout="horizontal"+ label="IOPS"+ description={+ watchedStorageType === 'io2' ? (+ <>+ For <code className="text-xs">io2</code> storage type, IOPS must be{' '}+ {watchedTotalSize >= 8 ? `between 100 and ${maxIOPS}.` : `at least 100`}+ </>+ ) : (+ <>+ For <code className="text-xs">gp3</code> storage type, IOPS must be{' '}+ {watchedTotalSize >= 8+ ? `between 3,000 and ${maxIOPS.toLocaleString()}.`+ : `at least 3,000`}+ </>+ )+ }+ labelOptional="Input/output operations per second. Higher IOPS is suitable for applications requiring high throughput."+ >+ <div className="flex gap-3 items-center">+ <div className="flex -space-x-px">+ <FormControl_Shadcn_>+ <Input+ id="provisionedIOPS"+ type="number"+ className="flex-grow font-mono rounded-r-none max-w-32"+ {...field}+ disabled={disableInput}+ onChange={(e) => {+ setValue('provisionedIOPS', e.target.valueAsNumber, {+ shouldDirty: true,+ shouldValidate: true,+ })+ }}+ />+ </FormControl_Shadcn_>+ <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">IOPS</span>+ </div>+ </div>+ <BillingChangeBadge+ show={+ (watchedStorageType !== type ||+ (watchedStorageType === 'gp3' && field.value !== iops)) &&+ !formState.errors.provisionedIOPS+ }+ beforePrice={Number(iopsPrice.oldPrice)}+ afterPrice={Number(iopsPrice.newPrice)}+ />+ </div>+ </FormItemLayout>+ )}+ />+ <AnimatePresence initial={false}>+ {form.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 (MiBps)"+ layout="horizontal"+ description={+ <>+ For <code className="text-xs">gp3</code> storage type, throughput+ must be between 125 and {maxThroughput} MiBps+ </>+ }+ >+ <div className="flex gap-3 items-center">+ <div className="flex -space-x-px">+ <FormControl_Shadcn_>+ <Input+ type="number"+ {...field}+ onChange={(e) => {+ setValue('throughput', e.target.valueAsNumber, {+ shouldDirty: true,+ shouldValidate: true,+ })+ }}+ className="flex-grow font-mono rounded-r-none max-w-32"+ disabled={disableInput || watchedStorageType === 'io2'}+ />+ </FormControl_Shadcn_>+ <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">+ MiBps+ </span>+ </div>+ </div>+ <BillingChangeBadge+ show={+ formState.isDirty &&+ formState.dirtyFields.throughput &&+ !formState.errors.throughput+ }+ beforePrice={Number(throughputPrice.oldPrice)}+ afterPrice={Number(throughputPrice.newPrice)}+ />+ </div>+ </FormItemLayout>+ )}+ />+ </motion.div>+ )}+ </AnimatePresence>+ </CardContent>+ <Separator />+ <CardContent className="py-10 px-8">+ <FormField_Shadcn_+ name="totalSize"+ control={control}+ render={({ field }) => (+ <FormItemLayout label="Disk Size" layout="horizontal">+ <div className="mt-1 relative flex gap-2 items-center">+ <div className="flex -space-x-px max-w-48">+ <FormControl_Shadcn_>+ <Input+ type="number"+ step="1"+ {...field}+ disabled={disableInput}+ className="flex-grow 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_>+ <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">GiB</span>+ </div>+ </div>+ <AnimatePresence initial={false}>+ {isAllocatedStorageDirty && (+ <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.15 }}+ style={{ overflow: 'hidden' }}+ >+ <Button+ htmlType="button"+ type="default"+ size="small"+ className="px-2"+ onClick={() => form.resetField('totalSize')}+ >+ <RotateCcw className="h-4 w-4" aria-hidden="true" />+ </Button>+ </motion.div>+ )}+ </AnimatePresence>+ <BillingChangeBadge+ beforePrice={Number(diskSizePrice.oldPrice)}+ afterPrice={Number(diskSizePrice.newPrice)}+ show={+ formState.isDirty &&+ !formState.errors.totalSize &&+ diskSizePrice.oldPrice !== diskSizePrice.newPrice+ }+ />+ {includedDiskGB > 0 && (+ <div className="text-xs text-foreground-light">+ Your plan includes {includedDiskGB} GiB of disk size for{' '}+ {watchedStorageType}.+ </div>+ )}+ </div>+ </FormItemLayout>+ )}+ />+ <div className="grid grid-cols-12 gap-3">+ {/* 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={+ form.getValues('totalSize') <= size_gb+ ? size_gb+ : form.getValues('totalSize')+ }+ />+ <DiskManagementDiskSizeReadReplicas+ isDirty={form.formState.dirtyFields.totalSize !== undefined}+ totalSize={size_gb * 1.25}+ usedSize={mainDiskUsed}+ newTotalSize={+ form.getValues('totalSize') <= size_gb+ ? size_gb * 1.25+ : form.getValues('totalSize') * 1.25+ }+ />+ </div>+ </div>+ </CardContent>+ </Card>++ {isRequestingChanges ? (+ <Card className="px-2 rounded-none">+ <CardContent className="py-3 flex gap-3 px-3 items-center">+ <div className="flex flex-col">+ <p className="text-foreground-lighter text-sm p-0">+ Disk configuration changes have been requested+ </p>+ <p className="text-sm">+ The requested changes will be applied to your disk shortly+ </p>+ </div>+ </CardContent>+ </Card>+ ) : (+ <DiskCountdownRadial remainingTime={remainingTime} />+ )}++ {isPlanUpgradeRequired && <DiskManagementPlanUpgradeRequired />}++ <Card className="bg-surface-100 rounded-t-none">+ <CardContent className="flex items-center pb-0 py-3 px-8 gap-3 justify-end">+ <FormFooterChangeBadge formState={formState} />+ <div className="flex gap-2">+ <Button+ type="default"+ onClick={() => form.reset()}+ disabled={!form.formState.isDirty}+ >+ Cancel+ </Button>+ <DiskManagementReviewAndSubmitDialog+ onSubmit={onSubmit}+ isDialogOpen={isDialogOpen}+ setIsDialogOpen={setIsDialogOpen}+ isWithinCooldown={disableInput}+ form={form}+ loading={isUpdatingDiskConfiguration}+ diskSizePrice={diskSizePrice}+ iopsPrice={iopsPrice}+ throughputPrice={throughputPrice}+ />+ </div>+ </CardContent>+ </Card>+ </div>+ </form>+ </Form_Shadcn_>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.ts b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.tsnew file mode 100644index 00000000000..0564d7a99f7--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementPanelSchema.ts@@ -0,0 +1,85 @@+import { z } from 'zod'++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 GiB.' })+ .max(16384, { message: 'Allocated disk size must not exceed 16 TiB.' })+ .describe('Allocated disk size in GiB'),+ provisionedIOPS: z.number().describe('Provisioned IOPS for storage type'),+ throughput: z.number().optional().describe('Throughput in MiBps for gp3'),+})++export const DiskStorageSchema = baseSchema.superRefine((data, ctx) => {+ const { storageType, totalSize, provisionedIOPS, throughput } = data++ if (storageType === 'io2') {+ // Validation rules for io2+ const maxIOPS = Math.min(1000 * totalSize, 256000)+ if (provisionedIOPS < 100) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Provisioned IOPS must be at least 100 for io2.',+ path: ['provisionedIOPS'],+ })+ } else if (provisionedIOPS > maxIOPS) {+ if (totalSize >= 8) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Provisioned IOPS must be at most ${maxIOPS} for io2.`,+ path: ['provisionedIOPS'],+ })+ } else {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Invalid IOPS value due to invalid disk size`,+ path: ['provisionedIOPS'],+ })+ }+ }+ if (throughput !== undefined) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: 'Throughput is not configurable for io2.',+ path: ['throughput'],+ })+ }+ } else if (storageType === 'gp3') {+ // Validation rules for gp3+ const maxIOPS = Math.min(500 * totalSize, 16000)+ const maxThroughput = Math.min(0.25 * provisionedIOPS, 1000)++ if (provisionedIOPS < 3000) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Provisioned IOPS must be at least 3000 for gp3.`,+ path: ['provisionedIOPS'],+ })+ } else if (provisionedIOPS > maxIOPS) {+ if (totalSize >= 8) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Provisioned IOPS must be at most ${maxIOPS} for gp3.`,+ path: ['provisionedIOPS'],+ })+ } else {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Invalid IOPS value due to invalid disk size`,+ path: ['provisionedIOPS'],+ })+ }+ }++ if (throughput !== undefined && (throughput < 125 || throughput > maxThroughput)) {+ ctx.addIssue({+ code: z.ZodIssueCode.custom,+ message: `Throughput must be set between 125 and ${maxThroughput} MiBps.`,+ path: ['throughput'],+ })+ }+ }+})++export type DiskStorageSchemaType = z.infer<typeof DiskStorageSchema>diff --git a/apps/studio/components/interfaces/DiskManagement/DiskManagementPlanUpgradeRequired.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementPlanUpgradeRequired.tsxnew file mode 100644index 00000000000..48534c9d1ea--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementPlanUpgradeRequired.tsx@@ -0,0 +1,46 @@+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 {+ Alert_Shadcn_ as Alert,+ AlertDescription_Shadcn_ as AlertDescription,+ AlertTitle_Shadcn_ as AlertTitle,+ buttonVariants,+ cn,+ InfoIcon,+} from 'ui'++export function DiskManagementPlanUpgradeRequired() {+ const org = useSelectedOrganization()+ const { data } = useOrgSubscriptionQuery({ orgSlug: org?.slug })++ 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/DiskManagementReviewAndSubmitDialog.tsx b/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsxnew file mode 100644index 00000000000..f9050dbce45--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskManagementReviewAndSubmitDialog.tsx@@ -0,0 +1,232 @@+import { ChevronRight } from 'lucide-react'+import { UseFormReturn } from 'react-hook-form'++import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import {+ Badge,+ Button,+ Dialog,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogSectionSeparator,+ DialogTitle,+ DialogTrigger,+ Table,+ TableBody,+ TableCaption,+ TableCell,+ TableHead,+ TableHeader,+ TableRow,+} from 'ui'+import BillingChangeBadge from './BillingChangeBadge'+import { DiskStorageSchemaType } from './DiskManagementPanelSchema'+import { DiskMangementCoolDownSection } from './DiskManagementCoolDownSection'++const TableHeaderRow = () => (+ <TableRow>+ <TableHead className="w-[140px] pl-5">Disk attribute</TableHead>+ <TableHead className="text-right">-</TableHead>+ <TableHead className="w-[100px]">Unit</TableHead>+ <TableHead className="text-right pr-5">Price Change</TableHead>+ </TableRow>+)++interface TableDataRowProps {+ attribute: string+ defaultValue: string | number+ newValue: string | number+ unit: string+ beforePrice: number+ afterPrice: number+ hidePrice?: boolean+}++const TableDataRow = ({+ attribute,+ defaultValue,+ newValue,+ unit,+ beforePrice,+ afterPrice,+ hidePrice = false,+}: TableDataRowProps) => (+ <TableRow>+ <TableCell className="pl-5">+ <div className="flex flex-row gap-2 items-center">+ <span>{attribute}</span>+ </div>+ </TableCell>+ <TableCell className="text-right font-mono">+ {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>+ <ChevronRight size={12} strokeWidth={2} className="text-foreground-muted" />+ <span className="text-xs font-mono text-foreground">{newValue}</span>+ </div>+ </Badge>+ ) : (+ <span className="text-xs font-mono">+ <span className="text-foreground-muted"></span>+ {defaultValue}+ </span>+ )}+ </TableCell>+ <TableCell className="text-xs font-mono">{unit}</TableCell>+ <TableCell className="text-right pr-5">+ {hidePrice ? (+ <span className="text-xs font-mono">-</span>+ ) : beforePrice !== afterPrice ? (+ <BillingChangeBadge show={true} beforePrice={beforePrice} afterPrice={afterPrice} />+ ) : (+ <span className="text-xs font-mono">${beforePrice}</span>+ )}+ </TableCell>+ </TableRow>+)++interface DiskSizeMeterProps {+ loading: boolean+ form: UseFormReturn<DiskStorageSchemaType>+ iopsPrice: { oldPrice: string; newPrice: string }+ throughputPrice: { oldPrice: string; newPrice: string }+ diskSizePrice: { oldPrice: string; newPrice: string }+ isDialogOpen: boolean+ isWithinCooldown: boolean+ setIsDialogOpen: (isOpen: boolean) => void+ onSubmit: (values: DiskStorageSchemaType) => Promise<void>+}++export const DiskManagementReviewAndSubmitDialog = ({+ isDialogOpen,+ setIsDialogOpen,+ isWithinCooldown,+ form,+ loading,+ onSubmit,+ iopsPrice,+ throughputPrice,+ diskSizePrice,+}: DiskSizeMeterProps) => {+ const isDirty = Object.keys(form.formState.dirtyFields).length > 0++ return (+ <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>+ <DialogTrigger asChild>+ <ButtonTooltip+ htmlType="submit"+ type="primary"+ onClick={async (e) => {+ e.preventDefault()+ const isValid = await form.trigger()+ if (isValid) setIsDialogOpen(true)+ }}+ disabled={isWithinCooldown || !isDirty}+ tooltip={{+ content: {+ side: 'bottom',+ text: isWithinCooldown+ ? 'Currently within cooldown period from previous disk change'+ : undefined,+ },+ }}+ >+ Review changes+ </ButtonTooltip>+ </DialogTrigger>+ <DialogContent size="large">+ <DialogHeader>+ <DialogTitle>Review changes</DialogTitle>+ <DialogDescription>+ Disk configuration changes will be applied shortly once confirmed.+ </DialogDescription>+ </DialogHeader>+ <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="Disk size"+ defaultValue={form.formState.defaultValues?.totalSize ?? 0}+ newValue={form.getValues('totalSize')}+ unit="GiB"+ beforePrice={Number(diskSizePrice.oldPrice)}+ afterPrice={Number(diskSizePrice.newPrice)}+ />+ <TableDataRow+ attribute="IOPS"+ defaultValue={form.formState.defaultValues?.provisionedIOPS ?? 0}+ newValue={form.getValues('provisionedIOPS')}+ unit="IOPS"+ beforePrice={Number(iopsPrice.oldPrice)}+ afterPrice={Number(iopsPrice.newPrice)}+ />+ {form.getValues('storageType') === 'gp3' ? (+ <TableDataRow+ attribute="Throughput"+ defaultValue={form.formState.defaultValues?.throughput ?? 0}+ newValue={form.getValues('throughput') ?? 0}+ unit="MiBps"+ beforePrice={Number(throughputPrice.oldPrice)}+ afterPrice={Number(throughputPrice.newPrice)}+ />+ ) : (+ <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>+ )}+ </TableBody>+ <TableCaption className="mt-2 mb-2">+ Please take note of the above billing changes+ </TableCaption>+ </Table>++ <DialogSectionSeparator />++ <DiskMangementCoolDownSection />++ <DialogFooter>+ <Button block size="small" type="default" onClick={() => setIsDialogOpen(false)}>+ Cancel+ </Button>++ <Button+ block+ size="small"+ htmlType="submit"+ loading={loading}+ onClick={async () => {+ await onSubmit(form.getValues())+ }}+ >+ Confirm changes+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/studio/components/interfaces/DiskManagement/DiskSpaceBar.tsx b/apps/studio/components/interfaces/DiskManagement/DiskSpaceBar.tsxnew file mode 100644index 00000000000..83012b5ee9f--- /dev/null+++ b/apps/studio/components/interfaces/DiskManagement/DiskSpaceBar.tsx@@ -0,0 +1,200 @@+import { AnimatePresence, motion } from 'framer-motion'+import MotionNumber from 'motion-number'+import { useState } from 'react'++import {+ badgeVariants,+ cn,+ HoverCard,+ HoverCardContent,+ HoverCardTrigger,+ Tooltip_Shadcn_,+ TooltipContent_Shadcn_,+ TooltipTrigger_Shadcn_,+} from 'ui'++interface DiskSpaceBarProps {+ showNewBar: boolean+ totalSize: number+ usedSize: number+ newTotalSize: number+}++export default function DiskSpaceBar({+ showNewBar,+ totalSize,+ usedSize,+ newTotalSize,+}: DiskSpaceBarProps) {+ // const [totalSize, setTotalSize] = useState<number>(8) // 8 GB total disk size+ // const [usedSize, setUsedSize] = useState<number>(4) // Starting with 4 GB used (50% usage)+ const [resizeThreshold, setResizeThreshold] = useState<number>(0.5) // 500 MB threshold for resize++ const usedPercentage = (usedSize / totalSize) * 100+ const resizePoint = totalSize - resizeThreshold+ const resizePercentage = (resizePoint / totalSize) * 100++ const newUsedPercentage = (usedSize / newTotalSize) * 100+ const newResizePoint = newTotalSize - resizeThreshold+ const newResizePercentage = (newResizePoint / newTotalSize) * 100++ return (+ <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{' '}+ <span className="text-foreground font-semibold -mt-[2px]">+ <MotionNumber+ value={newTotalSize}+ style={{ lineHeight: 0.8 }}+ transition={{+ y: { type: 'spring', duration: 0.35, bounce: 0 },+ }}+ className="font-mono"+ />+ </span>{' '}+ GB+ </span>+ </div>+ <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'+ )}+ >+ <AnimatePresence>+ {!showNewBar ? (+ <motion.div+ key="currentBar"+ initial={{ rotateY: 90, zIndex: 2 }}+ animate={{ rotateY: 0, zIndex: 1 }}+ exit={{ rotateY: -90, zIndex: 2 }}+ transition={{ duration: 0.3 }}+ style={{ transformOrigin: 'left center', backfaceVisibility: 'hidden' }}+ className="absolute inset-0 rounded-sm overflow-hidden"+ >+ <div className="h-full flex">+ <div+ className="bg-foreground relative overflow-hidden transition-all duration-500 ease-in-out"+ style={{ width: `${usedPercentage}%` }}+ >+ <div+ className="absolute inset-0"+ style={{+ backgroundImage: `repeating-linear-gradient(+ -45deg,+ rgba(255,255,255,0.1),+ rgba(255,255,255,0.1) 1px,+ transparent 1px,+ transparent 4px+ )`,+ }}+ />+ </div>+ <div+ className="bg-transparent border-r transition-all duration-500 ease-in-out"+ style={{ width: `${resizePercentage - usedPercentage}%` }}+ />+ </div>+ </motion.div>+ ) : (+ <motion.div+ key="newBar"+ initial={{ rotateY: -90, zIndex: 2 }}+ animate={{ rotateY: 0, zIndex: 1 }}+ exit={{ rotateY: 90, zIndex: 2 }}+ transition={{ duration: 0.3 }}+ style={{ transformOrigin: 'left center', backfaceVisibility: 'hidden' }}+ className="absolute inset-0 rounded-sm overflow-hidden"+ >+ <div className="h-full flex">+ <div+ className="bg-foreground relative overflow-hidden transition-all duration-500 ease-in-out"+ style={{ width: `${newUsedPercentage}%` }}+ >+ <div+ className="absolute inset-0"+ style={{+ backgroundImage: `repeating-linear-gradient(+ -45deg,+ rgba(255,255,255,0.1),+ rgba(255,255,255,0.1) 1px,+ transparent 1px,+ transparent 4px+ )`,+ }}+ />+ </div>+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ <AnimatePresence>+ {showNewBar && (+ <motion.span+ initial={{ opacity: 0, x: 4 }}+ animate={{ opacity: 1, x: 0 }}+ exit={{ opacity: 0, x: 4 }}+ transition={{+ duration: 0.12,+ delay: 0.12,+ }}+ className={cn(badgeVariants({ variant: 'success' }), 'absolute right-1 top-[5px]')}+ >+ New disk size+ </motion.span>+ )}+ </AnimatePresence>+ </div>+ <AnimatePresence mode="wait">+ {!showNewBar && (+ <motion.div+ key="currentSize"+ initial={{ opacity: 0, y: -10 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: 10 }}+ transition={{ duration: 0.1 }}+ className="absolute h-8 w-full -mx-[2px]"+ >+ <div+ className="absolute top-0 -left-0 h-full flex items-center transition-all duration-500 ease-in-out"+ style={{ left: `${showNewBar ? newResizePercentage : resizePercentage}%` }}+ >+ <Tooltip_Shadcn_>+ <TooltipTrigger_Shadcn_ asChild>+ <div className="absolute right-full bottom-0 border mr-2 px-2 py-1 bg-surface-400 rounded text-xs text-foreground-light whitespace-nowrap">+ Autoscaling+ </div>+ </TooltipTrigger_Shadcn_>+ <TooltipContent_Shadcn_ side="bottom" className="w-[310px] flex flex-col gap-y-1">+ <p>+ Supabase expands your disk storage automatically when the database reached 90%+ of the disk size. However, any disk modifications, including auto-scaling, can+ only take place once every 6 hours.+ </p>+ <p>+ If within those 6 hours you reach 95% of the disk space, your project{' '}+ <span className="text-destructive-600">will enter read-only mode.</span>+ </p>+ </TooltipContent_Shadcn_>+ </Tooltip_Shadcn_>+ <div className="w-px h-full bg-border" />+ </div>+ </motion.div>+ )}+ </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>+ </div>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsx b/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsxindex 3a5fd782d24..db60e354dcd 100644--- a/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsx+++ b/apps/studio/components/interfaces/Organization/IntegrationSettings/SidePanelVercelProjectLinker.tsx@@ -19,7 +19,7 @@ import { SidePanel } from 'ui'const VERCEL_ICON = (<svg xmlns="http://www.w3.org/2000/svg" fill="white" viewBox="0 0 512 512" className="w-6">- <path fill-rule="evenodd" d="M256,48,496,464H16Z" />+ <path fillRule="evenodd" d="M256,48,496,464H16Z" /></svg>)diff --git a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsxindex 65400338c3e..263c5752d72 100644--- a/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx+++ b/apps/studio/components/interfaces/Settings/Database/ConnectionPooling/ConnectionPooling.tsx@@ -2,6 +2,7 @@ import { zodResolver } from '@hookform/resolvers/zod'import { PermissionAction } from '@supabase/shared-types/out/constants'import { useParams } from 'common'import { capitalize } from 'lodash'+import { ExternalLink } from 'lucide-react'import { Fragment, useEffect } from 'react'import { SubmitHandler, useForm } from 'react-hook-form'import { toast } from 'sonner'@@ -37,7 +38,6 @@ import {} from 'ui'import { SESSION_MODE_DESCRIPTION, TRANSACTION_MODE_DESCRIPTION } from '../Database.constants'import { POOLING_OPTIMIZATIONS } from './ConnectionPooling.constants'-import { ExternalLink } from 'lucide-react'const formId = 'connection-pooling-form'diff --git a/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx b/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsxindex ae3d6a4954e..0f7ff4d7fbd 100644--- a/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DiskSizeConfiguration.tsx@@ -19,7 +19,7 @@ import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { useUrlState } from 'hooks/ui/useUrlState'import { formatBytes } from 'lib/helpers'-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button } from 'ui'+import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, InfoIcon } from 'ui'export interface DiskSizeConfigurationProps {disabled?: boolean@@ -49,13 +49,12 @@ const DiskSizeConfiguration = ({ disabled = false }: DiskSizeConfigurationProps)})const { data: projectSubscriptionData } = useOrgSubscriptionQuery({ orgSlug: organization?.slug })- const { mutate: updateProjectUsage, isLoading: isUpdatingDiskSize } =- useProjectDiskResizeMutation({- onSuccess: (res, variables) => {- toast.success(`Successfully updated disk size to ${variables.volumeSize} GB`)- setShowIncreaseDiskSizeModal(false)- },- })+ const { isLoading: isUpdatingDiskSize } = useProjectDiskResizeMutation({+ onSuccess: (_, variables) => {+ toast.success(`Successfully updated disk size to ${variables.volumeSize} GB`)+ setShowIncreaseDiskSizeModal(false)+ },+ })const currentDiskSize = project?.volumeSizeGb ?? 0@@ -154,7 +153,7 @@ Read more about [disk management](https://supabase.com/docs/guides/platform/data</div>) : (<Alert_Shadcn_>- <Info size={16} />+ <InfoIcon /><AlertTitle_Shadcn_>{projectSubscriptionData?.plan?.id === 'free'? 'Disk size configuration is not available for projects on the Free Plan'diff --git a/apps/studio/components/interfaces/Settings/Database/DiskSizeConfigurationModal.tsx b/apps/studio/components/interfaces/Settings/Database/DiskSizeConfigurationModal.tsxindex cbd8a637f23..6a63584472e 100644--- a/apps/studio/components/interfaces/Settings/Database/DiskSizeConfigurationModal.tsx+++ b/apps/studio/components/interfaces/Settings/Database/DiskSizeConfigurationModal.tsx@@ -17,6 +17,7 @@ import {Alert_Shadcn_,Button,Form,+ InfoIcon,InputNumber,Modal,WarningIcon,@@ -177,7 +178,7 @@ const DiskSizeConfigurationModal = ({</Form>) : (<Alert_Shadcn_ className="border-none">- <Info size={16} />+ <InfoIcon /><AlertTitle_Shadcn_>{projectSubscriptionData?.plan?.id === 'free'? 'Disk size configuration is not available for projects on the Free Plan'diff --git a/apps/studio/components/layouts/Scaffold.tsx b/apps/studio/components/layouts/Scaffold.tsxindex d5ef8d85c21..9497e4a1115 100644--- a/apps/studio/components/layouts/Scaffold.tsx+++ b/apps/studio/components/layouts/Scaffold.tsx@@ -1,7 +1,7 @@import React from 'react'import { cn } from 'ui'-const maxWidthClasses = 'mx-auto w-full max-w-[1600px]'+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]'diff --git a/apps/studio/components/ui/CountdownTimer/CountdownTimerRadial.tsx b/apps/studio/components/ui/CountdownTimer/CountdownTimerRadial.tsxnew file mode 100644index 00000000000..487d36c618e--- /dev/null+++ b/apps/studio/components/ui/CountdownTimer/CountdownTimerRadial.tsx@@ -0,0 +1,58 @@+import { PolarGrid, RadialBar, RadialBarChart } from 'recharts'+import { ChartConfig, ChartContainer } from 'ui'++interface CountdownTimerRadialProps {+ progress: number+}++const chartConfig = {+ timeRemaining: {+ label: 'timeRemaining',+ color: 'hsl(var(--warning-default))',+ },+ hand: {+ label: 'hand',+ color: 'hsl(var(--warning-default))',+ },+} satisfies ChartConfig++const CountdownTimerRadial = ({ progress }: CountdownTimerRadialProps) => {+ return (+ <div className="relative w-12 h-12">+ {/* timer ring */}+ <ChartContainer config={chartConfig} className="absolute w-12 h-12">+ <RadialBarChart+ data={[{ timeRemaining: 100, fill: 'var(--color-timeRemaining)' }]}+ startAngle={90}+ endAngle={90 - (progress * 360) / 100}+ innerRadius={21}+ outerRadius={14}+ >+ <PolarGrid+ gridType="circle"+ radialLines={false}+ stroke="none"+ className="first:fill-foreground-muted/50 last:fill-background-200"+ polarRadius={[16, 11]}+ />+ <RadialBar dataKey="timeRemaining" cornerRadius={2} />+ </RadialBarChart>+ </ChartContainer>++ <ChartContainer config={chartConfig} className="absolute top-1 left-1 w-10 h-10">+ <RadialBarChart+ data={[{ hand: 100, fill: 'var(--color-hand)' }]}+ // Adjust the angles to create a small hand+ startAngle={80 - (progress * 360) / 100}+ endAngle={140 - (progress * 360) / 100}+ innerRadius={14}+ outerRadius={5}+ >+ <RadialBar dataKey="hand" cornerRadius={2} isAnimationActive={true} />+ </RadialBarChart>+ </ChartContainer>+ </div>+ )+}++export default CountdownTimerRadialdiff --git a/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsx b/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsxnew file mode 100644index 00000000000..db91c93dec1--- /dev/null+++ b/apps/studio/components/ui/CountdownTimer/CountdownTimerSpan.tsx@@ -0,0 +1,43 @@+import MotionNumber from 'motion-number'++interface CountdownTimerSpanProps {+ seconds: number+}++const CountdownTimerSpan = ({ seconds }: CountdownTimerSpanProps) => {+ const transitionConfig = {+ y: { type: 'spring', duration: 0.35, bounce: 0 },+ }++ const hours = Math.floor(seconds / 3600)+ const minutes = Math.floor((seconds % 3600) / 60)+ const remainingSeconds = seconds % 60++ const formatConfig = { minimumIntegerDigits: 2 }+ 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>+ )+}++export default CountdownTimerSpandiff --git a/apps/studio/data/config/disk-attributes-query.ts b/apps/studio/data/config/disk-attributes-query.tsnew file mode 100644index 00000000000..450dd9cccf1--- /dev/null+++ b/apps/studio/data/config/disk-attributes-query.ts@@ -0,0 +1,71 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'+import dayjs from 'dayjs'+import { useMemo } from 'react'++import type { components } from 'data/api'+import { get, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { COOLDOWN_DURATION } from './disk-attributes-update-mutation'+import { configKeys } from './keys'++export type DiskAttributesVariables = {+ projectRef?: string+}++export type DiskAttribute = components['schemas']['DiskResponse']++export async function getDiskAttributes(+ { projectRef }: DiskAttributesVariables,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('Project ref is required')++ const { data, error } = await get(`/platform/projects/{ref}/disk`, {+ params: { path: { ref: projectRef } },+ signal,+ })++ if (error) handleError(error)+ return data+}++export type DiskAttributesData = Awaited<ReturnType<typeof getDiskAttributes>>+export type DiskAttributesError = ResponseError++export const useDiskAttributesQuery = <TData = DiskAttributesData>(+ { projectRef }: DiskAttributesVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<DiskAttributesData, DiskAttributesError, TData> = {}+) =>+ useQuery<DiskAttributesData, DiskAttributesError, TData>(+ configKeys.diskAttributes(projectRef),+ ({ signal }) => getDiskAttributes({ projectRef }, signal),+ { enabled: enabled && typeof projectRef !== 'undefined', ...options }+ )++export const useRemainingDurationForDiskAttributeUpdate = ({+ projectRef,+}: {+ projectRef?: string+}) => {+ const { data } = useDiskAttributesQuery({ projectRef })++ const lastModifiedAtString = dayjs(data?.last_modified_at ?? '').utc()+ const secondsFromNow = Math.max(+ 0,+ dayjs().utc().diff(dayjs(lastModifiedAtString).utc(), 'second')+ )++ const remainingDuration = useMemo(() => {+ return lastModifiedAtString === undefined || COOLDOWN_DURATION - secondsFromNow < 0+ ? 0+ : COOLDOWN_DURATION - secondsFromNow+ }, [lastModifiedAtString])++ if (data?.last_modified_at === undefined)+ return { remainingDuration: 0, isWithinCooldownWindow: false }++ return { remainingDuration, isWithinCooldownWindow: remainingDuration > 0 }+}diff --git a/apps/studio/data/config/disk-attributes-update-mutation.ts b/apps/studio/data/config/disk-attributes-update-mutation.tsnew file mode 100644index 00000000000..3b8ea297cb1--- /dev/null+++ b/apps/studio/data/config/disk-attributes-update-mutation.ts@@ -0,0 +1,81 @@+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'+import { toast } from 'sonner'++import { handleError, post } from 'data/fetchers'+import type { ResponseError } from 'types'+import { components } from 'api-types'+import { configKeys } from './keys'++type UpdateGP3Body = components['schemas']['DiskRequestAttributesGP3']+type UpdateIO2Body = components['schemas']['DiskRequestAttributesIO2']++export const COOLDOWN_DURATION = 60 * 60 * 6++export type UpdateDiskAttributesVariables = {+ ref: string+ storageType: 'gp3' | 'io2'+ provisionedIOPS: number+ throughput?: number+ totalSize: number+}++// [Joshen] Need to fix this+export async function updateDiskAttributes({+ ref,+ storageType,+ provisionedIOPS,+ throughput,+ totalSize,+}: UpdateDiskAttributesVariables) {+ const attributes =+ storageType === 'gp3'+ ? ({+ iops: provisionedIOPS,+ throughput_mbps: throughput,+ size_gb: totalSize,+ type: storageType,+ } as UpdateGP3Body)+ : ({+ iops: provisionedIOPS,+ size_gb: totalSize,+ type: storageType,+ } as UpdateIO2Body)++ const { data, error } = await post('/platform/projects/{ref}/disk', {+ params: { path: { ref } },+ body: { attributes },+ })+ if (error) handleError(error)+ return data+}++type UpdateDiskAttributesData = Awaited<ReturnType<typeof updateDiskAttributes>>++export const useUpdateDiskAttributesMutation = ({+ onSuccess,+ onError,+ ...options+}: Omit<+ UseMutationOptions<UpdateDiskAttributesData, ResponseError, UpdateDiskAttributesVariables>,+ 'mutationFn'+> = {}) => {+ const queryClient = useQueryClient()+ return useMutation<UpdateDiskAttributesData, ResponseError, UpdateDiskAttributesVariables>(+ (vars) => updateDiskAttributes(vars),+ {+ async onSuccess(data, variables, context) {+ const { ref } = variables+ await queryClient.invalidateQueries(configKeys.diskAttributes(ref))+ await onSuccess?.(data, variables, context)+ },+ async onError(data, variables, context) {+ if (onError === undefined) {+ toast.error(`Failed to update disk attributes: ${data.message}`)+ } else {+ onError(data, variables, context)+ }+ },+ ...options,+ }+ )+}diff --git a/apps/studio/data/config/disk-utilization-query.ts b/apps/studio/data/config/disk-utilization-query.tsnew file mode 100644index 00000000000..5d8b786f3e8--- /dev/null+++ b/apps/studio/data/config/disk-utilization-query.ts@@ -0,0 +1,40 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import { get, handleError } from 'data/fetchers'+import type { ResponseError } from 'types'+import { configKeys } from './keys'++export type DiskUtilizationVariables = {+ projectRef?: string+}++export async function getDiskUtilization(+ { projectRef }: DiskUtilizationVariables,+ signal?: AbortSignal+) {+ if (!projectRef) throw new Error('Project ref is required')++ const { data, error } = await get(`/platform/projects/{ref}/disk/util`, {+ params: { path: { ref: projectRef } },+ signal,+ })++ if (error) handleError(error)+ return data+}++export type DiskUtilizationData = Awaited<ReturnType<typeof getDiskUtilization>>+export type DiskUtilizationError = ResponseError++export const useDiskUtilizationQuery = <TData = DiskUtilizationData>(+ { projectRef }: DiskUtilizationVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<DiskUtilizationData, DiskUtilizationError, TData> = {}+) =>+ useQuery<DiskUtilizationData, DiskUtilizationError, TData>(+ configKeys.diskUtilization(projectRef),+ ({ signal }) => getDiskUtilization({ projectRef }, signal),+ { enabled: enabled && typeof projectRef !== 'undefined', ...options }+ )diff --git a/apps/studio/data/config/keys.ts b/apps/studio/data/config/keys.tsindex ab20e0a678e..c0b37ff5210 100644--- a/apps/studio/data/config/keys.ts+++ b/apps/studio/data/config/keys.ts@@ -11,4 +11,8 @@ export const configKeys = {['projects', projectRef, 'upgrade-eligibility'] as const,upgradeStatus: (projectRef: string | undefined) =>['projects', projectRef, 'upgrade-status'] as const,+ diskAttributes: (projectRef: string | undefined) =>+ ['projects', projectRef, 'disk-attributes'] as const,+ diskUtilization: (projectRef: string | undefined) =>+ ['projects', projectRef, 'disk-utilization'] as const,}diff --git a/apps/studio/data/config/project-disk-resize-mutation.ts b/apps/studio/data/config/project-disk-resize-mutation.tsindex af0e9aeb689..1118c9286f2 100644--- a/apps/studio/data/config/project-disk-resize-mutation.ts+++ b/apps/studio/data/config/project-disk-resize-mutation.ts@@ -31,6 +31,11 @@ export async function resizeProjectDisk({ projectRef, volumeSize }: ProjectDiskRtype ProjectDiskResizeData = Awaited<ReturnType<typeof resizeProjectDisk>>+/**+ * @deprecated We'll need to use the new endpoint instead+ * @param param0+ * @returns+ */export const useProjectDiskResizeMutation = ({onSuccess,onError,diff --git a/apps/studio/data/subscriptions/org-subscription-query.ts b/apps/studio/data/subscriptions/org-subscription-query.tsindex 7b44f8cd351..5521589596a 100644--- a/apps/studio/data/subscriptions/org-subscription-query.ts+++ b/apps/studio/data/subscriptions/org-subscription-query.ts@@ -5,11 +5,14 @@ import { get, handleError } from 'data/fetchers'import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'import type { ResponseError } from 'types'import { subscriptionKeys } from './keys'+import { components } from 'api-types'export type OrgSubscriptionVariables = {orgSlug?: string}+export type PlanType = components['schemas']['BillingPlanId']+export async function getOrgSubscription({ orgSlug }: OrgSubscriptionVariables,signal?: AbortSignaldiff --git a/apps/studio/package.json b/apps/studio/package.jsonindex 4dae61c3ec0..cb15dab98a3 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -68,6 +68,7 @@"mobx": "^6.10.2","mobx-react-lite": "^4.0.5","monaco-editor": "0.33.0",+ "motion-number": "^0.1.7","next": "^14.2.3","next-themes": "^0.3.0","nuqs": "^1.17.8",diff --git a/apps/studio/pages/project/[ref]/reports/database.tsx b/apps/studio/pages/project/[ref]/reports/database.tsxindex abd873d978c..479a18d74df 100644--- a/apps/studio/pages/project/[ref]/reports/database.tsx+++ b/apps/studio/pages/project/[ref]/reports/database.tsx@@ -26,6 +26,9 @@ import { TIME_PERIODS_INFRA } from 'lib/constants/metrics'import { formatBytes } from 'lib/helpers'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import type { NextPageWithLayout } from 'types'+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import { useFlag } from 'hooks/ui/useFlag'const DatabaseReport: NextPageWithLayout = () => {return (@@ -40,13 +43,20 @@ DatabaseReport.getLayout = (page) => <ReportsLayout title="Database">{page}</Repexport default DatabaseReportconst DatabaseUsage = () => {- const { db, chart } = useParams()+ const { db, chart, ref } = useParams()const { project } = useProjectContext()- const [dateRange, setDateRange] = useState<any>(undefined)+ const diskManagementV2 = useFlag('diskManagementV2')++ const org = useSelectedOrganization()const state = useDatabaseSelectorStateSnapshot()+ const [dateRange, setDateRange] = useState<any>(undefined)const isReplicaSelected = state.selectedDatabaseId !== project?.ref+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: org?.slug })+ const showNewDiskManagementUI =+ subscription?.usage_based_billing_project_addons && diskManagementV2+const report = useDatabaseReport()const { data } = useDatabaseSizeQuery({projectRef: project?.ref,@@ -213,21 +223,29 @@ const DatabaseUsage = () => {</div><div className="col-span-8 text-right">- <ButtonTooltip- type="default"- disabled={!canUpdateDiskSizeConfig}- onClick={() => setshowIncreaseDiskSizeModal(true)}- tooltip={{- content: {- side: 'bottom',- text: !canUpdateDiskSizeConfig- ? 'You need additional permissions to increase the disk size'- : undefined,- },- }}- >- Increase disk size- </ButtonTooltip>+ {showNewDiskManagementUI ? (+ <Button asChild type="default">+ <Link href={`/project/${ref}/settings/database#disk-management`}>+ Increase disk size+ </Link>+ </Button>+ ) : (+ <ButtonTooltip+ type="default"+ disabled={!canUpdateDiskSizeConfig}+ onClick={() => setshowIncreaseDiskSizeModal(true)}+ tooltip={{+ content: {+ side: 'bottom',+ text: !canUpdateDiskSizeConfig+ ? 'You need additional permissions to increase the disk size'+ : undefined,+ },+ }}+ >+ Increase disk size+ </ButtonTooltip>+ )}</div></div>diff --git a/apps/studio/pages/project/[ref]/settings/database.tsx b/apps/studio/pages/project/[ref]/settings/database.tsxindex 209e0b70ffb..11230ca81c3 100644--- a/apps/studio/pages/project/[ref]/settings/database.tsx+++ b/apps/studio/pages/project/[ref]/settings/database.tsx@@ -6,15 +6,26 @@ import {import SettingsLayout from 'components/layouts/ProjectSettingsLayout/SettingsLayout'import type { NextPageWithLayout } from 'types'+import { DiskManagementPanelForm } from 'components/interfaces/DiskManagement/DiskManagementPanelForm'import BannedIPs from 'components/interfaces/Settings/Database/BannedIPs'import { DatabaseReadOnlyAlert } from 'components/interfaces/Settings/Database/DatabaseReadOnlyAlert'import { DatabaseConnectionString } from 'components/interfaces/Settings/Database/DatabaseSettings/DatabaseConnectionString'-import DiskSizeConfiguration from 'components/interfaces/Settings/Database/DiskSizeConfiguration'import { PoolingModesModal } from 'components/interfaces/Settings/Database/PoolingModesModal'import SSLConfiguration from 'components/interfaces/Settings/Database/SSLConfiguration'import { ScaffoldContainer, ScaffoldHeader, ScaffoldTitle } from 'components/layouts/Scaffold'+import DiskSizeConfiguration from 'components/interfaces/Settings/Database/DiskSizeConfiguration'+import { useFlag } from 'hooks/ui/useFlag'+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'const ProjectSettings: NextPageWithLayout = () => {+ const diskManagementV2 = useFlag('diskManagementV2')+ const selectedOrg = useSelectedOrganization()+ const { data: subscription } = useOrgSubscriptionQuery({ orgSlug: selectedOrg?.slug })++ const showNewDiskManagementUI =+ subscription?.usage_based_billing_project_addons && diskManagementV2+return (<><ScaffoldContainer>@@ -32,7 +43,7 @@ const ProjectSettings: NextPageWithLayout = () => {</div><SSLConfiguration />- <DiskSizeConfiguration />+ {showNewDiskManagementUI ? <DiskManagementPanelForm /> : <DiskSizeConfiguration />}<NetworkRestrictions /><BannedIPs /></div>diff --git a/apps/studio/styles/main.scss b/apps/studio/styles/main.scssindex 45d68861e71..76b53d65087 100644--- a/apps/studio/styles/main.scss+++ b/apps/studio/styles/main.scss@@ -7,6 +7,22 @@@import '~ui/build/css/themes/light.css';@import '~ui/build/css/themes/classic-dark.css';+:root {+ --chart-1: 12 76% 61%;+ --chart-2: 173 58% 39%;+ --chart-3: 197 37% 24%;+ --chart-4: 43 74% 66%;+ --chart-5: 27 87% 67%;+}++.dark {+ --chart-1: 220 70% 50%;+ --chart-2: 160 60% 45%;+ --chart-3: 30 80% 55%;+ --chart-4: 280 65% 60%;+ --chart-5: 340 75% 55%;+}+@layer utilities {.btn-primary {@apply inline-block rounded border border-green-500 bg-green-500 py-1 px-3 text-sm;diff --git a/package-lock.json b/package-lock.jsonindex 77a7195197f..b0a7d2d6ea2 100644--- a/package-lock.json+++ b/package-lock.json@@ -1555,6 +1555,7 @@"mobx": "^6.10.2","mobx-react-lite": "^4.0.5","monaco-editor": "0.33.0",+ "motion-number": "^0.1.7","next": "^14.2.3","next-themes": "^0.3.0","nuqs": "^1.17.8",@@ -2560,20 +2561,21 @@}},"apps/studio/node_modules/framer-motion": {- "version": "11.0.3",- "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.0.3.tgz",- "integrity": "sha512-6x2poQpIWBdbZwLd73w6cKZ1I9IEPIU94C6/Swp1Zt3LJ+sB5bPe1E2wC6EH5hSISXNkMJ4afH7AdwS7MrtkWw==",+ "version": "11.3.31",+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.3.31.tgz",+ "integrity": "sha512-Xmxs08WBXnc2tNzNZbFSpquI33lvleJg4Y+hmZ+vFkn+laN9ZnR3gbZnNGKDtuz7c/x3u8dLg05OU3EhLobCsg==","dependencies": {"tslib": "^2.4.0"},- "optionalDependencies": {- "@emotion/is-prop-valid": "^0.8.2"- },"peerDependencies": {+ "@emotion/is-prop-valid": "*","react": "^18.0.0","react-dom": "^18.0.0"},"peerDependenciesMeta": {+ "@emotion/is-prop-valid": {+ "optional": true+ },"react": {"optional": true},@@ -2624,6 +2626,16 @@"node": ">= 0.6"}},+ "apps/studio/node_modules/motion-number": {+ "version": "0.1.7",+ "resolved": "https://registry.npmjs.org/motion-number/-/motion-number-0.1.7.tgz",+ "integrity": "sha512-WOqZSqimX/OTNoFsz6Hk67r1omeUmtC2jH2x6Zy7/gNVnh98AOTrkINygXLR2xoef8k7iVDoKwk4PUcrxI+bog==",+ "peerDependencies": {+ "framer-motion": "^11.3.19",+ "react": "^18.0.0",+ "react-dom": "^18.0.0"+ }+ },"apps/studio/node_modules/openapi-fetch": {"version": "0.6.2","resolved": "https://registry.npmjs.org/openapi-fetch/-/openapi-fetch-0.6.2.tgz",@@ -43188,6 +43200,7 @@"common-tags": "^1.8.2","date-fns": "^2.30.0","formik": "^2.2.9",+ "framer-motion": "^11.0.3","highlightjs-curl": "^1.3.0","input-otp": "^1.2.3","lodash": "^4.17.21",@@ -44305,6 +44318,30 @@"balanced-match": "^1.0.0"}},+ "packages/ui/node_modules/framer-motion": {+ "version": "11.5.4",+ "resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-11.5.4.tgz",+ "integrity": "sha512-E+tb3/G6SO69POkdJT+3EpdMuhmtCh9EWuK4I1DnIC23L7tFPrl8vxP+LSovwaw6uUr73rUbpb4FgK011wbRJQ==",+ "dependencies": {+ "tslib": "^2.4.0"+ },+ "peerDependencies": {+ "@emotion/is-prop-valid": "*",+ "react": "^18.0.0",+ "react-dom": "^18.0.0"+ },+ "peerDependenciesMeta": {+ "@emotion/is-prop-valid": {+ "optional": true+ },+ "react": {+ "optional": true+ },+ "react-dom": {+ "optional": true+ }+ }+ },"packages/ui/node_modules/glob": {"version": "8.1.0","dev": true,diff --git a/packages/api-types/types/api.d.ts b/packages/api-types/types/api.d.tsindex 0bb2e311027..2af696d3d7a 100644--- a/packages/api-types/types/api.d.ts+++ b/packages/api-types/types/api.d.ts@@ -57,15 +57,7 @@ export interface paths {}'/partners/vercel/callback': {/** Redirects to Supabase dashboard after completing Vercel sso flow */- get: operations['CallbackController_redirectToDashboardFlyioExtensionScreen']- }- '/partners/vercel/mock-usage': {- /** Fake it till you make it */- get: operations['MockBillingController_mockUsage']- }- '/partners/vercel/mock-usage/invoice': {- /** Fake it till you make it */- get: operations['MockBillingController_sendInvoice']+ get: operations['CallbackController_redirectToDashboardVercelExtensionScreen']}'/partners/vercel/v1/installations/{installation_id}': {/** Gets the set of billing plans available to a specific Installation */@@ -159,6 +151,10 @@ export interface paths {/** Download project backup */post: operations['BackupsController_downloadBackup']}+ '/platform/database/{ref}/backups/downloadable-backups': {+ /** Gets backups that might be downloadable, but potentially not restorable. */+ get: operations['BackupsController_getDownloadableBackups']+ }'/platform/database/{ref}/backups/enable-physical-backups': {/** Enable usage of physical backups */post: operations['BackupsController_enablePhysicalBackup']@@ -885,6 +881,16 @@ export interface paths {/** Updates the database password */patch: operations['DbPasswordController_updatePassword']}+ '/platform/projects/{ref}/disk': {+ /** Get database disk attributes */+ get: operations['DiskController_getDisk']+ /** Modify database disk */+ post: operations['DiskController_modifyDisk']+ }+ '/platform/projects/{ref}/disk/util': {+ /** Get disk utilization */+ get: operations['DiskController_getDiskUtilization']+ }'/platform/projects/{ref}/infra-monitoring': {/** Gets project's usage metrics */get: operations['InfraMonitoringController_getUsageMetrics']@@ -1113,6 +1119,10 @@ export interface paths {/** Processes Vercel event */post: operations['VercelWebhooksController_processEvent']}+ '/system/orb/vercel/sync/invoices/{invoice_id}': {+ /** Syncs an invoice to Vercel. If already synced, Vercel will not process it again. */+ post: operations['VercelSyncController_syncInvoice']+ }'/system/orb/webhooks': {/** Processes Orb events */post: operations['OrbWebhooksController_processEvent']@@ -1218,6 +1228,10 @@ export interface paths {/** Refreshes secrets */post: operations['SecretsRefreshController_refreshSecrets']}+ '/system/projects/{ref}/wal-verification-reporting': {+ /** Processes a project's WAL verification report. */+ put: operations['WalVerificationReportingController_processWalVerification']+ }'/system/stripe/webhooks': {/** Processes Stripe event */post: operations['StripeWebhooksController_processEvent']@@ -1270,6 +1284,10 @@ export interface paths {/** Download project backup */post: operations['BackupsController_downloadBackup']}+ '/v0/database/{ref}/backups/downloadable-backups': {+ /** Gets backups that might be downloadable, but potentially not restorable. */+ get: operations['BackupsController_getDownloadableBackups']+ }'/v0/database/{ref}/backups/enable-physical-backups': {/** Enable usage of physical backups */post: operations['BackupsController_enablePhysicalBackup']@@ -1706,6 +1724,16 @@ export interface paths {/** Updates the database password */patch: operations['DbPasswordController_updatePassword']}+ '/v0/projects/{ref}/disk': {+ /** Get database disk attributes */+ get: operations['DiskController_getDisk']+ /** Modify database disk */+ post: operations['DiskController_modifyDisk']+ }+ '/v0/projects/{ref}/disk/util': {+ /** Get disk utilization */+ get: operations['DiskController_getDiskUtilization']+ }'/v0/projects/{ref}/infra-monitoring': {/** Gets project's usage metrics */get: operations['InfraMonitoringController_getUsageMetrics']@@ -2366,6 +2394,7 @@ export interface components {rate_limit_token_refresh: number | nullrate_limit_verify: number | nullrefresh_token_rotation_enabled: boolean | null+ saml_allow_encrypted_assertions: boolean | nullsaml_enabled: boolean | nullsaml_external_url: string | nullsecurity_captcha_enabled: boolean | null@@ -3101,12 +3130,65 @@ export interface components {DetachPaymentMethodBody: {card_id: string}+ DiskRequestAttributesGP3: {+ iops: number+ size_gb: number+ throughput_mbps: number+ /** @enum {string} */+ type: 'gp3'+ }+ DiskRequestAttributesIO2: {+ iops: number+ size_gb: number+ /** @enum {string} */+ type: 'io2'+ }+ DiskRequestBody: {+ attributes:+ | components['schemas']['DiskRequestAttributesGP3']+ | components['schemas']['DiskRequestAttributesIO2']+ }+ DiskResponse: {+ attributes:+ | components['schemas']['DiskResponseAttributesGP3']+ | components['schemas']['DiskResponseAttributesIO2']+ last_modified_at?: string+ requested_modification?:+ | components['schemas']['DiskResponseAttributesGP3']+ | components['schemas']['DiskResponseAttributesIO2']+ }+ DiskResponseAttributesGP3: {+ iops: number+ size_gb: number+ throughput_mbps: number+ /** @enum {string} */+ type: 'gp3'+ }+ DiskResponseAttributesIO2: {+ iops: number+ size_gb: number+ /** @enum {string} */+ type: 'io2'+ }+ DiskUtilMetrics: {+ fs_avail_bytes: number+ fs_size_bytes: number+ fs_used_bytes: number+ }+ DiskUtilMetricsResponse: {+ metrics: components['schemas']['DiskUtilMetrics']+ timestamp: string+ }Domain: {created_at?: stringdomain?: stringid: stringupdated_at?: string}+ DownloadableBackupsResponse: {+ backups: components['schemas']['Backup'][]+ status: Record<string, never>+ }DownloadBackupBody: {data: Record<string, never>id: number@@ -3552,6 +3634,7 @@ export interface components {RATE_LIMIT_TOKEN_REFRESH: numberRATE_LIMIT_VERIFY: numberREFRESH_TOKEN_ROTATION_ENABLED: boolean+ SAML_ALLOW_ENCRYPTED_ASSERTIONS: booleanSAML_ENABLED: booleanSAML_EXTERNAL_URL: stringSECURITY_CAPTCHA_ENABLED: boolean@@ -5407,6 +5490,7 @@ export interface components {price_id?: string/** @enum {string} */proration_behaviour?: 'prorate_and_invoice_end_of_cycle' | 'prorate_and_invoice_now'+ skip_outstanding_invoice_check?: boolean}UpdateAddonBody: {addon_type: components['schemas']['ProjectAddonType']@@ -5797,6 +5881,7 @@ export interface components {RATE_LIMIT_TOKEN_REFRESH?: numberRATE_LIMIT_VERIFY?: numberREFRESH_TOKEN_ROTATION_ENABLED?: boolean+ SAML_ALLOW_ENCRYPTED_ASSERTIONS?: booleanSAML_ENABLED?: booleanSAML_EXTERNAL_URL?: stringSECURITY_CAPTCHA_ENABLED?: boolean@@ -6004,6 +6089,8 @@ export interface components {payment_method?: stringprice_id?: stringskip_free_plan_validations?: boolean+ skip_outstanding_invoice_check?: boolean+ skip_payment_method_available_check?: boolean/** @enum {string} */tier: 'tier_payg' | 'tier_pro' | 'tier_free' | 'tier_team' | 'tier_enterprise'}@@ -6399,6 +6486,10 @@ export interface components {VercelRedirectResponse: {url: string}+ WalVerificationReportBody: {+ reportingToken: string+ walVerification: Record<string, never>+ }}responses: neverparameters: never@@ -6412,7 +6503,7 @@ export type $defs = Record<string, never>export type external = Record<string, never>export interface operations {- /** Redirects to Supabase dashboard after completing Vercel sso flow */+ /** Redirects to Supabase dashboard after completing Fly sso */CallbackController_redirectToDashboardFlyioExtensionScreen: {responses: {200: {@@ -6567,16 +6658,8 @@ export interface operations {}}}- /** Fake it till you make it */- MockBillingController_mockUsage: {- responses: {- 200: {- content: never- }- }- }- /** Fake it till you make it */- MockBillingController_sendInvoice: {+ /** Redirects to Supabase dashboard after completing Vercel sso flow */+ CallbackController_redirectToDashboardVercelExtensionScreen: {responses: {200: {content: never@@ -6602,7 +6685,7 @@ export interface operations {/** Deletes the installation with provided installation_id */InstallationsController_deleteInstallation: {responses: {- 204: {+ 200: {content: never}}@@ -6696,11 +6779,6 @@ export interface operations {}/** Return quotes for different billing plans for a specific product */ProductsController_listResources: {- parameters: {- path: {- product_id: string- }- }responses: {200: {content: never@@ -7063,6 +7141,26 @@ export interface operations {}}}+ /** Gets backups that might be downloadable, but potentially not restorable. */+ BackupsController_getDownloadableBackups: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['DownloadableBackupsResponse']+ }+ }+ /** @description Failed to get project backups */+ 500: {+ content: never+ }+ }+ }/** Enable usage of physical backups */BackupsController_enablePhysicalBackup: {parameters: {@@ -12196,6 +12294,78 @@ export interface operations {}}}+ /** Get database disk attributes */+ DiskController_getDisk: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['DiskResponse']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to get database disk attributes */+ 500: {+ content: never+ }+ }+ }+ /** Modify database disk */+ DiskController_modifyDisk: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['DiskRequestBody']+ }+ }+ responses: {+ 201: {+ content: never+ }+ 403: {+ content: never+ }+ /** @description Failed to modify database disk */+ 500: {+ content: never+ }+ }+ }+ /** Get disk utilization */+ DiskController_getDiskUtilization: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ responses: {+ 200: {+ content: {+ 'application/json': components['schemas']['DiskUtilMetricsResponse']+ }+ }+ 403: {+ content: never+ }+ /** @description Failed to get disk utilization */+ 500: {+ content: never+ }+ }+ }/** Gets project's usage metrics */InfraMonitoringController_getUsageMetrics: {parameters: {@@ -13460,6 +13630,26 @@ export interface operations {}}}+ /** Syncs an invoice to Vercel. If already synced, Vercel will not process it again. */+ VercelSyncController_syncInvoice: {+ parameters: {+ query: {+ dryRun: boolean+ }+ path: {+ invoice_id: string+ }+ }+ responses: {+ 200: {+ content: never+ }+ /** @description Failed to sync invoice */+ 500: {+ content: never+ }+ }+ }/** Processes Orb events */OrbWebhooksController_processEvent: {requestBody: {@@ -14018,6 +14208,29 @@ export interface operations {}}}+ /** Processes a project's WAL verification report. */+ WalVerificationReportingController_processWalVerification: {+ parameters: {+ path: {+ /** @description Project ref */+ ref: string+ }+ }+ requestBody: {+ content: {+ 'application/json': components['schemas']['WalVerificationReportBody']+ }+ }+ responses: {+ 200: {+ content: never+ }+ /** @description Failed to update health status. */+ 500: {+ content: never+ }+ }+ }/** Processes Stripe event */StripeWebhooksController_processEvent: {parameters: {diff --git a/packages/ui-patterns/form/Layout/FormLayout.tsx b/packages/ui-patterns/form/Layout/FormLayout.tsxindex 7e2d1b68a3d..412dfd01fb2 100644--- a/packages/ui-patterns/form/Layout/FormLayout.tsx+++ b/packages/ui-patterns/form/Layout/FormLayout.tsx@@ -8,6 +8,7 @@ import {cn,} from 'ui'import { SIZE } from 'ui/src/lib/constants'+import { AnimatePresence, motion } from 'framer-motion'type Props = {align?: 'left' | 'right'@@ -60,7 +61,7 @@ const ContainerVariants = cva('relative grid gap-2', {defaultVariants: {},})-const LabelContainerVariants = cva('', {+const LabelContainerVariants = cva('transition-all duration-500 ease-in-out', {variants: {flex: {true: '',@@ -107,7 +108,7 @@ const LabelContainerVariants = cva('', {defaultVariants: {},})-const DataContainerVariants = cva('', {+const DataContainerVariants = cva('transition-all duration-500 ease-in-out', {variants: {flex: {true: '',@@ -278,7 +279,18 @@ export const FormLayout = React.forwardRef<const flex = layout === 'flex'const hasLabel = Boolean(label || beforeLabel || afterLabel)const renderError = isReactForm && !hideMessage && (- <FormMessage_Shadcn_ className="mt-2" data-formlayout-id={'message'} />+ <motion.div+ initial={{ opacity: 0, y: -10 }}+ animate={{ opacity: 1, y: 0 }}+ exit={{ opacity: 0, y: -10 }}+ transition={{ duration: 0.3, ease: 'easeInOut' }}+ className="mt-2"+ >+ <FormMessage_Shadcn_+ className="mt-2 transition-opacity duration-300 ease-in-out"+ data-formlayout-id={'message'}+ />+ </motion.div>)const renderDescription =diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex a0459d68998..10cadfc35e8 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -56,6 +56,7 @@"common-tags": "^1.8.2","date-fns": "^2.30.0","formik": "^2.2.9",+ "framer-motion": "^11.0.3","highlightjs-curl": "^1.3.0","input-otp": "^1.2.3","lodash": "^4.17.21",diff --git a/packages/ui/src/components/StatusIcon.tsx b/packages/ui/src/components/StatusIcon.tsxindex 68f307c5dd3..d7dc7b9c656 100644--- a/packages/ui/src/components/StatusIcon.tsx+++ b/packages/ui/src/components/StatusIcon.tsx@@ -41,9 +41,9 @@ const InfoIcon: React.FC<SVGProps<SVGSVGElement> & StatusIconProps> = ({)}><path- fill-rule="evenodd"+ fillRule="evenodd"d="M15 8A7 7 0 1 1 1 8a7 7 0 0 1 14 0ZM9 5a1 1 0 1 1-2 0 1 1 0 0 1 2 0ZM6.75 8a.75.75 0 0 0 0 1.5h.75v1.75a.75.75 0 0 0 1.5 0v-2.5A.75.75 0 0 0 8.25 8h-1.5Z"- clip-rule="evenodd"+ clipRule="evenodd"/></svg>)diff --git a/packages/ui/src/components/radio-group-card.tsx b/packages/ui/src/components/radio-group-card.tsxindex f0928ccd43b..b064842ebe2 100644--- a/packages/ui/src/components/radio-group-card.tsx+++ b/packages/ui/src/components/radio-group-card.tsx@@ -31,17 +31,16 @@ const RadioGroupCardItem = React.forwardRef<className={cn('flex flex-col gap-2','w-48',- 'bg-overlay/50',+ 'bg-overlay','rounded-md','border','p-2',- 'shadow-sm',- 'hover:bg-surface-300',+ '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]:bg-surface-300',+ 'data-[state=checked]:bg-surface-200 dark:data-[state=checked]:bg-surface-300','data-[state=checked]:border-foreground-muted','transition-colors','group',diff --git a/packages/ui/src/components/shadcn/ui/chart.tsx b/packages/ui/src/components/shadcn/ui/chart.tsxindex f300d678f92..3959978584e 100644--- a/packages/ui/src/components/shadcn/ui/chart.tsx+++ b/packages/ui/src/components/shadcn/ui/chart.tsx@@ -1,3 +1,5 @@+'use client'+import * as React from 'react'import * as RechartsPrimitive from 'recharts'@@ -71,8 +73,9 @@ const ChartStyle = ({ id, config }: { id: string; config: ChartConfig }) => {return (<styledangerouslySetInnerHTML={{- __html: Object.entries(THEMES).map(- ([theme, prefix]) => `+ __html: Object.entries(THEMES)+ .map(+ ([theme, prefix]) => `${prefix} [data-chart=${id}] {${colorConfig.map(([key, itemConfig]) => {@@ -82,7 +85,8 @@ ${colorConfig.join('\n')}}`- ),+ )+ .join('\n'),}}/>)@@ -176,7 +180,7 @@ const ChartTooltipContent = React.forwardRef<indicator === 'dot' && 'items-center')}>- {formatter && item.value && item.name ? (+ {formatter && item?.value !== undefined && item.name ? (formatter(item.value, item.name, item, index, item.payload)) : (<>diff --git a/packages/ui/src/components/shadcn/ui/form.tsx b/packages/ui/src/components/shadcn/ui/form.tsxindex 8d534dfd9af..e480d454583 100644--- a/packages/ui/src/components/shadcn/ui/form.tsx+++ b/packages/ui/src/components/shadcn/ui/form.tsx@@ -15,6 +15,7 @@ import {import { cn } from '../../../lib/utils/cn'import { Label } from './label'+import { motion, AnimatePresence } from 'framer-motion'const Form = FormProvider@@ -150,21 +151,30 @@ const FormMessage = React.forwardRef<const { error, formMessageId } = useFormField()const body = error ? String(error?.message) : children- if (!body) {- return null- }-return (- <p- ref={ref}- id={formMessageId}- className={cn('text-sm text-destructive', className)}- {...props}- >- {body}- </p>+ <AnimatePresence initial={false}>+ {body ? ( // Only animate if there is a message body+ <motion.div+ key={formMessageId} // Use a unique key to help with animations+ initial={{ opacity: 0, y: -5, height: 0 }} // Start slightly hidden+ animate={{ opacity: 1, y: 0, height: 'auto' }} // Fade in and slide up+ exit={{ opacity: 0, y: -5, height: 0 }} // Fade out and slide back up+ transition={{ duration: 0.15, ease: 'easeInOut' }} // Smooth transition+ >+ <p+ ref={ref}+ id={formMessageId}+ className={cn('text-sm text-destructive', className)}+ {...props}+ >+ {body}+ </p>+ </motion.div>+ ) : null}+ </AnimatePresence>)})+FormMessage.displayName = 'FormMessage'export {diff --git a/packages/ui/src/components/shadcn/ui/select.tsx b/packages/ui/src/components/shadcn/ui/select.tsxindex db47bfe45f3..9ae5ea35d2d 100644--- a/packages/ui/src/components/shadcn/ui/select.tsx+++ b/packages/ui/src/components/shadcn/ui/select.tsx@@ -33,7 +33,8 @@ const SelectTrigger = React.forwardRef<<SelectPrimitive.Triggerref={ref}className={cn(- 'flex w-full items-center justify-between rounded-md border border-button bg-button text-xs ring-offset-background-control placeholder:text-foreground-muted focus:outline-none ring-border-control focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50',+ 'flex w-full items-center justify-between rounded-md border border-strong hover:border-stronger bg-alternative dark:bg-muted hover:bg-selection text-xs ring-offset-background-control placeholder:text-foreground-muted focus:outline-none ring-border-control focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 transition-all duration-200',+ 'data-[state=open]:bg-selection data-[state=open]:border-stronger',SelectTriggerVariants({ size }),className)}@@ -136,7 +137,7 @@ const SelectItem = React.forwardRef<ref={ref}className={cn('group',- 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-xs outline-none focus:bg-overlay-hover text-foreground-light focus:text-foreground data-[state=checked]:text-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',+ 'relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-overlay-hover text-foreground-light focus:text-foreground data-[state=checked]:text-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',className)}{...props}diff --git a/packages/ui/src/components/shadcn/ui/sheet.tsx b/packages/ui/src/components/shadcn/ui/sheet.tsxindex 9e00ec0cffb..41d0f1cb5e8 100644--- a/packages/ui/src/components/shadcn/ui/sheet.tsx+++ b/packages/ui/src/components/shadcn/ui/sheet.tsx@@ -177,7 +177,10 @@ const SheetContent = React.forwardRef<SheetContent.displayName = SheetPrimitive.Content.displayNameconst SheetHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (- <div className={cn('px-5 py-4 text-center sm:text-left border-b', className)} {...props} />+ <div+ className={cn('px-5 py-4 text-center sm:text-left border-b bg-dash-sidebar', className)}+ {...props}+ />)SheetHeader.displayName = 'SheetHeader'@@ -202,11 +205,7 @@ const SheetTitle = React.forwardRef<React.ElementRef<typeof SheetPrimitive.Title>,React.ComponentPropsWithoutRef<typeof SheetPrimitive.Title>>(({ className, ...props }, ref) => (- <SheetPrimitive.Title- ref={ref}- className={cn('text-base text-foreground', className)}- {...props}- />+ <SheetPrimitive.Title ref={ref} className={cn('text-lg text-foreground', className)} {...props} />))SheetTitle.displayName = SheetPrimitive.Title.displayName@@ -216,7 +215,7 @@ const SheetDescription = React.forwardRef<>(({ className, ...props }, ref) => (<SheetPrimitive.Descriptionref={ref}- className={cn('text-sm text-foreground-muted', className)}+ className={cn('text-sm text-foreground-light', className)}{...props}/>))