Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.tsx
T
Jordi Enric 431a55435a fix(studio): keep the function overview range in logs FE-4973 (#53867)
## Problem

An Edge Function’s Overview can show an invocation from two hours ago.
Selecting **Open logs** or pressing **O** then **L** opens the
function’s Logs page with its default one-hour window, which hides that
invocation.

## Fix

Both actions now pass the start and end of the selected Overview window
to the function’s Logs page.

## How to test

1. Open an Edge Function with invocations in the last three hours and
select the three-hour interval on Overview.
2. Select **Open logs**. Check that Logs opens for the same function and
the date range spans exactly three hours. If an invocation is older than
one hour, confirm it appears in that range.
3. Return to Overview, select three hours again, and press **O** then
**L**. Check the same function and time range.

Related to [FE-4973](https://linear.app/supabase/issue/FE-4973).

## Verification

On the Studio staging preview, both **Open logs** and **O** then **L**
opened the same function with the exact Overview timestamps,
13:03:16.960 through 16:03:16.960 UTC. The results included a successful
invocation more than one hour before the window ended.

All 72 focused Overview and Logs navigation tests passed. Removing the
date range from either entry point independently failed its regression
assertion.
2026-12-01 13:03:23 +00:00

273 lines
8.8 KiB
TypeScript

import { useNavigate } from '@tanstack/react-router'
import { IS_PLATFORM, useParams } from 'common'
import { ExternalLinkIcon } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { PageContainer } from 'ui-patterns/PageContainer'
import { EdgeFunctionIntervalSelector } from './EdgeFunctionIntervalSelector'
import { EdgeFunctionInvocationsSection } from './EdgeFunctionInvocationsSection'
import {
EDGE_FUNCTION_CHART_INTERVALS,
getEdgeFunctionLogsUrl,
getExecutionMetrics,
getInvocationChartData,
getInvocationChartNavigationUrl,
getInvocationTotals,
getInvocationUpdateAnnotation,
getRollingTimeRange,
getUsageMetrics,
toEdgeFunctionChartData,
} from './EdgeFunctionOverview.utils'
import type { EdgeFunctionChartRawDatum } from './EdgeFunctionOverview.utils'
import { EdgeFunctionOverviewHeader } from './EdgeFunctionOverviewHeader'
import { EdgeFunctionPerformanceSection } from './EdgeFunctionPerformanceSection'
import { EdgeFunctionRecentErrors } from './EdgeFunctionRecentErrors'
import { EdgeFunctionUsageSection } from './EdgeFunctionUsageSection'
import { useEdgeFunctionOverviewShortcuts } from './useEdgeFunctionOverviewShortcuts'
import { useUnifiedLogsPreview } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { NoPermission } from '@/components/ui/NoPermission'
import {
FunctionsCombinedStatsVariables,
useFunctionsCombinedStatsQuery,
} from '@/data/analytics/functions-combined-stats-query'
import { useEdgeFunctionQuery } from '@/data/edge-functions/edge-function-query'
import { useFillTimeseriesSorted } from '@/hooks/analytics/useFillTimeseriesSorted'
import { FGA_PERMISSIONS, useAsyncCheckPermissionsV2 } from '@/hooks/misc/useCheckPermissionsV2'
import { navigateToUrl } from '@/lib/navigation'
export const EdgeFunctionOverview = () => {
const navigate = useNavigate()
const { ref: projectRef, functionSlug } = useParams()
const { isEnabled: isUnifiedLogsEnabled } = useUnifiedLogsPreview()
const [interval, setInterval] = useState<string>('1hr')
const selectedInterval =
EDGE_FUNCTION_CHART_INTERVALS.find((item) => item.key === interval) ||
EDGE_FUNCTION_CHART_INTERVALS[1]
const {
data: selectedFunction,
error: functionError,
isPending: isLoadingFunction,
isError: isErrorFunction,
} = useEdgeFunctionQuery({
projectRef,
slug: functionSlug,
})
const id = selectedFunction?.id
const combinedStatsResults = useFunctionsCombinedStatsQuery(
{
projectRef,
functionId: id,
interval: selectedInterval.key as FunctionsCombinedStatsVariables['interval'],
},
{
enabled: IS_PLATFORM,
}
)
const combinedStatsData = useMemo(
() => (combinedStatsResults.data?.result as EdgeFunctionChartRawDatum[] | undefined) || [],
[combinedStatsResults.data]
)
const [startDate, endDate] = useMemo(
() =>
getRollingTimeRange(
selectedInterval,
new Date(combinedStatsResults.dataUpdatedAt || Date.now())
),
[selectedInterval, combinedStatsResults.dataUpdatedAt]
)
const dateTimeFormat = selectedInterval.format ?? 'MMM D, h:mma'
const {
data: combinedStatsChartData,
error: combinedStatsError,
isError: isErrorCombinedStats,
} = useFillTimeseriesSorted({
data: combinedStatsData,
timestampKey: 'timestamp',
valueKey: [
'requests_count',
'log_count',
'log_info_count',
'log_warn_count',
'log_error_count',
'success_count',
'redirect_count',
'client_err_count',
'server_err_count',
'avg_cpu_time_used',
'avg_memory_used',
'avg_execution_time',
'max_execution_time',
'avg_heap_memory_used',
'avg_external_memory_used',
'max_cpu_time_used',
],
defaultValue: 0,
})
const chartData = useMemo(
() => toEdgeFunctionChartData(combinedStatsChartData),
[combinedStatsChartData]
)
const invocationChartData = useMemo(() => getInvocationChartData(chartData), [chartData])
const { totalInvocationCount, totalWarningCount, totalErrorCount } = useMemo(
() => getInvocationTotals(invocationChartData),
[invocationChartData]
)
const { averageExecutionTime, maxExecutionTime } = useMemo(
() => getExecutionMetrics(chartData),
[chartData]
)
const {
averageCpuTime,
maxCpuTime,
averageMemoryUsage,
totalHeapMemory,
totalExternalMemory,
totalMemoryByType,
} = useMemo(() => getUsageMetrics(chartData), [chartData])
const invocationUpdateAnnotation = useMemo(
() =>
getInvocationUpdateAnnotation({
updatedAt: selectedFunction?.updated_at,
invocationChartData,
windowStart: startDate,
windowEnd: endDate,
}),
[invocationChartData, selectedFunction?.updated_at, endDate, startDate]
)
const openLogsUrl = useMemo(() => {
if (!projectRef || !functionSlug) return undefined
if (!isUnifiedLogsEnabled) return `/project/${projectRef}/functions/${functionSlug}/invocations`
return getEdgeFunctionLogsUrl({
projectRef,
functionSlug,
start: startDate.toISOString(),
end: endDate.toISOString(),
})
}, [endDate, functionSlug, isUnifiedLogsEnabled, projectRef, startDate])
const invocationActions = useMemo(
() =>
openLogsUrl
? [
{
label: isUnifiedLogsEnabled ? 'Open logs' : 'Open invocations',
href: openLogsUrl,
icon: <ExternalLinkIcon size={12} />,
},
]
: [],
[isUnifiedLogsEnabled, openLogsUrl]
)
useEdgeFunctionOverviewShortcuts({
onSetInterval: setInterval,
onRefresh: () => {
combinedStatsResults.refetch()
},
onOpenLogs: () => {
if (openLogsUrl) void navigateToUrl(navigate, openLogsUrl)
},
})
const { isLoading: permissionsLoading, can: canReadFunction } = useAsyncCheckPermissionsV2(
FGA_PERMISSIONS.PROJECT.EDGE_FUNCTIONS_READ
)
useEffect(() => {
if (!IS_PLATFORM && projectRef && functionSlug) {
void navigate({
to: '/project/$ref/functions/$functionSlug/details',
params: { ref: projectRef, functionSlug },
replace: true,
})
}
}, [functionSlug, navigate, projectRef])
if (!canReadFunction && !permissionsLoading) {
return <NoPermission isFullPage resourceText="access this edge function" />
}
if (!IS_PLATFORM) {
return null
}
return (
<>
<EdgeFunctionOverviewHeader
actions={
<EdgeFunctionIntervalSelector interval={interval} onIntervalChange={setInterval} />
}
/>
<PageContainer size="default">
<EdgeFunctionInvocationsSection
dateTimeFormat={dateTimeFormat}
actions={invocationActions}
totalInvocationCount={totalInvocationCount}
totalErrorCount={totalErrorCount}
totalWarningCount={totalWarningCount}
isLoadingFunction={isLoadingFunction}
isErrorFunction={isErrorFunction}
functionError={functionError}
isLoadingChart={combinedStatsResults.isLoading}
isErrorChart={isErrorCombinedStats}
chartErrorMessage={combinedStatsError?.message ?? 'Unknown error'}
chartData={invocationChartData}
onChartClick={(timestamp) => {
if (!projectRef || !functionSlug) return
void navigateToUrl(
navigate,
getInvocationChartNavigationUrl({
projectRef,
functionSlug,
isUnifiedLogsEnabled,
rangeStart: startDate.toISOString(),
rangeEnd: endDate.toISOString(),
clickedTimestamp: timestamp,
})
)
}}
updateAnnotation={invocationUpdateAnnotation}
/>
<EdgeFunctionRecentErrors
functionId={id}
functionSlug={functionSlug as string}
projectRef={projectRef as string}
updatedAt={selectedFunction?.updated_at}
/>
<EdgeFunctionPerformanceSection
data={chartData}
dateTimeFormat={dateTimeFormat}
isLoading={combinedStatsResults.isLoading}
isError={isErrorCombinedStats}
errorMessage={combinedStatsError?.message ?? 'Unknown error'}
averageExecutionTime={averageExecutionTime}
maxExecutionTime={maxExecutionTime}
/>
<EdgeFunctionUsageSection
data={chartData}
dateTimeFormat={dateTimeFormat}
isLoading={combinedStatsResults.isLoading}
isError={isErrorCombinedStats}
errorMessage={combinedStatsError?.message ?? 'Unknown error'}
averageCpuTime={averageCpuTime}
maxCpuTime={maxCpuTime}
averageMemoryUsage={averageMemoryUsage}
totalHeapMemory={totalHeapMemory}
totalExternalMemory={totalExternalMemory}
totalMemoryByType={totalMemoryByType}
/>
</PageContainer>
</>
)
}