Skip to content

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

feat: storage report cache misses

TzeYiingb65ebe8bf9ab
diff --git a/studio/components/interfaces/Reports/Reports.constants.ts b/studio/components/interfaces/Reports/Reports.constants.ts
index 71b5f65324f..354614b26f0 100644
--- a/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/studio/components/interfaces/Reports/Reports.constants.ts
@@ -228,6 +228,50 @@ export const PRESET_CONFIG: Record<Presets, PresetConfig> = {
title: '',
queries: {},
},
+ [Presets.STORAGE]: {
+ title: 'Storage',
+ queries: {
+ cacheHitRate: {
+ queryType: 'logs',
+ // storage report does not perform any filtering
+ sql: (_filters) => `
+SELECT
+ timestamp_trunc(timestamp, hour) as timestamp,
+ countif( h.cf_cache_status in ('HIT', 'STALE', 'REVALIDATED', 'UPDATING') ) as hit_count,
+ countif( h.cf_cache_status in ('MISS', 'NONE/UNKNOWN', 'EXPIRED', 'BYPASS', 'DYNAMIC') ) as miss_count
+from edge_logs f
+ cross join unnest(f.metadata) as m
+ cross join unnest(m.request) as r
+ cross join unnest(m.response) as res
+ cross join unnest(res.headers) as h
+where starts_with(r.path, '/storage/v1/object') and r.method = 'GET'
+group by timestamp
+order by timestamp desc
+`,
+ },
+ topCacheMisses: {
+ queryType: 'logs',
+ // storage report does not perform any filtering
+ sql: (_filters) => `
+SELECT
+ r.path as path,
+ r.search as search,
+ count(id) as count
+from edge_logs f
+ cross join unnest(f.metadata) as m
+ cross join unnest(m.request) as r
+ cross join unnest(m.response) as res
+ cross join unnest(res.headers) as h
+where starts_with(r.path, '/storage/v1/object')
+ and r.method = 'GET'
+ and h.cf_cache_status in ('MISS', 'NONE/UNKNOWN', 'EXPIRED', 'BYPASS', 'DYNAMIC')
+group by path, search
+order by count desc
+limit 12
+ `,
+ },
+ },
+ },
[Presets.QUERY_PERFORMANCE]: {
title: 'Query performance',
queries: {
diff --git a/studio/components/interfaces/Reports/Reports.types.ts b/studio/components/interfaces/Reports/Reports.types.ts
index a13240a5125..900a7c0c437 100644
--- a/studio/components/interfaces/Reports/Reports.types.ts
+++ b/studio/components/interfaces/Reports/Reports.types.ts
@@ -3,6 +3,7 @@ import { DEFAULT_QUERY_PARAMS } from './Reports.constants'
export enum Presets {
API = 'api',
+ STORAGE = 'storage',
AUTH = 'auth',
QUERY_PERFORMANCE = 'query_performance',
}
diff --git a/studio/components/interfaces/Reports/renderers/StorageRenderers.tsx b/studio/components/interfaces/Reports/renderers/StorageRenderers.tsx
new file mode 100644
index 00000000000..0cc73886f19
--- /dev/null
+++ b/studio/components/interfaces/Reports/renderers/StorageRenderers.tsx
@@ -0,0 +1,83 @@
+import { TextFormatter } from 'components/interfaces/Settings/Logs/LogsFormatters'
+import Table from 'components/to-be-cleaned/Table'
+import StackedBarChart from 'components/ui/Charts/StackedBarChart'
+import { Fragment } from 'react'
+import { ReportWidgetProps, ReportWidgetRendererProps } from '../ReportWidget'
+
+export const CacheHitRateChartRenderer = (
+ props: ReportWidgetProps<{
+ timestamp: string
+ hit_count: number
+ miss_count: number
+ }>
+) => {
+ const stackedData = props.data.flatMap((datum) => [
+ {
+ timestamp: datum.timestamp,
+ count: datum.hit_count,
+ type: 'hit',
+ },
+ {
+ timestamp: datum.timestamp,
+ count: datum.miss_count,
+ type: 'miss',
+ },
+ ])
+
+ return (
+ <StackedBarChart
+ hideHeader
+ variant="percentages"
+ data={stackedData}
+ xAxisKey="timestamp"
+ yAxisKey="count"
+ stackKey="type"
+ stackColors={['brand', 'amber']}
+ />
+ )
+}
+
+export const TopCacheMissesRenderer = (
+ props: ReportWidgetRendererProps<{
+ path: string
+ search: string
+ count: number
+ }>
+) => {
+ if (props.data.length === 0) return null
+ const headerClasses = '!text-xs !py-2 p-0 font-bold !bg-scale-400'
+ const cellClasses = '!text-xs !py-2'
+
+ return (
+ <Table
+ head={
+ <>
+ <Table.th className={headerClasses}>Request</Table.th>
+ <Table.th className={headerClasses + ' text-right'}>Count</Table.th>
+ </>
+ }
+ body={
+ <>
+ {props.data.map((datum) => (
+ <Fragment key={datum.path + (datum.search || '')}>
+ <Table.tr className="p-0">
+ <Table.td className={[cellClasses].join(' ')}>
+ <div className=" truncate max-w-sm lg:max-w-lg">
+ <TextFormatter className="text-scale-1100" value={datum.path} />
+ <TextFormatter
+ className="max-w-sm text-scale-900 truncate "
+ value={decodeURIComponent(datum.search || '')}
+ />
+ </div>
+ </Table.td>
+ <Table.td className={[cellClasses, 'text-right align-top'].join(' ')}>
+ {datum.count}
+ </Table.td>
+ </Table.tr>
+ </Fragment>
+ ))}
+ </>
+ }
+ />
+ )
+}
diff --git a/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts b/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts
index 4e088fd0ae6..1595e65861b 100644
--- a/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts
+++ b/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts
@@ -1,9 +1,10 @@
import { Project } from 'types'
import { ProductMenuGroup } from 'components/ui/ProductMenu/ProductMenu.types'
+import { useFlag } from 'hooks'
export const generateReportsMenu = (project?: Project): ProductMenuGroup[] => {
const ref = project?.ref ?? 'default'
-
+ const storageReportFlag = useFlag('storageReport')
return [
{
title: '',
@@ -25,6 +26,17 @@ export const generateReportsMenu = (project?: Project): ProductMenuGroup[] => {
items: [],
label: 'NEW',
},
+ ...(storageReportFlag
+ ? [
+ {
+ name: 'Storage',
+ key: 'storage',
+ url: `/project/${ref}/reports/storage`,
+ items: [],
+ label: 'NEW',
+ },
+ ]
+ : []),
{
name: 'Database',
key: 'database',
diff --git a/studio/components/ui/Charts/Charts.constants.ts b/studio/components/ui/Charts/Charts.constants.ts
index d760c7bf7e6..1354ac68914 100644
--- a/studio/components/ui/Charts/Charts.constants.ts
+++ b/studio/components/ui/Charts/Charts.constants.ts
@@ -10,28 +10,35 @@ export const CHART_COLORS = {
}
// refer to packages/ui/radix-colors.js for full list of colors
-export const STACK_COLORS = [
- ['brand', 9],
- ['mint', 9],
- ['blue', 9],
- ['sky', 9],
- ['lime', 9],
- ['yellow', 9],
- ['orange', 9],
-].map(([color, n]) => ({
- lighter: `var(--colors-${color}${(n as number) - 1})`,
- base: `var(--colors-${color}${n})`,
- darker: `var(--colors-${color}${(n as number) + 1})`,
-}))
+export type ValidStackColor =
+ | 'brand'
+ | 'blue'
+ | 'red'
+ | 'yellow'
+ | 'green'
+ | 'slate'
+ | 'indigo'
+ | 'tomato'
+ | 'orange'
+ | 'amber'
-export const USAGE_COLORS = {
- 200: 'hsl(var(--brand-default))',
- 201: 'hsl(var(--brand-500))',
- 400: 'var(--colors-amber9)',
- 401: 'var(--colors-amber8)',
- 404: 'var(--colors-amber7)',
- 500: 'var(--colors-red9)',
-}
+export const genStackColorScales = (colors: ValidStackColor[]) =>
+ colors.map((color) => {
+ // override default base scale for certain colors that do not have good contrast
+ const scale =
+ (
+ {
+ slate: 11,
+ } as any
+ )[color] ?? 9
+ return {
+ lighter: `var(--colors-${color}${(scale as number) - 1})`,
+ base: `var(--colors-${color}${scale})`,
+ darker: `var(--colors-${color}${(scale as number) + 1})`,
+ }
+ })
+
+export const DEFAULT_STACK_COLORS = ['brand', 'slate', 'blue', 'yellow', 'indigo']
export enum DateTimeFormats {
FULL = 'MMM D, YYYY, hh:mma',
diff --git a/studio/components/ui/Charts/StackedBarChart.tsx b/studio/components/ui/Charts/StackedBarChart.tsx
index 4ce2b8e1ee8..f3123578129 100644
--- a/studio/components/ui/Charts/StackedBarChart.tsx
+++ b/studio/components/ui/Charts/StackedBarChart.tsx
@@ -1,7 +1,7 @@
import { useState } from 'react'
import { BarChart, Bar, XAxis, Tooltip, Legend, Cell, TooltipProps } from 'recharts'
import ChartHeader from './ChartHeader'
-import { CHART_COLORS, STACK_COLORS, DateTimeFormats } from './Charts.constants'
+import { CHART_COLORS, STACK_COLORS, DateTimeFormats, DEFAULT_STACK_COLORS, genStackColorScales } from './Charts.constants'
import { CommonChartProps } from './Charts.types'
import { timestampFormatter, useChartSize, useStacked } from './Charts.utils'
import { precisionFormatter } from './Charts.utils'
@@ -16,6 +16,7 @@ interface Props extends CommonChartProps<any> {
displayDateInUtc?: boolean
hideLegend?: boolean
hideHeader?: boolean
+ stackColors?: ValidStackColor
}
const StackedBarChart: React.FC<Props> = ({
size,
@@ -33,6 +34,7 @@ const StackedBarChart: React.FC<Props> = ({
displayDateInUtc,
hideLegend = false,
hideHeader = false,
+ stackColors = DEFAULT_STACK_COLORS
}) => {
const { Container } = useChartSize(size)
const { dataKeys, stackedData, percentagesStackedData } = useStacked({
@@ -44,6 +46,7 @@ const StackedBarChart: React.FC<Props> = ({
})
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
if (!data || data.length === 0) return <NoDataPlaceholder size={size} />
+ const stackColorScales = genStackColorScales(stackColors)
return (
<div className="w-full">
{!hideHeader && (
@@ -94,7 +97,7 @@ const StackedBarChart: React.FC<Props> = ({
dataKey={datum}
type="monotone"
legendType="circle"
- fill={STACK_COLORS[stackIndex].base}
+ fill={stackColorScales[stackIndex].base}
stackId={1}
animationDuration={300}
maxBarSize={48}
diff --git a/studio/pages/project/[ref]/reports/storage.tsx b/studio/pages/project/[ref]/reports/storage.tsx
new file mode 100644
index 00000000000..80047336e38
--- /dev/null
+++ b/studio/pages/project/[ref]/reports/storage.tsx
@@ -0,0 +1,114 @@
+import { observer } from 'mobx-react-lite'
+import { NextPageWithLayout } from 'types'
+import { ReportsLayout } from 'components/layouts'
+import {
+ PRESET_CONFIG,
+ REPORTS_DATEPICKER_HELPERS,
+} from 'components/interfaces/Reports/Reports.constants'
+import ReportWidget from 'components/interfaces/Reports/ReportWidget'
+import { queriesFactory } from 'components/interfaces/Reports/Reports.utils'
+import {
+ CacheHitRateChartRenderer,
+ TopCacheMissesRenderer,
+} from 'components/interfaces/Reports/renderers/StorageRenderers'
+import { useMemo } from 'react'
+import ReportHeader from 'components/interfaces/Reports/ReportHeader'
+import { DatePickerToFrom, LogsEndpointParams } from 'components/interfaces/Settings/Logs'
+import { useParams } from 'common'
+import ShimmerLine from 'components/ui/ShimmerLine'
+import ReportPadding from 'components/interfaces/Reports/ReportPadding'
+import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'
+import DatePickers from 'components/interfaces/Settings/Logs/Logs.DatePickers'
+
+export const StorageReport: NextPageWithLayout = () => {
+ const { ref: projectRef } = useParams()
+ const report = useStorageReport()
+
+ const { data: subscription } = useProjectSubscriptionV2Query({ projectRef })
+ const plan = subscription?.plan
+
+ const handleDatepickerChange = ({ from, to }: DatePickerToFrom) => {
+ report.mergeParams({
+ iso_timestamp_start: from || '',
+ iso_timestamp_end: to || '',
+ })
+ }
+
+ const datepickerHelpers = useMemo(
+ () =>
+ REPORTS_DATEPICKER_HELPERS.map((helper, index) => ({
+ ...helper,
+ disabled: (index > 0 && plan?.id === 'free') || (index > 1 && plan?.id !== 'pro'),
+ })),
+ []
+ )
+
+ return (
+ <ReportPadding>
+ <ReportHeader title="Storage" isLoading={report.isLoading} onRefresh={report.refresh} />
+ <div className="w-full flex flex-col gap-1">
+ <div>
+ <DatePickers
+ onChange={handleDatepickerChange}
+ to={report.params.cacheHitRate.iso_timestamp_end || ''}
+ from={report.params.cacheHitRate.iso_timestamp_start || ''}
+ helpers={datepickerHelpers}
+ />
+ </div>
+ <div className="h-2 w-full">
+ <ShimmerLine active={report.isLoading} />
+ </div>
+ </div>
+
+ <ReportWidget
+ isLoading={report.isLoading}
+ params={report.params.cacheHitRate}
+ title="Cache Hits"
+ data={report.data.cacheHitRate || []}
+ renderer={CacheHitRateChartRenderer}
+ append={TopCacheMissesRenderer}
+ appendProps={{ data: report.data.topCacheMisses || [] }}
+ />
+ </ReportPadding>
+ )
+}
+
+// hook to fetch data
+const useStorageReport = () => {
+ const { ref: projectRef } = useParams()
+
+ const queryHooks = queriesFactory<keyof typeof PRESET_CONFIG.storage.queries>(
+ PRESET_CONFIG.storage.queries,
+ projectRef ?? 'default'
+ )
+ const cacheHitRate = queryHooks.cacheHitRate()
+ const topCacheMisses = queryHooks.topCacheMisses()
+ const activeHooks = [cacheHitRate, topCacheMisses]
+
+ const handleRefresh = async () => {
+ activeHooks.forEach((hook) => hook.runQuery())
+ }
+ const handleSetParams = (params: Partial<LogsEndpointParams>) => {
+ activeHooks.forEach((hook) => {
+ hook.setParams?.((prev: LogsEndpointParams) => ({ ...prev, ...params }))
+ })
+ }
+ const isLoading = activeHooks.some((hook) => hook.isLoading)
+ return {
+ data: {
+ cacheHitRate: cacheHitRate.logData,
+ topCacheMisses: topCacheMisses.logData,
+ },
+ params: {
+ cacheHitRate: cacheHitRate.params,
+ topCacheMisses: topCacheMisses.params,
+ },
+ mergeParams: handleSetParams,
+ isLoading,
+ refresh: handleRefresh,
+ }
+}
+
+StorageReport.getLayout = (page) => <ReportsLayout>{page}</ReportsLayout>
+
+export default observer(StorageReport)