Files
supabase/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts
Jordi EnricandClaude Sonnet 4.6 9c572a56fd feat(logs): add realtime, supavisor, and pgbouncer to unified logs (#46786)
## Problem

The unified logs view was missing three log sources that the backend
already returns: Realtime (`realtime_logs`), Supavisor
(`supavisor_logs`), and PgBouncer (`pgbouncer_logs`). Users had no way
to filter or view logs from these services in the unified view.

## Fix

- Added `realtime`, `supavisor`, and `pgbouncer` to `LOG_TYPE_PREDICATE`
and `LOG_TYPE_EXPR` in the OTEL query builder so rows from these sources
are matched and labeled correctly.
- Added the three types to `LOG_TYPES` so filter chips appear in the UI.
- Added icons (`Realtime` from the icons package, `Cable` from
lucide-react for both pooler types) in `LogTypeIcon.tsx`.
- Added display labels in `formatServiceTypeForDisplay` (`Realtime`,
`Supavisor`, `PgBouncer`).
- Fixed a pre-existing unsafe cast in `ServiceFlowPanel.tsx` where any
log type not in the service flow allow-list (like the new types) would
produce a truthy `serviceFlowType` and trigger a runtime error on row
click. The fix checks against `SERVICE_FLOW_TYPES` before casting.

Note: `pg_cron_logs` is not included because the backend otel query does
not yet return that source.

## How to test

1. Open unified logs for a project that has Realtime activity.
2. In the log type filter, confirm `realtime`, `supavisor`, and
`pgbouncer` chips are visible.
3. Toggle on `realtime` and confirm Realtime logs appear with the
correct icon.
4. Click a realtime log row and confirm the detail panel opens on the
raw JSON tab without a runtime error.
5. Toggle on `supavisor` or `pgbouncer` and confirm pooler logs appear
if the project has connection pooler activity.

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Added support for three new log types — Realtime, Supavisor, and
PgBouncer — in Unified Logs with display labels, icons, and
filtering/viewing support.

* **Bug Fixes / UI Behavior**
* Service Flow “Overview” tab now only shows when the service type is
recognized, preventing irrelevant overview content for unsupported log
sources.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 18:46:37 +02:00

137 lines
4.6 KiB
TypeScript

import { type Table as TTable } from '@tanstack/react-table'
import { cn } from 'ui'
import { FacetMetadataSchema } from './UnifiedLogs.schema'
import { LEVELS } from '@/components/ui/DataTable/DataTable.constants'
export const getFacetedUniqueValues = <TData>(facets?: Record<string, FacetMetadataSchema>) => {
return (_table: TTable<TData>, columnId: string) => {
return new Map(facets?.[columnId]?.rows?.map(({ value, total }) => [value, total]) || [])
}
}
export const getFacetedMinMaxValues = <TData>(facets?: Record<string, FacetMetadataSchema>) => {
return (_table: TTable<TData>, columnId: string) => {
const min = facets?.[columnId]?.min
const max = facets?.[columnId]?.max
if (typeof min === 'number' && typeof max === 'number') return [min, max]
if (typeof min === 'number') return [min, min]
if (typeof max === 'number') return [max, max]
return undefined
}
}
/**
* Returns a unified-logs row's timestamp in epoch milliseconds.
*
* The row mapper attaches a pre-parsed `date` (works for both BigQuery
* microsecond timestamps and OTEL ISO strings); fall back to the raw
* `timestamp` value when it's a number (older BQ-style microseconds).
*/
export function getRowTimestampMs(
row: { date?: Date | null; timestamp?: number | string | null } | null | undefined
): number | null {
if (row?.date instanceof Date) return row.date.getTime()
if (typeof row?.timestamp === 'number') return row.timestamp / 1000
return null
}
export const getLevelLabel = (value: (typeof LEVELS)[number]): string => {
switch (value) {
case 'success':
return '2xx'
case 'warning':
return '4xx'
case 'error':
return '5xx'
}
}
// Helper function to determine level from HTTP status code
export const getStatusLevel = (status?: number | string): string => {
if (!status) return 'success'
const statusNum = Number(status)
if (statusNum >= 500) return 'error'
if (statusNum >= 400) return 'warning'
if (statusNum >= 300) return 'info' // 3xx redirects are informational
if (statusNum >= 200) return 'success'
if (statusNum >= 100) return 'info'
return 'success'
}
export function getLevelRowClassName(value: (typeof LEVELS)[number]): string {
switch (value) {
case 'success':
return ''
case 'warning':
return cn(
'bg-warning/5 hover:bg-warning/10',
'data-[state=selected]:bg-warning/20 focus-visible:bg-warning/10',
'dark:bg-warning/10 dark:hover:bg-warning/20 dark:data-[state=selected]:bg-warning/30 dark:focus-visible:bg-warning/20'
)
case 'error':
return cn(
'bg-destructive/5 hover:bg-destructive/10',
'data-[state=selected]:bg-destructive/20 focus-visible:bg-destructive/10',
'dark:bg-error/10 dark:hover:bg-destructive/20 dark:data-[state=selected]:bg-destructive/30 dark:focus-visible:bg-destructive/20'
)
default:
return ''
}
}
/**
* Formats service type strings for display purposes
* Handles special cases like "edge function" -> "Edge Function"
* and applies proper capitalization to other service types
*/
export function formatServiceTypeForDisplay(serviceType: string): string {
if (!serviceType) return ''
// Handle special cases
const specialCases: Record<string, string> = {
'edge function': 'Edge Function',
postgrest: 'PostgREST',
postgres: 'Postgres',
auth: 'Auth',
storage: 'Storage',
realtime: 'Realtime',
supavisor: 'Supavisor',
pgbouncer: 'PgBouncer',
}
return specialCases[serviceType.toLowerCase()] || serviceType
}
/**
* Parses an auth log event_message that may be a stringified JSON object.
* Auth log entries store metadata as JSON in event_message (e.g. {"msg":"...","level":"info"}).
* Extracts the human-readable msg field, falling back to error, then the raw string.
* The fallback ensures self-hosted versions with different formats still render correctly.
*/
export function parseAuthLogEventMessage(value: string | undefined): string | undefined {
if (!value) return value
try {
const parsed = JSON.parse(value)
if (parsed && typeof parsed === 'object') {
const err = parsed.error || parsed.error_code
if (typeof err === 'string' && err.trim()) {
return !/^\d{3}:/.test(err) ? err.replaceAll('_', ' ') : err
}
const msg = parsed.msg
if (typeof msg === 'string' && msg.trim()) {
const action = parsed.action ?? parsed.auth_event?.action
const authEvent = typeof action === 'string' ? action.replaceAll('_', ' ') : undefined
return `${authEvent ? `${authEvent}: ` : ''}${msg}`
}
}
return value
} catch (error) {
return value
}
}