Skip to content

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

chore: refactor of project usage charts to use client-side data timestamp filling

TzeYiingdf14b782eac8
diff --git a/studio/components/interfaces/Home/ProjectUsage.tsx b/studio/components/interfaces/Home/ProjectUsage.tsx
index 9e68bdc32d9..116f8016832 100644
--- a/studio/components/interfaces/Home/ProjectUsage.tsx
+++ b/studio/components/interfaces/Home/ProjectUsage.tsx
@@ -3,12 +3,13 @@ import Link from 'next/link'
import { FC, useState } from 'react'
import { useRouter } from 'next/router'
import { Button, Dropdown, IconArchive, IconChevronDown, IconDatabase, IconKey, IconZap } from 'ui'
-import ChartHandler from 'components/to-be-cleaned/Charts/ChartHandler'
import Panel from 'components/ui/Panel'
-import { DATE_FORMAT, METRICS } from 'lib/constants'
import { ChartIntervals } from 'types'
import { useParams } from 'common/hooks'
-import { useProjectLogStatsQuery } from 'data/logs/project-log-stats-query'
+import { UsageApiCounts, useProjectLogStatsQuery } from 'data/analytics/project-log-stats-query'
+import BarChart from 'components/ui/Charts/BarChart'
+import sumBy from 'lodash/sumBy'
+import useFillTimeseriesSorted from 'hooks/analytics/useFillTimeseriesSorted'
const CHART_INTERVALS: ChartIntervals[] = [
{
@@ -29,29 +30,36 @@ const ProjectUsage: FC<Props> = ({}) => {
const [interval, setInterval] = useState<string>('hourly')
- const { data, error } = useProjectLogStatsQuery({ projectRef, interval })
+ const { data, error, isLoading } = useProjectLogStatsQuery({ projectRef, interval })
const selectedInterval = CHART_INTERVALS.find((i) => i.key === interval) || CHART_INTERVALS[1]
- const startDate = dayjs()
- .subtract(selectedInterval.startValue, selectedInterval.startUnit as dayjs.ManipulateType)
- .format(DATE_FORMAT)
- const endDate = dayjs().format(DATE_FORMAT)
- const charts = data?.data
+ const startDateLocal = dayjs().subtract(
+ selectedInterval.startValue,
+ selectedInterval.startUnit as dayjs.ManipulateType
+ )
+ const endDateLocal = dayjs()
+ const charts = useFillTimeseriesSorted(
+ data?.result || [],
+ 'timestamp',
+ [
+ 'total_auth_requests',
+ 'total_rest_requests',
+ 'total_storage_requests',
+ 'total_realtime_requests',
+ ],
+ 0,
+ startDateLocal.toISOString(),
+ endDateLocal.toISOString()
+ )
const datetimeFormat = selectedInterval.format || 'MMM D, ha'
- const handleBarClick = (v: any, search: string) => {
- if (!v || !v.activePayload?.[0]?.payload) return
- // returns rechart internal tooltip data type
- const payload = v.activePayload[0].payload
- const timestamp = payload.timestamp
- const timestampDigits = String(timestamp).length
- if (timestampDigits < 16) {
- // pad unix timestamp with additional 0 and then forward
- const paddedTimestamp = String(timestamp) + '0'.repeat(16 - timestampDigits)
- router.push(`/project/${projectRef}/logs/edge-logs?te=${paddedTimestamp}`)
- } else {
- router.push(`/project/${projectRef}/logs/edge-logs?te=${timestamp}`)
- }
+ const handleBarClick = (
+ value: UsageApiCounts,
+ // TODO (ziinc): link to edge logs with correct filter applied
+ _type: 'rest' | 'realtime' | 'storage' | 'auth'
+ ) => {
+ const selected = dayjs(value.timestamp).toISOString()
+ router.push(`/project/${projectRef}/logs/edge-logs?ite=${encodeURIComponent(selected)}`)
}
return (
@@ -78,118 +86,101 @@ const ProjectUsage: FC<Props> = ({}) => {
Statistics for past {selectedInterval.label}
</span>
</div>
- <div className="">
- {startDate && endDate && (
- <>
- <div className="grid grid-cols-1 md:grid-cols-2 md:gap-4 lg:grid-cols-4 lg:gap-8">
- <Panel key="database-chart">
- <Panel.Content className="space-y-4">
- <PanelHeader
- icon={
- <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
- <IconDatabase strokeWidth={2} size={16} />
- </div>
- }
- title="Database"
- href={`/project/${projectRef}/editor`}
- />
- <ChartHandler
- startDate={startDate}
- endDate={endDate}
- attribute={'total_rest_requests'}
- label={METRICS.find((x: any) => x.key == 'total_rest_requests')?.label ?? ''}
- provider="log-stats"
- interval="1d"
- hideChartType
- customDateFormat={datetimeFormat}
- data={charts}
- isLoading={!charts && !error ? true : false}
- onBarClick={(v) => handleBarClick(v, '/rest')}
- />
- </Panel.Content>
- </Panel>
- <Panel key="auth-chart">
- <Panel.Content className="space-y-4">
- <PanelHeader
- icon={
- <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
- <IconKey strokeWidth={2} size={16} />
- </div>
- }
- title="Auth"
- href={`/project/${projectRef}/auth/users`}
- />
- <ChartHandler
- startDate={startDate}
- endDate={endDate}
- attribute={'total_auth_requests'}
- label={METRICS.find((x) => x.key == 'total_auth_requests')?.label ?? ''}
- provider="log-stats"
- interval="1d"
- hideChartType
- customDateFormat={datetimeFormat}
- data={charts}
- isLoading={!charts && !error ? true : false}
- onBarClick={(v) => handleBarClick(v, '/auth')}
- />
- </Panel.Content>
- </Panel>
- <Panel key="storage-chart">
- <Panel.Content className="space-y-4">
- <PanelHeader
- icon={
- <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
- <IconArchive strokeWidth={2} size={16} />
- </div>
- }
- title="Storage"
- href={`/project/${projectRef}/storage/buckets`}
- />
- <ChartHandler
- startDate={startDate}
- endDate={endDate}
- attribute={'total_storage_requests'}
- label={METRICS.find((x) => x.key == 'total_storage_requests')?.label ?? ''}
- provider="log-stats"
- interval="1d"
- hideChartType
- customDateFormat={datetimeFormat}
- data={charts}
- isLoading={!charts && !error ? true : false}
- onBarClick={(v) => handleBarClick(v, '/storage')}
- />
- </Panel.Content>
- </Panel>
- <Panel key="realtime-chart">
- <Panel.Content className="space-y-4">
- <PanelHeader
- icon={
- <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
- <IconZap strokeWidth={2} size={16} />
- </div>
- }
- title="Realtime"
- />
- <ChartHandler
- startDate={startDate}
- endDate={endDate}
- attribute={'total_realtime_requests'}
- label={
- METRICS.find((x: any) => x.key == 'total_realtime_requests')?.label ?? ''
- }
- provider="log-stats"
- interval="1h"
- hideChartType
- customDateFormat={datetimeFormat}
- data={charts}
- isLoading={!charts && !error ? true : false}
- onBarClick={(v) => handleBarClick(v, '/realtime')}
- />
- </Panel.Content>
- </Panel>
- </div>
- </>
- )}
+ <div className="grid grid-cols-1 md:grid-cols-2 md:gap-4 lg:grid-cols-4 lg:gap-8">
+ <Panel>
+ <Panel.Content className="space-y-4">
+ <PanelHeader
+ icon={
+ <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
+ <IconDatabase strokeWidth={2} size={16} />
+ </div>
+ }
+ title="Database"
+ href={`/project/${projectRef}/editor`}
+ />
+
+ <BarChart
+ title="REST Requests"
+ data={charts}
+ xAxisKey="timestamp"
+ yAxisKey="total_rest_requests"
+ isLoading={isLoading}
+ onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'rest')}
+ customDateFormat={datetimeFormat}
+ highlightedValue={sumBy(charts, 'total_rest_requests')}
+ />
+ </Panel.Content>
+ </Panel>
+ <Panel>
+ <Panel.Content className="space-y-4">
+ <PanelHeader
+ icon={
+ <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
+ <IconKey strokeWidth={2} size={16} />
+ </div>
+ }
+ title="Auth"
+ href={`/project/${projectRef}/auth/users`}
+ />
+ <BarChart
+ title="Auth Requests"
+ data={charts}
+ xAxisKey="timestamp"
+ yAxisKey="total_auth_requests"
+ isLoading={!charts && !error ? true : false}
+ onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'auth')}
+ customDateFormat={datetimeFormat}
+ highlightedValue={sumBy(charts || [], 'total_auth_requests')}
+ />
+ </Panel.Content>
+ </Panel>
+ <Panel>
+ <Panel.Content className="space-y-4">
+ <PanelHeader
+ icon={
+ <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
+ <IconArchive strokeWidth={2} size={16} />
+ </div>
+ }
+ title="Storage"
+ href={`/project/${projectRef}/storage/buckets`}
+ />
+
+ <BarChart
+ title="Storage Requests"
+ data={charts}
+ xAxisKey="timestamp"
+ yAxisKey="total_storage_requests"
+ isLoading={isLoading}
+ onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'storage')}
+ customDateFormat={datetimeFormat}
+ highlightedValue={sumBy(charts, 'total_storage_requests')}
+ />
+ </Panel.Content>
+ </Panel>
+ <Panel>
+ <Panel.Content className="space-y-4">
+ <PanelHeader
+ icon={
+ <div className="rounded bg-scale-600 p-1.5 text-scale-1000 shadow-sm">
+ <IconZap strokeWidth={2} size={16} />
+ </div>
+ }
+ title="Realtime"
+ />
+
+ <BarChart
+ title="Realtime Requests"
+ data={charts}
+ xAxisKey="timestamp"
+ yAxisKey="total_realtime_requests"
+ isLoading={isLoading}
+ onBarClick={(v: unknown) => handleBarClick(v as UsageApiCounts, 'realtime')}
+ customDateFormat={datetimeFormat}
+ highlightedValue={sumBy(charts, 'total_realtime_requests')}
+ />
+ </Panel.Content>
+ </Panel>
</div>
</div>
)
diff --git a/studio/components/interfaces/Home/ProjectUsageSection.tsx b/studio/components/interfaces/Home/ProjectUsageSection.tsx
index 932f22577be..2da74e27413 100644
--- a/studio/components/interfaces/Home/ProjectUsageSection.tsx
+++ b/studio/components/interfaces/Home/ProjectUsageSection.tsx
@@ -43,7 +43,7 @@ const ProjectUsageSection: FC = observer(({}) => {
<IconLoader className="animate-spin" size={14} />
<p className="text-sm">Retrieving project usage statistics</p>
</div>
- ) : hasProjectData ? (
+ ) : true ? (
<ProjectUsage />
) : (
<NewProjectPanel />
diff --git a/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 45d9dea510a..0759259ff80 100644
--- a/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -239,6 +239,7 @@ export const genChartQuery = (
return `
SELECT
+-- event-chart
timestamp_trunc(t.timestamp, ${trunc}) as timestamp,
count(t.timestamp) as count
FROM
@@ -367,7 +368,7 @@ export const useEditorHints = () => {
export const fillTimeseries = (
timeseriesData: any[],
timestampKey: string,
- valueKey: string,
+ valueKey: string | string[],
defaultValue: number,
min?: string,
max?: string
@@ -390,10 +391,21 @@ export const fillTimeseries = (
const diff = maxDate.diff(minDate, truncation as dayjs.UnitType)
for (let i = 0; i <= diff; i++) {
const dateToMaybeAdd = minDate.add(i, truncation as dayjs.ManipulateType)
+
+ const keys = typeof valueKey === 'string' ? [valueKey] : valueKey
+
+ const toMerge = keys.reduce(
+ (acc, key) => ({
+ ...acc,
+ [key]: defaultValue,
+ }),
+ {}
+ )
+
if (!dates.find((d) => isEqual(d, dateToMaybeAdd))) {
newData.push({
[timestampKey]: dateToMaybeAdd.toISOString(),
- [valueKey]: defaultValue,
+ ...toMerge,
})
}
}
diff --git a/studio/components/ui/Charts/AreaChart.tsx b/studio/components/ui/Charts/AreaChart.tsx
index d7050f5926a..8bcbacc9b62 100644
--- a/studio/components/ui/Charts/AreaChart.tsx
+++ b/studio/components/ui/Charts/AreaChart.tsx
@@ -41,7 +41,7 @@ const AreaChart: React.FC<AreaChartProps> = ({
const { Container } = useChartSize(size)
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
- if (data.length === 0) return <ChartNoData className={className} />
+ if (data.length === 0) return <ChartNoData size={size} className={className} />
const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))
const resolvedHighlightedLabel =
diff --git a/studio/components/ui/Charts/BarChart.tsx b/studio/components/ui/Charts/BarChart.tsx
index 8d371a1c89a..539de0212c7 100644
--- a/studio/components/ui/Charts/BarChart.tsx
+++ b/studio/components/ui/Charts/BarChart.tsx
@@ -37,7 +37,7 @@ const BarChart: React.FC<BarChartProps> = ({
const { Container } = useChartSize(size)
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
- if (data.length === 0) return <ChartNoData className={className} />
+ if (data.length === 0) return <ChartNoData size={size} className={className} />
const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))
const resolvedHighlightedLabel =
@@ -48,7 +48,7 @@ const BarChart: React.FC<BarChartProps> = ({
highlightedLabel
const resolvedHighlightedValue =
- (focusDataIndex !== null ? data[focusDataIndex]?.[yAxisKey] : highlightedValue)
+ focusDataIndex !== null ? data[focusDataIndex]?.[yAxisKey] : highlightedValue
return (
<div className={['flex flex-col gap-3', className].join(' ')}>
diff --git a/studio/components/ui/Charts/NoDataPlaceholder.tsx b/studio/components/ui/Charts/NoDataPlaceholder.tsx
index 6a7a7e29c72..54f36619dfe 100644
--- a/studio/components/ui/Charts/NoDataPlaceholder.tsx
+++ b/studio/components/ui/Charts/NoDataPlaceholder.tsx
@@ -1,27 +1,34 @@
import { IconBarChart2 } from 'ui'
+import { useChartSize } from './Charts.utils'
interface Props {
title?: string
message?: string
className?: string
+ size: Parameters<typeof useChartSize>[0]
}
const NoDataPlaceholder: React.FC<Props> = ({
title = 'No data to show',
message,
className = '',
-}) => (
- <div
- className={
- 'border-scale-600 flex w-full flex-col items-center justify-center space-y-2 border border-dashed text-center ' +
- className
- }
- style={{minHeight: "100px"}}
- >
- <IconBarChart2 className="text-scale-800" />
- <div>
- <p className="text-scale-1100 text-xs">{title}</p>
- {message && <p className="text-scale-900 text-xs">{message}</p>}
+ size,
+}) => {
+ const { minHeight } = useChartSize(size)
+ return (
+ <div
+ className={
+ 'border-scale-600 flex flex-grow w-full flex-col items-center justify-center space-y-2 border border-dashed text-center ' +
+ className
+ }
+ // extra 20 px for the x ticks
+ style={{ minHeight: minHeight + 20 }}
+ >
+ <IconBarChart2 className="text-scale-800" />
+ <div>
+ <p className="text-scale-1100 text-xs">{title}</p>
+ {message && <p className="text-scale-900 text-xs">{message}</p>}
+ </div>
</div>
- </div>
-)
+ )
+}
export default NoDataPlaceholder
diff --git a/studio/components/ui/Charts/StackedBarChart.tsx b/studio/components/ui/Charts/StackedBarChart.tsx
index d378cef19a8..a508960b1fd 100644
--- a/studio/components/ui/Charts/StackedBarChart.tsx
+++ b/studio/components/ui/Charts/StackedBarChart.tsx
@@ -43,7 +43,7 @@ const StackedBarChart: React.FC<Props> = ({
variant,
})
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
- if (!data || data.length === 0) return <NoDataPlaceholder />
+ if (!data || data.length === 0) return <NoDataPlaceholder size={size} />
return (
<div className="w-full">
{!hideHeader && (
diff --git a/studio/data/analytics/keys.ts b/studio/data/analytics/keys.ts
index 049d7d0a0a0..ad9e94223b1 100644
--- a/studio/data/analytics/keys.ts
+++ b/studio/data/analytics/keys.ts
@@ -30,4 +30,7 @@ export const analyticsKeys = {
'infra-monitoring',
{ attribute, startDate, endDate, interval },
] as const,
+ usageApiCounts: (projectRef: string | undefined, interval: string | undefined) =>
+ ['projects', projectRef, 'usage.api-counts', interval] as const,
}
+
diff --git a/studio/data/logs/project-log-stats-query.ts b/studio/data/analytics/project-log-stats-query.ts
similarity index 68%
rename from studio/data/logs/project-log-stats-query.ts
rename to studio/data/analytics/project-log-stats-query.ts
index b14039751e9..db294c11124 100644
--- a/studio/data/logs/project-log-stats-query.ts
+++ b/studio/data/analytics/project-log-stats-query.ts
@@ -2,14 +2,23 @@ import { useQuery, useQueryClient, UseQueryOptions } from '@tanstack/react-query
import { get } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
import { useCallback } from 'react'
-import { logKeys } from './keys'
+import { analyticsKeys } from './keys'
export type ProjectLogStatsVariables = {
projectRef?: string
interval?: string
}
-export type ProjectLogStatsResponse = any
+export type ProjectLogStatsResponse = {
+ result: UsageApiCounts[]
+}
+export interface UsageApiCounts {
+ total_auth_requests: number
+ total_storage_requests: number
+ total_rest_requests: number
+ total_realtime_requests: number
+ timestamp: string
+}
export async function getProjectLogStats(
{ projectRef, interval }: ProjectLogStatsVariables,
@@ -22,9 +31,12 @@ export async function getProjectLogStats(
throw new Error('interval is required')
}
- const response = await get(`${API_URL}/projects/${projectRef}/log-stats?interval=${interval}`, {
- signal,
- })
+ const response = await get(
+ `${API_URL}/projects/${projectRef}/analytics/endpoints/usage.api-counts?interval=${interval}`,
+ {
+ signal,
+ }
+ )
if (response.error) {
throw response.error
}
@@ -32,7 +44,7 @@ export async function getProjectLogStats(
return response as ProjectLogStatsResponse
}
-export type ProjectLogStatsData = Awaited<ReturnType<typeof getProjectLogStats>>
+export type ProjectLogStatsData = Awaited<ReturnType<ProjectLogStatsResponse>>
export type ProjectLogStatsError = unknown
export const useProjectLogStatsQuery = <TData = ProjectLogStatsData>(
@@ -43,7 +55,7 @@ export const useProjectLogStatsQuery = <TData = ProjectLogStatsData>(
}: UseQueryOptions<ProjectLogStatsData, ProjectLogStatsError, TData> = {}
) =>
useQuery<ProjectLogStatsData, ProjectLogStatsError, TData>(
- logKeys.logStats(projectRef, interval),
+ analyticsKeys.usageApiCounts(projectRef, interval),
({ signal }) => getProjectLogStats({ projectRef, interval }, signal),
{
enabled: enabled && typeof projectRef !== 'undefined' && typeof interval !== 'undefined',
@@ -56,7 +68,7 @@ export const useProjectLogStatsPrefetch = ({ projectRef, interval }: ProjectLogS
return useCallback(() => {
if (projectRef && interval) {
- client.prefetchQuery(logKeys.logStats(projectRef, interval), ({ signal }) =>
+ client.prefetchQuery(analyticsKeys.usageApiCounts(projectRef, interval), ({ signal }) =>
getProjectLogStats({ projectRef, interval }, signal)
)
}
diff --git a/studio/data/logs/keys.ts b/studio/data/logs/keys.ts
deleted file mode 100644
index c9ba47f22aa..00000000000
--- a/studio/data/logs/keys.ts
+++ /dev/null
@@ -1,4 +0,0 @@
-export const logKeys = {
- logStats: (projectRef: string | undefined, interval: string | undefined) =>
- ['projects', projectRef, 'log-stats', interval] as const,
-}
diff --git a/studio/tests/pages/projects/Logs.utils.test.js b/studio/tests/pages/projects/Logs.utils.test.js
index b705fa4c729..38f24429f9d 100644
--- a/studio/tests/pages/projects/Logs.utils.test.js
+++ b/studio/tests/pages/projects/Logs.utils.test.js
@@ -144,6 +144,19 @@ test.each([
{ timestamp: '2023-04-26T20:00:00.000Z', count: 0 },
],
},
+ // fill multiple keys in one go
+ {
+ case: 'fill beyond min/max',
+ data: [],
+ len: 2,
+ min: '2023-04-26T18:00:00.000Z',
+ max: '2023-04-26T19:00:00.000Z',
+ keys: ['count', 'other'],
+ includes: [
+ { timestamp: '2023-04-26T18:00:00.000Z', count: 0, other: 0 },
+ { timestamp: '2023-04-26T19:00:00.000Z', count: 0, other: 0 },
+ ],
+ },
])(
'fillTimeseries : $case',
({ data, len, includes, min, max, tsKey = 'timestamp', valKey = 'count', defaultVal = 0 }) => {