import { queryOptions, type QueryClient } from '@tanstack/react-query' import { z } from 'zod' import { logsKeys } from './keys' import { getLogTimeWindow, runOtelLogsSql, unifiedLogAttributesQueryOptions, type UnifiedLogAttributesVariables, } from './unified-log-attributes-query' import { UNIFIED_LOGS_QUERY_OPTIONS } from './unified-logs-infinite-query' import { mapUnifiedLogRow, unifiedLogsQueryRowSchema } from './unified-logs.utils' import { getRequestCorrelationIds, getRequestTimelineQuery, type RequestCorrelationIds, } from '@/components/interfaces/UnifiedLogs/UnifiedLogs.queries' import { IS_PLATFORM } from '@/lib/constants' import type { StudioError } from '@/lib/errors/studio-errors' const TIMELINE_WINDOW_MS = 7 * 60 * 1000 const MAX_LOOKUPS = 2 const timelineRowSchema = unifiedLogsQueryRowSchema.extend({ source: z.string() }) export type UnifiedLogRequestTimelineVariables = UnifiedLogAttributesVariables export type UnifiedLogRequestTimelineError = StudioError const hasNewIds = (next: RequestCorrelationIds, prev: RequestCorrelationIds) => next.requestIds.some((id) => !prev.requestIds.includes(id)) || next.executionIds.some((id) => !prev.executionIds.includes(id)) || next.nativeRequestIds.some((id) => !prev.nativeRequestIds.includes(id)) || next.traceIds.some((id) => !prev.traceIds.includes(id)) async function getUnifiedLogRequestTimeline( { projectRef, logId, source, logTimestampMs }: UnifiedLogRequestTimelineVariables, queryClient: QueryClient, signal?: AbortSignal ) { if (!projectRef) throw new Error('projectRef is required') if (!logId) throw new Error('logId is required') if (!source) throw new Error('source is required') if (typeof logTimestampMs !== 'number' || !Number.isFinite(logTimestampMs)) { throw new Error('logTimestampMs is required') } const root = await queryClient.fetchQuery( unifiedLogAttributesQueryOptions({ projectRef, logId, source, logTimestampMs }) ) signal?.throwIfAborted() let ids = getRequestCorrelationIds( root ? [{ source: root.source, attributes: root.log_attributes }] : [] ) // Correlation keys are omitted from the list query's metadata for some sources (gateway, auth), // so the selected log's own trace ID can only be resolved from this full attributes lookup. const ownTraceId = ids.traceIds[0] let rows: z.infer[] = [] for (let lookup = 0; lookup < MAX_LOOKUPS; lookup++) { if (Object.values(ids).every((values) => values.length === 0)) break const result = await runOtelLogsSql({ projectRef, sql: getRequestTimelineQuery(ids), ...getLogTimeWindow(logTimestampMs, TIMELINE_WINDOW_MS), signal, }) rows = z.array(timelineRowSchema).parse(result) const found = getRequestCorrelationIds( rows.map((row) => ({ source: row.source, attributes: row.metadata })) ) if (!hasNewIds(found, ids)) break ids = { requestIds: [...new Set([...ids.requestIds, ...found.requestIds])], executionIds: [...new Set([...ids.executionIds, ...found.executionIds])], nativeRequestIds: [...new Set([...ids.nativeRequestIds, ...found.nativeRequestIds])], traceIds: [...new Set([...ids.traceIds, ...found.traceIds])], } } const logs = rows.map((row) => ({ ...mapUnifiedLogRow(row), metadata: row.metadata ?? null })) return { requestIds: ids.requestIds, executionIds: ids.executionIds, logs, ownTraceId } } export type UnifiedLogRequestTimelineData = Awaited> export const unifiedLogRequestTimelineQueryOptions = ({ projectRef, logId, source, logTimestampMs, }: UnifiedLogRequestTimelineVariables) => queryOptions({ queryKey: logsKeys.requestTimeline(projectRef, logId, source, logTimestampMs), queryFn: ({ client, signal }) => getUnifiedLogRequestTimeline({ projectRef, logId, source, logTimestampMs }, client, signal), enabled: IS_PLATFORM && typeof projectRef !== 'undefined' && typeof logId !== 'undefined' && typeof source !== 'undefined' && typeof logTimestampMs === 'number' && Number.isFinite(logTimestampMs), ...UNIFIED_LOGS_QUERY_OPTIONS, })