Files
supabase/apps/studio/components/interfaces/Functions/EdgeFunctionOverview/EdgeFunctionRecentErrors.tsx
T
7f7ebf527b feat(studio): use shared logs table for recent function errors (#50958)
The Overview's "Errors in the last 24h" section now uses the Logs tab's
queries (#50954) and the read-only `EmbeddedLogsTable` (#50953) instead
of its own SQL and table. It previews the latest five errors since the
last deploy, capped at 24h, shows "+N more" when there are more and
links to the rest. It's behind the `edgeFunctionsOverview` flag, like
the rest of the new Overview.

- Rows have no multi-select checkbox. Clicking one opens it in the Logs
tab with the same range and error filter, and "View logs" and "+N more"
open the filtered list.
- With the unified logs preview off, those links open the pre-unified
Invocations tab (for invocation rows) or Logs tab (for runtime rows),
using those tabs' own `its`/`ite`/`log` params.
- "Explain with AI" and "Copy summary" send the previewed errors to the
Assistant with the same prompt as selected logs on the Logs page. The
prompt also notes how many errors were left out.
- One count query, scoped to the function and unfiltered, gives both the
error count behind "+N more" and the invocations since the deploy, from
its level and log type facets. It replaces the hand-built invocation
count SQL, so the section runs two queries instead of three.
- The row query fetches only the five errors shown, through a new
`pageSize` option on `useUnifiedLogsInfiniteQuery`.
- The section uses the edge function preset from #50957, so it runs the
Logs tab's scoped queries and shares its saved columns.
- The custom error grouping and its SQL are removed. Net, the PR removes
about 390 lines.

### How to test

1. With `edgeFunctionsOverview` on, open a function that has recent
errors. You should see up to five rows without checkboxes, and "+N more"
when there are more.
2. Click a row with the unified logs preview on. It opens the Logs tab
with that log selected. Turn the preview off and click an invocation row
and a runtime row. They open Invocations and Logs respectively.
3. Use Explain with AI and Copy summary and check the prompt.
4. For a function with no errors since the last deploy, the section
shows the invocation count instead.

### Validation

- MSW component tests: preview rows and "+N more", no checkboxes, the
summary prompt, row links with the preview on and off, and the no-errors
state. They also check the row query asks for five rows and that a
single unfiltered count runs. `pageSize` and the facet count helper have
unit tests.
- Studio typecheck, lint ratchet, Prettier and knip pass on this layer.

### Stack

Merge in order:

1. #50953 — reusable logs table building blocks
2. #50954 — function-scoped unified logs queries
3. #50955 — slimmer function detail layout, header on Overview
4. #50957 — Invocations merged into a function-scoped Logs tab
5. #50958 — Overview errors in the shared logs table
6. #52281 — remove the legacy Overview

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Jordi Enric <jordi.err@gmail.com>
2026-10-27 16:47:51 +01:00

195 lines
6.8 KiB
TypeScript

import { CheckIcon, ExternalLinkIcon, EyeIcon } from 'lucide-react'
import { useRouter } from 'next/router'
import { useMemo } from 'react'
import { Button, Card } from 'ui'
import {
PageSection,
PageSectionAside,
PageSectionContent,
PageSectionMeta,
PageSectionSummary,
PageSectionTitle,
} from 'ui-patterns/PageSection'
import {
EDGE_FUNCTION_LOGS_VIEW,
getEdgeFunctionLogsScope,
getEdgeFunctionLogsUrl,
getLegacyEdgeFunctionLogsUrl,
} from './EdgeFunctionOverview.utils'
import {
getSinceLastDeployInvocationPhrase,
getSinceLastDeployLogRange,
} from './EdgeFunctionRecentErrors.utils'
import { EdgeFunctionRecentErrorsActions } from './EdgeFunctionRecentErrorsActions'
import { useUnifiedLogsPreview } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import { EmbeddedLogsTable } from '@/components/interfaces/UnifiedLogs/components/EmbeddedLogsTable'
import type { ColumnSchema } from '@/components/interfaces/UnifiedLogs/UnifiedLogs.schema'
import {
createUnifiedLogsSearch,
getFacetValueCount,
getUniqueLogRows,
} from '@/components/interfaces/UnifiedLogs/UnifiedLogs.utils'
import { useUnifiedLogsCountQuery } from '@/data/logs/unified-logs-count-query'
import { useUnifiedLogsInfiniteQuery } from '@/data/logs/unified-logs-infinite-query'
const ERROR_LOG_FILTERS = ['level:eq:error']
const MAX_VISIBLE_ERRORS = 5
interface EdgeFunctionRecentErrorsProps {
functionId?: string
functionSlug?: string
projectRef?: string
updatedAt?: string | number
}
export const EdgeFunctionRecentErrors = ({
functionId,
functionSlug,
projectRef,
updatedAt,
}: EdgeFunctionRecentErrorsProps) => {
const router = useRouter()
const { isEnabled: isUnifiedLogsEnabled } = useUnifiedLogsPreview()
const { isoTimestampStart, isoTimestampEnd } = useMemo(
() => getSinceLastDeployLogRange(updatedAt),
[updatedAt]
)
const { errorsSearch, countsSearch } = useMemo(() => {
const scope = functionId ? getEdgeFunctionLogsScope(functionId) : undefined
const date =
isoTimestampStart && isoTimestampEnd
? [new Date(isoTimestampStart), new Date(isoTimestampEnd)]
: null
return {
errorsSearch: createUnifiedLogsSearch({ filter: ERROR_LOG_FILTERS, date }, scope),
countsSearch: createUnifiedLogsSearch({ date }, scope),
}
}, [functionId, isoTimestampStart, isoTimestampEnd])
const isQueryEnabled = Boolean(projectRef && functionId && isoTimestampStart)
const { data, error, isError, isPending, isFetching } = useUnifiedLogsInfiniteQuery(
{ projectRef, search: errorsSearch, pageSize: MAX_VISIBLE_ERRORS },
{ enabled: isQueryEnabled, placeholderData: undefined }
)
const { data: counts } = useUnifiedLogsCountQuery(
{ projectRef, search: countsSearch },
{ enabled: isQueryEnabled }
)
const rows = useMemo(() => getUniqueLogRows<ColumnSchema>(data?.pages), [data?.pages])
const errorCount = counts ? getFacetValueCount(counts.facets, 'level', 'error') : rows.length
const hiddenErrorCount = Math.max(errorCount - rows.length, 0)
const invocationCount = counts
? getFacetValueCount(counts.facets, 'log_type', 'edge function')
: undefined
const getLogsUrl = (row?: ColumnSchema) => {
const target = {
projectRef: projectRef ?? '',
functionSlug: functionSlug ?? '',
start: isoTimestampStart,
end: isoTimestampEnd,
logId: row?.id,
}
if (isUnifiedLogsEnabled) {
return getEdgeFunctionLogsUrl({ ...target, filters: ERROR_LOG_FILTERS })
}
const tab = row?.log_type === 'edge function' ? 'invocations' : 'logs'
return getLegacyEdgeFunctionLogsUrl({ ...target, tab })
}
const handleOpenLogs = () => router.push(getLogsUrl())
const handleOpenLog = (logId: string) => {
router.push(getLogsUrl(rows.find((row) => row.id === logId)))
}
const isLoading = !functionId || (isQueryEnabled && isPending)
const hasNoErrors = !isLoading && !isError && rows.length === 0
return (
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
<PageSectionTitle>Errors in the last 24h</PageSectionTitle>
</PageSectionSummary>
<PageSectionAside>
<EdgeFunctionRecentErrorsActions rows={rows} omittedCount={hiddenErrorCount} />
<Button size="tiny" icon={<ExternalLinkIcon size={14} />} onClick={handleOpenLogs}>
View logs
</Button>
</PageSectionAside>
</PageSectionMeta>
<PageSectionContent>
{hasNoErrors && (
<div className="rounded-md border border-dashed px-5 py-6 text-sm text-foreground-light">
<div className="flex items-start gap-3">
{invocationCount !== undefined && invocationCount > 0 && (
<CheckIcon
size={16}
strokeWidth={1.5}
className="mt-0.5 shrink-0 text-primary"
aria-hidden="true"
/>
)}
{invocationCount === 0 && (
<EyeIcon
size={16}
strokeWidth={1.5}
className="mt-0.5 shrink-0 text-foreground-muted"
aria-hidden="true"
/>
)}
<div>
{invocationCount !== undefined ? (
<>
There {invocationCount === 1 ? 'has' : 'have'} been{' '}
<span className="text-foreground">
{getSinceLastDeployInvocationPhrase(invocationCount)}
</span>{' '}
since last deploy and no errors.
</>
) : (
'Runtime errors since the last deploy will appear here when this function returns a 5xx response.'
)}
</div>
</div>
</div>
)}
{!hasNoErrors && (
<Card className="overflow-hidden">
<EmbeddedLogsTable
rows={rows}
isLoading={isLoading}
isFetching={isFetching}
error={error}
isError={isError}
onRowClick={handleOpenLog}
skeletonRowCount={MAX_VISIBLE_ERRORS}
columnPreferencesKey={EDGE_FUNCTION_LOGS_VIEW.columnPreferencesKey}
footer={
hiddenErrorCount > 0 && (
<div className="px-0.5 py-0.5">
<Button
variant="text"
size="tiny"
className="text-foreground-lighter"
onClick={handleOpenLogs}
>
+{hiddenErrorCount.toLocaleString('en-US')} more
</Button>
</div>
)
}
/>
</Card>
)}
</PageSectionContent>
</PageSection>
)
}