Files
kemal.earth b7d8b2d311 feat(studio): traces tab in unified logs (#54393)
## Problem

Unified Logs can show the logs correlated with a request, but not the
trace behind it. Where time actually went across services isn't visible
anywhere in Studio.

Part 3 of 3, and the one that ships the feature. Builds on the `Trace`
primitives from part 1 and the spans query from part 2.

## Solution

Adds a **Trace** tab to the log detail panel, composed entirely from the
shared `Trace` primitives — header, summary strip, waterfall, inspector
— and ships it as a feature preview.

**Resolving the trace id.** The selected log's own trace id wins. A
related log's id is used only as a fallback, and only when there's
exactly one candidate — picking between several would be a guess. The
ids come from the correlated logs the Timeline tab already fetches, so
the two tabs share a cache entry instead of each making a request.

**Mapping spans.** `RequestTrace.utils.ts` turns the endpoint's spans
into `Trace`'s `Span`/`TraceData` shape. Three things worth noting:

- Span names come from OTel attributes where the raw name isn't useful
on its own — a span named `GET` becomes `GET /rest/v1/orders` from
`http.route`, falling back to the path from `url.full` for outbound
fetches that have no server-matched route.
- `Date.parse` only resolves whole milliseconds, so two spans less than
a millisecond apart would round to the same instant and render stacked.
The fractional part of the ISO string is added back.
- Spans with a missing or invalid start time are counted and reported
rather than dropped silently.

**States.** The tab is always present when the Timeline is, so a request
with no trace shows an empty state rather than a tab that appears and
disappears as the trace resolves. Separate states cover: no trace id, a
trace with no spans, spans that exist but can't be placed, and a failed
fetch. `meta.partial` surfaces as a badge, since a trace can be
incomplete while spans are still being collected.

**Feature preview.** Listed under Observability as "Request traces",
following the same pattern as the Explorer and Storage versioning
previews. Two gates gives the kill switch and the opt-in independently:

- `enableTracesWaterfall` (ConfigCat) controls whether the preview is
listed at all
- The user's opt-in controls the tab, stored in local storage and
preserved across sign-out

It's not default opt-in, so nobody gets the tab without choosing it —
the endpoint is still alpha.

Also removes the temporary `knip.jsonc` entry added in part 2, now that
the query has an importer.

## Review instructions

1. Open the feature preview modal and confirm **Request traces** is
listed under Observability, with a panel describing the feature. Enable
it.
2. Open **Logs** and select a request log that has a trace id.
3. Confirm the **Trace** tab appears beside Timeline, with the header,
the summary strip (trace start, duration, services, depth, span count)
and the waterfall.
4. Select a span and confirm the inspector opens with its attributes and
events.
5. Select a request with no trace id and confirm the tab is still there,
showing an empty state.
6. Turn the preview off and confirm the tab disappears while Timeline is
unaffected.
7. `pnpm --filter studio test
components/interfaces/UnifiedLogs/components/RequestTrace.utils.test.ts
components/interfaces/UnifiedLogs/components/RequestTimeline.platform.test.tsx`

Note the traces endpoint is in alpha: a request only has a trace when
its logs carry a trace ID, so landing on the empty state in step 2 isn't
necessarily this PR misbehaving. The component tests cover every state
against mocked responses.
2026-12-04 11:24:48 +00:00

231 lines
7.6 KiB
TypeScript

import {
FeatureFlagContext,
LOCAL_STORAGE_KEYS,
safeLocalStorage,
useFlag,
useParams,
} from 'common'
import { noop } from 'lodash'
import { useQueryState } from 'nuqs'
import {
createContext,
useCallback,
useContext,
useEffect,
useEffectEvent,
useMemo,
useState,
type PropsWithChildren,
} from 'react'
import { useFeaturePreviews } from './useFeaturePreviews'
import { useProjectStorageConfigQuery } from '@/data/config/project-storage-config-query'
import { IS_PLATFORM } from '@/lib/constants'
import { EMPTY_OBJ } from '@/lib/void'
type FeaturePreviewContextType = {
flags: { [key: string]: boolean }
isInitialized: boolean
onUpdateFlag: (key: string, value: boolean) => void
}
const FeaturePreviewContext = createContext<FeaturePreviewContextType>({
flags: EMPTY_OBJ,
isInitialized: false,
onUpdateFlag: noop,
})
export const useFeaturePreviewContext = () => useContext(FeaturePreviewContext)
export const FeaturePreviewContextProvider = ({ children }: PropsWithChildren) => {
const { hasLoaded } = useContext(FeatureFlagContext)
const featurePreviews = useFeaturePreviews()
const [flags, setFlags] = useState(() =>
featurePreviews.reduce((a, b) => ({ ...a, [b.key]: false }), {})
)
// Tracks whether `flags` reflects the loaded feature flags (vs. the pre-load
// defaults). Only set true once `initializeFlags` runs with `hasLoaded`.
const [isInitialized, setIsInitialized] = useState(false)
const initializeFlags = useEffectEvent(() => {
setFlags(
featurePreviews.reduce((a, b) => {
// Platform-only previews can never be enabled outside the hosted platform
if (!IS_PLATFORM && b.isPlatformOnly) {
return { ...a, [b.key]: false }
}
// A forced preview has become the default behavior, so it's on whatever
// the user stored previously — including an explicit opt-out. Applied
// here rather than in the individual `useIsXEnabled` helpers so that the
// feature preview modal reflects it too.
if (b.isForced) {
return { ...a, [b.key]: true }
}
const defaultOptIn = b.isDefaultOptIn
const localStorageValue = safeLocalStorage.getItem(b.key)
return {
...a,
[b.key]: !localStorageValue ? defaultOptIn : localStorageValue === 'true',
}
}, {})
)
})
useEffect(() => {
if (typeof window !== 'undefined') {
initializeFlags()
// Defer marking initialized until the underlying flags have loaded, so
// flag-derived defaults (e.g. default opt-in) are reflected in `flags`.
if (hasLoaded) setIsInitialized(true)
}
}, [hasLoaded])
const value = {
flags,
isInitialized,
onUpdateFlag: (key: string, value: boolean) => {
safeLocalStorage.setItem(key, value ? 'true' : 'false')
setFlags((prevFlags) => ({ ...prevFlags, [key]: value }))
},
}
return <FeaturePreviewContext.Provider value={value}>{children}</FeaturePreviewContext.Provider>
}
// Helpers
export const usePipelineCreationPreview = () => {
const { flags, isInitialized } = useFeaturePreviewContext()
const isAvailable = useFlag('pipelineCreationWizard')
const isEnabled =
IS_PLATFORM &&
isInitialized &&
isAvailable &&
flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_PIPELINE_CREATION] === true
return { isEnabled, isLoading: !isInitialized }
}
export const useIsColumnLevelPrivilegesEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_CLS]
}
export const useUnifiedLogsPreview = () => {
const { flags, isInitialized, onUpdateFlag } = useFeaturePreviewContext()
const isLoading = !isInitialized
const isEnabled = IS_PLATFORM && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS]
const hasToggledPreview = !!safeLocalStorage.getItem(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS)
const isDefaultOptIn = IS_PLATFORM && !hasToggledPreview
const enable = () => onUpdateFlag(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, true)
const disable = () => onUpdateFlag(LOCAL_STORAGE_KEYS.UI_PREVIEW_UNIFIED_LOGS, false)
return { isEnabled, isLoading, isDefaultOptIn, enable, disable }
}
export const useIsPgDeltaDiffEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_PG_DELTA_DIFF]
}
export const useIsAdvisorRulesEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_ADVISOR_RULES]
}
export const useIsPlatformWebhooksEnabled = () => {
const { flags } = useFeaturePreviewContext()
const platformWebhooksEnabled = useFlag('platformWebhooks')
return platformWebhooksEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_PLATFORM_WEBHOOKS]
}
export const useIsJitDbAccessEnabled = () => {
const { flags } = useFeaturePreviewContext()
const jitDbAccessEnabled = useFlag('jitDbAccess')
return jitDbAccessEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_JIT_DB_ACCESS]
}
/**
* Whether the SQL Editor saves snippets only on request. True when the user
* opted into the preview themselves *or* the `sqlEditorManualSaveForced` rollout
* has reached them — the preview's `isForced` flag folds the latter into `flags`.
*/
export const useIsSqlEditorManualSaveEnabled = () => {
const { flags } = useFeaturePreviewContext()
return flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_SQL_EDITOR_MANUAL_SAVE]
}
export const useIsExplorerEnabled = () => {
const { flags } = useFeaturePreviewContext()
const isExplorerEnabled = useFlag('explorer')
return isExplorerEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_EXPLORER]
}
/** Three gates: the ConfigCat kill switch, the project's capability, and the user's opt-in. */
export const useIsStorageVersioningEnabled = () => {
const { ref } = useParams()
const { flags } = useFeaturePreviewContext()
const isStorageVersioningEnabled = useFlag('storageVersioningPrivateAlpha')
const { data } = useProjectStorageConfigQuery({ projectRef: ref })
const isObjectVersioningAvailable = !!data?.capabilities?.object_versioning
return (
isStorageVersioningEnabled &&
isObjectVersioningAvailable &&
flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_STORAGE_VERSIONING]
)
}
/** Two gates: the ConfigCat kill switch and the user's opt-in. */
export const useIsTracesEnabled = () => {
const { flags } = useFeaturePreviewContext()
const isTracesEnabled = useFlag('enableTracesWaterfall')
return isTracesEnabled && flags[LOCAL_STORAGE_KEYS.UI_PREVIEW_TRACES]
}
export const useFeaturePreviewModal = () => {
const featurePreviews = useFeaturePreviews()
const [featurePreviewModal, setFeaturePreviewModal] = useQueryState('featurePreviewModal')
const selectedFeatureKeyFromQuery = featurePreviewModal?.trim() ?? null
const showFeaturePreviewModal = selectedFeatureKeyFromQuery !== null
const selectedFeatureKey = (
!selectedFeatureKeyFromQuery ? featurePreviews[0].key : selectedFeatureKeyFromQuery
) as (typeof featurePreviews)[number]['key']
const selectFeaturePreview = useCallback(
(featureKey: (typeof featurePreviews)[number]['key']) => {
setFeaturePreviewModal(featureKey)
},
[setFeaturePreviewModal]
)
const toggleFeaturePreviewModal = useCallback(
(value: boolean) => {
if (!value) {
setFeaturePreviewModal(null)
} else {
selectFeaturePreview(selectedFeatureKey)
}
},
[selectFeaturePreview, setFeaturePreviewModal, selectedFeatureKey]
)
return useMemo(
() => ({
showFeaturePreviewModal,
selectedFeatureKey,
selectFeaturePreview,
toggleFeaturePreviewModal,
}),
[showFeaturePreviewModal, selectedFeatureKey, selectFeaturePreview, toggleFeaturePreviewModal]
)
}