Skip to content

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

feat: daily stats for compute (#19414)

Kevin Grüneberg771948c1a6c1
diff --git a/apps/studio/components/interfaces/Organization/Usage/Compute.tsx b/apps/studio/components/interfaces/Organization/Usage/Compute.tsx
new file mode 100644
index 00000000000..898f9793f16
--- /dev/null
+++ b/apps/studio/components/interfaces/Organization/Usage/Compute.tsx
@@ -0,0 +1,151 @@
+import { DataPoint } from 'data/analytics/constants'
+import { ComputeUsageMetric, computeUsageMetricLabel } from 'data/analytics/org-daily-stats-query'
+import { OrgSubscription } from 'data/subscriptions/org-subscription-query'
+import SectionContent from './SectionContent'
+import ShimmeringLoader, { GenericSkeletonLoader } from 'components/ui/ShimmeringLoader'
+import AlertError from 'components/ui/AlertError'
+import Panel from 'components/ui/Panel'
+import { IconBarChart2 } from 'ui'
+import UsageBarChart from './UsageBarChart'
+import { Attribute, AttributeColor } from './Usage.constants'
+import { useMemo } from 'react'
+import { useOrgDailyComputeStatsQuery } from 'data/analytics/org-daily-compute-stats-query'
+
+export interface ComputeProps {
+ orgSlug: string
+ projectRef?: string
+ startDate: string | undefined
+ endDate: string | undefined
+ subscription: OrgSubscription | undefined
+}
+
+const Compute = ({ orgSlug, projectRef, startDate, endDate }: ComputeProps) => {
+ const allAttributeKeys = Object.values(ComputeUsageMetric).map((it) => it.toLowerCase())
+ const {
+ data: egressData,
+ isLoading,
+ error,
+ isSuccess,
+ } = useOrgDailyComputeStatsQuery({
+ orgSlug,
+ projectRef,
+ startDate,
+ endDate,
+ })
+
+ const chartData: DataPoint[] = egressData?.data ?? []
+
+ const COMPUTE_TO_COLOR: Record<ComputeUsageMetric, AttributeColor> = {
+ [ComputeUsageMetric.COMPUTE_HOURS_BRANCH]: 'blue',
+ [ComputeUsageMetric.COMPUTE_HOURS_XS]: 'white',
+ [ComputeUsageMetric.COMPUTE_HOURS_SM]: 'green',
+ [ComputeUsageMetric.COMPUTE_HOURS_MD]: 'dark-green',
+ [ComputeUsageMetric.COMPUTE_HOURS_L]: 'yellow',
+ [ComputeUsageMetric.COMPUTE_HOURS_XL]: 'dark-yellow',
+ [ComputeUsageMetric.COMPUTE_HOURS_2XL]: 'orange',
+ [ComputeUsageMetric.COMPUTE_HOURS_4XL]: 'dark-orange',
+ [ComputeUsageMetric.COMPUTE_HOURS_8XL]: 'red',
+ [ComputeUsageMetric.COMPUTE_HOURS_12XL]: 'dark-red',
+ [ComputeUsageMetric.COMPUTE_HOURS_16XL]: 'purple',
+ }
+
+ const attributes: Attribute[] = Object.keys(ComputeUsageMetric).map((it) => ({
+ key: it.toLowerCase(),
+ color: COMPUTE_TO_COLOR[it as ComputeUsageMetric] || 'white',
+ name: computeUsageMetricLabel(it as ComputeUsageMetric),
+ }))
+
+ const attributeKeysWithData = useMemo(() => {
+ return allAttributeKeys.filter((attributeKey) => chartData.some((data) => data[attributeKey]))
+ }, [chartData])
+
+ const notAllValuesZero = useMemo(() => {
+ return attributeKeysWithData.length > 0
+ }, [attributeKeysWithData])
+
+ return (
+ <div id="compute" className="scroll-my-12">
+ <SectionContent
+ section={{
+ name: 'Compute Hours',
+ description:
+ 'Amount of hours your projects were active. Each project is a dedicated server and database.\nPaid plans come with $10 in Compute Credits to cover one project running on Starter Compute or parts of any compute add-on.\nBilling is based on the sum of Compute Hours used. Paused projects do not count towards usage.',
+ links: [
+ {
+ name: 'Compute Add-ons',
+ url: 'https://supabase.com/docs/guides/platform/compute-add-ons',
+ },
+ {
+ name: 'Usage-billing for Compute',
+ url: 'https://supabase.com/docs/guides/platform/org-based-billing#usage-based-billing-for-compute',
+ },
+ ],
+ }}
+ >
+ {isLoading && <GenericSkeletonLoader />}
+
+ {error != null && <AlertError subject="Failed to retrieve usage data" error={error} />}
+
+ {isSuccess && (
+ <>
+ <div className="space-y-1">
+ {chartData.length > 0 && (
+ <div className="flex items-center justify-between">
+ <div className="flex items-center space-x-4">
+ <p className="text-sm">Compute Hours usage</p>
+ </div>
+ </div>
+ )}
+
+ {attributeKeysWithData.map((key) => (
+ <div
+ key={key}
+ className="flex items-center justify-between border-b last:border-b-0 py-1 last:py-0"
+ >
+ <p className="text-sm text-foreground-light">
+ <span className="font-medium">
+ {computeUsageMetricLabel(key.toUpperCase() as ComputeUsageMetric)}
+ </span>{' '}
+ Compute Hours usage in period
+ </p>
+ <p className="text-sm">
+ {chartData.reduce((prev, cur) => prev + ((cur[key] as number) ?? 0), 0)} hours
+ </p>
+ </div>
+ ))}
+ </div>
+
+ <div className="space-y-1">
+ <p className="text-sm">Compute Hours usage per day</p>
+ <p className="text-sm text-foreground-light">The data refreshes every hour.</p>
+ </div>
+
+ {isLoading ? (
+ <GenericSkeletonLoader />
+ ) : chartData.length > 0 && notAllValuesZero ? (
+ <UsageBarChart
+ name={`Compute Hours usage`}
+ unit={'hours'}
+ attributes={attributes}
+ data={chartData}
+ yMin={24}
+ />
+ ) : (
+ <Panel>
+ <Panel.Content>
+ <div className="flex flex-col items-center justify-center">
+ <IconBarChart2 className="text-foreground-light mb-2" />
+ <p className="text-sm">No data in period</p>
+ <p className="text-sm text-foreground-light">May take up to one hour to show</p>
+ </div>
+ </Panel.Content>
+ </Panel>
+ )}
+ </>
+ )}
+ </SectionContent>
+ </div>
+ )
+}
+
+export default Compute
diff --git a/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx b/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx
index 1f049b2497b..b17ef43462c 100644
--- a/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/SectionContent.tsx
@@ -5,7 +5,7 @@ import { Badge, IconExternalLink } from 'ui'
import { CategoryAttribute } from './Usage.constants'
export interface SectionContent {
- section: CategoryAttribute
+ section: Pick<CategoryAttribute, 'name' | 'description' | 'links'>
includedInPlan?: boolean
}
diff --git a/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx b/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
index 29448815c20..3dc11511099 100644
--- a/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/Usage.constants.tsx
@@ -6,10 +6,16 @@ import { Alert } from 'ui'
export const COLOR_MAP = {
white: { bar: 'fill-foreground', marker: 'bg-foreground' },
- green: { bar: 'fill-green-1000', marker: 'bg-green-1000' },
- blue: { bar: 'fill-blue-1000', marker: 'bg-blue-1000' },
- yellow: { bar: 'fill-amber-1000', marker: 'bg-amber-1000' },
- orange: { bar: 'fill-orange-1000', marker: 'bg-orange-1000' },
+ green: { bar: 'fill-green-800', marker: 'bg-green-800' },
+ 'dark-green': { bar: 'fill-green-1000', marker: 'bg-green-1000' },
+ blue: { bar: 'fill-blue-900', marker: 'bg-blue-900' },
+ yellow: { bar: 'fill-yellow-800', marker: 'bg-yellow-800' },
+ 'dark-yellow': { bar: 'fill-yellow-1000', marker: 'bg-yellow-1000' },
+ orange: { bar: 'fill-orange-800', marker: 'bg-orange-800' },
+ 'dark-orange': { bar: 'fill-orange-1000', marker: 'bg-orange-1100' },
+ red: { bar: 'fill-red-800', marker: 'bg-red-800' },
+ 'dark-red': { bar: 'fill-red-1000', marker: 'bg-red-1000' },
+ purple: { bar: 'fill-purple-900', marker: 'bg-purple-900' },
}
export const Y_DOMAIN_CEILING_MULTIPLIER = 4 / 3
@@ -20,17 +26,30 @@ export const USAGE_STATUS = {
EXCEEDED: 'EXCEEDED',
}
+export type AttributeColor =
+ | 'white'
+ | 'blue'
+ | 'green'
+ | 'yellow'
+ | 'orange'
+ | 'purple'
+ | 'red'
+ | 'dark-red'
+ | 'dark-orange'
+ | 'dark-yellow'
+ | 'dark-green'
+
export interface Attribute {
key: string
name?: string
- color: 'white' | 'blue' | 'green' | 'yellow' | 'orange'
+ color: AttributeColor
}
export interface CategoryAttribute {
anchor: string
key: string // Property from organization usage
attributes: Attribute[] // For querying against stats-daily / infra-monitoring
name: string
- unit: 'bytes' | 'absolute' | 'percentage'
+ unit: 'bytes' | 'absolute' | 'percentage' | 'hours'
links?: {
name: string
url: string
@@ -42,10 +61,10 @@ export interface CategoryAttribute {
additionalInfo?: (subscription?: OrgSubscription, usage?: OrgUsageResponse) => JSX.Element | null
}
-export type CategoryMetaKey = 'bandwidth' | 'sizeCount' | 'activity'
+export type CategoryMetaKey = 'bandwidth' | 'sizeCount' | 'activity' | 'compute'
export interface CategoryMeta {
- key: 'bandwidth' | 'sizeCount' | 'activity'
+ key: CategoryMetaKey
name: string
description: string
attributes: CategoryAttribute[]
@@ -250,7 +269,7 @@ export const USAGE_CATEGORIES: CategoryMeta[] = [
anchor: 'realtimeMessageCount',
key: PricingMetric.REALTIME_MESSAGE_COUNT,
attributes: [{ key: PricingMetric.REALTIME_MESSAGE_COUNT.toLowerCase(), color: 'white' }],
- name: 'Realtime Message Count',
+ name: 'Realtime Messages',
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.",
diff --git a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
index 6fd28587f65..8b97c49e296 100644
--- a/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/Usage.tsx
@@ -18,6 +18,7 @@ import { Alert, Button, IconExternalLink, IconInfo, Listbox } from 'ui'
import Activity from './Activity'
import Bandwidth from './Bandwidth'
import SizeAndCounts from './SizeAndCounts'
+import Compute from './Compute'
const Usage = () => {
const { slug, projectRef } = useParams()
@@ -228,6 +229,14 @@ const Usage = () => {
</ScaffoldContainer>
)}
+ <Compute
+ orgSlug={slug as string}
+ projectRef={selectedProjectRef}
+ subscription={subscription}
+ startDate={startDate}
+ endDate={endDate}
+ />
+
<Bandwidth
orgSlug={slug as string}
projectRef={selectedProjectRef}
diff --git a/apps/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx b/apps/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx
index aa5e7047f70..003943ddfa5 100644
--- a/apps/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/UsageBarChart.tsx
@@ -21,8 +21,9 @@ export interface UsageBarChartProps {
data: DataPoint[]
name: string // Used within the tooltip
attributes: Attribute[]
- unit: 'bytes' | 'absolute' | 'percentage'
+ unit: 'bytes' | 'absolute' | 'percentage' | 'hours'
yLimit?: number
+ yMin?: number
yLeftMargin?: number
yFormatter?: (value: number | string) => string
tooltipFormatter?: (value: number | string) => string
@@ -36,10 +37,10 @@ const UsageBarChart = ({
yLimit,
yLeftMargin = 10,
yFormatter,
+ yMin,
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]
+ const yDomain = [yMin ?? 0, Math.max(yMin ?? 0, yLimit ?? 0)]
return (
<div className="w-full h-[200px]">
@@ -77,6 +78,7 @@ const UsageBarChart = ({
values={payload}
isAfterToday={isAfterToday}
tooltipFormatter={tooltipFormatter}
+ unit={unit}
/>
) : (
<SingleAttributeTooltipContent
diff --git a/apps/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx b/apps/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx
index a10feab2f63..ea59cdd0649 100644
--- a/apps/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx
+++ b/apps/studio/components/interfaces/Organization/Usage/UsageChartTooltips.tsx
@@ -4,7 +4,7 @@ import { Attribute, COLOR_MAP } from './Usage.constants'
export interface SingleAttributeTooltipContentProps {
name: string
- unit: 'bytes' | 'percentage' | 'absolute'
+ unit: 'bytes' | 'percentage' | 'absolute' | 'hours'
value: any
isAfterToday: boolean
tooltipFormatter?: (value: any) => any
@@ -37,6 +37,7 @@ export interface MultiAttributeTooltipContentProps {
values: Payload<ValueType, string | number>[]
isAfterToday: boolean
tooltipFormatter?: (value: any) => any
+ unit: 'bytes' | 'percentage' | 'absolute' | 'hours'
}
const AttributeContent = ({
@@ -44,25 +45,29 @@ const AttributeContent = ({
attributeMeta,
sumValue,
tooltipFormatter,
+ unit,
}: {
attribute: Attribute
attributeMeta?: Payload<ValueType, string | number>
sumValue: number
tooltipFormatter?: (value: any) => any
+ unit: 'bytes' | 'percentage' | 'absolute' | 'hours'
}) => {
const attrValue = Number(attributeMeta?.value ?? 0)
const percentageContribution = ((attrValue / sumValue) * 100).toFixed(1)
return (
<div key={attribute.name} className="flex items-center justify-between">
- <div className="flex items-center space-x-2 w-[200px]">
+ <div className="flex items-center space-x-2 w-[175px]">
<div className={clsx('w-3 h-3 rounded-full border', COLOR_MAP[attribute.color].marker)} />
<p className="text-xs prose">
{attribute.name} ({percentageContribution}%):{' '}
</p>
</div>
<p className="text-xs tabular-nums">
- {tooltipFormatter !== undefined ? tooltipFormatter(attrValue) : attrValue}
+ {tooltipFormatter !== undefined
+ ? tooltipFormatter(attrValue)
+ : `${attrValue}${unit === 'hours' ? ' H' : ''}`}
</p>
</div>
)
@@ -73,6 +78,7 @@ export const MultiAttributeTooltipContent = ({
values,
isAfterToday,
tooltipFormatter,
+ unit,
}: MultiAttributeTooltipContentProps) => {
const sumValue = values.reduce((a, b) => a + Number(b.value), 0)
return (
@@ -94,6 +100,7 @@ export const MultiAttributeTooltipContent = ({
attributeMeta={attributeMeta}
sumValue={sumValue}
tooltipFormatter={tooltipFormatter}
+ unit={unit}
/>
)
})}
diff --git a/apps/studio/data/analytics/keys.ts b/apps/studio/data/analytics/keys.ts
index 4d7f028cc8c..9f1cee14020 100644
--- a/apps/studio/data/analytics/keys.ts
+++ b/apps/studio/data/analytics/keys.ts
@@ -57,6 +57,29 @@ export const analyticsKeys = {
},
] as const,
+ orgDailyComputeStats: (
+ orgSlug: string | undefined,
+ {
+ startDate,
+ endDate,
+ projectRef,
+ }: {
+ startDate?: string
+ endDate?: string
+ projectRef?: string
+ }
+ ) =>
+ [
+ 'organizations',
+ orgSlug,
+ 'daily-stats-compute',
+ {
+ startDate: isoDateStringToDate(startDate),
+ endDate: isoDateStringToDate(endDate),
+ projectRef,
+ },
+ ] as const,
+
orgDailyStats: (
orgSlug: string | undefined,
{
diff --git a/apps/studio/data/analytics/org-daily-compute-stats-query.ts b/apps/studio/data/analytics/org-daily-compute-stats-query.ts
new file mode 100644
index 00000000000..a4bf2e24e1f
--- /dev/null
+++ b/apps/studio/data/analytics/org-daily-compute-stats-query.ts
@@ -0,0 +1,75 @@
+import { useQuery, UseQueryOptions } from '@tanstack/react-query'
+import dayjs from 'dayjs'
+import { get } from 'data/fetchers'
+import { AnalyticsData } from './constants'
+import { analyticsKeys } from './keys'
+import { ResponseError } from 'types'
+
+export type OrgDailyComputeStatsVariables = {
+ // API parameters
+ orgSlug?: string
+ startDate?: string
+ endDate?: string
+ projectRef?: string
+ // Client specific
+ dateFormat?: string
+ modifier?: (x: number) => number
+}
+
+export async function getOrgDailyComputeStats(
+ { orgSlug, startDate, endDate, projectRef }: OrgDailyComputeStatsVariables,
+ signal?: AbortSignal
+) {
+ if (!orgSlug) throw new Error('Org slug is required')
+ if (!startDate) throw new Error('Start date is required')
+ if (!endDate) throw new Error('End date is required')
+
+ let endpoint = `/platform/organizations/{slug}/daily-stats/compute?&startDate=${encodeURIComponent(
+ startDate
+ )}&endDate=${encodeURIComponent(endDate)}`
+
+ if (projectRef) endpoint += `&projectRef=${projectRef}`
+
+ const { data, error } = await get('/platform/organizations/{slug}/daily-stats/compute', {
+ params: { path: { slug: orgSlug }, query: { projectRef, startDate, endDate } },
+ signal,
+ })
+ if (error) throw error
+ return data as AnalyticsData
+}
+
+export type OrgDailyComputeStatsData = Awaited<ReturnType<typeof getOrgDailyComputeStats>>
+export type OrgDailyComputeStatsError = ResponseError
+
+export const useOrgDailyComputeStatsQuery = <TData = OrgDailyComputeStatsData>(
+ { orgSlug, startDate, endDate, projectRef, dateFormat = 'DD MMM' }: OrgDailyComputeStatsVariables,
+ {
+ enabled = true,
+ ...options
+ }: UseQueryOptions<OrgDailyComputeStatsData, OrgDailyComputeStatsError, TData> = {}
+) =>
+ useQuery<OrgDailyComputeStatsData, OrgDailyComputeStatsError, TData>(
+ analyticsKeys.orgDailyComputeStats(orgSlug, { startDate, endDate, projectRef }),
+ ({ signal }) => getOrgDailyComputeStats({ orgSlug, startDate, endDate, projectRef }, signal),
+ {
+ enabled:
+ enabled &&
+ typeof orgSlug !== 'undefined' &&
+ typeof startDate !== 'undefined' &&
+ typeof endDate !== 'undefined',
+
+ select(data) {
+ return {
+ ...data,
+ data: data.data.map((x) => {
+ return {
+ ...x,
+ periodStartFormatted: dayjs(x.period_start).format(dateFormat),
+ }
+ }),
+ } as TData
+ },
+ staleTime: 1000 * 60 * 60, // default good for an hour for now
+ ...options,
+ }
+ )
diff --git a/apps/studio/data/analytics/org-daily-stats-query.ts b/apps/studio/data/analytics/org-daily-stats-query.ts
index 10aa9ec597a..8425f04ea8d 100644
--- a/apps/studio/data/analytics/org-daily-stats-query.ts
+++ b/apps/studio/data/analytics/org-daily-stats-query.ts
@@ -16,9 +16,7 @@ export enum EgressType {
// [Joshen] Get this from common package instead of API and dashboard having one copy each
export enum PricingMetric {
EGRESS = 'EGRESS',
- DATABASE_EGRESS = 'DATABASE_EGRESS',
DATABASE_SIZE = 'DATABASE_SIZE',
- STORAGE_EGRESS = 'STORAGE_EGRESS',
STORAGE_SIZE = 'STORAGE_SIZE',
MONTHLY_ACTIVE_USERS = 'MONTHLY_ACTIVE_USERS',
MONTHLY_ACTIVE_SSO_USERS = 'MONTHLY_ACTIVE_SSO_USERS',
@@ -30,6 +28,7 @@ export enum PricingMetric {
}
export enum ComputeUsageMetric {
+ COMPUTE_HOURS_BRANCH = 'COMPUTE_HOURS_BRANCH',
COMPUTE_HOURS_XS = 'COMPUTE_HOURS_XS',
COMPUTE_HOURS_SM = 'COMPUTE_HOURS_SM',
COMPUTE_HOURS_MD = 'COMPUTE_HOURS_MD',
@@ -42,6 +41,33 @@ export enum ComputeUsageMetric {
COMPUTE_HOURS_16XL = 'COMPUTE_HOURS_16XL',
}
+export const computeUsageMetricLabel = (computeUsageMetric: ComputeUsageMetric) => {
+ switch (computeUsageMetric) {
+ case 'COMPUTE_HOURS_BRANCH':
+ return 'Branches'
+ case 'COMPUTE_HOURS_XS':
+ return 'Starter'
+ case 'COMPUTE_HOURS_SM':
+ return 'Small'
+ case 'COMPUTE_HOURS_MD':
+ return 'Medium'
+ case 'COMPUTE_HOURS_L':
+ return 'Large'
+ case 'COMPUTE_HOURS_XL':
+ return 'XL'
+ case 'COMPUTE_HOURS_2XL':
+ return '2XL'
+ case 'COMPUTE_HOURS_4XL':
+ return '4XL'
+ case 'COMPUTE_HOURS_8XL':
+ return '8XL'
+ case 'COMPUTE_HOURS_12XL':
+ return '12XL'
+ case 'COMPUTE_HOURS_16XL':
+ return '16XL'
+ }
+}
+
export type OrgDailyStatsVariables = {
// API parameters
orgSlug?: string