The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Auth Overview: Refactor to Logflare Endpoint for all metrics (#40042)
Jordi Enricbe5e8b289e2d
diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.tsxnew file mode 100644index 00000000000..803d5b52273--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewMetrics.tsx@@ -0,0 +1,398 @@+import { useQuery } from '@tanstack/react-query'+import { useParams } from 'common'+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ cn,+ Skeleton,+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from 'ui'+import Link from 'next/link'+import { ChevronRight, ExternalLink, HelpCircle } from 'lucide-react'+import { Reports } from 'icons'+import {+ ScaffoldSection,+ ScaffoldSectionTitle,+ ScaffoldSectionContent,+} from 'components/layouts/Scaffold'+import {+ calculatePercentageChange,+ getChangeColor,+ getMetricValues,+ AuthMetricsResponse,+ getApiSuccessRates,+ getAuthSuccessRates,+} from './OverviewUsage.constants'+import {+ fetchTopAuthErrorCodes,+ fetchTopResponseErrors,+ AuthErrorCodeRow,+ ResponseErrorRow,+} from './OverviewErrors.constants'+import { OverviewTable } from './OverviewTable'+import dayjs from 'dayjs'+import AlertError from 'components/ui/AlertError'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { useRouter } from 'next/router'+import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'+import { getStatusLevel } from 'components/interfaces/UnifiedLogs/UnifiedLogs.utils'++const StatCard = ({+ title,+ current,+ previous,+ loading,+ suffix = '',+ invert = false,+ href,+ tooltip,+}: {+ title: string+ current: number+ previous: number+ loading: boolean+ suffix?: string+ invert?: boolean+ href?: string+ tooltip?: string+}) => {+ const router = useRouter()+ const isZeroChange = previous === 0+ const changeColor = isZeroChange+ ? 'text-foreground-lighter'+ : invert+ ? previous >= 0+ ? 'text-destructive'+ : 'text-brand'+ : getChangeColor(previous)+ const formattedCurrent =+ suffix === 'ms'+ ? current.toFixed(2)+ : suffix === '%'+ ? current.toFixed(1)+ : Math.round(current).toLocaleString()+ const signChar = previous > 0 ? '+' : previous < 0 ? '-' : ''++ return (+ <Card className={cn(href, 'mb-0 flex flex-col')}>+ <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0 pb-0 border-b-0 relative">+ <CardTitle className="text-foreground-light flex items-center gap-2">+ {title}+ {tooltip && (+ <Tooltip>+ <TooltipTrigger>+ <HelpCircle className="text-foreground-light" size={14} strokeWidth={1.5} />+ </TooltipTrigger>+ <TooltipContent className="w-[300px]">+ <p>{tooltip}</p>+ </TooltipContent>+ </Tooltip>+ )}+ </CardTitle>+ <ButtonTooltip+ type="text"+ size="tiny"+ icon={<ExternalLink />}+ className="w-6 h-6 absolute right-4 top-3"+ onClick={() => router.push(href || '')}+ tooltip={{+ content: {+ side: 'top',+ text: 'Go to Auth Report',+ },+ }}+ />+ </CardHeader>+ <CardContent+ className={cn(+ 'pb-4 px-6 pt-0 flex-1 h-full overflow-hidden',+ loading && 'pt-2 opacity-50 items-center justify-center'+ )}+ >+ {loading ? (+ <div className="flex flex-col gap-2">+ <Skeleton className="h-6 w-20" />+ <Skeleton className="h-3 w-8" />+ </div>+ ) : (+ <div className="flex flex-col gap-0.5">+ <p className="text-xl">{`${formattedCurrent}${suffix}`}</p>+ <span className={cn('flex items-center gap-1 text-sm', changeColor)}>+ <span>{`${signChar}${Math.abs(previous).toFixed(1)}%`}</span>+ </span>+ </div>+ )}+ </CardContent>+ </Card>+ )+}++const LogsLink = ({ href }: { href: string }) => (+ <Tooltip>+ <TooltipTrigger asChild>+ <Link className="block text-foreground-lighter hover:text-foreground p-1.5" href={href}>+ <ChevronRight className="size-4" />+ </Link>+ </TooltipTrigger>+ <TooltipContent>Go to logs</TooltipContent>+ </Tooltip>+)++function isResponseErrorRow(row: unknown): row is ResponseErrorRow {+ if (!row || typeof row !== 'object') return false+ const r = row as Record<string, unknown>+ return (+ typeof r.method === 'string' &&+ typeof r.path === 'string' &&+ typeof r.status_code === 'number' &&+ typeof r.count === 'number'+ )+}++function isAuthErrorCodeRow(row: unknown): row is AuthErrorCodeRow {+ if (!row || typeof row !== 'object') return false+ const r = row as Record<string, unknown>+ return typeof r.error_code === 'string' && typeof r.count === 'number'+}++interface OverviewMetricsProps {+ metrics?: AuthMetricsResponse+ isLoading: boolean+ error: unknown+}++export const OverviewMetrics = ({ metrics, isLoading, error }: OverviewMetricsProps) => {+ const { ref } = useParams()+ const endDate = dayjs().toISOString()+ const startDate = dayjs().subtract(24, 'hour').toISOString()++ const { current: activeUsersCurrent, previous: activeUsersPrevious } = getMetricValues(+ metrics,+ 'activeUsers'+ )++ const { current: signUpsCurrent, previous: signUpsPrevious } = getMetricValues(+ metrics,+ 'signUpCount'+ )++ const activeUsersChange = calculatePercentageChange(activeUsersCurrent, activeUsersPrevious)+ const signUpsChange = calculatePercentageChange(signUpsCurrent, signUpsPrevious)++ const { current: apiSuccessRateCurrent, previous: apiSuccessRatePrevious } =+ getApiSuccessRates(metrics)+ const { current: authSuccessRateCurrent, previous: authSuccessRatePrevious } =+ getAuthSuccessRates(metrics)++ const apiSuccessRateChange = calculatePercentageChange(+ apiSuccessRateCurrent,+ apiSuccessRatePrevious+ )+ const authSuccessRateChange = calculatePercentageChange(+ authSuccessRateCurrent,+ authSuccessRatePrevious+ )++ const { data: respErrData, isLoading: isLoadingResp } = useQuery({+ queryKey: ['auth-overview', ref, 'top-response-errors'],+ queryFn: () => fetchTopResponseErrors(ref as string),+ enabled: !!ref,+ })++ const { data: codeErrData, isLoading: isLoadingCodes } = useQuery({+ queryKey: ['auth-overview', ref, 'top-auth-error-codes'],+ queryFn: () => fetchTopAuthErrorCodes(ref as string),+ enabled: !!ref,+ })++ const responseErrors: ResponseErrorRow[] = Array.isArray(respErrData?.result)+ ? (respErrData?.result as unknown[]).filter(isResponseErrorRow)+ : []+ const errorCodes: AuthErrorCodeRow[] = Array.isArray(codeErrData?.result)+ ? (codeErrData?.result as unknown[]).filter(isAuthErrorCodeRow)+ : []++ return (+ <>+ <ScaffoldSection isFullWidth>+ {!!error && (+ <AlertError+ className="mb-4"+ subject="Error fetching auth metrics"+ error={{+ message: 'There was an error fetching the auth metrics.',+ }}+ />+ )}+ <div className="flex items-center justify-between mb-4">+ <ScaffoldSectionTitle>Usage</ScaffoldSectionTitle>+ <Link+ href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}&isHelper=true&helperText=Last+24+hours`}+ className="text-sm text-link inline-flex items-center gap-x-1.5"+ >+ <Reports size={14} />+ <span>View all reports</span>+ <ChevronRight size={14} />+ </Link>+ </div>+ <ScaffoldSectionContent className="gap-4">+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <StatCard+ title="Auth Activity"+ current={activeUsersCurrent}+ previous={activeUsersChange}+ loading={isLoading}+ href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#usage`}+ tooltip="Users who generated any Auth event in this period. This metric tracks authentication activity, not total product usage. Some active users won't appear here if their session stayed valid."+ />+ <StatCard+ title="Sign ups"+ current={signUpsCurrent}+ previous={signUpsChange}+ loading={isLoading}+ href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#usage`}+ />+ </div>+ </ScaffoldSectionContent>+ </ScaffoldSection>++ <ScaffoldSection isFullWidth>+ <div className="flex items-center justify-between mb-4">+ <ScaffoldSectionTitle>Monitoring</ScaffoldSectionTitle>+ </div>+ <ScaffoldSectionContent className="gap-4">+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <StatCard+ title="Auth API Success Rate"+ current={apiSuccessRateCurrent}+ previous={apiSuccessRateChange}+ loading={isLoading}+ suffix="%"+ href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#monitoring`}+ />+ <StatCard+ title="Auth Server Success Rate"+ current={authSuccessRateCurrent}+ previous={authSuccessRateChange}+ loading={isLoading}+ suffix="%"+ href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#monitoring`}+ />+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <Card>+ <CardHeader className={cn('border-b-0', responseErrors.length > 0 ? 'pb-4' : 'pb-0')}>+ <CardTitle className="text-foreground-light">Auth API Errors</CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ <OverviewTable<ResponseErrorRow>+ isLoading={isLoadingResp}+ data={responseErrors}+ columns={[+ {+ key: 'request',+ header: 'Request',+ className: 'w-[60px]',+ render: (row) => (+ <span className="font-mono text-xs truncate select-text cursor-text py-1 px-1.5 text-center rounded-md bg-alternative-200">+ {row.method}+ </span>+ ),+ },+ {+ key: 'status_code',+ header: 'Status',+ className: 'w-[60px]',+ render: (row) => (+ <DataTableColumnStatusCode+ value={row.status_code}+ level={getStatusLevel(row.status_code)}+ className="text-sm"+ />+ ),+ },+ {+ key: 'path',+ header: 'Path',+ className: 'flex-shrink-0 w-52',+ render: (row) => (+ <div className="line-clamp-1 font-mono text-foreground-light text-xs">+ {row.path}+ </div>+ ),+ },+ {+ key: 'count',+ header: 'Count',+ className: 'text-right flex-shrink-0 ml-auto justify-end',+ render: (row) => (+ <div className="text-right text-xs tabular-nums">{row.count}</div>+ ),+ },+ {+ key: 'actions',+ header: '',+ className: 'w-6',+ render: (row) => (+ <div className="flex justify-end">+ <LogsLink href={`/project/${ref}/logs/edge-logs?s=${row.path}`} />+ </div>+ ),+ },+ ]}+ />+ </CardContent>+ </Card>++ <Card>+ <CardHeader className={cn('border-b-0', errorCodes.length > 0 ? 'pb-4' : 'pb-0')}>+ <CardTitle className="text-foreground-light">Auth Server Errors</CardTitle>+ </CardHeader>+ <CardContent className="p-0">+ <OverviewTable<AuthErrorCodeRow>+ isLoading={isLoadingCodes}+ data={errorCodes}+ columns={[+ {+ key: 'error_code',+ header: 'Error code',+ className: 'w-full',+ render: (row) => (+ <div className="line-clamp-1 font-mono text-foreground uppercase text-xs">+ {row.error_code}+ </div>+ ),+ },+ {+ key: 'count',+ header: 'Count',+ className: 'text-right',+ render: (row) => (+ <div className="text-right text-xs tabular-nums">{row.count}</div>+ ),+ },+ {+ key: 'actions',+ header: '',+ className: 'text-right',+ render: (row) => (+ <div>+ <LogsLink href={`/project/${ref}/logs/auth-logs?s=${row.error_code}`} />+ </div>+ ),+ },+ ]}+ />+ </CardContent>+ </Card>+ </div>+ </ScaffoldSectionContent>+ </ScaffoldSection>+ </>+ )+}diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewMonitoring.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewMonitoring.tsxdeleted file mode 100644index 43c7868ed0f..00000000000--- a/apps/studio/components/interfaces/Auth/Overview/OverviewMonitoring.tsx+++ /dev/null@@ -1,244 +0,0 @@-import { useQuery } from '@tanstack/react-query'-import { useParams } from 'common'-import {- Card,- CardContent,- CardHeader,- CardTitle,- Tooltip,- TooltipContent,- TooltipTrigger,- cn,-} from 'ui'-import {- fetchTopAuthErrorCodes,- fetchTopResponseErrors,- AuthErrorCodeRow,- ResponseErrorRow,-} from './OverviewErrors.constants'-import { OverviewTable } from './OverviewTable'-import {- ScaffoldSection,- ScaffoldSectionContent,- ScaffoldSectionTitle,-} from 'components/layouts/Scaffold'-import {- calculatePercentageChange,- fetchAllAuthMetrics,- processAllAuthMetrics,-} from './OverviewUsage.constants'-import { StatCard } from './OverviewUsage'-import { ChevronRight } from 'lucide-react'-import Link from 'next/link'-import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'-import { getStatusLevel } from 'components/interfaces/UnifiedLogs/UnifiedLogs.utils'-import dayjs from 'dayjs'--const LogsLink = ({ href }: { href: string }) => (- <Tooltip>- <TooltipTrigger asChild>- <Link className="block text-foreground-lighter hover:text-foreground p-1.5" href={href}>- <ChevronRight className="size-4" />- </Link>- </TooltipTrigger>- <TooltipContent>Go to logs</TooltipContent>- </Tooltip>-)--function isResponseErrorRow(row: unknown): row is ResponseErrorRow {- if (!row || typeof row !== 'object') return false- const r = row as Record<string, unknown>- return (- typeof r.method === 'string' &&- typeof r.path === 'string' &&- typeof r.status_code === 'number' &&- typeof r.count === 'number'- )-}--function isAuthErrorCodeRow(row: unknown): row is AuthErrorCodeRow {- if (!row || typeof row !== 'object') return false- const r = row as Record<string, unknown>- return typeof r.error_code === 'string' && typeof r.count === 'number'-}--export const OverviewMonitoring = () => {- const { ref } = useParams()- const endDate = dayjs().toISOString()- const startDate = dayjs().subtract(24, 'hour').toISOString()-- // Success rate metrics (reuse OverviewUsage fetching)- const { data: currentData, isLoading: currentLoading } = useQuery({- queryKey: ['auth-metrics', ref, 'current'],- queryFn: () => fetchAllAuthMetrics(ref as string, 'current'),- enabled: !!ref,- })- const { data: previousData, isLoading: previousLoading } = useQuery({- queryKey: ['auth-metrics', ref, 'previous'],- queryFn: () => fetchAllAuthMetrics(ref as string, 'previous'),- enabled: !!ref,- })- const metrics = processAllAuthMetrics(currentData?.result || [], previousData?.result || [])-- // Tables- const { data: respErrData, isLoading: isLoadingResp } = useQuery({- queryKey: ['auth-overview', ref, 'top-response-errors'],- queryFn: () => fetchTopResponseErrors(ref as string),- enabled: !!ref,- })-- const { data: codeErrData, isLoading: isLoadingCodes } = useQuery({- queryKey: ['auth-overview', ref, 'top-auth-error-codes'],- queryFn: () => fetchTopAuthErrorCodes(ref as string),- enabled: !!ref,- })-- const responseErrors: ResponseErrorRow[] = Array.isArray(respErrData?.result)- ? (respErrData?.result as unknown[]).filter(isResponseErrorRow)- : []- const errorCodes: AuthErrorCodeRow[] = Array.isArray(codeErrData?.result)- ? (codeErrData?.result as unknown[]).filter(isAuthErrorCodeRow)- : []-- return (- <ScaffoldSection isFullWidth>- <div className="flex items-center justify-between mb-4">- <ScaffoldSectionTitle>Monitoring</ScaffoldSectionTitle>- </div>- <ScaffoldSectionContent className="gap-4">- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <StatCard- title="Auth API Success Rate"- current={Math.max(0, 100 - metrics.current.apiErrorRate)}- previous={calculatePercentageChange(- Math.max(0, 100 - metrics.current.apiErrorRate),- Math.max(0, 100 - metrics.previous.apiErrorRate)- )}- loading={currentLoading || previousLoading}- suffix="%"- href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#monitoring`}- />- <StatCard- title="Auth Server Success Rate"- current={Math.max(0, 100 - metrics.current.authErrorRate)}- previous={calculatePercentageChange(- Math.max(0, 100 - metrics.current.authErrorRate),- Math.max(0, 100 - metrics.previous.authErrorRate)- )}- loading={currentLoading || previousLoading}- suffix="%"- href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#monitoring`}- />- </div>-- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <Card>- <CardHeader className={cn('border-b-0', responseErrors.length > 0 ? 'pb-4' : 'pb-0')}>- <CardTitle className="text-foreground-light">Auth API Errors</CardTitle>- </CardHeader>- <CardContent className="p-0">- <OverviewTable<ResponseErrorRow>- isLoading={isLoadingResp || currentLoading || previousLoading}- data={responseErrors}- columns={[- {- key: 'request',- header: 'Request',- className: 'w-[60px]',- render: (row) => (- <span className="font-mono text-xs truncate select-text cursor-text py-1 px-1.5 text-center rounded-md bg-alternative-200">- {row.method}- </span>- ),- },- {- key: 'status_code',- header: 'Status',- className: 'w-[60px]',- render: (row) => (- <DataTableColumnStatusCode- value={row.status_code}- level={getStatusLevel(row.status_code)}- className="text-sm"- />- ),- },- {- key: 'path',- header: 'Path',- className: 'flex-shrink-0 w-52',- render: (row) => (- <div className="line-clamp-1 font-mono text-foreground-light text-xs">- {row.path}- </div>- ),- },- {- key: 'count',- header: 'Count',- className: 'text-right flex-shrink-0 ml-auto justify-end',- render: (row) => (- <div className="text-right text-xs tabular-nums">{row.count}</div>- ),- },- {- key: 'actions',- header: '',- className: 'w-6',- render: (row) => (- <div className="flex justify-end">- <LogsLink href={`/project/${ref}/logs/edge-logs?s=${row.path}`} />- </div>- ),- },- ]}- />- </CardContent>- </Card>-- <Card>- <CardHeader className={cn('border-b-0', errorCodes.length > 0 ? 'pb-4' : 'pb-0')}>- <CardTitle className="text-foreground-light">Auth Server Errors</CardTitle>- </CardHeader>- <CardContent className="p-0">- <OverviewTable<AuthErrorCodeRow>- isLoading={isLoadingCodes || currentLoading || previousLoading}- data={errorCodes}- columns={[- {- key: 'error_code',- header: 'Error code',- className: 'w-full',- render: (row) => (- <div className="line-clamp-1 font-mono text-foreground uppercase text-xs">- {row.error_code}- </div>- ),- },- {- key: 'count',- header: 'Count',- className: 'text-right',- render: (row) => (- <div className="text-right text-xs tabular-nums">{row.count}</div>- ),- },- {- key: 'actions',- header: '',- className: 'text-right',- render: (row) => (- <div>- <LogsLink href={`/project/${ref}/logs/auth-logs?s=${row.error_code}`} />- </div>- ),- },- ]}- />- </CardContent>- </Card>- </div>- </ScaffoldSectionContent>- </ScaffoldSection>- )-}diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.ts b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.tsindex eb9977bf3f9..ed6cd20888f 100644--- a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.ts+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.constants.ts@@ -1,129 +1,102 @@-import dayjs from 'dayjs'-import { fetchLogs } from 'data/reports/report.utils'+import { get } from 'data/fetchers'+import {+ RawAuthMetricsResponseSchema,+ type RawAuthMetricsResponse,+ type RawAuthMetricsRow,+} from './OverviewUsage.schema'++export type AuthMetricsResponse = RawAuthMetricsResponse++export type MetricName =+ | 'activeUsers'+ | 'signUpCount'+ | 'apiTotalRequests'+ | 'apiErrorRequests'+ | 'authTotalRequests'+ | 'authTotalErrors'+ | 'passwordResetRequests'++type NumericMetricKey = keyof Omit<RawAuthMetricsRow, 'period'>++const metricKeyMap: Record<MetricName, NumericMetricKey> = {+ activeUsers: 'active_users',+ signUpCount: 'sign_up_count',+ apiTotalRequests: 'api_total_requests',+ apiErrorRequests: 'api_error_requests',+ authTotalRequests: 'auth_total_requests',+ authTotalErrors: 'auth_total_errors',+ passwordResetRequests: 'password_reset_requests',+}-// Date range helpers-export const getDateRanges = () => {- const endDate = dayjs().toISOString()- const startDate = dayjs().subtract(24, 'hour').toISOString()- const previousEndDate = dayjs().subtract(24, 'hour').toISOString()- const previousStartDate = dayjs().subtract(48, 'hour').toISOString()+export const fetchAllAuthMetrics = async (projectRef: string): Promise<RawAuthMetricsResponse> => {+ const { data, error } = await get(+ `/platform/projects/{ref}/analytics/endpoints/auth.metrics` as any,+ {+ params: {+ path: { ref: projectRef },+ query: {+ interval: '1day',+ },+ },+ }+ )+ if (error) throw error++ const parsed = RawAuthMetricsResponseSchema.safeParse(data)+ if (!parsed.success) {+ const first = parsed.error.issues[0]+ throw new Error(`Invalid auth metrics response: ${first?.message ?? 'Invalid shape'}`)+ }+ return parsed.data+}+export const getMetricValues = (+ metrics: AuthMetricsResponse | undefined,+ metricName: MetricName+) => {+ const key = metricKeyMap[metricName]+ const currentRow = metrics?.result.find((r) => r.period === 'current')+ const previousRow = metrics?.result.find((r) => r.period === 'previous')return {- current: { startDate, endDate },- previous: { startDate: previousStartDate, endDate: previousEndDate },+ current: currentRow ? currentRow[key] : 0,+ previous: previousRow ? previousRow[key] : 0,}}-export const AUTH_COMBINED_QUERY = () => `--- auth-overview- with base as (- select- json_value(event_message, "$.auth_event.action") as action,- json_value(event_message, "$.auth_event.actor_id") as actor_id,- cast(json_value(event_message, "$.duration") as int64) as duration_ns- from auth_logs+export const getApiSuccessRates = (metrics: AuthMetricsResponse | undefined) => {+ const { current: apiTotalCurrent, previous: apiTotalPrevious } = getMetricValues(+ metrics,+ 'apiTotalRequests')-- select- 'activeUsers' as metric,- cast(count(distinct case- when action in (- 'login','user_signedup','token_refreshed','user_modified',- 'user_recovery_requested','user_reauthenticate_requested'- ) then actor_id- else null- end) as float64) as value- from base-- union all- select 'passwordResetRequests' as metric,- cast(count(case when action = 'user_recovery_requested' then 1 else null end) as float64)- from base-- union all- select 'signUpCount' as metric,- cast(count(case when action = 'user_signedup' then 1 else null end) as float64)- from base-- union all- select 'apiTotalRequests' as metric,- cast(count(*) as float64) as value- from edge_logs- cross join unnest(metadata) as m- cross join unnest(m.request) as request- cross join unnest(m.response) as response- cross join unnest(response.headers) as h- where path like '%auth/v1%'-- union all- select 'apiErrorRequests' as metric,- cast(count(*) as float64) as value- from edge_logs- cross join unnest(metadata) as m- cross join unnest(m.request) as request- cross join unnest(m.response) as response- cross join unnest(response.headers) as h- where path like '%auth/v1%'- and response.status_code >= 400 and response.status_code <= 599-- union all- select 'authErrorRequests' as metric,- cast(count(*) as float64) as value- from edge_logs- cross join unnest(metadata) as m- cross join unnest(m.request) as request- cross join unnest(m.response) as response- cross join unnest(response.headers) as h- where path like '%auth/v1%'- and response.status_code >= 400 and response.status_code <= 599- and h.x_sb_error_code is not null-`--export const fetchAllAuthMetrics = async (projectRef: string, period: 'current' | 'previous') => {- const sql = AUTH_COMBINED_QUERY()- const { current, previous } = getDateRanges()- const dateRange = period === 'current' ? current : previous-- return await fetchLogs(projectRef, sql, dateRange.startDate, dateRange.endDate)+ const { current: apiErrorCurrent, previous: apiErrorPrevious } = getMetricValues(+ metrics,+ 'apiErrorRequests'+ )+ const current =+ apiTotalCurrent > 0 ? Math.max(0, 100 - (apiErrorCurrent / apiTotalCurrent) * 100) : 0+ const previous =+ apiTotalPrevious > 0 ? Math.max(0, 100 - (apiErrorPrevious / apiTotalPrevious) * 100) : 0+ return { current, previous }}-export const processAllAuthMetrics = (currentData: any[], previousData: any[]) => {- const processData = (data: any[]) => {- if (!data || !Array.isArray(data)) {- return { activeUsers: 0, signUps: 0, apiErrorRate: 0, authErrorRate: 0 }- }-- const result = data.reduce(- (acc, row) => {- const { metric, value } = row- if (metric === 'activeUsers') acc.activeUsers = value || 0- if (metric === 'signUpCount') acc.signUps = value || 0- if (metric === 'apiTotalRequests') acc._apiTotal = value || 0- if (metric === 'apiErrorRequests') acc._apiErrors = value || 0- if (metric === 'authErrorRequests') acc._authErrors = value || 0- return acc- },- { activeUsers: 0, signUps: 0, _apiTotal: 0, _apiErrors: 0, _authErrors: 0 } as any- )-- const apiErrorRate = result._apiTotal > 0 ? (result._apiErrors / result._apiTotal) * 100 : 0- const authErrorRate = result._apiTotal > 0 ? (result._authErrors / result._apiTotal) * 100 : 0-- return {- activeUsers: result.activeUsers,- signUps: result.signUps,- apiErrorRate,- authErrorRate,- }- }-- return {- current: processData(currentData),- previous: processData(previousData),- }+export const getAuthSuccessRates = (metrics: AuthMetricsResponse | undefined) => {+ const { current: authTotalRequestsCurrent, previous: authTotalRequestsPrevious } =+ getMetricValues(metrics, 'authTotalRequests')+ const { current: authTotalErrorsCurrent, previous: authTotalErrorsPrevious } = getMetricValues(+ metrics,+ 'authTotalErrors'+ )+ const current =+ authTotalRequestsCurrent > 0+ ? Math.max(0, 100 - (authTotalErrorsCurrent / authTotalRequestsCurrent) * 100)+ : 0+ const previous =+ authTotalRequestsPrevious > 0+ ? Math.max(0, 100 - (authTotalErrorsPrevious / authTotalRequestsPrevious) * 100)+ : 0+ return { current, previous }}-// Utility functionsexport const calculatePercentageChange = (current: number, previous: number): number => {if (previous === 0) return current > 0 ? 100 : 0return ((current - previous) / previous) * 100@@ -132,7 +105,3 @@ export const calculatePercentageChange = (current: number, previous: number): nuexport const getChangeColor = (percentageChange: number): string => {return percentageChange >= 0 ? 'text-brand' : 'text-destructive'}--export const getChangeSign = (percentageChange: number): string => {- return percentageChange >= 0 ? '+' : ''-}diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.schema.ts b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.schema.tsnew file mode 100644index 00000000000..bf35f40df17--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.schema.ts@@ -0,0 +1,22 @@+import { z } from 'zod'++export const AuthMetricsPeriodSchema = z.enum(['current', 'previous'])++export const RawAuthMetricsRowSchema = z.object({+ period: AuthMetricsPeriodSchema,+ active_users: z.number().min(0),+ api_error_requests: z.number().min(0),+ api_total_requests: z.number().min(0),+ auth_total_errors: z.number().min(0),+ auth_total_requests: z.number().min(0),+ password_reset_requests: z.number().min(0),+ sign_up_count: z.number().min(0),+})++export const RawAuthMetricsResponseSchema = z.object({+ result: z.array(RawAuthMetricsRowSchema),+ error: z.unknown().nullable(),+})++export type RawAuthMetricsRow = z.infer<typeof RawAuthMetricsRowSchema>+export type RawAuthMetricsResponse = z.infer<typeof RawAuthMetricsResponseSchema>diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.test.ts b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.test.tsnew file mode 100644index 00000000000..8bbd192915c--- /dev/null+++ b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.test.ts@@ -0,0 +1,127 @@+import { describe, expect, test } from 'vitest'+import { RawAuthMetricsResponseSchema } from './OverviewUsage.schema'+import {+ getMetricValues,+ calculatePercentageChange,+ getApiSuccessRates,+ getAuthSuccessRates,+ type AuthMetricsResponse,+} from './OverviewUsage.constants'++const validSample = {+ result: [+ {+ period: 'current',+ active_users: 5,+ api_error_requests: 0,+ api_total_requests: 38,+ auth_total_errors: 0,+ auth_total_requests: 0,+ password_reset_requests: 0,+ sign_up_count: 4,+ },+ {+ period: 'previous',+ active_users: 0,+ api_error_requests: 0,+ api_total_requests: 0,+ auth_total_errors: 0,+ auth_total_requests: 0,+ password_reset_requests: 0,+ sign_up_count: 0,+ },+ ],+ error: null,+}++describe('RawAuthMetricsResponseSchema', () => {+ test('parses valid payload', () => {+ const parsed = RawAuthMetricsResponseSchema.safeParse(validSample)+ expect(parsed.success).toBe(true)+ })++ test('rejects negative numbers', () => {+ const invalid = {+ ...validSample,+ result: [{ ...validSample.result[0], active_users: -1 }, validSample.result[1]],+ }+ const parsed = RawAuthMetricsResponseSchema.safeParse(invalid)+ expect(parsed.success).toBe(false)+ })++ test('rejects missing fields', () => {+ const invalid = {+ result: [+ {+ period: 'current',+ active_users: 1,+ api_error_requests: 0,+ auth_total_errors: 0,+ auth_total_requests: 0,+ password_reset_requests: 0,+ sign_up_count: 0,+ },+ ],+ error: null,+ }+ const parsed = RawAuthMetricsResponseSchema.safeParse(invalid)+ expect(parsed.success).toBe(false)+ })+})++const sampleMetrics: AuthMetricsResponse = {+ result: [+ {+ period: 'current',+ active_users: 10,+ api_error_requests: 2,+ api_total_requests: 50,+ auth_total_errors: 1,+ auth_total_requests: 20,+ password_reset_requests: 3,+ sign_up_count: 7,+ },+ {+ period: 'previous',+ active_users: 5,+ api_error_requests: 5,+ api_total_requests: 25,+ auth_total_errors: 2,+ auth_total_requests: 10,+ password_reset_requests: 1,+ sign_up_count: 4,+ },+ ],+ error: null,+}++describe('OverviewUsage helpers', () => {+ test('getMetricValues maps snake_case to camel metric names', () => {+ const { current, previous } = getMetricValues(sampleMetrics, 'signUpCount')+ expect(current).toBe(7)+ expect(previous).toBe(4)+ })++ test('getMetricValues returns 0 defaults when metrics undefined', () => {+ const { current, previous } = getMetricValues(undefined, 'activeUsers')+ expect(current).toBe(0)+ expect(previous).toBe(0)+ })++ test('calculatePercentageChange handles zero previous', () => {+ expect(calculatePercentageChange(10, 0)).toBe(100)+ expect(calculatePercentageChange(0, 0)).toBe(0)+ })++ test('getApiSuccessRates computes success rates correctly', () => {+ const { current, previous } = getApiSuccessRates(sampleMetrics)+ expect(current).toBeCloseTo(96)+ expect(previous).toBeCloseTo(80)+ })++ test('getAuthSuccessRates computes success rates correctly', () => {+ const { current, previous } = getAuthSuccessRates(sampleMetrics)+ expect(current).toBeCloseTo(95)+ expect(previous).toBeCloseTo(80)+ })+})diff --git a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsx b/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsxdeleted file mode 100644index 2da5ec03eaf..00000000000--- a/apps/studio/components/interfaces/Auth/Overview/OverviewUsage.tsx+++ /dev/null@@ -1,209 +0,0 @@-import {- ScaffoldSection,- ScaffoldSectionTitle,- ScaffoldSectionContent,-} from 'components/layouts/Scaffold'-import {- Card,- CardContent,- CardHeader,- CardTitle,- cn,- Skeleton,- Tooltip,- TooltipContent,- TooltipTrigger,-} from 'ui'-import Link from 'next/link'-import { useParams } from 'common'-import { ChevronRight, ExternalLink, HelpCircle } from 'lucide-react'-import { Reports } from 'icons'-import {- getChangeColor,- fetchAllAuthMetrics,- processAllAuthMetrics,- calculatePercentageChange,-} from './OverviewUsage.constants'-import { useQuery } from '@tanstack/react-query'-import dayjs from 'dayjs'-import AlertError from 'components/ui/AlertError'-import { ButtonTooltip } from 'components/ui/ButtonTooltip'-import { useRouter } from 'next/router'--export const StatCard = ({- title,- current,- previous,- loading,- suffix = '',- invert = false,- href,- tooltip,-}: {- title: string- current: number- previous: number- loading: boolean- suffix?: string- invert?: boolean- href?: string- tooltip?: string-}) => {- const router = useRouter()- const isZeroChange = previous === 0- const changeColor = isZeroChange- ? 'text-foreground-lighter'- : invert- ? previous >= 0- ? 'text-destructive'- : 'text-brand'- : getChangeColor(previous)- const formattedCurrent =- suffix === 'ms'- ? current.toFixed(2)- : suffix === '%'- ? current.toFixed(1)- : Math.round(current).toLocaleString()- const signChar = previous > 0 ? '+' : previous < 0 ? '-' : ''-- return (- <Card className={cn(href, 'mb-0 flex flex-col')}>- <CardHeader className="flex flex-row items-center justify-between gap-2 space-y-0 pb-0 border-b-0 relative">- <CardTitle className="text-foreground-light flex items-center gap-2">- {title}- {tooltip && (- <Tooltip>- <TooltipTrigger>- <HelpCircle className="text-foreground-light" size={14} strokeWidth={1.5} />- </TooltipTrigger>- <TooltipContent className="w-[300px]">- <p>{tooltip}</p>- </TooltipContent>- </Tooltip>- )}- </CardTitle>- <ButtonTooltip- type="text"- size="tiny"- icon={<ExternalLink />}- className="w-6 h-6 absolute right-4 top-3"- onClick={() => router.push(href || '')}- tooltip={{- content: {- side: 'top',- text: 'Go to Auth Report',- },- }}- />- </CardHeader>- <CardContent- className={cn(- 'pb-4 px-6 pt-0 flex-1 h-full overflow-hidden',- loading && 'pt-2 opacity-50 items-center justify-center'- )}- >- {loading ? (- <div className="flex flex-col gap-2">- <Skeleton className="h-6 w-20" />- <Skeleton className="h-3 w-8" />- </div>- ) : (- <div className="flex flex-col gap-0.5">- <p className="text-xl">{`${formattedCurrent}${suffix}`}</p>- <span className={cn('flex items-center gap-1 text-sm', changeColor)}>- <span>{`${signChar}${Math.abs(previous).toFixed(1)}%`}</span>- </span>- </div>- )}- </CardContent>- </Card>- )-}--export const OverviewUsage = () => {- const { ref } = useParams()-- const {- data: currentData,- isLoading: currentLoading,- error: currentError,- } = useQuery({- queryKey: ['auth-metrics', ref, 'current'],- queryFn: () => fetchAllAuthMetrics(ref as string, 'current'),- enabled: !!ref,- })-- const {- data: previousData,- isLoading: previousLoading,- error: previousError,- } = useQuery({- queryKey: ['auth-metrics', ref, 'previous'],- queryFn: () => fetchAllAuthMetrics(ref as string, 'previous'),- enabled: !!ref,- })-- const metrics = processAllAuthMetrics(currentData?.result || [], previousData?.result || [])- const isLoading = currentLoading || previousLoading- const isError = !!previousError || !!currentError- const errorMessage =- (previousError as any)?.message ||- (currentError as any)?.message ||- 'There was an error fetching the auth metrics.'-- const activeUsersChange = calculatePercentageChange(- metrics.current.activeUsers,- metrics.previous.activeUsers- )-- const signUpsChange = calculatePercentageChange(metrics.current.signUps, metrics.previous.signUps)-- const endDate = dayjs().toISOString()- const startDate = dayjs().subtract(24, 'hour').toISOString()-- // No charts on overview; keep date range for link only-- return (- <ScaffoldSection isFullWidth>- {isError && (- <AlertError- className="mb-4"- subject="Error fetching auth metrics"- error={{- message: errorMessage,- }}- />- )}- <div className="flex items-center justify-between mb-4">- <ScaffoldSectionTitle>Usage</ScaffoldSectionTitle>- <Link- href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}&isHelper=true&helperText=Last+24+hours`}- className="text-sm text-link inline-flex items-center gap-x-1.5"- >- <Reports size={14} />- <span>View all reports</span>- <ChevronRight size={14} />- </Link>- </div>- <ScaffoldSectionContent className="gap-4">- <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">- <StatCard- title="Auth Activity" // https://supabase.slack.com/archives/C08N7894QTG/p1761210058358439?thread_ts=1761147906.491599&cid=C08N7894QTG- current={metrics.current.activeUsers}- previous={activeUsersChange}- loading={isLoading}- href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#usage`}- tooltip="Users who generated any Auth event in this period. This metric tracks authentication activity, not total product usage. Some active users won't appear here if their session stayed valid."- />- <StatCard- title="Sign ups"- current={metrics.current.signUps}- previous={signUpsChange}- loading={isLoading}- href={`/project/${ref}/reports/auth?its=${startDate}&ite=${endDate}#usage`}- />- </div>- </ScaffoldSectionContent>- </ScaffoldSection>- )-}diff --git a/apps/studio/data/auth/auth-overview-query.ts b/apps/studio/data/auth/auth-overview-query.tsnew file mode 100644index 00000000000..8fb6a39538e--- /dev/null+++ b/apps/studio/data/auth/auth-overview-query.ts@@ -0,0 +1,56 @@+import { useQuery } from '@tanstack/react-query'+import { get, handleError } from 'data/fetchers'+import {+ RawAuthMetricsResponseSchema,+ type RawAuthMetricsResponse,+} from 'components/interfaces/Auth/Overview/OverviewUsage.schema'+import type { UseCustomQueryOptions } from 'types'+import { authKeys } from './keys'++export type AuthOverviewVariables = {+ projectRef?: string+}++export async function getAuthOverviewMetrics(+ { projectRef }: AuthOverviewVariables,+ signal?: AbortSignal+) {+ if (!projectRef) {+ throw new Error('projectRef is required')+ }+ const { data, error } = await get(+ '/platform/projects/{ref}/analytics/endpoints/auth.metrics' as any,+ {+ params: {+ path: { ref: projectRef },+ query: { interval: '1day' },+ },+ signal,+ }+ )+ if (error) handleError(error)++ const parsed = RawAuthMetricsResponseSchema.safeParse(data)+ if (!parsed.success) {+ const first = parsed.error.issues[0]+ throw new Error(`Invalid auth metrics response: ${first?.message ?? 'Invalid shape'}`)+ }+ return parsed.data as RawAuthMetricsResponse+}++export type AuthOverviewData = Awaited<ReturnType<typeof getAuthOverviewMetrics>>+export type AuthOverviewError = unknown++export const useAuthOverviewQuery = <TData = AuthOverviewData>(+ { projectRef }: AuthOverviewVariables,+ {+ enabled = true,+ ...options+ }: UseCustomQueryOptions<AuthOverviewData, AuthOverviewError, TData> = {}+) =>+ useQuery<AuthOverviewData, AuthOverviewError, TData>({+ queryKey: authKeys.overviewMetrics(projectRef),+ queryFn: ({ signal }) => getAuthOverviewMetrics({ projectRef }, signal),+ enabled: enabled && typeof projectRef !== 'undefined',+ ...options,+ })diff --git a/apps/studio/data/auth/keys.ts b/apps/studio/data/auth/keys.tsindex 02c9fe9084d..0adb87b7b9e 100644--- a/apps/studio/data/auth/keys.ts+++ b/apps/studio/data/auth/keys.ts@@ -48,4 +48,6 @@ export const authKeys = {authConfig: (projectRef: string | undefined) => ['projects', projectRef, 'auth-config'] as const,accessToken: () => ['access-token'] as const,+ overviewMetrics: (projectRef: string | undefined) =>+ ['projects', projectRef, 'auth-overview-metrics'] as const,}diff --git a/apps/studio/pages/project/[ref]/auth/overview.tsx b/apps/studio/pages/project/[ref]/auth/overview.tsxindex f16920f031f..d68f9c83617 100644--- a/apps/studio/pages/project/[ref]/auth/overview.tsx+++ b/apps/studio/pages/project/[ref]/auth/overview.tsx@@ -1,7 +1,6 @@import { FeatureFlagContext, useFlag, useParams } from 'common'import { OverviewLearnMore } from 'components/interfaces/Auth/Overview/OverviewLearnMore'-import { OverviewMonitoring } from 'components/interfaces/Auth/Overview/OverviewMonitoring'-import { OverviewUsage } from 'components/interfaces/Auth/Overview/OverviewUsage'+import { OverviewMetrics } from 'components/interfaces/Auth/Overview/OverviewMetrics'import AuthLayout from 'components/layouts/AuthLayout/AuthLayout'import DefaultLayout from 'components/layouts/DefaultLayout'import { PageLayout } from 'components/layouts/PageLayout/PageLayout'@@ -11,6 +10,7 @@ import { DOCS_URL } from 'lib/constants'import { useRouter } from 'next/router'import { useContext, useEffect } from 'react'import type { NextPageWithLayout } from 'types'+import { useAuthOverviewQuery } from 'data/auth/auth-overview-query'const AuthOverview: NextPageWithLayout = () => {const router = useRouter()@@ -18,6 +18,12 @@ const AuthOverview: NextPageWithLayout = () => {const { hasLoaded } = useContext(FeatureFlagContext)const authOverviewPageEnabled = useFlag('authOverviewPage')+ const {+ data: metrics,+ isLoading,+ error,+ } = useAuthOverviewQuery({ projectRef: ref }, { enabled: !!ref })+useEffect(() => {if (hasLoaded && !authOverviewPageEnabled) {router.replace(`/project/${ref}/auth/users`)@@ -32,8 +38,7 @@ const AuthOverview: NextPageWithLayout = () => {return (<ScaffoldContainer size="large"><div className="mb-4 flex flex-col gap-2">- <OverviewUsage />- <OverviewMonitoring />+ <OverviewMetrics metrics={metrics} isLoading={isLoading} error={error} /><OverviewLearnMore /></div></ScaffoldContainer>