Skip to content

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

feat: refactored hook generation logic

TzeYiing31880c2740a4
diff --git a/studio/components/interfaces/Reports/Reports.constants.ts b/studio/components/interfaces/Reports/Reports.constants.ts
index c2a81041b29..2f99d265a3d 100644
--- a/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/studio/components/interfaces/Reports/Reports.constants.ts
@@ -36,118 +36,135 @@ export const DEFAULT_QUERY_PARAMS = {
export const PRESET_CONFIG: Record<Presets, PresetConfig> = {
[Presets.API_OVERVIEW]: {
title: '',
- sql: {
- statusCodes: `
- select
- timestamp_trunc(timestamp, hour) as timestamp,
- r.status_code as status_code,
- count(status_code) as count
- FROM
- edge_logs
- CROSS JOIN UNNEST(metadata) AS m
- CROSS JOIN UNNEST(m.response) AS r
- GROUP BY
- timestamp,
- status_code
- ORDER BY
- timestamp ASC`,
- errorRate: `
-select
- timestamp_trunc(timestamp, hour) as timestamp,
- count(timestamp) as count
-FROM
- edge_logs
- LEFT JOIN UNNEST(metadata) AS f1 ON TRUE
- LEFT JOIN UNNEST(f1.response) AS f3 ON TRUE
-WHERE
- f3.status_code >= 400
-GROUP BY
- timestamp
-ORDER BY
- timestamp ASC
-`,
- requestPaths: `
- 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
- FROM
- 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
- GROUP BY
- path,
- query_params,
- method,
- status_code
- ORDER BY
- sum DESC,
- count desc,
- avg_origin_time DESC
- LIMIT 50
-`,
+ queries: {
+ statusCodes: {
+ queryType: 'logs',
+ sql: `
+ select
+ timestamp_trunc(timestamp, hour) as timestamp,
+ r.status_code as status_code,
+ count(status_code) as count
+ FROM
+ edge_logs
+ CROSS JOIN UNNEST(metadata) AS m
+ CROSS JOIN UNNEST(m.response) AS r
+ GROUP BY
+ timestamp,
+ status_code
+ ORDER BY
+ timestamp ASC`,
+ },
+ errorRates: {
+ queryType: 'logs',
+ sql: `
+ select
+ timestamp_trunc(timestamp, hour) as timestamp,
+ count(timestamp) as count
+ FROM
+ edge_logs
+ LEFT JOIN UNNEST(metadata) AS f1 ON TRUE
+ LEFT JOIN UNNEST(f1.response) AS f3 ON TRUE
+ WHERE
+ f3.status_code >= 400
+ GROUP BY
+ timestamp
+ ORDER BY
+ timestamp ASC
+ `,
+ },
+ requestPaths: {
+ queryType: 'logs',
+ sql: `
+ 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
+ FROM
+ 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
+ GROUP BY
+ path,
+ query_params,
+ method,
+ status_code
+ ORDER BY
+ sum DESC,
+ count desc,
+ avg_origin_time DESC
+ LIMIT 50
+ `,
+ },
},
},
[Presets.API_BOTS]: {
title: 'API Bots',
- sql: {
- userAgents: `
-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: `
-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
- `,
+ queries: {
+ 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',
- sql: {
- dailyActiveUsers: `
+ queries: {
+ dailyActiveUsers: {
+ queryType: 'logs',
+ sql: `
select
timestamp_trunc(timestamp, day) as timestamp,
count(distinct json_extract(f.event_message, "$.user_id")) as count
@@ -159,7 +176,10 @@ group by
order by
timestamp
`,
-newUsers: `
+ },
+ newUsers: {
+ queryType: 'logs',
+ sql: `
select
TIMESTAMP_TRUNC(f.timestamp, DAY) as timestamp,
count(id) as count
@@ -173,7 +193,8 @@ and JSON_VALUE(f.event_message, "$.auth_event.actor_id") is not null
and JSON_VALUE(f.event_message, "$.auth_event.action") != "user_repeated_signup"
group by
timestamp
-`
+`,
+ },
},
},
}
diff --git a/studio/components/interfaces/Reports/Reports.types.ts b/studio/components/interfaces/Reports/Reports.types.ts
index 5ace186ea57..f86e32ef143 100644
--- a/studio/components/interfaces/Reports/Reports.types.ts
+++ b/studio/components/interfaces/Reports/Reports.types.ts
@@ -4,9 +4,24 @@ export enum Presets {
AUTH = 'auth',
}
+export interface BaseReportParams {
+ iso_timestamp_start: string
+ iso_timestamp_end: string
+}
+
+export type VariableSql = string | ((params: BaseReportParams) => string)
+
+export type PresetSql = string | VariableSql
+
export interface PresetConfig {
title: string
- sql: Record<string, string>
+ queries: Record<
+ string,
+ {
+ sql: PresetSql
+ queryType: 'logs' | 'db'
+ }
+ >
}
export interface StatusCodesDatum {
timestamp: number
diff --git a/studio/components/interfaces/Reports/Reports.utils.tsx b/studio/components/interfaces/Reports/Reports.utils.tsx
index 659362a0a9c..1f624714b2c 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 useDbQuery, { DbQueryData, DbQueryHandler } from 'hooks/analytics/useDbQuery'
import useLogsQuery, { LogsQueryData, LogsQueryHandlers } from 'hooks/analytics/useLogsQuery'
import React from 'react'
import { Button } from 'ui'
@@ -15,23 +16,35 @@ export const queryParamsToObject = (params: string) => {
}
// generate hooks based on preset config
-type PresetHooks = Record<keyof PresetConfig['sql'], () => [LogsQueryData, LogsQueryHandlers]>
+type PresetHookResult = [LogsQueryData, LogsQueryHandlers]
+type PresetHooks = Record<keyof PresetConfig['queries'], () => PresetHookResult>
export const hooksFactory = (projectRef: string, config: PresetConfig) => {
- const hooks: PresetHooks = Object.entries(config.sql).reduce((acc, [k, sql]) => {
- return {
- ...acc,
- [k]: () =>
- useLogsQuery(projectRef, {
- sql,
- ...DEFAULT_QUERY_PARAMS,
- }),
- }
- }, {})
- console.log(hooks)
+ const hooks: PresetHooks = Object.entries(config.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
}
-export const usePresetReport = (data: LogsQueryData[], handlers: LogsQueryHandlers[]) => {
+export const usePresetReport = (hooks: PresetHookResult[]) => {
+ const data = hooks.map((h) => h[0])
+ const handlers = hooks.map((h) => h[1])
const handleRefresh = () => {
handlers.forEach((handler) => {
handler.runQuery()
@@ -41,21 +54,23 @@ export const usePresetReport = (data: LogsQueryData[], handlers: LogsQueryHandle
const newParams = { iso_timestamp_start: from || '', iso_timestamp_end: to || '' }
handlers.forEach((handler) => {
- handler.setParams((prev) => ({
- ...prev,
- ...newParams,
- }))
+ if (handler.setParams) {
+ handler.setParams((prev) => ({
+ ...prev,
+ ...newParams,
+ }))
+ }
})
}
const isLoading = data.map((datum) => datum.isLoading).some((v) => v)
- const Layout: React.FC<{title: string}> = ({ title, children }) => (
+ const Layout: React.FC<{ title: string }> = ({ title, children }) => (
<div className="1xl:px-28 mx-auto flex flex-col gap-4 px-5 py-6 lg:px-16 xl:px-24 2xl:px-32">
<h1 className="text-2xl text-scale-1200">{title}</h1>
<div className="flex flex-row justify-between">
<DatePickers
onChange={handleDatepickerChange}
- to={data[0].params.iso_timestamp_end || ''}
- from={data[0].params.iso_timestamp_end || ''}
+ to={data[0]?.params?.iso_timestamp_end || ''}
+ from={data[0]?.params?.iso_timestamp_end || ''}
helpers={REPORTS_DATEPICKER_HELPERS}
/>
<Button
diff --git a/studio/hooks/analytics/useDbQuery.tsx b/studio/hooks/analytics/useDbQuery.tsx
new file mode 100644
index 00000000000..8bd728de66f
--- /dev/null
+++ b/studio/hooks/analytics/useDbQuery.tsx
@@ -0,0 +1,37 @@
+import { DEFAULT_QUERY_PARAMS } from 'components/interfaces/Reports/Reports.constants'
+import { BaseReportParams, PresetSql } from 'components/interfaces/Reports/Reports.types'
+import { useStore } from 'hooks'
+import useSWR from 'swr'
+import { ResponseError } from 'types'
+
+type QueryResponse = any | { error: ResponseError }
+export interface DbQueryData<T = unknown[]> {
+ data: T
+ params?: never
+ logData?: never
+ isLoading: boolean
+ error: string
+}
+export interface DbQueryHandler {
+ runQuery: () => void
+ setParams?: never
+ changeQuery?: never
+}
+type UseDbQuery<T = unknown[]> = (sql: PresetSql, params?: BaseReportParams) => [DbQueryData<T>, DbQueryHandler]
+const useDbQuery: UseDbQuery = (sql, params = DEFAULT_QUERY_PARAMS) => {
+ const { meta } = useStore()
+
+ const resolvedSql = typeof sql === 'function' ? sql(params) : sql
+
+ const {
+ data,
+ error: swrError,
+ isValidating: isLoading,
+ mutate,
+ } = useSWR<QueryResponse>(resolvedSql, meta.query, { revalidateOnFocus: false })
+
+ const error = swrError || data?.error
+ return [{ error, data, isLoading }, { runQuery: () => mutate() }]
+}
+
+export default useDbQuery
diff --git a/studio/pages/project/[ref]/reports/api-bots.tsx b/studio/pages/project/[ref]/reports/api-bots.tsx
index 40f518ae010..5f4198ac55a 100644
--- a/studio/pages/project/[ref]/reports/api-bots.tsx
+++ b/studio/pages/project/[ref]/reports/api-bots.tsx
@@ -14,31 +14,30 @@ export const ApiBotsPage: NextPageWithLayout = () => {
const { ref } = router.query
const config = PRESET_CONFIG[Presets.API_BOTS]
const hooks = hooksFactory(ref as string, config)
- const [userAgents, userAgentsHandlers] = hooks.userAgents()
- const [botScores, botScoresHandlers] = hooks.botScores()
+ const userAgents = hooks.userAgents()
+ const botScores = hooks.botScores()
const { isLoading, Layout } = usePresetReport(
[userAgents, botScores],
- [userAgentsHandlers, botScoresHandlers]
)
return (
<Layout title={config.title}>
<div className="grid lg:grid-cols-4">
<ReportWidget
isLoading={isLoading}
- params={userAgents.params}
+ 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.logData}
+ data={userAgents[0].logData}
renderer={renderUserAgents}
/>
<ReportWidget
isLoading={isLoading}
- params={botScores.params}
+ 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.logData}
+ data={botScores[0].logData}
renderer={renderBotScores}
/>
</div>
diff --git a/studio/pages/project/[ref]/reports/api-overview.tsx b/studio/pages/project/[ref]/reports/api-overview.tsx
index cd211996a34..7f2881877bb 100644
--- a/studio/pages/project/[ref]/reports/api-overview.tsx
+++ b/studio/pages/project/[ref]/reports/api-overview.tsx
@@ -18,41 +18,38 @@ export const ApiOverviewPage: NextPageWithLayout = () => {
const { ref } = router.query
const config = PRESET_CONFIG[Presets.API_OVERVIEW]
const hooks = hooksFactory(ref as string, config)
- const [statusCodes, statusCodesHandlers] = hooks.statusCodes()
- const [errorRate, errorRateHandlers] = hooks.errorRate()
- const [requestPaths, requestPathsHandlers] = hooks.requestPaths()
- const { isLoading, Layout } = usePresetReport(
- [statusCodes, errorRate, requestPaths],
- [statusCodesHandlers, errorRateHandlers, requestPathsHandlers]
- )
+ const statusCodes = hooks.statusCodes()
+ const errorRates = hooks.errorRates()
+ const requestPaths = hooks.requestPaths()
+ const { isLoading, Layout } = usePresetReport([statusCodes, errorRates, requestPaths])
return (
<Layout title={config.title}>
<div className="grid lg:grid-cols-4">
<ReportWidget
isLoading={isLoading}
- params={statusCodes.params}
+ 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.logData}
+ data={statusCodes[0].logData}
renderer={renderStatusCodesChart}
/>
<ReportWidget
isLoading={isLoading}
- params={errorRate.params}
+ params={errorRates[0].params}
className="col-span-4 col-start-1"
title="Error Rate"
description="Percentage of API 5XX and 4XX error responses."
- data={errorRate.logData}
+ data={errorRates[0].logData}
renderer={renderErrorRateChart}
/>
<ReportWidget
isLoading={isLoading}
- params={requestPaths.params}
+ 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.logData}
+ data={requestPaths[0].logData}
renderer={renderRequestsPathsTable}
/>
</div>
diff --git a/studio/pages/project/[ref]/reports/auth.tsx b/studio/pages/project/[ref]/reports/auth.tsx
index 2a33a8d6837..14b871b51b7 100644
--- a/studio/pages/project/[ref]/reports/auth.tsx
+++ b/studio/pages/project/[ref]/reports/auth.tsx
@@ -17,31 +17,30 @@ export const ApiBotsPage: NextPageWithLayout = () => {
const { ref } = router.query
const config = PRESET_CONFIG[Presets.AUTH]
const hooks = hooksFactory(ref as string, config)
- const [dailyActiveUsers, dailyActiveUsersHandlers] = hooks.dailyActiveUsers()
- const [newUsers, newUsersHandlers] = hooks.newUsers()
+ const dailyActiveUsers = hooks.dailyActiveUsers()
+ const newUsers = hooks.newUsers()
const { isLoading, Layout } = usePresetReport(
[dailyActiveUsers, newUsers],
- [dailyActiveUsersHandlers, newUsersHandlers]
)
return (
<Layout title={config.title}>
<div className="grid lg:grid-cols-4">
<ReportWidget
isLoading={isLoading}
- params={dailyActiveUsers.params}
+ params={dailyActiveUsers[0].params}
className="col-span-4 col-start-1"
title="Daily Active Users"
description="The daily count of active authenticated users"
- data={dailyActiveUsers.logData}
+ data={dailyActiveUsers[0].logData}
renderer={renderDailyActiveUsers}
/>
<ReportWidget
isLoading={isLoading}
- params={newUsers.params}
+ params={newUsers[0].params}
className="col-span-4 col-start-1"
title="Daily New Users"
description="The daily count of new user signups"
- data={newUsers.logData}
+ data={newUsers[0].logData}
renderer={renderNewUsers}
/>
</div>