import { InfiniteData, keepPreviousData, useInfiniteQuery, useQueryClient, } from '@tanstack/react-query' import { useFeatureFlags } from 'common' import { executeAnalyticsSql } from './execute-analytics-sql' import { logsKeys } from './keys' import { logsAllEndpointUrl, pickLogsQueryBuilder } from './logs-endpoint' import { analyticsLiteral, safeSql } from './safe-analytics-sql' import { mapUnifiedLogRow, parseUnifiedLogsQueryRows, type UnifiedLogsQueryRow, } from './unified-logs.utils' import { getUnifiedLogsQuery } from '@/components/interfaces/UnifiedLogs/UnifiedLogs.queries' import { getUnifiedLogsQuery as getUnifiedLogsQueryBq } from '@/components/interfaces/UnifiedLogs/UnifiedLogs.queries.bq' import { PageParam, QuerySearchParamsType, } from '@/components/interfaces/UnifiedLogs/UnifiedLogs.types' import { handleError } from '@/data/fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomInfiniteQueryOptions } from '@/types' const LOGS_PAGE_LIMIT = 50 const REFRESH_REQUESTS_PER_RETAINED_PAGE = 2 const REFRESH_EXTRA_REQUESTS = 10 const createRefreshBudget = (retainedPageCount = 1) => ({ remaining: retainedPageCount * REFRESH_REQUESTS_PER_RETAINED_PAGE + REFRESH_EXTRA_REQUESTS, }) const refreshBudgets = new WeakMap() type RowCursor = Pick type RefreshBoundary = { row: RowCursor; hasMore: true } | { hasMore: false } type UnifiedLogsPageParam = | (NonNullable & { row?: RowCursor; refreshThrough?: RefreshBoundary }) | null | undefined export const UNIFIED_LOGS_QUERY_OPTIONS = { refetchOnWindowFocus: false, refetchOnMount: false, refetchOnReconnect: false, refetchInterval: 0, staleTime: 1000 * 60 * 5, // 5 minutes, } export type UnifiedLogsData = Awaited> export type UnifiedLogsError = StudioError export type UnifiedLogsVariables = { projectRef?: string; search: QuerySearchParamsType } type UnifiedLogsPageVariables = UnifiedLogsVariables & { pageSize?: number } export const useUnifiedLogsBackend = (search?: QuerySearchParamsType) => { const { otelUnifiedLogs = true } = useFeatureFlags().configcat const isOtelEnabled = typeof otelUnifiedLogs === 'boolean' ? otelUnifiedLogs : true return isOtelEnabled || !!search?.scope } export const getUnifiedLogsISOStartEnd = ( search: QuerySearchParamsType, endHoursFromNow: number = 1 ) => { // Extract date range from search or use default (last hour) let isoTimestampStart: string let isoTimestampEnd: string if (search.date && search.date.length === 2) { const parseDate = (d: string | Date) => (d instanceof Date ? d : new Date(d)) isoTimestampStart = parseDate(search.date[0]).toISOString() isoTimestampEnd = parseDate(search.date[1]).toISOString() } else { const now = new Date() isoTimestampEnd = now.toISOString() const nHoursAgo = new Date(now.getTime() - 60 * 60 * (endHoursFromNow * 1000)) isoTimestampStart = nHoursAgo.toISOString() } return { isoTimestampStart, isoTimestampEnd } } export async function getUnifiedLogs( { projectRef, search, pageParam, pageSize = LOGS_PAGE_LIMIT, useOtel = false, refreshThrough = pageParam?.refreshThrough, refreshBudget = createRefreshBudget(), }: UnifiedLogsPageVariables & { pageParam: UnifiedLogsPageParam useOtel?: boolean refreshThrough?: RefreshBoundary refreshBudget?: { remaining: number } }, signal?: AbortSignal, headersInit?: HeadersInit ) { if (typeof projectRef === 'undefined') throw new Error('projectRef is required for getUnifiedLogs') const { isoTimestampStart, isoTimestampEnd } = getUnifiedLogsISOStartEnd(search) const buildQuery = pickLogsQueryBuilder(useOtel, getUnifiedLogsQuery, getUnifiedLogsQueryBq) const cursorValue = pageParam?.cursor const cursorDirection = pageParam?.direction let timestampEnd = isoTimestampEnd if (cursorDirection === 'prev') { timestampEnd = new Date().toISOString() } else if (cursorDirection === 'next' && !pageParam?.row) { timestampEnd = cursorValue !== null && cursorValue !== undefined ? new Date(Number(cursorValue)).toISOString() : isoTimestampEnd } const endpoint = logsAllEndpointUrl(useOtel) const idColumn = useOtel ? safeSql`toString(id)` : safeSql`id` const cursorTimestamp = (cursor: RowCursor) => { const rawTimestamp = String(cursor.timestamp) const isIsoTimestamp = /[T-]/.test(rawTimestamp) let timestamp if (isIsoTimestamp) { timestamp = useOtel ? safeSql`parseDateTime64BestEffort(${analyticsLiteral(rawTimestamp)}, 9, 'UTC')` : safeSql`CAST(${analyticsLiteral(rawTimestamp)} AS TIMESTAMP)` } else { timestamp = useOtel ? safeSql`fromUnixTimestamp64Micro(${analyticsLiteral(Number(rawTimestamp))})` : safeSql`TIMESTAMP_MICROS(${analyticsLiteral(Number(rawTimestamp))})` } return timestamp } const fetchPage = async (cursor?: RowCursor) => { signal?.throwIfAborted() if (refreshThrough && refreshBudget.remaining-- <= 0) { throw new Error('Too many logs to refresh. Narrow the time range or filters and try again.') } let paginationFilter if (cursor) { const timestamp = cursorTimestamp(cursor) paginationFilter = safeSql`(timestamp < ${timestamp} OR (timestamp = ${timestamp} AND ${idColumn} < ${analyticsLiteral(cursor.id)}))` } if (refreshThrough?.hasMore) { const timestamp = cursorTimestamp(refreshThrough.row) const boundaryFilter = safeSql`(timestamp > ${timestamp} OR (timestamp = ${timestamp} AND ${idColumn} >= ${analyticsLiteral(refreshThrough.row.id)}))` paginationFilter = paginationFilter ? safeSql`${paginationFilter} AND ${boundaryFilter}` : boundaryFilter } const sql = safeSql`${buildQuery(search, paginationFilter)} ORDER BY timestamp DESC, ${idColumn} DESC LIMIT ${analyticsLiteral(pageSize)}` const data = await executeAnalyticsSql({ projectRef, endpoint, sql, iso_timestamp_start: isoTimestampStart, iso_timestamp_end: timestampEnd, signal, headers: headersInit, }) if (data.error) handleError(new Error(data.error as string)) return parseUnifiedLogsQueryRows(data?.result) } let page = await fetchPage(pageParam?.row) const rows = [...page] if (refreshThrough) { while (page.length === pageSize) { page = await fetchPage(page[page.length - 1]) rows.push(...page) } } const result = rows.map(mapUnifiedLogRow) const firstRow = result.length > 0 ? result[0] : null const lastRow = result.length > 0 ? result[result.length - 1] : null const lastQueryRow = rows.length > 0 ? rows[rows.length - 1] : pageParam?.row const hasMore = refreshThrough?.hasMore ?? result.length === pageSize const nextCursor = lastRow ? lastRow.date.getTime() : (pageParam?.cursor ?? null) const prevCursor = firstRow ? firstRow.date.getTime() : new Date().getTime() return { data: result, nextCursor: hasMore ? nextCursor : null, prevCursor, nextRow: lastQueryRow ? { id: lastQueryRow.id, timestamp: lastQueryRow.timestamp } : null, } } export const useUnifiedLogsInfiniteQuery = ( { projectRef, search, pageSize }: UnifiedLogsPageVariables, { enabled = true, ...options }: UseCustomInfiniteQueryOptions< UnifiedLogsData, UnifiedLogsError, InfiniteData, readonly unknown[], UnifiedLogsPageParam > = {} ) => { const useOtel = useUnifiedLogsBackend(search) const queryClient = useQueryClient() const queryKey = [ ...logsKeys.unifiedLogsInfinite(projectRef, search), { otel: useOtel, pageSize }, ] const getCachedPages = () => queryClient.getQueryData>(queryKey)?.pages ?? [] const getLoadedPages = () => getCachedPages().filter( (page, index, pages) => page.data.length > 0 || index === pages.length - 1 ) const getRefreshBoundary = ( pages: UnifiedLogsData[], index: number ): RefreshBoundary | undefined => { const page = pages[index] if (!page) return undefined const isExhausted = index === pages.length - 1 && page.nextCursor === null if (isExhausted) return { hasMore: false } return page.nextRow ? { row: page.nextRow, hasMore: true } : undefined } return useInfiniteQuery({ queryKey, queryFn: ({ signal, pageParam, direction }) => { const effectivePageParam = pageParam?.direction === 'prev' && direction !== 'backward' ? null : pageParam const isRefreshingFirstPage = direction !== 'backward' && (effectivePageParam === null || effectivePageParam === undefined) const refreshThrough = isRefreshingFirstPage ? getRefreshBoundary(getLoadedPages(), 0) : effectivePageParam?.refreshThrough if (refreshThrough && !refreshBudgets.has(signal)) { refreshBudgets.set(signal, createRefreshBudget(getLoadedPages().length)) } return getUnifiedLogs( { projectRef, search, pageParam: effectivePageParam, pageSize, useOtel, refreshThrough, refreshBudget: refreshBudgets.get(signal), }, signal ) }, enabled: enabled && typeof projectRef !== 'undefined', placeholderData: keepPreviousData, getPreviousPageParam: (firstPage) => { if (!firstPage.prevCursor) return null return { cursor: firstPage.prevCursor, direction: 'prev' } as const }, initialPageParam: null, getNextPageParam(lastPage, pages) { if (!lastPage.nextCursor || !lastPage.nextRow) return null const cachedPages = getCachedPages() const isRefreshing = pages[0] !== cachedPages[0] const loadedPages = getLoadedPages() if (isRefreshing && pages.length >= loadedPages.length) return null return { cursor: lastPage.nextCursor, direction: 'next', row: lastPage.nextRow ?? undefined, refreshThrough: isRefreshing ? getRefreshBoundary(loadedPages, pages.length) : undefined, } as const }, ...UNIFIED_LOGS_QUERY_OPTIONS, ...options, }) }