Files
supabase/apps/studio/components/interfaces/Functions/FunctionLogsNavigation.platform.test.tsx
T
5d52b00f70 feat(studio): combine function invocations and logs (#50957)
With the unified logs preview on, an edge function's Logs tab renders
the unified logs view scoped to that function (#50954), with its
invocations and runtime output in one list. That replaces the separate
Invocations and Logs tabs.

- `UnifiedLogs` takes a `scope` plus view props: `hasFilterSideBar`,
`offeredFilters` and `columnPreferencesKey`. The function Logs tab turns
the sidebar off, which also drops the filters-toggle shortcut, and saves
its columns and panel layout separately from the Logs page.
- `getEdgeFunctionLogsScope` and `EDGE_FUNCTION_LOGS_VIEW` are the edge
function preset: the scope's fixed filters, the filters the tab offers
and its saved-columns key. It offers date, log type, level and message,
so no user filter, since no function row has a user.
- The Invocations tab and its shortcut are hidden. Old Invocations links
redirect to Logs, converting `its`/`ite`/`log` to `date`/`id`.
- `getEdgeFunctionLogsUrl` builds links into the scoped tab with the
shared params serializer from #50953, and clicking a bar on the
invocations chart uses it.

With the preview off, both tabs work as on master.

### How to test

1. Turn on the unified logs preview and open an edge function's Logs
tab. You should see only that function's invocations and runtime logs,
with the filter bar limited to date, log type, level and message.
2. Filter to Edge Function runtime, then to errors, and check counts and
the chart follow.
3. Open an old `/functions/<slug>/invocations?its=…&ite=…&log=…` link.
It lands on Logs with the same range and log selected.
4. Click a bar on the Overview invocations chart. The Logs tab opens on
that bucket.

### Validation

- URL helper, offered filter and preset tests, plus the scoped query
tests from #50954.
- 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 14:54:56 +01:00

204 lines
7.6 KiB
TypeScript

import { QueryClient } from '@tanstack/react-query'
import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { FeatureFlagContext, LOCAL_STORAGE_KEYS } from 'common'
import { HttpResponse } from 'msw'
import { createDynamicRouteParser } from 'next-router-mock/dynamic-routes'
import { useRouter } from 'next/router'
import { afterAll, afterEach, beforeEach, expect, it, vi } from 'vitest'
import { useFunctionLogsMigration } from './useFunctionLogsMigration'
import { useFunctionsDetailShortcuts } from './useFunctionsDetailShortcuts'
import { FeaturePreviewContextProvider } from '@/components/interfaces/App/FeaturePreview/FeaturePreviewContext'
import type { EdgeFunction } from '@/data/edge-functions/edge-function-query'
import { LogPage } from '@/pages/project/[ref]/functions/[functionSlug]/invocations'
import { LogPage as FunctionLogsPage } from '@/pages/project/[ref]/functions/[functionSlug]/logs'
import { customRender } from '@/tests/lib/custom-render'
import { addAPIMock } from '@/tests/lib/msw'
vi.unmock('common')
const { default: routerMock } =
await vi.importMock<typeof import('next-router-mock')>('next/router')
const removeRouteParser = routerMock.useParser(
createDynamicRouteParser([
'/project/[ref]/functions/[functionSlug]',
'/project/[ref]/functions/[functionSlug]/logs',
'/project/[ref]/functions/[functionSlug]/invocations',
])
)
afterAll(removeRouteParser)
const featureFlags = {
configcat: {
otelLegacyLogs: true,
pipelineCreationWizard: false,
platformWebhooks: false,
jitDbAccess: false,
marketplaceIntegrations: false,
explorer: false,
storageVersioningPrivateAlpha: false,
sqlEditorManualSaveForced: false,
},
posthog: {},
hasLoaded: true,
}
beforeEach(() => {
routerMock.setCurrentUrl('/project/default/functions/send-email/invocations')
localStorage.setItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, 'true')
})
afterEach(() => {
localStorage.removeItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS)
act(() => routerMock.setCurrentUrl('/'))
})
it('forwards an invocation bookmark with its selected log, message, and time range to Logs', async () => {
const legacy = new URLSearchParams({
its: '2026-03-20T10:00:00Z',
ite: '2026-03-20T11:00:00Z',
log: 'selected-invocation',
s: 'delivery failed',
})
routerMock.setCurrentUrl(`/project/default/functions/send-email/invocations?${legacy}`)
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/functions/:function_slug',
response: () =>
HttpResponse.json<EdgeFunction>({
id: 'function-id',
name: 'Send email',
slug: 'send-email',
status: 'ACTIVE',
version: 1,
created_at: 1774000800000,
updated_at: 1774000800000,
}),
})
customRender(
<FeatureFlagContext.Provider value={featureFlags}>
<FeaturePreviewContextProvider>
<LogPage dehydratedState={undefined} />
</FeaturePreviewContextProvider>
</FeatureFlagContext.Provider>,
{ queryClient: new QueryClient({ defaultOptions: { queries: { retry: false } } }) }
)
await waitFor(() =>
expect(routerMock.asPath.split('?')[0]).toBe('/project/default/functions/send-email/logs')
)
const params = new URLSearchParams(routerMock.asPath.split('?')[1])
expect(params.get('id')).toBe('selected-invocation')
expect(params.get('filter')).toBe('event_message:ilike:delivery failed')
expect(params.get('date')).toBe('1774000800000-1774004400000')
})
function FunctionLogNavigation({ isEnabled = true, isLoading = false }) {
const router = useRouter()
const state = useFunctionLogsMigration({
asPath: router.asPath,
onReplace: router.replace,
projectRef: 'default',
functionSlug: 'send-email',
isEnabled,
isLoading,
})
return <div>{state.shouldUseLegacyLogs ? 'Legacy logs' : 'Unified logs'}</div>
}
it('waits for preview initialization and leaves preview opt-outs on their original bookmark', async () => {
const bookmark = '/project/default/functions/send-email/logs?log=legacy-log'
routerMock.setCurrentUrl(bookmark)
const { rerender } = customRender(<FunctionLogNavigation isLoading />)
expect(routerMock.asPath).toBe(bookmark)
rerender(<FunctionLogNavigation isEnabled={false} />)
expect(routerMock.asPath).toBe(bookmark)
rerender(<FunctionLogNavigation />)
await waitFor(() => expect(routerMock.query.id).toBe('legacy-log'))
})
it('migrates a new legacy Logs bookmark during client-side navigation', async () => {
routerMock.setCurrentUrl('/project/default/functions/send-email/logs')
customRender(<FunctionLogNavigation />)
await act(() => routerMock.push('/project/default/functions/send-email/logs?log=first'))
await waitFor(() => expect(routerMock.query.id).toBe('first'))
await act(() => routerMock.push('/project/default/functions/send-email/logs?log=second'))
await waitFor(() => expect(routerMock.query.id).toBe('second'))
})
it('retains the old function log filters when their meaning cannot migrate to unified filters', () => {
const filter = encodeURIComponent(JSON.stringify({ severity: { error: true } }))
const bookmark = `/project/default/functions/send-email/logs?f=${filter}`
routerMock.setCurrentUrl(bookmark)
customRender(<FunctionLogNavigation />)
expect(screen.getByText('Legacy logs')).toBeVisible()
expect(routerMock.asPath).toBe(bookmark)
})
function FunctionDetailNavigation({ hasInvocationsTab }: { hasInvocationsTab: boolean }) {
useFunctionsDetailShortcuts({
projectRef: 'default',
functionSlug: 'send-email',
canReadFunctions: true,
isPlatform: true,
hasInvocationsTab,
onOpenTest: () => {},
onOpenDownload: () => {},
onCopyUrl: () => {},
})
return <div>Function navigation</div>
}
it('disables the hidden Invocations shortcut while preserving Logs navigation', async () => {
const user = userEvent.setup()
routerMock.setCurrentUrl('/project/default/functions/send-email')
const { rerender } = customRender(<FunctionDetailNavigation hasInvocationsTab={false} />)
await user.keyboard('2')
expect(routerMock.asPath).toBe('/project/default/functions/send-email')
await user.keyboard('3')
expect(routerMock.asPath).toBe('/project/default/functions/send-email/logs')
rerender(<FunctionDetailNavigation hasInvocationsTab />)
await user.keyboard('2')
expect(routerMock.asPath).toBe('/project/default/functions/send-email/invocations')
})
function LegacyFunctionLogsBookmark() {
const router = useRouter()
if (router.query.id) return <div>Selected log: {router.query.id}</div>
return <FunctionLogsPage dehydratedState={undefined} />
}
it('opens a selected log from an old Logs bookmark using the unified time range', async () => {
const legacy = new URLSearchParams({
its: '2026-03-20T10:00:00Z',
ite: '2026-03-20T11:00:00Z',
log: 'runtime-message',
})
routerMock.setCurrentUrl(`/project/default/functions/send-email/logs?${legacy}`)
addAPIMock({
method: 'get',
path: '/v1/projects/:ref/functions/:function_slug',
response: () =>
HttpResponse.json<EdgeFunction>({
id: 'function-id',
name: 'Send email',
slug: 'send-email',
status: 'ACTIVE',
version: 1,
created_at: 1774000800000,
updated_at: 1774000800000,
}),
})
customRender(
<FeatureFlagContext.Provider value={featureFlags}>
<FeaturePreviewContextProvider>
<LegacyFunctionLogsBookmark />
</FeaturePreviewContextProvider>
</FeatureFlagContext.Provider>
)
expect(await screen.findByText('Selected log: runtime-message')).toBeVisible()
expect(routerMock.query.date).toBe('1774000800000-1774004400000')
expect(routerMock.query.log).toBeUndefined()
})