Skip to content

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

Update and refactor a couple for files to pre-emptively support new structure from /usage endpoint

Joshen Lim559742f44a44
diff --git a/studio/components/interfaces/Home/NewProjectPanel/NewProjectPanel.tsx b/studio/components/interfaces/Home/NewProjectPanel/NewProjectPanel.tsx
index 2bae2c671a6..0658a231e89 100644
--- a/studio/components/interfaces/Home/NewProjectPanel/NewProjectPanel.tsx
+++ b/studio/components/interfaces/Home/NewProjectPanel/NewProjectPanel.tsx
@@ -5,7 +5,7 @@ import GetStartedPanel from './GetStartedPanel'
interface Props {}
const NewProjectPanel: FC<Props> = ({}) => (
- <div className="grid grid-cols-12 gap-8 mx-6">
+ <div className="grid grid-cols-12 gap-8">
<div className="col-span-12">
<GetStartedPanel />
</div>
diff --git a/studio/components/interfaces/Home/ProjectUsage.tsx b/studio/components/interfaces/Home/ProjectUsage.tsx
index c7b4e7bb732..f6aab813b97 100644
--- a/studio/components/interfaces/Home/ProjectUsage.tsx
+++ b/studio/components/interfaces/Home/ProjectUsage.tsx
@@ -1,3 +1,8 @@
+import useSWR from 'swr'
+import dayjs from 'dayjs'
+import Link from 'next/link'
+import { FC, useState } from 'react'
+import { useRouter } from 'next/router'
import {
Button,
Dropdown,
@@ -8,20 +13,16 @@ import {
IconZap,
Typography,
} from '@supabase/ui'
-import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
-import Panel from 'components/ui/Panel'
-import Table from 'components/to-be-cleaned/Table'
-import { USAGE_COLORS } from 'components/ui/Charts/Charts.constants'
-import StackedAreaChart from 'components/ui/Charts/StackedAreaChart'
-import dayjs from 'dayjs'
+
+import { ChartIntervals } from 'types'
import { useFlag } from 'hooks'
import { get } from 'lib/common/fetch'
import { API_URL, DATE_FORMAT, METRICS } from 'lib/constants'
-import Link from 'next/link'
-import { useRouter } from 'next/router'
-import { FC, useState } from 'react'
-import useSWR from 'swr'
-import { ChartIntervals } from 'types'
+import Panel from 'components/ui/Panel'
+import { USAGE_COLORS } from 'components/ui/Charts/Charts.constants'
+import StackedAreaChart from 'components/ui/Charts/StackedAreaChart'
+import Table from 'components/to-be-cleaned/Table'
+import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
import { EndpointResponse, PathsDatum, StatusCodesDatum } from './ChartData.types'
const CHART_INTERVALS: ChartIntervals[] = [
@@ -35,16 +36,15 @@ const CHART_INTERVALS: ChartIntervals[] = [
{ key: 'hourly', label: '24 hours', startValue: 24, startUnit: 'hour', format: 'MMM D, ha' },
{ key: 'daily', label: '7 days', startValue: 7, startUnit: 'day', format: 'MMM D' },
]
-interface Props {
- project: any
-}
+interface Props {}
-const ProjectUsage: FC<Props> = ({ project }) => {
- const logsUsageCodesPaths = useFlag('logsUsageCodesPaths')
- const [interval, setInterval] = useState<string>('hourly')
+const ProjectUsage: FC<Props> = () => {
const router = useRouter()
const { ref } = router.query
+ const logsUsageCodesPaths = useFlag('logsUsageCodesPaths')
+ const [interval, setInterval] = useState<string>('hourly')
+
const { data, error }: any = useSWR(
`${API_URL}/projects/${ref}/log-stats?interval=${interval}`,
get
diff --git a/studio/components/interfaces/Home/ProjectUsageSection.tsx b/studio/components/interfaces/Home/ProjectUsageSection.tsx
index 4561dd7c3be..0db6bf8c8a1 100644
--- a/studio/components/interfaces/Home/ProjectUsageSection.tsx
+++ b/studio/components/interfaces/Home/ProjectUsageSection.tsx
@@ -1,37 +1,51 @@
-import useSWR from 'swr'
import { FC } from 'react'
+import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
-import { Typography, IconLoader } from '@supabase/ui'
-import { get } from 'lib/common/fetch'
-import { API_URL } from 'lib/constants'
-import { useStore } from 'hooks'
+import { IconLoader, IconAlertCircle } from '@supabase/ui'
+
+import { useProjectUsage } from 'hooks'
import { ProjectUsage, NewProjectPanel } from 'components/interfaces/Home'
+import InformationBox from 'components/ui/InformationBox'
const ProjectUsageSection: FC = observer(({}) => {
- const { ui } = useStore()
- const project = ui.selectedProject
- const { data: usage, error: usageError }: any = useSWR(
- `${API_URL}/projects/${project?.ref}/usage`,
- get
- )
+ const router = useRouter()
+ const { ref } = router.query
+ const { usage, error: usageError, isLoading } = useProjectUsage(ref as string)
+
+ // [Joshen TODO] After API is ready need to update to include dbEgress, storageEgress
+ // And also to highlight in this chart which components are "approaching" and "over"
+ const mockUsage: any = {
+ dbSize: { usage: 20773283, limit: 524288000 },
+ dbEgress: { usage: 400000000, limit: 524288000 },
+ storageSize: { usage: 624288000, limit: 524288000 },
+ storageEgress: { usage: 2048, limit: 524288000 },
+ }
+
const hasProjectData =
usage && (usage?.bucketSize || (usage?.authUsers ?? '0') !== '0' || usage?.dbTables)
? true
: false
if (usageError) {
- return <Typography.Text type="danger">Error loading data {usageError.message}</Typography.Text>
+ return (
+ <InformationBox
+ hideCollapse
+ defaultVisibility
+ icon={<IconAlertCircle strokeWidth={2} />}
+ title="There was an issue loading the usage details of your project"
+ />
+ )
}
return (
<>
- {usage === undefined ? (
+ {isLoading ? (
<div className="w-full flex justify-center items-center space-x-2">
<IconLoader className="animate-spin" size={14} />
<p className="text-sm">Retrieving project usage statistics</p>
</div>
) : !usage.error && hasProjectData ? (
- <ProjectUsage project={project} />
+ <ProjectUsage />
) : (
<NewProjectPanel />
)}
diff --git a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.constants.tsx b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.constants.tsx
index 700a4a03a56..3d2fdbbe353 100644
--- a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.constants.tsx
+++ b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.constants.tsx
@@ -1,128 +1,20 @@
import { IconArchive, IconDatabase } from '@supabase/ui'
-import SparkBar from 'components/ui/SparkBar'
-import { UsageStats } from './ProjectUsageBars.types'
-// [Joshen TODO] These figures are technically wrong, GB and MB are in multiple increments of 1024
-const GB = 1000000000
-const MB = 1000000
-
-export const usageLimits = {
- database: {
+export const usageBasedItems = [
+ {
title: 'Database',
icon: <IconDatabase className="dark:text-scale-100" size={16} strokeWidth={2} />,
features: [
- {
- title: 'API requests',
- tiers: {
- free: {
- description: () => 'Unlimited',
- render: null,
- },
- pro: {
- description: () => 'Unlimited',
- render: null,
- },
- },
- },
- {
- title: 'Database space',
- tiers: {
- free: {
- description: (stats: UsageStats) =>
- `${((stats.dbSize / (500 * MB)) * 100).toFixed(2)} %`,
- render: (stats: UsageStats) => {
- const bytes: number = stats.dbSize
- const usage = {
- gb: bytes / GB,
- mb: bytes / MB,
- }
- return (
- <SparkBar
- value={usage.mb}
- max={500}
- type={'horizontal'}
- barClass={'bg-brand-900'}
- labelBottom={`${usage.mb.toFixed(2).toLocaleString()} MB`}
- labelTop={`500 MB`}
- />
- )
- },
- },
- pro: {
- description: (stats: UsageStats) =>
- `${((stats.dbSize / (8000 * MB)) * 100).toFixed(2)} %`,
- render: (stats: UsageStats) => {
- const bytes: number = stats.dbSize
- const usage = {
- gb: bytes / GB,
- mb: bytes / MB,
- }
- return (
- <SparkBar
- value={usage.mb}
- max={8000}
- type={'horizontal'}
- barClass={'bg-brand-900'}
- labelBottom={`${usage.mb.toFixed(2).toLocaleString()} MB`}
- labelTop={`8 GB`}
- />
- )
- },
- },
- },
- },
+ { key: 'dbSize', title: 'Database space' },
+ { key: 'dbEgress', title: 'Database egress' },
],
},
- storage: {
- title: 'File storage',
+ {
+ title: 'Storage',
icon: <IconArchive className="dark:text-scale-100" size={16} strokeWidth={2} />,
features: [
- {
- title: 'Storage space',
- tiers: {
- free: {
- description: (stats: UsageStats) =>
- `${((stats.bucketSize / (1 * GB)) * 100).toFixed(2)}%`,
- render: (stats: UsageStats) => (
- <SparkBar
- value={stats.bucketSize / (1024 * 1024) || 0}
- max={1 * 1024}
- type={'horizontal'}
- barClass={'bg-brand-900'}
- labelBottom={`${(stats.bucketSize / (1024 * 1024)).toLocaleString()} MB`}
- labelTop={`${(1 * 1024).toLocaleString()} MB`}
- />
- ),
- },
- pro: {
- description: (stats: UsageStats) =>
- `${((stats.bucketSize / (100 * GB)) * 100).toFixed(2)}%`,
- render: (stats: UsageStats) => (
- <SparkBar
- value={stats.bucketSize / (1024 * 1024) || 0}
- max={100 * 1024}
- type={'horizontal'}
- barClass={'bg-brand-900'}
- labelBottom={`${(stats.bucketSize / (1024 * 1024)).toLocaleString()} MB`}
- labelTop={`${Number(100).toLocaleString()} GB`}
- />
- ),
- },
- },
- },
- {
- title: 'Transfer limits',
- tiers: {
- free: {
- description: () => `${Number(2).toLocaleString()} GB`,
- render: () => {},
- },
- pro: {
- description: () => `${Number(200).toLocaleString()} GB`,
- render: () => {},
- },
- },
- },
+ { key: 'storageSize', title: 'Storage space' },
+ { key: 'storageEgress', title: 'Storage egress' },
],
},
-}
+]
diff --git a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx
index 6ee02cbf860..c753c3e688e 100644
--- a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx
+++ b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.tsx
@@ -1,13 +1,12 @@
-import useSWR from 'swr'
-import React, { FC, useEffect } from 'react'
-import { Loading, Typography } from '@supabase/ui'
+import { FC, useEffect } from 'react'
+import { Badge, Loading } from '@supabase/ui'
-import { useProjectSubscription, useStore } from 'hooks'
-import { API_URL, PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
-import { get } from 'lib/common/fetch'
+import { useStore, useProjectUsage } from 'hooks'
+import { formatBytes } from 'lib/helpers'
+import { USAGE_APPROACHING_THRESHOLD } from 'lib/constants'
+import SparkBar from 'components/ui/SparkBar'
import ShimmeringLoader from 'components/ui/ShimmeringLoader'
-import { usageLimits } from './ProjectUsageBars.constants'
-import { UsageStats, ApiUsageStats } from './ProjectUsageBars.types'
+import { usageBasedItems } from './ProjectUsageBars.constants'
interface Props {
projectRef?: string
@@ -15,14 +14,14 @@ interface Props {
const ProjectUsage: FC<Props> = ({ projectRef }) => {
const { ui } = useStore()
- const { data: stats, error: usageError } = useSWR(`${API_URL}/projects/${projectRef}/usage`, get)
- const { subscription, isLoading: loading, error } = useProjectSubscription(projectRef)
+ const { usage, error, isLoading } = useProjectUsage(projectRef)
+ console.log(usage)
useEffect(() => {
if (error) {
ui.setNotification({
category: 'error',
- message: `Failed to get project subscription: ${error?.message ?? 'unknown'}`,
+ message: `Failed to get project's usage data: ${error?.message ?? 'unknown'}`,
})
}
}, [error])
@@ -30,132 +29,109 @@ const ProjectUsage: FC<Props> = ({ projectRef }) => {
// [Joshen TODO] After API is ready need to update to include dbEgress, storageEgress
// And also to highlight in this chart which components are "approaching" and "over"
const mockUsage: any = {
- dbSize: { value: 10773283, limit: 524288000 },
- dbEgress: { value: 400000000, limit: 524288000 },
- storageSize: { value: 624288000, limit: 524288000 },
- storageEgress: { value: 0, limit: 524288000 },
+ dbSize: { usage: 20773283, limit: 524288000 },
+ dbEgress: { usage: 400000000, limit: 524288000 },
+ storageSize: { usage: 624288000, limit: 524288000 },
+ storageEgress: { usage: 2048, limit: 524288000 },
}
- // We can try to do up some simple UI logic now while waiting for API
-
- const tier =
- subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PRO ? 'pro' : 'free'
return (
- <Loading active={loading}>
- <div className="">
- {Object.values(usageLimits).map((product) => (
- <div
- className="border-panel-border-light dark:border-panel-border-dark mb-8 overflow-hidden rounded border"
- key={product.title}
- >
- <table className="bg-panel-body-light dark:bg-panel-body-dark w-full">
- <thead className="bg-panel-header-light dark:bg-panel-header-dark">
- <tr className="overflow-hidden rounded">
- <th className="w-1/4 px-6 py-3 text-left">
- <div className="flex items-center space-x-3">
- <div className="flex h-8 w-8 items-center justify-center rounded bg-scale-500 dark:bg-white">
- {product.icon}
+ <Loading active={isLoading}>
+ <div>
+ {usageBasedItems.map((product) => {
+ const isExceededUsage = product.features
+ .map((feature) => {
+ const featureUsage = mockUsage[feature.key]
+ return featureUsage.usage / featureUsage.limit > 1
+ })
+ .some((x) => x === true)
+ return (
+ <div
+ key={product.title}
+ className={[
+ 'mb-8 overflow-hidden rounded border',
+ 'border-panel-border-light dark:border-panel-border-dark',
+ ].join(' ')}
+ >
+ <table className="bg-panel-body-light dark:bg-panel-body-dark w-full">
+ {/* Header */}
+ <thead className="bg-panel-header-light dark:bg-panel-header-dark">
+ <tr className="overflow-hidden rounded">
+ <th className="w-1/4 px-6 py-3 text-left">
+ <div className="flex items-center space-x-4">
+ <div
+ className={[
+ 'flex h-8 w-8 items-center justify-center',
+ 'rounded bg-scale-500 dark:bg-white',
+ ].join(' ')}
+ >
+ {product.icon}
+ </div>
+ <h5 className="mb-0">{product.title}</h5>
</div>
- <Typography.Title level={5} className="mb-0">
- {product.title}
- </Typography.Title>
- </div>
- </th>
- <th className="hidden p-3 text-left text-xs font-medium leading-4 text-gray-400 lg:table-cell">
+ </th>
{/* Plan Limits */}
- </th>
- <th className="p-3 text-left text-xs font-medium leading-4 text-gray-400">
+ <th className="hidden p-3 text-left text-xs font-medium leading-4 text-gray-400 lg:table-cell">
+ {isExceededUsage && <Badge color="red">Exceeded usage</Badge>}
+ </th>
{/* Usage */}
- </th>
- </tr>
- </thead>
+ <th className="p-3 text-left text-xs font-medium leading-4 text-gray-400" />
+ </tr>
+ </thead>
+
+ {/* Line items */}
+ {usage === undefined ? (
+ <div className="w-96 px-4 pt-1 pb-4">
+ <ShimmeringLoader />
+ </div>
+ ) : (
+ <tbody>
+ {product.features.map((feature) => {
+ // [Joshen TODO] Update to use actual usage endpoint
+ const featureUsage = mockUsage[feature.key]
+ const usageRatio = featureUsage.usage / featureUsage.limit
+ const isApproaching = usageRatio >= USAGE_APPROACHING_THRESHOLD
+ const isExceeded = usageRatio >= 1
- {stats === undefined ? (
- <div className="w-96 px-4 pt-1 pb-4">
- <ShimmeringLoader />
- </div>
- ) : (
- <tbody className="">
- {product.features.map((feature) => {
- return (
- <tr
- className="border-panel-border-light dark:border-panel-border-dark border-t"
- key={feature.title}
- >
- <td className="text-typography-body-light dark:text-typography-body-dark whitespace-nowrap px-6 py-3 text-sm">
- {feature.title}
- </td>
- <td className="text-typography-body-light dark:text-typography-body-dark hidden w-1/5 whitespace-nowrap p-3 text-sm lg:table-cell">
- {feature.tiers[tier]?.description(stats)}
- </td>
- <td className="text-typography-body-light dark:text-typography-body-dark px-6 py-3 text-sm ">
- {/* @ts-ignore */}
- {feature.tiers[tier]?.render ? feature.tiers[tier].render(stats) : null}
- </td>
- </tr>
- )
- })}
- </tbody>
- )}
- </table>
- </div>
- ))}
+ return (
+ <tr
+ key={feature.title}
+ className="border-panel-border-light dark:border-panel-border-dark border-t"
+ >
+ <td className="whitespace-nowrap px-6 py-3 text-sm text-scale-1200">
+ {feature.title}
+ </td>
+ <td className="w-1/5 whitespace-nowrap p-3 text-sm lg:table-cell hidden text-scale-1200">
+ {(usageRatio * 100).toFixed(2)} %
+ </td>
+ <td className="px-6 py-3 text-sm text-scale-1200">
+ <SparkBar
+ type="horizontal"
+ barClass={`${
+ isExceeded
+ ? 'bg-red-900'
+ : isApproaching
+ ? 'bg-yellow-900'
+ : 'bg-brand-900'
+ }`}
+ value={featureUsage.usage}
+ max={featureUsage.limit}
+ labelBottom={formatBytes(featureUsage.usage)}
+ labelTop={formatBytes(featureUsage.limit)}
+ />
+ </td>
+ </tr>
+ )
+ })}
+ </tbody>
+ )}
+ </table>
+ </div>
+ )
+ })}
</div>
</Loading>
)
}
export default ProjectUsage
-
-interface ProjectUsageMinimalProps extends Props {
- filter: string
-}
-
-export const ProjectUsageMinimal: FC<ProjectUsageMinimalProps> = ({ projectRef, filter }) => {
- const { data: apiStats, error: usageError } = useSWR<ApiUsageStats>(
- `${API_URL}/projects/${projectRef}/usage`,
- get
- )
- const { subscription, isLoading: loading, error } = useProjectSubscription(projectRef)
- const stats: UsageStats = {
- authUsers: Number(apiStats?.authUsers),
- bucketSize: Number(apiStats?.bucketSize),
- dbSize: Number(apiStats?.dbSize),
- dbTables: Number(apiStats?.dbTables),
- }
-
- if (subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PAYG) {
- return <></>
- }
-
- const tier =
- subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PRO ? 'pro' : 'free'
-
- return (
- <Loading active={loading}>
- <div className="space-y-4">
- {Object.values(usageLimits)
- .filter((product) => product.title === filter)
- .map((product) => {
- return (
- <div key={product.title}>
- {product.features.map((feature) => {
- return (
- <div key={feature.title}>
- {feature.tiers[tier]?.render && feature.title !== 'Transfer limits' ? (
- <h5 className="text-scale-900 text-sm">{feature.title}</h5>
- ) : null}
- <div className="text-typography-body-light dark:text-typography-body-dark text-sm">
- {/* @ts-ignore */}
- {feature.tiers[tier]?.render ? feature.tiers[tier].render(stats) : null}
- </div>
- </div>
- )
- })}
- </div>
- )
- })}
- </div>
- </Loading>
- )
-}
diff --git a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.types.ts b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.types.ts
index 674423c6d9d..bbc49f797ed 100644
--- a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.types.ts
+++ b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars.types.ts
@@ -5,6 +5,18 @@ export interface UsageStats {
dbTables: number
}
+export interface ResourceUsage {
+ usage: number
+ limit: number
+}
+
+export interface UsageStatsUpdated {
+ dbSize: ResourceUsage
+ dbEgress: ResourceUsage
+ storageSize: ResourceUsage
+ storageEgress: ResourceUsage
+}
+
export interface ApiUsageStats {
authUsers: string | null
bucketSize: string | null
diff --git a/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageMinimal.tsx b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageMinimal.tsx
new file mode 100644
index 00000000000..1ed12b0aa2e
--- /dev/null
+++ b/studio/components/interfaces/Settings/ProjectUsageBars/ProjectUsageMinimal.tsx
@@ -0,0 +1,78 @@
+import { FC } from 'react'
+import { Loading } from '@supabase/ui'
+
+import { useProjectSubscription, useProjectUsage } from 'hooks'
+import { formatBytes } from 'lib/helpers'
+import { PRICING_TIER_PRODUCT_IDS, USAGE_APPROACHING_THRESHOLD } from 'lib/constants'
+import SparkBar from 'components/ui/SparkBar'
+import { usageBasedItems } from './ProjectUsageBars.constants'
+import { UsageStats } from './ProjectUsageBars.types'
+
+interface ProjectUsageMinimalProps {
+ projectRef?: string
+ filter: string
+}
+
+// [Joshen TODO] Need to update to use the newer usageBasedItems from constants
+const ProjectUsageMinimal: FC<ProjectUsageMinimalProps> = ({ projectRef, filter }) => {
+ const { usage, error: usageError, isLoading } = useProjectUsage(projectRef)
+ const { subscription, error } = useProjectSubscription(projectRef)
+
+ const stats: UsageStats = {
+ authUsers: Number(usage?.authUsers),
+ bucketSize: Number(usage?.bucketSize),
+ dbSize: Number(usage?.dbSize),
+ dbTables: Number(usage?.dbTables),
+ }
+
+ // [Joshen TODO] After API is ready need to update to include dbEgress, storageEgress
+ // And also to highlight in this chart which components are "approaching" and "over"
+ const mockUsage: any = {
+ dbSize: { usage: 20773283, limit: 524288000 },
+ dbEgress: { usage: 400000000, limit: 524288000 },
+ storageSize: { usage: 624288000, limit: 524288000 },
+ storageEgress: { usage: 2048, limit: 524288000 },
+ }
+
+ if (subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PAYG) {
+ return <></>
+ }
+
+ const tier =
+ subscription?.tier?.supabase_prod_id === PRICING_TIER_PRODUCT_IDS.PRO ? 'pro' : 'free'
+
+ const product = usageBasedItems.find((item) => item.title === filter)
+ if (!product) return <></>
+
+ return (
+ <Loading active={isLoading}>
+ <div className="space-y-4">
+ {product.features.map((feature) => {
+ // [Joshen TODO] Update to use actual usage endpoint
+ const featureUsage = mockUsage[feature.key]
+ const usageRatio = featureUsage.usage / featureUsage.limit
+ const isApproaching = usageRatio >= USAGE_APPROACHING_THRESHOLD
+ const isExceeded = usageRatio >= 1
+
+ return (
+ <div key={feature.key} className="space-y-1">
+ <h5 className="text-scale-1200 text-sm">{feature.title}</h5>
+ <SparkBar
+ type="horizontal"
+ barClass={`${
+ isExceeded ? 'bg-red-900' : isApproaching ? 'bg-yellow-900' : 'bg-brand-900'
+ }`}
+ value={featureUsage.usage}
+ max={featureUsage.limit}
+ labelBottom={formatBytes(featureUsage.usage)}
+ labelTop={formatBytes(featureUsage.limit)}
+ />
+ </div>
+ )
+ })}
+ </div>
+ </Loading>
+ )
+}
+
+export default ProjectUsageMinimal
diff --git a/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx b/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
index 4cad2143457..8fc8aba68a5 100644
--- a/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
+++ b/studio/components/layouts/ProjectLayout/LayoutHeader/LayoutHeader.tsx
@@ -3,7 +3,7 @@ import { observer } from 'mobx-react-lite'
import { useRouter } from 'next/router'
import { IS_PLATFORM } from 'lib/constants'
-import { useStore, useProjectUsageStatus } from 'hooks'
+import { useStore, useProjectUsage } from 'hooks'
import BreadcrumbsView from './BreadcrumbsView'
import OrgDropdown from './OrgDropdown'
import ProjectDropdown from './ProjectDropdown'
@@ -23,10 +23,10 @@ const LayoutHeader = ({ customHeaderComponents, breadcrumbs = [], headerBorder =
// [Joshen TODO] After API is ready, to do up proper logic here
const usage: any = {
- dbSize: { value: 10773283, limit: 524288000 },
- dbEgress: { value: 400000000, limit: 524288000 },
- storageSize: { value: 624288000, limit: 524288000 },
- storageEgress: { value: 0, limit: 524288000 },
+ dbSize: { usage: 10773283, limit: 524288000 },
+ dbEgress: { usage: 400000000, limit: 524288000 },
+ storageSize: { usage: 624288000, limit: 524288000 },
+ storageEgress: { usage: 0, limit: 524288000 },
}
const resourcesExceededLimits = getResourcesExceededLimits(usage)
const isOverUsageLimits = resourcesExceededLimits.length > 0
diff --git a/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx b/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx
index c6c15220be8..cc3546f9060 100644
--- a/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx
+++ b/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx
@@ -1,4 +1,5 @@
-import { IconBarChart2, Loading } from '@supabase/ui'
+import dayjs from 'dayjs'
+import { Loading } from '@supabase/ui'
import { useState } from 'react'
import {
BarChart as RechartBarChart,
@@ -8,13 +9,12 @@ import {
XAxis,
YAxis,
Tooltip,
- ReferenceLine,
Cell,
ResponsiveContainer,
} from 'recharts'
-import dayjs from 'dayjs'
import { formatBytes } from 'lib/helpers'
+import EmptyState from 'components/ui/Charts/EmptyState'
import { CHART_COLORS } from 'components/ui/Charts/Charts.constants'
function dataCheck(data: any, attribute: any) {
@@ -127,37 +127,6 @@ const Header = ({
)
}
-const NoData = ({ title = 'No data to show', message = 'May take 24 hours for data to show' }) => (
- <div
- className="
- border-scale-600 flex
- h-full w-full flex-col
- items-center justify-center space-y-2 border
- border-dashed text-center
- "
- >
- <IconBarChart2 className="text-scale-800" />
- <div>
- <p className="text-scale-1100 text-xs">{title}</p>
- <p className="text-scale-900 text-xs">{message}</p>
- </div>
- </div>
-)
-const total = (data: any, format: any, attribute: any) => {
- let total = 0
- data?.map((item: any) => {
- total = total + Number(item[attribute])
- })
- if (format === '%') {
- return Number(total).toFixed(2)
- }
- return numberWithCommas(total)
-}
-
-function numberWithCommas(x: any) {
- return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
-}
-
export function BarChart({
data,
attribute,
@@ -293,7 +262,7 @@ export function BarChart({
)}
</>
) : (
- <NoData title={noDataTitle} message={noDataMessage} />
+ <EmptyState title={noDataTitle} message={noDataMessage} />
)}
</div>
</div>
@@ -415,7 +384,7 @@ export function AreaChart({
)}
</>
) : (
- <NoData />
+ <EmptyState />
)}
</div>
</Loading>
diff --git a/studio/components/ui/Charts/EmptyState.tsx b/studio/components/ui/Charts/EmptyState.tsx
index e329be770f7..582703dea27 100644
--- a/studio/components/ui/Charts/EmptyState.tsx
+++ b/studio/components/ui/Charts/EmptyState.tsx
@@ -1,20 +1,28 @@
import { FC } from 'react'
-import { Typography, IconBarChart2 } from '@supabase/ui'
+import { IconBarChart2 } from '@supabase/ui'
-interface Props {}
+interface Props {
+ title?: string
+ message?: string
+}
-const EmptyState: FC<Props> = () => (
+const EmptyState: FC<Props> = ({
+ title = 'No data to show',
+ message = 'May take 24 hours for data to show',
+}) => (
<div
className="
- h-full w-full py-4
- border border-dashed dark:border-dark
- flex flex-col items-center justify-center
+ border-scale-600 flex
+ h-full w-full flex-col
+ items-center justify-center space-y-2 border
+ border-dashed text-center py-4 space-y-2
"
>
- <Typography.Text className="mb-2">
- <IconBarChart2 />
- </Typography.Text>
- <Typography.Text>No data to show</Typography.Text>
+ <IconBarChart2 className="text-scale-1100" />
+ <div>
+ <p className="text-xs text-scale-1100">{title}</p>
+ <p className="text-xs text-scale-1000">{message}</p>
+ </div>
</div>
)
diff --git a/studio/components/ui/OveragesBanner/OveragesBanner.tsx b/studio/components/ui/OveragesBanner/OveragesBanner.tsx
index 194b9410cb5..da7deb0f3b8 100644
--- a/studio/components/ui/OveragesBanner/OveragesBanner.tsx
+++ b/studio/components/ui/OveragesBanner/OveragesBanner.tsx
@@ -2,7 +2,7 @@ import Link from 'next/link'
import { FC } from 'react'
import { Alert, Button } from '@supabase/ui'
-import { useStore, useProjectUsageStatus } from 'hooks'
+import { useStore, useProjectUsage } from 'hooks'
import { PRICING_TIER_PRODUCT_IDS } from 'lib/constants'
import { getResourcesApproachingLimits, getResourcesExceededLimits } from './OveragesBanner.utils'
@@ -17,11 +17,11 @@ const OveragesBanner: FC<Props> = ({ tier, minimal }) => {
// [Joshen TODO] After API is ready, to do up proper logic here
// const { usageStatus } = useProjectUsageStatus(ui.selectedProject?.ref)
- const usage: any = {
- dbSize: { value: 10773283, limit: 524288000 },
- dbEgress: { value: 400000000, limit: 524288000 },
- storageSize: { value: 624288000, limit: 524288000 },
- storageEgress: { value: 0, limit: 524288000 },
+ const usage = {
+ dbSize: { usage: 10773283, limit: 524288000 },
+ dbEgress: { usage: 400000000, limit: 524288000 },
+ storageSize: { usage: 624288000, limit: 524288000 },
+ storageEgress: { usage: 0, limit: 524288000 },
}
const resourcesApproachingLimits = getResourcesApproachingLimits(usage)
@@ -47,40 +47,13 @@ const OveragesBanner: FC<Props> = ({ tier, minimal }) => {
: ''
const minimalDescription =
- tier === PRICING_TIER_PRODUCT_IDS.FREE ? (
- <>
- You can check your project's usage details or upgrade to the pro tier{' '}
- <Link href={`/project/${ref}/settings/billing`}>
- <a>
- <span className="cursor-pointer underline">here</span>
- </a>
- </Link>{' '}
- to support the growth of your project.
- </>
- ) : tier === PRICING_TIER_PRODUCT_IDS.PRO ? (
- <>
- You can check your project's usage details or consider disabling spend cap{' '}
- <Link href={`/project/${ref}/settings/billing`}>
- <a>
- <span className="cursor-pointer underline">here</span>
- </a>
- </Link>{' '}
- to support the growth of your project.
- </>
- ) : tier === PRICING_TIER_PRODUCT_IDS.PAYG ? (
- <>
- As you have disabled spend cap, additional resources will be charged on a per-usage basis.
- You can check your project's usage details{' '}
- <Link href={`/project/${ref}/settings/billing`}>
- <a>
- <span className="cursor-pointer underline">here</span>
- </a>
- </Link>{' '}
- for more information.
- </>
- ) : (
- ''
- )
+ tier === PRICING_TIER_PRODUCT_IDS.FREE
+ ? "You can check your project's usage details or upgrade to the pro tier to support the growth of your project."
+ : tier === PRICING_TIER_PRODUCT_IDS.PRO
+ ? "You can check your project's usage details or consider disabling spend cap to support the growth of your project."
+ : tier === PRICING_TIER_PRODUCT_IDS.PAYG
+ ? "As you have disabled spend cap, additional resources will be charged on a per-usage basis. You can check your project's usage details for more information."
+ : ''
const description =
tier === PRICING_TIER_PRODUCT_IDS.FREE
@@ -114,7 +87,11 @@ const OveragesBanner: FC<Props> = ({ tier, minimal }) => {
actions={
minimal ? (
<div className="h-full flex items-center">
- <Button type="default">Explore usage details</Button>
+ <Link href={`/project/${ref}/settings/billing`}>
+ <a>
+ <Button type="default">Explore usage details</Button>
+ </a>
+ </Link>
</div>
) : (
<></>
diff --git a/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts b/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts
index 71489c99995..de63d9965d0 100644
--- a/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts
+++ b/studio/components/ui/OveragesBanner/OveragesBanner.utils.ts
@@ -1,20 +1,20 @@
import { compact } from 'lodash'
import { USAGE_APPROACHING_THRESHOLD } from 'lib/constants'
-export const getResourcesApproachingLimits = (usage: any) => {
+export const getResourcesApproachingLimits = (usages: any) => {
return compact(
- Object.keys(usage).map((resourceName) => {
- const resource = usage[resourceName]
- if (resource.value / resource.limit >= USAGE_APPROACHING_THRESHOLD) return resourceName
+ Object.keys(usages).map((resourceName) => {
+ const resource = usages[resourceName]
+ if (resource.usage / resource.limit >= USAGE_APPROACHING_THRESHOLD) return resourceName
})
)
}
-export const getResourcesExceededLimits = (usage: any) => {
+export const getResourcesExceededLimits = (usages: any) => {
return compact(
- Object.keys(usage).map((resourceName) => {
- const resource = usage[resourceName]
- if (resource.value / resource.limit >= 1) return resourceName
+ Object.keys(usages).map((resourceName) => {
+ const resource = usages[resourceName]
+ if (resource.usage / resource.limit >= 1) return resourceName
})
)
}
diff --git a/studio/components/ui/SparkBar.tsx b/studio/components/ui/SparkBar.tsx
index 27cdb882dd3..d2385ef3dfe 100644
--- a/studio/components/ui/SparkBar.tsx
+++ b/studio/components/ui/SparkBar.tsx
@@ -21,17 +21,17 @@ const SparkBar: FC<Props> = ({
labelBottom = '',
labelTop = '',
}) => {
- if (type == 'horizontal') {
- let width = Number((value / max) * 100)
- if (width < 3) width = 3
- let widthCss = `${width}%`
+ if (type === 'horizontal') {
+ const width = Number((value / max) * 100)
+ const widthCss = `${width}%`
const hasLabels = labelBottom || labelTop
+
return (
<div className="flex flex-col w-full">
{hasLabels && (
<div className="flex align-baseline justify-between pb-1 space-x-8">
- <span className="text-scale-1200 text-base truncate">{labelBottom}</span>
- <span className="text-scale-900 text-sm tabular-nums">{labelTop}</span>
+ <span className="text-scale-1200 text-sm truncate">{labelBottom}</span>
+ <span className="text-scale-1100 text-sm tabular-nums">{labelTop}</span>
</div>
)}
<div
@@ -50,6 +50,7 @@ const SparkBar: FC<Props> = ({
const totalHeight = 35
let height = Number((value / max) * totalHeight)
if (height < 2) height = 2
+
return (
<div
className={`relative rounded w-5 overflow-hidden border p-1 ${
diff --git a/studio/hooks/queries/index.ts b/studio/hooks/queries/index.ts
index 538ce64e6fb..7217a4941f7 100644
--- a/studio/hooks/queries/index.ts
+++ b/studio/hooks/queries/index.ts
@@ -8,4 +8,4 @@ export * from './useProjectPaygStatistics'
export * from './useProjectSettings'
export * from './useProjectSubscription'
export * from './useSubscriptionStats'
-export * from './useProjectUsageStatus'
+export * from './useProjectUsage'
diff --git a/studio/hooks/queries/usePermissions.ts b/studio/hooks/queries/usePermissions.ts
index 878ac75db11..7d4307a10e5 100644
--- a/studio/hooks/queries/usePermissions.ts
+++ b/studio/hooks/queries/usePermissions.ts
@@ -4,7 +4,6 @@ import jsonLogic from 'json-logic-js'
import { useFlag, useStore } from 'hooks'
import { get } from 'lib/common/fetch'
import { API_URL, IS_PLATFORM } from 'lib/constants'
-import { toJS } from 'mobx'
export function usePermissions(returning?: 'minimal') {
let url = `${API_URL}/profile/permissions`
diff --git a/studio/hooks/queries/useProjectUsageStatus.ts b/studio/hooks/queries/useProjectUsage.ts
similarity index 66%
rename from studio/hooks/queries/useProjectUsageStatus.ts
rename to studio/hooks/queries/useProjectUsage.ts
index 13a902e41fd..89e07df0687 100644
--- a/studio/hooks/queries/useProjectUsageStatus.ts
+++ b/studio/hooks/queries/useProjectUsage.ts
@@ -2,13 +2,13 @@ import useSWR from 'swr'
import { get } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
-export function useProjectUsageStatus(ref?: string) {
- const url = `${API_URL}/projects/${ref}/usage-status`
+export function useProjectUsage(ref?: string) {
+ const url = `${API_URL}/projects/${ref}/usage`
const { data, error } = useSWR<any>(ref ? url : null, get)
const anyError = data?.error || error
return {
- usageStatus: anyError ? undefined : data,
+ usage: anyError ? undefined : data,
error: anyError,
isLoading: !anyError && !data,
isError: !!anyError,
diff --git a/studio/lib/helpers.ts b/studio/lib/helpers.ts
index 74fd00df8a9..a9a3002168f 100644
--- a/studio/lib/helpers.ts
+++ b/studio/lib/helpers.ts
@@ -139,7 +139,7 @@ export const propsAreEqual = (prevProps: any, nextProps: any) => {
export const formatBytes = (bytes: any, decimals = 2) => {
if (bytes === 0 || bytes === undefined) return '0 bytes'
- const k = 1000
+ const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
diff --git a/studio/pages/project/[ref]/index.tsx b/studio/pages/project/[ref]/index.tsx
index 8faa6f3e66f..2c45cdf10d1 100644
--- a/studio/pages/project/[ref]/index.tsx
+++ b/studio/pages/project/[ref]/index.tsx
@@ -1,7 +1,7 @@
import { observer } from 'mobx-react-lite'
import { Typography } from '@supabase/ui'
-import { useStore, useProjectUsageStatus } from 'hooks'
+import { useStore } from 'hooks'
import { NextPageWithLayout } from 'types'
import { IS_PLATFORM, PROJECT_STATUS } from 'lib/constants'
import { ProjectLayoutWithAuth } from 'components/layouts'
@@ -28,13 +28,15 @@ const Home: NextPageWithLayout = () => {
<h1 className="text-3xl">{projectName}</h1>
</div>
- <div className="mx-6 space-y-2">
+ <div className="mx-6">
{projectTier !== undefined && <OveragesBanner minimal tier={projectTier} />}
</div>
{project?.status === PROJECT_STATUS.INACTIVE && <ProjectPausedState project={project} />}
- {IS_PLATFORM && project?.status !== PROJECT_STATUS.INACTIVE && <ProjectUsageSection />}
+ <div className="mx-6">
+ {IS_PLATFORM && project?.status !== PROJECT_STATUS.INACTIVE && <ProjectUsageSection />}
+ </div>
<div className="space-y-8">
<div className="mx-6">
diff --git a/studio/pages/project/[ref]/settings/billing/index.tsx b/studio/pages/project/[ref]/settings/billing/index.tsx
index ca92aaa88f4..75bb4dba853 100644
--- a/studio/pages/project/[ref]/settings/billing/index.tsx
+++ b/studio/pages/project/[ref]/settings/billing/index.tsx
@@ -4,12 +4,7 @@ import { observer } from 'mobx-react-lite'
import { Typography, Loading, IconArrowRight } from '@supabase/ui'
import { Project, NextPageWithLayout } from 'types'
-import {
- useProjectPaygStatistics,
- useProjectSubscription,
- useStore,
- useProjectUsageStatus,
-} from 'hooks'
+import { useProjectPaygStatistics, useProjectSubscription, useStore } from 'hooks'
import { STRIPE_PRODUCT_IDS, TIME_PERIODS_REPORTS, TIME_PERIODS_BILLING } from 'lib/constants'
import { SettingsLayout } from 'components/layouts'
import LoadingUI from 'components/ui/Loading'
diff --git a/studio/pages/project/[ref]/settings/database.tsx b/studio/pages/project/[ref]/settings/database.tsx
index 18f9a002b87..1c580a01ed5 100644
--- a/studio/pages/project/[ref]/settings/database.tsx
+++ b/studio/pages/project/[ref]/settings/database.tsx
@@ -20,7 +20,7 @@ import Panel from 'components/ui/Panel'
import DateRangePicker from 'components/to-be-cleaned/DateRangePicker'
import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
import ConnectionPooling from 'components/interfaces/Database/Pooling/ConnectionPooling'
-import { ProjectUsageMinimal } from 'components/interfaces/Settings/ProjectUsageBars/ProjectUsageBars'
+import ProjectUsageMinimal from 'components/interfaces/Settings/ProjectUsageBars/ProjectUsageMinimal'
const ProjectSettings: NextPageWithLayout = () => {
const router = useRouter()
@@ -128,7 +128,7 @@ const Usage: FC<any> = ({ project }) => {
<Panel
title={
<Typography.Title key="panel-title" level={5} className="mb-0">
- Database storage
+ Database usage
</Typography.Title>
}
>
diff --git a/studio/stores/UiStore.ts b/studio/stores/UiStore.ts
index 7599784ce8a..3f6328beaf1 100644
--- a/studio/stores/UiStore.ts
+++ b/studio/stores/UiStore.ts
@@ -1,6 +1,6 @@
import { uuidv4 } from 'lib/helpers'
import { action, makeAutoObservable } from 'mobx'
-import { Project, Notification, User, Organization, ProjectBase } from 'types'
+import { Project, Notification, User, Organization, ProjectBase, Permission } from 'types'
import { IRootStore } from './RootStore'
import Telemetry from 'lib/telemetry'
@@ -16,7 +16,7 @@ export interface IUiStore {
selectedOrganization?: Organization
notification?: Notification
profile?: User
- permissions?: any // [Joshen TODO]: type this
+ permissions?: Permission[]
load: () => void
setTheme: (theme: 'dark' | 'light') => void
@@ -25,7 +25,7 @@ export interface IUiStore {
setOrganizationSlug: (slug?: string) => void
setNotification: (notification: Notification) => string
setProfile: (value?: User) => void
- setPermissions: (permissions?: any) => void // [Joshen TODO]: type this
+ setPermissions: (permissions?: Permission[]) => void
}
export default class UiStore implements IUiStore {
rootStore: IRootStore
@@ -37,7 +37,7 @@ export default class UiStore implements IUiStore {
selectedOrganizationSlug?: string
notification?: Notification
profile?: User
- permissions?: any = [] // [Joshen TODO]: define this
+ permissions?: Permission[] = []
constructor(rootStore: IRootStore) {
this.rootStore = rootStore
diff --git a/studio/types/base.ts b/studio/types/base.ts
index 970cfb7c3cc..002e303ee2c 100644
--- a/studio/types/base.ts
+++ b/studio/types/base.ts
@@ -1,3 +1,4 @@
+import jsonLogic from 'json-logic-js'
import { PermissionAction } from '@supabase/shared-types/out/constants'
export interface Organization {
@@ -70,7 +71,7 @@ export interface Role {
export interface Permission {
actions: PermissionAction[]
- condition: string | null
+ condition: jsonLogic.RulesLogic
organization_id: number
resources: string[]
}