Skip to content

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

Support checking API reports by replicas (#26238)

Joshen Lim3f0793490548
diff --git a/apps/studio/__mocks__/hooks/useApiReport.ts b/apps/studio/__mocks__/hooks/useApiReport.ts
index 0dce9f66426..e6f6064462e 100644
--- a/apps/studio/__mocks__/hooks/useApiReport.ts
+++ b/apps/studio/__mocks__/hooks/useApiReport.ts
@@ -17,6 +17,11 @@ export const useApiReport = jest.fn().mockReturnValue({
sql: '',
},
},
+ error: {
+ totalRequests: null,
+ topRoutes: null,
+ topErrorRoutes: null,
+ },
filters: [],
isLoading: false,
mergeParams: jest.fn(),
diff --git a/apps/studio/components/interfaces/Reports/ReportFilterBar.tsx b/apps/studio/components/interfaces/Reports/ReportFilterBar.tsx
index a84a7ac3908..272a1780f61 100644
--- a/apps/studio/components/interfaces/Reports/ReportFilterBar.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportFilterBar.tsx
@@ -4,6 +4,7 @@ import SVG from 'react-inlinesvg'
import { useProjectContext } from 'components/layouts/ProjectLayout/ProjectContext'
import DatabaseSelector from 'components/ui/DatabaseSelector'
+import { useLoadBalancersQuery } from 'data/read-replicas/load-balancers-query'
import { Auth, Realtime, Storage } from 'icons'
import { BASE_PATH } from 'lib/constants'
import {
@@ -85,8 +86,9 @@ const ReportFilterBar = ({
datepickerHelpers,
}: ReportFilterBarProps) => {
const { project } = useProjectContext()
- // [Joshen] TODO: Once API support is out
- const showReadReplicasUI = false // project?.is_read_replicas_enabled
+ const showReadReplicasUI = project?.is_read_replicas_enabled
+
+ const { data: loadBalancers } = useLoadBalancersQuery({ projectRef: project?.ref })
const filterKeys = [
'request.path',
@@ -304,7 +306,15 @@ const ReportFilterBar = ({
</Button>
</Popover>
</div>
- {showReadReplicasUI && <DatabaseSelector />}
+ {showReadReplicasUI && (
+ <DatabaseSelector
+ additionalOptions={
+ (loadBalancers ?? []).length > 0
+ ? [{ id: `${project.ref}-all`, name: 'API Load Balancer' }]
+ : []
+ }
+ />
+ )}
</div>
)
}
diff --git a/apps/studio/components/interfaces/Reports/ReportWidget.tsx b/apps/studio/components/interfaces/Reports/ReportWidget.tsx
index 336946945fb..7429aeaf7dd 100644
--- a/apps/studio/components/interfaces/Reports/ReportWidget.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportWidget.tsx
@@ -14,11 +14,13 @@ import {
} from 'ui'
import { LogsEndpointParams } from '../Settings/Logs'
import type { BaseReportParams, ReportQueryType } from './Reports.types'
+import AlertError from 'components/ui/AlertError'
export interface ReportWidgetProps<T = any> {
data: T[]
title: string
description?: string
+ error?: string | Object | null
tooltip?: string
className?: string
renderer: (props: ReportWidgetRendererProps) => ReactNode
diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.ts b/apps/studio/components/interfaces/Reports/Reports.constants.ts
index 7741f6bfe2d..7da9f033eff 100644
--- a/apps/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/apps/studio/components/interfaces/Reports/Reports.constants.ts
@@ -39,17 +39,19 @@ export const generateRegexpWhere = (filters: ReportFilterItem[], prepend = true)
.map((filter) => {
const splitKey = filter.key.split('.')
const normalizedKey = [splitKey[splitKey.length - 2], splitKey[splitKey.length - 1]].join('.')
+ const filterKey = filter.key.includes('.') ? normalizedKey : filter.key
+
if (filter.compare === 'matches') {
- return `REGEXP_CONTAINS(${normalizedKey}, '${filter.value}')`
+ return `REGEXP_CONTAINS(${filterKey}, '${filter.value}')`
} else if (filter.compare === 'is') {
- return `${normalizedKey} = ${filter.value}`
+ return `${filterKey} = ${filter.value}`
}
})
.join(' AND ')
if (prepend) {
return 'WHERE ' + conditions
} else {
- return conditions
+ return 'AND ' + conditions
}
}
diff --git a/apps/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx b/apps/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx
index aa96863c082..a666c19fbd4 100644
--- a/apps/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx
+++ b/apps/studio/components/interfaces/Reports/renderers/ApiRenderers.tsx
@@ -13,6 +13,8 @@ import useFillTimeseriesSorted from 'hooks/analytics/useFillTimeseriesSorted'
import { Button, Collapsible } from 'ui'
import { queryParamsToObject } from '../Reports.utils'
import { ReportWidgetProps, ReportWidgetRendererProps } from '../ReportWidget'
+import AlertError from 'components/ui/AlertError'
+import { ResponseError } from 'types'
export const NetworkTrafficRenderer = (
props: ReportWidgetProps<{
@@ -35,6 +37,14 @@ export const NetworkTrafficRenderer = (
function determinePrecision(valueInMb: number) {
return valueInMb < 0.001 ? 7 : totalIngress > 1 ? 2 : 4
}
+
+ if (props.error !== null && props.error !== undefined) {
+ const error = (
+ typeof props.error === 'string' ? { message: props.error } : props.error
+ ) as ResponseError
+ return <AlertError subject="Failed to retrieve network traffic" error={error} />
+ }
+
return (
<div className="flex flex-col gap-2 w-full">
<BarChart
@@ -83,6 +93,14 @@ export const TotalRequestsChartRenderer = (
props.params?.iso_timestamp_start,
props.params?.iso_timestamp_end
)
+
+ if (props.error !== null && props.error !== undefined) {
+ const error = (
+ typeof props.error === 'string' ? { message: props.error } : props.error
+ ) as ResponseError
+ return <AlertError subject="Failed to retrieve total requests" error={error} />
+ }
+
return (
<BarChart
size="small"
@@ -216,6 +234,13 @@ export const ErrorCountsChartRenderer = (
props.params?.iso_timestamp_end
)
+ if (props.error !== null && props.error !== undefined) {
+ const error = (
+ typeof props.error === 'string' ? { message: props.error } : props.error
+ ) as ResponseError
+ return <AlertError subject="Failed to retrieve request errors" error={error} />
+ }
+
return (
<BarChart
size="small"
@@ -251,6 +276,14 @@ export const ResponseSpeedChartRenderer = (
)
const lastAvg = props.data[props.data.length - 1]?.avg
+
+ if (props.error !== null && props.error !== undefined) {
+ const error = (
+ typeof props.error === 'string' ? { message: props.error } : props.error
+ ) as ResponseError
+ return <AlertError subject="Failed to retrieve response speeds" error={error} />
+ }
+
return (
<BarChart
size="small"
diff --git a/apps/studio/components/ui/AlertError.tsx b/apps/studio/components/ui/AlertError.tsx
index 4bb1a367db3..619943b3969 100644
--- a/apps/studio/components/ui/AlertError.tsx
+++ b/apps/studio/components/ui/AlertError.tsx
@@ -7,6 +7,7 @@ import {
Button,
IconAlertCircle,
} from 'ui'
+import { WarningIcon } from 'ui-patterns/Icons/StatusIcons'
export interface AlertErrorProps {
ref?: string
@@ -25,13 +26,13 @@ const AlertError = ({ ref, subject, error, className }: AlertErrorProps) => {
if (subjectString) href += `&subject=${subjectString}`
if (error) href += `&message=Error:%20${error.message}`
- const formattedErrorMessage = error?.message.includes('503')
+ const formattedErrorMessage = error?.message?.includes('503')
? '503 Service Temporarily Unavailable'
: error?.message
return (
<Alert_Shadcn_ className={className} variant="warning" title={subject}>
- <IconAlertCircle className="h-4 w-4" strokeWidth={2} />
+ <WarningIcon className="h-4 w-4" strokeWidth={2} />
<AlertTitle_Shadcn_>{subject}</AlertTitle_Shadcn_>
<AlertDescription_Shadcn_ className="flex flex-col gap-3 break-words">
<div>
diff --git a/apps/studio/data/reports/api-report-query.ts b/apps/studio/data/reports/api-report-query.ts
index b343dc660ca..743d560416a 100644
--- a/apps/studio/data/reports/api-report-query.ts
+++ b/apps/studio/data/reports/api-report-query.ts
@@ -14,8 +14,9 @@ export const useApiReport = () => {
const { ref: projectRef } = useParams()
const state = useDatabaseSelectorStateSnapshot()
- // [Joshen] TODO: Once API support is out
- const showReadReplicasUI = false // project?.is_read_replicas_enabled
+ const identifier = project?.is_read_replicas_enabled ? state.selectedDatabaseId : project?.ref
+
+ const [filters, setFilters] = useState<ReportFilterItem[]>([])
const queryHooks = queriesFactory<keyof typeof PRESET_CONFIG.api.queries>(
PRESET_CONFIG.api.queries,
@@ -37,7 +38,7 @@ export const useApiReport = () => {
topSlowRoutes,
networkTraffic,
]
- const [filters, setFilters] = useState<ReportFilterItem[]>([])
+
const addFilter = (filter: ReportFilterItem) => {
// use a deep equal when comparing objects.
if (filters.some((f) => isEqual(f, filter))) return
@@ -62,43 +63,54 @@ export const useApiReport = () => {
})
}
+ // [Joshen] Keeping database selector separate from filter state, and merging them here for simplicity
+ const formattedFilters: ReportFilterItem[] = [
+ ...filters,
+ ...(identifier !== undefined && identifier !== project?.ref
+ ? [{ key: 'identifier', value: `'${identifier}'`, compare: 'is' } as ReportFilterItem]
+ : []),
+ ]
+
useEffect(() => {
// update sql for each query
if (totalRequests.changeQuery) {
- totalRequests.changeQuery(PRESET_CONFIG.api.queries.totalRequests.sql(filters))
+ totalRequests.changeQuery(PRESET_CONFIG.api.queries.totalRequests.sql(formattedFilters))
}
if (topRoutes.changeQuery) {
- topRoutes.changeQuery(PRESET_CONFIG.api.queries.topRoutes.sql(filters))
+ topRoutes.changeQuery(PRESET_CONFIG.api.queries.topRoutes.sql(formattedFilters))
}
if (errorCounts.changeQuery) {
- errorCounts.changeQuery(PRESET_CONFIG.api.queries.errorCounts.sql(filters))
+ errorCounts.changeQuery(PRESET_CONFIG.api.queries.errorCounts.sql(formattedFilters))
}
if (topErrorRoutes.changeQuery) {
- topErrorRoutes.changeQuery(PRESET_CONFIG.api.queries.topErrorRoutes.sql(filters))
+ topErrorRoutes.changeQuery(PRESET_CONFIG.api.queries.topErrorRoutes.sql(formattedFilters))
}
if (responseSpeed.changeQuery) {
- responseSpeed.changeQuery(PRESET_CONFIG.api.queries.responseSpeed.sql(filters))
+ responseSpeed.changeQuery(PRESET_CONFIG.api.queries.responseSpeed.sql(formattedFilters))
}
if (topSlowRoutes.changeQuery) {
- topSlowRoutes.changeQuery(PRESET_CONFIG.api.queries.topSlowRoutes.sql(filters))
+ topSlowRoutes.changeQuery(PRESET_CONFIG.api.queries.topSlowRoutes.sql(formattedFilters))
}
if (networkTraffic.changeQuery) {
- networkTraffic.changeQuery(PRESET_CONFIG.api.queries.networkTraffic.sql(filters))
+ networkTraffic.changeQuery(PRESET_CONFIG.api.queries.networkTraffic.sql(formattedFilters))
}
- }, [JSON.stringify(filters)])
+ }, [JSON.stringify(formattedFilters)])
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: {
totalRequests: totalRequests.logData,
@@ -118,6 +130,15 @@ export const useApiReport = () => {
topSlowRoutes: topSlowRoutes.params,
networkTraffic: networkTraffic.params,
},
+ error: {
+ totalRequest: totalRequests.error,
+ errorCounts: errorCounts.error,
+ responseSpeed: responseSpeed.error,
+ topRoutes: topRoutes.error,
+ topErrorRoute: topErrorRoutes.error,
+ topSlowRoutes: topSlowRoutes.error,
+ networkTraffic: networkTraffic.error,
+ },
mergeParams: handleSetParams,
filters,
addFilter,
diff --git a/apps/studio/hooks/analytics/useLogsQuery.tsx b/apps/studio/hooks/analytics/useLogsQuery.tsx
index eb18f77bfa3..21149e67520 100644
--- a/apps/studio/hooks/analytics/useLogsQuery.tsx
+++ b/apps/studio/hooks/analytics/useLogsQuery.tsx
@@ -11,10 +11,8 @@ import type {
Logs,
LogsEndpointParams,
} from 'components/interfaces/Settings/Logs/Logs.types'
-import { useReadReplicasQuery } from 'data/read-replicas/replicas-query'
import { get, isResponseOk } from 'lib/common/fetch'
import { API_URL } from 'lib/constants'
-import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
export interface LogsQueryHook {
params: LogsEndpointParams
@@ -31,10 +29,6 @@ const useLogsQuery = (
projectRef: string,
initialParams: Partial<LogsEndpointParams> = {}
): LogsQueryHook => {
- // [Joshen] TODO once API is unblocked
- const state = useDatabaseSelectorStateSnapshot()
- const { data: databases } = useReadReplicasQuery({ projectRef })
-
const defaultHelper = getDefaultHelper(EXPLORER_DATEPICKER_HELPERS)
const [params, setParams] = useState<LogsEndpointParams>({
sql: initialParams?.sql || '',
@@ -50,6 +44,7 @@ const useLogsQuery = (
const enabled = typeof projectRef !== 'undefined' && Boolean(params.sql)
const queryParams = genQueryParams(params as any)
+
const {
data,
error: rqError,
diff --git a/apps/studio/pages/project/[ref]/reports/api-overview.tsx b/apps/studio/pages/project/[ref]/reports/api-overview.tsx
index c43dca3bb3f..dc5f4cf88bd 100644
--- a/apps/studio/pages/project/[ref]/reports/api-overview.tsx
+++ b/apps/studio/pages/project/[ref]/reports/api-overview.tsx
@@ -59,6 +59,7 @@ export const ApiReport: NextPageWithLayout = () => {
params={report.params.totalRequests}
title="Total Requests"
data={report.data.totalRequests || []}
+ error={report.error.totalRequest}
renderer={TotalRequestsChartRenderer}
append={TopApiRoutesRenderer}
appendProps={{ data: report.data.topRoutes || [], params: report.params.topRoutes }}
@@ -69,6 +70,7 @@ export const ApiReport: NextPageWithLayout = () => {
title="Response Errors"
tooltip="Error responses with 4XX or 5XX status codes"
data={report.data.errorCounts || []}
+ error={report.error.errorCounts}
renderer={ErrorCountsChartRenderer}
appendProps={{
data: report.data.topErrorRoutes || [],
@@ -82,6 +84,7 @@ export const ApiReport: NextPageWithLayout = () => {
title="Response Speed"
tooltip="Average response speed (in miliseconds) of a request"
data={report.data.responseSpeed || []}
+ error={report.error.responseSpeed}
renderer={ResponseSpeedChartRenderer}
appendProps={{ data: report.data.topSlowRoutes || [], params: report.params.topSlowRoutes }}
append={TopApiRoutesRenderer}
@@ -90,6 +93,7 @@ export const ApiReport: NextPageWithLayout = () => {
<ReportWidget
isLoading={report.isLoading}
params={report.params.networkTraffic}
+ error={report.error.networkTraffic}
title="Network Traffic"
tooltip="Ingress and egress of requests and responses respectively"
data={report.data.networkTraffic || []}