import dayjs from 'dayjs' import { DEFAULT_LOG_TYPES, LOG_TYPE_TO_SOURCE } from './UnifiedLogs.constants' import { getLogAttributeKey, groupLogsFiltersByColumn, parseLogsFilterGroupUrlParams, parseLogsFilterUrlParams, type LogsFilterGroup, type LogsFilterOperator, } from './UnifiedLogs.filters' import { unifiedLogsScopeSchema } from './UnifiedLogs.schema' import { QuerySearchParamsType, SearchParamsType, UnifiedLogsScope } from './UnifiedLogs.types' import { wrapIlikePattern } from './UnifiedLogs.utils' import { PIPELINE_ID_OTEL_SQL } from '@/data/logs/pipeline-logs' import { joinSqlFragments, analyticsLiteral as lit, safeSql, type SafeLogSqlFragment, } from '@/data/logs/safe-analytics-sql' import { COMPUTE_LOG_SUBSERVICES } from '@/lib/constants/compute' // Operator fragments for SQL emission. `safeSql` rejects plain strings, so we // pre-brand the keywords we want to switch between. const IN_OP = safeSql`IN` const NOT_IN_OP = safeSql`NOT IN` const LIKE_OP = safeSql`LIKE` const NOT_LIKE_OP = safeSql`NOT LIKE` const ILIKE_OP = safeSql`ILIKE` const NOT_ILIKE_OP = safeSql`NOT ILIKE` // Facets the count query is allowed to be invoked for. Reject anything else // at the entry point rather than letting an unsupported value reach // `log_attributes[…]` lookups. const FACET_FIELDS = ['log_type', 'level', 'method', 'status', 'pathname', 'pipeline_id'] as const // OTEL log_attributes keys for HTTP-style fields. Centralized so they can be // adjusted in one place if the backend conventions change. const ATTR = { method: safeSql`log_attributes['request.method']`, status: safeSql`log_attributes['response.status_code']`, path: safeSql`log_attributes['request.path']`, } as const // The HTTP status code lives under different OTEL attribute keys per service: // gateway rows (edge / postgrest / edge function) expose it as // `response.status_code`, auth-service rows expose it as `status`, and // storage-service rows expose it as `res.statusCode`. This normalizes the // three so both the displayed status and the derived severity are correct // for those sources (which would otherwise have an empty status and fall // back to their `severity_text` of INFO, classifying every 4xx/5xx as success). const HTTP_STATUS_EXPR: SafeLogSqlFragment = safeSql`CASE WHEN source = 'auth_logs' THEN log_attributes['status'] WHEN source = 'storage_logs' THEN log_attributes['res.statusCode'] ELSE ${ATTR.status} END` // storage-service rows expose method/path under `req.method` / `req.url` // rather than the gateway's `request.method` / `request.path`, and // edge function rows expose their path as `request.pathname`. A missing map // key reads as '', so edge function rows without `request.pathname` fall // through to `request.path`. const HTTP_METHOD_EXPR: SafeLogSqlFragment = safeSql`if(source = 'storage_logs', log_attributes['req.method'], ${ATTR.method})` const HTTP_PATH_EXPR: SafeLogSqlFragment = safeSql`multiIf(source = 'storage_logs', log_attributes['req.url'], source = 'function_edge_logs' AND log_attributes['request.pathname'] != '', log_attributes['request.pathname'], ${ATTR.path})` /** * Condition that matches rows belonging to a given log_type. Mirrors the * shape of the original BigQuery unified-logs CTEs: edge gateway traffic * (`source = 'edge_logs'`) is split between `edge`, `postgrest` and `storage` * based on URL path. Other types map straight to a single source. * * The OTEL `postgrest_logs` and `storage_logs` sources contain process-level * logs from postgREST / storage-api and are intentionally not part of unified * logs; the UI surfaces gateway HTTP traffic for those buckets. */ // Compute rows are matched on their stream names rather than a source: the mapping does // not classify them, so `source` is empty and the backend's top-level `subservice` lands // in `log_attributes`. The stream names are product-prefixed, which is what makes this // list a product filter as well as a stream one. const COMPUTE_SUBSERVICE_VALUES = Object.values(COMPUTE_LOG_SUBSERVICES) const COMPUTE_SUBSERVICE_CONDITION = safeSql`log_attributes['subservice'] IN (${joinSqlFragments( COMPUTE_SUBSERVICE_VALUES.map((subservice) => lit(subservice)), ',' )})` const LOG_TYPE_CONDITION: Record = { ...Object.fromEntries( Object.entries(LOG_TYPE_TO_SOURCE).map(([type, source]) => [ type, safeSql`source = ${lit(source)}`, ]) ), compute: COMPUTE_SUBSERVICE_CONDITION, } // Derived `log_type` column for SELECT / GROUP BY / countIf use. // WHEN source = 'edge_logs' AND ${ATTR.path} LIKE '%/rest/%' THEN 'postgrest' // WHEN source = 'edge_logs' AND ${ATTR.path} LIKE '%/storage/%' THEN 'storage' const LOG_TYPE_EXPR: SafeLogSqlFragment = safeSql`CASE WHEN source = 'postgrest_logs' THEN 'postgrest' WHEN source = 'storage_logs' THEN 'storage' WHEN source = 'edge_logs' THEN 'edge' WHEN source = 'postgres_logs' THEN 'postgres' WHEN source = 'function_edge_logs' THEN 'edge function' WHEN source = 'function_logs' THEN 'edge function runtime' WHEN source = 'auth_logs' THEN 'auth' WHEN source = 'realtime_logs' THEN 'realtime' WHEN source = 'supavisor_logs' THEN 'supavisor' WHEN source = 'pgbouncer_logs' THEN 'pgbouncer' WHEN source = 'multigres_logs' THEN 'multigres' WHEN source = 'etl_replication_logs' THEN 'pipelines' WHEN ${COMPUTE_SUBSERVICE_CONDITION} THEN 'compute' ELSE source END` // Status code is sourced from the HTTP response for gateway-style rows, the // auth-service `status` attribute for auth rows, and the Postgres // `parsed.sql_state_code` (e.g. `42P01`) for postgres rows. const STATUS_EXPR: SafeLogSqlFragment = safeSql`CASE WHEN ${COMPUTE_SUBSERVICE_CONDITION} THEN null WHEN source = 'etl_replication_logs' THEN null WHEN source = 'postgres_logs' THEN toString(log_attributes['parsed.sql_state_code']) ELSE toString((${HTTP_STATUS_EXPR})) END` const METHOD_EXPR: SafeLogSqlFragment = safeSql`if(${COMPUTE_SUBSERVICE_CONDITION} OR source = 'etl_replication_logs', null, ${HTTP_METHOD_EXPR})` const PATHNAME_EXPR: SafeLogSqlFragment = safeSql`if(${COMPUTE_SUBSERVICE_CONDITION} OR source = 'etl_replication_logs', null, ${HTTP_PATH_EXPR})` const METADATA_EXPR: SafeLogSqlFragment = safeSql`if(${COMPUTE_SUBSERVICE_CONDITION} OR source IN ('function_logs', 'etl_replication_logs'), log_attributes, map())` const LEVEL_EXPR: SafeLogSqlFragment = safeSql`CASE WHEN ${COMPUTE_SUBSERVICE_CONDITION} THEN null WHEN source = 'etl_replication_logs' THEN multiIf( upper(coalesce(nullIf(log_attributes['level'], ''), severity_text)) IN ('ERROR','FATAL','PANIC','CRITICAL','ALERT','EMERGENCY'), 'error', upper(coalesce(nullIf(log_attributes['level'], ''), severity_text)) IN ('WARN','WARNING'), 'warning', 'success' ) WHEN source = 'function_logs' AND lower(log_attributes['level']) IN ('error','fatal') THEN 'error' WHEN source = 'function_logs' AND lower(log_attributes['level']) IN ('warn','warning') THEN 'warning' WHEN (${HTTP_STATUS_EXPR}) != '' AND toInt32OrZero((${HTTP_STATUS_EXPR})) >= 500 THEN 'error' WHEN (${HTTP_STATUS_EXPR}) != '' AND toInt32OrZero((${HTTP_STATUS_EXPR})) BETWEEN 400 AND 499 THEN 'warning' WHEN (${HTTP_STATUS_EXPR}) != '' AND toInt32OrZero((${HTTP_STATUS_EXPR})) BETWEEN 200 AND 299 THEN 'success' WHEN severity_text IN ('ERROR','FATAL','PANIC','CRITICAL','ALERT','EMERGENCY') THEN 'error' WHEN severity_text IN ('WARN','WARNING') THEN 'warning' WHEN severity_text IN ('TRACE','DEBUG','INFO','LOG','NOTICE') THEN 'success' ELSE 'success' END` // The `auth_user` column is derived from the source-specific fields that can be attributed to a user. const AUTH_USER_EXPR: SafeLogSqlFragment = safeSql`nullIf(CASE WHEN source = 'auth_logs' THEN log_attributes['auth_event.actor_id'] WHEN source = 'edge_logs' THEN log_attributes['request.sb.jwt.authorization.payload.subject'] ELSE null END, '')` const logTypeWhereCondition = (logTypes: string[]): SafeLogSqlFragment => { const effective = logTypes.filter((t) => t in LOG_TYPE_CONDITION) const types = effective.length ? effective : [...DEFAULT_LOG_TYPES] const branches = types.map((t) => safeSql`(${LOG_TYPE_CONDITION[t]})`) return safeSql`(${joinSqlFragments(branches, ' OR ')})` } /** * Translates one (column, values, operator) group from the parsed `filter` URL * param into an underlying SQL condition. The OTEL endpoint rejects queries * that reference derived aliases like `log_type` or `level` in WHERE for some * shapes, so we always emit raw-column conditions (source/severity_text/ * log_attributes[…]). For `<>`, IN becomes NOT IN, LIKE becomes NOT LIKE, and * multi-value lists are joined with AND so the row must not match *any* value. */ const translateFilter = ( key: string, values: readonly string[], operator: LogsFilterOperator ): SafeLogSqlFragment | null => { if (values.length === 0) return null const isNeq = operator === '<>' const inOp = isNeq ? NOT_IN_OP : IN_OP const likeOp = isNeq ? NOT_LIKE_OP : LIKE_OP const joinAndOr = isNeq ? ' AND ' : ' OR ' const inList = (vals: readonly string[]): SafeLogSqlFragment => safeSql`(${joinSqlFragments( vals.map((v) => lit(v)), ',' )})` const attributeKey = getLogAttributeKey(key) if (attributeKey !== undefined) { return safeSql`log_attributes[${lit(attributeKey)}] ${inOp} ${inList(values)}` } switch (key) { case 'pipeline_id': return safeSql`(source = 'etl_replication_logs' AND ${PIPELINE_ID_OTEL_SQL} ${inOp} ${inList(values)})` case 'log_type': { const branches = values.map((t) => { const condition = LOG_TYPE_CONDITION[t] ?? safeSql`source = ${lit(t)}` return isNeq ? safeSql`NOT (${condition})` : safeSql`(${condition})` }) return safeSql`(${joinSqlFragments(branches, joinAndOr)})` } case 'level': // No simple raw column for level; reference the inline CASE expression. return safeSql`(${LEVEL_EXPR}) ${inOp} ${inList(values)}` case 'method': // Match the displayed method: gateway rows read `request.method`, // storage rows read `req.method`. Inline HTTP_METHOD_EXPR so filtering // picks up storage rows too. return safeSql`(${HTTP_METHOD_EXPR}) ${inOp} ${inList(values)}` case 'status': // Match the displayed status: HTTP response code for gateway rows, // Postgres SQLSTATE for postgres rows. Inline STATUS_EXPR so e.g. // filtering on '00000' picks up postgres success rows. return safeSql`(${STATUS_EXPR}) ${inOp} ${inList(values)}` case 'pathname': { // Match the displayed pathname: gateway rows read `request.path`, // storage rows read `req.url`, and edge function rows read // `request.pathname`. Inline HTTP_PATH_EXPR so filtering picks up all of them. if (operator === '~~*' || operator === '!~~*') { const op = operator === '~~*' ? ILIKE_OP : NOT_ILIKE_OP const join = operator === '!~~*' ? ' AND ' : ' OR ' return safeSql`(${joinSqlFragments( values.map((v) => safeSql`(${HTTP_PATH_EXPR}) ${op} ${lit(wrapIlikePattern(v))}`), join )})` } return safeSql`(${HTTP_PATH_EXPR}) ${inOp} ${inList(values)}` } case 'host': // Best-effort: use full request URL since `host` isn't a top-level field. return safeSql`(${joinSqlFragments( values.map((v) => safeSql`log_attributes['request.url'] ${likeOp} ${lit('%' + v + '%')}`), joinAndOr )})` case 'event_message': { // event_message is a top-level column, not a log_attributes key. ILIKE/NOT ILIKE // auto-wrap with `%…%` so the user can type "permission denied" as a substring // search; explicit `%`s in the input are passed through unchanged. Multiple // ILIKE values join with OR (match any); multiple NOT ILIKE values join with AND // (the row must contain none of them). if (operator === '~~*' || operator === '!~~*') { const op = operator === '~~*' ? ILIKE_OP : NOT_ILIKE_OP const join = operator === '!~~*' ? ' AND ' : ' OR ' return safeSql`(${joinSqlFragments( values.map((v) => safeSql`event_message ${op} ${lit(wrapIlikePattern(v))}`), join )})` } // = / <> still emit exact match against the column — defensive; the // FilterBar doesn't expose them for event_message, but a hand-crafted URL // might. return safeSql`event_message ${inOp} ${inList(values)}` } default: return safeSql`log_attributes[${lit(key)}] ${inOp} ${inList(values)}` } } /** * Translates one `group:or:…` filter entry into `(cond1 OR cond2 …)`. Returns null when any * condition can't be translated, so the caller drops the whole group — dropping a single * condition would silently narrow the OR. */ const translateFilterGroup = (group: LogsFilterGroup): SafeLogSqlFragment | null => { const conditions: SafeLogSqlFragment[] = [] for (const { column, operator, value } of group.filters) { try { const condition = translateFilter(column, [value], operator) if (!condition) return null conditions.push(condition) } catch { return null } } if (conditions.length === 0) return null return safeSql`(${joinSqlFragments(conditions, ' OR ')})` } const NO_ROWS: SafeLogSqlFragment = safeSql`0` export const getUnifiedLogsScopeCondition = ( scope?: UnifiedLogsScope ): SafeLogSqlFragment | null => { if (!scope) return null const result = unifiedLogsScopeSchema.safeParse(scope) if (!result.success || result.data.filters.length === 0) return NO_ROWS const groups = new Map< string, { column: string; operator: LogsFilterOperator; values: string[] } >() for (const { column, operator, value } of result.data.filters) { const isPatternOperator = operator === '~~*' || operator === '!~~*' const supportsPatternOperator = column === 'event_message' || column === 'pathname' if (isPatternOperator && !supportsPatternOperator) return NO_ROWS const key = `${column}:${operator}` const group = groups.get(key) ?? { column, operator, values: [] } group.values.push(value) groups.set(key, group) } const conditions: SafeLogSqlFragment[] = [] for (const { column, operator, values } of groups.values()) { try { const condition = translateFilter(column, values, operator) if (!condition) return NO_ROWS conditions.push(condition) } catch { return NO_ROWS } } return safeSql`(${joinSqlFragments(conditions, ' AND ')})` } const whereClause = (conditions: SafeLogSqlFragment[]): SafeLogSqlFragment => conditions.length > 0 ? safeSql`WHERE ${joinSqlFragments(conditions, ' AND ')}` : safeSql`` /** * Calculates the chart bucketing level (minute/hour/day) given the date range. */ const calculateChartBucketing = ( search: SearchParamsType | Record ): 'MINUTE' | 'HOUR' | 'DAY' => { const dateRange = (search.date as Array) || [] const convertToMillis = (timestamp: Date | string | number | null | undefined) => { if (!timestamp) return null if (timestamp instanceof Date) return timestamp.getTime() if (typeof timestamp === 'string') return dayjs(timestamp).valueOf() if (typeof timestamp === 'number') { const str = timestamp.toString() if (str.length >= 16) return Math.floor(timestamp / 1000) return timestamp } return null } let startMillis = convertToMillis(dateRange[0]) let endMillis = convertToMillis(dateRange[1]) if (!startMillis) startMillis = dayjs().subtract(1, 'hour').valueOf() if (!endMillis) endMillis = dayjs().valueOf() const startTime = dayjs(startMillis) const endTime = dayjs(endMillis) const hourDiff = endTime.diff(startTime, 'hour') const dayDiff = endTime.diff(startTime, 'day') if (dayDiff >= 2) return 'DAY' if (hourDiff >= 12) return 'HOUR' return 'MINUTE' } const truncationFunction = (level: 'MINUTE' | 'HOUR' | 'DAY'): SafeLogSqlFragment => { switch (level) { case 'DAY': return safeSql`toStartOfDay` case 'HOUR': return safeSql`toStartOfHour` case 'MINUTE': default: return safeSql`toStartOfMinute` } } /** * Returns the projection list for a unified-logs row. All derivations are * inlined so the result can be referenced (or filtered) at the same query * level — the OTEL endpoint rejects subqueries. */ const ROW_PROJECTION: SafeLogSqlFragment = safeSql` id, null AS source_id, timestamp, ${LOG_TYPE_EXPR} AS log_type, ${STATUS_EXPR} AS status, ${LEVEL_EXPR} AS level, ${PATHNAME_EXPR} AS pathname, event_message, ${METHOD_EXPR} AS method, ${AUTH_USER_EXPR} AS auth_user, if(source = 'etl_replication_logs', ${PIPELINE_ID_OTEL_SQL}, null) AS pipeline_id, ${METADATA_EXPR} AS metadata, null AS log_count, null AS logs ` const buildBaseWhere = ( search: QuerySearchParamsType, excludeField?: string ): SafeLogSqlFragment[] => { const grouped = groupLogsFiltersByColumn(parseLogsFilterUrlParams(search.filter)) const parts: SafeLogSqlFragment[] = [] if (excludeField !== 'log_type') { const logTypeFilter = grouped.log_type if (logTypeFilter) { const condition = translateFilter('log_type', logTypeFilter.values, logTypeFilter.operator) if (condition) parts.push(condition) if (!search.scope && logTypeFilter.operator === '<>') { parts.push(safeSql`NOT (${LOG_TYPE_CONDITION['edge function runtime']})`) } } else if (grouped.pipeline_id) { parts.push(safeSql`source = 'etl_replication_logs'`) } else if (!search.scope && !userFilterValue(search)) { // Skip the default (postgres|edge) source restriction while the user filter is // active — the user clause governs which sources are eligible (auth + postgres), // and the default would otherwise exclude auth_logs, the primary attributable source. parts.push(logTypeWhereCondition([...DEFAULT_LOG_TYPES])) } } const scope = getUnifiedLogsScopeCondition(search.scope) if (scope) parts.push(scope) for (const [key, { operator, values }] of Object.entries(grouped)) { if (key === excludeField) continue if (key === 'log_type') continue // handled above try { const condition = translateFilter(key, values, operator) if (condition) parts.push(condition) } catch { // analyticsLiteral rejected an unsupported input — drop the condition. } } for (const group of parseLogsFilterGroupUrlParams(search.filter)) { const condition = translateFilterGroup(group) if (condition) parts.push(condition) } const searchParamsFilter = applySearchParamsFilter(search) if (searchParamsFilter) parts.push(searchParamsFilter) return parts } // Path substrings that identify which downstream service an `edge_logs` // (API Gateway) row was routed to. Mirrors the convention already used by // the sibling Logs Explorer (Logs.constants.ts / Logs.utils.otel.ts) and by // ServiceFlow.sql.ts within this same feature. const EDGE_SERVICE_PATH_FILTER: Record<'edge_auth' | 'edge_storage' | 'edge_postgrest', string> = { edge_auth: '%/auth/%', edge_storage: '%/storage/%', edge_postgrest: '%/rest/%', } /** * Returns view-option WHERE conditions — toggles from the filter sidebar that * hide a subset of rows without being a `filter` URL param (Postgres * connection lifecycle messages, and per-service traffic nested inside the * API Gateway `edge_logs` source). Shared by every query via `buildBaseWhere`, * so the row list, chart and sidebar facet counts stay in sync (otherwise the * badges over-count by the rows the list hides). */ /** Trimmed value of the cross-cutting user filter, or '' when inactive. */ const userFilterValue = (search: QuerySearchParamsType): string => typeof search.user === 'string' ? search.user.trim() : '' /** * Matches structured user identifiers in Auth events and API Gateway JWT subjects. * Sources without these fields cannot match the user filter. */ const userAttributionCondition = (search: QuerySearchParamsType): SafeLogSqlFragment | null => { const value = userFilterValue(search) if (!value) return null const exact = lit(value) return safeSql`( (source = 'auth_logs' AND log_attributes['auth_event.actor_id'] = ${exact}) OR (source = 'edge_logs' AND log_attributes['request.sb.jwt.authorization.payload.subject'] = ${exact}) )` } const USER_ATTRIBUTABLE_SOURCES = new Set([LOG_TYPE_TO_SOURCE.auth, LOG_TYPE_TO_SOURCE.edge]) /** * True when the user filter is active but an explicit log_type filter restricts the * view to source(s) that can never satisfy `userAttributionCondition` (e.g. `postgres`) — * the combination is guaranteed to match zero rows. Consumed by the UI to show a * specific empty state instead of the generic "No results found". * */ export const isUserFilterUnreachable = (search: QuerySearchParamsType): boolean => { if (!userFilterValue(search)) return false const logTypeFilter = groupLogsFiltersByColumn(parseLogsFilterUrlParams(search.filter)).log_type if (!logTypeFilter) return false const sources = logTypeFilter.values.map( (v) => LOG_TYPE_TO_SOURCE[v as keyof typeof LOG_TYPE_TO_SOURCE] ?? v ) if (logTypeFilter.operator === '<>') { // Excludes these sources from view — unreachable only if both attributable // sources are excluded (excluding just one still leaves the other eligible). return [...USER_ATTRIBUTABLE_SOURCES].every((source) => sources.includes(source)) } // Restricts the view to these sources — unreachable unless at least one is attributable. return !sources.some((source) => USER_ATTRIBUTABLE_SOURCES.has(source)) } const applySearchParamsFilter = (search: QuerySearchParamsType): SafeLogSqlFragment | null => { const conditions: SafeLogSqlFragment[] = [] const userCondition = userAttributionCondition(search) if (userCondition) conditions.push(userCondition) // Visible by default — only an explicit `false` hides connection logs. if (search.show_connection_logs === false) { conditions.push(safeSql`(source != 'postgres_logs' OR ( event_message NOT LIKE 'connection received%' AND event_message NOT LIKE 'connection authenticated%' AND event_message NOT LIKE 'connection authorized%' ))`) } // Visible by default — only an explicit `false` hides that service's // requests within the API Gateway log type. for (const key of ['edge_auth', 'edge_storage', 'edge_postgrest'] as const) { if (search[key] === false) { conditions.push( safeSql`(source != 'edge_logs' OR ${ATTR.path} NOT LIKE ${lit(EDGE_SERVICE_PATH_FILTER[key])})` ) } } if (conditions.length === 0) return null return safeSql`(${joinSqlFragments(conditions, ' AND ')})` } /** * Unified logs row query — flat SELECT, no subquery wrapper. */ export const getUnifiedLogsQuery = ( search: QuerySearchParamsType, paginationFilter?: SafeLogSqlFragment ): SafeLogSqlFragment => { const conditions = buildBaseWhere(search) if (paginationFilter) conditions.push(paginationFilter) return safeSql`-- unified logs: row list SELECT ${ROW_PROJECTION} FROM logs ${whereClause(conditions)} ` } /** * Single-facet count query — a complete flat SELECT with GROUP BY. */ export const getFacetCountQuery = ({ search, facet, facetSearch, }: { search: QuerySearchParamsType facet: string facetSearch?: string }): SafeLogSqlFragment => { if (!(FACET_FIELDS as readonly string[]).includes(facet)) { throw new Error('Invalid unified logs facet') } const MAX_FACETS_QUANTITY = 20 const facetExpr: SafeLogSqlFragment = facet === 'log_type' ? LOG_TYPE_EXPR : facet === 'level' ? LEVEL_EXPR : facet === 'method' ? METHOD_EXPR : facet === 'status' ? STATUS_EXPR : facet === 'pathname' ? PATHNAME_EXPR : facet === 'pipeline_id' ? PIPELINE_ID_OTEL_SQL : safeSql`log_attributes[${lit(facet)}]` const conditions: SafeLogSqlFragment[] = [ ...buildBaseWhere(search, facet), safeSql`(${facetExpr}) IS NOT NULL AND (${facetExpr}) != ''`, ] if (facetSearch) { conditions.push(safeSql`(${facetExpr}) LIKE ${lit('%' + facetSearch + '%')}`) } return safeSql`-- unified logs: single-facet counts (${lit(facet)}) SELECT ${lit(facet)} AS facet, (${facetExpr}) AS value, count() AS count FROM logs ${whereClause(conditions)} GROUP BY value ORDER BY count DESC LIMIT ${lit(MAX_FACETS_QUANTITY)} ` } /** * Builds the facet-count query for the logs sidebar. Each row is * (facet, value, count): for one filter category (e.g. level) and one of its * values (e.g. warning), how many logs matched. The special `total` facet * counts every matching log for the count badge. */ export const getLogsCountQuery = (search: QuerySearchParamsType): SafeLogSqlFragment => { const grouped = groupLogsFiltersByColumn(parseLogsFilterUrlParams(search.filter)) const whereFor = (excludeField?: string): SafeLogSqlFragment => { const conditions = buildBaseWhere(search, excludeField) return conditions.length > 0 ? joinSqlFragments(conditions, ' AND ') : safeSql`1` } const VALUE_EXPR = { total: safeSql`'all'`, log_type: LOG_TYPE_EXPR, level: LEVEL_EXPR, method: METHOD_EXPR, status: STATUS_EXPR, pipeline_id: safeSql`if(source = 'etl_replication_logs', ${PIPELINE_ID_OTEL_SQL}, null)`, } const scanBlock = ( facets: (keyof typeof VALUE_EXPR)[], where: SafeLogSqlFragment ): SafeLogSqlFragment => { const facetArray = joinSqlFragments( facets.map((facet) => lit(facet)), ',' ) const branches = facets.map((facet) => safeSql`facet = ${lit(facet)}, ${VALUE_EXPR[facet]}`) return safeSql` SELECT arrayJoin([${facetArray}]) AS facet, multiIf(${joinSqlFragments([...branches, safeSql`''`], ', ')}) AS value, count() AS count FROM logs WHERE ${where} GROUP BY facet, value HAVING value != '' ` } // log_type always scans alone: excluding it also drops the default-types // filter, so its counts differ from the base scan even when unfiltered. const blocks = [scanBlock(['log_type'], whereFor('log_type'))] // A filtered facet gets its own scan so it can exclude its own filter and // still count its other values; the rest share the base scan. const baseFacets: (keyof typeof VALUE_EXPR)[] = ['total'] for (const facet of ['level', 'method', 'status', 'pipeline_id'] as const) { if (grouped[facet]) blocks.push(scanBlock([facet], whereFor(facet))) else baseFacets.push(facet) } blocks.push(scanBlock(baseFacets, whereFor())) return safeSql`-- unified logs: sidebar facet counts ${joinSqlFragments(blocks, ' UNION ALL ')}` } /** * Logs chart query with dynamic bucketing based on time range. */ export const getLogsChartQuery = (search: QuerySearchParamsType): SafeLogSqlFragment => { const truncationLevel = calculateChartBucketing(search) const truncFn = truncationFunction(truncationLevel) const conditions = buildBaseWhere(search) return safeSql`-- unified logs: severity chart (${truncFn} buckets) SELECT ${truncFn}(timestamp) AS time_bucket, countIf((${LEVEL_EXPR}) = 'success') AS success, countIf((${LEVEL_EXPR}) = 'warning') AS warning, countIf((${LEVEL_EXPR}) = 'error') AS error, count() AS total_per_bucket FROM logs ${whereClause(conditions)} GROUP BY time_bucket ORDER BY time_bucket ASC ` } export const REQUEST_CORRELATION_KEYS = { requestId: { edge_logs: ['request.headers.cf_ray', 'response.headers.cf_ray'], auth_logs: ['request_id'], storage_logs: ['req.headers.cf_ray'], function_edge_logs: ['request.headers.cf_ray'], }, executionId: { function_edge_logs: ['execution_id'], function_logs: ['execution_id'], }, nativeRequestId: Object.fromEntries( Object.values(LOG_TYPE_TO_SOURCE).map((source) => [source, ['request_id']]) ), traceId: Object.fromEntries( Object.values(LOG_TYPE_TO_SOURCE).map((source) => [source, ['trace_id']]) ), } as const satisfies Record> export type RequestCorrelationIds = { requestIds: string[] executionIds: string[] nativeRequestIds: string[] traceIds: string[] } export const REQUEST_TIMELINE_LIMIT = 200 const CORRELATION_ID_PATTERN = /^[0-9A-Za-z-]{1,64}$/ const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i const TRACE_ID_PATTERN = /^[0-9a-f]{32}$/i const ZERO_ID_PATTERN = /^0+(?:-0+)*$/ export const getRequestCorrelationIds = ( logs: { source: string; attributes: Record | null | undefined }[] ): RequestCorrelationIds => { const collect = ( keysBySource: Record, pattern = CORRELATION_ID_PATTERN, isLegacyRequest = false ) => { const ids = new Set() for (const { source, attributes } of logs) { for (const key of keysBySource[source] ?? []) { const value = attributes?.[key] if (typeof value !== 'string' || !pattern.test(value) || ZERO_ID_PATTERN.test(value)) { continue } if (isLegacyRequest && UUID_PATTERN.test(value)) continue ids.add(value) } } return [...ids].sort() } return { requestIds: collect(REQUEST_CORRELATION_KEYS.requestId, CORRELATION_ID_PATTERN, true), executionIds: collect(REQUEST_CORRELATION_KEYS.executionId), nativeRequestIds: collect(REQUEST_CORRELATION_KEYS.nativeRequestId, UUID_PATTERN), traceIds: collect(REQUEST_CORRELATION_KEYS.traceId, TRACE_ID_PATTERN), } } const correlationConditions = ( keysBySource: Record, ids: string[] ): SafeLogSqlFragment[] => { if (ids.length === 0) return [] const idList = joinSqlFragments( ids.map((id) => lit(id)), ',' ) return Object.entries(keysBySource).map(([source, keys]) => { const matches = keys.map((key) => safeSql`log_attributes[${lit(key)}] IN (${idList})`) return safeSql`(source = ${lit(source)} AND (${joinSqlFragments(matches, ' OR ')}))` }) } export const getLogAttributesQuery = ({ logId, source, }: { logId: string source: string }): SafeLogSqlFragment => safeSql` SELECT source, log_attributes FROM logs WHERE id = ${lit(logId)} AND source = ${lit(source)} LIMIT 1 ` export const getRequestTimelineQuery = ({ requestIds, executionIds, nativeRequestIds = [], traceIds = [], }: Pick & Partial>): SafeLogSqlFragment => { const conditions = [ ...correlationConditions(REQUEST_CORRELATION_KEYS.requestId, requestIds), ...correlationConditions(REQUEST_CORRELATION_KEYS.executionId, executionIds), ...correlationConditions(REQUEST_CORRELATION_KEYS.nativeRequestId, nativeRequestIds), ...correlationConditions(REQUEST_CORRELATION_KEYS.traceId, traceIds), ] if (conditions.length === 0) throw new Error('A request or execution ID is required') return safeSql` SELECT id, timestamp, source, ${LOG_TYPE_EXPR} AS log_type, ${STATUS_EXPR} AS status, ${LEVEL_EXPR} AS level, ${PATHNAME_EXPR} AS pathname, event_message, ${METHOD_EXPR} AS method, ${AUTH_USER_EXPR} AS auth_user, log_attributes AS metadata, null AS log_count, null AS logs FROM logs WHERE ${joinSqlFragments(conditions, ' OR ')} ORDER BY timestamp ASC, id ASC LIMIT ${lit(REQUEST_TIMELINE_LIMIT)} ` }