The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: add auth reports FE-1569 (#36555)
Jordi Enric3b3a75202eb0
diff --git a/apps/studio/components/interfaces/Reports/ReportChart.tsx b/apps/studio/components/interfaces/Reports/ReportChart.tsxnew file mode 100644index 00000000000..8cfe89816f0--- /dev/null+++ b/apps/studio/components/interfaces/Reports/ReportChart.tsx@@ -0,0 +1,58 @@+/**+ * ReportChart+ *+ * A wrapper component that uses the useChartData hook to fetch data for a chart+ * and then passes the data and loading state to the ComposedChartHandler.+ *+ * This component acts as a bridge between the data-fetching logic and the+ * presentational chart component.+ */+import ComposedChartHandler from 'components/ui/Charts/ComposedChartHandler'+import { useChartData } from 'hooks/useChartData'+import type { UpdateDateRange } from 'pages/project/[ref]/reports/database'+import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'++const ReportChart = ({+ chart,+ startDate,+ endDate,+ interval,+ updateDateRange,+}: {+ chart: any+ startDate: string+ endDate: string+ interval: string+ updateDateRange: UpdateDateRange+}) => {+ const {+ data,+ isLoading: isLoading,+ chartAttributes,+ highlightedValue,+ } = useChartData({+ attributes: chart.attributes,+ startDate,+ endDate,+ interval,+ data: undefined,+ highlightedValue:+ chart.id === 'client-connections' || chart.id === 'pgbouncer-connections'+ ? true+ : chart.showMaxValue,+ })++ return (+ <ComposedChartHandler+ {...chart}+ attributes={+ (chartAttributes.length > 0 ? chartAttributes : chart.attributes) as MultiAttribute[]+ }+ data={data}+ isLoading={isLoading}+ highlightedValue={highlightedValue as any}+ updateDateRange={updateDateRange}+ />+ )+}+export default ReportChartdiff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsxindex ce1e4ab1267..1afb9f51a7a 100644--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx+++ b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx@@ -18,6 +18,7 @@ import { useProfile } from 'lib/profile'import { Menu, cn } from 'ui'import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'import { ReportMenuItem } from './ReportMenuItem'+import { useFlag } from 'hooks/ui/useFlag'const ReportsMenu = () => {const router = useRouter()@@ -25,6 +26,7 @@ const ReportsMenu = () => {const { ref, id } = useParams()const pageKey = (id || router.pathname.split('/')[4]) as stringconst storageEnabled = useIsFeatureEnabled('project_storage:all')+ const authEnabled = useFlag('authreportv2')const canCreateCustomReport = useCheckPermissions(PermissionAction.CREATE, 'user_content', {resource: { type: 'report', owner_id: profile?.id },@@ -97,21 +99,29 @@ const ReportsMenu = () => {key: 'api-overview',url: `/project/${ref}/reports/api-overview`,},- ...(storageEnabled+ ...(authEnabled? [{- name: 'Storage',- key: 'storage',- url: `/project/${ref}/reports/storage`,+ name: 'Auth',+ key: 'auth',+ url: `/project/${ref}/reports/auth`,},]: []),-{name: 'Database',key: 'database',url: `/project/${ref}/reports/database`,},+ ...(storageEnabled+ ? [+ {+ name: 'Storage',+ key: 'storage',+ url: `/project/${ref}/reports/storage`,+ },+ ]+ : []),],},]diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsxindex 0c36f49f72e..a1d501fd655 100644--- a/apps/studio/components/ui/Charts/ComposedChart.tsx+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx@@ -28,13 +28,9 @@ import {} from './Charts.constants'import { CommonChartProps, Datum } from './Charts.types'import { numberFormatter, useChartSize } from './Charts.utils'-import {- calculateTotalChartAggregate,- CustomLabel,- CustomTooltip,- type MultiAttribute,-} from './ComposedChart.utils'+import { calculateTotalChartAggregate, CustomLabel, CustomTooltip } from './ComposedChart.utils'import NoDataPlaceholder from './NoDataPlaceholder'+import { MultiAttribute } from './ComposedChart.utils'import { ChartHighlight } from './useChartHighlight'import { formatBytes } from 'lib/helpers'@@ -58,6 +54,7 @@ export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {chartStyle?: stringonChartStyleChange?: (style: string) => voidupdateDateRange: any+ titleTooltip?: stringhideYAxis?: booleanhideHighlightedValue?: booleansyncId?: string@@ -114,6 +111,22 @@ export default function ComposedChart({const { Container } = useChartSize(size)+ const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))++ const formatTimestamp = (ts: unknown) => {+ if (typeof ts !== 'number' && typeof ts !== 'string') {+ return ''+ }++ // Timestamps from auth logs can be in microseconds+ if (typeof ts === 'number' && ts > 1e14) {+ return day(ts / 1000).format(customDateFormat)+ }++ // dayjs can handle ISO strings and millisecond numbers+ return day(ts).format(customDateFormat)+ }+// Default propsconst _XAxisProps = XAxisProps || {interval: data.length - 2,@@ -127,18 +140,19 @@ export default function ComposedChart({width: 0,}- const day = (value: number | string) => (displayDateInUtc ? dayjs(value).utc() : dayjs(value))-function getHeaderLabel() {if (!xAxisIsDate) {if (!focusDataIndex) return highlightedLabel- return data[focusDataIndex]?.timestamp+ return data[focusDataIndex]?.[xAxisKey]}return ((focusDataIndex !== null &&data &&data[focusDataIndex] !== undefined &&- day(data[focusDataIndex].timestamp).format(customDateFormat)) ||+ (() => {+ const ts = data[focusDataIndex][xAxisKey]+ return formatTimestamp(ts)+ })()) ||highlightedLabel)}@@ -149,13 +163,45 @@ export default function ComposedChart({color: CHART_COLORS.REFERENCE_LINE,}+ const chartData =+ data && !!data[0]+ ? Object.entries(data[0])+ ?.map(([key, value]) => ({+ name: key,+ value: value,+ }))+ .filter(+ (att) =>+ att.name !== 'timestamp' &&+ att.name !== 'period_start' &&+ att.name !== maxAttribute?.attribute &&+ attributes.some((attr) => attr.attribute === att.name && attr.enabled !== false)+ )+ .map((att, index) => {+ const attribute = attributes.find((attr) => attr.attribute === att.name)+ return {+ ...att,+ color: attribute?.color+ ? resolvedTheme?.includes('dark')+ ? attribute.color.dark+ : attribute.color.light+ : STACKED_CHART_COLORS[index % STACKED_CHART_COLORS.length],+ }+ })+ : []+const lastDataPoint = !!data[data.length - 1]? Object.entries(data[data.length - 1]).map(([key, value]) => ({dataKey: key,value: value as number,}))- .filter((entry) => entry.dataKey !== 'timestamp')+ .filter(+ (entry) =>+ entry.dataKey !== 'timestamp' &&+ entry.dataKey !== 'period_start' &&+ attributes.some((attr) => attr.attribute === entry.dataKey && attr.enabled !== false)+ ): undefinedconst referenceLines = attributes.filter((attribute) => attribute?.provider === 'reference-line')@@ -184,32 +230,17 @@ export default function ComposedChart({chartHighlight?.coordinates.right &&chartHighlight?.coordinates.left !== chartHighlight?.coordinates.right- const chartData =- data && !!data[0]- ? Object.entries(data[0])- ?.map(([key, value], index) => ({- name: key,- value: value,- color: STACKED_CHART_COLORS[index - (1 % STACKED_CHART_COLORS.length)],- }))- .filter(- (att) =>- att.name !== 'timestamp' &&- att.name !== maxAttribute?.attribute &&- !referenceLines.map((a) => a.attribute).includes(att.name)- )- : []-const stackedAttributes = chartData.filter((att) => !att.name.includes('max'))const isPercentage = format === '%'const isRamChart = chartData?.some((att: any) => att.name.toLowerCase().includes('ram_'))const isDiskSpaceChart = chartData?.some((att: any) =>att.name.toLowerCase().includes('disk_space_'))- const isDiskSizeChart = chartData?.some((att: any) => att.name.toLowerCase().includes('disk_fs_'))+ const isDBSizeChart = chartData?.some((att: any) =>+ att.name.toLowerCase().includes('pg_database_size')+ )const isNetworkChart = chartData?.some((att: any) => att.name.toLowerCase().includes('network_'))- const shouldFormatBytes = isRamChart || isDiskSpaceChart || isDiskSizeChart || isNetworkChart-+ const shouldFormatBytes = isRamChart || isDiskSpaceChart || isDBSizeChart || isNetworkChart//*// Set the y-axis domain// to the highest value in the chart data for percentage charts@@ -387,6 +418,7 @@ export default function ComposedChart({y={line.value}strokeWidth={1}{...line}+ color={line.color?.dark}strokeDasharray={line.strokeDasharray ?? '3 3'}label={undefined}>@@ -418,13 +450,11 @@ export default function ComposedChart({className="text-foreground-lighter -mt-9 flex items-center justify-between text-xs"style={{ marginLeft: YAxisProps?.width }}>- <span>- {xAxisIsDate ? day(data[0]?.timestamp).format(customDateFormat) : data[0]?.timestamp}- </span>+ <span>{xAxisIsDate ? formatTimestamp(data[0]?.[xAxisKey]) : data[0]?.[xAxisKey]}</span><span>{xAxisIsDate- ? day(data[data?.length - 1]?.timestamp).format(customDateFormat)- : data[data?.length - 1]?.timestamp}+ ? formatTimestamp(data[data.length - 1]?.[xAxisKey])+ : data[data.length - 1]?.[xAxisKey]}</span></div>)}diff --git a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx b/apps/studio/components/ui/Charts/ComposedChart.utils.tsxindex 95444d52230..831f4b6153a 100644--- a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx+++ b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx@@ -31,13 +31,19 @@ export interface ReportAttributes {hideHighlightedValue?: boolean}-type Provider = 'infra-monitoring' | 'daily-stats' | 'reference-line' | 'combine'+export type Provider = 'infra-monitoring' | 'daily-stats' | 'mock' | 'reference-line' | 'logs'export type MultiAttribute = {attribute: stringprovider: Providerlabel?: string- color?: string+ color?: {+ light: string+ dark: string+ }+ statusCode?: string+ grantType?: string+ providerType?: stringstackId?: stringformat?: stringdescription?: string@@ -65,6 +71,7 @@ export type MultiAttribute = {strokeDasharray?: stringclassName?: stringhide?: boolean+ enabled?: boolean}interface CustomIconProps {@@ -167,7 +174,7 @@ const CustomTooltip = ({return (<div key={entry.name} className="flex items-center w-full">{getIcon(entry.color, isMax)}- <span className="text-foreground-lighter ml-1 flex-grow">+ <span className="text-foreground-lighter ml-1 flex-grow cursor-default select-none">{attribute?.label || entry.name}</span><span className="ml-3.5 flex items-end gap-1">@@ -194,9 +201,12 @@ const CustomTooltip = ({><p className="font-medium">{dayjs(timestamp).format(DateTimeFormats.FULL_SECONDS)}</p><div className="grid gap-0">- {payload.reverse().map((entry: any, index: number) => (- <LabelItem key={`${entry.name}-${index}`} entry={entry} />- ))}+ {payload+ .reverse()+ .filter((entry: any) => entry.value !== 0)+ .map((entry: any, index: number) => (+ <LabelItem key={`${entry.name}-${index}`} entry={entry} />+ ))}{active && showTotal && (<div className="flex md:flex-col gap-1 md:gap-0 text-foreground mt-1"><span className="flex-grow text-foreground-lighter">Total</span>@@ -270,7 +280,7 @@ const CustomLabel = ({ payload, attributes, showMaxValue, onLabelHover }: Custom{getIcon(entry.name, entry.color)}<spanclassName={cn(- 'text-nowrap text-foreground-lighter',+ 'text-nowrap text-foreground-lighter cursor-default select-none',hoveredLabel && !isHovered && 'opacity-50')}>diff --git a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx b/apps/studio/components/ui/Charts/ComposedChartHandler.tsxindex 1c90a17dd37..84f50022199 100644--- a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx+++ b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx@@ -1,5 +1,11 @@-import React, { PropsWithChildren, useState, useMemo, useEffect, useRef } from 'react'-import { useRouter } from 'next/router'+/**+ * ComposedChartHandler+ *+ * A presentational component for rendering charts.+ * It is responsible only for rendering the chart UI based on the data and loading state passed to it as props.+ * All the complex data fetching logic has been moved to the useChartData hook.+ */+import React, { PropsWithChildren, useState, useEffect, useRef } from 'react'import { Loader2 } from 'lucide-react'import { cn, WarningIcon } from 'ui'@@ -11,14 +17,14 @@ import { InfraMonitoringAttribute } from 'data/analytics/infra-monitoring-query'import { useInfraMonitoringQueries } from 'data/analytics/infra-monitoring-queries'import { ProjectDailyStatsAttribute } from 'data/analytics/project-daily-stats-query'import { useProjectDailyStatsQueries } from 'data/analytics/project-daily-stats-queries'-import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'import { useChartHighlight } from './useChartHighlight'+import { getMockDataForAttribute } from 'data/reports/auth-charts'import type { ChartData } from './Charts.types'import type { UpdateDateRange } from 'pages/project/[ref]/reports/database'-import { MultiAttribute } from './ComposedChart.utils'+import type { MultiAttribute } from './ComposedChart.utils'-export interface ComposedChartHandlerProps {+interface ComposedChartHandlerProps {id?: stringlabel: stringattributes: MultiAttribute[]@@ -40,6 +46,7 @@ export interface ComposedChartHandlerProps {updateDateRange: UpdateDateRangevaluePrecision?: numberisVisible?: boolean+ titleTooltip?: stringdocsUrl?: string}@@ -91,9 +98,6 @@ const LazyChartWrapper = ({ children }: PropsWithChildren) => {const ComposedChartHandler = ({label,attributes,- startDate,- endDate,- interval,customDateFormat,children = null,defaultChartStyle = 'bar',@@ -109,131 +113,14 @@ const ComposedChartHandler = ({showTotal,updateDateRange,valuePrecision,- isVisible = true,+ titleTooltip,id,...otherProps}: PropsWithChildren<ComposedChartHandlerProps>) => {- const router = useRouter()- const { ref } = router.query-- const state = useDatabaseSelectorStateSnapshot()const [chartStyle, setChartStyle] = useState<string>(defaultChartStyle)const chartHighlight = useChartHighlight()- const databaseIdentifier = state.selectedDatabaseId-- // Use the custom hook at the top level of the component- const attributeQueries = useAttributeQueries(- attributes,- ref,- startDate,- endDate,- interval as AnalyticsInterval,- databaseIdentifier,- data,- isVisible- )-- // Combine all the data into a single dataset- const combinedData = useMemo(() => {- if (data) return data-- const isLoading = attributeQueries.some((query: any) => query.isLoading)- if (isLoading) return undefined-- const hasError = attributeQueries.some((query: any) => !query.data)- if (hasError) return undefined-- // Get all unique timestamps from all datasets- const timestamps = new Set<string>()- attributeQueries.forEach((query: any) => {- query.data?.data?.forEach((point: any) => {- if (point?.period_start) {- timestamps.add(point.period_start)- }- })- })-- const referenceLineQueries = attributeQueries.filter(- (_, index) => attributes[index].provider === 'reference-line'- )-- // Combine data points for each timestamp- const combined = Array.from(timestamps)- .sort()- .map((timestamp) => {- const point: any = { timestamp }-- // Add regular attributes- attributes.forEach((attr, index) => {- if (!attr) return-- // Handle custom value attributes (like disk size)- if (attr.customValue !== undefined) {- point[attr.attribute] = attr.customValue- return- }-- // Skip reference line attributes here, we'll add them below- if (attr.provider === 'reference-line') return-- const queryData = attributeQueries[index]?.data?.data- const matchingPoint = queryData?.find((p: any) => p.period_start === timestamp)- let value = matchingPoint?.[attr.attribute] ?? 0-- // Apply value manipulation if provided- if (attr.manipulateValue && typeof attr.manipulateValue === 'function') {- // Ensure value is a number before manipulation- const numericValue = typeof value === 'number' ? value : Number(value) || 0- value = attr.manipulateValue(numericValue)- }-- point[attr.attribute] = value- })-- // Add reference line values for each timestamp- referenceLineQueries.forEach((query: any) => {- const attr = query.data.attribute- const value = query.data.total- point[attr] = value- })-- return point as DataPoint- })-- return combined as DataPoint[]- }, [data, attributeQueries, attributes])-- const loading = isLoading || attributeQueries.some((query: any) => query.isLoading)-- // Calculate highlighted value based on the first attribute's data- const _highlightedValue = useMemo(() => {- if (highlightedValue !== undefined) return highlightedValue-- const firstAttr = attributes[0]- const firstQuery = attributeQueries[0]- const firstData = firstQuery?.data-- if (!firstData) return undefined-- const shouldHighlightMaxValue =- firstAttr.provider === 'daily-stats' &&- !firstAttr.attribute.includes('ingress') &&- !firstAttr.attribute.includes('egress') &&- 'maximum' in firstData-- const shouldHighlightTotalGroupedValue = 'totalGrouped' in firstData-- return shouldHighlightMaxValue- ? firstData.maximum- : firstAttr.provider === 'daily-stats'- ? firstData.total- : shouldHighlightTotalGroupedValue- ? firstData.totalGrouped?.[firstAttr.attribute as keyof typeof firstData.totalGrouped]- : (firstData.data[firstData.data.length - 1] as any)?.[firstAttr.attribute]- }, [highlightedValue, attributes, attributeQueries])-- if (loading) {+ if (isLoading) {return (<PanelclassName={cn(@@ -250,7 +137,7 @@ const ComposedChartHandler = ({)}- if (!combinedData) {+ if (!data) {return (<div className="flex h-52 w-full flex-col items-center justify-center gap-y-2"><WarningIcon />@@ -272,11 +159,11 @@ const ComposedChartHandler = ({<div className="absolute right-6 z-50 flex justify-between scroll-mt-16">{children}</div><ComposedChartattributes={attributes}- data={combinedData as DataPoint[]}+ data={data as any}format={format}xAxisKey="period_start"yAxisKey={attributes[0].attribute}- highlightedValue={_highlightedValue}+ highlightedValue={highlightedValue}title={label}customDateFormat={customDateFormat}chartHighlight={chartHighlight}@@ -289,6 +176,7 @@ const ComposedChartHandler = ({updateDateRange={updateDateRange}valuePrecision={valuePrecision}hideChartType={hideChartType}+ titleTooltip={titleTooltip}{...otherProps}/></Panel.Content>@@ -296,7 +184,7 @@ const ComposedChartHandler = ({)}-const useAttributeQueries = (+export const useAttributeQueries = (attributes: MultiAttribute[],ref: string | string[] | undefined,startDate: string,@@ -306,16 +194,15 @@ const useAttributeQueries = (data: ChartData | undefined,isVisible: boolean) => {- const infraAttributes = attributes- .filter((attr) => attr?.provider === 'infra-monitoring')- .map((attr) => attr.attribute as InfraMonitoringAttribute)- const dailyStatsAttributes = attributes- .filter((attr) => attr?.provider === 'daily-stats')- .map((attr) => attr.attribute as ProjectDailyStatsAttribute)- const referenceLines = attributes.filter((attr) => attr?.provider === 'reference-line')+ const projectRef = typeof ref === 'string' ? ref : Array.isArray(ref) ? ref[0] : ''++ const infraAttributes = attributes.filter((attr) => attr.provider === 'infra-monitoring')+ const dailyStatsAttributes = attributes.filter((attr) => attr.provider === 'daily-stats')+ const mockAttributes = attributes.filter((attr) => attr.provider === 'mock')+ const referenceLineAttributes = attributes.filter((attr) => attr.provider === 'reference-line')const infraQueries = useInfraMonitoringQueries(- infraAttributes,+ infraAttributes.map((attr) => attr.attribute as InfraMonitoringAttribute),ref,startDate,endDate,@@ -325,7 +212,7 @@ const useAttributeQueries = (isVisible)const dailyStatsQueries = useProjectDailyStatsQueries(- dailyStatsAttributes,+ dailyStatsAttributes.map((attr) => attr.attribute as ProjectDailyStatsAttribute),ref,startDate,endDate,@@ -335,23 +222,48 @@ const useAttributeQueries = (isVisible)- const referenceLineQueries = referenceLines.map((line) => {- let value = line.value || 0-- return {- data: {- data: [], // Will be populated in combinedData- attribute: line.attribute,- total: value,- maximum: value,- totalGrouped: { [line.attribute]: value },- },- isLoading: false,- isError: false,- }- })-- return [...infraQueries, ...dailyStatsQueries, ...referenceLineQueries]+ let infraIdx = 0+ let dailyStatsIdx = 0+ return attributes+ .filter((attr) => attr.provider !== 'logs')+ .map((attr) => {+ if (attr.provider === 'infra-monitoring') {+ return {+ ...infraQueries[infraIdx++],+ data: { ...infraQueries[infraIdx - 1]?.data, provider: 'infra-monitoring' },+ }+ } else if (attr.provider === 'daily-stats') {+ return {+ ...dailyStatsQueries[dailyStatsIdx++],+ data: { ...dailyStatsQueries[dailyStatsIdx - 1]?.data, provider: 'daily-stats' },+ }+ } else if (attr.provider === 'mock') {+ const mockData = getMockDataForAttribute(attr.attribute)+ return {+ isLoading: false,+ data: { ...mockData, provider: 'mock', attribute: attr.attribute },+ }+ } else if (attr.provider === 'reference-line') {+ let value = attr.value || 0+ return {+ data: {+ data: [],+ attribute: attr.attribute,+ total: value,+ maximum: value,+ totalGrouped: { [attr.attribute]: value },+ provider: 'reference-line',+ },+ isLoading: false,+ isError: false,+ }+ } else {+ return {+ isLoading: false,+ data: undefined,+ }+ }+ })}export default function LazyComposedChartHandler(props: ComposedChartHandlerProps) {diff --git a/apps/studio/data/reports/auth-charts.ts b/apps/studio/data/reports/auth-charts.tsnew file mode 100644index 00000000000..7978511209c--- /dev/null+++ b/apps/studio/data/reports/auth-charts.ts@@ -0,0 +1,1197 @@+export const getAuthReportAttributes = (isFreePlan: boolean) => [+ {+ id: 'active-users',+ label: 'Active Users',+ valuePrecision: 0,+ hide: false,+ showTooltip: false,+ showLegend: false,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ attributes: [+ { attribute: 'ActiveUsers', provider: 'logs', label: 'Active Users', enabled: true },+ ],+ },+ {+ id: 'sign-in-attempts',+ label: 'Sign In Attempts by Type',+ valuePrecision: 0,+ hide: false,+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ titleTooltip: 'The total number of sign in attempts by grant type.',+ attributes: [+ {+ attribute: 'SignInAttempts',+ provider: 'logs',+ label: 'Password',+ grantType: 'password',+ enabled: true,+ },+ {+ attribute: 'SignInAttempts',+ provider: 'logs',+ label: 'PKCE',+ grantType: 'pkce',+ enabled: true,+ },+ {+ attribute: 'SignInAttempts',+ provider: 'logs',+ label: 'Refresh Token',+ grantType: 'refresh_token',+ enabled: true,+ },+ {+ attribute: 'SignInAttempts',+ provider: 'logs',+ label: 'ID Token',+ grantType: 'id_token',+ enabled: true,+ },+ ],+ },+ {+ id: 'signups',+ label: 'Sign Ups',+ valuePrecision: 0,+ hide: false,+ showTooltip: true,+ showLegend: false,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ titleTooltip: 'The total number of sign ups.',+ attributes: [+ {+ attribute: 'TotalSignUps',+ provider: 'logs',+ label: 'Sign Ups',+ enabled: true,+ },+ ],+ },+ {+ id: 'auth-errors',+ label: 'Auth Errors',+ valuePrecision: 0,+ hide: false,+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ titleTooltip: 'The total number of auth errors by status code.',+ attributes: [+ {+ attribute: 'ErrorsByStatus',+ provider: 'logs',+ label: 'Auth Errors',+ },+ ],+ },+ {+ id: 'password-reset-requests',+ label: 'Password Reset Requests',+ valuePrecision: 0,+ hide: false,+ showTooltip: false,+ showLegend: false,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'bar',+ attributes: [+ {+ attribute: 'PasswordResetRequests',+ provider: 'logs',+ label: 'Password Reset Requests',+ enabled: true,+ },+ ],+ },+ {+ id: 'sign-in-latency',+ label: 'Sign In Latency',+ valuePrecision: 2,+ hide: true, // Jordi: Hidden until we can fix the query+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'line',+ titleTooltip: 'Average latency for sign in operations by grant type.',+ attributes: [+ {+ attribute: 'SignInLatency',+ provider: 'logs',+ label: 'Password',+ grantType: 'password',+ enabled: true,+ },+ {+ attribute: 'SignInLatency',+ provider: 'logs',+ label: 'PKCE',+ grantType: 'pkce',+ enabled: true,+ },+ {+ attribute: 'SignInLatency',+ provider: 'logs',+ label: 'Refresh Token',+ grantType: 'refresh_token',+ enabled: true,+ },+ {+ attribute: 'SignInLatency',+ provider: 'logs',+ label: 'ID Token',+ grantType: 'id_token',+ enabled: true,+ },+ ],+ },+ {+ id: 'sign-up-latency',+ label: 'Sign Up Latency',+ valuePrecision: 2,+ hide: true, // Jordi: Hidden until we can fix the query+ showTooltip: true,+ showLegend: true,+ showMaxValue: false,+ hideChartType: false,+ defaultChartStyle: 'line',+ titleTooltip: 'Average latency for sign up operations by provider.',+ attributes: [+ {+ attribute: 'SignUpLatency',+ provider: 'logs',+ label: 'Email',+ providerType: 'email',+ enabled: true,+ },+ {+ attribute: 'SignUpLatency',+ provider: 'logs',+ label: 'Google',+ providerType: 'google',+ enabled: true,+ },+ {+ attribute: 'SignUpLatency',+ provider: 'logs',+ label: 'GitHub',+ providerType: 'github',+ enabled: true,+ },+ {+ attribute: 'SignUpLatency',+ provider: 'logs',+ label: 'Apple',+ providerType: 'apple',+ enabled: true,+ },+ ],+ },+]++/**+ * ================================================+ * Mock data below+ * TODO: Remove once we have real data+ * ================================================+ * */++// Time points for all mock data+const DEFAULT_TIME_POINTS = [+ '2025-05-05T13:47:23Z',+ '2025-05-05T14:47:23Z',+ '2025-05-05T15:47:23Z',+ '2025-05-05T16:47:23Z',+ '2025-05-05T17:47:23Z',+ '2025-05-05T18:47:23Z',+ '2025-05-05T19:47:23Z',+ '2025-05-05T20:47:23Z',+ '2025-05-05T21:47:23Z',+ '2025-05-05T22:47:23Z',+ '2025-05-05T23:47:23Z',+ '2025-05-06T00:47:23Z',+ '2025-05-06T01:47:23Z',+ '2025-05-06T02:47:23Z',+ '2025-05-06T03:47:23Z',+ '2025-05-06T04:47:23Z',+ '2025-05-06T05:47:23Z',+ '2025-05-06T06:47:23Z',+ '2025-05-06T07:47:23Z',+ '2025-05-06T08:47:23Z',+ '2025-05-06T09:47:23Z',+ '2025-05-06T10:47:23Z',+ '2025-05-06T11:47:23Z',+ '2025-05-06T12:47:23Z',+ '2025-05-06T13:47:23Z',+]++// Helper to generate random values with some "realistic" patterns+const generatePatternedValues = (+ length: number,+ base: number = 5,+ variance: number = 5,+ spikeProbability: number = 0.1,+ spikeMultiplier: number = 5+): number[] => {+ return Array(length)+ .fill(0)+ .map(() => {+ const hasSpike = Math.random() < spikeProbability+ const baseValue = base + Math.floor(Math.random() * variance)+ return hasSpike ? baseValue * spikeMultiplier : baseValue+ })+}++export const getAuthRequestsMockData = (provider: string) => {+ let values: number[] = []++ if (provider === 'Email') {+ values = [3, 4, 4, 5, 4, 3, 5, 6, 4, 3, 5, 5, 4, 3, 4, 5, 6, 7, 5, 15, 6, 9, 17, 8, 4]+ } else if (provider === 'Google') {+ values = [2, 1, 3, 0, 5, 2, 0, 0, 1, 2, 0, 0, 1, 2, 1, 0, 0, 0, 1, 1, 2, 4, 0, 4, 12]+ } else if (provider === 'GitHub') {+ values = [0, 0, 8, 0, 3, 0, 0, 1, 0, 0, 3, 0, 0, 0, 1, 0, 8, 4, 2, 0, 2, 1, 3, 6, 10]+ } else {+ values = Array(25).fill(0)+ }++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [provider]: values[index],+ }))++ return {+ data,+ yAxisLimit: 100,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++// Add new mock data generator for provider-specific sessions+export const getProviderSessionsMockData = (provider: string) => {+ let values: number[] = []++ // Generate higher base values for sessions compared to signups+ if (provider === 'EmailSessions') {+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 15, 8, 0.1, 2)+ } else if (provider === 'GoogleSessions') {+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 12, 6, 0.1, 2.5)+ } else if (provider === 'GitHubSessions') {+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 10, 5, 0.1, 2.2)+ } else {+ // For other providers, generate lower values+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 5, 3, 0.1, 2)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [provider]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++// Add new mock data generator for provider-specific churn rates+export const getProviderChurnMockData = (provider: string) => {+ let values: number[] = []++ // Generate realistic churn rates (typically between 2-15%)+ if (provider === 'EmailChurn') {+ // Email typically has higher churn+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 2, 10, 0.1, 5.2).map((v) =>+ Math.min(v, 20)+ )+ } else if (provider === 'GoogleChurn') {+ // Google typically has lower churn due to account persistence+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 8, 2, 0.1, 1.3).map((v) =>+ Math.min(v, 15)+ )+ } else if (provider === 'GitHubChurn') {+ // GitHub has moderate churn+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 10, 2.5, 0.1, 1.2).map((v) =>+ Math.min(v, 18)+ )+ } else {+ // Other providers have varying churn rates+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 9, 3, 0.1, 1.4).map((v) =>+ Math.min(v, 20)+ )+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [provider]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: 20, // Max 20% churn rate+ format: '%',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++// Add new mock data generator for churn rates+export const getChurnRateMockData = (attribute: string) => {+ let values: number[] = []++ // Overall churn rate with some variance+ values = generatePatternedValues(DEFAULT_TIME_POINTS.length, 0.6, 2, 0.15, 2.6)+ .map((v) => Math.max(0, v - 0.25)) // Allow some values to go to 0+ .map((v) => Math.min(v, 3.2))++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [attribute]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: 1.5, // Max 1.5% churn rate+ format: '%',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++// Mock data generators for new charts+export const getActiveUsersMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ // Generate more realistic pattern for Daily Active Users+ // Create 30 days of data for a better view+ const thirtyDays = 30+ const thirtyDayDates = Array(thirtyDays)+ .fill(0)+ .map((_, i) => {+ const date = new Date()+ date.setDate(date.getDate() - (thirtyDays - i - 1))+ return date.toISOString()+ })++ // Base values that reflect a gradual growth trend+ const baseValue = 200+ const dailyGrowth = 1.5 // Small daily growth factor++ if (metric === 'DAU') {+ values = Array(thirtyDays)+ .fill(0)+ .map((_, i) => {+ const dayOfWeek = new Date(thirtyDayDates[i]).getDay()+ const isWeekend = dayOfWeek === 0 || dayOfWeek === 6++ // Base value with growth trend+ let value = baseValue + i * dailyGrowth++ // Weekday/weekend pattern (weekends have ~20% less activity)+ if (isWeekend) {+ value = value * 0.8+ }++ // Add some randomness+ const randomFactor = 0.9 + Math.random() * 0.2 // ±10%+ value = value * randomFactor++ return Math.round(value)+ })+ } else {+ // For WAU and MAU (not used in this case)+ values = Array(thirtyDays).fill(0)+ }++ const data = thirtyDayDates.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getUserTypesMockData = (type: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (type === 'NewUsers') {+ values = generatePatternedValues(length, 40, 20, 0.15, 3)+ } else if (type === 'ReturningUsers') {+ values = generatePatternedValues(length, 200, 50, 0.1, 1.5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [type]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getAuthSessionsMockData = (sessionType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (sessionType === 'TotalSessions') {+ values = generatePatternedValues(length, 1200, 300, 0.1, 1.3)+ } else if (sessionType === 'WebSessions') {+ values = generatePatternedValues(length, 800, 200, 0.1, 1.4)+ } else if (sessionType === 'MobileSessions') {+ values = generatePatternedValues(length, 400, 150, 0.12, 1.5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [sessionType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getSessionDurationMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ // Session duration in minutes following a relatively stable pattern+ const values = generatePatternedValues(length, 15, 5, 0.05, 1.5)++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++// Mock data generators for authentication flows+export const getPasswordResetMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (metric === 'PasswordResetRequests') {+ values = generatePatternedValues(length, 25, 15, 0.1, 2)+ } else if (metric === 'PasswordResetCompleted') {+ values = generatePatternedValues(length, 18, 10, 0.1, 1.5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getEmailVerificationMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (metric === 'VerificationSent') {+ values = generatePatternedValues(length, 50, 20, 0.12, 1.8)+ } else if (metric === 'VerificationCompleted') {+ values = generatePatternedValues(length, 35, 15, 0.1, 1.5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getVerificationRatesMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (metric === 'EmailOpenRate') {+ // Email open rates between 50-80%+ values = generatePatternedValues(length, 65, 15, 0.05, 1.2).map((v) => Math.min(v, 100))+ } else if (metric === 'VerificationRate') {+ // Verification completion rates between 60-90%+ values = generatePatternedValues(length, 75, 15, 0.05, 1.1).map((v) => Math.min(v, 100))+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: 100, // Percentage chart+ format: '%',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++export const getMfaUsageMockData = (method: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (method === 'MfaSMS') {+ values = generatePatternedValues(length, 15, 8, 0.1, 1.5)+ } else if (method === 'MfaAuthenticator') {+ values = generatePatternedValues(length, 25, 10, 0.1, 1.4)+ } else if (method === 'MfaEmail') {+ values = generatePatternedValues(length, 10, 5, 0.1, 1.6)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [method]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getMfaAdoptionMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ // MFA adoption between 15-35%+ const values = generatePatternedValues(length, 25, 10, 0.05, 1.2).map((v) => Math.min(v, 100))++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: 100, // Percentage chart+ format: '%',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++// Mock data generators for error and security charts+export const getAuthErrorsMockData = (errorType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (errorType === 'Status403') {+ // 403 Forbidden - Relatively uncommon+ values = generatePatternedValues(length, 1, 1, 0.05, 3)+ } else if (errorType === 'Status422') {+ // 422 Unprocessable Entity - More common validation errors+ values = generatePatternedValues(length, 8, 5, 0.12, 2)+ } else if (errorType === 'Status429') {+ // 429 Too Many Requests - Rate limiting, can be spiky+ values = generatePatternedValues(length, 3, 2, 0.15, 4)+ } else if (errorType === 'Status500') {+ // 500 Internal Server Error - Server errors, usually low but impactful+ values = generatePatternedValues(length, 1, 1, 0.08, 5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [errorType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getProviderErrorRateMockData = (provider: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ // Error rates between 0.5-8%+ if (provider === 'EmailErrorRate') {+ values = generatePatternedValues(length, 2.5, 2, 0.15, 2).map((v) => Math.min(v, 10))+ } else if (provider === 'GoogleErrorRate') {+ values = generatePatternedValues(length, 1.2, 1, 0.1, 2.5).map((v) => Math.min(v, 10))+ } else if (provider === 'GitHubErrorRate') {+ values = generatePatternedValues(length, 1.5, 1.2, 0.12, 2.2).map((v) => Math.min(v, 10))+ } else if (provider === 'FacebookErrorRate') {+ values = generatePatternedValues(length, 2, 1.5, 0.1, 2).map((v) => Math.min(v, 10))+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [provider]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: 10, // Percentage chart+ format: '%',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++export const getRateLimitingMockData = (eventType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (eventType === 'IPRateLimited') {+ values = generatePatternedValues(length, 4, 3, 0.1, 4)+ } else if (eventType === 'UserRateLimited') {+ values = generatePatternedValues(length, 2, 2, 0.08, 3)+ } else if (eventType === 'BruteForceAttempts') {+ values = generatePatternedValues(length, 1, 1, 0.05, 5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [eventType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getAuthLatencyMockData = (operationType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (operationType === 'SignInLatency') {+ values = generatePatternedValues(length, 180, 50, 0.1, 1.5)+ } else if (operationType === 'SignUpLatency') {+ values = generatePatternedValues(length, 250, 70, 0.1, 1.4)+ } else if (operationType === 'TokenRefreshLatency') {+ values = generatePatternedValues(length, 120, 40, 0.1, 1.6)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [operationType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(0)),+ total,+ }+}++export const getSecurityEventsMockData = (eventType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (eventType === 'SuspiciousLogins') {+ values = generatePatternedValues(length, 3, 2, 0.1, 3)+ } else if (eventType === 'NewDeviceLogins') {+ values = generatePatternedValues(length, 15, 8, 0.1, 1.5)+ } else if (eventType === 'PasswordBreachDetections') {+ values = generatePatternedValues(length, 1, 1, 0.05, 5)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [eventType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getTokenUsageMockData = (metricType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (metricType === 'TokenIssuance') {+ values = generatePatternedValues(length, 100, 40, 0.1, 1.5)+ } else if (metricType === 'TokenRefresh') {+ values = generatePatternedValues(length, 400, 100, 0.1, 1.3)+ } else if (metricType === 'TokenRevocation') {+ values = generatePatternedValues(length, 30, 15, 0.1, 2)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metricType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++// Mock data generators for conversion metrics+export const getAuthFunnelMockData = (stage: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (stage === 'PageVisits') {+ values = generatePatternedValues(length, 500, 200, 0.1, 1.5)+ } else if (stage === 'SignupStarts') {+ values = generatePatternedValues(length, 120, 50, 0.1, 1.4)+ } else if (stage === 'SignupCompletes') {+ values = generatePatternedValues(length, 80, 30, 0.1, 1.3)+ } else if (stage === 'FirstLogins') {+ values = generatePatternedValues(length, 75, 25, 0.1, 1.3)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [stage]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getConversionRatesMockData = (rateType: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (rateType === 'VisitToSignupRate') {+ // Visit to signup: 20-30%+ values = generatePatternedValues(length, 25, 5, 0.1, 1.2).map((v) => Math.min(v, 40))+ } else if (rateType === 'SignupCompletionRate') {+ // Signup completion: 60-80%+ values = generatePatternedValues(length, 70, 10, 0.1, 1.1).map((v) => Math.min(v, 90))+ } else if (rateType === 'RetentionRate') {+ // 7-day retention: 40-60%+ values = generatePatternedValues(length, 50, 10, 0.1, 1.1).map((v) => Math.min(v, 75))+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [rateType]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: 100, // Percentage chart+ format: '%',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++export const getOnboardingCompletionMockData = (stage: string) => {+ const length = DEFAULT_TIME_POINTS.length+ let values: number[] = []++ if (stage === 'OnboardingStarts') {+ values = generatePatternedValues(length, 70, 25, 0.1, 1.4)+ } else if (stage === 'ProfileCompletions') {+ values = generatePatternedValues(length, 50, 20, 0.1, 1.3)+ } else if (stage === 'VerificationCompletions') {+ values = generatePatternedValues(length, 40, 15, 0.1, 1.3)+ } else {+ values = Array(length).fill(0)+ }++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [stage]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(2)),+ total,+ }+}++export const getOnboardingTimeMockData = (metric: string) => {+ const length = DEFAULT_TIME_POINTS.length+ // Onboarding time in minutes, generally 5-15 minutes+ const values = generatePatternedValues(length, 10, 5, 0.1, 1.3)++ const data = DEFAULT_TIME_POINTS.map((time, index) => ({+ period_start: time,+ [metric]: values[index],+ }))++ const total = values.reduce((sum, val) => sum + val, 0)+ const totalAverage = total / values.length++ return {+ data,+ yAxisLimit: Math.max(...values) * 1.2,+ format: '',+ totalAverage: parseFloat(totalAverage.toFixed(1)),+ total,+ }+}++// Master mock data resolver - routes to the appropriate data generator based on attribute+export const getMockDataForAttribute = (attribute: string) => {+ // Auth Requests (original chart)+ if (+ [+ 'Email',+ 'Google',+ 'GitHub',+ 'Phone',+ 'SAML',+ 'Apple',+ 'Azure',+ 'Bitbucket',+ 'Discord',+ 'Facebook',+ 'Figma',+ 'GitLab',+ 'Kakao',+ 'KeyCloak',+ 'LinkedIn',+ 'Notion',+ 'Twitch',+ 'Twitter',+ 'Slack',+ 'Spotify',+ 'WorkOS',+ 'Zoom',+ ].includes(attribute)+ ) {+ return getAuthRequestsMockData(attribute)+ }++ // Provider-specific sessions+ if (+ [+ 'EmailSessions',+ 'PhoneSessions',+ 'SAMLSessions',+ 'AppleSessions',+ 'AzureSessions',+ 'BitbucketSessions',+ 'DiscordSessions',+ 'FacebookSessions',+ 'FigmaSessions',+ 'GitHubSessions',+ 'GitLabSessions',+ 'GoogleSessions',+ 'KakaoSessions',+ 'KeyCloakSessions',+ 'LinkedInSessions',+ 'NotionSessions',+ 'TwitchSessions',+ 'TwitterSessions',+ 'SlackSessions',+ 'SpotifySessions',+ 'WorkOSSessions',+ 'ZoomSessions',+ ].includes(attribute)+ ) {+ return getProviderSessionsMockData(attribute)+ }++ // Provider-specific churn+ if (+ [+ 'EmailChurn',+ 'PhoneChurn',+ 'SAMLChurn',+ 'AppleChurn',+ 'AzureChurn',+ 'BitbucketChurn',+ 'DiscordChurn',+ 'FacebookChurn',+ 'FigmaChurn',+ 'GitHubChurn',+ 'GitLabChurn',+ 'GoogleChurn',+ 'KakaoChurn',+ 'KeyCloakChurn',+ 'LinkedInChurn',+ 'NotionChurn',+ 'TwitchChurn',+ 'TwitterChurn',+ 'SlackChurn',+ 'SpotifyChurn',+ 'WorkOSChurn',+ 'ZoomChurn',+ ].includes(attribute)+ ) {+ return getProviderChurnMockData(attribute)+ }++ // Overall churn rate+ if (attribute === 'ChurnRate') {+ return getChurnRateMockData(attribute)+ }++ // Active Users charts+ if (['DAU', 'WAU', 'MAU'].includes(attribute)) {+ return getActiveUsersMockData(attribute)+ }++ // User Types charts+ if (['NewUsers', 'ReturningUsers'].includes(attribute)) {+ return getUserTypesMockData(attribute)+ }++ // Auth Sessions charts+ if (['TotalSessions', 'WebSessions', 'MobileSessions'].includes(attribute)) {+ return getAuthSessionsMockData(attribute)+ }++ // Session Duration+ if (attribute === 'AvgSessionDuration') {+ return getSessionDurationMockData(attribute)+ }++ // Password Reset metrics+ if (['PasswordResetRequests', 'PasswordResetCompleted'].includes(attribute)) {+ return getPasswordResetMockData(attribute)+ }++ // Email Verification metrics+ if (['VerificationSent', 'VerificationCompleted'].includes(attribute)) {+ return getEmailVerificationMockData(attribute)+ }++ // Verification Rates+ if (['EmailOpenRate', 'VerificationRate'].includes(attribute)) {+ return getVerificationRatesMockData(attribute)+ }++ // MFA Usage+ if (['MfaSMS', 'MfaAuthenticator', 'MfaEmail'].includes(attribute)) {+ return getMfaUsageMockData(attribute)+ }++ // MFA Adoption Rate+ if (attribute === 'MfaAdoptionRate') {+ return getMfaAdoptionMockData(attribute)+ }++ // Auth Errors+ if (['Status403', 'Status422', 'Status429', 'Status500'].includes(attribute)) {+ return getAuthErrorsMockData(attribute)+ }++ // Provider Error Rates+ if (+ ['EmailErrorRate', 'GoogleErrorRate', 'GitHubErrorRate', 'FacebookErrorRate'].includes(+ attribute+ )+ ) {+ return getProviderErrorRateMockData(attribute)+ }++ // Rate Limiting+ if (['IPRateLimited', 'UserRateLimited', 'BruteForceAttempts'].includes(attribute)) {+ return getRateLimitingMockData(attribute)+ }++ // Auth Latency+ if (['SignInLatency', 'SignUpLatency', 'TokenRefreshLatency'].includes(attribute)) {+ return getAuthLatencyMockData(attribute)+ }++ // Security Events+ if (['SuspiciousLogins', 'NewDeviceLogins', 'PasswordBreachDetections'].includes(attribute)) {+ return getSecurityEventsMockData(attribute)+ }++ // Token Usage+ if (['TokenIssuance', 'TokenRefresh', 'TokenRevocation'].includes(attribute)) {+ return getTokenUsageMockData(attribute)+ }++ // Auth Funnel+ if (['PageVisits', 'SignupStarts', 'SignupCompletes', 'FirstLogins'].includes(attribute)) {+ return getAuthFunnelMockData(attribute)+ }++ // Conversion Rates+ if (['VisitToSignupRate', 'SignupCompletionRate', 'RetentionRate'].includes(attribute)) {+ return getConversionRatesMockData(attribute)+ }++ // Onboarding Completion+ if (['OnboardingStarts', 'ProfileCompletions', 'VerificationCompletions'].includes(attribute)) {+ return getOnboardingCompletionMockData(attribute)+ }++ // Onboarding Time+ if (attribute === 'TimeToCompleteOnboarding') {+ return getOnboardingTimeMockData(attribute)+ }++ // Default fallback+ return {+ data: DEFAULT_TIME_POINTS.map((time) => ({ period_start: time, [attribute]: 0 })),+ yAxisLimit: 10,+ format: '',+ totalAverage: 0,+ total: 0,+ }+}diff --git a/apps/studio/data/reports/auth-report-query.ts b/apps/studio/data/reports/auth-report-query.tsnew file mode 100644index 00000000000..99f6ec0c352--- /dev/null+++ b/apps/studio/data/reports/auth-report-query.ts@@ -0,0 +1,328 @@+import { useQuery } from '@tanstack/react-query'+import { get } from 'data/fetchers'+import { AnalyticsInterval } from 'data/analytics/constants'+import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'+import { getHttpStatusCodeInfo } from 'lib/http-status-codes'+import { analyticsIntervalToGranularity } from './report.utils'++/**+ * METRICS+ * Each chart in the UI has a corresponding metric key.+ */++const METRIC_KEYS = [+ 'ActiveUsers',+ 'SignInAttempts',+ 'PasswordResetRequests',+ 'TotalSignUps',+ 'SignInLatency',+ 'SignUpLatency',+ 'ErrorsByStatus',+]++const STATUS_CODE_COLORS: { [key: string]: { light: string; dark: string } } = {+ '400': { light: '#FFD54F', dark: '#FFF176' },+ '401': { light: '#FF8A65', dark: '#FFAB91' },+ '403': { light: '#FFB74D', dark: '#FFCC80' },+ '404': { light: '#90A4AE', dark: '#B0BEC5' },+ '409': { light: '#BA68C8', dark: '#CE93D8' },+ '410': { light: '#A1887F', dark: '#BCAAA4' },+ '422': { light: '#FF9800', dark: '#FFB74D' },+ '429': { light: '#E65100', dark: '#F57C00' },+ '500': { light: '#B71C1C', dark: '#D32F2F' },+ '502': { light: '#9575CD', dark: '#B39DDB' },+ '503': { light: '#0097A7', dark: '#4DD0E1' },+ '504': { light: '#C0CA33', dark: '#D4E157' },+ default: { light: '#757575', dark: '#9E9E9E' },+}++type MetricKey = (typeof METRIC_KEYS)[number]++/**+ * SQL+ * Each metric has a corresponding SQL query.+ */++const METRIC_SQL: Record<MetricKey, (interval: AnalyticsInterval) => string> = {+ ActiveUsers: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --active-users+ select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ count(distinct json_value(f.event_message, "$.auth_event.actor_id")) as count+ from auth_logs f+ where json_value(f.event_message, "$.auth_event.action") in (+ 'login', 'user_signedup', 'token_refreshed', 'user_modified',+ 'user_recovery_requested', 'user_reauthenticate_requested'+ )+ group by timestamp+ order by timestamp desc+ `+ },+ SignInAttempts: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --sign-in-attempts+ select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ json_value(event_message, "$.grant_type") as grant_type,+ count(*) as count+ from auth_logs+ where json_value(event_message, "$.path") = '/token'+ group by timestamp, grant_type+ order by timestamp desc, grant_type+ `+ },+ PasswordResetRequests: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --password-reset-requests+ select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ count(*) as count+ from auth_logs f+ where json_value(f.event_message, "$.auth_event.action") = 'user_recovery_requested'+ group by timestamp+ order by timestamp desc+ `+ },+ TotalSignUps: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --total-signups+ select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ count(*) as count+ from auth_logs+ where json_value(event_message, "$.auth_event.action") = 'user_signedup'+ group by timestamp+ order by timestamp desc+ `+ },+ SignInLatency: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --signin-latency+ select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ json_value(event_message, "$.grant_type") as grant_type,+ count(*) as request_count,+ round(avg(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as avg_latency_ms,+ round(min(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as min_latency_ms,+ round(max(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as max_latency_ms,+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(50)] / 1000000, 2) as p50_latency_ms,+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(95)] / 1000000, 2) as p95_latency_ms,+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(99)] / 1000000, 2) as p99_latency_ms+ from auth_logs+ where json_value(event_message, "$.path") = '/token'+ group by timestamp, grant_type+ order by timestamp desc, grant_type+ `+ },+ SignUpLatency: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --signup-latency+ select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ json_value(event_message, "$.auth_event.traits.provider") as provider,+ round(avg(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as avg_latency_ms,+ round(min(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as min_latency_ms,+ round(max(cast(json_value(event_message, "$.duration") as int64)) / 1000000, 2) as max_latency_ms,+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(50)] / 1000000, 2) as p50_latency_ms,+ round(approx_quantiles(cast(json_value(event_message, "$.duration") as int64), 100)[offset(95)] / 1000000, 2) as p95_latency_ms+ from auth_logs+ where json_value(event_message, "$.auth_event.action") = 'user_signedup'+ and json_value(event_message, "$.status") = '200'+ group by timestamp, provider+ order by timestamp desc, provider+ `+ },+ ErrorsByStatus: (interval) => {+ const granularity = analyticsIntervalToGranularity(interval)+ return `+ --auth-errors-by-status+select+ timestamp_trunc(timestamp, ${granularity}) as timestamp,+ count(*) as count,+ response.status_code+from edge_logs+ cross join unnest(metadata) as m+ cross join unnest(m.request) as request+ cross join unnest(m.response) as response+where path like '%/auth%'+ and response.status_code >= 400 and response.status_code <= 599+group by timestamp, status_code+order by timestamp desc+ `+ },+}++/**+ * FORMATTERS.+ * Metrics need to be formatted before being passed on to the UI charts.+ */++function defaultFormatter(rawData: any, attributes: MultiAttribute[]) {+ const chartAttributes = attributes+ if (!rawData) return { data: undefined, chartAttributes }+ const result = rawData.result || []+ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[attributes[0].attribute] = p.count+ })+ return point+ })+ return { data, chartAttributes }+}++const METRIC_FORMATTER: Record<+ MetricKey,+ (+ rawData: any,+ attributes: MultiAttribute[],+ logsMetric: string+ ) => { data: any; chartAttributes: any }+> = {+ ActiveUsers: (rawData, attributes) => defaultFormatter(rawData, attributes),+ SignInAttempts: (rawData, attributes) => {+ const chartAttributes = attributes.map((attr) => {+ if (attr.attribute === 'SignInAttempts' && attr.grantType) {+ return { ...attr, attribute: `${attr.attribute}_${attr.grantType}` }+ }+ return attr+ })+ if (!rawData) return { data: undefined, chartAttributes }+ const result = rawData.result || []+ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[`SignInAttempts_${p.grant_type}`] = p.count+ })+ return point+ })+ return { data, chartAttributes }+ },+ PasswordResetRequests: (rawData, attributes) => defaultFormatter(rawData, attributes),+ TotalSignUps: (rawData, attributes) => defaultFormatter(rawData, attributes),+ SignInLatency: (rawData, attributes) => defaultFormatter(rawData, attributes),+ SignUpLatency: (rawData, attributes) => defaultFormatter(rawData, attributes),+ ErrorsByStatus: (rawData, attributes) => {+ if (!rawData) return { data: undefined, chartAttributes: attributes }+ const result = rawData.result || []++ const statusCodes = Array.from(new Set(result.map((p: any) => p.status_code)))++ const chartAttributes = statusCodes.map((statusCode) => {+ const statusCodeInfo = getHttpStatusCodeInfo(Number(statusCode))+ const color = STATUS_CODE_COLORS[String(statusCode)] || STATUS_CODE_COLORS.default++ return {+ attribute: `status_${statusCode}`,+ label: `${statusCode} ${statusCodeInfo.label}`,+ provider: 'logs',+ enabled: true,+ color: color,+ statusCode: String(statusCode),+ }+ })++ const timestamps = new Set<string>(result.map((p: any) => p.timestamp))+ const data = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }+ chartAttributes.forEach((attr) => {+ point[attr.attribute] = 0+ })+ const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)+ matchingPoints.forEach((p: any) => {+ point[`status_${p.status_code}`] = p.count+ })+ return point+ })++ return { data, chartAttributes }+ },+}++/**+ * REPORT QUERY.+ * Fetching and state management for the report.+ */++export function useAuthLogsReport({+ projectRef,+ attributes,+ startDate,+ endDate,+ interval,+ enabled = true,+}: {+ projectRef: string+ attributes: MultiAttribute[]+ startDate: string+ endDate: string+ interval: AnalyticsInterval+ enabled?: boolean+}) {+ const logsMetric = attributes.length > 0 ? attributes[0].attribute : ''++ const isAuthMetric = METRIC_KEYS.includes(logsMetric)++ const sql = isAuthMetric ? METRIC_SQL[logsMetric](interval) : ''++ const {+ data: rawData,+ error,+ isLoading,+ } = useQuery(+ ['auth-logs-report', projectRef, logsMetric, startDate, endDate, interval, sql],+ async () => {+ const { data, error } = await get(`/platform/projects/{ref}/analytics/endpoints/logs.all`, {+ params: {+ path: { ref: projectRef },+ query: {+ sql,+ iso_timestamp_start: startDate,+ iso_timestamp_end: endDate,+ },+ },+ })+ if (error) throw error+ return data+ },+ {+ enabled: Boolean(projectRef && sql && enabled && isAuthMetric),+ refetchOnWindowFocus: false,+ }+ )++ // Use formatter if available+ const formatter =+ (isAuthMetric ? METRIC_FORMATTER[logsMetric as MetricKey] : undefined) || defaultFormatter+ const { data, chartAttributes } = formatter(rawData, attributes, logsMetric)++ return {+ data,+ attributes: chartAttributes,+ isLoading,+ error,+ }+}diff --git a/apps/studio/data/reports/report.utils.ts b/apps/studio/data/reports/report.utils.tsnew file mode 100644index 00000000000..e41bf7e759d--- /dev/null+++ b/apps/studio/data/reports/report.utils.ts@@ -0,0 +1,21 @@+import { AnalyticsInterval } from 'data/analytics/constants'++export type Granularity = 'minute' | 'hour' | 'day' | 'week'+export function analyticsIntervalToGranularity(interval: AnalyticsInterval): Granularity {+ switch (interval) {+ case '1m':+ return 'minute'+ case '5m':+ return 'minute'+ case '10m':+ return 'minute'+ case '30m':+ return 'minute'+ case '1h':+ return 'hour'+ case '1d':+ return 'day'+ default:+ return 'hour'+ }+}diff --git a/apps/studio/hooks/useChartData.ts b/apps/studio/hooks/useChartData.tsnew file mode 100644index 00000000000..a413d7ee726--- /dev/null+++ b/apps/studio/hooks/useChartData.ts@@ -0,0 +1,188 @@+/**+ * useChartData+ *+ * A hook for fetching and processing data for a chart.+ * This hook is responsible for all the data fetching, combining, and state management logic+ * that was previously inside ComposedChartHandler.+ *+ * It takes all necessary parameters like project reference, date range, and attributes,+ * and returns the final chart data, loading state, and derived attributes.+ */+import { useMemo } from 'react'+import { useRouter } from 'next/router'++import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'+import type { AnalyticsInterval, DataPoint } from 'data/analytics/constants'+import { useAuthLogsReport } from 'data/reports/auth-report-query'+import type { ChartData } from 'components/ui/Charts/Charts.types'+import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'+import { useAttributeQueries } from 'components/ui/Charts/ComposedChartHandler'++export const useChartData = ({+ attributes,+ startDate,+ endDate,+ interval,+ data,+ highlightedValue,+}: {+ attributes: MultiAttribute[]+ startDate: string+ endDate: string+ interval: string+ data?: ChartData+ highlightedValue?: string | number+}) => {+ const router = useRouter()+ const { ref } = router.query+ const state = useDatabaseSelectorStateSnapshot()++ const logsAttributes = attributes.filter((attr) => attr.provider === 'logs')+ const nonLogsAttributes = attributes.filter((attr) => attr.provider !== 'logs')++ const {+ data: logsData,+ attributes: logsChartAttributes,+ isLoading: isLogsLoading,+ } = useAuthLogsReport({+ projectRef: ref as string,+ attributes: logsAttributes,+ startDate,+ endDate,+ interval: interval as AnalyticsInterval,+ enabled: logsAttributes.length > 0,+ })++ const chartAttributes = useMemo(+ () => nonLogsAttributes.concat(logsChartAttributes || []),+ [nonLogsAttributes, logsChartAttributes]+ )++ const databaseIdentifier = state.selectedDatabaseId++ // Use the custom hook at the top level of the component+ const attributeQueries = useAttributeQueries(+ attributes,+ ref,+ startDate,+ endDate,+ interval as AnalyticsInterval,+ databaseIdentifier,+ data,+ true+ )++ // Combine all the data into a single dataset+ const combinedData = useMemo(() => {+ if (data) return data++ const regularAttributeQueries = attributeQueries.filter(+ (q) => q.data?.provider !== 'logs' && q.data?.provider !== 'reference-line'+ )+ const isLoading =+ (logsAttributes.length > 0 && isLogsLoading) ||+ regularAttributeQueries.some((query: any) => query.isLoading)+ if (isLoading) {+ return undefined+ }++ const hasError = regularAttributeQueries.some((query: any) => !query.data)+ if (hasError) {+ return undefined+ }++ // Get all unique timestamps from all datasets+ const timestamps = new Set<string>()+ if (logsData) {+ logsData.forEach((point: any) => {+ if (point?.period_start) {+ timestamps.add(point.period_start)+ }+ })+ }+ regularAttributeQueries.forEach((query: any) => {+ query.data?.data?.forEach((point: any) => {+ if (point?.period_start) {+ timestamps.add(point.period_start)+ }+ })+ })++ const referenceLineQueries = attributeQueries.filter(+ (q) => q.data?.provider === 'reference-line'+ )++ // Combine data points for each timestamp+ const combined = Array.from(timestamps)+ .sort()+ .map((timestamp) => {+ const point: any = { period_start: timestamp }++ const logPoint = logsData?.find((p: any) => p.period_start === timestamp) || {}+ Object.assign(point, logPoint)++ chartAttributes.forEach((attr) => {+ if (!attr) return+ if (attr.provider === 'logs') return+ if (attr.provider === 'reference-line') return+ if (attr.customValue !== undefined) {+ point[attr.attribute] = attr.customValue+ return+ }++ const query = regularAttributeQueries.find((q) => q.data?.attribute === attr.attribute)+ const matchingPoint = query?.data?.data?.find((p: any) => p.period_start === timestamp)+ point[attr.attribute] = matchingPoint?.[attr.attribute] ?? 0+ })++ // Add reference line values for each timestamp+ referenceLineQueries.forEach((query: any) => {+ const attr = query.data.attribute+ const value = query.data.total+ point[attr] = value+ })++ return point as DataPoint+ })++ return combined as DataPoint[]+ }, [data, attributeQueries, attributes, chartAttributes, isLogsLoading, logsData, logsAttributes])++ const loading =+ (logsAttributes.length > 0 && isLogsLoading) ||+ attributeQueries.some((query: any) => query.isLoading)++ // Calculate highlighted value based on the first attribute's data+ const _highlightedValue = useMemo(() => {+ if (highlightedValue !== undefined) return highlightedValue++ const firstAttr = attributes[0]+ const firstQuery = attributeQueries[0]+ const firstData = firstQuery?.data++ if (!firstData) return undefined++ const shouldHighlightMaxValue =+ firstAttr.provider === 'daily-stats' &&+ !firstAttr.attribute.includes('ingress') &&+ !firstAttr.attribute.includes('egress') &&+ 'maximum' in firstData++ const shouldHighlightTotalGroupedValue = 'totalGrouped' in firstData++ return shouldHighlightMaxValue+ ? firstData.maximum+ : firstAttr.provider === 'daily-stats'+ ? firstData.total+ : shouldHighlightTotalGroupedValue+ ? firstData.totalGrouped?.[firstAttr.attribute as keyof typeof firstData.totalGrouped]+ : (firstData.data?.[firstData.data?.length - 1] as any)?.[firstAttr.attribute]+ }, [highlightedValue, attributes, attributeQueries])++ return {+ data: combinedData,+ isLoading: loading,+ chartAttributes,+ highlightedValue: _highlightedValue,+ }+}diff --git a/apps/studio/lib/http-status-codes.test.ts b/apps/studio/lib/http-status-codes.test.tsnew file mode 100644index 00000000000..171f4950fe0--- /dev/null+++ b/apps/studio/lib/http-status-codes.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest'+import { getHttpStatusCodeInfo } from './http-status-codes'++describe('getHttpStatusCodeInfo', () => {+ it('should return the correct status code info', () => {+ const statusCodeInfo = getHttpStatusCodeInfo(400)+ expect(statusCodeInfo).toEqual({+ code: 400,+ name: 'BAD_REQUEST',+ message: 'The server cannot or will not process the request due to an apparent client error.',+ label: 'Bad Request',+ })+ })++ it('should return unknown for an unknown status code', () => {+ const statusCodeInfo = getHttpStatusCodeInfo(999)+ expect(statusCodeInfo).toEqual({+ code: 999,+ name: 'UNKNOWN',+ message: 'Unknown status code',+ label: 'Unknown',+ })+ })+})diff --git a/apps/studio/lib/http-status-codes.ts b/apps/studio/lib/http-status-codes.tsnew file mode 100644index 00000000000..4e0d2042985--- /dev/null+++ b/apps/studio/lib/http-status-codes.ts@@ -0,0 +1,30 @@+import { status } from 'http-status'++export function getHttpStatusCodeInfo(codeNumber: number): {+ code: number+ name: string+ message: string+ label: string+} {+ type StatusCodeKey = keyof typeof status++ if (!(codeNumber in status)) {+ return {+ code: codeNumber,+ name: 'UNKNOWN',+ message: 'Unknown status code',+ label: 'Unknown',+ }+ }++ const statusCodeLabel = status[codeNumber as StatusCodeKey]+ const statusCodeMessage = status[`${codeNumber}_MESSAGE` as StatusCodeKey]+ const statusCodeName = status[`${codeNumber}_NAME` as StatusCodeKey]++ return {+ code: codeNumber,+ name: statusCodeName as string,+ label: statusCodeLabel as string,+ message: statusCodeMessage as string,+ }+}diff --git a/apps/studio/package.json b/apps/studio/package.jsonindex b81ddd9fbed..f7e586bacd0 100644--- a/apps/studio/package.json+++ b/apps/studio/package.json@@ -84,6 +84,7 @@"framer-motion": "^11.11.17","generate-password-browser": "^1.1.0","html-to-image": "^1.10.8",+ "http-status": "^2.1.0","icons": "workspace:*","idb": "^8.0.2","immutability-helper": "^3.1.1",diff --git a/apps/studio/pages/project/[ref]/reports/auth.tsx b/apps/studio/pages/project/[ref]/reports/auth.tsxnew file mode 100644index 00000000000..74a0fea6a27--- /dev/null+++ b/apps/studio/pages/project/[ref]/reports/auth.tsx@@ -0,0 +1,166 @@+import { useState } from 'react'+import { useQueryClient } from '@tanstack/react-query'+import dayjs from 'dayjs'+import { ArrowRight, RefreshCw } from 'lucide-react'+import { useParams } from 'common'++import ReportHeader from 'components/interfaces/Reports/ReportHeader'+import ReportPadding from 'components/interfaces/Reports/ReportPadding'+import DefaultLayout from 'components/layouts/DefaultLayout'+import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { DateRangePicker } from 'components/ui/DateRangePicker'++import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'+import { TIME_PERIODS_INFRA } from 'lib/constants/metrics'+import { getAuthReportAttributes } from 'data/reports/auth-charts'++import ReportChart from 'components/interfaces/Reports/ReportChart'+import type { NextPageWithLayout } from 'types'++const AuthReport: NextPageWithLayout = () => {+ return (+ <ReportPadding>+ <AuthUsage />+ </ReportPadding>+ )+}++AuthReport.getLayout = (page) => (+ <DefaultLayout>+ <ReportsLayout title="Auth">{page}</ReportsLayout>+ </DefaultLayout>+)++export type UpdateDateRange = (from: string, to: string) => void+export default AuthReport++const AuthUsage = () => {+ const { ref } = useParams()++ const defaultStart = dayjs().subtract(1, 'day').toISOString()+ const defaultEnd = dayjs().toISOString()+ const [dateRange, setDateRange] = useState<any>({+ period_start: { date: defaultStart, time_period: '1d' },+ period_end: { date: defaultEnd, time_period: 'today' },+ interval: '1h',+ })++ const queryClient = useQueryClient()+ const [isRefreshing, setIsRefreshing] = useState(false)++ const { plan: orgPlan, isLoading: isOrgPlanLoading } = useCurrentOrgPlan()+ const isFreePlan = !isOrgPlanLoading && orgPlan?.id === 'free'++ const AUTH_REPORT_ATTRIBUTES = getAuthReportAttributes(isFreePlan)++ const onRefreshReport = async () => {+ if (!dateRange) return++ setIsRefreshing(true)+ AUTH_REPORT_ATTRIBUTES.forEach((attr) => {+ attr.attributes.forEach((subAttr) => {+ queryClient.invalidateQueries([+ 'auth-metrics',+ ref,+ subAttr.attribute,+ dateRange.period_start.date,+ dateRange.period_end.date,+ dateRange.interval,+ ])+ })+ })+ setTimeout(() => setIsRefreshing(false), 1000)+ }++ const handleIntervalGranularity = (from: string, to: string) => {+ const conditions = {+ '1m': dayjs(to).diff(from, 'hour') < 3, // less than 3 hours+ '10m': dayjs(to).diff(from, 'hour') < 6, // less than 6 hours+ '30m': dayjs(to).diff(from, 'hour') < 18, // less than 18 hours+ '1h': dayjs(to).diff(from, 'day') < 10, // less than 10 days+ '1d': dayjs(to).diff(from, 'day') >= 10, // more than 10 days+ }++ switch (true) {+ case conditions['1m']:+ return '1m'+ case conditions['10m']:+ return '10m'+ case conditions['30m']:+ return '30m'+ default:+ return '1h'+ }+ }++ const updateDateRange: UpdateDateRange = (from: string, to: string) => {+ setDateRange({+ period_start: { date: from, time_period: '1d' },+ period_end: { date: to, time_period: 'today' },+ interval: handleIntervalGranularity(from, to),+ })+ }++ return (+ <>+ <ReportHeader title="Auth" />+ <section className="relative pt-16 -mt-2">+ <div className="absolute inset-0 z-40 pointer-events-none flex flex-col gap-4">+ <div className="sticky top-0 py-4 mb-4 flex items-center space-x-3 pointer-events-auto dark:bg-background-200 bg-background">+ <ButtonTooltip+ type="default"+ disabled={isRefreshing}+ icon={<RefreshCw className={isRefreshing ? 'animate-spin' : ''} />}+ className="w-7"+ tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}+ onClick={onRefreshReport}+ />+ <div className="flex items-center gap-3">+ <DateRangePicker+ loading={false}+ value={'1d'}+ options={TIME_PERIODS_INFRA}+ currentBillingPeriodStart={undefined}+ onChange={(values) => {+ if (values.interval === '1d') {+ setDateRange({ ...values, interval: '1h' })+ } else {+ setDateRange(values)+ }+ }}+ />+ {dateRange && (+ <div className="flex items-center gap-x-2 text-xs">+ <p className="text-foreground-light">+ {dayjs(dateRange.period_start.date).format('MMM D, h:mma')}+ </p>+ <p className="text-foreground-light">+ <ArrowRight size={12} />+ </p>+ <p className="text-foreground-light">+ {dayjs(dateRange.period_end.date).format('MMM D, h:mma')}+ </p>+ </div>+ )}+ </div>+ </div>+ </div>++ <div className="grid grid-cols-1 gap-4">+ {dateRange &&+ AUTH_REPORT_ATTRIBUTES.filter((attr) => !attr.hide).map((attr, i) => (+ <ReportChart+ key={`${attr.id}-${i}`}+ chart={attr}+ interval={dateRange.interval}+ startDate={dateRange?.period_start?.date}+ endDate={dateRange?.period_end?.date}+ updateDateRange={updateDateRange}+ />+ ))}+ </div>+ </section>+ </>+ )+}diff --git a/apps/studio/pages/project/[ref]/reports/database.tsx b/apps/studio/pages/project/[ref]/reports/database.tsxindex 7e883005489..3a1952fc28a 100644--- a/apps/studio/pages/project/[ref]/reports/database.tsx+++ b/apps/studio/pages/project/[ref]/reports/database.tsx@@ -21,7 +21,6 @@ import ChartHandler from 'components/ui/Charts/ChartHandler'import Panel from 'components/ui/Panel'import ShimmerLine from 'components/ui/ShimmerLine'import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'-import ComposedChartHandler from 'components/ui/Charts/ComposedChartHandler'import { DateRangePicker } from 'components/ui/DateRangePicker'import GrafanaPromoBanner from 'components/ui/GrafanaPromoBanner'@@ -37,8 +36,8 @@ import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'import { TIME_PERIODS_INFRA } from 'lib/constants/metrics'import { formatBytes } from 'lib/helpers'+import ReportChart from 'components/interfaces/Reports/ReportChart'import type { NextPageWithLayout } from 'types'-import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'const DatabaseReport: NextPageWithLayout = () => {return (@@ -208,15 +207,10 @@ const DatabaseUsage = () => {return (<><ReportHeader showDatabaseSelector title="Database" />- <div className="w-full flex flex-col gap-1">- <div className="h-2 w-full">- <ShimmerLine active={report.isLoading} />- </div>- </div><GrafanaPromoBanner /><section className="relative pt-16 -mt-2"><div className="absolute inset-0 z-40 pointer-events-none flex flex-col gap-4">- <div className="sticky top-0 bg-200 py-4 mb-4 flex items-center space-x-3 pointer-events-auto">+ <div className="sticky top-0 py-4 mb-4 flex items-center space-x-3 pointer-events-auto dark:bg-background-200 bg-background"><ButtonTooltiptype="default"disabled={isRefreshing}@@ -259,20 +253,13 @@ const DatabaseUsage = () => {<div className="grid grid-cols-1 gap-4">{dateRange &&REPORT_ATTRIBUTES_V2.filter((chart) => !chart.hide).map((chart) => (- <ComposedChartHandler+ <ReportChartkey={chart.id}- {...chart}- attributes={chart.attributes as MultiAttribute[]}- interval={dateRange.interval}+ chart={chart}startDate={dateRange?.period_start?.date}endDate={dateRange?.period_end?.date}+ interval={dateRange.interval}updateDateRange={updateDateRange}- defaultChartStyle={chart.defaultChartStyle as 'line' | 'bar' | 'stackedAreaLine'}- showMaxValue={- chart.id === 'client-connections' || chart.id === 'pgbouncer-connections'- ? true- : chart.showMaxValue- }/>))}</div>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5968c9d1f35..f3ac524c098 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -331,7 +331,7 @@ importers:version: 1.0.3(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])'@sentry/nextjs':specifier: ^9.15.0- version: 9.15.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected])([email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])+ version: 9.15.0(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected])([email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])'@supabase/supabase-js':specifier: 'catalog:'version: 2.49.3@@ -451,7 +451,7 @@ importers:nuqs:specifier: ^1.19.1- version: 1.19.1([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))+ version: 1.19.1([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))openai:specifier: ^4.20.1version: 4.71.1([email protected])([email protected])@@ -828,6 +828,9 @@ importers:html-to-image:specifier: ^1.10.8version: 1.11.11+ http-status:+ specifier: ^2.1.0+ version: 2.1.0icons:specifier: workspace:*version: link:../../packages/icons@@ -1131,7 +1134,7 @@ importers:version: 2.4.11([email protected])next-router-mock:specifier: ^0.9.13- version: 0.9.13([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])+ version: 0.9.13([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])postcss:specifier: ^8.5.3version: 8.5.3@@ -2287,7 +2290,7 @@ importers:version: link:../api-typesnext-router-mock:specifier: ^0.9.13- version: 0.9.13([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])+ version: 0.9.13([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])tsx:specifier: ^4.19.3version: 4.19.3@@ -11032,7 +11035,6 @@ packages:resolution: {integrity: sha512-t0q23FIpvHDTtnORW+bDJziGsal5uh9RJTJ1fyH8drd4lICOoXhJ5pLMUZ5C0VQei6dNmwTzzoTRgMkO9JgHEQ==}peerDependencies:eslint: '>= 5'- bundledDependencies: []resolution: {integrity: sha512-ixmkI62Rbc2/w8Vfxyh1jQRTdRTF52VxwRVHl/ykPAmqG+Nb7/kNn+byLP0LxPgI7zWA16Jt82SybJInmMia3A==}@@ -25381,7 +25383,7 @@ snapshots:- supports-color- webpack- '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected])([email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])':+ '@sentry/[email protected](@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected])([email protected]))(@opentelemetry/[email protected](@opentelemetry/[email protected]))([email protected])([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected])([email protected])([email protected])':dependencies:'@opentelemetry/api': 1.9.0'@opentelemetry/semantic-conventions': 1.32.0@@ -34321,7 +34323,7 @@ snapshots:dependencies:js-yaml-loader: 1.2.2- [email protected]([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]):+ [email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected]))([email protected]):dependencies:next: 15.3.1(@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])react: 18.3.1@@ -34658,7 +34660,7 @@ snapshots:- [email protected]([email protected](@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected])):+ [email protected]([email protected](@opentelemetry/[email protected])(@playwright/[email protected])([email protected]([email protected]))([email protected])([email protected])):dependencies:mitt: 3.0.1next: 15.3.1(@babel/[email protected]([email protected]))(@opentelemetry/[email protected])(@playwright/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected])