The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: initial implementation of api performance report
TzeYiingbfcf1d74953f
diff --git a/packages/ui/src/components/Loading/Loading.tsx b/packages/ui/src/components/Loading/Loading.tsxindex fe5de53dff5..dec0a6f96d6 100644--- a/packages/ui/src/components/Loading/Loading.tsx+++ b/packages/ui/src/components/Loading/Loading.tsx@@ -5,13 +5,15 @@ import { IconLoader } from './../../../index'interface Props {children: React.ReactNodeactive: boolean+ className?: string+ contentClassName?: string}-export default function Loading({ children, active }: Props) {+export default function Loading({ children, active, className, contentClassName }: Props) {const __styles = styleHandler('loading')- let classNames = [__styles.base]+ let classNames = [__styles.base, className]- let contentClasses = [__styles.content.base]+ let contentClasses = [__styles.content.base, contentClassName]if (active) {contentClasses.push(__styles.content.active)diff --git a/studio/components/interfaces/Reports/ReportFilterBar.tsx b/studio/components/interfaces/Reports/ReportFilterBar.tsxnew file mode 100644index 00000000000..376842161e8--- /dev/null+++ b/studio/components/interfaces/Reports/ReportFilterBar.tsx@@ -0,0 +1,209 @@+import { keyBy } from 'lodash'+import React from 'react'+import { useState } from 'react'+import { Dropdown, Popover, Button, IconPlus, IconChevronDown, Select, Input, IconX } from 'ui'+import DatePickers from '../Settings/Logs/Logs.DatePickers'+import { REPORTS_DATEPICKER_HELPERS } from './Reports.constants'+import { ReportFilterItem } from './Reports.types'++interface Props {+ filters: ReportFilterItem[]+ onAddFilter: (filter: ReportFilterItem) => void+ onRemoveFilter: (filter: ReportFilterItem) => void+}++const ReportFilterBar: React.FC<Props> = ({ filters, onAddFilter, onRemoveFilter }) => {+ const filterKeys = ['request.path', 'request.host' , 'response.status_code']+ const [showAdder, setShowAdder] = useState(false)+ const [addFilterValues, setAddFilterValues] = useState<ReportFilterItem>({+ key: filterKeys[0],+ compare: 'is',+ value: '',+ })++ const resetFilterValues = () => {+ setAddFilterValues({+ key: filterKeys[0],+ compare: 'is',+ value: '',+ })+ }++ const handleProductFilterChange = async (+ filterToRemove: ReportFilterItem | null,+ key: string+ ) => {+ if (filterToRemove) {+ await onRemoveFilter(filterToRemove)+ }+ if (key !== 'all') {+ await onAddFilter({+ key: 'request.path',+ compare: 'matches',+ value: `/${key}/`,+ })+ }+ }+ const getPathFilterMatchValue = (filter: ReportFilterItem) => {+ return [...String(filter.value).matchAll(/\/(storage|realtime|auth|functions)\//g)]+ }+ const currentProductFilter =+ filters.find((filter) => {+ const matches = getPathFilterMatchValue(filter)+ if (filter.key == 'request.path' && matches.length > 0) {+ return true+ } else {+ return false+ }+ }) || null++ const currentProductFilterKey = currentProductFilter+ ? getPathFilterMatchValue(currentProductFilter)[0][1]+ : 'all'+ return (+ <div>+ <div className="flex flex-row justify-start items-center flex-wrap gap-2">+ <Dropdown+ size="small"+ side="bottom"+ align="start"+ overlay={+ <>+ <Dropdown.Item onClick={() => handleProductFilterChange(currentProductFilter, 'all')}>+ All+ </Dropdown.Item>+ <Dropdown.Separator />+ {[+ { key: 'rest', label: 'REST' },+ { key: 'auth', label: 'Auth' },+ { key: 'storage', label: 'Storage' },+ { key: 'realtime', label: 'Realtime' },+ { key: 'functions', label: 'Functions' },+ { key: 'graphql', label: 'GraphQL' },+ ].map(({ key, label }) => (+ <Dropdown.Item+ key={key}+ disabled={key === currentProductFilterKey}+ onClick={() => handleProductFilterChange(currentProductFilter, key)}+ >+ <span className={[key === currentProductFilterKey ? 'font-bold' : ''].join(' ')}>+ {label}+ </span>+ </Dropdown.Item>+ ))}+ </>+ }+ >+ <Button+ as="span"+ type="default"+ className="inline-flex flex-row gap-2"+ iconRight={<IconChevronDown size={14} />}+ >+ {currentProductFilterKey === 'all'+ ? 'All'+ : `${currentProductFilterKey+ .slice(0, 1)+ .toUpperCase()}${currentProductFilterKey.slice(+ 1,+ currentProductFilterKey.length+ )}`}+ </Button>+ </Dropdown>+ {filters+ .filter((filter) => filter !== currentProductFilter)+ .map((filter) => (+ <div className="text-xs rounded border border-scale-1100 bg-scale-500 px-1 h-7 flex flex-row justify-center gap-1 items-center">+ {filter.key} {filter.compare} {filter.value}+ <Button+ type="text"+ size="tiny"+ className="!p-0 h-6 w-6 flex flex-row justify-center items-center"+ onClick={() => {+ onRemoveFilter(filter)+ }}+ icon={<IconX size="tiny" className="text-scale-1100" />}+ >+ <span className="sr-only">Remove</span>+ </Button>+ </div>+ ))}+ <Popover+ align="end"+ header={+ <div className="flex justify-between items-center py-1">+ <h5 className="text-sm text-scale-1200">Add Filter</h5>++ <Button+ type="primary"+ size="tiny"+ onClick={() => {+ onAddFilter(addFilterValues)+ setShowAdder(false)+ resetFilterValues()+ }}+ >+ Save+ </Button>+ </div>+ }+ open={showAdder}+ onOpenChange={(openValue) => setShowAdder(openValue)}+ overlay={[+ <div className="px-3 py-3 flex flex-col gap-2">+ <Select+ size="tiny"+ value={addFilterValues.key}+ onChange={(e) => {+ setAddFilterValues((prev) => ({ ...prev, key: e.target.value }))+ }}+ label="Attribute Filter"+ defaultValue={'request.host'}+ >+ {filterKeys.map((key) => (+ <Select.Option key={key} value={key}>+ {key}+ </Select.Option>+ ))}+ </Select>+ <Select+ size="tiny"+ value={addFilterValues.compare}+ onChange={(e) => {+ setAddFilterValues((prev) => ({+ ...prev,+ compare: e.target.value as ReportFilterItem['compare'],+ }))+ }}+ label="Comparison"+ >+ {['matches', 'is'].map((value) => (+ <Select.Option key={value} value={value}>+ {value}+ </Select.Option>+ ))}+ </Select>+ <Input+ size="tiny"+ label="Value"+ onChange={(e) => {+ setAddFilterValues((prev) => ({ ...prev, value: e.target.value }))+ }}+ />+ </div>,+ ]}+ showClose+ >+ <Button+ type="default"+ size="tiny"+ icon={<IconPlus size="tiny" className={`text-scale-1100 `} />}+ >+ Add filter+ </Button>+ </Popover>+ </div>+ </div>+ )+}+export default ReportFilterBardiff --git a/studio/components/interfaces/Reports/ReportHeader.tsx b/studio/components/interfaces/Reports/ReportHeader.tsxnew file mode 100644index 00000000000..da3cdc35b1c--- /dev/null+++ b/studio/components/interfaces/Reports/ReportHeader.tsx@@ -0,0 +1,48 @@+import { Button, IconRefreshCw } from 'ui'+import DatePickers from '../Settings/Logs/Logs.DatePickers'+import { REPORTS_DATEPICKER_HELPERS } from './Reports.constants'++interface Props {+ title: string+ onDatepickerChange: React.ComponentProps<typeof DatePickers>['onChange']+ datepickerTo?: string+ datepickerFrom?: string+ onRefresh: () => void+ isLoading: boolean+}++const ReportHeader: React.FC<Props> = ({+ title,+ onDatepickerChange,+ datepickerTo = '',+ datepickerFrom = '',+ onRefresh,+ isLoading,+}) => (+ <div className="flex flex-col gap-4">+ <h1 className="text-2xl text-scale-1200">{title}</h1>+ <div className="flex flex-row justify-start gap-4">+ <DatePickers+ onChange={onDatepickerChange}+ to={datepickerTo}+ from={datepickerFrom}+ helpers={REPORTS_DATEPICKER_HELPERS}+ />+ <Button+ type="default"+ size="tiny"+ onClick={onRefresh}+ disabled={isLoading ? true : false}+ icon={+ <IconRefreshCw+ size="tiny"+ className={`text-scale-1100 ${isLoading ? 'animate-spin' : ''}`}+ />+ }+ >+ Refresh+ </Button>+ </div>+ </div>+)+export default ReportHeaderdiff --git a/studio/components/interfaces/Reports/ReportWidget.tsx b/studio/components/interfaces/Reports/ReportWidget.tsxindex 41f0a39dcaa..10aeca87f21 100644--- a/studio/components/interfaces/Reports/ReportWidget.tsx+++ b/studio/components/interfaces/Reports/ReportWidget.tsx@@ -28,7 +28,7 @@ const ReportWidget: React.FC<ReportWidgetProps> = (props) => {bodyClassName="h-full"wrapWithLoading={false}>- <Panel.Content className="space-y-4">+ <Panel.Content className="space-y-4 "><div className="flex flex-row items-start justify-between"><div className="gap-2"><div className="flex flex-row gap-2">@@ -86,7 +86,7 @@ const ReportWidget: React.FC<ReportWidgetProps> = (props) => {</Dropdown></div>- <LoadingOpacity active={props.isLoading}>{props.data === undefined ? null : props.renderer(props)}</LoadingOpacity>+ <LoadingOpacity className="w-full" active={props.isLoading}>{props.data === undefined ? null : props.renderer(props)}</LoadingOpacity></Panel.Content></Panel>)diff --git a/studio/components/interfaces/Reports/Reports.constants.ts b/studio/components/interfaces/Reports/Reports.constants.tsindex 17183a514bc..fd5a45c8f56 100644--- a/studio/components/interfaces/Reports/Reports.constants.ts+++ b/studio/components/interfaces/Reports/Reports.constants.ts@@ -1,21 +1,25 @@import dayjs from 'dayjs'import { DatetimeHelper } from '../Settings/Logs'-import { PresetConfig, Presets } from './Reports.types'+import { PresetConfig, Presets, ReportFilterItem } from './Reports.types'export const LAYOUT_COLUMN_COUNT = 24export const REPORTS_DATEPICKER_HELPERS: DatetimeHelper[] = [+ {+ text: 'Last 24 Hours',+ calcFrom: () => dayjs().subtract(1, 'day').startOf('day').toISOString(),+ calcTo: () => '',+ default: true,+ },{text: 'Last 7 days',calcFrom: () => dayjs().subtract(7, 'day').startOf('day').toISOString(),calcTo: () => '',- default: true,},{text: 'Last 14 days',calcFrom: () => dayjs().subtract(7, 'day').startOf('day').toISOString(),calcTo: () => '',- default: true,},{text: 'Last 30 days',@@ -29,218 +33,90 @@ export const DEFAULT_QUERY_PARAMS = {iso_timestamp_end: REPORTS_DATEPICKER_HELPERS[0].calcTo(),}+const generateRexepWhere = (filters: ReportFilterItem[], prepend=true) => {+ if (filters.length === 0) return ''+ const conditions = filters+ .map((filter) => {+ if (filter.compare === "matches"){+ return `REGEXP_CONTAINS(${filter.key}, '${filter.value}')`+ } else if (filter.compare === "is") {+ return `${filter.key} = ${filter.value}`+ }+ })+ .join(' AND ')+ if (prepend){+ return 'WHERE ' + conditions++ } else {+ return conditions+ }+}+export const PRESET_CONFIG: Record<Presets, PresetConfig> = {[Presets.API]: {title: 'API',queries: {- statusCodes: {+ totalRequests: {queryType: 'logs',- sql: `+ sql: (filters) => `select- timestamp_trunc(timestamp, hour) as timestamp,- r.status_code as status_code,- count(status_code) as count+ cast(timestamp_trunc(t.timestamp, hour) as datetime) as timestamp,+ count(t.id) as countFROM- edge_logs- CROSS JOIN UNNEST(metadata) AS m- CROSS JOIN UNNEST(m.response) AS r+ edge_logs t+ cross join unnest(metadata) as m+ cross join unnest(m.response) as response+ cross join unnest(m.request) as request+ ${generateRexepWhere(filters)}GROUP BY- timestamp,- status_code+ timestampORDER BYtimestamp ASC`,},- errorRates: {+ errorCounts: {queryType: 'logs',- sql: `+ sql: (filters) => `select- timestamp_trunc(timestamp, hour) as timestamp,- count(timestamp) as count+ cast(timestamp_trunc(t.timestamp, hour) as datetime) as timestamp,+ count(t.id) as countFROM- edge_logs- LEFT JOIN UNNEST(metadata) AS f1 ON TRUE- LEFT JOIN UNNEST(f1.response) AS f3 ON TRUE+ edge_logs t+ cross join unnest(metadata) as m+ cross join unnest(m.response) as response+ cross join unnest(m.request) as requestWHEREf3.status_code >= 400+ ${generateRexepWhere(filters, false)}GROUP BYtimestampORDER BYtimestamp ASC`,},- requestPaths: {+ responseSpeed: {queryType: 'logs',- sql: `+ sql: (filters) => `select- f2.path as path,- f2.search as query_params,- f2.method as method,- f3.status_code as status_code,- avg(f3.origin_time) as avg_origin_time,- sum(f3.origin_time) as sum,- APPROX_QUANTILES(f3.origin_time, 100) as quantiles,- count(timestamp) as count+ cast(timestamp_trunc(t.timestamp, hour) as datetime) as timestamp,+ avg(response.origin_time) as avg,+ APPROX_QUANTILES(response.origin_time, 100) as quantilesFROM- edge_logs- LEFT JOIN UNNEST(metadata) AS f1 ON TRUE- LEFT JOIN UNNEST(f1.request) AS f2 ON TRUE- LEFT JOIN UNNEST(f1.response) AS f3 ON TRUE+ edge_logs t+ cross join unnest(metadata) as m+ cross join unnest(m.response) as response+ cross join unnest(m.request) as request+ ${generateRexepWhere(filters)}GROUP BY- path,- query_params,- method,- status_code+ timestampORDER BY- sum DESC,- count desc,- avg_origin_time DESC- LIMIT 50+ timestamp ASC`,},- userAgents: {- queryType: 'logs',- sql: `- select- h.user_agent as user_agent,- cf.asOrganization as request_source,- count(f.id) as count- from- edge_logs as f- cross join unnest(f.metadata) as m- cross join unnest(m.request) as r- cross join unnest(r.cf) as cf- cross join unnest(r.headers) as h- group by- user_agent,- request_source- order by- count desc- limit 12- `,- },- botScores: {- queryType: 'logs',- sql: `- select- h.cf_connecting_ip as ip,- h.cf_ipcountry as country,- h.user_agent as user_agent,- r.path as path,- b.score as bot_score,- b.verifiedBot as bot_verified,- count(f.id) as count- from- edge_logs as f- cross join unnest(f.metadata) as m- cross join unnest(m.request) as r- cross join unnest(r.cf) as cf- cross join unnest(r.headers) as h- cross join unnest(cf.botManagement) as b- group by- ip,- country,- path,- user_agent,- bot_score,- bot_verified- order by- bot_score desc- limit 20- `,- },- },+ }},[Presets.AUTH]: {- title: 'Auth',- queries: {- bannedUsers: {- queryType: 'db',- sql: (_params) => `-select- count(distinct u.id) as count-from auth.users u-where u.banned_until is not null and u.banned_until > now()-limit 1- `,- },- unverifiedUsers: {- queryType: 'db',- sql: (params) => `-select- date_trunc('day', u.created_at) as timestamp,- count(distinct u.id) as count-from auth.users u-where u.confirmed_at is null and '${params.iso_timestamp_start}' < u.created_at-group by timestamp-order by timestamp desc- `,- },- signUpProviders: {- queryType: 'db',- sql: (params) => `-select- sum(count(u.id)) over (order by date_trunc('day', u.created_at)) as count,- date_trunc('day', u.created_at) as timestamp,- i.provider as provider-from auth.users u-join auth.identities as i on u.id = i.user_id-where date_trunc('day', u.created_at) > '${params.iso_timestamp_start}'-group by timestamp, provider-order by timestamp desc- `,- },- failedMigrations: {- queryType: 'logs',- sql: `-select count(f.id)-from auth_logs-where json_value(f.event_message, "$.level") = "fatal"- and regexp_contains(f.event_message, "error executing migrations")-limit 1-`,- },- dailyActiveUsers: {- queryType: 'logs',- sql: `-select- timestamp_trunc(timestamp, day) as timestamp,- count(distinct json_value(f.event_message, "$.user_id")) as count-from auth_logs f-where json_value(f.event_message, "$.action") = "login"-group by- timestamp-order by- timestamp desc-`,- },- cumulativeUsers: {- queryType: 'db',- sql: (params) => `--select- date_trunc('day', u.created_at) as timestamp,- sum(count(u.id)) over (order by date_trunc('day', u.created_at)) as count-from auth.users as u-where u.confirmed_at is not null and date_trunc('day', u.created_at) > '${params.iso_timestamp_start}'-group by timestamp-order by timestamp desc- `,- },- newUsers: {- queryType: 'db',- sql: (params) => `-select-date_trunc('day', u.created_at) as timestamp,-count(u.id) as count-from auth.users as u-where u.confirmed_at is not null and date_trunc('day', u.created_at) > '${params.iso_timestamp_start}'-group by- timestamp-order by- timestamp desc-`,- },- },+ title: "",+ queries: {}},[Presets.QUERY_PERFORMANCE]: {title: 'Query performance',@@ -327,5 +203,241 @@ select},},}+ // userAgents: {+ // queryType: 'logs',+ // sql: `+ // select+ // h.user_agent as user_agent,+ // cf.asOrganization as request_source,+ // count(f.id) as count+ // from+ // edge_logs as f+ // cross join unnest(f.metadata) as m+ // cross join unnest(m.request) as r+ // cross join unnest(r.cf) as cf+ // cross join unnest(r.headers) as h+ // group by+ // user_agent,+ // request_source+ // order by+ // count desc+ // limit 12+ // `,+ // },+ // botScores: {+ // queryType: 'logs',+ // sql: `+ // select+ // h.cf_connecting_ip as ip,+ // h.cf_ipcountry as country,+ // h.user_agent as user_agent,+ // r.path as path,+ // b.score as bot_score,+ // b.verifiedBot as bot_verified,+ // count(f.id) as count+ // from+ // edge_logs as f+ // cross join unnest(f.metadata) as m+ // cross join unnest(m.request) as r+ // cross join unnest(r.cf) as cf+ // cross join unnest(r.headers) as h+ // cross join unnest(cf.botManagement) as b+ // group by+ // ip,+ // country,+ // path,+ // user_agent,+ // bot_score,+ // bot_verified+ // order by+ // bot_score desc+ // limit 20+ // `,+ // },+// },+ // [Presets.AUTH]: {+ // title: 'Auth',+ // queries: {+ // bannedUsers: {+ // queryType: 'db',+ // sql: (_params) => `+ // select+ // count(distinct u.id) as count+ // from auth.users u+ // where u.banned_until is not null and u.banned_until > now()+ // limit 1+ // `,+ // },+ // unverifiedUsers: {+ // queryType: 'db',+ // sql: (params) => `+ // select+ // date_trunc('day', u.created_at) as timestamp,+ // count(distinct u.id) as count+ // from auth.users u+ // where u.confirmed_at is null and '${params.iso_timestamp_start}' < u.created_at+ // group by timestamp+ // order by timestamp desc+ // `,+ // },+ // signUpProviders: {+ // queryType: 'db',+ // sql: (params) => `+ // select+ // sum(count(u.id)) over (order by date_trunc('day', u.created_at)) as count,+ // date_trunc('day', u.created_at) as timestamp,+ // i.provider as provider+ // from auth.users u+ // join auth.identities as i on u.id = i.user_id+ // where date_trunc('day', u.created_at) > '${params.iso_timestamp_start}'+ // group by timestamp, provider+ // order by timestamp desc+ // `,+ // },+ // failedMigrations: {+ // queryType: 'logs',+ // sql: `+ // select count(f.id)+ // from auth_logs+ // where json_value(f.event_message, "$.level") = "fatal"+ // and regexp_contains(f.event_message, "error executing migrations")+ // limit 1+ // `,+ // },+ // dailyActiveUsers: {+ // queryType: 'logs',+ // sql: `+ // select+ // timestamp_trunc(timestamp, day) as timestamp,+ // count(distinct json_value(f.event_message, "$.user_id")) as count+ // from auth_logs f+ // where json_value(f.event_message, "$.action") = "login"+ // group by+ // timestamp+ // order by+ // timestamp desc+ // `,+ // },+ // cumulativeUsers: {+ // queryType: 'db',+ // sql: (params) => `++ // select+ // date_trunc('day', u.created_at) as timestamp,+ // sum(count(u.id)) over (order by date_trunc('day', u.created_at)) as count+ // from auth.users as u+ // where u.confirmed_at is not null and date_trunc('day', u.created_at) > '${params.iso_timestamp_start}'+ // group by timestamp+ // order by timestamp desc+ // `,+ // },+ // newUsers: {+ // queryType: 'db',+ // sql: (params) => `+ // select+ // date_trunc('day', u.created_at) as timestamp,+ // count(u.id) as count+ // from auth.users as u+ // where u.confirmed_at is not null and date_trunc('day', u.created_at) > '${params.iso_timestamp_start}'+ // group by+ // timestamp+ // order by+ // timestamp desc+ // `,+ // },+ // },+ // },+ // [Presets.STORAGE]: {+ // title: 'Storage',+ // queries: {+ // largestObjectsPerBucket: {+ // queryType: 'db',+ // sql: (_params) => `+ // select *+ // from (+ // SELECT+ // name,+ // metadata->>'mimetype' as mimetype,+ // bucket_id,+ // (metadata->>'size')::bigint as size,+ // row_number() over (partition by bucket_id ORDER BY (metadata->>'size')::bigint DESC ) AS row+ // FROM storage.objects+ // ) as f+ // where f.row <= 10+ // order by size desc`,+ // },+ // topDownloaded: {+ // queryType: 'logs',+ // sql: `+ // select+ // count(f.id) as count,+ // r.path as path+ // from edge_logs f+ // cross join unnest(f.metadata) as m+ // cross join unnest(m.request) as r+ // where starts_with(r.path, '/storage/v1/object') and r.method = 'GET'+ // group by path+ // order by count desc+ // `,+ // },+ // mostFiles: {+ // queryType: 'db',+ // sql: () => `+ // select owner,+ // count(id) as file_count,+ // sum((metadata->>'size')::bigint)::bigint as total_size+ // from storage.objects+ // where owner is not null+ // group by owner+ // order by total_size desc+ // `,+ // },+ // staleFiles: {+ // queryType: 'db',+ // sql: () => `+ // select+ // count(id) filter (where last_accessed_at < (NOW() - interval '1 month') ) as one_month,+ // count(id) filter (where last_accessed_at < (NOW() - interval '3 month') ) as three_month,+ // count(id) filter (where last_accessed_at < (NOW() - interval '6 month') ) as six_month,+ // count(id) filter (where last_accessed_at < (NOW() - interval '1 year') ) as twelve_month+ // from storage.objects+ // `,+ // },+ // topSizes: {+ // queryType: 'logs',+ // sql: `+ // SELECT+ // count(f.id) as count,+ // r.search as search+ // from edge_logs f+ // cross join unnest(f.metadata) as m+ // cross join unnest(m.request) as r+ // where starts_with(r.path, '/storage/v1/object')+ // and r.method = 'GET'+ // and regexp_contains(r.search, 'width|height')+ // group by search+ // order by count desc+ // `,+ // },+ // cacheHitRate: {+ // queryType: 'logs',+ // sql: `+ // 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+ // `,+ // },+ // },+ // },export const DATETIME_FORMAT = 'MMM D, ha'diff --git a/studio/components/interfaces/Reports/Reports.types.ts b/studio/components/interfaces/Reports/Reports.types.tsindex af6ca322b0a..8dedb0c0a3b 100644--- a/studio/components/interfaces/Reports/Reports.types.ts+++ b/studio/components/interfaces/Reports/Reports.types.ts@@ -26,18 +26,15 @@ export type MetaQueryResponse = any & { error: ResponseError }export type BaseReportParams = typeof DEFAULT_QUERY_PARAMS & { sql?: string } & unknownexport interface PresetConfig {title: string- queries: Record<string, DbQuery | LogsQuery>+ queries: BaseQueries}+export type BaseQueries = Record<string, Query>-export interface DbQuery {- queryType: 'db'- sql: string | ((params: BaseReportParams) => string)+export interface Query {+ queryType: 'db' | "logs"+ sql: ((filters: ReportFilterItem[]) => string)}-export interface LogsQuery {- queryType: 'logs'- sql: string-}export interface StatusCodesDatum {timestamp: numberstatus_code: number@@ -53,3 +50,9 @@ export interface PathsDatum {avg_origin_time: numberquantiles: number[]}++export interface ReportFilterItem {+ key: string+ value: string | number+ compare: 'matches' | 'is'+}diff --git a/studio/components/interfaces/Reports/Reports.utils.tsx b/studio/components/interfaces/Reports/Reports.utils.tsxindex 507176c6cc1..c3c2f06e76c 100644--- a/studio/components/interfaces/Reports/Reports.utils.tsx+++ b/studio/components/interfaces/Reports/Reports.utils.tsx@@ -1,4 +1,5 @@import { IconRefreshCw } from '@supabase/ui'+import { useStore } from 'hooks'import useDbQuery from 'hooks/analytics/useDbQuery'import useLogsQuery, { LogsQueryData, LogsQueryHandlers } from 'hooks/analytics/useLogsQuery'import React from 'react'@@ -6,7 +7,7 @@ import { Button } from 'ui'import { DatePickerToFrom } from '../Settings/Logs'import DatePickers from '../Settings/Logs/Logs.DatePickers'import { DEFAULT_QUERY_PARAMS, REPORTS_DATEPICKER_HELPERS } from './Reports.constants'-import { DbQueryData, DbQueryHandler, PresetConfig } from './Reports.types'+import { BaseQueries, DbQuery, DbQueryData, DbQueryHandler, LogsQuery, PresetConfig } from './Reports.types'/*** Converts a query params string to an object@@ -15,6 +16,34 @@ export const queryParamsToObject = (params: string) => {return Object.fromEntries(new URLSearchParams(params))}++export const queriesFactory = <T,>(queries: BaseQueries<T>):PresetHooks => {+ const {ui} = useStore()+ const projectRef = ui.selectedProject?.ref ?? 'default'++ const hooks: PresetHooks = Object.entries<DbQuery | LogsQuery>(queries).reduce(+ (acc, [k, { sql, queryType }]) => {+ if (queryType === 'db') {+ return {+ ...acc,+ [k]: () => useDbQuery(sql),+ }+ } else {+ return {+ ...acc,+ [k]: () =>+ useLogsQuery(projectRef, {+ sql: sql as string,+ ...DEFAULT_QUERY_PARAMS,+ }),+ }+ }+ },+ {}+ )+ return hooks+}+// generate hooks based on preset configtype PresetHookResult = [LogsQueryData | DbQueryData, LogsQueryHandlers | DbQueryHandler]type PresetHooks = Record<keyof PresetConfig['queries'], () => PresetHookResult>diff --git a/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx b/studio/components/interfaces/Reports/renderers/ApiRenderers.tsxindex e6e8156d296..f52ceee3030 100644--- a/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx+++ b/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx@@ -9,258 +9,334 @@ import { DATETIME_FORMAT } from '../Reports.constants'import { PathsDatum, StatusCodesDatum } from '../Reports.types'import { queryParamsToObject } from '../Reports.utils'import { ReportWidgetProps } from '../ReportWidget'+import AreaChart from 'components/ui/Charts/AreaChart'-export const renderUserAgents = (+export const renderTotalRequests = (props: ReportWidgetProps<{- user_agent: string- request_source: string+ timestamp: stringcount: number}>) => {+ const total = props.data.reduce((acc, datum) => {+ return acc + datum.count+ }, 0)return (- <Table- containerClassName="max-h-72 w-full overflow-y-auto"- className="relative rounded border border-scale-600"- head={- <>- <Table.th className="sticky top-0 z-10">User Agents</Table.th>- <Table.th className="sticky top-0 z-10">Request Source</Table.th>- <Table.th className="sticky top-0 z-10">Count</Table.th>- </>- }- body={- <>- {props.data.map((row, index) => {- return (- <Table.tr key={index}>- <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>- {row.user_agent ? (- row.user_agent- ) : (- <span className="text-scale-1000">No user agent</span>- )}- </Table.td>- <Table.td>{row.request_source}</Table.td>- <Table.td style={{ padding: '0.5rem' }} className="align-top text-xs">- {row.count}- </Table.td>- </Table.tr>- )- })}- </>- }+ <AreaChart+ size="small"+ minimalHeader+ highlightedValue={total}+ className="w-full h-36"+ data={props.data}+ yAxisKey="count"+ xAxisKey="timestamp"+ displayDateInUtc/>)}-export const renderBotScores = (+export const renderErrorCounts = (props: ReportWidgetProps<{- ip: string- country: string- user_agent: string- path: string- bot_score: number- bot_verified: boolean+ timestamp: stringcount: number}>) => {+ const total = props.data.reduce((acc, datum) => {+ return acc + datum.count+ }, 0)return (- <Table- containerClassName="max-h-72 w-full overflow-y-auto"- className="relative rounded border border-scale-600"- head={- <>- <Table.th className="sticky top-0 z-10">IP (Country)</Table.th>- <Table.th className="sticky top-0 z-10">Request Path</Table.th>- <Table.th className="sticky top-0 z-10">User Agent</Table.th>- <Table.th className="sticky top-0 z-10">Bot Score</Table.th>- <Table.th className="sticky top-0 z-10">Is Verified Bot</Table.th>- <Table.th className="sticky top-0 z-10">Count</Table.th>- </>- }- body={- <>- {props.data.map((row, index) => {- return (- <Table.tr key={index}>- <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>- {row.ip} ({row.country})- </Table.td>- <Table.td>{row.path}</Table.td>- <Table.td className="max-w-xs truncate">{row.user_agent}</Table.td>- <Table.td>{row.bot_score}</Table.td>- <Table.td>{row.bot_verified ? 'Yes' : 'No'}</Table.td>- <Table.td style={{ padding: '0.5rem' }} className="align-top text-xs">- {row.count}- </Table.td>- </Table.tr>- )- })}- </>- }+ <BarChart+ chartSize="small"+ highlightedValue={total}+ wrapperClassName="w-full h-36"+ data={props.data}+ attribute="count"+ xAxisKey="timestamp"+ displayDateInUtc+ label=""+ minimalHeader+ customDateFormat={DATETIME_FORMAT}+ noDataMessage={'No errors yet'}/>)}-export const renderStatusCodesChart = (props: ReportWidgetProps<StatusCodesDatum>) => (- <StackedAreaChart- dateFormat={DATETIME_FORMAT}- data={props.data}- stackKey="status_code"+export const renderResponseSpeed = (+ props : ReportWidgetProps<{+ timestamp: string+ avg: number+ quantiles: number[]+ }>+) => {+ const transformedData = props.data.map(datum=>({+ timestamp: datum.timestamp,+ avg: datum.avg,+ median: datum.quantiles[49]+ }))+ const lastAvg = props.data[props.data.length - 1]?.avg+ return <AreaChart+ size="small"+ highlightedValue={lastAvg}+ format=" ms"+ minimalHeader+ className="w-full h-36"+ data={transformedData}+ yAxisKey="avg"xAxisKey="timestamp"- yAxisKey="count"- isLoading={false}- xAxisFormatAsDate- size="large"- styleMap={{- 200: { stroke: USAGE_COLORS['200'], fill: USAGE_COLORS['200'] },- 201: { stroke: USAGE_COLORS['201'], fill: USAGE_COLORS['201'] },- 400: { stroke: USAGE_COLORS['400'], fill: USAGE_COLORS['400'] },- 401: { stroke: USAGE_COLORS['401'], fill: USAGE_COLORS['401'] },- 404: { stroke: USAGE_COLORS['404'], fill: USAGE_COLORS['404'] },- 500: { stroke: USAGE_COLORS['500'], fill: USAGE_COLORS['500'] },- }}+ displayDateInUtc/>-)-export const renderErrorRateChart = (props: ReportWidgetProps) => {- return (- <div className="flex w-full flex-col">- <BarChart- data={props.data}- attribute="count"- label=""- minimalHeader- customDateFormat={DATETIME_FORMAT}- noDataMessage={'No errors yet'}- />- </div>- )}-export const renderRequestsPathsTable = (props: ReportWidgetProps<PathsDatum>) => {- const transformedData = props.data.map((data: PathsDatum) => ({- ...data,- p99_time: data.quantiles[98],- }))- const requestPathsSums = transformedData.map((v) => v.sum) as number[]- const requestPathsSumMax = Math.max(...requestPathsSums)- const requestPathsSumMin = Math.min(...requestPathsSums)- const requestPathsAvgs = transformedData.map((v) => v.avg_origin_time) as number[]- const requestPathsAvgMax = Math.max(...requestPathsAvgs)- const requestPathsAvgMin = Math.min(...requestPathsAvgs)- const requestPathsP99s = transformedData.map((v) => v.p99_time) as number[]- const requestPathsP99Max = Math.max(...requestPathsP99s)- const requestPathsP99Min = Math.min(...requestPathsP99s)+// export const renderUserAgents = (+// props: ReportWidgetProps<{+// user_agent: string+// request_source: string+// count: number+// }>+// ) => {+// return (+// <Table+// containerClassName="max-h-72 w-full overflow-y-auto"+// className="relative rounded border border-scale-600"+// head={+// <>+// <Table.th className="sticky top-0 z-10">User Agents</Table.th>+// <Table.th className="sticky top-0 z-10">Request Source</Table.th>+// <Table.th className="sticky top-0 z-10">Count</Table.th>+// </>+// }+// body={+// <>+// {props.data.map((row, index) => {+// return (+// <Table.tr key={index}>+// <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>+// {row.user_agent ? (+// row.user_agent+// ) : (+// <span className="text-scale-1000">No user agent</span>+// )}+// </Table.td>+// <Table.td>{row.request_source}</Table.td>+// <Table.td style={{ padding: '0.5rem' }} className="align-top text-xs">+// {row.count}+// </Table.td>+// </Table.tr>+// )+// })}+// </>+// }+// />+// )+// }- const renderNumericCellWithColorScale = (value: number, percentage: number) => (- <Table.td- style={{- padding: '0.5rem',- }}- className={`${- percentage >= 80- ? 'bg-orange-600'- : percentage > 60- ? 'bg-orange-500'- : percentage > 40- ? 'bg-yellow-500'- : percentage > 20- ? 'bg-yellow-400'- : percentage > 10- ? 'bg-yellow-200'- : 'bg-green-100'- } align-top text-xs`}- >- <span className="text-scale-1100">{Number(value).toFixed(1)}</span>- </Table.td>- )- return (- <Table- containerClassName="max-h-72 w-full overflow-y-auto"- className="relative rounded border border-scale-600"- head={- <>- <Table.th className="sticky top-0 z-10">Path</Table.th>- <Table.th className="sticky top-0 z-10">Count</Table.th>- <Table.th className="sticky top-0 z-10">Avg. Time (ms)</Table.th>- <Table.th className="sticky top-0 z-10">p99 Time (ms)</Table.th>- <Table.th className="sticky top-0 z-10">Total Query Time</Table.th>- </>- }- body={- <>- {transformedData.map((row, index) => {- const [show, setShow] = useState(false)+// export const renderBotScores = (+// props: ReportWidgetProps<{+// ip: string+// country: string+// user_agent: string+// path: string+// bot_score: number+// bot_verified: boolean+// count: number+// }>+// ) => {+// return (+// <Table+// containerClassName="max-h-72 w-full overflow-y-auto"+// className="relative rounded border border-scale-600"+// head={+// <>+// <Table.th className="sticky top-0 z-10">IP (Country)</Table.th>+// <Table.th className="sticky top-0 z-10">Request Path</Table.th>+// <Table.th className="sticky top-0 z-10">User Agent</Table.th>+// <Table.th className="sticky top-0 z-10">Bot Score</Table.th>+// <Table.th className="sticky top-0 z-10">Is Verified Bot</Table.th>+// <Table.th className="sticky top-0 z-10">Count</Table.th>+// </>+// }+// body={+// <>+// {props.data.map((row, index) => {+// return (+// <Table.tr key={index}>+// <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>+// {row.ip} ({row.country})+// </Table.td>+// <Table.td>{row.path}</Table.td>+// <Table.td className="max-w-xs truncate">{row.user_agent}</Table.td>+// <Table.td>{row.bot_score}</Table.td>+// <Table.td>{row.bot_verified ? 'Yes' : 'No'}</Table.td>+// <Table.td style={{ padding: '0.5rem' }} className="align-top text-xs">+// {row.count}+// </Table.td>+// </Table.tr>+// )+// })}+// </>+// }+// />+// )+// }- const totalQueryTimePercentage =- ((row.sum - requestPathsSumMin) / requestPathsSumMax) * 100- const avgTimePercentage =- ((row.avg_origin_time - requestPathsAvgMin) / requestPathsAvgMax) * 100- const p99TimePercentage =- ((row.p99_time - requestPathsP99Min) / requestPathsP99Max) * 100- return (- <>- <Table.tr key={index}>- <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>- <Button- onClick={() => setShow(!show)}- type="text"- className="flex w-full justify-start space-x-1 text-scale-1200"- icon={- <span className={`transition ${show ? 'rotate-90' : 'rotate-0'}`}>- <IconChevronRight size="tiny" />- </span>- }- >- <div className="overflow-x-none flex items-center space-x-2">- <p className="font-mono text-xs text-scale-1200">{row.method}</p>- <p className="max-w-xs truncate font-mono text-xs text-scale-1200 ">- {row.path}- <span className="text-scale-1000">{row.query_params}</span>- </p>- </div>- </Button>- </Table.td>- <Table.td style={{ padding: '0.5rem' }} className="align-top text-xs">- {row.count}- </Table.td>- {renderNumericCellWithColorScale(row.avg_origin_time, avgTimePercentage)}- {renderNumericCellWithColorScale(row.p99_time, p99TimePercentage)}- <Table.td className="py-1 align-top">- <div- className={`mt-1 h-2 w-full rounded bg-green-1100`}- style={{- width: `${totalQueryTimePercentage}%`,- }}- />- </Table.td>- </Table.tr>- <Table.tr className="transition-all duration-500">- <Table.td- colSpan={4}- className={`overflow-none w-full ${- show ? 'h-auto opacity-100' : 'table-cell !h-0 !p-0 opacity-0'- }`}- >- <pre- className={`syntax-highlight max-w-lg overflow-auto rounded bg-scale-300 p-2 text-xs ${- show ? '' : 'h-0 !p-0'- }`}- >- <div- className="text-wrap"- dangerouslySetInnerHTML={{- __html: jsonSyntaxHighlight(queryParamsToObject(row.query_params)),- }}- />- </pre>- </Table.td>- </Table.tr>- </>- )- })}- </>- }- />- )-}+// export const renderStatusCodesChart = (props: ReportWidgetProps<StatusCodesDatum>) => (+// <StackedAreaChart+// dateFormat={DATETIME_FORMAT}+// data={props.data}+// stackKey="status_code"+// xAxisKey="timestamp"+// yAxisKey="count"+// isLoading={false}+// xAxisFormatAsDate+// size="large"+// styleMap={{+// 200: { stroke: USAGE_COLORS['200'], fill: USAGE_COLORS['200'] },+// 201: { stroke: USAGE_COLORS['201'], fill: USAGE_COLORS['201'] },+// 400: { stroke: USAGE_COLORS['400'], fill: USAGE_COLORS['400'] },+// 401: { stroke: USAGE_COLORS['401'], fill: USAGE_COLORS['401'] },+// 404: { stroke: USAGE_COLORS['404'], fill: USAGE_COLORS['404'] },+// 500: { stroke: USAGE_COLORS['500'], fill: USAGE_COLORS['500'] },+// }}+// />+// )+// export const renderErrorRateChart = (props: ReportWidgetProps) => {+// return (+// <div className="flex w-full flex-col">+// <BarChart+// data={props.data}+// attribute="count"+// label=""+// minimalHeader+// customDateFormat={DATETIME_FORMAT}+// noDataMessage={'No errors yet'}+// />+// </div>+// )+// }++// export const renderRequestsPathsTable = (props: ReportWidgetProps<PathsDatum>) => {+// const transformedData = props.data.map((data: PathsDatum) => ({+// ...data,+// p99_time: data.quantiles[98],+// }))+// const requestPathsSums = transformedData.map((v) => v.sum) as number[]+// const requestPathsSumMax = Math.max(...requestPathsSums)+// const requestPathsSumMin = Math.min(...requestPathsSums)+// const requestPathsAvgs = transformedData.map((v) => v.avg_origin_time) as number[]+// const requestPathsAvgMax = Math.max(...requestPathsAvgs)+// const requestPathsAvgMin = Math.min(...requestPathsAvgs)+// const requestPathsP99s = transformedData.map((v) => v.p99_time) as number[]+// const requestPathsP99Max = Math.max(...requestPathsP99s)+// const requestPathsP99Min = Math.min(...requestPathsP99s)++// const renderNumericCellWithColorScale = (value: number, percentage: number) => (+// <Table.td+// style={{+// padding: '0.5rem',+// }}+// className={`${+// percentage >= 80+// ? 'bg-orange-600'+// : percentage > 60+// ? 'bg-orange-500'+// : percentage > 40+// ? 'bg-yellow-500'+// : percentage > 20+// ? 'bg-yellow-400'+// : percentage > 10+// ? 'bg-yellow-200'+// : 'bg-green-100'+// } align-top text-xs`}+// >+// <span className="text-scale-1100">{Number(value).toFixed(1)}</span>+// </Table.td>+// )+// return (+// <Table+// containerClassName="max-h-72 w-full overflow-y-auto"+// className="relative rounded border border-scale-600"+// head={+// <>+// <Table.th className="sticky top-0 z-10">Path</Table.th>+// <Table.th className="sticky top-0 z-10">Count</Table.th>+// <Table.th className="sticky top-0 z-10">Avg. Time (ms)</Table.th>+// <Table.th className="sticky top-0 z-10">p99 Time (ms)</Table.th>+// <Table.th className="sticky top-0 z-10">Total Query Time</Table.th>+// </>+// }+// body={+// <>+// {transformedData.map((row, index) => {+// const [show, setShow] = useState(false)++// const totalQueryTimePercentage =+// ((row.sum - requestPathsSumMin) / requestPathsSumMax) * 100+// const avgTimePercentage =+// ((row.avg_origin_time - requestPathsAvgMin) / requestPathsAvgMax) * 100+// const p99TimePercentage =+// ((row.p99_time - requestPathsP99Min) / requestPathsP99Max) * 100+// return (+// <>+// <Table.tr key={index}>+// <Table.td className="max-w-sm lg:max-w-lg" style={{ padding: '0.3rem' }}>+// <Button+// onClick={() => setShow(!show)}+// type="text"+// className="flex w-full justify-start space-x-1 text-scale-1200"+// icon={+// <span className={`transition ${show ? 'rotate-90' : 'rotate-0'}`}>+// <IconChevronRight size="tiny" />+// </span>+// }+// >+// <div className="overflow-x-none flex items-center space-x-2">+// <p className="font-mono text-xs text-scale-1200">{row.method}</p>+// <p className="max-w-xs truncate font-mono text-xs text-scale-1200 ">+// {row.path}+// <span className="text-scale-1000">{row.query_params}</span>+// </p>+// </div>+// </Button>+// </Table.td>+// <Table.td style={{ padding: '0.5rem' }} className="align-top text-xs">+// {row.count}+// </Table.td>+// {renderNumericCellWithColorScale(row.avg_origin_time, avgTimePercentage)}+// {renderNumericCellWithColorScale(row.p99_time, p99TimePercentage)}+// <Table.td className="py-1 align-top">+// <div+// className={`mt-1 h-2 w-full rounded bg-green-1100`}+// style={{+// width: `${totalQueryTimePercentage}%`,+// }}+// />+// </Table.td>+// </Table.tr>+// <Table.tr className="transition-all duration-500">+// <Table.td+// colSpan={4}+// className={`overflow-none w-full ${+// show ? 'h-auto opacity-100' : 'table-cell !h-0 !p-0 opacity-0'+// }`}+// >+// <pre+// className={`syntax-highlight max-w-lg overflow-auto rounded bg-scale-300 p-2 text-xs ${+// show ? '' : 'h-0 !p-0'+// }`}+// >+// <div+// className="text-wrap"+// dangerouslySetInnerHTML={{+// __html: jsonSyntaxHighlight(queryParamsToObject(row.query_params)),+// }}+// />+// </pre>+// </Table.td>+// </Table.tr>+// </>+// )+// })}+// </>+// }+// />+// )+// }diff --git a/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts b/studio/components/layouts/ReportsLayout/ReportsMenu.utils.tsindex 49fab313ab1..9682a0a40a6 100644--- a/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts+++ b/studio/components/layouts/ReportsLayout/ReportsMenu.utils.ts@@ -5,6 +5,8 @@ import { useFlag } from 'hooks'export const generateReportsMenu = (project?: Project): ProductMenuGroup[] => {const ref = project?.ref ?? 'default'const productReports = useFlag('productReports')+ const reportStorage = useFlag('reportStorage')+ const reportAuth = useFlag('reportAuth')return [{@@ -18,30 +20,25 @@ export const generateReportsMenu = (project?: Project): ProductMenuGroup[] => {},],},- {- items: [- ...(productReports- ? [- {- name: 'API',- key: 'api',- url: `/project/${ref}/reports/api`,- items: [],- },- {- name: 'Auth',- key: 'auth',- url: `/project/${ref}/reports/auth`,- items: [],- },++ ...(productReports+ ? [+ {+ title: 'API Performance',+ items: [{- name: 'Storage',- key: 'storage',- url: `/project/${ref}/reports/storage`,+ name: 'Overview',+ key: 'api-overview',+ url: `/project/${ref}/reports/api-overview`,items: [],},- ]- : []),+ ],+ },+ ]+ : []),++ {+ items: [{name: 'Database',key: 'database',diff --git a/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx b/studio/components/to-be-cleaned/Charts/ChartRenderer.tsxindex 8329a32669a..f6bd2b5798c 100644--- a/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx+++ b/studio/components/to-be-cleaned/Charts/ChartRenderer.tsx@@ -139,6 +139,7 @@ export function BarChart({minimalHeader,chartSize = 'normal',className = '',+ wrapperClassName = '',noDataTitle,noDataMessage,}: any) {@@ -172,7 +173,7 @@ export function BarChart({}[chartSize as string] as numberreturn (- <Loading active={!data}>+ <Loading active={!data} className={wrapperClassName}><div className={className}><HeaderminimalHeader={minimalHeader}diff --git a/studio/components/ui/Charts/AreaChart.tsx b/studio/components/ui/Charts/AreaChart.tsxindex 90e783da40d..31378caaa9f 100644--- a/studio/components/ui/Charts/AreaChart.tsx+++ b/studio/components/ui/Charts/AreaChart.tsx@@ -36,13 +36,18 @@ const AreaChart: React.FC<AreaChartProps> = ({displayDateInUtc,minimalHeader,className = '',+ size = 'normal',}) => {const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)// For future reference: https://github.com/supabase/supabase/pull/5311#discussion_r800852828- const chartHeight = 160+ const chartHeight = {+ tiny: 76,+ small: 96,+ normal: 160,+ }[size as string] as number- if (data.length === 0) return <ChartNoData />+ if (data.length === 0) return <ChartNoData className={className} />const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))const resolvedHighlightedLabel =diff --git a/studio/components/ui/Charts/ChartHeader.tsx b/studio/components/ui/Charts/ChartHeader.tsxindex c4d841f6bac..ee515259815 100644--- a/studio/components/ui/Charts/ChartHeader.tsx+++ b/studio/components/ui/Charts/ChartHeader.tsx@@ -33,7 +33,7 @@ const ChartHeader: React.FC<ChartHeaderProps> = ({if (minimalHeader) {return (<div className="flex flex-row items-center gap-x-4" style={{ minHeight: '1.8rem' }}>- {chartTitle}+ {title && chartTitle}<div className="flex flex-row items-baseline gap-x-2">{highlightedValue && highlighted}{label}@@ -44,7 +44,7 @@ const ChartHeader: React.FC<ChartHeaderProps> = ({return (<div className="h-16">- {chartTitle}+ {title && chartTitle}{highlightedValue && highlighted}{label}</div>diff --git a/studio/components/ui/Charts/Charts.types.tsx b/studio/components/ui/Charts/Charts.types.tsxindex 3332fc441ae..6b5a1aa3650 100644--- a/studio/components/ui/Charts/Charts.types.tsx+++ b/studio/components/ui/Charts/Charts.types.tsx@@ -14,7 +14,7 @@ export interface CommonChartProps<D>title?: stringclassName?: stringisLoading?: boolean- size?: 'small' | 'normal' | 'large'+ size?: 'tiny' | 'small' | 'normal' | 'large'}export interface StackedChartProps<D> extends CommonChartProps<D> {diff --git a/studio/components/ui/LoadingOpacity.tsx b/studio/components/ui/LoadingOpacity.tsxindex ff15c8b38b3..af867eb9758 100644--- a/studio/components/ui/LoadingOpacity.tsx+++ b/studio/components/ui/LoadingOpacity.tsx@@ -1,11 +1,21 @@import React from 'react'-const LoadingOpacity = ({ children, active }: { children?: React.ReactNode; active: boolean }) => {+const LoadingOpacity = ({+ children,+ active,+ className,+}: {+ children?: React.ReactNode+ active: boolean+ className?: string+}) => {return (<div- className={- 'flex h-full flex-grow transition-opacity ' + (active ? 'opacity-30' : 'opacity-100')- }+ className={[+ className,+ 'flex h-full flex-grow transition-opacity ',+ active ? 'opacity-30' : 'opacity-100',+ ].join(' ')}>{children}</div>diff --git a/studio/pages/project/[ref]/reports/api-overview.tsx b/studio/pages/project/[ref]/reports/api-overview.tsxnew file mode 100644index 00000000000..c78616ae249--- /dev/null+++ b/studio/pages/project/[ref]/reports/api-overview.tsx@@ -0,0 +1,143 @@+import { observer } from 'mobx-react-lite'+import { useRouter } from 'next/router'++import { NextPageWithLayout } from 'types'+import { Presets, ReportFilterItem } from 'components/interfaces/Reports/Reports.types'+import { ReportsLayout } from 'components/layouts'+import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'+import ReportWidget from 'components/interfaces/Reports/ReportWidget'+import { queriesFactory } from 'components/interfaces/Reports/Reports.utils'+import {+ renderTotalRequests,+ renderErrorCounts,+ renderResponseSpeed,+} from 'components/interfaces/Reports/renderers/ApiRenderers'+import { useState, useEffect } from 'react'+import ReportHeader from 'components/interfaces/Reports/ReportHeader'+import { LogsEndpointParams } from 'components/interfaces/Settings/Logs'+import ReportFilterBar from 'components/interfaces/Reports/ReportFilterBar'++export const ApiReport: NextPageWithLayout = () => {+ const report = useApiReport()++ return (+ <div className="flex flex-col gap-4 px-5 py-6 mx-auto 1xl:px-28 lg:px-16 xl:px-24 2xl:px-32">+ <ReportHeader+ title="API Performance"+ onDatepickerChange={(value) => console.log(value)}+ datepickerFrom={report.params.totalRequests.iso_timestamp_start}+ datepickerTo={report.params.totalRequests.iso_timestamp_end}+ isLoading={report.isLoading}+ onRefresh={report.refresh}+ />++ <ReportFilterBar+ onAddFilter={report.addFilter}+ onRemoveFilter={report.removeFilter}+ filters={report.filters}+ />++ <ReportWidget+ isLoading={report.isLoading}+ params={report.params.totalRequests}+ title="Total Requests"+ data={report.data.totalRequests || []}+ renderer={renderTotalRequests}+ />+ <ReportWidget+ isLoading={report.isLoading}+ params={report.params.errorCounts}+ title="Response Errors"+ tooltip="Error responses with 4XX or 5XX status codes"+ data={report.data.errorCounts || []}+ renderer={renderErrorCounts}+ />+ <ReportWidget+ isLoading={report.isLoading}+ params={report.params.responseSpeed}+ title="Response Speed"+ tooltip="Average response speed (in miliseconds) of a request"+ data={report.data.responseSpeed || []}+ renderer={renderResponseSpeed}+ />+ </div>+ )+}++// hook to fetch data+const useApiReport = () => {+ const queryHooks = queriesFactory<keyof typeof PRESET_CONFIG.api.queries>(+ PRESET_CONFIG.api.queries+ )+ const totalRequests = queryHooks.totalRequests()+ const errorCounts = queryHooks.errorCounts()+ const responseSpeed = queryHooks.responseSpeed()+ const activeHooks = [totalRequests, errorCounts, responseSpeed]+ const [filters, setFilters] = useState<ReportFilterItem[]>([])+ const addFilter = (filter: ReportFilterItem) => {+ if (filters.includes(filter)) return+ setFilters((prev) =>+ [...prev, filter].sort((a, b) => {+ const keyA = a.key.toLowerCase()+ const keyB = b.key.toLowerCase()+ if (keyA < keyB) {+ return -1+ }+ if (keyA > keyB) {+ return 1+ }+ return 0+ })+ )+ }+ const removeFilter = (filter: ReportFilterItem) => {+ setFilters((prev) => prev.filter((f) => f !== filter))+ }++ useEffect(() => {+ // update sql for each query+ if (totalRequests[1].changeQuery) {+ totalRequests[1].changeQuery(PRESET_CONFIG.api.queries.totalRequests.sql(filters))+ }+ if (errorCounts[1].changeQuery) {+ errorCounts[1].changeQuery(PRESET_CONFIG.api.queries.errorCounts.sql(filters))+ }+ if (responseSpeed[1].changeQuery) {+ responseSpeed[1].changeQuery(PRESET_CONFIG.api.queries.responseSpeed.sql(filters))+ }+ }, [JSON.stringify(filters)])++ const handleRefresh = () => {+ activeHooks.forEach(([_hookData, hookHandler]) => {+ hookHandler.runQuery()+ })+ }+ const handleSetParams = (params: LogsEndpointParams) => {+ activeHooks.forEach(([_hookData, hookHandler]) => {+ hookHandler.setParams?.((prev) => ({ ...prev, ...params }))+ })+ }+ const isLoading = activeHooks.some(([hookData]) => hookData.isLoading)+ return {+ data: {+ totalRequests: totalRequests[0].logData,+ errorCounts: errorCounts[0].logData,+ responseSpeed: responseSpeed[0].logData,+ },+ params: {+ totalRequests: totalRequests[0].params,+ errorCounts: errorCounts[0].params,+ responseSpeed: responseSpeed[0].params,+ },+ setParams: handleSetParams,+ filters,+ addFilter,+ removeFilter,+ isLoading,+ refresh: handleRefresh,+ }+}++ApiReport.getLayout = (page) => <ReportsLayout>{page}</ReportsLayout>++export default observer(ApiReport)diff --git a/studio/pages/project/[ref]/reports/api-slow-query-finder.tsx b/studio/pages/project/[ref]/reports/api-slow-query-finder.tsxnew file mode 100644index 00000000000..e96b7c94fe7--- /dev/null+++ b/studio/pages/project/[ref]/reports/api-slow-query-finder.tsx@@ -0,0 +1,35 @@+import { observer } from 'mobx-react-lite'+import { useRouter } from 'next/router'++import { NextPageWithLayout } from 'types'+import { Presets } from 'components/interfaces/Reports/Reports.types'+import { ReportsLayout } from 'components/layouts'+import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'+import ReportWidget from 'components/interfaces/Reports/ReportWidget'+import { hooksFactory, usePresetReport } from 'components/interfaces/Reports/Reports.utils'+import { renderRequestsPathsTable } from 'components/interfaces/Reports/renderers/ApiRenderers'++export const ApiReport: NextPageWithLayout = () => {+ const router = useRouter()+ const { ref } = router.query+ const config = PRESET_CONFIG[Presets.API]+ const hooks = hooksFactory(ref as string, config)+ const requestPaths = hooks.requestPaths()+ const { isLoading, Layout } = usePresetReport([requestPaths], { wideLayout: true })+ return (+ <Layout title={`${config.title} - Slow Query Finder`}>+ <ReportWidget+ isLoading={isLoading}+ params={requestPaths[0].params}+ title="Slow API Requests"+ description="Most frequently used requests, sorted by total querying time"+ data={requestPaths[0].logData || []}+ renderer={renderRequestsPathsTable}+ />+ </Layout>+ )+}++ApiReport.getLayout = (page) => <ReportsLayout>{page}</ReportsLayout>++export default observer(ApiReport)diff --git a/studio/pages/project/[ref]/reports/api.tsx b/studio/pages/project/[ref]/reports/api.tsxdeleted file mode 100644index 31f799665c7..00000000000--- a/studio/pages/project/[ref]/reports/api.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { observer } from 'mobx-react-lite'-import { useRouter } from 'next/router'--import { NextPageWithLayout } from 'types'-import { Presets } from 'components/interfaces/Reports/Reports.types'-import { ReportsLayout } from 'components/layouts'-import { PRESET_CONFIG } from 'components/interfaces/Reports/Reports.constants'-import ReportWidget from 'components/interfaces/Reports/ReportWidget'-import { hooksFactory, usePresetReport } from 'components/interfaces/Reports/Reports.utils'-import {- renderErrorRateChart,- renderRequestsPathsTable,- renderStatusCodesChart,- renderBotScores,- renderUserAgents,-} from 'components/interfaces/Reports/renderers/ApiRenderers'--export const ApiReport: NextPageWithLayout = () => {- const router = useRouter()- const { ref } = router.query- const config = PRESET_CONFIG[Presets.API]- const hooks = hooksFactory(ref as string, config)- const statusCodes = hooks.statusCodes()- const errorRates = hooks.errorRates()- const requestPaths = hooks.requestPaths()- const userAgents = hooks.userAgents()- const botScores = hooks.botScores()- const { isLoading, Layout } = usePresetReport([- statusCodes,- errorRates,- requestPaths,- userAgents,- botScores,- ])- return (- <Layout title={config.title}>- <div className="grid lg:grid-cols-4 gap-4">- <ReportWidget- isLoading={isLoading}- params={statusCodes[0].params}- className="col-span-4 col-start-1"- title="API Status Codes"- description="Distribution of API responses by status codes."- data={statusCodes[0].logData || []}- renderer={renderStatusCodesChart}- />- <ReportWidget- isLoading={isLoading}- params={errorRates[0].params}- className="col-span-4 col-start-1"- title="Error Rate"- description="Percentage of API 5XX and 4XX error responses."- data={errorRates[0].logData || []}- renderer={renderErrorRateChart}- />- <ReportWidget- isLoading={isLoading}- params={requestPaths[0].params}- className="col-span-4 col-start-1"- title="Slow API Requests"- description="Most frequently used requests, sorted by total querying time"- data={requestPaths[0].logData || []}- renderer={renderRequestsPathsTable}- />-- <h2>Bots</h2>-- <ReportWidget- isLoading={isLoading}- params={userAgents[0].params}- className="col-span-4 col-start-1"- title="Top User Agents"- description="The types of user agents using the API and their organization source."- data={userAgents[0].logData || []}- renderer={renderUserAgents}- />- <ReportWidget- isLoading={isLoading}- params={botScores[0].params}- className="col-span-4 col-start-1"- title="Bot-like API Requests"- description="Suspicious bot-like requests, as flagged by Cloudflare"- data={botScores[0].logData || []}- renderer={renderBotScores}- />- </div>- </Layout>- )-}--ApiReport.getLayout = (page) => <ReportsLayout>{page}</ReportsLayout>--export default observer(ApiReport)diff --git a/studio/tests/pages/projects/reports/product-reports.test.js b/studio/tests/pages/projects/reports/product-reports.test.jsindex bc70babaf53..0748f9585a2 100644--- a/studio/tests/pages/projects/reports/product-reports.test.js+++ b/studio/tests/pages/projects/reports/product-reports.test.js@@ -1,7 +1,7 @@import { get, post } from 'lib/common/fetch'import { render } from '../../../helpers'import { fireEvent, waitFor, screen } from '@testing-library/react'-import { ApiReport } from 'pages/project/[ref]/reports/api'+import { ApiReport } from 'pages/project/[ref]/reports/api-overview'import { AuthReport } from 'pages/project/[ref]/reports/auth'import userEvent from '@testing-library/user-event'import { StorageReport } from 'pages/project/[ref]/reports/storage'