Skip to content

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

Reports consolidation 1: Edge Functions (#38129)

Jordi Enricf65884f341d3
diff --git a/apps/studio/components/interfaces/Reports/ReportChart.tsx b/apps/studio/components/interfaces/Reports/ReportChart.tsx
index 41f9a8b4a2a..de4d39b45d8 100644
--- a/apps/studio/components/interfaces/Reports/ReportChart.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportChart.tsx
@@ -1,36 +1,13 @@
-/**
- * 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 Link from 'next/link'
-import { useRef, useState } from 'react'
-
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
import LogChartHandler from 'components/ui/Charts/LogChartHandler'
-import Panel from 'components/ui/Panel'
import { useFillTimeseriesSorted } from 'hooks/analytics/useFillTimeseriesSorted'
import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
import { useChartData } from 'hooks/useChartData'
import type { UpdateDateRange } from 'pages/project/[ref]/reports/database'
-import { Button, cn } from 'ui'
+import { ReportChartUpsell } from './v2/ReportChartUpsell'
-const ReportChart = ({
- chart,
- startDate,
- endDate,
- interval,
- updateDateRange,
- functionIds,
- isLoading,
- className,
-}: {
+interface ReportChartProps {
chart: any
startDate: string
endDate: string
@@ -38,13 +15,28 @@ const ReportChart = ({
updateDateRange: UpdateDateRange
functionIds?: string[]
isLoading?: boolean
- className?: string
-}) => {
+}
+
+/**
+ * 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.
+ */
+export const ReportChart = ({
+ chart,
+ startDate,
+ endDate,
+ interval,
+ updateDateRange,
+ functionIds,
+ isLoading,
+}: ReportChartProps) => {
const { data: org } = useSelectedOrganizationQuery()
const { plan: orgPlan } = useCurrentOrgPlan()
const orgPlanId = orgPlan?.id
- const [isHoveringUpgrade, setIsHoveringUpgrade] = useState(false)
const isAvailable =
chart.availableIn === undefined || (orgPlanId && chart.availableIn.includes(orgPlanId))
@@ -87,77 +79,8 @@ const ReportChart = ({
? filledData
: chartDataArray
- const getExpDemoChartData = () =>
- new Array(20).fill(0).map((_, index) => ({
- period_start: new Date(startDate).getTime() + index * 1000,
- demo: Math.floor(Math.pow(1.25, index) * 10),
- max_demo: 1000,
- }))
-
- const getDemoChartData = () =>
- new Array(20).fill(0).map((_, index) => ({
- period_start: new Date(startDate).getTime() + index * 1000,
- demo: Math.floor(Math.random() * 10) + 1,
- max_demo: 1000,
- }))
-
- // [Jordi] useRef to prevent re-rendering making the chart change.
- const demoChartData = useRef(getDemoChartData())
- const exponentialChartData = useRef(getExpDemoChartData())
-
- const chartData = isHoveringUpgrade ? exponentialChartData.current : demoChartData.current
-
if (!isAvailable && !isLoading) {
- return (
- <Panel
- title={<p className="text-sm">{chart.label}</p>}
- className={cn('h-[260px] relative', className)}
- >
- <div className="z-10 flex flex-col items-center justify-center space-y-2 h-full absolute top-0 left-0 w-full bg-surface-100/70 backdrop-blur-md">
- <h2>{chart.label}</h2>
- <p className="text-sm text-foreground-light">
- This chart is available from{' '}
- <span className="capitalize">
- {!!chart.availableIn?.length ? chart.availableIn[0] : 'Pro'}
- </span>{' '}
- plan and above
- </p>
- <Button
- asChild
- type="primary"
- onMouseEnter={() => setIsHoveringUpgrade(true)}
- onMouseLeave={() => setIsHoveringUpgrade(false)}
- >
- <Link href={`/org/${org?.slug}/billing?panel=subscriptionPlan&source=reports`}>
- Upgrade to{' '}
- <span className="capitalize">
- {!!chart.availableIn?.length ? chart.availableIn[0] : 'Pro'}
- </span>
- </Link>
- </Button>
- </div>
- <div className="absolute top-0 left-0 w-full h-full z-0">
- <LogChartHandler
- attributes={[
- {
- attribute: 'demo',
- enabled: true,
- label: 'Demo',
- provider: 'logs',
- },
- ]}
- label={chart.label}
- startDate={startDate}
- endDate={endDate}
- interval={interval}
- data={chartData as any}
- isLoading={false}
- highlightedValue={0}
- updateDateRange={updateDateRange}
- />
- </div>
- </Panel>
- )
+ return <ReportChartUpsell report={chart} orgSlug={org?.slug ?? ''} />
}
return (
@@ -171,4 +94,3 @@ const ReportChart = ({
/>
)
}
-export default ReportChart
diff --git a/apps/studio/components/interfaces/Reports/Reports.utils.test.ts b/apps/studio/components/interfaces/Reports/Reports.utils.test.ts
new file mode 100644
index 00000000000..8884c0e8a70
--- /dev/null
+++ b/apps/studio/components/interfaces/Reports/Reports.utils.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest'
+import { formatTimestamp } from './Reports.utils'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+dayjs.extend(utc)
+
+describe('formatTimestamp', () => {
+ it('formats milliseconds timestamp correctly', () => {
+ const timestamp = 1640995200000 // 2022-01-01 00:00:00 UTC in milliseconds
+ const result = formatTimestamp(timestamp, { returnUtc: true })
+ expect(result).toBe('Jan 1, 12:00am')
+ })
+
+ it('formats microseconds timestamp correctly', () => {
+ const timestamp = 1640995200000000 // 2022-01-01 00:00:00 UTC in microseconds
+ const result = formatTimestamp(timestamp, { returnUtc: true })
+ expect(result).toBe('Jan 1, 12:00am')
+ })
+
+ it('formats seconds timestamp correctly', () => {
+ const timestamp = 1640995200 // 2022-01-01 00:00:00 UTC in seconds
+ const result = formatTimestamp(timestamp, { returnUtc: true })
+ expect(result).toBe('Jan 1, 12:00am')
+ })
+
+ it('handles string timestamp input', () => {
+ const timestamp = '1640995200000'
+ const result = formatTimestamp(timestamp, { returnUtc: true })
+ expect(result).toBe('Jan 1, 12:00am')
+ })
+
+ it('handles invalid string timestamp', () => {
+ const timestamp = 'invalid-timestamp'
+ const result = formatTimestamp(timestamp, { returnUtc: true })
+ expect(result).toBe('Invalid Date')
+ })
+
+ it('handles zero timestamp', () => {
+ const timestamp = 0
+ const result = formatTimestamp(timestamp, { returnUtc: true })
+ expect(result).toBe('Jan 1, 12:00am')
+ })
+})
diff --git a/apps/studio/components/interfaces/Reports/Reports.utils.tsx b/apps/studio/components/interfaces/Reports/Reports.utils.tsx
index eb2337e6ce1..f0eef8b93ad 100644
--- a/apps/studio/components/interfaces/Reports/Reports.utils.tsx
+++ b/apps/studio/components/interfaces/Reports/Reports.utils.tsx
@@ -1,3 +1,5 @@
+import dayjs from 'dayjs'
+
import useDbQuery, { DbQueryHook } from 'hooks/analytics/useDbQuery'
import useLogsQuery, { LogsQueryHook } from 'hooks/analytics/useLogsQuery'
import type { BaseQueries, PresetConfig, ReportQuery } from './Reports.types'
@@ -9,10 +11,13 @@ export const queryParamsToObject = (params: string) => {
return Object.fromEntries(new URLSearchParams(params))
}
-// generate hooks based on preset config
export type PresetHookResult = LogsQueryHook | DbQueryHook
type PresetHooks = Record<keyof PresetConfig['queries'], () => PresetHookResult>
-
+/**
+ * @deprecated
+ * Queries are hooks, avoid generating hooks dynamically
+ * Generate fetch functions instead, and pass it to a hook inside the component
+ */
export const queriesFactory = <T extends string>(
queries: BaseQueries<T>,
projectRef: string
@@ -35,3 +40,36 @@ export const queriesFactory = <T extends string>(
)
return hooks
}
+
+/**
+ * Formats a timestamp to a human readable format in UTC
+ *
+ * @param timestamp - The timestamp to format
+ * @param returnUtc - Whether to return the timestamp in UTC
+ * @param format - The format to use for the timestamp
+ * @returns The formatted timestamp string
+ */
+export const formatTimestamp = (
+ timestamp: number | string,
+ { returnUtc = false, format = 'MMM D, h:mma' }: { returnUtc?: boolean; format?: string } = {}
+) => {
+ try {
+ const isSeconds = String(timestamp).length === 10
+ const isMicroseconds = String(timestamp).length === 16
+
+ const timestampInMs = isSeconds
+ ? Number(timestamp) * 1000
+ : isMicroseconds
+ ? Number(timestamp) / 1000
+ : Number(timestamp)
+
+ if (returnUtc) {
+ return dayjs.utc(timestampInMs).format(format)
+ } else {
+ return dayjs(timestampInMs).format(format)
+ }
+ } catch (error) {
+ console.error(error)
+ return 'Invalid Date'
+ }
+}
diff --git a/apps/studio/components/interfaces/Reports/v2/ReportChartUpsell.tsx b/apps/studio/components/interfaces/Reports/v2/ReportChartUpsell.tsx
new file mode 100644
index 00000000000..5a31fa5a00e
--- /dev/null
+++ b/apps/studio/components/interfaces/Reports/v2/ReportChartUpsell.tsx
@@ -0,0 +1,81 @@
+import Link from 'next/link'
+import { useRef, useState } from 'react'
+
+import { LogChartHandler } from 'components/ui/Charts/LogChartHandler'
+import { ReportConfig } from 'data/reports/v2/reports.types'
+import { Button, Card, cn } from 'ui'
+
+export function ReportChartUpsell({ report, orgSlug }: { report: ReportConfig; orgSlug: string }) {
+ const [isHoveringUpgrade, setIsHoveringUpgrade] = useState(false)
+
+ const startDate = '2025-01-01'
+ const endDate = '2025-01-02'
+
+ const getExpDemoChartData = () =>
+ new Array(20).fill(0).map((_, index) => ({
+ period_start: new Date(startDate).getTime() + index * 1000,
+ demo: Math.floor(Math.pow(1.25, index) * 10),
+ max_demo: 1000,
+ }))
+
+ const getDemoChartData = () =>
+ new Array(20).fill(0).map((_, index) => ({
+ period_start: new Date(startDate).getTime() + index * 1000,
+ demo: Math.floor(Math.random() * 10) + 1,
+ max_demo: 1000,
+ }))
+
+ const demoChartData = useRef(getDemoChartData())
+ const exponentialChartData = useRef(getExpDemoChartData())
+
+ const demoData = isHoveringUpgrade ? exponentialChartData.current : demoChartData.current
+
+ return (
+ <Card className={cn('h-[260px] relative')}>
+ <div className="z-10 flex flex-col items-center justify-center space-y-2 h-full absolute top-0 left-0 w-full bg-surface-100/70 backdrop-blur-md">
+ <h2 className="text-sm">{report.label}</h2>
+ <p className="text-sm text-foreground-light">
+ This chart is available from{' '}
+ <span className="capitalize">
+ {!!report.availableIn?.length ? report.availableIn[0] : 'Pro'}
+ </span>{' '}
+ plan and above
+ </p>
+ <Button
+ asChild
+ type="primary"
+ onMouseEnter={() => setIsHoveringUpgrade(true)}
+ onMouseLeave={() => setIsHoveringUpgrade(false)}
+ className="mt-4"
+ >
+ <Link href={`/org/${orgSlug}/billing?panel=subscriptionPlan&source=reports`}>
+ Upgrade to{' '}
+ <span className="capitalize">
+ {!!report.availableIn?.length ? report.availableIn[0] : 'Pro'}
+ </span>
+ </Link>
+ </Button>
+ </div>
+ <div className="absolute top-0 left-0 w-full h-full z-0">
+ <LogChartHandler
+ attributes={[
+ {
+ attribute: 'demo',
+ enabled: true,
+ label: 'Demo',
+ provider: 'logs',
+ },
+ ]}
+ label={''}
+ startDate={startDate}
+ endDate={endDate}
+ interval={'1d'}
+ data={demoData as any}
+ isLoading={false}
+ highlightedValue={0}
+ updateDateRange={() => {}}
+ />
+ </div>
+ </Card>
+ )
+}
diff --git a/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx b/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx
new file mode 100644
index 00000000000..36538a71681
--- /dev/null
+++ b/apps/studio/components/interfaces/Reports/v2/ReportChartV2.tsx
@@ -0,0 +1,139 @@
+import { useQuery } from '@tanstack/react-query'
+import { Loader2 } from 'lucide-react'
+import { useState } from 'react'
+
+import { ComposedChart } from 'components/ui/Charts/ComposedChart'
+import type { AnalyticsInterval } from 'data/analytics/constants'
+import type { ReportConfig } from 'data/reports/v2/reports.types'
+import { useFillTimeseriesSorted } from 'hooks/analytics/useFillTimeseriesSorted'
+import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
+import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { Card, CardContent, cn } from 'ui'
+import { ReportChartUpsell } from './ReportChartUpsell'
+
+export interface ReportChartV2Props {
+ report: ReportConfig
+ projectRef: string
+ startDate: string
+ endDate: string
+ interval: AnalyticsInterval
+ updateDateRange: (from: string, to: string) => void
+ functionIds?: string[]
+ edgeFnIdToName?: (id: string) => string | undefined
+ className?: string
+ syncId?: string
+}
+
+export const ReportChartV2 = ({
+ report,
+ projectRef,
+ startDate,
+ endDate,
+ interval,
+ updateDateRange,
+ functionIds,
+ edgeFnIdToName,
+ className,
+ syncId,
+}: ReportChartV2Props) => {
+ const { data: org } = useSelectedOrganizationQuery()
+ const { plan: orgPlan } = useCurrentOrgPlan()
+ const orgPlanId = orgPlan?.id
+
+ const isAvailable =
+ report.availableIn === undefined || (orgPlanId && report.availableIn.includes(orgPlanId))
+
+ const canFetch = orgPlanId !== undefined
+
+ const {
+ data: queryResult,
+ isLoading: isLoadingChart,
+ error,
+ } = useQuery(
+ ['projects', projectRef, 'report-v2', report.id, { startDate, endDate, interval, functionIds }],
+ async () => {
+ return await report.dataProvider(
+ projectRef,
+ startDate,
+ endDate,
+ interval,
+ functionIds,
+ edgeFnIdToName
+ )
+ },
+ {
+ enabled: Boolean(projectRef && canFetch && isAvailable),
+ refetchOnWindowFocus: false,
+ }
+ )
+
+ const chartData = queryResult?.data || []
+ const dynamicAttributes = queryResult?.attributes || []
+
+ const { data: filledChartData, isError: isFillError } = useFillTimeseriesSorted(
+ chartData,
+ 'timestamp',
+ (dynamicAttributes as any[]).map((attr: any) => attr.attribute),
+ 0,
+ startDate,
+ endDate,
+ undefined,
+ interval
+ )
+
+ const finalChartData =
+ filledChartData && filledChartData.length > 0 && !isFillError ? filledChartData : chartData
+
+ const [chartStyle, setChartStyle] = useState<string>(report.defaultChartStyle)
+
+ if (!isAvailable && !isLoadingChart) {
+ return <ReportChartUpsell report={report} orgSlug={org?.slug ?? ''} />
+ }
+
+ const isErrorState = error && !isLoadingChart
+ const showEmptyState = (!finalChartData || finalChartData.length === 0) && !isLoadingChart
+
+ return (
+ <Card id={report.id} className={cn('relative w-full overflow-hidden scroll-mt-16', className)}>
+ <CardContent className="flex flex-col gap-4 min-h-[280px] items-center justify-center">
+ {isLoadingChart ? (
+ <Loader2 className="size-5 animate-spin text-foreground-light" />
+ ) : showEmptyState ? (
+ <p className="text-sm text-foreground-light text-center h-full flex items-center justify-center">
+ No data available for the selected time range
+ </p>
+ ) : isErrorState ? (
+ <p className="text-sm text-foreground-light text-center h-full flex items-center justify-center">
+ Error loading chart data
+ </p>
+ ) : (
+ <div className="w-full">
+ <ComposedChart
+ attributes={dynamicAttributes}
+ data={finalChartData}
+ format={report.format ?? undefined}
+ xAxisKey={report.xAxisKey ?? 'timestamp'}
+ yAxisKey={report.yAxisKey ?? dynamicAttributes[0]?.attribute}
+ highlightedValue={0}
+ title={report.label}
+ customDateFormat={undefined}
+ chartHighlight={undefined}
+ chartStyle={chartStyle}
+ showTooltip={report.showTooltip}
+ showLegend={report.showLegend}
+ showTotal={false}
+ showMaxValue={report.showMaxValue}
+ onChartStyleChange={setChartStyle}
+ updateDateRange={updateDateRange}
+ valuePrecision={report.valuePrecision}
+ hideChartType={report.hideChartType}
+ titleTooltip={report.titleTooltip}
+ syncId={syncId}
+ sql={queryResult?.query}
+ />
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ )
+}
diff --git a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
index 2a32d88cc81..1d61aeefbce 100644
--- a/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
+++ b/apps/studio/components/interfaces/Settings/Logs/Logs.utils.ts
@@ -15,7 +15,7 @@ import type { Filters, LogData, LogsEndpointParams } from './Logs.types'
* Convert a micro timestamp from number/string to iso timestamp
*/
export const unixMicroToIsoTimestamp = (unix: string | number): string => {
- return dayjs.unix(Number(unix) / 1000 / 1000).toISOString()
+ return dayjs.utc(Number(unix) / 1000).toISOString()
}
export const isUnixMicro = (unix: string | number): boolean => {
@@ -483,19 +483,22 @@ export const fillTimeseries = (
// If we have more points than minPointsToFill, just normalize timestamps and return
if (timeseriesData.length > minPointsToFill) {
return timeseriesData.map((datum) => {
- const iso = dayjs.utc(datum[timestampKey]).toISOString()
+ const timestamp = datum[timestampKey]
+ const iso = isUnixMicro(timestamp)
+ ? unixMicroToIsoTimestamp(timestamp)
+ : dayjs.utc(timestamp).toISOString()
datum[timestampKey] = iso
return datum
})
}
- if (timeseriesData.length <= 1 && !(min || max)) return timeseriesData
+ if (timeseriesData.length <= 1 && !(min && max)) return timeseriesData
const dates: unknown[] = timeseriesData.map((datum) => dayjs.utc(datum[timestampKey]))
const maxDate = max ? dayjs.utc(max) : dayjs.utc(Math.max.apply(null, dates as number[]))
const minDate = min ? dayjs.utc(min) : dayjs.utc(Math.min.apply(null, dates as number[]))
- // const truncationSample = timeseriesData.length > 0 ? timeseriesData[0][timestampKey] : min || max
+ // When no data exists but min/max are provided, we need to determine truncation from the time range
const truncationSamples = timeseriesData.length > 0 ? dates : [minDate, maxDate]
let truncation: 'second' | 'minute' | 'hour' | 'day'
let step = 1
@@ -515,11 +518,21 @@ export const fillTimeseries = (
truncation = getTimestampTruncation(truncationSamples as Dayjs[])
}
+ // If no data exists and no interval specified, default to minute precision
+ if (timeseriesData.length === 0 && !interval) {
+ truncation = 'minute'
+ }
+
const newData = timeseriesData.map((datum) => {
const timestamp = datum[timestampKey]
const iso = isUnixMicro(timestamp)
? unixMicroToIsoTimestamp(timestamp)
: dayjs.utc(timestamp).toISOString()
+
+ if (Array.isArray(valueKey) && valueKey.length === 0) {
+ return { [timestampKey]: iso }
+ }
+
datum[timestampKey] = iso
return datum
})
@@ -533,7 +546,8 @@ export const fillTimeseries = (
d_date.month() === currentDate.month() &&
d_date.date() === currentDate.date() &&
d_date.hour() === currentDate.hour() &&
- d_date.minute() === currentDate.minute()
+ d_date.minute() === currentDate.minute() &&
+ d_date.second() === currentDate.second()
)
})
if (!found) {
diff --git a/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx b/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx
index c5f086fc59d..9ba27b4b8a3 100644
--- a/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx
+++ b/apps/studio/components/layouts/LogsLayout/LogsSidebarMenuV2.tsx
@@ -105,6 +105,9 @@ export function LogsSidebarMenuV2() {
},
{
enabled: enablePgReplicate,
+ retry: false,
+ refetchOnMount: false,
+ refetchOnWindowFocus: false,
}
)
diff --git a/apps/studio/components/ui/Charts/AreaChart.tsx b/apps/studio/components/ui/Charts/AreaChart.tsx
index 4328b6ba580..8336b681818 100644
--- a/apps/studio/components/ui/Charts/AreaChart.tsx
+++ b/apps/studio/components/ui/Charts/AreaChart.tsx
@@ -4,7 +4,7 @@ import { Area, AreaChart as RechartAreaChart, Tooltip, XAxis } from 'recharts'
import { useChartHoverState } from './useChartHoverState'
import { CHART_COLORS, DateTimeFormats } from 'components/ui/Charts/Charts.constants'
-import ChartHeader from './ChartHeader'
+import { ChartHeader } from './ChartHeader'
import type { CommonChartProps, Datum } from './Charts.types'
import { numberFormatter, useChartSize } from './Charts.utils'
import NoDataPlaceholder from './NoDataPlaceholder'
diff --git a/apps/studio/components/ui/Charts/BarChart.tsx b/apps/studio/components/ui/Charts/BarChart.tsx
index 5977709174e..e626d833c46 100644
--- a/apps/studio/components/ui/Charts/BarChart.tsx
+++ b/apps/studio/components/ui/Charts/BarChart.tsx
@@ -1,6 +1,5 @@
import dayjs from 'dayjs'
-import { ComponentProps, useState, useMemo } from 'react'
-import { useChartHoverState } from './useChartHoverState'
+import { ComponentProps, useMemo, useState } from 'react'
import {
Bar,
CartesianGrid,
@@ -14,10 +13,11 @@ import {
import { CHART_COLORS, DateTimeFormats } from 'components/ui/Charts/Charts.constants'
import type { CategoricalChartState } from 'recharts/types/chart/types'
-import ChartHeader from './ChartHeader'
+import { ChartHeader } from './ChartHeader'
import type { CommonChartProps, Datum } from './Charts.types'
import { numberFormatter, useChartSize } from './Charts.utils'
import NoDataPlaceholder from './NoDataPlaceholder'
+import { useChartHoverState } from './useChartHoverState'
export interface BarChartProps<D = Datum> extends CommonChartProps<D> {
yAxisKey: string
@@ -57,10 +57,9 @@ const BarChart = ({
showGrid = false,
syncId,
}: BarChartProps) => {
+ const { hoveredIndex, isHovered, isCurrentChart, setHover, clearHover } =
+ useChartHoverState('default')
const { Container } = useChartSize(size)
- const { hoveredIndex, syncTooltip, setHover, clearHover } = useChartHoverState(
- syncId || 'default'
- )
const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
// Transform data to ensure yAxisKey values are numbers
@@ -177,7 +176,7 @@ const BarChart = ({
/>
<Tooltip
content={(props) =>
- syncId && syncTooltip && hoveredIndex !== null ? (
+ syncId && isHovered && isCurrentChart && hoveredIndex !== null ? (
<div className="bg-black/90 text-white p-2 rounded text-xs">
<div className="font-medium">
{dayjs(data[hoveredIndex]?.[xAxisKey]).format(customDateFormat)}
diff --git a/apps/studio/components/ui/Charts/ChartHeader.tsx b/apps/studio/components/ui/Charts/ChartHeader.tsx
index 92840ba3a0e..60b3e870c3e 100644
--- a/apps/studio/components/ui/Charts/ChartHeader.tsx
+++ b/apps/studio/components/ui/Charts/ChartHeader.tsx
@@ -1,11 +1,20 @@
-import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
-import { Activity, BarChartIcon, GitCommitHorizontalIcon, InfoIcon } from 'lucide-react'
+import dayjs from 'dayjs'
+import {
+ Activity,
+ BarChartIcon,
+ GitCommitHorizontalIcon,
+ InfoIcon,
+ SquareTerminal,
+} from 'lucide-react'
import Link from 'next/link'
+import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
-import dayjs from 'dayjs'
+
+import { useParams } from 'common'
+import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { formatBytes } from 'lib/helpers'
-import { useChartHoverState } from './useChartHoverState'
import { numberFormatter } from './Charts.utils'
+import { useChartHoverState } from './useChartHoverState'
export interface ChartHeaderProps {
title?: string
@@ -31,9 +40,10 @@ export interface ChartHeaderProps {
shouldFormatBytes?: boolean
isNetworkChart?: boolean
attributes?: any[]
+ sql?: string
}
-const ChartHeader = ({
+export const ChartHeader = ({
format,
highlightedValue,
highlightedLabel,
@@ -57,16 +67,25 @@ const ChartHeader = ({
shouldFormatBytes = false,
isNetworkChart = false,
attributes,
+ sql,
}: ChartHeaderProps) => {
- const { hoveredIndex, syncHover } = useChartHoverState(syncId || 'default')
+ const { hoveredIndex, isHovered, isCurrentChart, setHover, clearHover } = useChartHoverState(
+ syncId || 'default'
+ )
const [localHighlightedValue, setLocalHighlightedValue] = useState(highlightedValue)
const [localHighlightedLabel, setLocalHighlightedLabel] = useState(highlightedLabel)
+ const { ref } = useParams()
+ const router = useRouter()
const formatHighlightedValue = (value: any) => {
if (typeof value !== 'number') {
return value
}
+ if (typeof format === 'function') {
+ return format(value)
+ }
+
if (shouldFormatBytes) {
const bytesValue = isNetworkChart ? Math.abs(value) : value
return formatBytes(bytesValue, valuePrecision)
@@ -76,7 +95,7 @@ const ChartHeader = ({
}
useEffect(() => {
- if (syncId && hoveredIndex !== null && syncHover && data && xAxisKey && yAxisKey) {
+ if (syncId && hoveredIndex !== null && isHovered && data && xAxisKey && yAxisKey) {
const activeDataPoint = data[hoveredIndex]
if (activeDataPoint) {
// For stacked charts, we need to calculate the total of all attributes
@@ -128,7 +147,7 @@ const ChartHeader = ({
}
}, [
hoveredIndex,
- syncHover,
+ isHovered,
syncId,
data,
xAxisKey,
@@ -147,20 +166,21 @@ const ChartHeader = ({
{title}
</h3>
{docsUrl && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Link
- href={docsUrl}
- target="_blank"
- className="text-foreground-lighter hover:text-foreground-light"
- >
- <InfoIcon className="w-3 h-3" />
- </Link>
- </TooltipTrigger>
- <TooltipContent side="top" align="center">
- Read docs
- </TooltipContent>
- </Tooltip>
+ <ButtonTooltip
+ type="text"
+ className="px-1"
+ asChild
+ tooltip={{
+ content: {
+ side: 'top',
+ text: 'Read docs',
+ },
+ }}
+ >
+ <Link href={docsUrl} target="_blank">
+ <InfoIcon className="w-4 h-4 text-foreground-lighter" />
+ </Link>
+ </ButtonTooltip>
)}
</div>
)
@@ -170,10 +190,6 @@ const ChartHeader = ({
className={`text-foreground text-xl font-normal ${minimalHeader ? 'text-base' : 'text-2xl'}`}
>
{localHighlightedValue !== undefined && formatHighlightedValue(localHighlightedValue)}
- {format === 'seconds' ? ' ' : ''}
- <span className="text-lg">
- {typeof format === 'function' ? format(localHighlightedValue) : format}
- </span>
</h4>
)
const label = <h4 className="text-foreground-lighter text-xs">{localHighlightedLabel}</h4>
@@ -202,43 +218,57 @@ const ChartHeader = ({
</div>
</div>
<div className="flex items-center gap-2">
+ {sql ? (
+ <ButtonTooltip
+ type="default"
+ className="px-1.5"
+ asChild
+ tooltip={{
+ content: {
+ side: 'top',
+ text: 'Open in Log Explorer',
+ },
+ }}
+ >
+ <Link href={`/project/${ref}/logs/explorer?q=${encodeURIComponent(sql)}`}>
+ <SquareTerminal className="w-4 h-4 text-foreground-lighter" />
+ </Link>
+ </ButtonTooltip>
+ ) : null}
+
{!hideChartType && onChartStyleChange && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="default"
- className="px-1.5"
- icon={chartStyle === 'bar' ? <Activity /> : <BarChartIcon />}
- onClick={() => onChartStyleChange(chartStyle === 'bar' ? 'line' : 'bar')}
- />
- </TooltipTrigger>
- <TooltipContent side="top" align="center">
- View as {chartStyle === 'bar' ? 'line chart' : 'bar chart'}
- </TooltipContent>
- </Tooltip>
+ <ButtonTooltip
+ type="default"
+ className="px-1.5"
+ icon={chartStyle === 'bar' ? <Activity /> : <BarChartIcon />}
+ onClick={() => onChartStyleChange(chartStyle === 'bar' ? 'line' : 'bar')}
+ tooltip={{
+ content: {
+ side: 'top',
+ text: `View as ${chartStyle === 'bar' ? 'line chart' : 'bar chart'}`,
+ },
+ }}
+ />
)}
{setShowMaxValue && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type={showMaxValue ? 'default' : 'dashed'}
- className="px-1.5"
- icon={
- <GitCommitHorizontalIcon
- className={showMaxValue ? 'text-foreground-light' : 'text-foreground-lighter'}
- />
- }
- onClick={() => setShowMaxValue(!showMaxValue)}
+ <ButtonTooltip
+ type={showMaxValue ? 'default' : 'dashed'}
+ className="px-1.5"
+ icon={
+ <GitCommitHorizontalIcon
+ className={showMaxValue ? 'text-foreground-light' : 'text-foreground-lighter'}
/>
- </TooltipTrigger>
- <TooltipContent side="top" align="center">
- {showMaxValue ? 'Hide' : 'Show'} limit
- </TooltipContent>
- </Tooltip>
+ }
+ onClick={() => setShowMaxValue(!showMaxValue)}
+ tooltip={{
+ content: {
+ side: 'top',
+ text: `${showMaxValue ? 'Hide' : 'Show'} limit`,
+ },
+ }}
+ />
)}
</div>
</div>
)
}
-
-export default ChartHeader
diff --git a/apps/studio/components/ui/Charts/Charts.utils.tsx b/apps/studio/components/ui/Charts/Charts.utils.tsx
index 43082aad54e..31463e0adc6 100644
--- a/apps/studio/components/ui/Charts/Charts.utils.tsx
+++ b/apps/studio/components/ui/Charts/Charts.utils.tsx
@@ -1,13 +1,10 @@
import dayjs from 'dayjs'
-import utc from 'dayjs/plugin/utc'
import { FC, PropsWithChildren, useMemo } from 'react'
import { ResponsiveContainer } from 'recharts'
import { DateTimeFormats } from './Charts.constants'
import type { CommonChartProps, StackedChartProps } from './Charts.types'
-dayjs.extend(utc)
-
/**
* Auto formats a number to a default precision if it is a float
*
diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsx
index 619e7ddf7c2..4eb959ad95d 100644
--- a/apps/studio/components/ui/Charts/ComposedChart.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx
@@ -1,10 +1,7 @@
-'use client'
-
import dayjs from 'dayjs'
import { formatBytes } from 'lib/helpers'
import { useTheme } from 'next-themes'
import { ComponentProps, useEffect, useState } from 'react'
-import { useChartHoverState } from './useChartHoverState'
import {
Area,
Bar,
@@ -18,9 +15,10 @@ import {
XAxis,
YAxis,
} from 'recharts'
+
import { CategoricalChartState } from 'recharts/types/chart/types'
import { cn } from 'ui'
-import ChartHeader from './ChartHeader'
+import { ChartHeader } from './ChartHeader'
import ChartHighlightActions from './ChartHighlightActions'
import {
CHART_COLORS,
@@ -38,6 +36,7 @@ import {
} from './ComposedChart.utils'
import NoDataPlaceholder from './NoDataPlaceholder'
import { ChartHighlight } from './useChartHighlight'
+import { useChartHoverState } from './useChartHoverState'
export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
attributes: MultiAttribute[]
@@ -64,9 +63,10 @@ export interface ComposedChartProps<D = Datum> extends CommonChartProps<D> {
hideHighlightedValue?: boolean
syncId?: string
docsUrl?: string
+ sql?: string
}
-export default function ComposedChart({
+export function ComposedChart({
data,
attributes,
yAxisKey,
@@ -100,6 +100,7 @@ export default function ComposedChart({
hideHighlightedValue,
syncId,
docsUrl,
+ sql,
}: ComposedChartProps) {
const { resolvedTheme } = useTheme()
const { hoveredIndex, syncTooltip, setHover, clearHover } = useChartHoverState(
@@ -325,6 +326,7 @@ export default function ComposedChart({
shouldFormatBytes={shouldFormatBytes}
isNetworkChart={isNetworkChart}
attributes={attributes}
+ sql={sql}
/>
<Container className="relative z-10">
<RechartComposedChart
diff --git a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
index 14161b06fd3..1fc029b1f34 100644
--- a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
@@ -37,7 +37,7 @@ export type Provider = 'infra-monitoring' | 'daily-stats' | 'mock' | 'reference-
export type MultiAttribute = {
attribute: string
- provider: Provider
+ provider?: Provider
label?: string
color?: {
light: string
diff --git a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
index 785874c9229..11a15544a3c 100644
--- a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
+++ b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
@@ -4,7 +4,7 @@ import React, { PropsWithChildren, useEffect, useMemo, useRef, useState } from '
import { cn, WarningIcon } from 'ui'
import Panel from 'components/ui/Panel'
-import ComposedChart from './ComposedChart'
+import { ComposedChart } from './ComposedChart'
import { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
import { useInfraMonitoringQueries } from 'data/analytics/infra-monitoring-queries'
@@ -353,7 +353,7 @@ const useAttributeQueries = (
return [...infraQueries, ...dailyStatsQueries, ...referenceLineQueries]
}
-export default function LazyComposedChartHandler(props: ComposedChartHandlerProps) {
+export function LazyComposedChartHandler(props: ComposedChartHandlerProps) {
if (props.hide) return null
return (
diff --git a/apps/studio/components/ui/Charts/LogChartHandler.tsx b/apps/studio/components/ui/Charts/LogChartHandler.tsx
index 610e67d727b..8802c780dc3 100644
--- a/apps/studio/components/ui/Charts/LogChartHandler.tsx
+++ b/apps/studio/components/ui/Charts/LogChartHandler.tsx
@@ -3,7 +3,7 @@ import { Loader2 } from 'lucide-react'
import { cn, WarningIcon } from 'ui'
import Panel from 'components/ui/Panel'
-import ComposedChart from './ComposedChart'
+import { ComposedChart } from './ComposedChart'
import { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
import { InfraMonitoringAttribute } from 'data/analytics/infra-monitoring-query'
@@ -40,6 +40,7 @@ interface LogChartHandlerProps {
isVisible?: boolean
titleTooltip?: string
docsUrl?: string
+ syncId?: string
}
/**
@@ -87,7 +88,7 @@ const LazyChartWrapper = ({ children }: PropsWithChildren) => {
*
* Provided data must be in the expected chart format.
*/
-const LogChartHandler = ({
+export const LogChartHandler = ({
label,
attributes,
customDateFormat,
@@ -107,6 +108,7 @@ const LogChartHandler = ({
valuePrecision,
titleTooltip,
id,
+ syncId,
...otherProps
}: PropsWithChildren<LogChartHandlerProps>) => {
const [chartStyle, setChartStyle] = useState<string>(defaultChartStyle)
@@ -143,7 +145,7 @@ const LogChartHandler = ({
data={data as any}
format={format}
xAxisKey="period_start"
- yAxisKey={attributes[0].attribute}
+ yAxisKey={attributes[0]?.attribute}
highlightedValue={highlightedValue}
title={label}
customDateFormat={customDateFormat}
@@ -158,6 +160,7 @@ const LogChartHandler = ({
valuePrecision={valuePrecision}
hideChartType={hideChartType}
titleTooltip={titleTooltip}
+ syncId={syncId}
{...otherProps}
/>
</Panel.Content>
diff --git a/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx b/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx
index f50878890a7..31ff9b9f669 100644
--- a/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx
+++ b/apps/studio/components/ui/Charts/NoDataPlaceholder.tsx
@@ -1,7 +1,7 @@
import { BarChart2 } from 'lucide-react'
import { cn } from 'ui'
-import ChartHeader from './ChartHeader'
+import { ChartHeader } from './ChartHeader'
import { useChartSize } from './Charts.utils'
interface NoDataPlaceholderProps {
diff --git a/apps/studio/components/ui/Charts/StackedBarChart.tsx b/apps/studio/components/ui/Charts/StackedBarChart.tsx
index 0ef800be4b3..ac12386f3b2 100644
--- a/apps/studio/components/ui/Charts/StackedBarChart.tsx
+++ b/apps/studio/components/ui/Charts/StackedBarChart.tsx
@@ -1,9 +1,8 @@
+import dayjs from 'dayjs'
import { useState } from 'react'
import { Bar, BarChart, Cell, Legend, Tooltip, XAxis } from 'recharts'
-import dayjs from 'dayjs'
-import utc from 'dayjs/plugin/utc'
-import { useChartHoverState } from './useChartHoverState'
-import ChartHeader from './ChartHeader'
+
+import { ChartHeader } from './ChartHeader'
import {
CHART_COLORS,
DateTimeFormats,
@@ -20,7 +19,7 @@ import {
useStacked,
} from './Charts.utils'
import NoDataPlaceholder from './NoDataPlaceholder'
-dayjs.extend(utc)
+import { useChartHoverState } from './useChartHoverState'
interface Props extends CommonChartProps<any> {
xAxisKey: string
diff --git a/apps/studio/components/ui/Panel.tsx b/apps/studio/components/ui/Panel.tsx
index e17362b66fb..bf802d991b1 100644
--- a/apps/studio/components/ui/Panel.tsx
+++ b/apps/studio/components/ui/Panel.tsx
@@ -15,6 +15,9 @@ interface PanelProps {
titleClasses?: string
}
+/**
+ * @deprecated Use Card component from ui package instead
+ */
function Panel(props: PropsWithChildren<PanelProps>) {
const content = (
<div
diff --git a/apps/studio/data/reports/edgefn-charts.ts b/apps/studio/data/reports/edgefn-charts.ts
deleted file mode 100644
index dbcd204e53d..00000000000
--- a/apps/studio/data/reports/edgefn-charts.ts
+++ /dev/null
@@ -1,70 +0,0 @@
-import { ReportAttributes } from 'components/ui/Charts/ComposedChart.utils'
-
-export const getEdgeFunctionReportAttributes = (): ReportAttributes[] => [
- {
- id: 'execution-status-codes',
- label: 'Edge Function Status Codes',
- valuePrecision: 0,
- hide: false,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'bar',
- titleTooltip: 'The total number of edge function executions by status code.',
- availableIn: ['free', 'pro', 'team', 'enterprise'],
- attributes: [
- {
- attribute: 'ExecutionStatusCodes',
- provider: 'logs',
- label: 'Execution Status Codes',
- },
- ],
- },
- {
- id: 'execution-time',
- label: 'Edge Function Execution Time',
- valuePrecision: 0,
- hide: false,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'line',
- titleTooltip: 'Average execution time for edge functions.',
- availableIn: ['free', 'pro', 'team', 'enterprise'],
- format: 'ms',
- YAxisProps: {
- width: 50,
- tickFormatter: (value: number) => `${value}ms`,
- },
- attributes: [
- {
- attribute: 'ExecutionTime',
- label: 'Avg. Execution Time (ms)',
- provider: 'logs',
- enabled: true,
- },
- ],
- },
- {
- id: 'invocations-by-region',
- label: 'Edge Function Invocations by Region',
- valuePrecision: 0,
- hide: false,
- showTooltip: true,
- showLegend: true,
- showMaxValue: false,
- hideChartType: false,
- defaultChartStyle: 'bar',
- titleTooltip: 'The total number of edge function invocations by region.',
- availableIn: ['pro', 'team', 'enterprise'],
- attributes: [
- {
- attribute: 'InvocationsByRegion',
- provider: 'logs',
- label: 'Invocations by Region',
- },
- ],
- },
-]
diff --git a/apps/studio/data/reports/edgefn-query.ts b/apps/studio/data/reports/edgefn-query.ts
deleted file mode 100644
index 1671f7e4ec4..00000000000
--- a/apps/studio/data/reports/edgefn-query.ts
+++ /dev/null
@@ -1,415 +0,0 @@
-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, useEdgeFnIdToName } from './report.utils'
-import { REPORT_STATUS_CODE_COLORS } from './report.utils'
-
-/**
- * METRICS
- * Each chart in the UI has a corresponding metric key.
- */
-
-const METRIC_KEYS = [
- 'TotalInvocations',
- 'ExecutionStatusCodes',
- 'InvocationsByRegion',
- 'ExecutionTime',
-]
-
-type MetricKey = (typeof METRIC_KEYS)[number]
-
-/**
- * SQL
- * Each metric has a corresponding SQL query.
- */
-
-const METRIC_SQL: Record<
- MetricKey,
- (interval: AnalyticsInterval, functionIds?: string[]) => string
-> = {
- TotalInvocations: (interval, functionIds) => {
- return `
---edgefn-report-invocations
-select
- timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
- function_id,
- count(*) as count
-from
- function_edge_logs
- CROSS JOIN UNNEST(metadata) AS m
- CROSS JOIN UNNEST(m.request) AS request
- CROSS JOIN UNNEST(m.response) AS response
- ${
- functionIds && functionIds.length > 0
- ? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
- : ''
- }
-group by
- timestamp,
- function_id
-order by
- timestamp desc;
-
- `
- },
- ExecutionStatusCodes: (interval, functionIds) => {
- return `
---edgefn-report-execution-status-codes
-select
- timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
- response.status_code AS status_code,
- COUNT(*) AS count
-FROM
- function_edge_logs
- CROSS JOIN UNNEST(metadata) AS m
- CROSS JOIN UNNEST(m.response) AS response
- CROSS JOIN UNNEST(m.request) AS request
- ${
- functionIds && functionIds.length > 0
- ? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
- : ''
- }
-group by
- timestamp,
- status_code
-order by
- timestamp desc;
- `
- },
- InvocationsByRegion: (interval, functionIds) => {
- const granularity = analyticsIntervalToGranularity(interval)
- return `
---edgefn-report-invocations-by-region
-select
- timestamp_trunc(timestamp, ${granularity}) as timestamp,
- h.x_sb_edge_region as region,
- count(*) as count
-from
- function_edge_logs
- cross join unnest(metadata) as m
- cross join unnest(m.response) as r
- cross join unnest(r.headers) as h
- where h.x_sb_edge_region is not null
- ${
- functionIds && functionIds.length > 0
- ? `and function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
- : ''
- }
-group by
- timestamp,
- region
-order by
- timestamp desc
- `
- },
- ExecutionTime: (interval, functionIds) => {
- const granularity = analyticsIntervalToGranularity(interval)
- const hasFunctions = functionIds && functionIds.length > 0
- return `
---edgefn-report-execution-time
-select
- timestamp_trunc(timestamp, ${granularity}) as timestamp,
- ${hasFunctions ? 'function_id,' : ''}
- avg(m.execution_time_ms) as avg_execution_time
-from
- function_edge_logs
- cross join unnest(metadata) as m
- cross join unnest(m.request) as request
- ${hasFunctions ? `where function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})` : ''}
-group by
- timestamp
- ${hasFunctions ? ', function_id' : ''}
-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,
- functionIds?: string[],
- edgeFnIdToName?: (id: string) => string | undefined
- ) => { data: any; chartAttributes: any }
-> = {
- TotalInvocations: (rawData, attributes, logsMetric, functionIds, edgeFnIdToName) => {
- // Always use dynamic attributes, so the chart can show per-function stats.
- if (!rawData) return { data: undefined, chartAttributes: attributes }
- const result = rawData.result || []
-
- const functionIdsInData = Array.from(new Set(result.map((p: any) => p.function_id))) as string[]
-
- const chartFunctionIds = functionIds && functionIds.length > 0 ? functionIds : functionIdsInData
-
- if (chartFunctionIds.length === 0) {
- return { data: [], chartAttributes: [] } // No data, empty chart
- }
-
- const chartAttributes = chartFunctionIds.map((id: string) => ({
- attribute: id,
- label: edgeFnIdToName?.(id) ?? id,
- provider: 'logs',
- enabled: true,
- }))
-
- 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[p.function_id as string] = p.count
- })
- return point
- })
-
- return { data, chartAttributes }
- },
- ExecutionStatusCodes: (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 =
- REPORT_STATUS_CODE_COLORS[String(statusCode)] || REPORT_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 }
- },
- InvocationsByRegion: (rawData, attributes) => {
- if (!rawData) return { data: undefined, chartAttributes: attributes }
- const result = rawData.result || []
-
- const regions = Array.from(new Set(result.map((p: any) => p.region))).filter(Boolean)
-
- if (regions.length === 0) {
- return { data: [], chartAttributes: [] } // No data, empty chart
- }
-
- const chartAttributes = regions.map((region) => {
- return {
- attribute: region,
- label: region,
- provider: 'logs',
- enabled: true,
- }
- })
-
- 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 as string] = 0
- })
- const matchingPoints = result.filter((p: any) => p.timestamp === timestamp)
- matchingPoints.forEach((p: any) => {
- point[p.region] = p.count
- })
- return point
- })
-
- return { data, chartAttributes }
- },
- ExecutionTime: (rawData, attributes, logsMetric, functionIds, edgeFnIdToName) => {
- if (!rawData) return { data: undefined, chartAttributes: attributes }
- const result = rawData.result || []
- const hasFunctions = functionIds && functionIds.length > 0
-
- if (hasFunctions) {
- const chartAttributes = functionIds.map((id: string) => ({
- attribute: id,
- label: edgeFnIdToName?.(id) ?? id,
- provider: 'logs',
- enabled: true,
- }))
-
- if (result.length === 0) {
- return { data: [], chartAttributes }
- }
-
- 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[p.function_id as string] = p.avg_execution_time
- })
- return point
- })
-
- return { data, chartAttributes }
- } else {
- const chartAttributes = [
- {
- attribute: 'avg_execution_time',
- label: 'Avg. execution time (ms)',
- provider: 'logs',
- enabled: true,
- },
- ]
-
- const data = result
- .map((p: any) => ({
- period_start: p.timestamp,
- avg_execution_time: p.avg_execution_time,
- }))
- .sort(
- (a: { period_start: string }, b: { period_start: string }) =>
- new Date(a.period_start).getTime() - new Date(b.period_start).getTime()
- )
-
- return { data, chartAttributes }
- }
- },
-}
-
-/**
- * REPORT QUERY.
- * Fetching and state management for the report.
- */
-
-export function useEdgeFunctionReport({
- projectRef,
- attributes,
- startDate,
- endDate,
- interval,
- enabled = true,
- functionIds,
-}: {
- projectRef: string
- attributes: MultiAttribute[]
- startDate: string
- endDate: string
- interval: AnalyticsInterval
- enabled?: boolean
- functionIds?: string[]
-}) {
- const logsMetric = attributes.length > 0 ? attributes[0].attribute : ''
- const { edgeFnIdToName } = useEdgeFnIdToName({ projectRef })
- const isEdgeFnMetric = METRIC_KEYS.includes(logsMetric)
-
- const sql = isEdgeFnMetric ? METRIC_SQL[logsMetric as MetricKey](interval, functionIds) : ''
-
- const {
- data: rawData,
- error,
- isLoading,
- } = useQuery(
- [
- 'edge-function-report',
- projectRef,
- logsMetric,
- startDate,
- endDate,
- interval,
- sql,
- functionIds,
- ],
- 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 && isEdgeFnMetric),
- refetchOnWindowFocus: false,
- }
- )
-
- // Use formatter if available
- const formatter =
- (isEdgeFnMetric ? METRIC_FORMATTER[logsMetric as MetricKey] : undefined) || defaultFormatter
- const { data, chartAttributes } = formatter(
- rawData,
- attributes,
- logsMetric,
- functionIds,
- edgeFnIdToName
- )
-
- return {
- data,
- attributes: chartAttributes,
- isLoading,
- error,
- }
-}
diff --git a/apps/studio/data/reports/v2/edge-functions.config.ts b/apps/studio/data/reports/v2/edge-functions.config.ts
new file mode 100644
index 00000000000..2e65c925232
--- /dev/null
+++ b/apps/studio/data/reports/v2/edge-functions.config.ts
@@ -0,0 +1,395 @@
+import dayjs from 'dayjs'
+
+import {
+ isUnixMicro,
+ unixMicroToIsoTimestamp,
+} from 'components/interfaces/Settings/Logs/Logs.utils'
+import type { AnalyticsInterval } from 'data/analytics/constants'
+import { get } from 'data/fetchers'
+import {
+ analyticsIntervalToGranularity,
+ REPORT_STATUS_CODE_COLORS,
+} from 'data/reports/report.utils'
+import { getHttpStatusCodeInfo } from 'lib/http-status-codes'
+import { ReportConfig } from './reports.types'
+
+const METRIC_SQL: Record<string, (interval: AnalyticsInterval, functionIds?: string[]) => string> =
+ {
+ TotalInvocations: (interval, functionIds) => {
+ return `
+--edgefn-report-invocations
+select
+ timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
+ function_id,
+ count(*) as count
+from
+ function_edge_logs
+ CROSS JOIN UNNEST(metadata) AS m
+ CROSS JOIN UNNEST(m.request) AS request
+ CROSS JOIN UNNEST(m.response) AS response
+ ${
+ functionIds && functionIds.length > 0
+ ? `WHERE function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
+ : ''
+ }
+group by
+ timestamp,
+ function_id
+order by
+ timestamp desc;
+`
+ },
+ ExecutionStatusCodes: (interval, functionIds) => {
+ return `
+--edgefn-report-execution-status-codes
+select
+ timestamp_trunc(timestamp, ${analyticsIntervalToGranularity(interval)}) as timestamp,
+ response.status_code as status_code,
+ count(response.status_code) as count
+from
+ function_edge_logs
+ cross join unnest(metadata) as m
+ cross join unnest(m.response) as response
+ ${
+ functionIds && functionIds.length > 0
+ ? `where function_id in (${functionIds.map((id) => `'${id}'`).join(',')})`
+ : ''
+ }
+group by
+ timestamp,
+ status_code
+order by
+ timestamp desc
+`
+ },
+ InvocationsByRegion: (interval, functionIds) => {
+ const granularity = analyticsIntervalToGranularity(interval)
+ return `
+--edgefn-report-invocations-by-region
+select
+ timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ h.x_sb_edge_region as region,
+ count(*) as count
+from
+ function_edge_logs
+ cross join unnest(metadata) as m
+ cross join unnest(m.response) as r
+ cross join unnest(r.headers) as h
+ where h.x_sb_edge_region is not null
+ ${
+ functionIds && functionIds.length > 0
+ ? `and function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})`
+ : ''
+ }
+group by
+ timestamp,
+ region
+order by
+ timestamp desc
+`
+ },
+ ExecutionTime: (interval, functionIds) => {
+ const granularity = analyticsIntervalToGranularity(interval)
+ const hasFunctions = functionIds && functionIds.length > 0
+ return `
+--edgefn-report-execution-time
+select
+ timestamp_trunc(timestamp, ${granularity}) as timestamp,
+ ${hasFunctions ? 'function_id,' : ''}
+ avg(m.execution_time_ms) as avg_execution_time
+from
+ function_edge_logs
+ cross join unnest(metadata) as m
+ cross join unnest(m.request) as request
+ ${hasFunctions ? `where function_id IN (${functionIds.map((id) => `'${id}'`).join(',')})` : ''}
+group by
+ timestamp
+ ${hasFunctions ? ', function_id' : ''}
+order by
+ timestamp desc
+`
+ },
+ }
+
+async function runQuery(projectRef: string, sql: string, startDate: string, endDate: string) {
+ 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
+}
+
+export function extractStatusCodesFromData(data: any[]): string[] {
+ const statusCodes = new Set<string>()
+
+ data.forEach((item: any) => {
+ if (item.status_code) {
+ statusCodes.add(String(item.status_code))
+ }
+ })
+
+ return Array.from(statusCodes).sort()
+}
+
+export function generateStatusCodeAttributes(statusCodes: string[]) {
+ return statusCodes.map((code) => ({
+ attribute: code,
+ label: `${code} ${getHttpStatusCodeInfo(parseInt(code)).label}`,
+ color: REPORT_STATUS_CODE_COLORS[code] || REPORT_STATUS_CODE_COLORS.default,
+ }))
+}
+
+/**
+ * Converts a list of { timestamp, status_code, count }
+ * to a list of { timestamp, [status_code]: count }
+ * That we can pass to the chart for rendering
+ */
+export function transformStatusCodeData(data: any[], statusCodes: string[]) {
+ const pivotedData = data.reduce((acc: Record<string, any>, d: any) => {
+ const timestamp = isUnixMicro(d.timestamp)
+ ? unixMicroToIsoTimestamp(d.timestamp)
+ : dayjs.utc(d.timestamp).toISOString()
+ if (!acc[timestamp]) {
+ acc[timestamp] = { timestamp }
+ statusCodes.forEach((code) => {
+ acc[timestamp][code] = 0
+ })
+ }
+ acc[timestamp][d.status_code] = d.count
+ return acc
+ }, {})
+
+ return Object.values(pivotedData)
+}
+
+/**
+ * Transforms raw invocation data by normalizing timestamps and adding function names
+ * @param data - Raw data from the database
+ * @param functions - Array of function objects with id and name
+ * @returns Transformed data with normalized timestamps and function names
+ */
+export function transformInvocationData(data: any[], functions: { id: string; name: string }[]) {
+ return data.map((log: any) => ({
+ ...log,
+ timestamp: isUnixMicro(log.timestamp)
+ ? unixMicroToIsoTimestamp(log.timestamp)
+ : dayjs.utc(log.timestamp).toISOString(),
+ function_name: functions.find((f) => f.id === log.function_id)?.name ?? log.function_id,
+ }))
+}
+
+/**
+ * Aggregates invocation data by timestamp, summing counts for each timestamp
+ * @param data - Transformed invocation data
+ * @returns Aggregated data with one entry per timestamp
+ */
+export function aggregateInvocationsByTimestamp(data: any[]) {
+ const aggregatedData = data.reduce((acc: Record<string, any>, item: any) => {
+ const timestamp = item.timestamp
+ if (!acc[timestamp]) {
+ acc[timestamp] = { timestamp, count: 0 }
+ }
+ acc[timestamp].count += item.count
+ return acc
+ }, {})
+
+ return Object.values(aggregatedData)
+}
+
+export const edgeFunctionReports = ({
+ projectRef,
+ functions,
+ startDate,
+ endDate,
+ interval,
+ filters,
+}: {
+ projectRef: string
+ functions: { id: string; name: string }[]
+ startDate: string
+ endDate: string
+ interval: AnalyticsInterval
+ filters: {
+ functionIds?: string[]
+ }
+}): ReportConfig[] => [
+ {
+ id: 'total-invocations',
+ label: 'Total Edge Function Invocations',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of edge function invocations over time.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const sql = METRIC_SQL.TotalInvocations(interval, filters.functionIds)
+ const response = await runQuery(projectRef, sql, startDate, endDate)
+
+ if (!response?.result) return { data: [] }
+
+ // Transform and aggregate the data using extracted functions
+ const transformedData = transformInvocationData(response.result, functions)
+ const data = aggregateInvocationsByTimestamp(transformedData)
+
+ const attributes = [
+ {
+ attribute: 'count',
+ label: 'Count',
+ },
+ ]
+
+ return { data, attributes, query: sql }
+ },
+ },
+ {
+ id: 'execution-status-codes',
+ label: 'Edge Function Status Codes',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of edge function executions by status code.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ dataProvider: async (
+ projectRef: string,
+ startDate: string,
+ endDate: string,
+ interval: AnalyticsInterval,
+ functionIds?: string[]
+ ) => {
+ const sql = METRIC_SQL.ExecutionStatusCodes(interval, functionIds)
+ const rawData = await runQuery(projectRef, sql, startDate, endDate)
+
+ if (!rawData?.result) return { data: [] }
+
+ /**
+ * The query returns { timestamp, status_code: 500, count: 10 }
+ * and we have to transform it to { timestamp, 500: 10 }
+ * to be able to render the chart.
+ */
+
+ const statusCodes = extractStatusCodesFromData(rawData.result)
+ const attributes = generateStatusCodeAttributes(statusCodes)
+
+ const data = transformStatusCodeData(rawData.result, statusCodes)
+
+ return { data, attributes, query: sql }
+ },
+ },
+ {
+ id: 'execution-time',
+ label: 'Edge Function Execution Time',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'Average execution time for edge functions.',
+ availableIn: ['free', 'pro', 'team', 'enterprise'],
+ YAxisProps: {
+ width: 50,
+ tickFormatter: (value: number) => `${value}ms`,
+ },
+ format: (value: unknown) => `${Number(value).toFixed(0)}ms`,
+ dataProvider: async () => {
+ const sql = METRIC_SQL.ExecutionTime(interval, filters.functionIds)
+ const rawData = await runQuery(projectRef, sql, startDate, endDate)
+
+ if (!rawData?.result) return { data: [] }
+
+ // Transform the raw data to ensure one data point per timestamp
+ const transformedData = rawData.result?.map((point: any) => ({
+ ...point,
+ timestamp: isUnixMicro(point.timestamp)
+ ? unixMicroToIsoTimestamp(point.timestamp)
+ : dayjs.utc(point.timestamp).toISOString(),
+ function_name: functions.find((f) => f.id === point.function_id)?.name ?? point.function_id,
+ }))
+
+ // If we have multiple function IDs, we need to aggregate the execution times per timestamp
+ const aggregatedData = transformedData.reduce((acc: Record<string, any>, item: any) => {
+ const timestamp = item.timestamp
+ if (!acc[timestamp]) {
+ acc[timestamp] = {
+ timestamp,
+ avg_execution_time: item.avg_execution_time,
+ count: 1,
+ }
+ } else {
+ // Calculate weighted average for multiple functions at the same timestamp
+ const totalTime =
+ acc[timestamp].avg_execution_time * acc[timestamp].count + item.avg_execution_time
+ acc[timestamp].count += 1
+ acc[timestamp].avg_execution_time = totalTime / acc[timestamp].count
+ }
+ return acc
+ }, {})
+
+ const data = Object.values(aggregatedData).map(({ count, ...item }) => item)
+
+ const attributes = [
+ {
+ attribute: 'avg_execution_time',
+ label: 'Avg. execution time (ms)',
+ },
+ ]
+ return { data, attributes, query: sql }
+ },
+ },
+ {
+ id: 'invocations-by-region',
+ label: 'Edge Function Invocations by Region',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ titleTooltip: 'The total number of edge function invocations by region.',
+ availableIn: ['pro', 'team', 'enterprise'],
+ dataProvider: async () => {
+ const sql = METRIC_SQL.InvocationsByRegion(interval, filters.functionIds)
+ const rawData = await runQuery(projectRef, sql, startDate, endDate)
+ const data = rawData.result?.map((point: any) => ({
+ ...point,
+ timestamp: isUnixMicro(point.timestamp)
+ ? unixMicroToIsoTimestamp(point.timestamp)
+ : dayjs.utc(point.timestamp).toISOString(),
+ }))
+
+ const attributes = [
+ {
+ attribute: 'region',
+ label: 'Region',
+ provider: 'logs',
+ enabled: true,
+ },
+ {
+ attribute: 'count',
+ label: 'Count',
+ provider: 'logs',
+ enabled: true,
+ },
+ ]
+
+ return { data, attributes, query: sql }
+ },
+ },
+]
diff --git a/apps/studio/data/reports/v2/edge-functions.test.tsx b/apps/studio/data/reports/v2/edge-functions.test.tsx
new file mode 100644
index 00000000000..e1217d7b7a0
--- /dev/null
+++ b/apps/studio/data/reports/v2/edge-functions.test.tsx
@@ -0,0 +1,251 @@
+import { describe, expect, it } from 'vitest'
+import {
+ extractStatusCodesFromData,
+ generateStatusCodeAttributes,
+ transformStatusCodeData,
+ transformInvocationData,
+ aggregateInvocationsByTimestamp,
+} from './edge-functions.config'
+
+describe('extractStatusCodesFromData', () => {
+ it('should extract and sort unique status codes from the data', () => {
+ const data = [
+ { status_code: 200 },
+ { status_code: 500 },
+ { status_code: 200 },
+ { status_code: 404 },
+ ]
+ const result = extractStatusCodesFromData(data)
+ expect(result).toEqual(['200', '404', '500'])
+ })
+
+ it('should handle an empty array', () => {
+ const data: any[] = []
+ const result = extractStatusCodesFromData(data)
+ expect(result).toEqual([])
+ })
+
+ it('should handle data with missing status_code properties', () => {
+ const data = [{ status_code: 200 }, {}, { status_code: 500 }]
+ const result = extractStatusCodesFromData(data)
+ expect(result).toEqual(['200', '500'])
+ })
+
+ it('should handle various data types for status_code', () => {
+ const data = [{ status_code: 200 }, { status_code: '500' }, { status_code: 404 }]
+ const result = extractStatusCodesFromData(data)
+ expect(result).toEqual(['200', '404', '500'])
+ })
+})
+
+describe('generateStatusCodeAttributes', () => {
+ it('should generate the correct attributes for a list of status codes', () => {
+ const statusCodes = ['200', '404', '500']
+ const result = generateStatusCodeAttributes(statusCodes)
+ expect(result.map(({ color, ...rest }) => rest)).toEqual([
+ {
+ attribute: '200',
+ label: '200 OK',
+ },
+ {
+ attribute: '404',
+ label: '404 Not Found',
+ },
+ {
+ attribute: '500',
+ label: '500 Internal Server Error',
+ },
+ ])
+ })
+
+ it('should handle an empty array', () => {
+ const statusCodes: string[] = []
+ const result = generateStatusCodeAttributes(statusCodes)
+ expect(result).toEqual([])
+ })
+})
+
+describe('transformStatusCodeData', () => {
+ it('should pivot the data correctly', () => {
+ const data = [
+ { timestamp: '2023-01-01T00:00:00Z', status_code: 200, count: 10 },
+ { timestamp: '2023-01-01T00:00:00Z', status_code: 500, count: 5 },
+ { timestamp: '2023-01-02T00:00:00Z', status_code: 200, count: 20 },
+ ]
+ const result = transformStatusCodeData(data, ['200', '500'])
+ expect(result).toEqual([
+ { timestamp: '2023-01-01T00:00:00.000Z', '200': 10, '500': 5 },
+ { timestamp: '2023-01-02T00:00:00.000Z', '200': 20, '500': 0 },
+ ])
+ })
+
+ it('should handle an empty array', () => {
+ const data: any[] = []
+ const result = transformStatusCodeData(data, [])
+ expect(result).toEqual([])
+ })
+
+ it('should handle a single entry', () => {
+ const data = [{ timestamp: '2023-01-01T00:00:00Z', status_code: 200, count: 10 }]
+ const result = transformStatusCodeData(data, ['200', '404'])
+ expect(result).toEqual([{ timestamp: '2023-01-01T00:00:00.000Z', '200': 10, '404': 0 }])
+ })
+})
+
+describe('transformInvocationData', () => {
+ const mockFunctions = [
+ { id: 'func1', name: 'Function One' },
+ { id: 'func2', name: 'Function Two' },
+ ]
+
+ it('should transform raw invocation data with function names', () => {
+ const rawData = [
+ {
+ timestamp: '2023-01-01T00:00:00Z',
+ function_id: 'func1',
+ count: 10,
+ },
+ {
+ timestamp: '2023-01-01T01:00:00Z',
+ function_id: 'func2',
+ count: 5,
+ },
+ ]
+
+ const result = transformInvocationData(rawData, mockFunctions)
+ expect(result).toEqual([
+ {
+ timestamp: '2023-01-01T00:00:00.000Z',
+ function_id: 'func1',
+ count: 10,
+ function_name: 'Function One',
+ },
+ {
+ timestamp: '2023-01-01T01:00:00.000Z',
+ function_id: 'func2',
+ count: 5,
+ function_name: 'Function Two',
+ },
+ ])
+ })
+
+ it('should use function_id as fallback when function name not found', () => {
+ const rawData = [
+ {
+ timestamp: '2023-01-01T00:00:00Z',
+ function_id: 'unknown_func',
+ count: 10,
+ },
+ ]
+
+ const result = transformInvocationData(rawData, mockFunctions)
+ expect(result).toEqual([
+ {
+ timestamp: '2023-01-01T00:00:00.000Z',
+ function_id: 'unknown_func',
+ count: 10,
+ function_name: 'unknown_func',
+ },
+ ])
+ })
+
+ it('should handle unix micro timestamps', () => {
+ const rawData = [
+ {
+ timestamp: 1672531200000000, // Unix micro timestamp for 2023-01-01T00:00:00Z
+ function_id: 'func1',
+ count: 10,
+ },
+ ]
+
+ const result = transformInvocationData(rawData, mockFunctions)
+ expect(result[0].timestamp).toBe('2023-01-01T00:00:00.000Z')
+ expect(result[0].function_name).toBe('Function One')
+ })
+
+ it('should handle empty data array', () => {
+ const result = transformInvocationData([], mockFunctions)
+ expect(result).toEqual([])
+ })
+
+ it('should handle empty functions array', () => {
+ const rawData = [
+ {
+ timestamp: '2023-01-01T00:00:00Z',
+ function_id: 'func1',
+ count: 10,
+ },
+ ]
+
+ const result = transformInvocationData(rawData, [])
+ expect(result).toEqual([
+ {
+ timestamp: '2023-01-01T00:00:00.000Z',
+ function_id: 'func1',
+ count: 10,
+ function_name: 'func1',
+ },
+ ])
+ })
+})
+
+describe('aggregateInvocationsByTimestamp', () => {
+ it('should aggregate counts by timestamp', () => {
+ const data = [
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 10 },
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func2', count: 5 },
+ { timestamp: '2023-01-01T01:00:00.000Z', function_id: 'func1', count: 20 },
+ ]
+
+ const result = aggregateInvocationsByTimestamp(data)
+ expect(result).toEqual([
+ { timestamp: '2023-01-01T00:00:00.000Z', count: 15 },
+ { timestamp: '2023-01-01T01:00:00.000Z', count: 20 },
+ ])
+ })
+
+ it('should handle single entry per timestamp', () => {
+ const data = [
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 10 },
+ { timestamp: '2023-01-01T01:00:00.000Z', function_id: 'func2', count: 5 },
+ ]
+
+ const result = aggregateInvocationsByTimestamp(data)
+ expect(result).toEqual([
+ { timestamp: '2023-01-01T00:00:00.000Z', count: 10 },
+ { timestamp: '2023-01-01T01:00:00.000Z', count: 5 },
+ ])
+ })
+
+ it('should handle empty data array', () => {
+ const result = aggregateInvocationsByTimestamp([])
+ expect(result).toEqual([])
+ })
+
+ it('should handle multiple entries with same timestamp and different counts', () => {
+ const data = [
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 1 },
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func2', count: 2 },
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func3', count: 3 },
+ ]
+
+ const result = aggregateInvocationsByTimestamp(data)
+ expect(result).toEqual([{ timestamp: '2023-01-01T00:00:00.000Z', count: 6 }])
+ })
+
+ it('should preserve timestamp order from reduce operation', () => {
+ const data = [
+ { timestamp: '2023-01-01T02:00:00.000Z', function_id: 'func1', count: 30 },
+ { timestamp: '2023-01-01T00:00:00.000Z', function_id: 'func1', count: 10 },
+ { timestamp: '2023-01-01T01:00:00.000Z', function_id: 'func1', count: 20 },
+ ]
+
+ const result = aggregateInvocationsByTimestamp(data)
+ expect(result).toHaveLength(3)
+ expect(result.map((item) => item.timestamp)).toEqual([
+ '2023-01-01T02:00:00.000Z',
+ '2023-01-01T00:00:00.000Z',
+ '2023-01-01T01:00:00.000Z',
+ ])
+ })
+})
diff --git a/apps/studio/data/reports/v2/reports.types.ts b/apps/studio/data/reports/v2/reports.types.ts
new file mode 100644
index 00000000000..5edd0b23791
--- /dev/null
+++ b/apps/studio/data/reports/v2/reports.types.ts
@@ -0,0 +1,45 @@
+import { AnalyticsInterval } from 'data/analytics/constants'
+import { YAxisProps } from 'recharts'
+
+type ReportDataProviderFilter = {
+ functionIds?: string[]
+}
+
+export interface ReportDataProvider {
+ (
+ projectRef: string,
+ startDate: string,
+ endDate: string,
+ interval: AnalyticsInterval,
+ functionIds?: string[],
+ edgeFnIdToName?: (id: string) => string | undefined,
+ filters?: ReportDataProviderFilter[]
+ ): Promise<{
+ data: any
+ attributes?: {
+ attribute: string
+ label: string
+ color?: { light: string; dark: string }
+ }[]
+ query?: string // The SQL used to fetch the data if any
+ }> // [jordi] would be cool to have a type that forces data keys to match the attributes
+}
+
+export interface ReportConfig {
+ id: string
+ label: string
+ dataProvider: ReportDataProvider
+ valuePrecision: number
+ hide: boolean
+ showTooltip: boolean
+ showLegend: boolean
+ showMaxValue: boolean
+ hideChartType: boolean
+ defaultChartStyle: string
+ titleTooltip: string
+ availableIn: string[]
+ format?: (value: unknown) => string
+ YAxisProps?: YAxisProps
+ xAxisKey?: string
+ yAxisKey?: string
+}
diff --git a/apps/studio/hooks/misc/useReportDateRange.ts b/apps/studio/hooks/misc/useReportDateRange.ts
index af9502de124..bd1be26821c 100644
--- a/apps/studio/hooks/misc/useReportDateRange.ts
+++ b/apps/studio/hooks/misc/useReportDateRange.ts
@@ -9,6 +9,7 @@ import {
} from 'components/interfaces/Reports/Reports.constants'
import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
import { maybeShowUpgradePrompt } from 'components/interfaces/Settings/Logs/Logs.utils'
+import { AnalyticsInterval } from 'data/analytics/constants'
export const DATERANGE_LIMITS: { [key: string]: number } = {
free: 1,
@@ -20,7 +21,7 @@ export const DATERANGE_LIMITS: { [key: string]: number } = {
export interface ReportDateRange {
period_start: { date: string; time_period: string }
period_end: { date: string; time_period: string }
- interval: string
+ interval: AnalyticsInterval
}
// Create parsers for individual URL parameters
diff --git a/apps/studio/hooks/useChartData.ts b/apps/studio/hooks/useChartData.ts
index 63998abc939..29f129b464a 100644
--- a/apps/studio/hooks/useChartData.ts
+++ b/apps/studio/hooks/useChartData.ts
@@ -15,7 +15,6 @@ 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 { useEdgeFunctionReport } from 'data/reports/edgefn-query'
export const useChartData = ({
attributes,
@@ -56,25 +55,9 @@ export const useChartData = ({
enabled: enabled && logsAttributes.length > 0 && !isEdgeFunctionRoute,
})
- const {
- data: edgeFunctionData,
- attributes: edgeFunctionChartAttributes,
- isLoading: isEdgeFunctionLoading,
- } = useEdgeFunctionReport({
- projectRef: ref as string,
- attributes: logsAttributes,
- startDate,
- endDate,
- interval: interval as AnalyticsInterval,
- enabled: enabled && logsAttributes.length > 0 && isEdgeFunctionRoute,
- functionIds,
- })
-
- const logsData = isEdgeFunctionRoute ? edgeFunctionData : authData
- const logsChartAttributes = isEdgeFunctionRoute
- ? edgeFunctionChartAttributes
- : authChartAttributes
- const isLogsLoading = isEdgeFunctionRoute ? isEdgeFunctionLoading : isAuthLoading
+ const logsData = authData
+ const logsChartAttributes = authChartAttributes
+ const isLogsLoading = isAuthLoading
const combinedData = useMemo(() => {
if (data) return data
diff --git a/apps/studio/pages/project/[ref]/reports/auth.tsx b/apps/studio/pages/project/[ref]/reports/auth.tsx
index 3c65f9ca8f2..34838356c35 100644
--- a/apps/studio/pages/project/[ref]/reports/auth.tsx
+++ b/apps/studio/pages/project/[ref]/reports/auth.tsx
@@ -4,7 +4,7 @@ import dayjs from 'dayjs'
import { ArrowRight, RefreshCw } from 'lucide-react'
import { useState } from 'react'
-import ReportChart from 'components/interfaces/Reports/ReportChart'
+import { ReportChart } from 'components/interfaces/Reports/ReportChart'
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
diff --git a/apps/studio/pages/project/[ref]/reports/database.tsx b/apps/studio/pages/project/[ref]/reports/database.tsx
index 48ab74b916f..959967b54aa 100644
--- a/apps/studio/pages/project/[ref]/reports/database.tsx
+++ b/apps/studio/pages/project/[ref]/reports/database.tsx
@@ -7,7 +7,7 @@ import { useEffect, useState } from 'react'
import { toast } from 'sonner'
import { useFlag, useParams } from 'common'
-import ReportChart from 'components/interfaces/Reports/ReportChart'
+import { ReportChart } from 'components/interfaces/Reports/ReportChart'
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
@@ -22,7 +22,7 @@ import Table from 'components/to-be-cleaned/Table'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import ChartHandler from 'components/ui/Charts/ChartHandler'
import type { MultiAttribute } from 'components/ui/Charts/ComposedChart.utils'
-import ComposedChartHandler from 'components/ui/Charts/ComposedChartHandler'
+import { LazyComposedChartHandler } from 'components/ui/Charts/ComposedChartHandler'
import { ReportSettings } from 'components/ui/Charts/ReportSettings'
import GrafanaPromoBanner from 'components/ui/GrafanaPromoBanner'
import Panel from 'components/ui/Panel'
@@ -269,7 +269,7 @@ const DatabaseUsage = () => {
orgPlan?.id &&
(showChartsV2
? REPORT_ATTRIBUTES_V2.filter((chart) => !chart.hide).map((chart) => (
- <ComposedChartHandler
+ <LazyComposedChartHandler
key={chart.id}
{...chart}
attributes={chart.attributes as MultiAttribute[]}
@@ -288,7 +288,7 @@ const DatabaseUsage = () => {
))
: REPORT_ATTRIBUTES.filter((chart) => !chart.hide).map((chart, i) =>
chart.availableIn?.includes(orgPlan?.id) ? (
- <ComposedChartHandler
+ <LazyComposedChartHandler
key={chart.id}
{...chart}
attributes={chart.attributes as MultiAttribute[]}
@@ -310,7 +310,6 @@ const DatabaseUsage = () => {
<ReportChart
key={`${chart.id}-${i}`}
chart={chart}
- className="!mb-0"
interval={selectedDateRange.interval}
startDate={selectedDateRange?.period_start?.date}
endDate={selectedDateRange?.period_end?.date}
diff --git a/apps/studio/pages/project/[ref]/reports/edge-functions.tsx b/apps/studio/pages/project/[ref]/reports/edge-functions.tsx
index fa2ff6f1c3f..16b4705e043 100644
--- a/apps/studio/pages/project/[ref]/reports/edge-functions.tsx
+++ b/apps/studio/pages/project/[ref]/reports/edge-functions.tsx
@@ -2,10 +2,10 @@ import { useQueryClient } from '@tanstack/react-query'
import { useParams } from 'common'
import dayjs from 'dayjs'
import { ArrowRight, ChevronDown, RefreshCw } from 'lucide-react'
-import { useEffect, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { Label } from '@ui/components/shadcn/ui/label'
-import ReportChart from 'components/interfaces/Reports/ReportChart'
+import { ReportChartV2 } from 'components/interfaces/Reports/v2/ReportChartV2'
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
import ReportStickyNav from 'components/interfaces/Reports/ReportStickyNav'
@@ -14,17 +14,19 @@ import DefaultLayout from 'components/layouts/DefaultLayout'
import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { Button, Checkbox, DropdownMenu, DropdownMenuContent, DropdownMenuTrigger } from 'ui'
+import { useChartHoverState } from 'components/ui/Charts/useChartHoverState'
import { useEdgeFunctionsQuery } from 'data/edge-functions/edge-functions-query'
-import { getEdgeFunctionReportAttributes } from 'data/reports/edgefn-charts'
+import { edgeFunctionReports } from 'data/reports/v2/edge-functions.config'
import { REPORT_DATERANGE_HELPER_LABELS } from 'components/interfaces/Reports/Reports.constants'
import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'
import { useReportDateRange } from 'hooks/misc/useReportDateRange'
import type { NextPageWithLayout } from 'types'
+import { ReportSettings } from 'components/ui/Charts/ReportSettings'
-const EdgeFunctionsReport: NextPageWithLayout = () => {
+const EdgeFunctionsReportV2: NextPageWithLayout = () => {
return (
<ReportPadding>
<EdgeFunctionsUsage />
@@ -32,20 +34,23 @@ const EdgeFunctionsReport: NextPageWithLayout = () => {
)
}
-EdgeFunctionsReport.getLayout = (page) => (
+EdgeFunctionsReportV2.getLayout = (page) => (
<DefaultLayout>
<ReportsLayout title="Edge Functions">{page}</ReportsLayout>
</DefaultLayout>
)
-export type UpdateDateRange = (from: string, to: string) => void
-export default EdgeFunctionsReport
+export default EdgeFunctionsReportV2
const EdgeFunctionsUsage = () => {
const { ref } = useParams()
const { data: functions, isLoading: isLoadingFunctions } = useEdgeFunctionsQuery({
projectRef: ref,
})
+
+ const chartSyncId = `edge-functions-${ref}`
+ useChartHoverState(chartSyncId)
+
const [isOpen, setIsOpen] = useState(false)
const [functionIds, setFunctionIds] = useState<string[]>([])
const [tempFunctionIds, setTempFunctionIds] = useState<string[]>(functionIds)
@@ -61,8 +66,6 @@ const EdgeFunctionsUsage = () => {
updateDateRange,
datePickerValue,
datePickerHelpers,
- isOrgPlanLoading,
- orgPlan,
showUpgradePrompt,
setShowUpgradePrompt,
handleDatePickerChange,
@@ -71,21 +74,27 @@ const EdgeFunctionsUsage = () => {
const queryClient = useQueryClient()
const [isRefreshing, setIsRefreshing] = useState(false)
- const EDGEFN_CHARTS = getEdgeFunctionReportAttributes()
+ const reportConfig = useMemo(() => {
+ return edgeFunctionReports({
+ projectRef: ref!,
+ functions: functions ?? [],
+ startDate: selectedDateRange?.period_start?.date ?? '',
+ endDate: selectedDateRange?.period_end?.date ?? '',
+ interval: selectedDateRange?.interval ?? 'minute',
+ filters: {
+ functionIds,
+ },
+ })
+ }, [ref, functions, selectedDateRange, functionIds])
const onRefreshReport = async () => {
if (!selectedDateRange) return
setIsRefreshing(true)
- queryClient.invalidateQueries(['edge-function-report', ref])
+ queryClient.invalidateQueries(['report-v2'])
setTimeout(() => setIsRefreshing(false), 1000)
}
- if (!ref) {
- // Prevent rendering charts until the ref is available
- return <></>
- }
-
return (
<>
<ReportHeader title="Edge Functions" showDatabaseSelector={false} />
@@ -101,6 +110,8 @@ const EdgeFunctionsUsage = () => {
tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}
onClick={onRefreshReport}
/>
+ <ReportSettings chartId="edge-functions-charts" />
+
<LogsDatePicker
onSubmit={handleDatePickerChange}
value={datePickerValue}
@@ -214,17 +225,21 @@ const EdgeFunctionsUsage = () => {
>
<div className="mt-8 flex flex-col gap-4">
{selectedDateRange &&
- EDGEFN_CHARTS.filter((attr) => !attr.hide).map((attr, i) => (
- <ReportChart
- key={`${attr.id}-${i}`}
- chart={attr}
- interval={selectedDateRange.interval}
- startDate={selectedDateRange?.period_start?.date}
- endDate={selectedDateRange?.period_end?.date}
- updateDateRange={updateDateRange}
- functionIds={functionIds}
- />
- ))}
+ reportConfig
+ .filter((report) => !report.hide)
+ .map((report) => (
+ <ReportChartV2
+ key={`${report.id}`}
+ report={report}
+ projectRef={ref!}
+ interval={selectedDateRange.interval}
+ startDate={selectedDateRange?.period_start?.date}
+ endDate={selectedDateRange?.period_end?.date}
+ updateDateRange={updateDateRange}
+ functionIds={functionIds}
+ syncId={chartSyncId}
+ />
+ ))}
</div>
</ReportStickyNav>
</>
diff --git a/apps/studio/pages/project/[ref]/reports/realtime.tsx b/apps/studio/pages/project/[ref]/reports/realtime.tsx
index 27b2c81abce..14ef2d580bd 100644
--- a/apps/studio/pages/project/[ref]/reports/realtime.tsx
+++ b/apps/studio/pages/project/[ref]/reports/realtime.tsx
@@ -19,7 +19,7 @@ import {
TopApiRoutesRenderer,
TotalRequestsChartRenderer,
} from 'components/interfaces/Reports/renderers/ApiRenderers'
-import ComposedChartHandler from 'components/ui/Charts/ComposedChartHandler'
+import { LazyComposedChartHandler } from 'components/ui/Charts/ComposedChartHandler'
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
import ReportFilterBar from 'components/interfaces/Reports/ReportFilterBar'
@@ -187,7 +187,7 @@ const RealtimeUsage = () => {
>
{selectedDateRange &&
REALTIME_REPORT_ATTRIBUTES.filter((chart) => !chart.hide).map((chart) => (
- <ComposedChartHandler
+ <LazyComposedChartHandler
key={chart.id}
{...chart}
attributes={chart.attributes as MultiAttribute[]}
diff --git a/apps/studio/tests/features/logs/Logs.utils.test.ts b/apps/studio/tests/features/logs/Logs.utils.test.ts
index b074f865b8a..ace442b6142 100644
--- a/apps/studio/tests/features/logs/Logs.utils.test.ts
+++ b/apps/studio/tests/features/logs/Logs.utils.test.ts
@@ -2,8 +2,235 @@ import {
checkForILIKEClause,
checkForWildcard,
checkForWithClause,
+ fillTimeseries,
+ unixMicroToIsoTimestamp,
} from 'components/interfaces/Settings/Logs/Logs.utils'
import { describe, test, expect } from 'vitest'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+
+dayjs.extend(utc)
+
+describe('fillTimeseries', () => {
+ test('should return empty array for empty data without min/max', () => {
+ const result = fillTimeseries([], 'timestamp', 'value', 0)
+ expect(result).toEqual([])
+ })
+
+ test('should return empty array for empty data with min/max', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T01:00:00.000Z'
+ const result = fillTimeseries([], 'timestamp', 'value', 0, min, max)
+
+ // When min/max are provided, the function fills the time range with default values
+ // This creates 61 data points (one for each minute from 00:00 to 01:00)
+ expect(result).toHaveLength(61)
+ expect(result[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
+ expect(result[60]).toEqual({ timestamp: '2023-01-01T01:00:00.000Z', value: 0 })
+ })
+
+ test('should normalize timestamps when data exceeds minPointsToFill', () => {
+ const data = [
+ { timestamp: '2023-01-01T00:00:00.000Z', value: 1 },
+ { timestamp: '2023-01-01T00:01:00.000Z', value: 2 },
+ { timestamp: '2023-01-01T00:02:00.000Z', value: 3 },
+ { timestamp: '2023-01-01T00:03:00.000Z', value: 4 },
+ { timestamp: '2023-01-01T00:04:00.000Z', value: 5 },
+ { timestamp: '2023-01-01T00:05:00.000Z', value: 6 },
+ { timestamp: '2023-01-01T00:06:00.000Z', value: 7 },
+ { timestamp: '2023-01-01T00:07:00.000Z', value: 8 },
+ { timestamp: '2023-01-01T00:08:00.000Z', value: 9 },
+ { timestamp: '2023-01-01T00:09:00.000Z', value: 10 },
+ { timestamp: '2023-01-01T00:10:00.000Z', value: 11 },
+ { timestamp: '2023-01-01T00:11:00.000Z', value: 12 },
+ { timestamp: '2023-01-01T00:12:00.000Z', value: 13 },
+ { timestamp: '2023-01-01T00:13:00.000Z', value: 14 },
+ { timestamp: '2023-01-01T00:14:00.000Z', value: 15 },
+ { timestamp: '2023-01-01T00:15:00.000Z', value: 16 },
+ { timestamp: '2023-01-01T00:16:00.000Z', value: 17 },
+ { timestamp: '2023-01-01T00:17:00.000Z', value: 18 },
+ { timestamp: '2023-01-01T00:18:00.000Z', value: 19 },
+ { timestamp: '2023-01-01T00:19:00.000Z', value: 20 },
+ { timestamp: '2023-01-01T00:20:00.000Z', value: 21 },
+ ]
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 20)
+
+ // Should return normalized data without filling gaps
+ expect(result).toHaveLength(21)
+ result.forEach((item) => {
+ expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
+ })
+ })
+
+ test('should fill gaps in sparse data with 1-minute intervals', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T00:04:00.000Z'
+ const data = [
+ { timestamp: '2023-01-01T00:01:00.000Z', value: 10 },
+ { timestamp: '2023-01-01T00:03:00.000Z', value: 30 },
+ ]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '2m')
+
+ expect(result).toHaveLength(5)
+ const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
+
+ expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
+ expect(sortedResult[1]).toEqual({ timestamp: '2023-01-01T00:01:00.000Z', value: 10 })
+ expect(sortedResult[2]).toEqual({ timestamp: '2023-01-01T00:02:00.000Z', value: 0 })
+ expect(sortedResult[3]).toEqual({ timestamp: '2023-01-01T00:03:00.000Z', value: 30 })
+ expect(sortedResult[4]).toEqual({ timestamp: '2023-01-01T00:04:00.000Z', value: 0 })
+ })
+
+ test('should handle multiple value keys', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T00:02:00.000Z'
+ const data = [{ timestamp: '2023-01-01T00:01:00.000Z', count1: 10, count2: 100 }]
+
+ const result = fillTimeseries(data, 'timestamp', ['count1', 'count2'], 5, min, max, 20, '1m')
+
+ expect(result).toHaveLength(3)
+ const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
+
+ expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', count1: 5, count2: 5 })
+ expect(sortedResult[1]).toEqual({
+ timestamp: '2023-01-01T00:01:00.000Z',
+ count1: 10,
+ count2: 100,
+ })
+ expect(sortedResult[2]).toEqual({ timestamp: '2023-01-01T00:02:00.000Z', count1: 5, count2: 5 })
+ })
+
+ test('should handle different interval formats', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T00:10:00.000Z'
+ const data = [{ timestamp: '2023-01-01T00:05:00.000Z', value: 50 }]
+
+ // Test 5-minute intervals: 00:00, 00:05, 00:10 = 3 points
+ const result5m = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '5m')
+ expect(result5m).toHaveLength(3)
+
+ // Test 2-minute intervals: 00:00, 00:02, 00:04, 00:05, 00:06, 00:08, 00:10 = 7 points
+ const result2m = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '2m')
+ console.log(
+ '2m intervals:',
+ result2m.map((r) => r.timestamp)
+ )
+ expect(result2m).toHaveLength(7)
+
+ // Test 1-hour intervals: 00:00, 01:00, 02:00 with existing data at 00:05 = 4 points
+ const maxHour = '2023-01-01T02:00:00.000Z'
+ const result1h = fillTimeseries(data, 'timestamp', 'value', 0, min, maxHour, 20, '1h')
+ expect(result1h).toHaveLength(4)
+ })
+
+ test('should handle microsecond timestamps correctly', () => {
+ const now = dayjs.utc('2023-01-01T00:00:00.000Z')
+ const data = [
+ { timestamp: now.valueOf() * 1000, value: 1 },
+ { timestamp: now.add(1, 'minute').valueOf() * 1000, value: 2 },
+ ]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 1)
+
+ expect(result).toHaveLength(2)
+ result.forEach((item) => {
+ expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
+ })
+ })
+
+ test('should handle mixed timestamp formats', () => {
+ const data = [
+ { timestamp: '2023-01-01T00:00:00.000Z', value: 1 },
+ { timestamp: dayjs.utc('2023-01-01T00:01:00.000Z').valueOf() * 1000, value: 2 },
+ { timestamp: '2023-01-01T00:02:00.000Z', value: 3 },
+ ]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 1)
+
+ expect(result).toHaveLength(3)
+ result.forEach((item) => {
+ expect(item.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/)
+ })
+ })
+
+ test('should not fill gaps when data is dense enough', () => {
+ const data = Array.from({ length: 25 }, (_, i) => ({
+ timestamp: dayjs.utc('2023-01-01T00:00:00.000Z').add(i, 'minute').toISOString(),
+ value: i,
+ }))
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, undefined, undefined, 20)
+
+ expect(result).toHaveLength(25)
+ expect(result).toEqual(data)
+ })
+
+ test('should handle edge case with single data point', () => {
+ const data = [{ timestamp: '2023-01-01T00:00:00.000Z', value: 1 }]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0)
+
+ expect(result).toEqual(data)
+ })
+
+ test('should handle edge case with single data point and min/max', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T00:02:00.000Z'
+ const data = [{ timestamp: '2023-01-01T00:01:00.000Z', value: 1 }]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, '1m')
+
+ expect(result).toHaveLength(3)
+ const sortedResult = result.sort((a, b) => a.timestamp.localeCompare(b.timestamp))
+
+ expect(sortedResult[0]).toEqual({ timestamp: '2023-01-01T00:00:00.000Z', value: 0 })
+ expect(sortedResult[1]).toEqual({ timestamp: '2023-01-01T00:01:00.000Z', value: 1 })
+ expect(sortedResult[2]).toEqual({ timestamp: '2023-01-01T00:02:00.000Z', value: 0 })
+ })
+
+ test('should handle invalid interval format gracefully', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T00:02:00.000Z'
+ const data = [{ timestamp: '2023-01-01T00:01:00.000Z', value: 1 }]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0, min, max, 20, 'invalid')
+
+ // Should fall back to default behavior
+ expect(result.length).toBeGreaterThan(1)
+ })
+
+ test('should preserve all properties of original data', () => {
+ const data = [
+ {
+ timestamp: '2023-01-01T00:00:00.000Z',
+ value: 1,
+ extra: 'data',
+ nested: { prop: 'value' },
+ },
+ ]
+
+ const result = fillTimeseries(data, 'timestamp', 'value', 0)
+
+ expect(result[0]).toEqual(data[0])
+ expect(result[0].extra).toBe('data')
+ expect(result[0].nested).toEqual({ prop: 'value' })
+ })
+
+ test('should handle empty value keys array', () => {
+ const min = '2023-01-01T00:00:00.000Z'
+ const max = '2023-01-01T00:01:00.000Z'
+ const data = [{ timestamp: '2023-01-01T00:00:30.000Z', value: 1 }]
+
+ const result = fillTimeseries(data, 'timestamp', [], 0, min, max, 20, '30s')
+
+ expect(result).toHaveLength(3)
+ result.forEach((item) => {
+ expect(item).toHaveProperty('timestamp')
+ expect(item).not.toHaveProperty('value')
+ })
+ })
+})
describe('checkForWithClause', () => {
test('basic queries', () => {
diff --git a/apps/studio/tests/vitestSetup.ts b/apps/studio/tests/vitestSetup.ts
index f309589b528..df9816a4bba 100644
--- a/apps/studio/tests/vitestSetup.ts
+++ b/apps/studio/tests/vitestSetup.ts
@@ -4,6 +4,14 @@ import { createDynamicRouteParser } from 'next-router-mock/dist/dynamic-routes'
import { afterAll, afterEach, beforeAll, vi } from 'vitest'
import { routerMock } from './lib/route-mock'
import { mswServer } from './lib/msw'
+import dayjs from 'dayjs'
+import utc from 'dayjs/plugin/utc'
+import timezone from 'dayjs/plugin/timezone'
+import relativeTime from 'dayjs/plugin/relativeTime'
+
+dayjs.extend(utc)
+dayjs.extend(timezone)
+dayjs.extend(relativeTime)
// Uncomment this if HTML in errors are being annoying.
//
@@ -38,7 +46,7 @@ beforeAll(() => {
vi.mock('next/compat/router', () => require('next-router-mock'))
// Mock the useParams hook from common module globally
- vi.mock('common', async (importOriginal) => {
+ vi.mock('common', async (importOriginal: any) => {
const actual = await importOriginal()
return {
...(typeof actual === 'object' ? actual : {}),