Skip to content

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

Scaffold new usage tab for org v2

Joshen Limc406268c3d06
diff --git a/studio/components/interfaces/Organization/Usage/Activity.tsx b/studio/components/interfaces/Organization/Usage/Activity.tsx
new file mode 100644
index 00000000000..29fff89ff43
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/Activity.tsx
@@ -0,0 +1,126 @@
+import { useDailyStatsQuery } from 'data/analytics/daily-stats-query'
+import { DataPoint } from 'data/analytics/constants'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+import UsageSection from './UsageSection'
+
+export interface ActivityProps {
+ projectRef: string
+ startDate: string | undefined
+ endDate: string | undefined
+ subscription: ProjectSubscriptionResponse | undefined
+ currentBillingCycleSelected: boolean
+}
+
+const Activity = ({
+ projectRef,
+ subscription,
+ startDate,
+ endDate,
+ currentBillingCycleSelected,
+}: ActivityProps) => {
+ const { data: mauData, isLoading: isLoadingMauData } = useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_auth_billing_period_mau',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const { data: mauSSOData, isLoading: isLoadingMauSSOData } = useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_auth_billing_period_sso_mau',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const { data: assetTransformationsData, isLoading: isLoadingAssetTransformationsData } =
+ useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_storage_image_render_count',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const { data: funcInvocationsData, isLoading: isLoadingFuncInvocationsData } = useDailyStatsQuery(
+ {
+ projectRef,
+ attribute: 'total_func_invocations',
+ interval: '1d',
+ startDate,
+ endDate,
+ }
+ )
+
+ const { data: realtimeMessagesData, isLoading: isLoadingRealtimeMessagesData } =
+ useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_realtime_message_count',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const { data: realtimeConnectionsData, isLoading: isLoadingRealtimeConnectionsData } =
+ useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_realtime_peak_connection',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const chartMeta: {
+ [key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }
+ } = {
+ monthly_active_users: {
+ data: mauData?.data ?? [],
+ margin: 18,
+ isLoading: isLoadingMauData,
+ hasNoData: mauData?.hasNoData ?? false,
+ },
+ monthly_active_sso_users: {
+ data: mauSSOData?.data ?? [],
+ margin: 20,
+ isLoading: isLoadingMauSSOData,
+ hasNoData: mauSSOData?.hasNoData ?? false,
+ },
+ storage_image_render_count: {
+ data: assetTransformationsData?.data ?? [],
+ margin: 0,
+ isLoading: isLoadingMauSSOData,
+ hasNoData: assetTransformationsData?.hasNoData ?? false,
+ },
+ func_invocations: {
+ data: funcInvocationsData?.data ?? [],
+ margin: 26,
+ isLoading: isLoadingFuncInvocationsData,
+ hasNoData: funcInvocationsData?.hasNoData ?? false,
+ },
+ realtime_message_count: {
+ data: realtimeMessagesData?.data ?? [],
+ margin: 38,
+ isLoading: isLoadingRealtimeMessagesData,
+ hasNoData: realtimeMessagesData?.hasNoData ?? false,
+ },
+ realtime_peak_connection: {
+ data: realtimeConnectionsData?.data ?? [],
+ margin: 0,
+ isLoading: isLoadingRealtimeConnectionsData,
+ hasNoData: realtimeConnectionsData?.hasNoData ?? false,
+ },
+ }
+
+ return (
+ <UsageSection
+ projectRef={projectRef}
+ categoryKey="activity"
+ chartMeta={chartMeta}
+ subscription={subscription}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+ )
+}
+
+export default Activity
diff --git a/studio/components/interfaces/Organization/Usage/Bandwidth.tsx b/studio/components/interfaces/Organization/Usage/Bandwidth.tsx
new file mode 100644
index 00000000000..ef46ec26dc3
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/Bandwidth.tsx
@@ -0,0 +1,51 @@
+import { DataPoint } from 'data/analytics/constants'
+import { useDailyStatsQuery } from 'data/analytics/daily-stats-query'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+import UsageSection from './UsageSection'
+
+export interface BandwidthProps {
+ projectRef: string
+ startDate: string | undefined
+ endDate: string | undefined
+ subscription: ProjectSubscriptionResponse | undefined
+ currentBillingCycleSelected: boolean
+}
+
+const Bandwidth = ({
+ projectRef,
+ subscription,
+ startDate,
+ endDate,
+ currentBillingCycleSelected,
+}: BandwidthProps) => {
+ const { data: dbEgressData, isLoading: isLoadingDbEgressData } = useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_egress_modified',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const chartMeta: {
+ [key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }
+ } = {
+ db_egress: {
+ data: dbEgressData?.data ?? [],
+ margin: 16,
+ isLoading: isLoadingDbEgressData,
+ hasNoData: dbEgressData?.hasNoData ?? false,
+ },
+ }
+
+ return (
+ <UsageSection
+ projectRef={projectRef}
+ categoryKey="bandwidth"
+ chartMeta={chartMeta}
+ subscription={subscription}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+ )
+}
+
+export default Bandwidth
diff --git a/studio/components/interfaces/Organization/Usage/SectionContent.tsx b/studio/components/interfaces/Organization/Usage/SectionContent.tsx
new file mode 100644
index 00000000000..1d2d8f269e9
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/SectionContent.tsx
@@ -0,0 +1,63 @@
+import { PropsWithChildren } from 'react'
+import { Badge, IconExternalLink } from 'ui'
+import { CategoryAttribute } from './Usage.constants'
+import Link from 'next/link'
+
+export interface SectionContent {
+ section: CategoryAttribute
+ includedInPlan?: boolean
+}
+
+const SectionContent = ({
+ section,
+ includedInPlan,
+ children,
+}: PropsWithChildren<SectionContent>) => {
+ const { name, description, links } = section
+
+ return (
+ <div className="border-b">
+ <div className="1xl:px-28 mx-auto flex flex-col gap-10 px-5 lg:px-16 2xl:px-32 py-16">
+ <div className="grid grid-cols-12 gap-6">
+ <div className="col-span-12 lg:col-span-5">
+ <div className="sticky top-32 space-y-6">
+ <div className="space-y-1">
+ <div className="flex items-center space-x-2">
+ <p className="text-base capitalize">{name}</p>
+ {includedInPlan === false && <Badge color="gray">Not included</Badge>}
+ </div>
+ <div className="grid gap-4">
+ {description.split('\n').map((value, idx) => (
+ <p key={`desc-${idx}`} className="text-sm text-scale-1000 pr-8">
+ {value}
+ </p>
+ ))}
+ </div>
+ </div>
+ {links && links.length && (
+ <div className="space-y-2">
+ <p className="text-sm text-scale-1200 dark:text-scale-1100 mb-2">More information</p>
+ {links.map((link) => (
+ <div key={link.url}>
+ <Link href={link.url}>
+ <a target="_blank" rel="noreferrer">
+ <div className="flex items-center space-x-2 opacity-50 hover:opacity-100 transition">
+ <p className="text-sm">{link.name}</p>
+ <IconExternalLink size={16} strokeWidth={1.5} />
+ </div>
+ </a>
+ </Link>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ </div>
+ <div className="col-span-12 lg:col-span-7 space-y-6">{children}</div>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default SectionContent
diff --git a/studio/components/interfaces/Organization/Usage/SectionHeader.tsx b/studio/components/interfaces/Organization/Usage/SectionHeader.tsx
new file mode 100644
index 00000000000..6b2b35532b1
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/SectionHeader.tsx
@@ -0,0 +1,19 @@
+export interface SectionHeaderProps {
+ title: string
+ description: string
+}
+
+const SectionHeader = ({ title, description }: SectionHeaderProps) => {
+ return (
+ <div className="border-b">
+ <div className="1xl:px-28 mx-auto flex flex-col gap-10 px-5 lg:px-16 2xl:px-32 py-16">
+ <div>
+ <p className="text-xl">{title}</p>
+ <p className="text-sm text-scale-1000">{description}</p>
+ </div>
+ </div>
+ </div>
+ )
+}
+
+export default SectionHeader
diff --git a/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx b/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx
new file mode 100644
index 00000000000..6527a636ee7
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/SizeAndCounts.tsx
@@ -0,0 +1,79 @@
+import { useDailyStatsQuery } from 'data/analytics/daily-stats-query'
+import { DataPoint } from 'data/analytics/constants'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+import UsageSection from './UsageSection'
+
+export interface SizeAndCountsProps {
+ projectRef: string
+ startDate: string | undefined
+ endDate: string | undefined
+ subscription: ProjectSubscriptionResponse | undefined
+ currentBillingCycleSelected: boolean
+}
+
+const SizeAndCounts = ({
+ projectRef,
+ startDate,
+ endDate,
+ subscription,
+ currentBillingCycleSelected,
+}: SizeAndCountsProps) => {
+ const { data: dbSizeData, isLoading: isLoadingDbSizeData } = useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_db_size_bytes',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const { data: storageSizeData, isLoading: isLoadingStorageSizeData } = useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_storage_size_bytes',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const { data: functionCountData, isLoading: isLoadingFunctionCountData } = useDailyStatsQuery({
+ projectRef,
+ attribute: 'total_func_count',
+ interval: '1d',
+ startDate,
+ endDate,
+ })
+
+ const chartMeta: {
+ [key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }
+ } = {
+ db_size: {
+ isLoading: isLoadingDbSizeData,
+ margin: 14,
+ data: dbSizeData?.data ?? [],
+ hasNoData: dbSizeData?.hasNoData ?? false,
+ },
+ storage_size: {
+ isLoading: isLoadingStorageSizeData,
+ margin: 14,
+ data: storageSizeData?.data ?? [],
+ hasNoData: storageSizeData?.hasNoData ?? false,
+ },
+ func_count: {
+ isLoading: isLoadingFunctionCountData,
+ margin: 0,
+ data: functionCountData?.data ?? [],
+ hasNoData: functionCountData?.hasNoData ?? false,
+ },
+ }
+
+ return (
+ <UsageSection
+ projectRef={projectRef}
+ categoryKey="sizeCount"
+ chartMeta={chartMeta}
+ subscription={subscription}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+ )
+}
+
+export default SizeAndCounts
diff --git a/studio/components/interfaces/Organization/Usage/Usage.constants.tsx b/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
new file mode 100644
index 00000000000..0cbb438d5c2
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
@@ -0,0 +1,287 @@
+import Link from 'next/link'
+
+import { USAGE_APPROACHING_THRESHOLD } from 'components/interfaces/BillingV2/Billing.constants'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+import { ProjectUsageData } from 'data/usage/project-usage-query'
+import { Alert, Badge, Button, IconExternalLink } from 'ui'
+
+export const Y_DOMAIN_CEILING_MULTIPLIER = 4 / 3
+
+export const USAGE_STATUS = {
+ NORMAL: 'NORMAL',
+ APPROACHING: 'APPROACHING',
+ EXCEEDED: 'EXCEEDED',
+}
+
+export interface CategoryAttribute {
+ anchor: string
+ key: string // Property from project usage
+ attribute: string // For querying against stats-daily / infra-monitoring
+ name: string
+ chartPrefix?: string
+ unit: 'bytes' | 'absolute' | 'percentage'
+ links?: {
+ name: string
+ url: string
+ }[]
+ description: string
+ chartDescription: string
+ additionalInfo?: (
+ ref: string,
+ subscription?: ProjectSubscriptionResponse,
+ usage?: ProjectUsageData
+ ) => JSX.Element | null
+}
+
+export type CategoryMetaKey = 'bandwidth' | 'sizeCount' | 'activity'
+
+export interface CategoryMeta {
+ key: 'bandwidth' | 'sizeCount' | 'activity'
+ name: string
+ description: string
+ attributes: CategoryAttribute[]
+}
+
+export const USAGE_CATEGORIES: CategoryMeta[] = [
+ {
+ key: 'bandwidth',
+ name: 'Bandwidth',
+ description: 'Amount of data transmitted over all network connections',
+ attributes: [
+ {
+ anchor: 'dbEgress',
+ key: 'db_egress',
+ attribute: 'total_egress_modified',
+ name: 'Total Egress',
+ unit: 'bytes',
+ description:
+ 'Contains any outgoing traffic (egress) from your database.\nBilling is based on the total sum of egress in GB throughout your billing period.',
+ chartDescription: 'The data refreshes every 24 hours.',
+ },
+ ],
+ },
+ {
+ key: 'sizeCount',
+ name: 'Size & Counts',
+ description: 'Amount of resources your project is consuming',
+ attributes: [
+ {
+ anchor: 'dbSize',
+ key: 'db_size',
+ attribute: 'total_db_size_bytes',
+ name: 'Database size',
+ chartPrefix: 'Average ',
+ unit: 'bytes',
+ description:
+ 'Database size refers to the monthly average storage usage, as reported by Postgres. Paid plans use auto-scaling disks.\nBilling is based on the average daily database size used in GB throughout the billing period. Billing is independent of the provisioned disk size.',
+ links: [
+ {
+ name: 'Documentation',
+ url: 'https://supabase.com/docs/guides/platform/database-size',
+ },
+ ],
+ chartDescription: 'The data refreshes every 24 hours.',
+ additionalInfo: (
+ ref: string,
+ subscription?: ProjectSubscriptionResponse,
+ usage?: ProjectUsageData
+ ) => {
+ const usageMeta = usage?.['db_size'] ?? undefined
+ const usageRatio =
+ typeof usageMeta !== 'number' ? (usageMeta?.usage ?? 0) / (usageMeta?.limit ?? 0) : 0
+ const hasLimit = usageMeta && usageMeta.limit > 0
+
+ const isApproachingLimit = hasLimit && usageRatio >= USAGE_APPROACHING_THRESHOLD
+ const isExceededLimit = hasLimit && usageRatio >= 1
+
+ return subscription?.plan?.id !== 'free' ? (
+ <div>
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-2">
+ <p className="text-sm">Disk size:</p>
+ <p className="text-sm">{usage?.disk_volume_size_gb} GB</p>
+ <Badge color="green" size="small">
+ Auto-scaling
+ </Badge>
+ </div>
+ <Link href="https://supabase.com/docs/guides/platform/database-usage#disk-management">
+ <a>
+ <Button size="tiny" type="default" icon={<IconExternalLink size={14} />}>
+ What is disk size?
+ </Button>
+ </a>
+ </Link>
+ </div>
+ <p className="text-sm text-scale-1000 mt-3">
+ If you reach 95% of the disk space, your project will enter read-only mode. Your
+ disk storage expands automatically when the database reaches 90% of the disk size.
+ The disk is expanded to be 50% larger. Auto-scaling can only take place once every 6
+ hours. You can also{' '}
+ <Link passHref href={`/project/${ref}/settings/database#diskManagement`}>
+ <a className="text-brand-900 transition hover:text-brand-1000">preprovision</a>
+ </Link>{' '}
+ disk for loading larger amounts of data.
+ </p>
+ </div>
+ ) : (
+ <div>
+ {(isApproachingLimit || isExceededLimit) && (
+ <Alert
+ withIcon
+ variant={isExceededLimit ? 'danger' : 'warning'}
+ title={
+ isExceededLimit
+ ? 'Exceeding database size limit'
+ : 'Nearing database size limit'
+ }
+ >
+ <div className="flex w-full items-center flex-col justify-center space-y-2 md:flex-row md:justify-between">
+ <div>
+ When you reach your database size limit, your project can go into read-only
+ mode. Please upgrade your plan.
+ </div>
+ </div>
+ </Alert>
+ )}
+ </div>
+ )
+ },
+ },
+ {
+ anchor: 'storageSize',
+ key: 'storage_size',
+ attribute: 'total_storage_size_bytes',
+ name: 'Storage Size',
+ chartPrefix: 'Max ',
+ unit: 'bytes',
+ description:
+ 'Sum of all objects in your storage buckets.\nBilling is based on the average daily size in GB throughout your billing period.',
+ chartDescription: 'The data refreshes every 24 hours.',
+ links: [
+ {
+ name: 'Storage',
+ url: 'https://supabase.com/docs/guides/storage',
+ },
+ ],
+ },
+ {
+ anchor: 'funcCount',
+ key: 'func_count',
+ attribute: 'total_func_count',
+ name: 'Edge Function Count',
+ chartPrefix: 'Max ',
+ unit: 'absolute',
+ description:
+ 'Number of serverless functions in your project.\nBilling is based on the maximum amount of functions at any point in time throughout your billing period.',
+ chartDescription: 'The data refreshes every 24 hours.',
+ },
+ ],
+ },
+ {
+ key: 'activity',
+ name: 'Activity',
+ description: 'Usage statistics that reflect the activity of your project',
+ attributes: [
+ {
+ anchor: 'mau',
+ key: 'monthly_active_users',
+ attribute: 'total_auth_billing_period_mau',
+ name: 'Monthly Active Users',
+ unit: 'absolute',
+ description:
+ 'Users who log in or refresh their token count towards MAU.\nBilling is based on the sum of distinct users requesting your API throughout the billing period. Resets every billing cycle.',
+ chartDescription:
+ 'The data is refreshed over a period of 24 hours and resets at the beginning of every billing period.\nThe data points are relative to the beginning of your billing period.',
+ links: [
+ {
+ name: 'Auth',
+ url: 'https://supabase.com/docs/guides/auth',
+ },
+ ],
+ },
+ {
+ anchor: 'mauSso',
+ key: 'monthly_active_sso_users',
+ attribute: 'total_auth_billing_period_sso_mau',
+ name: 'Monthly Active SSO Users',
+ unit: 'absolute',
+ description:
+ 'SSO users who log in or refresh their token count towards SSO MAU.\nBilling is based on the sum of distinct Single Sign-On users requesting your API throughout the billing period. Resets every billing cycle.',
+ chartDescription:
+ 'The data refreshes over a period of 24 hours and resets at the beginning of every billing period.\nThe data points are relative to the beginning of your billing period.',
+ links: [
+ {
+ name: 'SSO with SAML 2.0',
+ url: 'https://supabase.com/docs/guides/auth/sso/auth-sso-saml',
+ },
+ ],
+ },
+ {
+ anchor: 'storageImageTransformations',
+ key: 'storage_image_render_count',
+ attribute: 'total_storage_image_render_count',
+ name: 'Storage Image Transformations',
+ unit: 'absolute',
+ description:
+ 'We count all images that were transformed in the billing period, ignoring any transformations.\nUsage example: You transform one image with four different size transformations and another image with just a single transformation. It counts as two, as only two images were transformed.\nBilling is based on the count of (origin) images that used transformations throughout the billing period. Resets every billing cycle.',
+ chartDescription:
+ 'The data refreshes every 24 hours.\nThe data points are relative to the beginning of your billing period.',
+ links: [
+ {
+ name: 'Documentation',
+ url: 'https://supabase.com/docs/guides/storage/image-transformations',
+ },
+ ],
+ },
+ {
+ anchor: 'functionInvocations',
+ key: 'func_invocations',
+ attribute: 'total_func_invocations',
+ name: 'Edge Function Invocations',
+ unit: 'absolute',
+ description:
+ 'Every serverless function invocation independent of response status is counted.\nBilling is based on the sum of all invocations throughout your billing period.',
+ chartDescription: 'The data refreshes every 24 hours.',
+ links: [
+ {
+ name: 'Edge Functions',
+ url: 'https://supabase.com/docs/guides/functions',
+ },
+ ],
+ },
+ {
+ anchor: 'realtimeMessageCount',
+ key: 'realtime_message_count',
+ attribute: 'total_realtime_message_count',
+ name: 'Realtime Message Count',
+ unit: 'absolute',
+ description:
+ "Count of messages going through Realtime.\nUsage example: If you do a database change and 5 clients listen to that change via Realtime, that's 5 messages. If you broadcast a message and 4 clients listen to that, that's 5 messages (1 message sent, 4 received).\nBilling is based on the total amount of messages throughout your billing period.",
+ chartDescription: 'The data refreshes every 24 hours.',
+ links: [
+ {
+ name: 'Realtime Quotas',
+ url: 'https://supabase.com/docs/guides/realtime/quotas',
+ },
+ ],
+ },
+ {
+ anchor: 'realtimePeakConnection',
+ key: 'realtime_peak_connection',
+ attribute: 'total_realtime_peak_connection',
+ name: 'Realtime Peak Connections',
+ chartPrefix: 'Max ',
+ unit: 'absolute',
+ description:
+ 'Total number of successful connections. Connections attempts are not counted towards usage.\nBilling is based on the maximum amount of concurrent peak connections throughout your billing period.',
+ chartDescription: 'The data refreshes every 24 hours.',
+ links: [
+ {
+ name: 'Realtime Quotas',
+ url: 'https://supabase.com/docs/guides/realtime/quotas',
+ },
+ ],
+ },
+ ],
+ },
+]
diff --git a/studio/components/interfaces/Organization/Usage/Usage.tsx b/studio/components/interfaces/Organization/Usage/Usage.tsx
new file mode 100644
index 00000000000..650b0cd0582
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/Usage.tsx
@@ -0,0 +1,99 @@
+import dayjs from 'dayjs'
+import { useMemo, useState } from 'react'
+
+import { useParams } from 'common'
+import Bandwidth from './Bandwidth'
+import { useOrgSubscriptionQuery } from 'data/subscriptions/org-subscription-query'
+import DateRangePicker from 'components/to-be-cleaned/DateRangePicker'
+import { TIME_PERIODS_BILLING, TIME_PERIODS_REPORTS } from 'lib/constants'
+import SizeAndCounts from './SizeAndCounts'
+import Activity from './Activity'
+
+const Usage = () => {
+ const { slug } = useParams()
+ const [dateRange, setDateRange] = useState<any>()
+
+ const selectedProjectRef = 'kojplftaeiavuneadgix'
+
+ const {
+ data: subscription,
+ isLoading: isLoadingSubscription,
+ isError,
+ isSuccess,
+ } = useOrgSubscriptionQuery({ orgSlug: slug })
+
+ const currentBillingCycleSelected = useMemo(() => {
+ // Selected by default
+ if (!dateRange?.period_start || !dateRange?.period_end || !subscription) return true
+
+ const { current_period_start, current_period_end } = subscription
+
+ return (
+ dayjs(dateRange.period_start.date).isSame(new Date(current_period_start * 1000)) &&
+ dayjs(dateRange.period_end.date).isSame(new Date(current_period_end * 1000))
+ )
+ }, [dateRange, subscription])
+
+ const startDate = useMemo(() => {
+ // If end date is in future, set end date to now
+ if (!dateRange?.period_start?.date) {
+ return undefined
+ } else {
+ // LF seems to have an issue with the milliseconds, causes infinite loading sometimes
+ return new Date(dateRange?.period_start?.date).toISOString().slice(0, -5) + 'Z'
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dateRange, subscription])
+
+ const endDate = useMemo(() => {
+ // If end date is in future, set end date to end of current day
+ if (dateRange?.period_end?.date && dayjs(dateRange.period_end.date).isAfter(dayjs())) {
+ // LF seems to have an issue with the milliseconds, causes infinite loading sometimes
+ // In order to have full days from Prometheus metrics when using 1d interval,
+ // the time needs to be greater or equal than the time of the start date
+ return dayjs().endOf('day').toISOString().slice(0, -5) + 'Z'
+ } else if (dateRange?.period_end?.date) {
+ // LF seems to have an issue with the milliseconds, causes infinite loading sometimes
+ return new Date(dateRange.period_end.date).toISOString().slice(0, -5) + 'Z'
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [dateRange, subscription])
+
+ return (
+ <>
+ <DateRangePicker
+ id="billingCycle"
+ name="billingCycle"
+ onChange={setDateRange}
+ value={TIME_PERIODS_BILLING[0].key}
+ options={[...TIME_PERIODS_BILLING, ...TIME_PERIODS_REPORTS]}
+ loading={isLoadingSubscription}
+ currentBillingPeriodStart={subscription?.current_period_start}
+ className="!w-[200px]"
+ />
+ <Bandwidth
+ projectRef={selectedProjectRef}
+ subscription={subscription}
+ startDate={startDate}
+ endDate={endDate}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+ <SizeAndCounts
+ projectRef={selectedProjectRef}
+ subscription={subscription}
+ startDate={startDate}
+ endDate={endDate}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+ <Activity
+ projectRef={selectedProjectRef}
+ subscription={subscription}
+ startDate={startDate}
+ endDate={endDate}
+ currentBillingCycleSelected={currentBillingCycleSelected}
+ />
+ </>
+ )
+}
+
+export default Usage
diff --git a/studio/components/interfaces/Organization/Usage/Usage.utils.ts b/studio/components/interfaces/Organization/Usage/Usage.utils.ts
new file mode 100644
index 00000000000..6bc5eb09712
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/Usage.utils.ts
@@ -0,0 +1,111 @@
+import { DataPoint } from 'data/analytics/constants'
+import { ProjectUsageResponse } from 'data/usage/project-usage-query'
+import { USAGE_APPROACHING_THRESHOLD } from 'components/interfaces/BillingV2/Billing.constants'
+import { CategoryAttribute, USAGE_STATUS } from './Usage.constants'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+
+// [Joshen] This is just for development to generate some test data for chart rendering
+export const generateUsageData = (attribute: string, days: number): DataPoint[] => {
+ const tempArray = new Array(days).fill(0)
+ return tempArray.map((x, idx) => {
+ return {
+ loopId: (idx + 1).toString(),
+ period_start: `${idx + 1}`,
+ [attribute]: Math.floor(Math.random() * 100).toString(),
+ }
+ })
+}
+
+export const getUsageStatus = (attributes: CategoryAttribute[], usage?: ProjectUsageResponse) => {
+ if (!usage) return USAGE_STATUS.NORMAL
+
+ const attributeStatuses = attributes.map((attribute) => {
+ const usageMeta = usage?.[attribute.key as keyof ProjectUsageResponse]
+ const usageRatio =
+ typeof usageMeta !== 'number' ? (usageMeta?.usage ?? 0) / (usageMeta?.limit ?? 0) : 0
+ if (usageRatio >= 1) return USAGE_STATUS.EXCEEDED
+ else if (usageRatio >= USAGE_APPROACHING_THRESHOLD) return USAGE_STATUS.APPROACHING
+ else return USAGE_STATUS.NORMAL
+ })
+
+ if (attributeStatuses.find((x) => x === USAGE_STATUS.EXCEEDED)) return USAGE_STATUS.EXCEEDED
+ else if (attributeStatuses.find((x) => x === USAGE_STATUS.APPROACHING))
+ return USAGE_STATUS.APPROACHING
+ else return USAGE_STATUS.NORMAL
+}
+
+export const getUpgradeUrl = (projectRef: string, subscription?: ProjectSubscriptionResponse) => {
+ if (!subscription) {
+ return `/project/${projectRef}/settings/billing/subscription`
+ }
+
+ return subscription?.plan?.id === 'pro' && subscription?.usage_billing_enabled === false
+ ? `/project/${projectRef}/settings/billing/subscription#cost-control`
+ : `/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`
+}
+
+const compactNumberFormatter = new Intl.NumberFormat('en-US', {
+ notation: 'compact',
+ compactDisplay: 'short',
+})
+
+/**
+ * For the y-axis, we don't need to be as precise, to avoid showing 58.597MB.
+ */
+export const ChartYFormatterCompactNumber = (number: number | string, unit: string) => {
+ if (typeof number === 'string') return number
+
+ if (unit === 'bytes') {
+ const formattedBytes = formatBytesCompact(number).replace(/\s/g, '')
+
+ return formattedBytes === '0bytes' ? '0' : formattedBytes
+ } else {
+ return compactNumberFormatter.format(number)
+ }
+}
+
+/**
+ * For the chart tooltip, we want to be more precise and show more decimals.
+ */
+export const ChartTooltipValueFormatter = (number: number | string, unit: string) => {
+ if (typeof number === 'string') return number
+
+ if (unit === 'bytes') {
+ const formattedBytes = formatBytesPrecision(number).replace(/\s/g, '')
+
+ return formattedBytes === '0bytes' ? '0' : formattedBytes
+ } else {
+ return compactNumberFormatter.format(number)
+ }
+}
+
+const sizes = ['bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
+
+export const formatBytesCompact = (bytes: number) => {
+ if (bytes === 0 || bytes === undefined) return '0 bytes'
+
+ const k = 1024
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+
+ const unit = sizes[i]
+
+ let dm = 2
+ if (['bytes', 'KB', 'MB'].includes(unit)) {
+ dm = 0
+ } else if (['GB'].includes(unit)) {
+ dm = 1
+ }
+
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + unit
+}
+
+export const formatBytesPrecision = (bytes: any) => {
+ if (bytes === 0 || bytes === undefined) return '0 bytes'
+
+ const k = 1024
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+
+ const unit = sizes[i]
+
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(3)) + ' ' + unit
+}
diff --git a/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx b/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx
new file mode 100644
index 00000000000..c93733f5eb6
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx
@@ -0,0 +1,97 @@
+import { DataPoint } from 'data/analytics/constants'
+import {
+ Bar,
+ CartesianGrid,
+ Cell,
+ ComposedChart,
+ ResponsiveContainer,
+ Tooltip,
+ XAxis,
+ YAxis,
+} from 'recharts'
+import dayjs from 'dayjs'
+
+// [Joshen] This BarChart is specifically for usage, hence not a reusable component, and not
+// replacing the existing BarChart in ui/Charts
+
+export interface UsageBarChartProps {
+ data: DataPoint[]
+ name: string // Used within the tooltip
+ attribute: string
+ unit: 'bytes' | 'absolute' | 'percentage'
+ yLimit?: number
+ yLeftMargin?: number
+ yFormatter?: (value: number | string) => string
+ tooltipFormatter?: (value: number | string) => string
+}
+
+const UsageBarChart = ({
+ data,
+ name,
+ attribute,
+ unit,
+ yLimit,
+ yLeftMargin = 10,
+ yFormatter,
+ tooltipFormatter
+}: UsageBarChartProps) => {
+ const yMin = 0 // We can consider passing this as a prop if there's a use case in the future
+
+ const yDomain = [yMin, yLimit ?? 0]
+
+
+ return (
+ <div className="w-full h-[200px]">
+ <ResponsiveContainer width="100%" height={200}>
+ <ComposedChart data={data} margin={{ top: 0, right: 0, left: yLeftMargin, bottom: 0 }}>
+ <CartesianGrid vertical={false} strokeDasharray="3 3" className="stroke-scale-800" />
+ <XAxis dataKey="periodStartFormatted" />
+ <YAxis
+ width={40}
+ axisLine={false}
+ tickLine={{ stroke: 'none' }}
+ domain={yDomain}
+ tickFormatter={yFormatter}
+ />
+ <Tooltip
+ content={(props) => {
+ const { active, payload } = props
+ if (active && payload && payload.length) {
+ const dataPeriod = dayjs(payload[0].payload.period_start)
+ const value =
+ unit === 'percentage'
+ ? Number(payload[0].value).toFixed(2)
+ : Number(payload[0].value)
+
+ return (
+ <div className="w-[170px] border bg-scale-300 rounded-md px-2 py-2">
+ <p className="text-xs text-scale-1000">
+ {attribute === 'disk_io_budget' ? `Remaining IO budget:` : `${name}:`}
+ </p>
+ {dataPeriod.startOf('day').isAfter(dayjs().startOf('day')) ? (
+ <p className="text-scale-1000 text-lg">No data yet</p>
+ ) : (
+ <p className="text-xl">
+ {tooltipFormatter !== undefined ? tooltipFormatter(value) : value}
+ </p>
+ )}
+ <p className="text-xs text-scale-1100 mt-1">
+ {dataPeriod.format('DD MMM YYYY')}
+ </p>
+ </div>
+ )
+ } else return null
+ }}
+ />
+ <Bar dataKey={attribute}>
+ {data.map((entry) => {
+ return <Cell key={`${entry.period_start}`} className="fill-scale-1200" />
+ })}
+ </Bar>
+ </ComposedChart>
+ </ResponsiveContainer>
+ </div>
+ )
+}
+
+export default UsageBarChart
diff --git a/studio/components/interfaces/Organization/Usage/UsageSection.tsx b/studio/components/interfaces/Organization/Usage/UsageSection.tsx
new file mode 100644
index 00000000000..9b67c1fd239
--- /dev/null
+++ b/studio/components/interfaces/Organization/Usage/UsageSection.tsx
@@ -0,0 +1,283 @@
+import ShimmeringLoader from 'components/ui/ShimmeringLoader'
+import SectionHeader from './SectionHeader'
+import { CategoryMetaKey, USAGE_CATEGORIES } from './Usage.constants'
+import {
+ ProjectUsageResponse,
+ UsageMetric,
+ useProjectUsageQuery,
+} from 'data/usage/project-usage-query'
+import { DataPoint } from 'data/analytics/constants'
+import SectionContent from './SectionContent'
+import { Button, IconAlertTriangle, IconBarChart2 } from 'ui'
+import { USAGE_APPROACHING_THRESHOLD } from 'components/interfaces/BillingV2/Billing.constants'
+import Link from 'next/link'
+import SparkBar from 'components/ui/SparkBar'
+import clsx from 'clsx'
+import { ProjectSubscriptionResponse } from 'data/subscriptions/project-subscription-v2-query'
+import {
+ ChartTooltipValueFormatter,
+ ChartYFormatterCompactNumber,
+ getUpgradeUrl,
+} from './Usage.utils'
+import { formatBytes } from 'lib/helpers'
+import UsageBarChart from './UsageBarChart'
+import Panel from 'components/ui/Panel'
+import * as Tooltip from '@radix-ui/react-tooltip'
+
+interface UsageSectionProps {
+ projectRef: string
+ categoryKey: CategoryMetaKey
+ subscription: ProjectSubscriptionResponse | undefined
+ chartMeta: {
+ [key: string]: { data: DataPoint[]; margin: number; isLoading: boolean; hasNoData: boolean }
+ }
+ currentBillingCycleSelected: boolean
+}
+
+const UsageSection = ({
+ projectRef,
+ categoryKey,
+ chartMeta,
+ subscription,
+ currentBillingCycleSelected,
+}: UsageSectionProps) => {
+ const { data: usage } = useProjectUsageQuery({ projectRef })
+ const categoryMeta = USAGE_CATEGORIES.find((category) => category.key === categoryKey)
+
+ if (!categoryMeta) return null
+
+ const usageBasedBilling = subscription?.usage_billing_enabled
+ const exceededLimitStyle = !usageBasedBilling ? 'text-red-900' : 'text-amber-900'
+
+ const upgradeUrl = getUpgradeUrl(projectRef, subscription)
+
+ return (
+ <>
+ <SectionHeader title={categoryMeta.name} description={categoryMeta.description} />
+
+ {categoryMeta.attributes.map((attribute) => {
+ const usageMeta = usage?.[attribute.key as keyof ProjectUsageResponse] as UsageMetric
+ const usageRatio =
+ typeof usageMeta !== 'number' ? (usageMeta?.usage ?? 0) / (usageMeta?.limit ?? 0) : 0
+ const usageExcess = (usageMeta?.usage ?? 0) - (usageMeta?.limit ?? 0)
+
+ const chartData = chartMeta[attribute.key]?.data ?? []
+
+ const notAllValuesZero = chartData.some(
+ (dataPoint) => Number(dataPoint[attribute.attribute]) !== 0
+ )
+
+ return (
+ <div id={attribute.anchor} key={attribute.key}>
+ <SectionContent section={attribute}>
+ {usageMeta?.available_in_plan ? (
+ <>
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-4">
+ <p className="text-sm">{attribute.name} usage</p>
+ {currentBillingCycleSelected &&
+ usageBasedBilling === false &&
+ usageRatio >= USAGE_APPROACHING_THRESHOLD && (
+ <Tooltip.Root delayDuration={0}>
+ <Tooltip.Trigger asChild>
+ {!usageBasedBilling && usageRatio >= 1 ? (
+ <div className="flex items-center space-x-2 min-w-[115px] cursor-help">
+ <IconAlertTriangle
+ size={14}
+ strokeWidth={2}
+ className={exceededLimitStyle}
+ />
+ <p className={`text-sm ${exceededLimitStyle}`}>
+ Exceeded limit
+ </p>
+ </div>
+ ) : (
+ !usageBasedBilling &&
+ usageRatio >= USAGE_APPROACHING_THRESHOLD && (
+ <div className="flex items-center space-x-2 min-w-[115px] cursor-help">
+ <IconAlertTriangle
+ size={14}
+ strokeWidth={2}
+ className="text-amber-900"
+ />
+ <p className="text-sm text-amber-900">Approaching limit</p>
+ </div>
+ )
+ )}
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content side="bottom">
+ <Tooltip.Arrow className="radix-tooltip-arrow" />
+ <div
+ className={[
+ 'rounded bg-scale-100 py-1 px-2 leading-none shadow',
+ 'border border-scale-200',
+ ].join(' ')}
+ >
+ <p className="text-xs text-scale-1200">
+ Exceeding your plans included usage will lead to restrictions
+ to your project.
+ </p>
+ <p className="text-xs text-scale-1200">
+ Upgrade to a usage-based plan or disable the spend cap to
+ avoid restrictions.
+ </p>
+ </div>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ )}
+ </div>
+
+ {currentBillingCycleSelected &&
+ !usageBasedBilling &&
+ usageRatio >= USAGE_APPROACHING_THRESHOLD && (
+ <Link href={upgradeUrl}>
+ <a className="pb-1">
+ <Button type="default" size="tiny">
+ {subscription?.plan?.id === 'free'
+ ? 'Upgrade plan'
+ : 'Change spend cap'}
+ </Button>
+ </a>
+ </Link>
+ )}
+ </div>
+ {currentBillingCycleSelected && usageMeta?.limit > 0 && (
+ <SparkBar
+ type="horizontal"
+ barClass={clsx(
+ usageRatio >= 1
+ ? usageBasedBilling
+ ? 'bg-scale-1100'
+ : 'bg-red-900'
+ : usageBasedBilling === false &&
+ usageRatio >= USAGE_APPROACHING_THRESHOLD
+ ? 'bg-amber-900'
+ : 'bg-scale-1100'
+ )}
+ bgClass="bg-gray-300 dark:bg-gray-600"
+ value={usageMeta?.usage ?? 0}
+ max={usageMeta?.limit || 1}
+ />
+ )}
+ <div>
+ <div className="flex items-center justify-between border-b py-1">
+ <p className="text-xs text-scale-1000">
+ Included in {subscription?.plan?.name.toLowerCase()} plan
+ </p>
+ {usageMeta?.limit === -1 ? (
+ <p className="text-xs">None</p>
+ ) : usageMeta?.limit === 0 ? (
+ <p className="text-xs">Unlimited</p>
+ ) : (
+ <p className="text-xs">
+ {attribute.unit === 'bytes'
+ ? formatBytes(usageMeta?.limit ?? 0)
+ : (usageMeta?.limit ?? 0).toLocaleString()}
+ </p>
+ )}
+ </div>
+ {currentBillingCycleSelected && (
+ <div className="flex items-center justify-between py-1">
+ <p className="text-xs text-scale-1000">
+ {attribute.chartPrefix || 'Used '}in period
+ </p>
+ <p className="text-xs">
+ {attribute.unit === 'bytes'
+ ? formatBytes(usageMeta?.usage ?? 0)
+ : (usageMeta?.usage ?? 0).toLocaleString()}
+ </p>
+ </div>
+ )}
+ {currentBillingCycleSelected && usageMeta?.limit > 0 && (
+ <div className="flex items-center justify-between border-t py-1">
+ <p className="text-xs text-scale-1000">Overage in period</p>
+ <p className="text-xs">
+ {(usageMeta?.limit ?? 0) === -1 || usageExcess < 0
+ ? 0
+ : attribute.unit === 'bytes'
+ ? formatBytes(usageExcess)
+ : usageExcess.toLocaleString()}
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {attribute.additionalInfo?.(projectRef, subscription, usage)}
+
+ <div className="space-y-1">
+ <p>
+ {attribute.chartPrefix || ''}
+ {attribute.name} per day
+ </p>
+ {attribute.chartDescription.split('\n').map((paragraph, idx) => (
+ <p key={`para-${idx}`} className="text-sm text-scale-1000">
+ {paragraph}
+ </p>
+ ))}
+ </div>
+ {chartMeta[attribute.key].isLoading ? (
+ <div className="space-y-2">
+ <ShimmeringLoader />
+ <ShimmeringLoader className="w-3/4" />
+ <ShimmeringLoader className="w-1/2" />
+ </div>
+ ) : chartData.length > 0 && notAllValuesZero ? (
+ <UsageBarChart
+ name={`${attribute.chartPrefix || ''}${attribute.name}`}
+ unit={attribute.unit}
+ attribute={attribute.attribute}
+ data={chartData}
+ yLeftMargin={chartMeta[attribute.key].margin}
+ yFormatter={(value) => ChartYFormatterCompactNumber(value, attribute.unit)}
+ tooltipFormatter={(value) =>
+ ChartTooltipValueFormatter(value, attribute.unit)
+ }
+ />
+ ) : (
+ <Panel>
+ <Panel.Content>
+ <div className="flex flex-col items-center justify-center">
+ <IconBarChart2 className="text-scale-1100 mb-2" />
+ <p className="text-sm">No data in period</p>
+ <p className="text-sm text-scale-1000">May take up to 24 hours to show</p>
+ </div>
+ </Panel.Content>
+ </Panel>
+ )}
+ </>
+ ) : (
+ <Panel>
+ <Panel.Content>
+ <div className="flex w-full items-center flex-col justify-center space-y-2 md:flex-row md:justify-between">
+ <div className="space-y-1">
+ <p className="text-sm">Not included in plan</p>
+ <div>
+ <p className="text-sm text-scale-1100">
+ You need to be on a higher plan in order to use this feature.
+ </p>
+ </div>
+ </div>
+ <Link
+ href={`/project/${projectRef}/settings/billing/subscription?panel=subscriptionPlan`}
+ >
+ <a>
+ <Button type="primary">Upgrade plan</Button>
+ </a>
+ </Link>
+ </div>
+ </Panel.Content>
+ </Panel>
+ )}
+ </SectionContent>
+ </div>
+ )
+ })}
+ </>
+ )
+}
+
+export default UsageSection
diff --git a/studio/components/interfaces/Organization/index.ts b/studio/components/interfaces/Organization/index.ts
index d37a3c1ca1d..c041402fdf2 100644
--- a/studio/components/interfaces/Organization/index.ts
+++ b/studio/components/interfaces/Organization/index.ts
@@ -4,6 +4,7 @@ import BillingSettings from './BillingSettings/BillingSettings'
import BillingSettingsV2 from './BillingSettings/BillingSettingsV2'
import InvoicesSettings from './InvoicesSettings/InvoicesSettings'
import NewOrgForm from './NewOrg/NewOrgForm'
+import Usage from './Usage/Usage'
import OAuthApps from './OAuthApps/OAuthApps'
export {
@@ -13,5 +14,6 @@ export {
BillingSettingsV2,
InvoicesSettings,
NewOrgForm,
+ Usage,
OAuthApps,
}
diff --git a/studio/pages/org/[slug]/usage.tsx b/studio/pages/org/[slug]/usage.tsx
index 4106cd88926..8826b1bae64 100644
--- a/studio/pages/org/[slug]/usage.tsx
+++ b/studio/pages/org/[slug]/usage.tsx
@@ -7,6 +7,7 @@ import { usePermissionsQuery } from 'data/permissions/permissions-query'
import { useFlag, useSelectedOrganization } from 'hooks'
import { NextPageWithLayout } from 'types'
import { Tabs } from 'ui'
+import { Usage } from 'components/interfaces/Organization'
const OrgUsage: NextPageWithLayout = () => {
const { data: permissions } = usePermissionsQuery()
@@ -20,9 +21,9 @@ const OrgUsage: NextPageWithLayout = () => {
{selectedOrganization === undefined && (permissions ?? []).length === 0 ? (
<Loading />
) : (
- <div className="p-4 pt-0">
- <div className="space-y-3">
- <section className="mt-4">
+ <div>
+ <div className="space-y-3.5">
+ <section className="mt-4 px-4">
<h1 className="text-3xl">{selectedOrganization?.name ?? 'Organization'} settings</h1>
</section>
<nav>
@@ -37,7 +38,7 @@ const OrgUsage: NextPageWithLayout = () => {
<Tabs.Panel id="general" label="General" />
<Tabs.Panel id="team" label="Team" />
<Tabs.Panel id="billing" label="Billing" />
- <Tabs.Panel id="usage" label="Usage" />
+ <Tabs.Panel id="usage" label="Usage" className="!m-0" />
<Tabs.Panel id="invoices" label="Invoices" />
{showOAuthApps && <Tabs.Panel id="apps" label="OAuth Apps" />}
</Tabs>
@@ -45,7 +46,7 @@ const OrgUsage: NextPageWithLayout = () => {
</div>
<div className="mb-8">
- <p>Billing V2</p>
+ <Usage />
</div>
</div>
)}