Skip to content

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

feat: reports infra o11y (#33310)

Francesco Sansalvadore939e5c855ad4
diff --git a/apps/studio/components/interfaces/Reports/Reports.constants.ts b/apps/studio/components/interfaces/Reports/Reports.constants.ts
index 148d1e40f62..aa9866308b9 100644
--- a/apps/studio/components/interfaces/Reports/Reports.constants.ts
+++ b/apps/studio/components/interfaces/Reports/Reports.constants.ts
@@ -11,23 +11,35 @@ interface ReportsDatetimeHelper extends DatetimeHelper {
}
export const REPORTS_DATEPICKER_HELPERS: ReportsDatetimeHelper[] = [
+ {
+ text: 'Last 10 minutes',
+ calcFrom: () => dayjs().subtract(10, 'minute').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ availableIn: ['team', 'enterprise'],
+ },
+ {
+ text: 'Last 30 minutes',
+ calcFrom: () => dayjs().subtract(30, 'minute').toISOString(),
+ calcTo: () => dayjs().toISOString(),
+ availableIn: ['team', 'enterprise'],
+ },
{
text: 'Last 60 minutes',
calcFrom: () => dayjs().subtract(1, 'hour').startOf('day').toISOString(),
- calcTo: () => '',
+ calcTo: () => dayjs().toISOString(),
default: true,
availableIn: ['free', 'pro', 'team', 'enterprise'],
},
{
text: 'Last 3 hours',
calcFrom: () => dayjs().subtract(3, 'hour').startOf('day').toISOString(),
- calcTo: () => '',
+ calcTo: () => dayjs().toISOString(),
availableIn: ['free', 'pro', 'team', 'enterprise'],
},
{
text: 'Last 24 hours',
calcFrom: () => dayjs().subtract(1, 'day').startOf('day').toISOString(),
- calcTo: () => '',
+ calcTo: () => dayjs().toISOString(),
availableIn: ['free', 'pro', 'team', 'enterprise'],
},
{
@@ -53,7 +65,7 @@ export const REPORTS_DATEPICKER_HELPERS: ReportsDatetimeHelper[] = [
export const createFilteredDatePickerHelpers = (planId: PlanId) => {
return REPORTS_DATEPICKER_HELPERS.map((helper) => ({
...helper,
- disabled: !helper.availableIn.includes(planId),
+ disabled: !helper.availableIn?.includes(planId),
}))
}
diff --git a/apps/studio/components/ui/Charts/ChartHandler.tsx b/apps/studio/components/ui/Charts/ChartHandler.tsx
index 7198dc3bdbc..1ffe98f9a9c 100644
--- a/apps/studio/components/ui/Charts/ChartHandler.tsx
+++ b/apps/studio/components/ui/Charts/ChartHandler.tsx
@@ -148,7 +148,7 @@ const ChartHandler = ({
return (
<div className="h-full w-full">
- <div className="absolute right-6 z-50 flex justify-between">
+ <div className="absolute right-6 z-10 flex justify-between">
{!hideChartType && (
<Tooltip>
<TooltipTrigger asChild>
diff --git a/apps/studio/components/ui/Charts/ChartHeader.tsx b/apps/studio/components/ui/Charts/ChartHeader.tsx
index 004cea2065e..7eabf60887e 100644
--- a/apps/studio/components/ui/Charts/ChartHeader.tsx
+++ b/apps/studio/components/ui/Charts/ChartHeader.tsx
@@ -1,11 +1,19 @@
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import { Activity, BarChartIcon, GitCommitHorizontalIcon } from 'lucide-react'
+
export interface ChartHeaderProps {
title?: string
format?: string | ((value: unknown) => string)
customDateFormat?: string
minimalHeader?: boolean
displayDateInUtc?: boolean
- highlightedLabel?: number | string | null
- highlightedValue?: number | string | null
+ highlightedLabel?: number | string | any | null
+ highlightedValue?: number | string | any | null
+ hideChartType?: boolean
+ chartStyle?: string
+ onChartStyleChange?: (style: string) => void
+ showMaxValue?: boolean
+ setShowMaxValue?: (value: boolean) => void
}
const ChartHeader = ({
@@ -14,6 +22,11 @@ const ChartHeader = ({
highlightedLabel,
title,
minimalHeader = false,
+ hideChartType = false,
+ chartStyle = 'bar',
+ onChartStyleChange,
+ showMaxValue = false,
+ setShowMaxValue,
}: ChartHeaderProps) => {
const chartTitle = (
<h3 className={'text-foreground-lighter ' + (minimalHeader ? 'text-xs' : 'text-sm')}>
@@ -22,17 +35,17 @@ const ChartHeader = ({
)
const highlighted = (
- <h5
+ <h4
className={`text-foreground text-xl font-normal ${minimalHeader ? 'text-base' : 'text-2xl'}`}
>
- {highlightedValue !== undefined && String(highlightedValue)}
+ {highlightedValue !== undefined && highlightedValue}
{format === 'seconds' ? ' ' : ''}
<span className="text-lg">
{typeof format === 'function' ? format(highlightedValue) : format}
</span>
- </h5>
+ </h4>
)
- const label = <h5 className="text-foreground-lighter text-xs">{highlightedLabel}</h5>
+ const label = <h4 className="text-foreground-lighter text-xs">{highlightedLabel}</h4>
if (minimalHeader) {
return (
@@ -47,10 +60,48 @@ const ChartHeader = ({
}
return (
- <div className="h-16">
- {title && chartTitle}
- {highlightedValue !== undefined && highlighted}
- {label}
+ <div className="flex-grow flex justify-between items-start min-h-16">
+ <div className="flex flex-col">
+ {title && chartTitle}
+ {highlightedValue !== undefined && highlighted}
+ {label}
+ </div>
+ <div className="flex items-center gap-2">
+ {!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="left" align="center">
+ View as {chartStyle === 'bar' ? 'line chart' : 'bar chart'}
+ </TooltipContent>
+ </Tooltip>
+ )}
+ {setShowMaxValue && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ type={showMaxValue ? 'default' : 'dashed'}
+ className="px-1.5"
+ icon={
+ <GitCommitHorizontalIcon
+ className={showMaxValue ? 'text-foreground' : 'text-foreground-lighter'}
+ />
+ }
+ onClick={() => setShowMaxValue(!showMaxValue)}
+ />
+ </TooltipTrigger>
+ <TooltipContent side="left" align="center">
+ {showMaxValue ? 'Hide' : 'Show'} limit
+ </TooltipContent>
+ </Tooltip>
+ )}
+ </div>
</div>
)
}
diff --git a/apps/studio/components/ui/Charts/ChartHighlightActions.tsx b/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
new file mode 100644
index 00000000000..83cac8af215
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ChartHighlightActions.tsx
@@ -0,0 +1,75 @@
+import React, { useEffect, useState } from 'react'
+import dayjs from 'dayjs'
+import { ArrowRight, SearchIcon } from 'lucide-react'
+import {
+ cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from 'ui'
+import { ChartHighlight } from './useChartHighlight'
+import { UpdateDateRange } from 'pages/project/[ref]/reports/database'
+
+const ChartHighlightActions = ({
+ chartHighlight,
+ updateDateRange,
+}: {
+ chartHighlight?: ChartHighlight
+ updateDateRange: UpdateDateRange
+}) => {
+ const { left: selectedRangeStart, right: selectedRangeEnd, clearHighlight } = chartHighlight ?? {}
+ const [isOpen, setIsOpen] = useState(!!chartHighlight?.popoverPosition)
+
+ useEffect(() => {
+ setIsOpen(!!chartHighlight?.popoverPosition && selectedRangeStart !== selectedRangeEnd)
+ }, [chartHighlight?.popoverPosition])
+
+ const disableZoomIn = dayjs(selectedRangeEnd).diff(dayjs(selectedRangeStart), 'minutes') < 10
+ const handleZoomIn = () => {
+ if (disableZoomIn) return
+ updateDateRange(selectedRangeStart!, selectedRangeEnd!)
+ clearHighlight && clearHighlight()
+ }
+
+ return (
+ <DropdownMenu open={isOpen} onOpenChange={setIsOpen}>
+ <DropdownMenuTrigger
+ className="w-auto p-0"
+ style={{
+ position: 'absolute',
+ left: chartHighlight?.popoverPosition?.x + 'px' || 0,
+ top: chartHighlight?.popoverPosition?.y + 'px' || 0,
+ }}
+ />
+ <DropdownMenuContent className="flex flex-col gap-1 p-1 w-fit text-left">
+ <DropdownMenuLabel className="flex items-center justify-center text-foreground-lighter font-mono gap-1 text-xs">
+ <span>{dayjs(selectedRangeStart).format('MMM D, H:mm')}</span>
+ <ArrowRight size={10} />
+ <span>{dayjs(selectedRangeEnd).format('MMM D, H:mm')}</span>
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator className="my-0" />
+ <DropdownMenuItem
+ disabled={disableZoomIn}
+ className={cn('group', disableZoomIn && '!bg-transparent')}
+ >
+ <button
+ disabled={disableZoomIn}
+ onClick={handleZoomIn}
+ className="w-full flex items-center gap-1.5"
+ >
+ <SearchIcon className="text-foreground-lighter" size={12} />
+ <span className="flex-grow text-left text-foreground-light">Zoom in</span>
+ {disableZoomIn && (
+ <span className="text-foreground-muted text-xs">10 minutes min.</span>
+ )}
+ </button>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )
+}
+
+export default ChartHighlightActions
diff --git a/apps/studio/components/ui/Charts/Charts.constants.ts b/apps/studio/components/ui/Charts/Charts.constants.ts
index a3caa2fd19f..17139558ba0 100644
--- a/apps/studio/components/ui/Charts/Charts.constants.ts
+++ b/apps/studio/components/ui/Charts/Charts.constants.ts
@@ -11,6 +11,36 @@ export const CHART_COLORS = {
RED_2: 'hsl(var(--destructive-500))',
}
+const LIGHT_STACKED_CHART_COLORS = [
+ '#3ECF8E',
+ '#097c4f',
+ '#DA760B',
+ '#EDC35E',
+ '#65BCD9',
+ '#0063E8',
+ '#DB8DF9',
+ '#B616A6',
+]
+
+const DARK_STACKED_CHART_COLORS = [
+ '#3ECF8E',
+ '#A3FFC2',
+ '#DA760B',
+ '#EDD35E',
+ '#65BCD9',
+ '#0063E8',
+ '#DB8DF9',
+ '#B616A6',
+]
+
+// Default to light mode colors, will be updated based on theme
+export let STACKED_CHART_COLORS = LIGHT_STACKED_CHART_COLORS
+
+// Function to update colors based on theme
+export const updateStackedChartColors = (isDarkMode: boolean) => {
+ STACKED_CHART_COLORS = isDarkMode ? DARK_STACKED_CHART_COLORS : LIGHT_STACKED_CHART_COLORS
+}
+
// refer to packages/ui/radix-colors.js for full list of colors
export type ValidStackColor =
| 'brand'
@@ -50,5 +80,6 @@ export const DEFAULT_STACK_COLORS: ValidStackColor[] = [
export enum DateTimeFormats {
FULL = 'MMM D, YYYY, hh:mma',
+ FULL_SECONDS = 'MMM D, YYYY, hh:mm:ssa',
DATE_ONLY = 'MMM D, YYYY',
}
diff --git a/apps/studio/components/ui/Charts/Charts.utils.tsx b/apps/studio/components/ui/Charts/Charts.utils.tsx
index 1e8b2b436cd..af6bf179b74 100644
--- a/apps/studio/components/ui/Charts/Charts.utils.tsx
+++ b/apps/studio/components/ui/Charts/Charts.utils.tsx
@@ -83,10 +83,15 @@ export const useChartSize = (
}
) => {
const minHeight = sizeMap[size]
- const Container: FC<PropsWithChildren> = useMemo(
+ const Container: FC<PropsWithChildren & { className?: string }> = useMemo(
() =>
- ({ children }) => (
- <ResponsiveContainer height={minHeight} minHeight={minHeight} width="100%">
+ ({ className, children }) => (
+ <ResponsiveContainer
+ className={className}
+ height={minHeight}
+ minHeight={minHeight}
+ width="100%"
+ >
{children as JSX.Element}
</ResponsiveContainer>
),
diff --git a/apps/studio/components/ui/Charts/ComposedChart.tsx b/apps/studio/components/ui/Charts/ComposedChart.tsx
new file mode 100644
index 00000000000..7ebfa5db0f6
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ComposedChart.tsx
@@ -0,0 +1,371 @@
+'use client'
+
+import { useState, ComponentProps, useEffect } from 'react'
+import dayjs from 'dayjs'
+import {
+ Area,
+ Bar,
+ ComposedChart as RechartComposedChart,
+ XAxis,
+ YAxis,
+ CartesianGrid,
+ Line,
+ ReferenceArea,
+ Tooltip,
+} from 'recharts'
+import { CategoricalChartState } from 'recharts/types/chart/types'
+import { cn } from 'ui'
+import { useTheme } from 'next-themes'
+import ChartHeader from './ChartHeader'
+import ChartHighlightActions from './ChartHighlightActions'
+import {
+ CHART_COLORS,
+ DateTimeFormats,
+ STACKED_CHART_COLORS,
+ updateStackedChartColors,
+} from './Charts.constants'
+import { Datum, CommonChartProps } from './Charts.types'
+import { useChartSize, numberFormatter } from './Charts.utils'
+import { ChartHighlight } from './useChartHighlight'
+import NoDataPlaceholder from './NoDataPlaceholder'
+import { MultiAttribute } from './ComposedChartHandler'
+import {
+ calculateTotalChartAggregate,
+ CustomLabel,
+ CustomTooltip,
+ formatBytes,
+} from './ComposedChart.utils'
+
+export interface BarChartProps<D = Datum> extends CommonChartProps<D> {
+ attributes: MultiAttribute[]
+ yAxisKey: string
+ xAxisKey: string
+ displayDateInUtc?: boolean
+ onBarClick?: (datum: Datum, tooltipData?: CategoricalChartState) => void
+ emptyStateMessage?: string
+ showLegend?: boolean
+ xAxisIsDate?: boolean
+ XAxisProps?: ComponentProps<typeof XAxis>
+ YAxisProps?: ComponentProps<typeof YAxis>
+ showGrid?: boolean
+ showTooltip?: boolean
+ showTotal?: boolean
+ showMaxValue?: boolean
+ chartHighlight?: ChartHighlight
+ hideChartType?: boolean
+ chartStyle?: string
+ onChartStyleChange?: (style: string) => void
+ updateDateRange: any
+}
+
+export default function ComposedChart({
+ data,
+ attributes,
+ yAxisKey,
+ xAxisKey,
+ format,
+ customDateFormat = DateTimeFormats.FULL,
+ title,
+ highlightedValue,
+ highlightedLabel,
+ displayDateInUtc,
+ minimalHeader,
+ valuePrecision,
+ className = '',
+ size = 'normal',
+ emptyStateMessage,
+ onBarClick,
+ showLegend = false,
+ xAxisIsDate = true,
+ XAxisProps,
+ YAxisProps,
+ showGrid = false,
+ showTooltip = false,
+ showTotal = true,
+ showMaxValue = false,
+ chartHighlight,
+ hideChartType,
+ chartStyle,
+ onChartStyleChange,
+ updateDateRange,
+}: BarChartProps) {
+ const { resolvedTheme } = useTheme()
+ const [_activePayload, setActivePayload] = useState<any>(null)
+ const [_showMaxValue, setShowMaxValue] = useState(showMaxValue)
+ const [focusDataIndex, setFocusDataIndex] = useState<number | null>(null)
+ const [hoveredLabel, setHoveredLabel] = useState<string | null>(null)
+
+ // Update chart colors when theme changes
+ useEffect(() => {
+ updateStackedChartColors(resolvedTheme?.includes('dark') ?? false)
+ }, [resolvedTheme])
+
+ const { Container } = useChartSize(size)
+
+ // Default props
+ const _XAxisProps = XAxisProps || {
+ interval: data.length - 2,
+ angle: 0,
+ tick: false,
+ }
+
+ const _YAxisProps = YAxisProps || {
+ tickFormatter: (value) => numberFormatter(value, valuePrecision),
+ tick: false,
+ 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 (
+ (focusDataIndex !== null &&
+ data &&
+ data[focusDataIndex] !== undefined &&
+ day(data[focusDataIndex].timestamp).format(customDateFormat)) ||
+ highlightedLabel
+ )
+ }
+
+ const maxAttribute = attributes.find((a) => a.isMaxValue)
+ const maxAttributeData = {
+ name: maxAttribute?.attribute,
+ color: '#3ECF8E',
+ }
+
+ 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')
+ : undefined
+
+ const resolvedHighlightedLabel = getHeaderLabel()
+ const resolvedHighlightedValue =
+ focusDataIndex !== null
+ ? showTotal
+ ? calculateTotalChartAggregate(
+ _activePayload,
+ maxAttribute?.attribute ? [maxAttribute?.attribute] : []
+ )
+ : data[focusDataIndex]?.[yAxisKey]
+ : showTotal && lastDataPoint
+ ? calculateTotalChartAggregate(
+ lastDataPoint,
+ maxAttribute?.attribute ? [maxAttribute?.attribute] : []
+ )
+ : highlightedValue
+
+ const showHighlightActions =
+ chartHighlight?.coordinates.left &&
+ 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)
+ : []
+
+ const stackedAttributes = chartData.filter((att) => !att.name.includes('max'))
+ const isPercentage = format === '%'
+ const isRamChart = chartData?.some((att: any) => att.name.toLowerCase().includes('ram_'))
+
+ //*
+ // Set the y-axis domain
+ // to the highest value in the chart data for percentage charts
+ // to vertically zoom in on the data
+ // */
+ const yDomain = [
+ 0,
+ Math.max(...chartData.map((att) => (typeof att.value === 'number' ? att.value : 0))),
+ ]
+
+ if (data.length === 0) {
+ return (
+ <NoDataPlaceholder
+ message={emptyStateMessage}
+ description="It may take up to 24 hours for data to refresh"
+ size={size}
+ className={className}
+ attribute={title}
+ format={format}
+ />
+ )
+ }
+
+ return (
+ <div className={cn('flex flex-col gap-y-3', className)}>
+ <ChartHeader
+ title={title}
+ format={format}
+ customDateFormat={customDateFormat}
+ highlightedValue={
+ typeof resolvedHighlightedValue === 'number'
+ ? isRamChart
+ ? formatBytes(resolvedHighlightedValue, valuePrecision)
+ : numberFormatter(resolvedHighlightedValue, valuePrecision)
+ : resolvedHighlightedValue
+ }
+ highlightedLabel={resolvedHighlightedLabel}
+ minimalHeader={minimalHeader}
+ hideChartType={hideChartType}
+ chartStyle={chartStyle}
+ onChartStyleChange={onChartStyleChange}
+ showMaxValue={_showMaxValue}
+ setShowMaxValue={maxAttribute ? setShowMaxValue : undefined}
+ />
+ <Container className="relative z-10">
+ <RechartComposedChart
+ data={data}
+ onMouseMove={(e: any) => {
+ if (e.activeTooltipIndex !== focusDataIndex) {
+ setFocusDataIndex(e.activeTooltipIndex)
+ setActivePayload(e.activePayload)
+ }
+ const activeTimestamp = data[e.activeTooltipIndex]?.timestamp
+ chartHighlight?.handleMouseMove({
+ activeLabel: activeTimestamp?.toString(),
+ coordinates: e.activeLabel,
+ })
+ }}
+ onMouseDown={(e: any) => {
+ const activeTimestamp = data[e.activeTooltipIndex]?.timestamp
+ chartHighlight?.handleMouseDown({
+ activeLabel: activeTimestamp?.toString(),
+ coordinates: e.activeLabel,
+ })
+ }}
+ onMouseUp={chartHighlight?.handleMouseUp}
+ onMouseLeave={(e) => {
+ setFocusDataIndex(null)
+ setActivePayload(null)
+ }}
+ onClick={(tooltipData) => {
+ const datum = tooltipData?.activePayload?.[0]?.payload
+ if (onBarClick) onBarClick(datum, tooltipData)
+ }}
+ >
+ {showGrid && <CartesianGrid stroke={CHART_COLORS.AXIS} />}
+ <YAxis {..._YAxisProps} hide domain={isPercentage ? yDomain : undefined} key={yAxisKey} />
+ <XAxis
+ {..._XAxisProps}
+ axisLine={{ stroke: CHART_COLORS.AXIS }}
+ tickLine={{ stroke: CHART_COLORS.AXIS }}
+ tickMargin={8}
+ minTickGap={3}
+ key={xAxisKey}
+ />
+ <Tooltip
+ content={(props) =>
+ showTooltip ? (
+ <CustomTooltip
+ {...props}
+ isPercentage={isPercentage}
+ label={resolvedHighlightedLabel}
+ attributes={attributes}
+ valuePrecision={valuePrecision}
+ showTotal={showTotal}
+ />
+ ) : null
+ }
+ />
+ {chartStyle === 'bar'
+ ? stackedAttributes.map((attribute) => (
+ <Bar
+ key={attribute.name}
+ dataKey={attribute.name}
+ stackId="1"
+ fill={attribute.color}
+ fillOpacity={hoveredLabel && hoveredLabel !== attribute.name ? 0.25 : 1}
+ radius={0.75}
+ opacity={hoveredLabel && hoveredLabel !== attribute.name ? 0.5 : 1}
+ name={
+ attributes?.find((a) => a.attribute === attribute.name)?.label || attribute.name
+ }
+ />
+ ))
+ : stackedAttributes.map((attribute) => (
+ <Area
+ key={attribute.name}
+ type="step"
+ dataKey={attribute.name}
+ stackId="1"
+ fill={attribute.color}
+ strokeOpacity={hoveredLabel && hoveredLabel !== attribute.name ? 0.4 : 1}
+ stroke={attribute.color}
+ radius={20}
+ animationDuration={375}
+ fillOpacity={
+ hoveredLabel && hoveredLabel !== attribute.name
+ ? 0.075
+ : hoveredLabel === attribute.name
+ ? 0.3
+ : 0.25
+ }
+ name={
+ attributes?.find((a) => a.attribute === attribute.name)?.label || attribute.name
+ }
+ />
+ ))}
+ {/* Max value, if available */}
+ {maxAttribute && _showMaxValue && (
+ <Line
+ key={maxAttribute.attribute}
+ type="stepAfter"
+ dataKey={maxAttribute.attribute}
+ stroke="#3ECF8E"
+ strokeWidth={2}
+ strokeDasharray="3 3"
+ dot={false}
+ name={maxAttribute.label}
+ />
+ )}
+ {/* Selection highlight */}
+ {showHighlightActions && (
+ <ReferenceArea
+ x1={chartHighlight?.coordinates.left}
+ x2={chartHighlight?.coordinates.right}
+ strokeOpacity={0.5}
+ stroke="#3ECF8E"
+ fill="#3ECF8E"
+ fillOpacity={0.3}
+ />
+ )}
+ </RechartComposedChart>
+ <ChartHighlightActions chartHighlight={chartHighlight} updateDateRange={updateDateRange} />
+ </Container>
+ {data && (
+ <div className="text-foreground-lighter -mt-9 flex items-center justify-between text-xs">
+ <span>
+ {xAxisIsDate ? day(data[0]?.timestamp).format(customDateFormat) : data[0]?.timestamp}
+ </span>
+ <span>
+ {xAxisIsDate
+ ? day(data[data?.length - 1]?.timestamp).format(customDateFormat)
+ : data[data?.length - 1]?.timestamp}
+ </span>
+ </div>
+ )}
+ {showLegend && (
+ <CustomLabel
+ payload={[maxAttributeData, ...chartData]}
+ attributes={attributes}
+ showMaxValue={_showMaxValue}
+ onLabelHover={setHoveredLabel}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/components/ui/Charts/ComposedChart.utils.tsx b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
new file mode 100644
index 00000000000..3a6e83663bc
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ComposedChart.utils.tsx
@@ -0,0 +1,235 @@
+'use client'
+
+import { useState } from 'react'
+import dayjs from 'dayjs'
+import { DateTimeFormats } from './Charts.constants'
+import { numberFormatter } from './Charts.utils'
+import { MultiAttribute } from './ComposedChartHandler'
+import { Tooltip, TooltipContent, TooltipTrigger } from 'ui'
+import { cn } from 'ui'
+
+interface CustomIconProps {
+ color: string
+}
+
+const CustomIcon = ({ color }: CustomIconProps) => (
+ <svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <circle cx="5" cy="5" r="3" fill={color} />
+ </svg>
+)
+
+const MaxConnectionsIcon = () => (
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
+ <line x1="2" y1="6" x2="12" y2="6" stroke="#3ECF8E" strokeWidth="2" strokeDasharray="2 2" />
+ </svg>
+)
+
+interface TooltipProps {
+ active?: boolean
+ payload?: any[]
+ label?: string | number
+ attributes?: MultiAttribute[]
+ isPercentage?: boolean
+ valuePrecision?: number
+ showMaxValue?: boolean
+ showTotal?: boolean
+}
+
+export const formatBytes = (bytes: number, precision: number = 1) => {
+ if (bytes === 0) return '0 Bytes'
+ const k = 1024
+ const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB']
+ const i = Math.floor(Math.log(bytes) / Math.log(k))
+ return `${(bytes / Math.pow(k, i)).toFixed(precision)} ${sizes[i]}`
+}
+
+const isMaxAttribute = (attributes?: MultiAttribute[]) => attributes?.find((a) => a.isMaxValue)
+
+/**
+ * Calculate the total aggregate of the chart values
+ * by summing the values of the attributes
+ * that are not in the `ignoreAttributes` array
+ */
+export const calculateTotalChartAggregate = (
+ payload: { dataKey: string; value: number }[],
+ ignoreAttributes?: string[]
+) =>
+ payload
+ ?.filter((p) => !ignoreAttributes?.includes(p.dataKey))
+ .reduce((acc, curr) => acc + curr.value, 0)
+
+const CustomTooltip = ({
+ active,
+ payload,
+ attributes,
+ isPercentage,
+ valuePrecision,
+ showTotal,
+}: TooltipProps) => {
+ if (active && payload && payload.length) {
+ const timestamp = payload[0].payload.timestamp
+ const maxValueAttribute = isMaxAttribute(attributes)
+ const maxValueData =
+ maxValueAttribute && payload?.find((p: any) => p.dataKey === maxValueAttribute.attribute)
+ const maxValue = maxValueData?.value
+ const isRamChart = payload?.some((p: any) => p.dataKey.toLowerCase().includes('ram_'))
+ const total =
+ showTotal &&
+ calculateTotalChartAggregate(
+ payload,
+ maxValueAttribute?.attribute ? [maxValueAttribute.attribute] : []
+ )
+
+ const getIcon = (name: string, color: string) => {
+ switch (name.toLowerCase().includes('max')) {
+ case false:
+ return <CustomIcon color={color} />
+ default:
+ return <MaxConnectionsIcon />
+ }
+ }
+
+ const LabelItem = ({ entry }: { entry: any }) => {
+ const attribute = attributes?.find((a: MultiAttribute) => a.attribute === entry.name)
+ const percentage = ((entry.value / maxValue) * 100).toFixed(1)
+ const isMax = entry.dataKey === maxValueAttribute?.attribute
+
+ return (
+ <div key={entry.name} className="flex items-center w-full">
+ {getIcon(entry.name, entry.color)}
+ <span className="text-foreground-lighter ml-1 flex-grow">
+ {attribute?.label || entry.name}
+ </span>
+ <span className="ml-3.5 flex items-end gap-1">
+ {isRamChart
+ ? formatBytes(entry.value, valuePrecision)
+ : numberFormatter(entry.value, valuePrecision)}
+ {isPercentage ? '%' : ''}
+
+ {/* Show percentage if max value is set */}
+ {!!maxValueData && !isMax && (
+ <span className="text-[11px] text-foreground-light mb-0.5">({percentage}%)</span>
+ )}
+ </span>
+ </div>
+ )
+ }
+
+ return (
+ <div className="grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg px-2.5 py-1.5 text-xs shadow-xl">
+ <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} />
+ ))}
+ {active && showTotal && (
+ <div className="flex md:flex-col gap-1 md:gap-0 text-foreground font-semibold">
+ <span className="flex-grow text-foreground-lighter">Total</span>
+ <div className="flex items-end gap-1">
+ <span className="text-base">
+ {isRamChart ? formatBytes(total as number, 1) : numberFormatter(total as number)}
+ {isPercentage ? '%' : ''}
+ </span>
+ {maxValueAttribute &&
+ !isNaN((total as number) / maxValueData?.value) &&
+ isFinite((total as number) / maxValueData?.value) && (
+ <span className="text-[11px] text-foreground-light mb-0.5">
+ ({(((total as number) / maxValueData?.value) * 100).toFixed(1)}%)
+ </span>
+ )}
+ </div>
+ </div>
+ )}
+ </div>
+ </div>
+ )
+ }
+
+ return null
+}
+
+interface CustomLabelProps {
+ payload?: any[]
+ attributes?: MultiAttribute[]
+ showMaxValue?: boolean
+ onLabelHover?: (label: string | null) => void
+}
+
+const CustomLabel = ({ payload, attributes, showMaxValue, onLabelHover }: CustomLabelProps) => {
+ const items = payload ?? []
+ const maxValueAttribute = isMaxAttribute(attributes)
+ const [hoveredLabel, setHoveredLabel] = useState<string | null>(null)
+
+ const handleMouseEnter = (label: string) => {
+ setHoveredLabel(label)
+ onLabelHover?.(label)
+ }
+
+ const handleMouseLeave = () => {
+ setHoveredLabel(null)
+ onLabelHover?.(null)
+ }
+
+ const getIcon = (name: string, color: string) => {
+ switch (name === maxValueAttribute?.attribute) {
+ case true:
+ return <MaxConnectionsIcon />
+ default:
+ return <CustomIcon color={color} />
+ }
+ }
+
+ const LabelItem = ({ entry }: { entry: any }) => {
+ const attribute = attributes?.find((a) => a.attribute === entry.name)
+ const isMax = entry.name === maxValueAttribute?.attribute
+ const isHovered = hoveredLabel === entry.name
+
+ const Label = () => (
+ <div className="flex items-center gap-1">
+ {getIcon(entry.name, entry.color)}
+ <span
+ className={cn(
+ 'text-nowrap text-foreground-lighter pr-2',
+ hoveredLabel && !isHovered && 'opacity-50'
+ )}
+ >
+ {attribute?.label || entry.name}
+ </span>
+ </div>
+ )
+
+ if (!showMaxValue && isMax) return null
+
+ return (
+ <div
+ key={entry.name}
+ className="inline-flex md:flex-col gap-1 md:gap-0 w-fit text-foreground"
+ onMouseEnter={() => handleMouseEnter(entry.name)}
+ onMouseOutCapture={handleMouseLeave}
+ >
+ {!!attribute?.tooltip ? (
+ <Tooltip>
+ <TooltipTrigger>
+ <Label />
+ </TooltipTrigger>
+ <TooltipContent side="bottom" align="center" className="max-w-[250px]">
+ {attribute.tooltip}
+ </TooltipContent>
+ </Tooltip>
+ ) : (
+ <Label />
+ )}
+ </div>
+ )
+ }
+
+ return (
+ <div className="relative z-0 mx-auto flex flex-col items-center gap-1 text-xs w-full">
+ <div className="flex flex-wrap items-center justify-center gap-2">
+ {items?.map((entry, index) => <LabelItem key={`${entry.name}-${index}`} entry={entry} />)}
+ </div>
+ </div>
+ )
+}
+
+export { CustomTooltip, CustomLabel }
diff --git a/apps/studio/components/ui/Charts/ComposedChartHandler.tsx b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
new file mode 100644
index 00000000000..c88e56ca587
--- /dev/null
+++ b/apps/studio/components/ui/Charts/ComposedChartHandler.tsx
@@ -0,0 +1,326 @@
+import React, { PropsWithChildren, useState, useMemo, useEffect, useRef } from 'react'
+import { useRouter } from 'next/router'
+import { Loader2 } from 'lucide-react'
+import { cn, WarningIcon } from 'ui'
+
+import Panel from 'components/ui/Panel'
+import ComposedChart from './ComposedChart'
+
+import { AnalyticsInterval, DataPoint } from 'data/analytics/constants'
+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 type { ChartData } from './Charts.types'
+import type { UpdateDateRange } from 'pages/project/[ref]/reports/database'
+
+type Provider = 'infra-monitoring' | 'daily-stats'
+
+export type MultiAttribute = {
+ attribute: string
+ provider: Provider
+ label?: string
+ color?: string
+ format?: 'percent' | 'number'
+ description?: string
+ docsLink?: string
+ isMaxValue?: boolean
+ type?: 'line' | 'area-bar'
+ omitFromTotal?: boolean
+ tooltip?: string
+}
+
+interface ComposedChartHandlerProps {
+ id?: string
+ label: string
+ attributes: MultiAttribute[]
+ startDate: string
+ endDate: string
+ interval: string
+ customDateFormat?: string
+ defaultChartStyle?: 'bar' | 'line' | 'stackedAreaLine'
+ hideChartType?: boolean
+ data?: ChartData
+ isLoading?: boolean
+ format?: string
+ highlightedValue?: string | number
+ className?: string
+ showTooltip?: boolean
+ showLegend?: boolean
+ showTotal?: boolean
+ showMaxValue?: boolean
+ updateDateRange: UpdateDateRange
+ valuePrecision?: number
+ isVisible?: boolean
+}
+
+/**
+ * Wrapper component that handles intersection observer logic for lazy loading
+ */
+const LazyChartWrapper = ({ children }: PropsWithChildren) => {
+ const [isVisible, setIsVisible] = useState(false)
+ const ref = useRef<HTMLDivElement>(null)
+
+ useEffect(() => {
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting) {
+ setIsVisible(true)
+ observer.disconnect()
+ }
+ },
+ {
+ rootMargin: '150px 0px', // Start loading before the component enters viewport
+ threshold: 0,
+ }
+ )
+
+ const currentRef = ref.current
+ if (currentRef) {
+ observer.observe(currentRef)
+ }
+
+ return () => {
+ if (currentRef) {
+ observer.unobserve(currentRef)
+ }
+ }
+ }, [])
+
+ return <div ref={ref}>{React.cloneElement(children as React.ReactElement, { isVisible })}</div>
+}
+
+/**
+ * Controls chart display state. Optionally fetches static chart data if data is not provided.
+ *
+ * If the `data` prop is provided, it will disable automatic chart data fetching and pass the data directly to the chart render.
+ * - loading state can also be provided through the `isLoading` prop, to display loading placeholders. Ignored if `data` key not provided.
+ * - if `isLoading=true` and `data` is `undefined`, loading error message will be shown.
+ *
+ * Provided data must be in the expected chart format.
+ */
+const ComposedChartHandler = ({
+ label,
+ attributes,
+ startDate,
+ endDate,
+ interval,
+ customDateFormat,
+ children = null,
+ defaultChartStyle = 'bar',
+ hideChartType = false,
+ data,
+ isLoading,
+ format,
+ highlightedValue,
+ className,
+ showTooltip,
+ showLegend,
+ showMaxValue,
+ showTotal,
+ updateDateRange,
+ valuePrecision,
+ isVisible = true,
+}: 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) => {
+ timestamps.add(point.period_start)
+ })
+ })
+
+ // Combine data points for each timestamp
+ const combined = Array.from(timestamps)
+ .sort()
+ .map((timestamp) => {
+ const point: any = { timestamp }
+ attributes.forEach((attr, index) => {
+ const queryData = attributeQueries[index].data?.data
+ const matchingPoint = queryData?.find((p: any) => p.period_start === timestamp)
+ point[attr.attribute] = matchingPoint?.[attr.attribute] ?? 0
+ })
+ 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) {
+ return (
+ <Panel
+ className={cn(
+ 'flex min-h-[320px] w-full flex-col items-center justify-center gap-y-2',
+ className
+ )}
+ wrapWithLoading={false}
+ noMargin
+ noHideOverflow
+ >
+ <Loader2 size={18} className="animate-spin text-border-strong" />
+ <p className="text-xs text-foreground-lighter">Loading data for {label}</p>
+ </Panel>
+ )
+ }
+
+ if (!combinedData) {
+ return (
+ <div className="flex h-52 w-full flex-col items-center justify-center gap-y-2">
+ <WarningIcon />
+ <p className="text-xs text-foreground-lighter">Unable to load data for {label}</p>
+ </div>
+ )
+ }
+
+ // Rest of the component remains similar, but pass all attributes to charts
+ return (
+ <Panel
+ noMargin
+ noHideOverflow
+ className={cn('relative py-2 w-full', className)}
+ wrapWithLoading={false}
+ >
+ <Panel.Content className="flex flex-col gap-4">
+ <div
+ className="absolute right-6 z-50 flex justify-between scroll-mt-10"
+ id={label.toLowerCase().replaceAll(' ', '-')}
+ >
+ {children}
+ </div>
+ <ComposedChart
+ attributes={attributes}
+ YAxisProps={{ width: 1 }}
+ data={combinedData as DataPoint[]}
+ format={format}
+ xAxisKey="period_start"
+ yAxisKey={attributes[0].attribute}
+ highlightedValue={_highlightedValue}
+ title={label}
+ customDateFormat={customDateFormat}
+ chartHighlight={chartHighlight}
+ chartStyle={chartStyle}
+ showTooltip={showTooltip}
+ showLegend={showLegend}
+ showTotal={showTotal}
+ showMaxValue={showMaxValue}
+ onChartStyleChange={setChartStyle}
+ updateDateRange={updateDateRange}
+ valuePrecision={valuePrecision}
+ hideChartType={hideChartType}
+ />
+ </Panel.Content>
+ </Panel>
+ )
+}
+
+const useAttributeQueries = (
+ attributes: MultiAttribute[],
+ ref: string | string[] | undefined,
+ startDate: string,
+ endDate: string,
+ interval: AnalyticsInterval,
+ databaseIdentifier: string | undefined,
+ 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 infraQueries = useInfraMonitoringQueries(
+ infraAttributes,
+ ref,
+ startDate,
+ endDate,
+ interval,
+ databaseIdentifier,
+ data,
+ isVisible
+ )
+ const dailyStatsQueries = useProjectDailyStatsQueries(
+ dailyStatsAttributes,
+ ref,
+ startDate,
+ endDate,
+ interval,
+ databaseIdentifier,
+ data,
+ isVisible
+ )
+
+ return [...infraQueries, ...dailyStatsQueries]
+}
+
+export default function LazyComposedChartHandler(props: ComposedChartHandlerProps) {
+ return (
+ <LazyChartWrapper>
+ <ComposedChartHandler {...props} />
+ </LazyChartWrapper>
+ )
+}
diff --git a/apps/studio/components/ui/Charts/useChartHighlight.tsx b/apps/studio/components/ui/Charts/useChartHighlight.tsx
new file mode 100644
index 00000000000..a9b0ff2f1f3
--- /dev/null
+++ b/apps/studio/components/ui/Charts/useChartHighlight.tsx
@@ -0,0 +1,85 @@
+import { useState } from 'react'
+import dayjs from 'dayjs'
+
+export interface ChartHighlight {
+ left: string | undefined
+ right: string | undefined
+ coordinates: { left: any; right: any }
+ isSelecting: boolean
+ popoverPosition: { x: number; y: number } | null
+ handleMouseDown: (e: { activeLabel?: string; coordinates?: any }) => void
+ handleMouseMove: (e: { activeLabel?: string; coordinates?: any }) => void
+ handleMouseUp: (e: any) => void
+ clearHighlight: () => void
+}
+
+export function useChartHighlight(): ChartHighlight {
+ const [left, setLeft] = useState<string | undefined>(undefined)
+ const [right, setRight] = useState<string | undefined>(undefined)
+ const [coordinates, setCoordinates] = useState<any>({ left: undefined, right: undefined })
+ const [isSelecting, setIsSelecting] = useState(false)
+ const [popoverPosition, setPopoverPosition] = useState<{ x: number; y: number } | null>(null)
+ const [initialPoint, setInitialPoint] = useState<string | undefined>(undefined)
+
+ const handleMouseDown = (e: any) => {
+ clearHighlight()
+ if (!e || !e.activeLabel) return
+ setIsSelecting(true)
+ setLeft(e.activeLabel)
+ setRight(e.activeLabel)
+ setInitialPoint(e.activeLabel)
+ setCoordinates({ left: e.coordinates, right: e.coordinates })
+ }
+
+ const handleMouseMove = (e: any) => {
+ if (!isSelecting || !e || !e.activeLabel) return
+
+ const currentTimestamp = dayjs(e.activeLabel)
+ const initialTimestamp = dayjs(initialPoint)
+
+ if (currentTimestamp.isBefore(initialTimestamp)) {
+ // If dragging left, update left and keep right as initial
+ setLeft(e.activeLabel)
+ setRight(initialPoint)
+ setCoordinates({
+ left: e.coordinates,
+ right: coordinates.right,
+ })
+ } else {
+ // If dragging right, update right and keep left as initial
+ setRight(e.activeLabel)
+ setLeft(initialPoint)
+ setCoordinates({
+ left: coordinates.left,
+ right: e.coordinates,
+ })
+ }
+ }
+
+ const handleMouseUp = (e: any) => {
+ if (!isSelecting) return
+ setIsSelecting(false)
+ setPopoverPosition({ x: e.chartX, y: e.chartY })
+ setInitialPoint(undefined)
+ }
+
+ const clearHighlight = () => {
+ setLeft(undefined)
+ setRight(undefined)
+ setCoordinates({ left: undefined, right: undefined })
+ setPopoverPosition(null)
+ setInitialPoint(undefined)
+ }
+
+ return {
+ left,
+ right,
+ coordinates,
+ isSelecting,
+ popoverPosition,
+ handleMouseDown,
+ handleMouseMove,
+ handleMouseUp,
+ clearHighlight,
+ }
+}
diff --git a/apps/studio/components/ui/DateRangePicker.tsx b/apps/studio/components/ui/DateRangePicker.tsx
index bb0c3ce342a..ae880c48092 100644
--- a/apps/studio/components/ui/DateRangePicker.tsx
+++ b/apps/studio/components/ui/DateRangePicker.tsx
@@ -100,6 +100,32 @@ export const DateRangePicker = ({
break
// all other time periods below are based on current date and time
// they will generate flexible dynamic date ranges
+ case '10m':
+ onChange({
+ period_start: {
+ date: dayjs().subtract(10, 'minutes').format(DATE_FORMAT),
+ time_period: '1d',
+ },
+ period_end: {
+ date: today,
+ time_period: 'today',
+ },
+ interval: '1m',
+ })
+ break
+ case '30m':
+ onChange({
+ period_start: {
+ date: dayjs().subtract(30, 'minutes').format(DATE_FORMAT),
+ time_period: '1d',
+ },
+ period_end: {
+ date: today,
+ time_period: 'today',
+ },
+ interval: '1m',
+ })
+ break
case '1d':
onChange({
period_start: {
@@ -136,7 +162,7 @@ export const DateRangePicker = ({
date: today,
time_period: 'today',
},
- interval: '5m',
+ interval: '1m',
})
break
case '7d':
@@ -205,7 +231,6 @@ export const DateRangePicker = ({
<span>{timePeriod && options.find((x) => x.key === timePeriod)?.label}</span>
</Button>
</DropdownMenuTrigger>
-
<DropdownMenuContent side="bottom" align="start" className={cn(!footer && 'w-36', className)}>
<DropdownMenuRadioGroup value={timePeriod} onValueChange={(x) => handleChange(x)}>
{options.map((option) => {
diff --git a/apps/studio/components/ui/GrafanaPromoBanner.tsx b/apps/studio/components/ui/GrafanaPromoBanner.tsx
new file mode 100644
index 00000000000..17b73b163e4
--- /dev/null
+++ b/apps/studio/components/ui/GrafanaPromoBanner.tsx
@@ -0,0 +1,92 @@
+import React from 'react'
+import Link from 'next/link'
+import { useParams } from 'common'
+import { BookOpen } from 'lucide-react'
+import { Alert_Shadcn_, AlertTitle_Shadcn_, AlertDescription_Shadcn_, cn, Button } from 'ui'
+import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
+import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
+import { BASE_PATH } from 'lib/constants'
+
+const GrafanaPromoBanner = () => (
+ <Alert_Shadcn_ className="relative overflow-hidden">
+ <div className="absolute inset-0 z-0">
+ <img
+ src={`${BASE_PATH}/img/reports/bg-grafana-dark.svg`}
+ alt="Supabase Grafana"
+ className="w-full h-full object-cover object-right hidden dark:block"
+ />
+ <img
+ src={`${BASE_PATH}/img/reports/bg-grafana-light.svg`}
+ alt="Supabase Grafana"
+ className="w-full h-full object-cover object-right dark:hidden"
+ />
+ <div className="absolute inset-0 bg-gradient-to-r from-background-alternative to-transparent" />
+ </div>
+ <svg
+ width="78"
+ height="86"
+ viewBox="0 0 78 86"
+ className="w-4 h-4"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M77.777 38.148c-.15-1.344-.299-2.987-.896-4.778-.448-1.792-1.194-3.733-2.24-5.823-1.045-2.09-2.388-4.18-4.03-6.27-.598-.747-1.344-1.643-2.24-2.39 1.194-4.777-1.493-8.808-1.493-8.808-4.48-.299-7.465 1.343-8.51 2.24-.15 0-.3-.15-.598-.3a41.262 41.262 0 0 0-2.388-.895c-.896-.299-1.643-.448-2.538-.747-.896-.15-1.792-.298-2.539-.448h-.448C47.917 3.66 42.243.971 42.243.971c-6.27 4.031-7.465 9.556-7.465 9.556v.298c-.299.15-.747.15-1.045.299-.448.15-.896.298-1.493.448-.448.149-.896.298-1.493.597-.896.448-1.941.896-2.837 1.344-.896.447-1.792 1.045-2.688 1.642-.149 0-.149-.15-.149-.15-8.809-3.284-16.572.747-16.572.747-.747 9.257 3.434 15.229 4.33 16.274-.15.597-.448 1.194-.598 1.792-.597 2.09-1.194 4.33-1.493 6.57 0 .298-.15.596-.15.895C2.529 45.314.14 53.526.14 53.526c6.718 7.763 14.631 8.211 14.631 8.211 1.045 1.792 2.09 3.434 3.434 5.077.597.597 1.195 1.343 1.643 1.94-2.39 7.018.298 12.84.298 12.84 7.465.3 12.392-3.284 13.437-4.18.747.299 1.493.448 2.24.747 2.24.597 4.628.895 7.017 1.045h2.837c3.583 5.076 9.705 5.822 9.705 5.822 4.479-4.628 4.628-9.256 4.628-10.302v-.299c.896-.596 1.791-1.343 2.688-2.09 1.791-1.642 3.284-3.433 4.628-5.374.15-.15.298-.299.298-.597 5.077.298 8.51-3.136 8.51-3.136-.895-5.225-3.882-7.763-4.479-8.211h-.149V48.748c-.15-.597-.15-1.194-.298-1.642-.597-2.24-1.344-4.33-2.538-6.271-1.195-1.941-2.539-3.583-4.181-5.076-1.642-1.493-3.434-2.538-5.375-3.434-1.94-.896-3.882-1.344-5.972-1.643-1.045-.149-1.94-.149-2.986-.149H48.663c-.448 0-1.045.15-1.493.15a14.617 14.617 0 0 0-5.524 2.09c-1.643 1.045-3.136 2.24-4.33 3.583-1.195 1.344-2.09 2.986-2.688 4.628-.597 1.643-.895 3.285-1.045 4.927V48.3c.15.746.299 1.643.448 2.389.448 1.493 1.195 2.837 1.941 4.03.896 1.196 1.941 2.091 2.986 2.838 1.045.746 2.24 1.343 3.434 1.642 1.195.299 2.24.448 3.434.448H47.767c.15 0 .299 0 .448-.15.298 0 .448-.148.747-.148.448-.15.895-.3 1.343-.598.448-.15.747-.448 1.195-.746.149 0 .15-.15.298-.299.448-.299.448-.896.15-1.194-.299-.299-.747-.448-1.045-.15-.15 0-.15.15-.299.15-.299.149-.597.298-1.045.447-.299.15-.747.15-1.045.299h-2.389c-.896-.15-1.643-.299-2.538-.746-.896-.299-1.643-.896-2.39-1.493-.746-.598-1.343-1.493-1.79-2.24-.448-.746-.897-1.792-1.046-2.836-.15-.448-.15-1.046-.15-1.494v-.746c0-.299 0-.598.15-.896a11.78 11.78 0 0 1 3.285-6.121c.448-.448.895-.747 1.343-1.195.448-.298 1.046-.597 1.493-.896.598-.298 1.195-.447 1.643-.597.597-.15 1.194-.298 1.791-.298h1.792c.597 0 1.344.149 1.94.298 1.345.299 2.539.747 3.734 1.493 2.388 1.344 4.33 3.434 5.673 5.823.597 1.194 1.045 2.538 1.344 3.882 0 .299.149.747.149 1.045V52.63c0 .448 0 .746-.15 1.194 0 .299-.149.747-.149 1.045 0 .299-.149.747-.298 1.046-.15.746-.448 1.492-.747 2.09a27.148 27.148 0 0 1-2.24 4.03c-1.79 2.39-4.18 4.48-7.016 5.674-1.344.598-2.837 1.045-4.33 1.344-.747.15-1.493.15-2.24.299H43.14c-1.642-.15-3.285-.448-4.778-.896-1.493-.448-3.135-1.045-4.479-1.792-2.837-1.493-5.375-3.583-7.465-6.121-1.045-1.194-1.941-2.538-2.538-4.031a28.024 28.024 0 0 1-1.792-4.48c-.448-1.492-.746-3.135-.746-4.628V44.567c0-.746.149-1.642.149-2.388.15-.747.299-1.643.448-2.389.15-.747.298-1.642.597-2.389.448-1.493 1.045-2.986 1.642-4.48 1.344-2.836 2.986-5.374 5.077-7.315.447-.448 1.045-1.045 1.642-1.493.597-.448 1.194-.896 1.792-1.194.597-.448 1.194-.747 1.791-1.046l.896-.447c.15 0 .299-.15.448-.15.15 0 .298-.149.448-.149.597-.299 1.344-.448 1.94-.746.15 0 .3-.15.449-.15.149 0 .299-.15.448-.15.298-.148.746-.148 1.045-.298.149 0 .298-.149.597-.149.15 0 .298 0 .597-.15.15 0 .299 0 .597-.149h.597c.15 0 .299 0 .598-.149.15 0 .448 0 .597-.15h5.225c1.344 0 2.688.15 4.032.449 2.538.448 4.927 1.343 7.166 2.389a23.309 23.309 0 0 1 5.823 3.881l.299.299.298.299c.15.149.448.298.597.597.15.298.448.298.598.597.149.299.448.448.597.597a15.109 15.109 0 0 1 1.94 2.39c1.195 1.492 2.24 3.134 2.987 4.627 0 .15.15.15.15.3 0 .148.148.148.148.298.15.149.15.298.299.597.15.15.15.298.299.597.149.15.149.299.298.597.3.747.598 1.344.747 1.941.298 1.045.597 1.941.746 2.688.15.298.448.597.747.448.298 0 .597-.299.597-.598.597-1.791.597-2.837.448-3.882Z"
+ fill="currentColor"
+ />
+ </svg>
+
+ <div className="flex flex-col md:flex-row gap-2 mt-1">
+ <AlertTitle_Shadcn_ className="flex-grow">Advanced observability</AlertTitle_Shadcn_>
+ <GrafanaBannerActions className="hidden xl:flex" />
+ </div>
+ <AlertDescription_Shadcn_ className="relative flex flex-col xl:flex-row gap-2 md:max-w-lg">
+ <p className="flex-grow">
+ Set up the Supabase Grafana Dashboard to visualize over 200 database performance and health
+ metrics on your Supabase project.
+ </p>
+ <GrafanaBannerActions className="xl:hidden" />
+ </AlertDescription_Shadcn_>
+ </Alert_Shadcn_>
+)
+
+const GrafanaBannerActions = ({ className }: { className?: string }) => {
+ const { ref } = useParams()
+ const org = useSelectedOrganization()
+ const { mutate: sendEvent } = useSendEventMutation()
+
+ return (
+ <div className={cn('flex gap-2', className)}>
+ <Button type="outline" className="bg-alternative" size="tiny" icon={<BookOpen />} asChild>
+ <Link
+ href="https://supabase.com/docs/guides/telemetry/metrics"
+ target="_blank"
+ onClick={() =>
+ sendEvent({
+ action: 'reports_database_grafana_banner_clicked',
+ groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },
+ })
+ }
+ >
+ Docs
+ </Link>
+ </Button>
+ <Button type="default" size="tiny" asChild>
+ <Link
+ href="https://github.com/supabase/supabase-grafana"
+ target="_blank"
+ onClick={() =>
+ sendEvent({
+ action: 'reports_database_grafana_banner_clicked',
+ groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },
+ })
+ }
+ >
+ Configure Grafana
+ </Link>
+ </Button>
+ </div>
+ )
+}
+
+export default GrafanaPromoBanner
diff --git a/apps/studio/data/analytics/infra-monitoring-queries.ts b/apps/studio/data/analytics/infra-monitoring-queries.ts
new file mode 100644
index 00000000000..dad4edd4258
--- /dev/null
+++ b/apps/studio/data/analytics/infra-monitoring-queries.ts
@@ -0,0 +1,28 @@
+import { useInfraMonitoringQuery } from './infra-monitoring-query'
+import type { InfraMonitoringAttribute } from './infra-monitoring-query'
+import { AnalyticsInterval } from './constants'
+
+export function useInfraMonitoringQueries(
+ attributes: InfraMonitoringAttribute[],
+ ref: string | string[] | undefined,
+ startDate: string,
+ endDate: string,
+ interval: AnalyticsInterval,
+ databaseIdentifier: string | undefined,
+ data: any,
+ isVisible: boolean
+) {
+ return attributes.map((attribute) =>
+ useInfraMonitoringQuery(
+ {
+ projectRef: ref as string,
+ attribute,
+ startDate,
+ endDate,
+ interval,
+ databaseIdentifier,
+ },
+ { enabled: data === undefined && isVisible }
+ )
+ )
+}
diff --git a/apps/studio/data/analytics/project-daily-stats-queries.ts b/apps/studio/data/analytics/project-daily-stats-queries.ts
new file mode 100644
index 00000000000..b3737885793
--- /dev/null
+++ b/apps/studio/data/analytics/project-daily-stats-queries.ts
@@ -0,0 +1,28 @@
+import { useProjectDailyStatsQuery } from './project-daily-stats-query'
+import type { ProjectDailyStatsAttribute } from './project-daily-stats-query'
+import { AnalyticsInterval } from './constants'
+
+export function useProjectDailyStatsQueries(
+ attributes: ProjectDailyStatsAttribute[],
+ ref: string | string[] | undefined,
+ startDate: string,
+ endDate: string,
+ interval: AnalyticsInterval,
+ databaseIdentifier: string | undefined,
+ data: any,
+ isVisible: boolean
+) {
+ return attributes.map((attribute) =>
+ useProjectDailyStatsQuery(
+ {
+ projectRef: ref as string,
+ attribute,
+ startDate,
+ endDate,
+ interval,
+ databaseIdentifier,
+ },
+ { enabled: data === undefined && isVisible }
+ )
+ )
+}
diff --git a/apps/studio/data/reports/database-charts.ts b/apps/studio/data/reports/database-charts.ts
new file mode 100644
index 00000000000..730c5dac89e
--- /dev/null
+++ b/apps/studio/data/reports/database-charts.ts
@@ -0,0 +1,199 @@
+export const getReportAttributes = (isFreePlan: boolean) => [
+ { id: 'ram_usage', label: 'Memory usage', hide: false },
+ { id: 'avg_cpu_usage', label: 'Average CPU usage', hide: false },
+ { id: 'max_cpu_usage', label: 'Max CPU usage', hide: false },
+ { id: 'disk_iops_write', label: 'Disk IOps write', hide: false },
+ { id: 'disk_iops_read', label: 'Disk IOps read', hide: false },
+ {
+ id: 'pg_stat_database_num_backends',
+ label: 'Pooler to database connections',
+ hide: false,
+ },
+ {
+ id: 'supavisor_connections_active',
+ label: 'Client to Shared Pooler connections',
+ hide: false,
+ },
+ {
+ id: 'client_connections_pgbouncer',
+ label: 'Client to Dedicated Pooler connections',
+ hide: isFreePlan,
+ },
+]
+
+export const getReportAttributesV2 = (isFreePlan: boolean) => [
+ {
+ id: 'ram-usage',
+ label: 'Memory usage',
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ showMaxValue: false,
+ attributes: [
+ {
+ attribute: 'ram_usage_used',
+ provider: 'infra-monitoring',
+ label: 'Used',
+ tooltip:
+ 'Total RAM currently in use by the system and applications. High usage may indicate memory pressure.',
+ },
+ {
+ attribute: 'ram_usage_cache_and_buffers',
+ provider: 'infra-monitoring',
+ label: 'Cache + buffers',
+ tooltip:
+ 'RAM used for caching and buffering disk operations. Higher values improve read performance.',
+ },
+ {
+ attribute: 'ram_usage_free',
+ provider: 'infra-monitoring',
+ label: 'Free',
+ tooltip:
+ 'Available unused RAM. A small amount is always reserved. High unused RAM present with erratic Used RAM may indicate unoptimized queries disrupting cache.',
+ },
+ {
+ attribute: 'ram_usage_swap',
+ provider: 'infra-monitoring',
+ label: 'Swap',
+ tooltip:
+ 'Memory swapped to disk when RAM is full. An instance has 1GB of SWAP. High swap with high disk I/O signals memory stress.',
+ },
+ ],
+ },
+ {
+ id: 'cpu-usage',
+ label: 'CPU usage',
+ format: '%',
+ valuePrecision: 2,
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ attributes: [
+ {
+ attribute: 'cpu_usage_busy_system',
+ provider: 'infra-monitoring',
+ label: 'System',
+ format: '%',
+ tooltip:
+ 'CPU time spent on kernel operations (e.g., process scheduling, memory management). High values may indicate system overhead.',
+ },
+ {
+ attribute: 'cpu_usage_busy_user',
+ provider: 'infra-monitoring',
+ label: 'User',
+ format: '%',
+ tooltip:
+ 'CPU time used by database queries and user-space processes. High values may suggest CPU-intensive queries.',
+ },
+ {
+ attribute: 'cpu_usage_busy_iowait',
+ provider: 'infra-monitoring',
+ label: 'IOwait',
+ format: '%',
+ tooltip:
+ 'CPU time waiting for disk or network I/O. High values may indicate disk bottlenecks.',
+ },
+ {
+ attribute: 'cpu_usage_busy_irqs',
+ provider: 'infra-monitoring',
+ label: 'IRQs',
+ format: '%',
+ tooltip: 'CPU time handling hardware interrupt requests (IRQ)',
+ },
+ {
+ attribute: 'cpu_usage_busy_other',
+ provider: 'infra-monitoring',
+ label: 'Other',
+ format: '%',
+ tooltip: 'CPU time spent on other tasks (e.g., background processes, software interrupts).',
+ },
+ ],
+ },
+ {
+ id: 'disk-iops',
+ label: 'Disk IOps',
+ hide: false,
+ showTooltip: true,
+ showLegend: true,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ attributes: [
+ {
+ attribute: 'disk_iops_write',
+ provider: 'infra-monitoring',
+ label: 'IOps write/s',
+ tooltip:
+ 'Number of write operations per second. High values indicate frequent data writes, logging, or transaction activity.',
+ },
+ {
+ attribute: 'disk_iops_read',
+ provider: 'infra-monitoring',
+ label: 'IOps read/s',
+ tooltip:
+ 'Number of read operations per second. High values suggest frequent disk reads due to queries or poor caching.',
+ },
+ ],
+ },
+ {
+ id: 'client-connections',
+ label: 'Database client connections',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: false,
+ showLegend: false,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ attributes: [
+ {
+ attribute: 'pg_stat_database_num_backends',
+ provider: 'infra-monitoring',
+ label: 'active connections',
+ tooltip: 'Active connections',
+ },
+ ],
+ },
+ {
+ id: 'pgbouncer-connections',
+ label: 'Pooler client connections',
+ valuePrecision: 0,
+ hide: false,
+ showTooltip: false,
+ showLegend: false,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ attributes: [
+ {
+ attribute: 'client_connections_pgbouncer',
+ provider: 'infra-monitoring',
+ label: 'pgbouncer',
+ tooltip: 'PgBouncer connections',
+ },
+ ],
+ },
+ {
+ id: 'supavisor-connections-active',
+ label: 'Supavisor client connections',
+ valuePrecision: 0,
+ hide: isFreePlan,
+ showTooltip: false,
+ showLegend: false,
+ showMaxValue: false,
+ hideChartType: false,
+ defaultChartStyle: 'line',
+ attributes: [
+ {
+ attribute: 'supavisor_connections_active',
+ provider: 'infra-monitoring',
+ label: 'supavisor',
+ tooltip: 'Supavisor connections',
+ },
+ ],
+ },
+]
diff --git a/apps/studio/lib/constants/metrics.tsx b/apps/studio/lib/constants/metrics.tsx
index feb68d99f2f..4ed2ed1a67c 100644
--- a/apps/studio/lib/constants/metrics.tsx
+++ b/apps/studio/lib/constants/metrics.tsx
@@ -372,6 +372,14 @@ export const TIME_PERIODS_REPORTS = [
]
export const TIME_PERIODS_INFRA = [
+ {
+ key: '10m',
+ label: 'Last 10 minutes',
+ },
+ {
+ key: '30m',
+ label: 'Last 30 minutes',
+ },
{
key: '1h',
label: 'Last hour',
diff --git a/apps/studio/pages/project/[ref]/reports/database.tsx b/apps/studio/pages/project/[ref]/reports/database.tsx
index fd5b8fa415f..f443675d218 100644
--- a/apps/studio/pages/project/[ref]/reports/database.tsx
+++ b/apps/studio/pages/project/[ref]/reports/database.tsx
@@ -1,13 +1,13 @@
+import { useEffect, useState } from 'react'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import { useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
-import { ArrowRight, BookOpen, ExternalLink, RefreshCw } from 'lucide-react'
+import { ArrowRight, ExternalLink, RefreshCw } from 'lucide-react'
import Link from 'next/link'
-import { useEffect, useState } from 'react'
import { toast } from 'sonner'
-import { AlertDescription_Shadcn_, AlertTitle_Shadcn_, Alert_Shadcn_, Button, cn } from 'ui'
-
+import { AlertDescription_Shadcn_, Alert_Shadcn_, Button } from 'ui'
import { useParams } from 'common'
+
import ReportHeader from 'components/interfaces/Reports/ReportHeader'
import ReportPadding from 'components/interfaces/Reports/ReportPadding'
import ReportWidget from 'components/interfaces/Reports/ReportWidget'
@@ -18,22 +18,25 @@ import ReportsLayout from 'components/layouts/ReportsLayout/ReportsLayout'
import Table from 'components/to-be-cleaned/Table'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import ChartHandler from 'components/ui/Charts/ChartHandler'
-import { DateRangePicker } from 'components/ui/DateRangePicker'
import Panel from 'components/ui/Panel'
+import ShimmerLine from 'components/ui/ShimmerLine'
+import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
+import ComposedChartHandler, { MultiAttribute } from 'components/ui/Charts/ComposedChartHandler'
+import { DateRangePicker } from 'components/ui/DateRangePicker'
+import GrafanaPromoBanner from 'components/ui/GrafanaPromoBanner'
+
import { analyticsKeys } from 'data/analytics/keys'
-import { useProjectDiskResizeMutation } from 'data/config/project-disk-resize-mutation'
+import { getReportAttributes, getReportAttributesV2 } from 'data/reports/database-charts'
import { useDatabaseSizeQuery } from 'data/database/database-size-query'
-import { usePgbouncerConfigQuery } from 'data/database/pgbouncer-config-query'
import { useDatabaseReport } from 'data/reports/database-report-query'
-import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
+import { useProjectDiskResizeMutation } from 'data/config/project-disk-resize-mutation'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
-import { useSelectedOrganization } from 'hooks/misc/useSelectedOrganization'
-import { BASE_PATH } from 'lib/constants'
+import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
+import { useFlag } from 'hooks/ui/useFlag'
import { TIME_PERIODS_INFRA } from 'lib/constants/metrics'
import { formatBytes } from 'lib/helpers'
-import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
+
import type { NextPageWithLayout } from 'types'
-import { useCurrentOrgPlan } from 'hooks/misc/useCurrentOrgPlan'
const DatabaseReport: NextPageWithLayout = () => {
return (
@@ -49,16 +52,26 @@ DatabaseReport.getLayout = (page) => (
</DefaultLayout>
)
+export type UpdateDateRange = (from: string, to: string) => void
export default DatabaseReport
const DatabaseUsage = () => {
const { db, chart, ref } = useParams()
const { project } = useProjectContext()
- const queryClient = useQueryClient()
+ const isReportsV2 = useFlag('reportsDatabaseV2')
const state = useDatabaseSelectorStateSnapshot()
+ const defaultStart = dayjs().subtract(7, 'day').toISOString()
+ const defaultEnd = dayjs().toISOString()
+ const [dateRange, setDateRange] = useState<any>({
+ period_start: { date: defaultStart, time_period: '7d' },
+ period_end: { date: defaultEnd, time_period: 'today' },
+ interval: '1h',
+ })
+
+ const queryClient = useQueryClient()
+
const [isRefreshing, setIsRefreshing] = useState(false)
- const [dateRange, setDateRange] = useState<any>(undefined)
const isReplicaSelected = state.selectedDatabaseId !== project?.ref
@@ -82,27 +95,8 @@ const DatabaseUsage = () => {
const { plan: orgPlan, isLoading: isOrgPlanLoading } = useCurrentOrgPlan()
const isFreePlan = !isOrgPlanLoading && orgPlan?.id === 'free'
- const REPORT_ATTRIBUTES = [
- { id: 'ram_usage', label: 'Memory usage', hide: false },
- { id: 'avg_cpu_usage', label: 'Average CPU usage', hide: false },
- { id: 'max_cpu_usage', label: 'Max CPU usage', hide: false },
- { id: 'disk_io_consumption', label: 'Disk IO consumed', hide: false },
- {
- id: 'pg_stat_database_num_backends',
- label: 'Pooler to database connections',
- hide: false,
- },
- {
- id: 'supavisor_connections_active',
- label: 'Client to Shared Pooler connections',
- hide: false,
- },
- {
- id: 'client_connections_pgbouncer',
- label: 'Client to Dedicated Pooler connections',
- hide: isFreePlan,
- },
- ] as const
+ const REPORT_ATTRIBUTES = getReportAttributes(isFreePlan)
+ const REPORT_ATTRIBUTES_V2 = getReportAttributesV2(isFreePlan)
const { isLoading: isUpdatingDiskSize } = useProjectDiskResizeMutation({
onSuccess: (_, variables) => {
@@ -162,91 +156,104 @@ const DatabaseUsage = () => {
}
}, [db, chart])
+ 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: '7d' },
+ period_end: { date: to, time_period: 'today' },
+ interval: handleIntervalGranularity(from, to),
+ })
+ }
+
return (
<>
<ReportHeader showDatabaseSelector title="Database" />
- <Alert_Shadcn_ className="relative overflow-hidden">
- <div className="absolute inset-0 z-0">
- <img
- src={`${BASE_PATH}/img/reports/bg-grafana-dark.svg`}
- alt="Supabase Grafana"
- className="w-full h-full object-cover object-right hidden dark:block"
- />
- <img
- src={`${BASE_PATH}/img/reports/bg-grafana-light.svg`}
- alt="Supabase Grafana"
- className="w-full h-full object-cover object-right dark:hidden"
- />
- <div className="absolute inset-0 bg-gradient-to-r from-background-alternative to-transparent" />
- </div>
- <svg
- width="78"
- height="86"
- viewBox="0 0 78 86"
- className="w-4 h-4"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- >
- <path
- d="M77.777 38.148c-.15-1.344-.299-2.987-.896-4.778-.448-1.792-1.194-3.733-2.24-5.823-1.045-2.09-2.388-4.18-4.03-6.27-.598-.747-1.344-1.643-2.24-2.39 1.194-4.777-1.493-8.808-1.493-8.808-4.48-.299-7.465 1.343-8.51 2.24-.15 0-.3-.15-.598-.3a41.262 41.262 0 0 0-2.388-.895c-.896-.299-1.643-.448-2.538-.747-.896-.15-1.792-.298-2.539-.448h-.448C47.917 3.66 42.243.971 42.243.971c-6.27 4.031-7.465 9.556-7.465 9.556v.298c-.299.15-.747.15-1.045.299-.448.15-.896.298-1.493.448-.448.149-.896.298-1.493.597-.896.448-1.941.896-2.837 1.344-.896.447-1.792 1.045-2.688 1.642-.149 0-.149-.15-.149-.15-8.809-3.284-16.572.747-16.572.747-.747 9.257 3.434 15.229 4.33 16.274-.15.597-.448 1.194-.598 1.792-.597 2.09-1.194 4.33-1.493 6.57 0 .298-.15.596-.15.895C2.529 45.314.14 53.526.14 53.526c6.718 7.763 14.631 8.211 14.631 8.211 1.045 1.792 2.09 3.434 3.434 5.077.597.597 1.195 1.343 1.643 1.94-2.39 7.018.298 12.84.298 12.84 7.465.3 12.392-3.284 13.437-4.18.747.299 1.493.448 2.24.747 2.24.597 4.628.895 7.017 1.045h2.837c3.583 5.076 9.705 5.822 9.705 5.822 4.479-4.628 4.628-9.256 4.628-10.302v-.299c.896-.596 1.791-1.343 2.688-2.09 1.791-1.642 3.284-3.433 4.628-5.374.15-.15.298-.299.298-.597 5.077.298 8.51-3.136 8.51-3.136-.895-5.225-3.882-7.763-4.479-8.211h-.149V48.748c-.15-.597-.15-1.194-.298-1.642-.597-2.24-1.344-4.33-2.538-6.271-1.195-1.941-2.539-3.583-4.181-5.076-1.642-1.493-3.434-2.538-5.375-3.434-1.94-.896-3.882-1.344-5.972-1.643-1.045-.149-1.94-.149-2.986-.149H48.663c-.448 0-1.045.15-1.493.15a14.617 14.617 0 0 0-5.524 2.09c-1.643 1.045-3.136 2.24-4.33 3.583-1.195 1.344-2.09 2.986-2.688 4.628-.597 1.643-.895 3.285-1.045 4.927V48.3c.15.746.299 1.643.448 2.389.448 1.493 1.195 2.837 1.941 4.03.896 1.196 1.941 2.091 2.986 2.838 1.045.746 2.24 1.343 3.434 1.642 1.195.299 2.24.448 3.434.448H47.767c.15 0 .299 0 .448-.15.298 0 .448-.148.747-.148.448-.15.895-.3 1.343-.598.448-.15.747-.448 1.195-.746.149 0 .15-.15.298-.299.448-.299.448-.896.15-1.194-.299-.299-.747-.448-1.045-.15-.15 0-.15.15-.299.15-.299.149-.597.298-1.045.447-.299.15-.747.15-1.045.299h-2.389c-.896-.15-1.643-.299-2.538-.746-.896-.299-1.643-.896-2.39-1.493-.746-.598-1.343-1.493-1.79-2.24-.448-.746-.897-1.792-1.046-2.836-.15-.448-.15-1.046-.15-1.494v-.746c0-.299 0-.598.15-.896a11.78 11.78 0 0 1 3.285-6.121c.448-.448.895-.747 1.343-1.195.448-.298 1.046-.597 1.493-.896.598-.298 1.195-.447 1.643-.597.597-.15 1.194-.298 1.791-.298h1.792c.597 0 1.344.149 1.94.298 1.345.299 2.539.747 3.734 1.493 2.388 1.344 4.33 3.434 5.673 5.823.597 1.194 1.045 2.538 1.344 3.882 0 .299.149.747.149 1.045V52.63c0 .448 0 .746-.15 1.194 0 .299-.149.747-.149 1.045 0 .299-.149.747-.298 1.046-.15.746-.448 1.492-.747 2.09a27.148 27.148 0 0 1-2.24 4.03c-1.79 2.39-4.18 4.48-7.016 5.674-1.344.598-2.837 1.045-4.33 1.344-.747.15-1.493.15-2.24.299H43.14c-1.642-.15-3.285-.448-4.778-.896-1.493-.448-3.135-1.045-4.479-1.792-2.837-1.493-5.375-3.583-7.465-6.121-1.045-1.194-1.941-2.538-2.538-4.031a28.024 28.024 0 0 1-1.792-4.48c-.448-1.492-.746-3.135-.746-4.628V44.567c0-.746.149-1.642.149-2.388.15-.747.299-1.643.448-2.389.15-.747.298-1.642.597-2.389.448-1.493 1.045-2.986 1.642-4.48 1.344-2.836 2.986-5.374 5.077-7.315.447-.448 1.045-1.045 1.642-1.493.597-.448 1.194-.896 1.792-1.194.597-.448 1.194-.747 1.791-1.046l.896-.447c.15 0 .299-.15.448-.15.15 0 .298-.149.448-.149.597-.299 1.344-.448 1.94-.746.15 0 .3-.15.449-.15.149 0 .299-.15.448-.15.298-.148.746-.148 1.045-.298.149 0 .298-.149.597-.149.15 0 .298 0 .597-.15.15 0 .299 0 .597-.149h.597c.15 0 .299 0 .598-.149.15 0 .448 0 .597-.15h5.225c1.344 0 2.688.15 4.032.449 2.538.448 4.927 1.343 7.166 2.389a23.309 23.309 0 0 1 5.823 3.881l.299.299.298.299c.15.149.448.298.597.597.15.298.448.298.598.597.149.299.448.448.597.597a15.109 15.109 0 0 1 1.94 2.39c1.195 1.492 2.24 3.134 2.987 4.627 0 .15.15.15.15.3 0 .148.148.148.148.298.15.149.15.298.299.597.15.15.15.298.299.597.149.15.149.299.298.597.3.747.598 1.344.747 1.941.298 1.045.597 1.941.746 2.688.15.298.448.597.747.448.298 0 .597-.299.597-.598.597-1.791.597-2.837.448-3.882Z"
- fill="currentColor"
- />
- </svg>
-
- <div className="flex flex-col md:flex-row gap-2 mt-1">
- <AlertTitle_Shadcn_ className="flex-grow">Advanced observability</AlertTitle_Shadcn_>
- <GrafanaBannerActions className="hidden xl:flex" />
+ <div className="w-full flex flex-col gap-1">
+ <div className="h-2 w-full">
+ <ShimmerLine active={report.isLoading} />
</div>
- <AlertDescription_Shadcn_ className="relative flex flex-col xl:flex-row gap-2 md:max-w-lg">
- <p className="flex-grow">
- Set up the Supabase Grafana Dashboard to visualize over 200 database performance and
- health metrics on your Supabase project.
- </p>
- <GrafanaBannerActions className="xl:hidden" />
- </AlertDescription_Shadcn_>
- </Alert_Shadcn_>
- <section>
- <Panel title={<h2>Database health</h2>}>
- <Panel.Content>
- <div className="mb-4 flex items-center gap-x-2">
- <ButtonTooltip
- type="default"
- disabled={isRefreshing}
- icon={<RefreshCw className={isRefreshing ? 'animate-spin' : ''} />}
- className="w-7"
- tooltip={{ content: { side: 'bottom', text: 'Refresh report' } }}
- onClick={onRefreshReport}
+ </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">
+ <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={'7d'}
+ options={TIME_PERIODS_INFRA}
+ currentBillingPeriodStart={undefined}
+ onChange={(values) => {
+ if (values.interval === '1d') {
+ setDateRange({ ...values, interval: '1h' })
+ } else {
+ setDateRange(values)
+ }
+ }}
/>
- <div className="flex items-center gap-x-3">
- <DateRangePicker
- loading={false}
- value={'7d'}
- 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">
- <p className="text-foreground-light">
- {dayjs(dateRange.period_start.date).format('MMMM D, hh:mma')}
- </p>
- <p className="text-foreground-light">
- <ArrowRight size={12} />
- </p>
- <p className="text-foreground-light">
- {dayjs(dateRange.period_end.date).format('MMMM D, hh:mma')}
- </p>
- </div>
- )}
- </div>
+ {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 className="space-y-6">
+ </div>
+ </div>
+ {isReportsV2 ? (
+ <div className="grid grid-cols-1 gap-4">
+ {dateRange &&
+ REPORT_ATTRIBUTES_V2.filter((attr) => !attr.hide).map((attr) => (
+ <ComposedChartHandler
+ key={attr.id}
+ {...attr}
+ attributes={attr.attributes as MultiAttribute[]}
+ interval={dateRange.interval}
+ startDate={dateRange?.period_start?.date}
+ endDate={dateRange?.period_end?.date}
+ updateDateRange={updateDateRange}
+ defaultChartStyle={attr.defaultChartStyle as 'line' | 'bar' | 'stackedAreaLine'}
+ />
+ ))}
+ </div>
+ ) : (
+ <Panel title={<h2>Database health</h2>}>
+ <Panel.Content className="grid grid-cols-1 gap-4">
{dateRange &&
REPORT_ATTRIBUTES.filter((attr) => !attr.hide).map((attr) => (
<ChartHandler
@@ -259,10 +266,9 @@ const DatabaseUsage = () => {
endDate={dateRange?.period_end?.date}
/>
))}
- </div>
- </Panel.Content>
- </Panel>
-
+ </Panel.Content>
+ </Panel>
+ )}
{dateRange && isReplicaSelected && (
<Panel title="Replica Information">
<Panel.Content>
@@ -364,7 +370,7 @@ const DatabaseUsage = () => {
)
}}
append={() => (
- <div className="px-6 pb-2">
+ <div className="px-6 pb-6">
<Alert_Shadcn_ variant="default" className="mt-4">
<AlertDescription_Shadcn_>
<div className="space-y-2">
@@ -399,42 +405,3 @@ const DatabaseUsage = () => {
</>
)
}
-
-const GrafanaBannerActions = ({ className }: { className?: string }) => {
- const { ref } = useParams()
- const org = useSelectedOrganization()
- const { mutate: sendEvent } = useSendEventMutation()
-
- return (
- <div className={cn('flex gap-2', className)}>
- <Button type="outline" className="bg-alternative" size="tiny" icon={<BookOpen />} asChild>
- <Link
- href="https://supabase.com/docs/guides/telemetry/metrics"
- target="_blank"
- onClick={() =>
- sendEvent({
- action: 'reports_database_grafana_banner_clicked',
- groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },
- })
- }
- >
- Docs
- </Link>
- </Button>
- <Button type="default" size="tiny" asChild>
- <Link
- href="https://github.com/supabase/supabase-grafana"
- target="_blank"
- onClick={() =>
- sendEvent({
- action: 'reports_database_grafana_banner_clicked',
- groups: { project: ref ?? 'Unknown', organization: org?.slug ?? 'Unknown' },
- })
- }
- >
- Configure Grafana
- </Link>
- </Button>
- </div>
- )
-}