Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionOverview.tsx
T
Alaister YoungandAlaister Young d8568215ad [FE-5109] (part 4) refactor(studio): migrate database, editor, storage, and functions interfaces off next/router (#54056)
Part 4 of a 6-PR stack migrating all `next/router` and
`next/compat/router` imports in `apps/studio` onto TanStack Router hooks
and removing the router shims.

| Part | PR | Scope |
| --- | --- | --- |
| 1 | #54053 | Core navigation helpers, `hooks/**`, `lib/**`,
`data/prefetchers/**` |
| 2 | #54054 | `components/ui/**` |
| 3 | #54055 | `components/layouts/**` and `state/tabs.tsx` |
| **4** | **#54056 ← this PR** | **Database, Branching, Compute, Edge
Functions, Explorer, SQL Editor, Storage, Table Editor** |
| 5 | #54057 | Remaining `components/interfaces/**` and
`QueryInsightsTable` router events |
| 6 | #54058 | Remove `next/router` & `next/compat/router` shims,
`_router-events.ts`, Vite aliases, and test mocks |

Migrates the database, branching, compute, functions, explorer, SQL
editor, storage, and table editor interfaces off `next/router` and
`next/compat/router`.

**Changed:**

- Migrated the sole `next/compat/router` consumer
(`components/interfaces/Database/Replication/Destinations.tsx`) to
`useNavigate`
- Replaced `useRouter` across `BranchManagement`, `Branching`,
`Compute`, `Database` (`Backups`, `Functions`, `Replication`, `Schemas`,
`Tables`, `Triggers`), `EdgeFunctions`, `Explorer`, `Functions`,
`SQLEditor`, `Storage` (`AnalyticsBuckets`, `FilesBuckets`,
`VectorBuckets`, `StorageMenuV2`, `Storage.utils`), and
`TableGridEditor` with TanStack Router hooks (`useNavigate`,
`useLocation`, `useRoutePattern`) and `useParams` from `common`
- Updated unit and component tests across `Database/Replication`,
`Explorer`, `Functions`, and
`Storage/FilesBuckets/DeleteBucketModal.test.tsx` to use TanStack Router

**Simplified:**

- `useSnippetEditor` and `useRedirectLegacyReadReplicaDestination` read
search values from `useParams` instead of casting `location.search`
- `resolveSourceSwitch` returns `replace: boolean` instead of a
`push`/`replace` method name
- `ExplorerQueryTab` and `EdgeFunctionDetails` guard on a defined ref
instead of navigating with `ref ?? ''`
- `useFunctionsDetailShortcuts` and `StorageMenuV2` use a local `goTo`
helper for their navigation shortcuts
- Tests use the shared `createTestRouter` and `customRender` router, use
`toMatchObject` for search assertions, and drop duplicate assertions

Addresses
[FE-5109](https://linear.app/supabase/issue/FE-5109/replace-the-nextrouter-shims-with-tanstack-router-hooks)

## To test

- [ ] SQL Editor: creating, renaming, moving, opening
templates/examples, and keyboard shortcuts navigate between snippets
cleanly
- [ ] Table Editor & Database: opening tables, schema table nodes,
triggers, functions, backups/PITR, and replication destination flows
navigate as expected
- [ ] Storage: switching between Files, Analytics, and Vector buckets
and deleting a bucket navigates cleanly
- [ ] Edge Functions & Explorer: opening function details/logs, explorer
chat/query tabs, and branch management actions navigate properly

---------

Co-authored-by: Alaister Young <10985857+alaister@users.noreply.github.com>
2026-12-01 14:44:59 +08:00

265 lines
8.6 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,
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 invocationActions = useMemo(
() => [
{
label: isUnifiedLogsEnabled ? 'Open logs' : 'Open invocations',
href: `/project/${projectRef}/functions/${functionSlug}/${
isUnifiedLogsEnabled ? 'logs' : 'invocations'
}`,
icon: <ExternalLinkIcon size={12} />,
},
],
[functionSlug, isUnifiedLogsEnabled, projectRef]
)
useEdgeFunctionOverviewShortcuts({
onSetInterval: setInterval,
onRefresh: () => {
combinedStatsResults.refetch()
},
onOpenLogs: () => {
void navigateToUrl(
navigate,
`/project/${projectRef}/functions/${functionSlug}/${
isUnifiedLogsEnabled ? 'logs' : 'invocations'
}`
)
},
})
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>
</>
)
}