The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
Feat/unified logs inspection panel (#36895)
Jonathan Summers-Muir1e3b5063bbc3
diff --git a/apps/studio/components/interfaces/UnifiedLogs/Queries/ServiceFlowQueries/ServiceFlow.sql.ts b/apps/studio/components/interfaces/UnifiedLogs/Queries/ServiceFlowQueries/ServiceFlow.sql.tsnew file mode 100644index 00000000000..cd0690b022f--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/Queries/ServiceFlowQueries/ServiceFlow.sql.ts@@ -0,0 +1,398 @@+/**+ * Service Flow SQL Queries+ *+ * This file contains SQL queries for fetching enriched service flow data+ * showing how requests flow through different layers of the infrastructure.+ */++// Service configuration for different log types+const SERVICE_CONFIGS = {+ postgrest: {+ pathFilter: '%/rest/%',+ },+ auth: {+ pathFilter: '%/auth/%',+ },+ 'edge-function': {+ pathFilter: '%/functions/%',+ },+ storage: {+ pathFilter: '%/storage/%',+ },+} as const++type EdgeServiceType = keyof typeof SERVICE_CONFIGS++/**+ * Base Edge Logs Service Flow Query+ * Consolidated query for all edge-based services (postgrest, auth, edge-function, storage)+ * to eliminate 500+ lines of SQL duplication+ */+const getBaseEdgeServiceFlowQuery = (logId: string, serviceType: EdgeServiceType): string => {+ const config = SERVICE_CONFIGS[serviceType]++ return `+ select+ id,+ el.timestamp as timestamp,+ '${serviceType}' as log_type,+ CAST(edge_logs_response.status_code AS STRING) as status,+ CASE+ WHEN edge_logs_response.status_code BETWEEN 200 AND 299 THEN 'success'+ WHEN edge_logs_response.status_code BETWEEN 400 AND 499 THEN 'warning'+ WHEN edge_logs_response.status_code >= 500 THEN 'error'+ ELSE 'success'+ END as level,++ -- Request data+ edge_logs_request.path as request_path,+ edge_logs_request.host as request_host,+ edge_logs_request.method as request_method,+ edge_logs_request.url as request_url,+ edge_logs_request.search as request_search,++ -- Response data+ edge_logs_response.origin_time as response_origin_time,+ edge_logs_response_headers.content_type as response_content_type,+ edge_logs_response_headers.cf_cache_status as response_cache_status,++ -- Client location data+ edge_logs_cf.continent as client_continent,+ edge_logs_cf.country as client_country,+ edge_logs_cf.city as client_city,+ edge_logs_cf.region as client_region,+ edge_logs_cf.regionCode as client_region_code,+ edge_logs_cf.latitude as client_latitude,+ edge_logs_cf.longitude as client_longitude,+ edge_logs_cf.timezone as client_timezone,++ -- Network data+ edge_logs_cf.httpProtocol as network_protocol,+ edge_logs_cf.colo as network_datacenter,++ -- Request headers+ edge_logs_request_headers.user_agent as headers_user_agent,+ edge_logs_request_headers.x_client_info as headers_x_client_info,+ edge_logs_request_headers.x_forwarded_proto as headers_x_forwarded_proto,+ edge_logs_request_headers.x_real_ip as headers_x_real_ip,+ edge_logs_request_headers.referer as headers_referer,++ -- Auth data+ authorization_payload.role as api_role,+ COALESCE(sb.auth_user, null) as auth_user,++ -- JWT Key Authentication (old keys)+ CASE+ WHEN apikey_payload.algorithm = 'HS256' AND+ apikey_payload.issuer = 'supabase' AND+ apikey_payload.role IN ('anon', 'service_role')+ THEN apikey_payload.role+ WHEN sb_apikey.invalid IS NOT NULL THEN '<invalid>'+ WHEN apikey_payload IS NOT NULL THEN '<unrecognized>'+ ELSE NULL+ END as jwt_key_role,++ apikey_payload.signature_prefix as jwt_key_prefix,++ -- API Key Authentication (new keys from sb.apikey[0].apikey[0])+ CASE+ WHEN sb_apikey_inner.prefix LIKE '%publishable%' THEN 'anon'+ WHEN sb_apikey_inner.prefix LIKE '%secret%' THEN 'service_role'+ WHEN sb_apikey_inner.prefix IS NOT NULL THEN 'unknown'+ ELSE NULL+ END as api_key_role,++ sb_apikey_inner.prefix as api_key_prefix,+ sb_apikey_inner.error as api_key_error,+ sb_apikey_inner.hash as api_key_hash,++ -- User Authorization+ authorization_payload.role as authorization_role,+ null as user_id,+ null as user_email,++ -- Cloudflare Network Info+ edge_logs_response_headers.cf_ray as cf_ray,+ edge_logs_request_headers.cf_ipcountry as cf_country,+ edge_logs_cf.colo as cf_datacenter,+ edge_logs_request_headers.cf_connecting_ip as client_ip,++ -- JWT data+ apikey_payload.role as jwt_apikey_role,+ apikey_payload.algorithm as jwt_apikey_algorithm,+ null as jwt_apikey_expires_at,+ apikey_payload.issuer as jwt_apikey_issuer,+ null as jwt_apikey_signature_prefix,+ null as jwt_apikey_key_id,+ null as jwt_apikey_session_id,+ null as jwt_apikey_subject,++ authorization_payload.role as jwt_auth_role,+ authorization_payload.algorithm as jwt_auth_algorithm,+ null as jwt_auth_expires_at,+ authorization_payload.issuer as jwt_auth_issuer,+ null as jwt_auth_signature_prefix,+ null as jwt_auth_key_id,+ null as jwt_auth_session_id,+ null as jwt_auth_subject,++ -- Storage specific data (included for all but only populated for storage)+ edge_logs_response_headers.sb_gateway_mode as storage_edge_gateway_mode,+ edge_logs_response_headers.sb_gateway_version as storage_edge_gateway_version,+ edge_logs_response_headers.cf_ray as correlation_cf_ray,++ -- Raw data+ el as raw_log_data++ from edge_logs as el+ cross join unnest(metadata) as edge_logs_metadata+ cross join unnest(edge_logs_metadata.request) as edge_logs_request+ cross join unnest(edge_logs_metadata.response) as edge_logs_response+ left join unnest(edge_logs_response.headers) as edge_logs_response_headers+ left join unnest(edge_logs_request.headers) as edge_logs_request_headers+ left join unnest(edge_logs_request.cf) as edge_logs_cf+ left join unnest(edge_logs_request.sb) as sb+ left join unnest(sb.jwt) as jwt+ left join unnest(jwt.apikey) as sb_apikey+ left join unnest(sb_apikey.payload) as apikey_payload+ left join unnest(jwt.authorization) as auth+ left join unnest(auth.payload) as authorization_payload+ left join unnest(sb.apikey) as sb_apikey_outer+ left join unnest(sb_apikey_outer.apikey) as sb_apikey_inner++WHERE+ el.id = '${logId}'+`+}++/**+ * PostgREST Service Flow Query for /rest/ requests+ * Fetches enriched edge log data for PostgREST requests with additional service-specific metadata+ */+export const getPostgrestServiceFlowQuery = (logId: string): string => {+ return getBaseEdgeServiceFlowQuery(logId, 'postgrest')+}++/**+ * Auth Service Flow Query for /auth/ requests+ * Fetches enriched edge log data for GoTrue auth requests with service-specific metadata+ */+export const getAuthServiceFlowQuery = (logId: string): string => {+ return getBaseEdgeServiceFlowQuery(logId, 'auth')+}++/**+ * Edge Function Service Flow Query for /functions/ requests+ * Fetches enriched edge log data for Edge Function requests with service-specific metadata+ * NOTE: Uses function_edge_logs table instead of edge_logs, so kept separate like postgres+ */+export const getEdgeFunctionServiceFlowQuery = (logId: string): string => {+ return `+ select+ fel.id as id,+ fel.timestamp as timestamp,+ 'edge-function' as log_type,+ CAST(fel_response.status_code AS STRING) as status,+ CASE+ WHEN fel_response.status_code BETWEEN 200 AND 299 THEN 'success'+ WHEN fel_response.status_code BETWEEN 400 AND 499 THEN 'warning'+ WHEN fel_response.status_code >= 500 THEN 'error'+ ELSE 'success'+ END as level,++ -- Request data+ fel_request.pathname as request_path,+ fel_request.host as request_host,+ fel_request.method as request_method,+ fel_request.url as request_url,+ fel_request.search as request_search,+ fel_request.protocol as request_protocol,+ fel_request.port as request_port,++ -- Response data (no origin_time in function_edge_logs)+ fel_response_headers.content_type as response_content_type,+ fel_response_headers.content_length as response_content_length,+ fel_response_headers.date as response_date,+ fel_response_headers.server as response_server,+ fel_response_headers.x_sb_edge_region as response_edge_region,+ fel_response_headers.x_sb_compute_multiplier as response_compute_multiplier,+ fel_response_headers.x_sb_resource_multiplier as response_resource_multiplier,+ fel_response_headers.x_served_by as response_served_by,++ -- Function specific data+ fel_metadata.execution_id as execution_id,+ fel_metadata.function_id as function_id,+ fel_metadata.deployment_id as deployment_id,+ fel_metadata.execution_time_ms as execution_time_ms,+ fel_metadata.project_ref as project_ref,+ fel_metadata.version as function_version,++ -- Request headers+ fel_request_headers.user_agent as headers_user_agent,+ fel_request_headers.x_client_info as headers_x_client_info,+ fel_request_headers.accept as headers_accept,+ fel_request_headers.accept_encoding as headers_accept_encoding,+ fel_request_headers.connection as headers_connection,+ fel_request_headers.cookie as headers_cookie,+ fel_request_headers.host as headers_host,++ -- Auth data+ authorization_payload.role as api_role,+ COALESCE(sb.auth_user, null) as auth_user,++ -- JWT Key Authentication (old keys)+ CASE+ WHEN apikey_payload.algorithm = 'HS256' AND+ apikey_payload.issuer = 'supabase' AND+ apikey_payload.role IN ('anon', 'service_role')+ THEN apikey_payload.role+ WHEN sb_apikey.invalid IS NOT NULL THEN '<invalid>'+ WHEN apikey_payload IS NOT NULL THEN '<unrecognized>'+ ELSE NULL+ END as jwt_key_role,++ apikey_payload.signature_prefix as jwt_key_prefix,++ -- API Key Authentication (new keys from sb.apikey[0].apikey[0])+ CASE+ WHEN sb_apikey_inner.prefix LIKE '%publishable%' THEN 'anon'+ WHEN sb_apikey_inner.prefix LIKE '%secret%' THEN 'service_role'+ WHEN sb_apikey_inner.prefix IS NOT NULL THEN 'unknown'+ ELSE NULL+ END as api_key_role,++ sb_apikey_inner.prefix as api_key_prefix,+ sb_apikey_inner.error as api_key_error,+ sb_apikey_inner.hash as api_key_hash,++ -- User Authorization+ authorization_payload.role as authorization_role,+ null as user_id,+ null as user_email,++ -- JWT data+ apikey_payload.role as jwt_apikey_role,+ apikey_payload.algorithm as jwt_apikey_algorithm,+ null as jwt_apikey_expires_at,+ apikey_payload.issuer as jwt_apikey_issuer,+ null as jwt_apikey_signature_prefix,+ null as jwt_apikey_key_id,+ null as jwt_apikey_session_id,+ null as jwt_apikey_subject,++ authorization_payload.role as jwt_auth_role,+ authorization_payload.algorithm as jwt_auth_algorithm,+ null as jwt_auth_expires_at,+ authorization_payload.issuer as jwt_auth_issuer,+ null as jwt_auth_signature_prefix,+ null as jwt_auth_key_id,+ null as jwt_auth_session_id,+ null as jwt_auth_subject,++ -- Function logs aggregation+ function_logs_agg.function_log_count as function_log_count,+ function_logs_agg.logs as function_logs,+ function_logs_agg.last_event_message as last_event_message,++ -- Raw data+ fel as raw_log_data++ from function_edge_logs as fel+ cross join unnest(metadata) as fel_metadata+ cross join unnest(fel_metadata.response) as fel_response+ cross join unnest(fel_metadata.request) as fel_request+ left join unnest(fel_response.headers) as fel_response_headers+ left join unnest(fel_request.headers) as fel_request_headers+ left join unnest(fel_request.sb) as sb+ left join unnest(sb.jwt) as jwt+ left join unnest(jwt.apikey) as sb_apikey+ left join unnest(sb_apikey.payload) as apikey_payload+ left join unnest(jwt.authorization) as auth+ left join unnest(auth.payload) as authorization_payload+ left join unnest(sb.apikey) as sb_apikey_outer+ left join unnest(sb_apikey_outer.apikey) as sb_apikey_inner+ left join (+ SELECT+ fl_metadata.execution_id,+ COUNT(fl.id) as function_log_count,+ ANY_VALUE(fl.event_message) as last_event_message,+ ARRAY_AGG(STRUCT(fl.id, fl.timestamp, fl.event_message, fl_metadata.level, fl_metadata.event_type)) as logs+ FROM function_logs as fl+ CROSS JOIN UNNEST(fl.metadata) as fl_metadata+ WHERE fl_metadata.execution_id IS NOT NULL+ GROUP BY fl_metadata.execution_id+ ) as function_logs_agg on fel_metadata.execution_id = function_logs_agg.execution_id++WHERE+ fel.id = '${logId}'+`+}++/**+ * Storage Service Flow Query for /storage/ requests+ * Fetches enriched edge log data for Storage requests with service-specific metadata+ */+export const getStorageServiceFlowQuery = (logId: string): string => {+ return getBaseEdgeServiceFlowQuery(logId, 'storage')+}++/**+ * Postgres Service Flow Query for database operations+ * Fetches enriched postgres log data with database-specific metadata+ *+ * This handles direct database operations, connections, and queries+ * NOTE: Uses postgres_logs table instead of edge_logs, so kept separate+ */+export const getPostgresServiceFlowQuery = (logId: string): string => {+ return `+ select+ pgl.id as id,+ pgl.timestamp as timestamp,+ 'postgres' as log_type,+ pgl_parsed.sql_state_code as status,+ CASE+ WHEN pgl_parsed.error_severity = 'LOG' THEN 'success'+ WHEN pgl_parsed.error_severity = 'WARNING' THEN 'warning'+ WHEN pgl_parsed.error_severity = 'FATAL' THEN 'error'+ WHEN pgl_parsed.error_severity = 'ERROR' THEN 'error'+ ELSE 'success'+ END as level,++ -- Database connection details+ pgl_parsed.database_name as database_name,+ pgl_parsed.user_name as database_user,+ pgl_parsed.connection_from as connection_from,+ pgl_metadata.host as database_host,++ -- Query/Operation details+ pgl_parsed.command_tag as command_tag,+ pgl_parsed.backend_type as backend_type,+ pgl_parsed.query_id as query_id,++ -- Session details+ pgl_parsed.session_id as session_id,+ pgl_parsed.process_id as process_id,+ pgl_parsed.virtual_transaction_id as virtual_transaction_id,+ pgl_parsed.transaction_id as transaction_id,+ pgl_parsed.session_start_time as session_start_time,+ pgl_parsed.session_line_num as session_line_num,++ -- Error/Status details+ pgl_parsed.error_severity as error_severity,+ pgl_parsed.sql_state_code as sql_state_code,+ pgl.event_message as event_message,++ -- Timing+ pgl_parsed.timestamp as operation_timestamp,++ -- Raw data+ pgl as raw_log_data++ from postgres_logs as pgl+ cross join unnest(pgl.metadata) as pgl_metadata+ cross join unnest(pgl_metadata.parsed) as pgl_parsed++WHERE+ pgl.id = '${logId}'+`+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceBlocks.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceBlocks.tsxnew file mode 100644index 00000000000..d4971cc420c--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceBlocks.tsx@@ -0,0 +1,39 @@+import {+ authBlockConfig,+ edgeFunctionBlockConfig,+ networkBlockConfig,+ postgresBlockConfig,+ postgrestBlockConfig,+ storageBlockConfig,+} from '../config/blockConfigs'+import { createBlock } from './shared/Block'++// Generate all block components+const MemoizedGoTrueBlock = createBlock(authBlockConfig)++const MemoizedPostgRESTBlock = createBlock(postgrestBlockConfig)++const MemoizedNetworkBlock = createBlock(networkBlockConfig)++const MemoizedEdgeFunctionBlock = createBlock(edgeFunctionBlockConfig)++const MemoizedStorageBlock = createBlock(storageBlockConfig)++const MemoizedPostgresBlock = createBlock(postgresBlockConfig)++// Set display names for debugging+MemoizedGoTrueBlock.displayName = 'MemoizedGoTrueBlock'+MemoizedPostgRESTBlock.displayName = 'MemoizedPostgRESTBlock'+MemoizedNetworkBlock.displayName = 'MemoizedNetworkBlock'+MemoizedEdgeFunctionBlock.displayName = 'MemoizedEdgeFunctionBlock'+MemoizedStorageBlock.displayName = 'MemoizedStorageBlock'+MemoizedPostgresBlock.displayName = 'MemoizedPostgresBlock'++export {+ MemoizedEdgeFunctionBlock,+ MemoizedGoTrueBlock,+ MemoizedNetworkBlock,+ MemoizedPostgresBlock,+ MemoizedPostgRESTBlock,+ MemoizedStorageBlock,+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceFlowHeader.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceFlowHeader.tsxnew file mode 100644index 00000000000..5f1c10d2774--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/ServiceFlowHeader.tsx@@ -0,0 +1,172 @@+import { ChevronDown, ChevronUp, X } from 'lucide-react'+import { useCallback, useMemo, useEffect } from 'react'+import { useDataTable } from 'components/ui/DataTable/providers/DataTableProvider'+import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'+import { LogTypeIcon } from '../../components/LogTypeIcon'+import { getStatusLevel } from '../../UnifiedLogs.utils'+import { TruncatedTextWithPopover } from './shared/TruncatedTextWithPopover'+import { Badge, Button, Separator } from 'ui'+import { ButtonTooltip } from 'components/ui/ButtonTooltip'+import { Kbd } from 'components/ui/DataTable/primitives/Kbd'+import { ColumnSchema } from '../../UnifiedLogs.schema'++interface ServiceFlowHeaderProps {+ selectedRow: ColumnSchema+ enrichedData?: Record<string, any>+}++export const ServiceFlowHeader = ({ selectedRow, enrichedData }: ServiceFlowHeaderProps) => {+ const { table, rowSelection, isLoading } = useDataTable()++ const method = selectedRow?.method+ const logType = selectedRow?.log_type+ const status = selectedRow?.status++ // Display logic: path → event_message → grayed out "/"+ const displayPath = useMemo(() => {+ const actualPath = enrichedData?.request_path || selectedRow?.pathname+ if (actualPath && actualPath !== '/') {+ return { text: actualPath, isDefault: false, isTruncatable: false }+ }++ const eventMessage = enrichedData?.event_message || selectedRow?.event_message+ if (eventMessage) {+ return { text: eventMessage, isDefault: false, isTruncatable: true }+ }++ return { text: '/', isDefault: true, isTruncatable: false }+ }, [enrichedData, selectedRow])++ // Navigation logic (same as DataTableSheetDetails)+ const selectedRowKey = Object.keys(rowSelection)?.[0]++ const selectedRowData = useMemo(() => {+ if (isLoading && !selectedRowKey) return+ return table.getCoreRowModel().flatRows.find((row) => row.id === selectedRowKey)+ }, [selectedRowKey, isLoading, table])++ const index = table.getCoreRowModel().flatRows.findIndex((row) => row.id === selectedRowData?.id)+ // Get the ID of the next row in the table for navigation+ const nextId = useMemo(+ () => table.getCoreRowModel().flatRows[index + 1]?.id,+ [index, isLoading, table]+ )++ // Get the ID of the previous row in the table for navigation+ const prevId = useMemo(+ () => table.getCoreRowModel().flatRows[index - 1]?.id,+ [index, isLoading, table]+ )++ // Navigate to the previous row when called+ const onPrev = useCallback(() => {+ if (prevId) table.setRowSelection({ [prevId]: true })+ }, [prevId, table])++ // Navigate to the next row when called+ const onNext = useCallback(() => {+ if (nextId) table.setRowSelection({ [nextId]: true })+ }, [nextId, table])++ // Close the current row selection+ const onClose = useCallback(() => {+ table.resetRowSelection()+ }, [table])++ useEffect(() => {+ const down = (e: KeyboardEvent) => {+ if (!selectedRowKey) return++ // REMINDER: prevent dropdown navigation inside of sheet to change row selection+ const activeElement = document.activeElement+ const isMenuActive = activeElement?.closest('[role="menu"]')++ if (isMenuActive) return++ if (e.key === 'ArrowUp') {+ e.preventDefault()+ onPrev()+ }+ if (e.key === 'ArrowDown') {+ e.preventDefault()+ onNext()+ }+ }++ document.addEventListener('keydown', down)+ return () => document.removeEventListener('keydown', down)+ }, [selectedRowKey, onNext, onPrev])++ return (+ <div className="flex items-center justify-between px-4 py-3">+ <div className="flex items-center gap-3 min-w-0 flex-1 mr-6">+ {logType && <LogTypeIcon type={logType} size={16} className="text-foreground/70" />}+ {method && (+ <Badge variant="default" className="font-mono text-xs rounded px-1">+ {method}+ </Badge>+ )}+ {displayPath.isTruncatable ? (+ <TruncatedTextWithPopover+ text={displayPath.text}+ maxLength={60}+ className={`font-mono text-sm truncate ${displayPath.isDefault ? 'text-foreground-muted' : 'text-foreground'}`}+ />+ ) : (+ <span+ className={`font-mono text-sm truncate ${displayPath.isDefault ? 'text-foreground-muted' : 'text-foreground'}`}+ >+ {displayPath.text}+ </span>+ )}+ </div>++ <div className="flex h-7 items-center gap-1">+ {status && (+ <DataTableColumnStatusCode+ value={status}+ level={getStatusLevel(status)}+ className="text-xs"+ />+ )}+ <ButtonTooltip+ size="tiny"+ type="text"+ disabled={!prevId}+ onClick={onPrev}+ className="px-1"+ icon={<ChevronUp />}+ tooltip={{+ content: {+ text: (+ <p>+ Navigate <Kbd>↑</Kbd>+ </p>+ ),+ },+ }}+ />+ <ButtonTooltip+ size="tiny"+ type="text"+ disabled={!nextId}+ onClick={onNext}+ className="px-1"+ icon={<ChevronDown />}+ tooltip={{+ content: {+ text: (+ <p>+ Navigate <Kbd>↓</Kbd>+ </p>+ ),+ },+ }}+ />+ <Separator orientation="vertical" className="mx-1" />++ <Button size="tiny" type="text" onClick={onClose} className="px-1" icon={<X />} />+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/blocks/RequestStartedBlock.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/blocks/RequestStartedBlock.tsxnew file mode 100644index 00000000000..44645b716fe--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/blocks/RequestStartedBlock.tsx@@ -0,0 +1,32 @@+import { Clock } from 'lucide-react'+import { memo } from 'react'+import { ColumnSchema } from '../../../UnifiedLogs.schema'+import { StyledIcon } from '../shared/TimelineStep'++// Request Started - Simple header component with connecting line+export const MemoizedRequestStartedBlock = memo(function RequestStartedBlock({+ data,+}: {+ data: ColumnSchema+}) {+ const timestamp = data?.timestamp || data?.date+ const formattedTime = timestamp ? new Date(timestamp).toLocaleString() : null++ return (+ <div>+ <div className="flex items-center justify-between py-0 px-2">+ <div className="flex items-center gap-2 text-sm text-foreground-light">+ <StyledIcon icon={Clock} title="Request started" />+ <span>Request started</span>+ </div>+ {formattedTime && (+ <span className="text-sm font-mono text-foreground-light">{formattedTime}</span>+ )}+ </div>+ {/* Connecting line to first timeline block */}+ <div className="border-l h-4 ml-5"></div>+ </div>+ )+})++MemoizedRequestStartedBlock.displayName = 'MemoizedRequestStartedBlock'diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/blocks/ResponseCompletedBlock.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/blocks/ResponseCompletedBlock.tsxnew file mode 100644index 00000000000..71898c18f1c--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/blocks/ResponseCompletedBlock.tsx@@ -0,0 +1,102 @@+import { memo } from 'react'+import { Clock } from 'lucide-react'+import { StyledIcon } from '../shared/TimelineStep'+import { EventMessage } from '../shared/EventMessage'+import { ColumnSchema } from '../../../UnifiedLogs.schema'++interface ResponseCompletedBlockProps {+ data: ColumnSchema+ enrichedData?: Record<string, any>+}++// Response (final step) - Shows completion details for HTTP or database operations+export const MemoizedResponseCompletedBlock = memo(function ResponseCompletedBlock({+ data,+ enrichedData,+}: ResponseCompletedBlockProps) {+ // Check if this is a postgres log+ const isPostgresLog = (enrichedData?.log_type || data?.log_type) === 'postgres'++ // HTTP response handling+ const hasError = data?.status && Number(data.status) >= 400+ const responseTime = enrichedData?.response_time_ms || enrichedData?.duration_ms+ const status = Number(data?.status)++ // Postgres operation handling+ const eventMessage = enrichedData?.event_message || (data as any)?.event_message+ const severity = enrichedData?.error_severity+ const hasPostgresError = severity && ['error', 'fatal'].includes(severity.toLowerCase())++ return (+ <div>+ <div className="flex items-center justify-between py-0 px-2">+ <div className="flex items-center gap-2 text-sm text-foreground-light">+ <StyledIcon icon={Clock} title="Response" />+ <span>{isPostgresLog ? 'Operation Result' : 'Response'}</span>+ </div>++ {/* Status display */}+ {isPostgresLog+ ? // Postgres status+ severity && (+ <span+ className={`text-sm font-mono ${+ hasPostgresError ? 'text-destructive' : 'text-foreground-light'+ }`}+ >+ {hasPostgresError ? `${severity.toUpperCase()} Error` : `${severity.toUpperCase()}`}+ </span>+ )+ : // HTTP status+ data?.status && (+ <span className="text-sm font-mono text-foreground-light">+ {hasError ? `${data.status} Error` : `${data.status} Success`}+ </span>+ )}+ </div>++ {/* Completion message */}+ {isPostgresLog ? (+ // Postgres completion message+ <div className="text-xs text-foreground-light px-2 py-1">+ {hasPostgresError+ ? 'Database operation completed with error'+ : 'Database operation completed successfully'}+ </div>+ ) : (+ // HTTP completion message+ responseTime && (+ <div className="text-xs text-foreground-light px-2 py-1">+ {hasError+ ? `Error response sent to client in ${responseTime}ms`+ : `Response sent to client in ${responseTime}ms`}+ </div>+ )+ )}++ {/* Error/Event details */}+ {isPostgresLog+ ? // Show postgres event message+ eventMessage && (+ <div className="px-2">+ <EventMessage message={eventMessage} severity={severity} />+ </div>+ )+ : // Show HTTP error details+ hasError && (+ <div className="px-2 py-1 mt-1">+ <div className="text-xs font-medium text-destructive mb-1">Error Details</div>+ <div className="text-xs text-foreground-light">+ {status >= 500+ ? 'Server error occurred during request processing'+ : status >= 400+ ? 'Client error - check request parameters and authentication'+ : 'Request completed with error status'}+ </div>+ </div>+ )}+ </div>+ )+})++MemoizedResponseCompletedBlock.displayName = 'MemoizedResponseCompletedBlock'diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/Block.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/Block.tsxnew file mode 100644index 00000000000..83e42654e71--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/Block.tsx@@ -0,0 +1,133 @@+import { SquareDashedBottomCode } from 'lucide-react'+import { memo } from 'react'++import { BlockFieldConfig, ServiceFlowBlockProps } from '../../types'+import { BlockField } from './BlockField'+import { CollapsibleSection } from './CollapsibleSection'+import { FieldWithSeeMore } from './FieldWithSeeMore'+import { TimelineStep } from './TimelineStep'++export interface BlockSection {+ title: string+ fields: BlockFieldConfig[]+ collapsible?: boolean+}++export interface FieldWithSeeMoreSection {+ type: 'fieldWithSeeMore'+ primaryField: BlockFieldConfig+ additionalFields: BlockFieldConfig[]+ showValueAsBadge?: boolean+}++export interface BlockConfig {+ title: string+ primaryFields?: BlockFieldConfig[]+ sections?: (BlockSection | FieldWithSeeMoreSection)[]+}++// Simple check: show empty state only for Postgres blocks in non-postgres logs+const shouldShowEmptyState = (config: BlockConfig, data: any): boolean => {+ return config.title === 'Postgres' && data?.log_type !== 'postgres'+}++// Empty state component+const BlockEmptyState = ({ title }: { title: string }) => (+ <div className="flex flex-col items-center justify-center py-8 px-4 text-center">+ <div className="flex items-center justify-center w-7 h-7 rounded-full bg-surface-300 mb-3">+ <SquareDashedBottomCode size={16} className="text-foreground-light" strokeWidth={1.5} />+ </div>+ <div className="text-sm text-foreground-light mb-1">+ No {title.toLowerCase()} data available+ </div>+ <div className="text-xs text-foreground-lighter">+ This service was involved but no details were captured+ </div>+ </div>+)++export function createBlock(config: BlockConfig) {+ const Block = memo(function Block({+ data,+ enrichedData,+ isLoading,+ isLast,+ filterFields,+ table,+ }: ServiceFlowBlockProps) {+ return (+ <TimelineStep title={config.title} isLast={isLast}>+ {shouldShowEmptyState(config, data) ? (+ <BlockEmptyState title={config.title} />+ ) : (+ <>+ {/* Primary Fields */}+ {config.primaryFields?.map((field) => (+ <BlockField+ key={field.id}+ config={field}+ data={data}+ enrichedData={enrichedData}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ))}++ {/* Sections */}+ {config.sections?.map((section, index) => {+ if ('type' in section && section.type === 'fieldWithSeeMore') {+ return (+ <FieldWithSeeMore+ key={index}+ primaryField={section.primaryField}+ additionalFields={section.additionalFields}+ data={data}+ enrichedData={enrichedData}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ showValueAsBadge={section.showValueAsBadge}+ />+ )+ }++ // Now we know it's a BlockSection+ const blockSection = section as BlockSection+ return blockSection.collapsible ? (+ <CollapsibleSection+ key={blockSection.title}+ title={blockSection.title}+ fields={blockSection.fields}+ data={data}+ enrichedData={enrichedData}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ) : (+ <div key={blockSection.title}>+ {blockSection.fields.map((field) => (+ <BlockField+ key={field.id}+ config={field}+ data={data}+ enrichedData={enrichedData}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ))}+ </div>+ )+ })}+ </>+ )}+ </TimelineStep>+ )+ })++ Block.displayName = 'Block'++ return Block+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/BlockField.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/BlockField.tsxnew file mode 100644index 00000000000..6f78aff95f3--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/BlockField.tsx@@ -0,0 +1,88 @@+import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'+import { DataTableSheetRowAction } from 'components/ui/DataTable/DataTableSheetRowAction'+import { Skeleton } from 'ui'+import { getStatusLevel } from '../../../UnifiedLogs.utils'+import { BlockFieldProps } from '../../types'+import { TruncatedTextWithPopover } from './TruncatedTextWithPopover'++const BlockField = ({+ config,+ data,+ enrichedData,+ isLoading,+ filterFields,+ table,+}: BlockFieldProps) => {+ const value = config.getValue(data, enrichedData)+ const displayValue = value ?? 'No value'+ const stringValue = String(displayValue)++ const shouldShowSkeleton = config.requiresEnrichedData && isLoading && !value++ const filterField = filterFields.find((field) => field.value === config.id)+ const isFilterable = !!filterField++ // Special handling for status field and key fields+ const isStatusField = config.id === 'status'+ const isApiKeyField = config.id === 'api_key_role'++ // Truncation config+ const maxLength = config.maxLength || 50 // Default to 50 characters++ const fieldContent = (+ <>+ <dt className="text-[13.5px] text-foreground-light">{config.label}</dt>+ <dd className="text-right">+ {shouldShowSkeleton ? (+ <Skeleton className="h-4 w-24" />+ ) : isStatusField && displayValue !== 'N/A' ? (+ <DataTableColumnStatusCode+ value={displayValue}+ level={getStatusLevel(displayValue)}+ className="text-xs"+ />+ ) : isApiKeyField && displayValue !== 'N/A' ? (+ <TruncatedTextWithPopover+ text={stringValue}+ maxLength={maxLength}+ className="px-2 py-1 text-xs font-mono border border-border rounded bg-surface-100"+ />+ ) : displayValue !== 'N/A' ? (+ <TruncatedTextWithPopover+ text={stringValue}+ maxLength={maxLength}+ className={`text-sm font-mono ${+ isFilterable ? 'text-foreground cursor-pointer hover:underline' : 'text-foreground'+ }`}+ />+ ) : (+ <span+ className={`text-sm font-mono ${+ isFilterable ? 'text-foreground cursor-pointer hover:underline' : 'text-foreground'+ } text-foreground-light`}+ >+ {displayValue}+ </span>+ )}+ </dd>+ </>+ )++ if (isFilterable && !shouldShowSkeleton && displayValue !== 'N/A') {+ return (+ <DataTableSheetRowAction+ fieldValue={config.id}+ filterFields={filterFields}+ value={stringValue}+ table={table}+ className="flex justify-between items-center py-1 px-2 rounded hover:bg-accent/50 cursor-pointer w-full hover:bg-surface-400"+ >+ {fieldContent}+ </DataTableSheetRowAction>+ )+ }++ return <div className="flex justify-between items-center py-1 px-2">{fieldContent}</div>+}++export { BlockField }diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/CollapsibleSection.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/CollapsibleSection.tsxnew file mode 100644index 00000000000..01c4f920568--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/CollapsibleSection.tsx@@ -0,0 +1,71 @@+import { Table } from '@tanstack/react-table'+import { ChevronDown, ChevronRight } from 'lucide-react'+import { useState } from 'react'++import { DataTableFilterField } from 'components/ui/DataTable/DataTable.types'+import {+ Button,+ Collapsible_Shadcn_ as Collapsible,+ CollapsibleContent_Shadcn_ as CollapsibleContent,+ CollapsibleTrigger_Shadcn_ as CollapsibleTrigger,+} from 'ui'+import { BlockFieldConfig } from '../../types'+import { BlockField } from './BlockField'++interface CollapsibleSectionProps {+ title: string+ fields: BlockFieldConfig[]+ data: any+ enrichedData?: any+ isLoading?: boolean+ filterFields: DataTableFilterField<any>[]+ table: Table<any>+ defaultOpen?: boolean+}++const CollapsibleSection = ({+ title,+ fields,+ data,+ enrichedData,+ isLoading,+ filterFields,+ table,+ defaultOpen = false,+}: CollapsibleSectionProps) => {+ const [isOpen, setIsOpen] = useState(defaultOpen)++ return (+ <div className="border-t border-border">+ <Collapsible open={isOpen} onOpenChange={setIsOpen}>+ <CollapsibleTrigger asChild>+ <Button+ type="text"+ size="tiny"+ className="w-full justify-start py-1 px-2 h-auto text-xs font-medium text-foreground-light hover:text-foreground"+ >+ <div className="flex items-center gap-1">+ {isOpen ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ <span>{title}</span>+ </div>+ </Button>+ </CollapsibleTrigger>+ <CollapsibleContent className="transition-all data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down pt-1">+ {fields.map((field) => (+ <BlockField+ key={field.id}+ config={field}+ data={data}+ enrichedData={enrichedData}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ))}+ </CollapsibleContent>+ </Collapsible>+ </div>+ )+}++export { CollapsibleSection }diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/EventMessage.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/EventMessage.tsxnew file mode 100644index 00000000000..409023e9d4c--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/EventMessage.tsx@@ -0,0 +1,64 @@+import { Database, LucideIcon } from 'lucide-react'++import { LEVELS } from 'components/ui/DataTable/DataTable.constants'+import { Badge } from 'ui'+import { LOG_TYPES } from '../../../UnifiedLogs.constants'+import { formatServiceTypeForDisplay } from '../../../UnifiedLogs.utils'++type LogType = (typeof LOG_TYPES)[number]+type Level = (typeof LEVELS)[number]++export interface EventMessageProps {+ message: string+ severity?: Level+ icon?: LucideIcon+ serviceType?: LogType+}++export const EventMessage = ({+ message,+ severity,+ icon: Icon = Database,+ serviceType = 'postgres',+}: EventMessageProps) => {+ const getSeverityIcon = (severity?: Level) => {+ switch (severity) {+ case 'error':+ return 'text-destructive'+ case 'warning':+ return 'text-warning'+ default:+ return 'text-foreground-light'+ }+ }++ return (+ <div className="mt-3 border-t border-border pt-3">+ <div className="flex items-center gap-2 mb-2">+ <Icon size={14} className={getSeverityIcon(severity)} />+ <span className="text-xs font-medium text-foreground-light">+ {formatServiceTypeForDisplay(serviceType)} Event+ {severity && (+ <Badge+ variant={+ severity === 'error'+ ? 'destructive'+ : severity === 'warning'+ ? 'warning'+ : 'default'+ }+ className="ml-2 text-xs"+ >+ {severity.toUpperCase()}+ </Badge>+ )}+ </span>+ </div>+ <div className="p-3 rounded-lg border border-border bg-surface-100">+ <div className="text-xs font-mono break-all whitespace-pre-wrap leading-relaxed max-h-32 overflow-y-auto">+ {message}+ </div>+ </div>+ </div>+ )+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/FieldWithSeeMore.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/FieldWithSeeMore.tsxnew file mode 100644index 00000000000..2bfbeb3884b--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/FieldWithSeeMore.tsx@@ -0,0 +1,135 @@+import { Table } from '@tanstack/react-table'+import { X } from 'lucide-react'+import { useState } from 'react'++import { DataTableFilterField } from 'components/ui/DataTable/DataTable.types'+import {+ Badge,+ Collapsible_Shadcn_ as Collapsible,+ CollapsibleContent_Shadcn_ as CollapsibleContent,+ CollapsibleTrigger_Shadcn_ as CollapsibleTrigger,+ Skeleton,+} from 'ui'+import { BlockFieldConfig } from '../../types'+import { BlockField } from './BlockField'++// Single source of truth for field row styling+const FieldRow = ({+ label,+ value,+ expandButton,+}: {+ label: string+ value: React.ReactNode+ expandButton?: React.ReactNode+}) => (+ <div className="flex justify-between items-center py-1 px-2">+ <dt className="flex items-center gap-2 text-[13.5px] text-foreground-light">+ <span>{label}</span>+ {expandButton}+ </dt>+ <dd className="text-right">{value}</dd>+ </div>+)++interface FieldWithSeeMoreProps {+ primaryField: BlockFieldConfig+ additionalFields: BlockFieldConfig[]+ data: any+ enrichedData?: any+ isLoading?: boolean+ filterFields: DataTableFilterField<any>[]+ table: Table<any>+ showValueAsBadge?: boolean+}++// Primary field with expandable additional details+const FieldWithSeeMore = ({+ primaryField,+ additionalFields,+ data,+ enrichedData,+ isLoading,+ filterFields,+ table,+ showValueAsBadge = false,+}: FieldWithSeeMoreProps) => {+ const [isOpen, setIsOpen] = useState(false)+ const hasAdditionalData = additionalFields.some(+ (field) => field.getValue(data, enrichedData) && field.getValue(data, enrichedData) !== 'N/A'+ )++ const primaryValue = primaryField.getValue(data, enrichedData)+ const shouldShowSkeleton = primaryField.requiresEnrichedData && isLoading && !primaryValue+ const isApiKeyField = primaryField.id === 'api_key_role'++ // Common value rendering logic+ const renderValue = () => {+ if (shouldShowSkeleton) {+ return <Skeleton className="h-4 w-24" />+ }++ if (isApiKeyField && primaryValue && primaryValue !== 'N/A') {+ return (+ <span className="border border-border rounded px-2 py-1 bg-surface-100 text-xs font-mono text-foreground">+ {primaryValue}+ </span>+ )+ }++ if (showValueAsBadge && primaryValue && primaryValue !== 'N/A') {+ return (+ <Badge variant="secondary" size="small">+ {primaryValue}+ </Badge>+ )+ }++ return (+ <span+ className={`text-sm font-mono text-foreground ${+ primaryValue === 'N/A' ? 'text-foreground-light' : ''+ }`}+ >+ {primaryValue ?? 'N/A'}+ </span>+ )+ }++ const expandButton = hasAdditionalData ? (+ <CollapsibleTrigger asChild>+ <button className="w-3 h-3 flex items-center justify-center selection:font-mono text-foreground-lighter text-xs hover:text-foreground-light bg-foreground-muted/75 rounded [&[data-state=open]>svg]:rotate-180 hover:bg-foreground-lighter">+ <X size={10} className="text-background-surface-400 rotate-45" strokeWidth={3} />+ </button>+ </CollapsibleTrigger>+ ) : undefined++ return (+ <div className="border-t border-border">+ {hasAdditionalData ? (+ <Collapsible open={isOpen} onOpenChange={setIsOpen}>+ <FieldRow label={primaryField.label} value={renderValue()} expandButton={expandButton} />+ <CollapsibleContent className="transition-all data-[state=closed]:animate-collapsible-up data-[state=open]:animate-collapsible-down">+ <div className="mt-1">+ {additionalFields.map((field) => (+ <BlockField+ key={field.id}+ config={field}+ data={data}+ enrichedData={enrichedData}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ))}+ </div>+ </CollapsibleContent>+ </Collapsible>+ ) : (+ <FieldRow label={primaryField.label} value={renderValue()} />+ )}+ </div>+ )+}++export { FieldRow, FieldWithSeeMore }diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/TimelineStep.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/TimelineStep.tsxnew file mode 100644index 00000000000..cde1d34e1f1--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/TimelineStep.tsx@@ -0,0 +1,73 @@+import { Clock, Database, Globe, LucideIcon, Server } from 'lucide-react'++import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'+import { Auth, EdgeFunctions, Storage } from 'icons'+import { getStatusLevel } from '../../../UnifiedLogs.utils'++// Type for icon components (covers both lucide-react and our icon library)+type IconComponent = LucideIcon | React.ComponentType<any>++// Reusable styled icon component+const StyledIcon = ({ icon: Icon, title }: { icon: IconComponent; title: string }) => (+ <div className="flex items-center gap-2 bg-surface-300 rounded p-0.5 border justify-center border-foreground-muted">+ <Icon className="w-4 h-4 text-foreground-lighter" strokeWidth={1} />+ </div>+)++const TimelineStep = ({+ title,+ status,+ statusText,+ children,+ isLast = false,+}: {+ title: string+ status?: number | string+ statusText?: string+ children: React.ReactNode+ isLast?: boolean+}) => (+ <>+ <div className="relative">+ {/* Timeline dot - positioned on the left timeline line */}+ <div className="py-1 bg-surface-100/50 border-r border-t border-l rounded-t px-2">+ <div>+ <div className="flex flex-row justify-between">+ <div className="flex items-center gap-2">+ {title === 'Request started' && <StyledIcon icon={Clock} title={title} />}+ {title === 'Network' && <StyledIcon icon={Globe} title={title} />}+ {title === 'Data API' && <StyledIcon icon={Server} title={title} />}+ {title === 'Authentication' && <StyledIcon icon={Auth} title={title} />}+ {title === 'Edge Function' && <StyledIcon icon={EdgeFunctions} title={title} />}+ {title === 'Storage' && <StyledIcon icon={Storage} title={title} />}+ {title === 'Postgres' && <StyledIcon icon={Database} title={title} />}+ {title === 'Response' && <StyledIcon icon={Clock} title={title} />}+ <h3 className="text-sm text-foreground tracking-wide">{title}</h3>+ </div>++ {statusText && (+ <span className="text-xs text-foreground-light tracking-wide">{statusText}</span>+ )}++ {status && (+ <DataTableColumnStatusCode+ value={status}+ level={getStatusLevel(status)}+ className="text-xs"+ />+ )}+ </div>+ </div>+ </div>++ {/* Main section box */}+ <div className="border rounded-b border-border">+ {/* Content */}+ <dl className="space-y-0 divide-y px-1 py-1 bg-surface-100/50">{children}</dl>+ </div>+ {!isLast && <div className="border-l h-3 ml-5"></div>}+ </div>+ </>+)++export { StyledIcon, TimelineStep }diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/TruncatedTextWithPopover.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/TruncatedTextWithPopover.tsxnew file mode 100644index 00000000000..24a7b095be4--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/components/shared/TruncatedTextWithPopover.tsx@@ -0,0 +1,38 @@+import { useState } from 'react'++import { Popover_Shadcn_, PopoverContent_Shadcn_, PopoverTrigger_Shadcn_ } from 'ui'++interface TruncatedTextWithPopoverProps {+ text: string+ maxLength?: number+ className?: string+ children?: React.ReactNode+}++export const TruncatedTextWithPopover = ({+ text,+ maxLength = 50,+ className = '',+ children,+}: TruncatedTextWithPopoverProps) => {+ const [isOpen, setIsOpen] = useState(false)+ const isTruncated = text.length > maxLength+ const truncatedText = isTruncated ? text.substring(0, maxLength) + '...' : text++ // If not truncated, just render the text without popover+ if (!isTruncated) {+ return children ? <>{children}</> : <span className={className}>{text}</span>+ }++ // If truncated, render with popover+ return (+ <Popover_Shadcn_ open={isOpen} onOpenChange={setIsOpen}>+ <PopoverTrigger_Shadcn_ asChild>+ <span className={`cursor-help ${className}`}>{children || truncatedText}</span>+ </PopoverTrigger_Shadcn_>+ <PopoverContent_Shadcn_ className="max-w-md p-3 break-words" side="top">+ <div className="text-sm font-mono whitespace-pre-wrap">{text}</div>+ </PopoverContent_Shadcn_>+ </Popover_Shadcn_>+ )+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/blockConfigs.ts b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/blockConfigs.tsnew file mode 100644index 00000000000..ee40b54b960--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/blockConfigs.ts@@ -0,0 +1,107 @@+import { BlockConfig } from '../components/shared/Block'+import {+ authPrimaryFields,+ postgrestPrimaryFields,+ postgrestResponseFields,+ networkPrimaryFields,+ apiKeyPrimaryField,+ apiKeyAdditionalFields,+ userPrimaryField,+ userAdditionalFields,+ locationPrimaryField,+ locationAdditionalFields,+ authorizationFields,+ techDetailsFields,+ edgeFunctionPrimaryFields,+ edgeFunctionDetailsFields,+ storagePrimaryFields,+ storageDetailsFields,+ postgresPrimaryFields,+ postgresDetailsFields,+} from './serviceFlowFields'++export const authBlockConfig: BlockConfig = {+ title: 'Authentication',+ primaryFields: authPrimaryFields,+}++export const postgrestBlockConfig: BlockConfig = {+ title: 'Data API',+ primaryFields: postgrestPrimaryFields,+ sections: [+ {+ title: 'Response Details',+ fields: postgrestResponseFields,+ collapsible: true,+ },+ ],+}++export const networkBlockConfig: BlockConfig = {+ title: 'Network',+ primaryFields: networkPrimaryFields,+ sections: [+ {+ type: 'fieldWithSeeMore',+ primaryField: apiKeyPrimaryField,+ additionalFields: apiKeyAdditionalFields,+ showValueAsBadge: true,+ },+ {+ type: 'fieldWithSeeMore',+ primaryField: userPrimaryField,+ additionalFields: userAdditionalFields,+ },+ {+ type: 'fieldWithSeeMore',+ primaryField: locationPrimaryField,+ additionalFields: locationAdditionalFields,+ },+ {+ title: 'Authorization',+ fields: authorizationFields,+ collapsible: true,+ },+ {+ title: 'Tech Details',+ fields: techDetailsFields,+ collapsible: true,+ },+ ],+}++export const edgeFunctionBlockConfig: BlockConfig = {+ title: 'Edge Function',+ primaryFields: edgeFunctionPrimaryFields,+ sections: [+ {+ title: 'Function Details',+ fields: edgeFunctionDetailsFields,+ collapsible: true,+ },+ ],+}++export const storageBlockConfig: BlockConfig = {+ title: 'Storage',+ primaryFields: storagePrimaryFields,+ sections: [+ {+ title: 'Storage Details',+ fields: storageDetailsFields,+ collapsible: true,+ },+ ],+}++export const postgresBlockConfig: BlockConfig = {+ title: 'Postgres',+ primaryFields: postgresPrimaryFields,+ sections: [+ {+ title: 'Connection & Session Details',+ fields: postgresDetailsFields,+ collapsible: true,+ },+ ],+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/fieldHelpers.ts b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/fieldHelpers.tsnew file mode 100644index 00000000000..a96245f8f53--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/fieldHelpers.ts@@ -0,0 +1,142 @@+import { BlockFieldConfig } from '../types'++/**+ * Common field configuration helpers to reduce duplication+ */++// Helper for simple fields that fallback from enrichedData to data+export const createField = (+ id: string,+ label: string,+ enrichedKey?: string,+ dataKey?: string,+ requiresEnrichedData = false+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => {+ const eKey = enrichedKey || id+ const dKey = dataKey || id+ return enrichedData?.[eKey] || data?.[dKey]+ },+ requiresEnrichedData,+})++// Helper for truncated text fields+export const createTruncatedField = (+ id: string,+ label: string,+ maxLength: number,+ enrichedKey?: string,+ dataKey?: string,+ requiresEnrichedData = false+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => {+ const eKey = enrichedKey || id+ const dKey = dataKey || id+ const value = enrichedData?.[eKey] || data?.[dKey]+ if (!value || typeof value !== 'string') return value+ return value.length > maxLength ? `${value.substring(0, maxLength)}...` : value+ },+ requiresEnrichedData,+})++// Helper for ID fields that show truncated version+export const createIdField = (+ id: string,+ label: string,+ truncateLength = 8,+ enrichedKey?: string,+ dataKey?: string,+ requiresEnrichedData = false+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => {+ const eKey = enrichedKey || id+ const dKey = dataKey || id+ const value = enrichedData?.[eKey] || data?.[dKey]+ if (!value) return null+ const stringValue = String(value)+ return truncateLength ? `${stringValue.substring(0, truncateLength)}...` : stringValue+ },+ requiresEnrichedData,+})++// Helper for time/duration fields+export const createTimeField = (+ id: string,+ label: string,+ unit = 'ms',+ enrichedKey?: string,+ dataKey?: string,+ requiresEnrichedData = false+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => {+ const eKey = enrichedKey || id+ const dKey = dataKey || id+ const time = enrichedData?.[eKey] || data?.[dKey]+ return time ? `${time}${unit}` : null+ },+ requiresEnrichedData,+})++// Helper for status fields with fallback logic+export const createStatusField = (+ id: string = 'status',+ label: string = 'Status'+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => enrichedData?.status || data?.status,+})++// Helper for path/filename extraction+export const createFileNameField = (+ id: string,+ label: string,+ pathKey = 'path',+ requiresEnrichedData = false+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => {+ const path = enrichedData?.[pathKey] || data?.[pathKey]+ if (!path) return null+ // Remove query parameters and hash, get last segment+ const cleanPath = path.split('?')[0].split('#')[0]+ const segments = cleanPath.split('/')+ return segments[segments.length - 1] || null+ },+ requiresEnrichedData,+})++// Helper for conditional fields based on error status+export const createConditionalField = (+ id: string,+ label: string,+ getValue: (data: any, enrichedData?: any) => any,+ errorValue: string = 'Unavailable',+ deletedValue: string = 'Object deleted',+ requiresEnrichedData = false+): BlockFieldConfig => ({+ id,+ label,+ getValue: (data, enrichedData) => {+ const status = enrichedData?.status || data?.status+ const numStatus = Number(status)++ if (status === 404 || status === '404') {+ return deletedValue+ } else if (numStatus >= 400) {+ return errorValue+ }++ return getValue(data, enrichedData)+ },+ requiresEnrichedData,+})diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/serviceFlowFields.ts b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/serviceFlowFields.tsnew file mode 100644index 00000000000..0b32cd34ab9--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/config/serviceFlowFields.ts@@ -0,0 +1,746 @@+import { formatBytes } from 'lib/helpers'+import { BlockFieldConfig } from '../types'+import { getStorageMetadata } from '../utils/storageUtils'++// Helper functions that avoid duplication with existing storage utilities+const getFileName = (path: string): string => {+ if (!path) return ''+ // Remove query parameters and hash+ const cleanPath = path.split('?')[0].split('#')[0]+ // Get the last part after the last slash+ const segments = cleanPath.split('/')+ return segments[segments.length - 1] || ''+}++const formatStorageDate = (dateString: string): string => {+ try {+ return new Date(dateString).toLocaleString()+ } catch {+ return dateString+ }+}++// =============================================================================+// NETWORK FIELDS+// =============================================================================++// Field configurations - using filterable field IDs where possible+export const originFields: BlockFieldConfig[] = [+ {+ id: 'date', // Matches filterFields 'date' (timerange) - FILTERABLE+ label: 'Time',+ getValue: (data) => {+ if (!data?.timestamp && !data?.date) return null+ try {+ const timestamp = data?.timestamp || data?.date+ return new Date(timestamp).toLocaleString()+ } catch {+ return 'Invalid date'+ }+ },+ },+]++// Primary Network Fields (Always Visible) - FILTERABLE+export const networkPrimaryFields: BlockFieldConfig[] = [+ {+ id: 'host', // Matches filterFields 'host' (input) - FILTERABLE+ label: 'Host',+ getValue: (data, enrichedData) =>+ enrichedData?.request_host || enrichedData?.host || data?.host,+ },+ {+ id: 'method', // Matches filterFields 'method' (checkbox) - FILTERABLE+ label: 'Method',+ getValue: (data, enrichedData) =>+ enrichedData?.request_method || enrichedData?.method || data?.method,+ },+ {+ id: 'pathname', // Matches filterFields 'pathname' (input) - FILTERABLE+ label: 'Path',+ getValue: (data, enrichedData) =>+ enrichedData?.request_path || enrichedData?.pathname || data?.pathname,+ },+ {+ id: 'user_agent',+ label: 'Client',+ getValue: (data, enrichedData) => {+ const userAgent = enrichedData?.headers_user_agent+ if (!userAgent) return null+ // TODO: Parse user agent for nice display with icons+ return userAgent.length > 50 ? userAgent.substring(0, 50) + '...' : userAgent+ },+ requiresEnrichedData: true,+ },+]++// Primary API Key Field (Always Visible) - Shows API key type only+export const apiKeyPrimaryField: BlockFieldConfig = {+ id: 'api_key_role',+ label: 'API Key',+ getValue: (data, enrichedData) => {+ const prefix = enrichedData?.api_key_prefix+ const jwtRole = enrichedData?.jwt_key_role+ const authRole = enrichedData?.authorization_role++ if (prefix) {+ // Extract key type from prefix+ if (prefix.includes('publishable')) return 'publishable'+ else if (prefix.includes('secret')) return 'secret'+ return 'unknown'+ }++ // Fallback to JWT apikey postgres role if no API key prefix+ if (jwtRole) {+ return jwtRole+ }++ // Fallback to authorization postgres role if no apikey JWT+ if (authRole) {+ return authRole+ }++ return null+ },+ requiresEnrichedData: true,+}++// Additional API Key Fields (Collapsible)+export const apiKeyAdditionalFields: BlockFieldConfig[] = [+ {+ id: 'api_key_prefix_full',+ label: 'API Key Prefix',+ getValue: (data, enrichedData) => {+ const prefix = enrichedData?.api_key_prefix+ return prefix || null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'postgres_role',+ label: 'Postgres Role',+ getValue: (data, enrichedData) => enrichedData?.jwt_key_role,+ requiresEnrichedData: true,+ },+ {+ id: 'api_key_error',+ label: 'API Key Error',+ getValue: (data, enrichedData) => enrichedData?.api_key_error,+ requiresEnrichedData: true,+ },+ {+ id: 'api_key_hash',+ label: 'API Key Hash',+ getValue: (data, enrichedData) => {+ const hash = enrichedData?.api_key_hash+ return hash ? `${hash.substring(0, 12)}...` : null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'authorization_role',+ label: 'Postgres Role',+ getValue: (data, enrichedData) => enrichedData?.authorization_role,+ requiresEnrichedData: true,+ },+]++// Primary User Field (Always Visible)+export const userPrimaryField: BlockFieldConfig = {+ id: 'user_id',+ label: 'User',+ getValue: (data, enrichedData) => {+ const userId = enrichedData?.user_id+ return userId ? `${userId.substring(0, 8)}...` : null+ },+ requiresEnrichedData: true,+}++// Additional User Fields (Collapsible)+export const userAdditionalFields: BlockFieldConfig[] = [+ {+ id: 'auth_user', // Matches filterFields 'auth_user' (input) - FILTERABLE+ label: 'Auth User',+ getValue: (data, enrichedData) => enrichedData?.auth_user || data?.auth_user,+ },+ {+ id: 'user_email',+ label: 'User Email',+ getValue: (data, enrichedData) => enrichedData?.user_email,+ requiresEnrichedData: true,+ },+]++// Primary Location Field (Always Visible)+export const locationPrimaryField: BlockFieldConfig = {+ id: 'client_country',+ label: 'Location',+ getValue: (data, enrichedData) => {+ const country = enrichedData?.client_country || enrichedData?.cf_country+ const city = enrichedData?.client_city+ if (country && city) return `${city}, ${country}`+ if (country) return country+ if (city) return city+ return null+ },+ requiresEnrichedData: true,+}++// Additional Location Fields (Collapsible) - includes IP addresses+export const locationAdditionalFields: BlockFieldConfig[] = [+ {+ id: 'client_continent',+ label: 'Continent',+ getValue: (data, enrichedData) => enrichedData?.client_continent,+ requiresEnrichedData: true,+ },+ {+ id: 'client_region',+ label: 'Region',+ getValue: (data, enrichedData) => enrichedData?.client_region,+ requiresEnrichedData: true,+ },+ {+ id: 'client_timezone',+ label: 'Timezone',+ getValue: (data, enrichedData) => enrichedData?.client_timezone,+ requiresEnrichedData: true,+ },+ {+ id: 'x_real_ip',+ label: 'Real IP',+ getValue: (data, enrichedData) => enrichedData?.headers_x_real_ip,+ requiresEnrichedData: true,+ },+ {+ id: 'client_ip',+ label: 'Client IP',+ getValue: (data, enrichedData) => enrichedData?.client_ip,+ requiresEnrichedData: true,+ },+]++// Authorization Fields (Collapsible) - JWT authorization details+export const authorizationFields: BlockFieldConfig[] = [+ {+ id: 'jwt_auth_key_id',+ label: 'Key ID',+ getValue: (data, enrichedData) =>+ enrichedData?.jwt_auth_key_id || enrichedData?.jwt_apikey_key_id,+ requiresEnrichedData: true,+ },+ {+ id: 'jwt_auth_session_id',+ label: 'Session ID',+ getValue: (data, enrichedData) =>+ enrichedData?.jwt_auth_session_id || enrichedData?.jwt_apikey_session_id,+ requiresEnrichedData: true,+ },+ {+ id: 'jwt_auth_subject',+ label: 'Subject',+ getValue: (data, enrichedData) =>+ enrichedData?.jwt_auth_subject || enrichedData?.jwt_apikey_subject,+ requiresEnrichedData: true,+ },+ {+ id: 'jwt_auth_issuer',+ label: 'Issuer',+ getValue: (data, enrichedData) =>+ enrichedData?.jwt_auth_issuer || enrichedData?.jwt_apikey_issuer,+ requiresEnrichedData: true,+ },+ {+ id: 'jwt_auth_algorithm',+ label: 'Algorithm',+ getValue: (data, enrichedData) =>+ enrichedData?.jwt_auth_algorithm || enrichedData?.jwt_apikey_algorithm,+ requiresEnrichedData: true,+ },+ {+ id: 'jwt_auth_expires_at',+ label: 'Expires At',+ getValue: (data, enrichedData) => {+ const expiresAt = enrichedData?.jwt_auth_expires_at || enrichedData?.jwt_apikey_expires_at+ if (!expiresAt) return null+ try {+ return new Date(expiresAt * 1000).toLocaleString()+ } catch {+ return expiresAt+ }+ },+ requiresEnrichedData: true,+ },+]++// Tech Details Fields (Collapsible)+export const techDetailsFields: BlockFieldConfig[] = [+ {+ id: 'network_protocol',+ label: 'Protocol',+ getValue: (data, enrichedData) => enrichedData?.network_protocol,+ requiresEnrichedData: true,+ },+ {+ id: 'cf_datacenter',+ label: 'Datacenter',+ getValue: (data, enrichedData) =>+ enrichedData?.network_datacenter || enrichedData?.cf_datacenter,+ requiresEnrichedData: true,+ },+ {+ id: 'cache_status',+ label: 'Cache Status',+ getValue: (data, enrichedData) => enrichedData?.response_cache_status,+ requiresEnrichedData: true,+ },+ {+ id: 'cf_ray',+ label: 'CF-Ray',+ getValue: (data, enrichedData) => enrichedData?.cf_ray,+ requiresEnrichedData: true,+ },+ {+ id: 'x_client_info',+ label: 'SDK',+ getValue: (data, enrichedData) => enrichedData?.headers_x_client_info,+ requiresEnrichedData: true,+ },+ {+ id: 'x_forwarded_proto',+ label: 'Forwarded Proto',+ getValue: (data, enrichedData) => enrichedData?.headers_x_forwarded_proto,+ requiresEnrichedData: true,+ },+]++// =============================================================================+// POSTGREST FIELDS+// =============================================================================++// Primary PostgREST Fields (Always Visible) - FILTERABLE+export const postgrestPrimaryFields: BlockFieldConfig[] = [+ {+ id: 'status', // Matches filterFields 'status' (checkbox) - FILTERABLE+ label: 'Status',+ getValue: (data, enrichedData) => enrichedData?.status || data?.status,+ },+ {+ id: 'postgres_role',+ label: 'Postgres Role',+ getValue: (data, enrichedData) => enrichedData?.api_role,+ requiresEnrichedData: true,+ },+ {+ id: 'response_time',+ label: 'Response Time',+ getValue: (data, enrichedData) => {+ const time = enrichedData?.response_origin_time || data?.response_time_ms+ return time ? `${time}ms` : null+ },+ requiresEnrichedData: true,+ },+]++// PostgREST Response Details (Collapsible)+export const postgrestResponseFields: BlockFieldConfig[] = [+ {+ id: 'query_params',+ label: 'Query',+ getValue: (data, enrichedData) => enrichedData?.request_search,+ requiresEnrichedData: true,+ },+ {+ id: 'content_type',+ label: 'Content Type',+ getValue: (data, enrichedData) => enrichedData?.response_content_type,+ requiresEnrichedData: true,+ },+ {+ id: 'message',+ label: 'Message',+ getValue: (data, enrichedData) => enrichedData?.message,+ requiresEnrichedData: true,+ },+]++// =============================================================================+// AUTH FIELDS+// =============================================================================++// Primary GoTrue/Auth Fields (Always Visible)+export const authPrimaryFields: BlockFieldConfig[] = [+ {+ id: 'auth_path',+ label: 'Auth Path',+ getValue: (data, enrichedData) => {+ return enrichedData?.path || enrichedData?.request_path || data?.path+ },+ requiresEnrichedData: true,+ },+ {+ id: 'log_id',+ label: 'Log ID',+ getValue: (data, enrichedData) => {+ const logId = data?.id || enrichedData?.id+ return logId ? `${logId.substring(0, 8)}...` : null+ },+ },+ {+ id: 'referer',+ label: 'Referer',+ getValue: (data, enrichedData) => {+ return enrichedData?.headers_referer || null+ },+ requiresEnrichedData: true,+ },+]++// =============================================================================+// EDGE FUNCTION FIELDS+// =============================================================================++// Primary Edge Function Fields (Always Visible)+export const edgeFunctionPrimaryFields: BlockFieldConfig[] = [+ {+ id: 'status',+ label: 'Status',+ getValue: (data, enrichedData) => enrichedData?.status || data?.status,+ },+ {+ id: 'function_path',+ label: 'Function Path',+ getValue: (data, enrichedData) => {+ return (+ enrichedData?.path || enrichedData?.request_path || data?.path || enrichedData?.request_url+ )+ },+ requiresEnrichedData: false,+ },+ {+ id: 'execution_time',+ label: 'Execution Time',+ getValue: (data, enrichedData) => {+ const time = enrichedData?.execution_time_ms || data?.execution_time_ms+ return time ? `${time}ms` : null+ },+ requiresEnrichedData: false,+ },+ {+ id: 'execution_id',+ label: 'Execution ID',+ getValue: (data, enrichedData) => {+ const execId = enrichedData?.execution_id || data?.execution_id+ return execId ? `${execId.substring(0, 8)}...` : null+ },+ requiresEnrichedData: false,+ },+]++// Edge Function Details (Collapsible)+export const edgeFunctionDetailsFields: BlockFieldConfig[] = [+ {+ id: 'function_id',+ label: 'Function ID',+ getValue: (data, enrichedData) => {+ const funcId = enrichedData?.function_id || data?.function_id+ return funcId ? `${funcId.substring(0, 8)}...` : null+ },+ requiresEnrichedData: false,+ },+ {+ id: 'execution_region',+ label: 'Execution Region',+ getValue: (data, enrichedData) => {+ return enrichedData?.execution_region || data?.execution_region || null+ },+ requiresEnrichedData: false,+ },+ {+ id: 'function_log_count',+ label: 'Function Logs',+ getValue: (data, enrichedData) => {+ const count = enrichedData?.function_log_count || data?.function_log_count || data?.log_count+ return count ? `${count} logs` : 'No logs'+ },+ requiresEnrichedData: false,+ },+ {+ id: 'method',+ label: 'Method',+ getValue: (data, enrichedData) => enrichedData?.method || data?.method,+ requiresEnrichedData: false,+ },+ {+ id: 'user_agent',+ label: 'User Agent',+ getValue: (data, enrichedData) => {+ const ua = enrichedData?.headers_user_agent || data?.headers_user_agent+ return ua ? (ua.length > 30 ? `${ua.substring(0, 30)}...` : ua) : null+ },+ requiresEnrichedData: false,+ },+]++// =============================================================================+// STORAGE FIELDS+// =============================================================================++// Primary Storage Fields (Always Visible)+export const storagePrimaryFields: BlockFieldConfig[] = [+ {+ id: 'status',+ label: 'Status',+ getValue: (data, enrichedData) => enrichedData?.status || data?.status,+ },+ {+ id: 'filename',+ label: 'File Name',+ getValue: (data, enrichedData) => {+ const path = enrichedData?.path || enrichedData?.request_path || data?.path+ return path ? getFileName(path) : null+ },+ requiresEnrichedData: false,+ },+ {+ id: 'content_type_size',+ label: 'Type & Size',+ getValue: (data, enrichedData) => {+ const status = enrichedData?.status || data?.status+ const isObjectDeleted = status === 404 || status === '404'+ const hasError = status && Number(status) >= 400++ // For deleted objects, show status message+ if (isObjectDeleted) {+ return 'Object deleted'+ } else if (hasError) {+ return `Error ${status}`+ }++ // Try to get metadata like PreviewPane does+ const metadata = getStorageMetadata(data, enrichedData)+ const mimeType = metadata?.mimetype+ const size = metadata?.size++ // Fallback to headers if metadata not available+ const contentType =+ mimeType ||+ enrichedData?.response_content_type ||+ enrichedData?.storage_request_content_type+ const contentLength =+ size ||+ (enrichedData?.storage_content_length+ ? parseInt(enrichedData.storage_content_length)+ : null)++ if (contentType && contentLength) {+ return `${contentType} - ${formatBytes(contentLength)}`+ } else if (contentType) {+ return contentType+ } else if (contentLength) {+ return formatBytes(contentLength)+ }+ return 'Unknown type'+ },+ requiresEnrichedData: true,+ },+ {+ id: 'response_time',+ label: 'Response Time',+ getValue: (data, enrichedData) => {+ const time = enrichedData?.response_origin_time || data?.response_time_ms+ return time ? `${time}ms` : null+ },+ requiresEnrichedData: true,+ },+]++// Storage Details (Collapsible)+export const storageDetailsFields: BlockFieldConfig[] = [+ {+ id: 'storage_path',+ label: 'Storage Path',+ getValue: (data, enrichedData) => {+ const path = enrichedData?.path || enrichedData?.request_path || data?.path+ // Extract just the object path from the full storage path+ const match = path?.match(/\/storage\/v1\/object\/([^\/]+)\/(.+)/)+ if (match) {+ const [, bucketName, objectPath] = match+ return `${bucketName}/${objectPath}`+ }+ return path+ },+ requiresEnrichedData: false,+ },+ {+ id: 'last_modified',+ label: 'Last Modified',+ getValue: (data, enrichedData) => {+ const status = enrichedData?.status || data?.status+ const isObjectDeleted = status === 404 || status === '404'+ const hasError = status && Number(status) >= 400++ if (isObjectDeleted) {+ return 'Object deleted'+ } else if (hasError) {+ return 'Unavailable'+ }++ // Try to get dates from metadata like PreviewPane does+ const metadata = getStorageMetadata(data, enrichedData)+ const updatedAt = metadata?.updated_at || data?.updated_at || enrichedData?.updated_at+ const lastModified = enrichedData?.storage_last_modified || updatedAt++ return lastModified ? formatStorageDate(lastModified) : null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'etag',+ label: 'ETag',+ getValue: (data, enrichedData) => {+ const status = enrichedData?.status || data?.status+ const isObjectDeleted = status === 404 || status === '404'+ const hasError = status && Number(status) >= 400++ if (isObjectDeleted) {+ return 'Object deleted'+ } else if (hasError) {+ return 'Unavailable'+ }++ const etag = enrichedData?.storage_etag+ return etag ? `${etag.substring(0, 12)}...` : null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'content_disposition',+ label: 'Content Disposition',+ getValue: (data, enrichedData) => {+ const status = enrichedData?.status || data?.status+ const isObjectDeleted = status === 404 || status === '404'+ const hasError = status && Number(status) >= 400++ if (isObjectDeleted) {+ return 'Object deleted'+ } else if (hasError) {+ return 'Unavailable'+ }++ return enrichedData?.storage_content_disposition || null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'method',+ label: 'Method',+ getValue: (data, enrichedData) => enrichedData?.method || data?.method,+ requiresEnrichedData: false,+ },+ {+ id: 'user_agent',+ label: 'User Agent',+ getValue: (data, enrichedData) => {+ const ua = enrichedData?.headers_user_agent || data?.headers_user_agent+ return ua ? (ua.length > 30 ? `${ua.substring(0, 30)}...` : ua) : null+ },+ requiresEnrichedData: false,+ },+]++// =============================================================================+// POSTGRES FIELDS+// =============================================================================++// Primary Postgres Fields (Always Visible)+export const postgresPrimaryFields: BlockFieldConfig[] = [+ {+ id: 'status',+ label: 'Status',+ getValue: (data, enrichedData) => enrichedData?.status || data?.status,+ },+ {+ id: 'command_tag',+ label: 'Command',+ getValue: (data, enrichedData) => enrichedData?.command_tag || data?.command_tag,+ requiresEnrichedData: true,+ },+ {+ id: 'database_name',+ label: 'Database',+ getValue: (data, enrichedData) => enrichedData?.database_name || data?.database_name,+ requiresEnrichedData: true,+ },+ {+ id: 'database_user',+ label: 'User',+ getValue: (data, enrichedData) => enrichedData?.database_user || data?.database_user,+ requiresEnrichedData: true,+ },+]++// Postgres Details (Collapsible)+export const postgresDetailsFields: BlockFieldConfig[] = [+ {+ id: 'backend_type',+ label: 'Backend Type',+ getValue: (data, enrichedData) => enrichedData?.backend_type || data?.backend_type,+ requiresEnrichedData: true,+ },+ {+ id: 'connection_from',+ label: 'Connection From',+ getValue: (data, enrichedData) => enrichedData?.connection_from || data?.connection_from,+ requiresEnrichedData: true,+ },+ {+ id: 'session_id',+ label: 'Session ID',+ getValue: (data, enrichedData) => {+ const sessionId = enrichedData?.session_id || data?.session_id+ return sessionId ? `${sessionId.substring(0, 12)}...` : null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'process_id',+ label: 'Process ID',+ getValue: (data, enrichedData) => enrichedData?.process_id || data?.process_id,+ requiresEnrichedData: true,+ },+ {+ id: 'query_id',+ label: 'Query ID',+ getValue: (data, enrichedData) => {+ const queryId = enrichedData?.query_id || data?.query_id+ return queryId ? String(queryId) : null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'transaction_id',+ label: 'Transaction ID',+ getValue: (data, enrichedData) => {+ const txId = enrichedData?.transaction_id || data?.transaction_id+ return txId ? String(txId) : null+ },+ requiresEnrichedData: true,+ },+ {+ id: 'virtual_transaction_id',+ label: 'Virtual TX ID',+ getValue: (data, enrichedData) =>+ enrichedData?.virtual_transaction_id || data?.virtual_transaction_id,+ requiresEnrichedData: true,+ },+ {+ id: 'session_start_time',+ label: 'Session Started',+ getValue: (data, enrichedData) => {+ const startTime = enrichedData?.session_start_time || data?.session_start_time+ return startTime ? new Date(startTime).toLocaleString() : null+ },+ requiresEnrichedData: true,+ },+]diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/types.ts b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/types.tsnew file mode 100644index 00000000000..d1541fa79a2--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/types.ts@@ -0,0 +1,42 @@+import { Table } from '@tanstack/react-table'+import { DataTableFilterField } from 'components/ui/DataTable/DataTable.types'++/**+ * Service Flow Type Definitions+ */++/**+ * Props for individual service flow blocks (Network, PostgREST, Auth, etc.)+ */+export interface ServiceFlowBlockProps {+ data: any // Original log data from the database+ enrichedData?: any // Enhanced data from service flow queries+ isLoading?: boolean // Whether enriched data is still loading+ error?: string // Error message if enriched data failed to load+ isLast?: boolean // Whether this is the last block in the flow+ filterFields: DataTableFilterField<any>[] // Available filter fields for clickable values+ table: Table<any> // Table instance for filtering actions+}++/**+ * Configuration for individual fields displayed in service blocks+ */+export interface BlockFieldConfig {+ id: string // Unique identifier for the field+ label: string // Display label for the field+ getValue: (data: any, enrichedData?: any) => string | number | null | undefined // Function to extract value+ requiresEnrichedData?: boolean // Whether field needs enriched data to display+ maxLength?: number // Maximum length for truncation+}++/**+ * Props for the BlockField component+ */+export interface BlockFieldProps {+ config: BlockFieldConfig+ data: any+ enrichedData?: any+ isLoading?: boolean+ filterFields: DataTableFilterField<any>[]+ table: Table<any>+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/utils/storageUtils.ts b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/utils/storageUtils.tsnew file mode 100644index 00000000000..c3976647511--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlow/utils/storageUtils.ts@@ -0,0 +1,26 @@+/**+ * Storage-specific utility functions for service flow+ */++/**+ * getStorageMetadata - Get storage metadata from enriched data or fallback+ *+ * This is the only storage utility we keep since it's specific to our service flow data structure.+ * All other storage utilities (file extensions, type detection, etc.) should use the+ * existing storage explorer utilities or standard helpers.+ */+export const getStorageMetadata = (data: any, enrichedData?: any): any => {+ // First try to get from enrichedData (service flow)+ const storageMetadata = enrichedData?.storage_metadata+ if (storageMetadata) {+ return storageMetadata+ }++ // Fallback to data metadata+ const dataMetadata = data?.metadata+ if (dataMetadata) {+ return dataMetadata+ }++ return {}+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/ServiceFlowPanel.tsx b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlowPanel.tsxnew file mode 100644index 00000000000..98ab6f2b58a--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/ServiceFlowPanel.tsx@@ -0,0 +1,233 @@+import { useState } from 'react'++import { useParams } from 'common'+import { useDataTable } from 'components/ui/DataTable/providers/DataTableProvider'+import { ServiceFlowType, useUnifiedLogInspectionQuery } from 'data/logs'+import {+ CodeBlock,+ ResizableHandle,+ ResizablePanel,+ Skeleton,+ Tabs_Shadcn_ as Tabs,+ TabsContent_Shadcn_ as TabsContent,+ TabsList_Shadcn_ as TabsList,+ TabsTrigger_Shadcn_ as TabsTrigger,+ cn,+} from 'ui'+import {+ MemoizedEdgeFunctionBlock,+ MemoizedGoTrueBlock,+ MemoizedNetworkBlock,+ MemoizedPostgRESTBlock,+ MemoizedPostgresBlock,+ MemoizedStorageBlock,+} from './ServiceFlow/components/ServiceBlocks'+import { ServiceFlowHeader } from './ServiceFlow/components/ServiceFlowHeader'+import { MemoizedRequestStartedBlock } from './ServiceFlow/components/blocks/RequestStartedBlock'+import { MemoizedResponseCompletedBlock } from './ServiceFlow/components/blocks/ResponseCompletedBlock'+import { ColumnSchema } from './UnifiedLogs.schema'+import { QuerySearchParamsType } from './UnifiedLogs.types'++interface ServiceFlowPanelProps {+ selectedRow: ColumnSchema+ selectedRowKey: string+ searchParameters: QuerySearchParamsType+}++export function ServiceFlowPanel({+ selectedRow,+ selectedRowKey,+ searchParameters,+}: ServiceFlowPanelProps) {+ const { table, filterFields } = useDataTable()+ const { ref: projectRef } = useParams()+ const [activeTab, setActiveTab] = useState('service-flow')++ const logType = selectedRow?.log_type+ const serviceFlowType: ServiceFlowType | undefined =+ logType === 'edge function' ? 'edge-function' : (logType as ServiceFlowType)+ const shouldShowServiceFlow = !!serviceFlowType++ // Query the logs API directly+ const {+ data: serviceFlowData,+ isLoading,+ error,+ } = useUnifiedLogInspectionQuery(+ {+ projectRef: projectRef,+ logId: selectedRow?.id,+ type: serviceFlowType,+ search: searchParameters,+ },+ {+ enabled: Boolean(projectRef) && Boolean(selectedRow?.id) && Boolean(serviceFlowType),+ }+ )++ // Prepare JSON data for Raw JSON tab+ const jsonData =+ shouldShowServiceFlow && serviceFlowData?.result?.[0] ? serviceFlowData.result[0] : selectedRow++ if (selectedRowKey) {+ return (+ <>+ <ResizableHandle withHandle className="z-10" />+ <ResizablePanel+ id="log-sidepanel"+ order={2}+ defaultSize={1}+ maxSize={40}+ className={cn(+ 'bg-dash-sidebar',+ 'z-40',+ 'border-l fixed right-0 top-0 bottom-0',+ 'md:absolute md:h-auto',+ // ' md:w-3/4',+ 'xl:z-[1]',+ 'min-w-[28rem] max-w-[45rem]',+ 'xl:relative xl:border-l-0'+ )}+ >+ <div className="h-full overflow-auto">+ {/* Service Flow Header with navigation */}+ <ServiceFlowHeader+ selectedRow={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ />++ <div className="relative">+ <Tabs+ defaultValue="service-flow"+ value={activeTab}+ onValueChange={setActiveTab}+ className="w-full h-full flex flex-col pt-2"+ >+ <TabsList className="flex gap-3 px-5">+ {shouldShowServiceFlow && (+ <TabsTrigger value="service-flow">Overview</TabsTrigger>+ )}+ <TabsTrigger value="raw-json">Raw JSON</TabsTrigger>+ </TabsList>++ {shouldShowServiceFlow && (+ <TabsContent value="service-flow">+ <div className="p-4">+ {error ? (+ <div className="text-center py-8 text-destructive">+ Error: {error.toString()}+ </div>+ ) : (+ <>+ {serviceFlowType === 'postgres' ? (+ // Postgres flows: Connection Started -> Postgres -> Response+ <>+ <MemoizedRequestStartedBlock data={selectedRow} />++ <MemoizedPostgresBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ isLast={false}+ filterFields={filterFields}+ table={table}+ />++ <MemoizedResponseCompletedBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ />+ </>+ ) : (+ // HTTP-based flows: Request Started -> Network -> Service -> Response+ <>+ <MemoizedRequestStartedBlock data={selectedRow} />++ <MemoizedNetworkBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />++ {serviceFlowType === 'auth' ? (+ <MemoizedGoTrueBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ) : serviceFlowType === 'edge-function' ? (+ <MemoizedEdgeFunctionBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ) : serviceFlowType === 'storage' ? (+ <MemoizedStorageBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ ) : (+ <>+ <MemoizedPostgRESTBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />++ <MemoizedPostgresBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ isLoading={isLoading}+ filterFields={filterFields}+ table={table}+ />+ </>+ )}++ <MemoizedResponseCompletedBlock+ data={selectedRow}+ enrichedData={serviceFlowData?.result?.[0]}+ />+ </>+ )}+ </>+ )}+ </div>+ </TabsContent>+ )}++ <TabsContent value="raw-json" className="flex-grow overflow-auto">+ {isLoading && shouldShowServiceFlow && (+ <div className="flex items-center gap-3 text-foreground-light p-3 bg-surface-100 border-b border-border">+ <Skeleton className="h-4 w-4 rounded-full animate-pulse" />+ <span className="text-sm">Enriching log...</span>+ </div>+ )}+ <CodeBlock+ language="json"+ className="max-h-[800px] overflow-auto border-none rounded-none [&_pre]:!leading-tight [&_code]:!leading-tight"+ >+ {JSON.stringify(jsonData, null, 2)}+ </CodeBlock>+ </TabsContent>+ </Tabs>+ </div>+ </div>+ </ResizablePanel>+ </>+ )+ }++ return null+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsxindex 2eeaf8a7bff..a429b1d02c5 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.constants.tsx@@ -35,25 +35,15 @@ export const CHART_CONFIG = {export const REGIONS = ['ams', 'fra', 'gru', 'hkg', 'iad', 'syd'] as constexport const METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'] as const-export const LOG_TYPES = [- 'auth',- 'edge',- 'edge_function',- 'function_events',- 'postgres',- 'postgres_upgrade',- 'postgrest',- 'storage',- 'supavisor',-] as const+export const LOG_TYPES = ['postgres', 'postgrest', 'auth', 'storage', 'edge function'] as constconst parseAsSort = createParser({- parse(queryValue) {+ parse(queryValue: string) {const [id, desc] = queryValue.split(SORT_DELIMITER)if (!id && !desc) return nullreturn { id, desc: desc === 'desc' }},- serialize(value) {+ serialize(value: { id: string; desc: boolean }) {return `${value.id}.${value.desc ? 'desc' : 'asc'}`},})@@ -85,6 +75,6 @@ export const SEARCH_PARAMS_PARSER = {cursor: parseAsTimestamp.withDefault(new Date()),live: parseAsBoolean.withDefault(false),- // REQUIRED FOR SELECTION+ uuid: parseAsString,id: parseAsString,}diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsxindex 48cea7695ce..686b0ac126a 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.fields.tsx@@ -20,6 +20,41 @@ export const filterFields = [defaultOpen: true,commandDisabled: true,},+ {+ label: 'Log Type',+ value: 'log_type',+ type: 'checkbox',+ defaultOpen: true,+ options: LOG_TYPES.map((type) => ({ label: type, value: type })),+ component: (props: Option) => {+ return (+ <div className="flex w-full items-center justify-between gap-2 font-mono">+ <span className="capitalize text-foreground/70 group-hover:text-accent-foreground text-xs">+ {props.label.replace('_', ' ')}+ </span>+ </div>+ )+ },+ },+ {+ label: 'Status',+ value: 'status',+ type: 'checkbox',+ defaultOpen: true,+ options: [+ { label: '2xx', value: 200 },+ { label: '4xx', value: 400 },+ { label: '4xx', value: 500 },+ ], // REMINDER: this is a placeholder to set the type in the client.tsx+ component: (props: Option) => {+ if (typeof props.value === 'boolean') return null+ if (typeof props.value === 'undefined') return null+ if (typeof props.value === 'string') return null+ return (+ <span className={cn('font-mono', getStatusColor(props.value).text)}>{props.value}</span>+ )+ },+ },{label: 'Level',value: 'level',@@ -43,21 +78,13 @@ export const filterFields = [},},{- label: 'Log Type',- value: 'log_type',+ label: 'Method',+ value: 'method',type: 'checkbox',defaultOpen: true,- options: LOG_TYPES.map((type) => ({ label: type, value: type })),+ options: METHODS.map((region) => ({ label: region, value: region })),component: (props: Option) => {- return (- <div className="flex w-full items-center justify-between gap-2 font-mono">- <span className="capitalize text-foreground/70 group-hover:text-accent-foreground text-xs">- {props.label.replace('_', ' ')}- </span>- {/* [Joshen] Temporarily hiding, this feels excessive */}- {/* <span className="text-xs text-muted-foreground/70">{props.value}</span> */}- </div>- )+ return <span className="font-mono">{props.value}</span>},},{@@ -75,34 +102,6 @@ export const filterFields = [value: 'auth_user',type: 'input',},- {- label: 'Status Code',- value: 'status',- type: 'checkbox',- options: [- { label: '200', value: 200 },- { label: '400', value: 400 },- { label: '404', value: 404 },- { label: '500', value: 500 },- ], // REMINDER: this is a placeholder to set the type in the client.tsx- component: (props: Option) => {- if (typeof props.value === 'boolean') return null- if (typeof props.value === 'undefined') return null- if (typeof props.value === 'string') return null- return (- <span className={cn('font-mono', getStatusColor(props.value).text)}>{props.value}</span>- )- },- },- {- label: 'Method',- value: 'method',- type: 'checkbox',- options: METHODS.map((region) => ({ label: region, value: region })),- component: (props: Option) => {- return <span className="font-mono">{props.value}</span>- },- },] satisfies DataTableFilterField<ColumnSchema>[]export const sheetFields = [@@ -150,26 +149,6 @@ export const sheetFields = [),skeletonClassName: 'w-56',},- {- id: 'status',- label: 'Status',- type: 'checkbox',- component: (props) => {- return (- <span className={cn('font-mono', getStatusColor(props.status).text)}>{props.status}</span>- )- },- skeletonClassName: 'w-12',- },- {- id: 'method',- label: 'Method',- type: 'checkbox',- component: (props) => {- return <span className="font-mono">{props.method}</span>- },- skeletonClassName: 'w-10',- },{id: 'host',label: 'Host',diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.tsindex 3930f8fa5cd..3c833ad632a 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.queries.ts@@ -313,6 +313,7 @@ const getPostgresLogsQuery = () => {CASEWHEN pgl_parsed.error_severity = 'LOG' THEN 'success'WHEN pgl_parsed.error_severity = 'WARNING' THEN 'warning'+ WHEN pgl_parsed.error_severity = 'FATAL' THEN 'error'WHEN pgl_parsed.error_severity = 'ERROR' THEN 'error'ELSE nullEND as level,@@ -346,7 +347,7 @@ const getEdgeFunctionLogsQuery = () => {WHEN fel_response.status_code >= 500 THEN 'error'ELSE 'success'END as level,- fel_request.path as pathname,+ fel_request.pathname as pathname,fel_request.host as host,COALESCE(function_logs_agg.last_event_message, '') as event_message,fel_request.method as method,@@ -419,34 +420,8 @@ const getAuthLogsQuery = () => {}/**- * Supavisor logs query fragment+ * Supabase storage logs query fragment*/-const getSupavisorLogsQuery = () => {- return `- select- id,- svl.timestamp as timestamp,- 'supavisor' as log_type,- 'undefined' as status,- CASE- WHEN LOWER(svl_metadata.level) = 'error' THEN 'error'- WHEN LOWER(svl_metadata.level) = 'warn' OR LOWER(svl_metadata.level) = 'warning' THEN 'warning'- ELSE 'success'- END as level,- null as pathname,- null as host,- null as event_message,- null as method,- 'api_role' as api_role,- null as auth_user,- null as log_count,- null as logs- from supavisor_logs as svl- cross join unnest(metadata) as svl_metadata- `-}--// WHERE pathname includes `/storage/`const getSupabaseStorageLogsQuery = () => {return `select@@ -487,8 +462,6 @@ const getSupabaseStorageLogsQuery = () => {const getUnifiedLogsCTE = () => {return `WITH unified_logs AS (- ${getEdgeLogsQuery()}- union all${getPostgrestLogsQuery()}union all${getPostgresLogsQuery()}@@ -497,8 +470,6 @@ WITH unified_logs AS (union all${getAuthLogsQuery()}union all- ${getSupavisorLogsQuery()}- union all${getSupabaseStorageLogsQuery()})`diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsxindex f4bd6be13d1..2410c0edd38 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.tsx@@ -9,6 +9,7 @@ import {Row,RowSelectionState,SortingState,+ Table,useReactTable,VisibilityState,} from '@tanstack/react-table'@@ -20,7 +21,6 @@ import { arrSome, inDateRange } from 'components/ui/DataTable/DataTable.utils'import { DataTableFilterCommand } from 'components/ui/DataTable/DataTableFilters/DataTableFilterCommand'import { DataTableHeaderLayout } from 'components/ui/DataTable/DataTableHeaderLayout'import { DataTableInfinite } from 'components/ui/DataTable/DataTableInfinite'-import { DataTableSheetDetails } from 'components/ui/DataTable/DataTableSheetDetails'import { DataTableSideBarLayout } from 'components/ui/DataTable/DataTableSideBarLayout'import { DataTableToolbar } from 'components/ui/DataTable/DataTableToolbar'import { FilterSideBar } from 'components/ui/DataTable/FilterSideBar'@@ -39,20 +39,16 @@ import {ResizablePanel,ResizablePanelGroup,Separator,- Tabs_Shadcn_ as Tabs,- TabsContent_Shadcn_ as TabsContent,- TabsList_Shadcn_ as TabsList,- TabsTrigger_Shadcn_ as TabsTrigger,} from 'ui'import { RefreshButton } from '../../ui/DataTable/RefreshButton'import { UNIFIED_LOGS_COLUMNS } from './components/Columns'-import { MemoizedDataTableSheetContent } from './components/DataTableSheetContent'-import { FunctionLogsTab } from './components/FunctionLogsTab'+import { LogsListPanel } from './components/LogsListPanel'+import { ServiceFlowPanel } from './ServiceFlowPanel'import { CHART_CONFIG, SEARCH_PARAMS_PARSER } from './UnifiedLogs.constants'-import { filterFields as defaultFilterFields, sheetFields } from './UnifiedLogs.fields'+import { filterFields as defaultFilterFields } from './UnifiedLogs.fields'import { useLiveMode, useResetFocus } from './UnifiedLogs.hooks'import { QuerySearchParamsType } from './UnifiedLogs.types'-import { getFacetedUniqueValues, getLevelRowClassName, logEventBus } from './UnifiedLogs.utils'+import { getFacetedUniqueValues, getLevelRowClassName } from './UnifiedLogs.utils'export const UnifiedLogs = () => {useResetFocus()@@ -69,11 +65,13 @@ export const UnifiedLogs = () => {.filter(({ value }) => value ?? undefined)const [topBarHeight, setTopBarHeight] = useState(0)- const [activeTab, setActiveTab] = useState('details')+const [sorting, setSorting] = useState<SortingState>(defaultColumnSorting)const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>(defaultColumnFilters)const [rowSelection, setRowSelection] = useState<RowSelectionState>(defaultRowSelection)+ const [showBottomLogsPanel, setShowBottomLogsPanelState] = useState(false)+const [columnVisibility, setColumnVisibility] = useLocalStorageQuery<VisibilityState>('data-table-visibility',defaultColumnVisibility@@ -85,15 +83,19 @@ export const UnifiedLogs = () => {// Create a stable query key object by removing nulls/undefined, id, and live// Mainly to prevent the react queries from unnecessarily re-fetching- const searchParameters = Object.entries(search).reduce(- (acc, [key, value]) => {- if (!['id', 'live'].includes(key) && value !== null && value !== undefined) {- acc[key] = value- }- return acc- },- {} as Record<string, any>- ) as QuerySearchParamsType+ const searchParameters = useMemo(+ () =>+ Object.entries(search).reduce(+ (acc, [key, value]) => {+ if (!['id', 'live'].includes(key) && value !== null && value !== undefined) {+ acc[key] = value+ }+ return acc+ },+ {} as Record<string, any>+ ) as QuerySearchParamsType,+ [search]+ )const {data: unifiedLogsData,@@ -164,7 +166,7 @@ export const UnifiedLogs = () => {return cn(levelClassName, isPast ? 'opacity-50' : 'opacity-100', 'h-[30px]')}- const table = useReactTable({+ const table: Table<any> = useReactTable({data: flatData,columns: UNIFIED_LOGS_COLUMNS,state: {@@ -192,13 +194,12 @@ export const UnifiedLogs = () => {getFacetedMinMaxValues: getTTableFacetedMinMaxValues(),})+ const selectedRowKey = Object.keys(rowSelection)?.[0]const selectedRow = useMemo(() => {if ((isLoading || isFetching) && !flatData.length) return- const selectedRowKey = Object.keys(rowSelection)?.[0]- return table.getCoreRowModel().flatRows.find((row) => row.id === selectedRowKey)- }, [rowSelection, flatData])- const selectedRowKey = Object.keys(rowSelection)?.[0]+ return table.getCoreRowModel().flatRows.find((row) => row.id === selectedRowKey)+ }, [isLoading, isFetching, flatData.length, table, selectedRowKey])// REMINDER: this is currently needed for the cmdk search// TODO: auto search via API when the user changes the filter instead of hardcoded@@ -252,26 +253,24 @@ export const UnifiedLogs = () => {useEffect(() => {if (isLoading || isFetching) return- if (Object.keys(rowSelection)?.length && !selectedRow) {+ const selectedRowId = Object.keys(rowSelection)?.[0]++ if (selectedRowId && !selectedRow) {+ // Clear both uuid and logId when no row is selectedsetSearch({ id: null })setRowSelection({})- } else {- setSearch({ id: Object.keys(rowSelection)?.[0] || null })+ } else if (selectedRowId && selectedRow) {+ setSearch({+ id: selectedRowId,+ })+ // Don't clear rowSelection here - let it persist to maintain the selection+ } else if (!selectedRowId && search.id) {+ // Clear the URL parameter when no row is selected+ setSearch({ id: null })}// eslint-disable-next-line react-hooks/exhaustive-deps}, [rowSelection, selectedRow, isLoading, isFetching])- // Set up event listener for trace tab selection- useEffect(() => {- const unsubscribe = logEventBus.on('selectTraceTab', (rowId) => {- setRowSelection({ [rowId]: true })- setActiveTab('trace')- })- return () => {- unsubscribe()- }- }, [setRowSelection])-return (<DataTableProvidertable={table}@@ -289,125 +288,84 @@ export const UnifiedLogs = () => {getFacetedUniqueValues={getFacetedUniqueValues(facets)}><DataTableSideBarLayout topBarHeight={topBarHeight}>- <FilterSideBar />- <div className="flex max-w-full flex-1 flex-col border-border sm:border-l overflow-hidden">- <DataTableHeaderLayout setTopBarHeight={setTopBarHeight}>- <DataTableFilterCommand- placeholder="Search logs..."- searchParamsParser={SEARCH_PARAMS_PARSER}- />- <DataTableToolbar- renderActions={() => [- <RefreshButton isLoading={isRefetchingData} onRefresh={refetchAllData} />,- fetchPreviousPage ? (- <LiveButton- key="live"- fetchPreviousPage={fetchPreviousPage}- searchParamsParser={SEARCH_PARAMS_PARSER}- />- ) : null,- ]}- />- <TimelineChart- data={unifiedLogsChart}- className="-mb-2"- columnId="timestamp"- chartConfig={filteredChartConfig}- />- </DataTableHeaderLayout>-- <Separator />-- <ResizablePanelGroup direction="horizontal" className="w-full h-full">- <ResizablePanel defaultSize={selectedRowKey ? 60 : 100} minSize={30} className="h-full">- <ResizablePanelGroup key="main-logs" direction="vertical" className="h-full">- <ResizablePanel defaultSize={100} minSize={30}>- <DataTableInfinite- columns={UNIFIED_LOGS_COLUMNS}- totalRows={totalDBRowCount}- filterRows={filterDBRowCount}- totalRowsFetched={totalFetched}- fetchNextPage={fetchNextPage}- hasNextPage={hasNextPage}- renderLiveRow={(props) => {- if (!liveMode.timestamp) return null- if (props?.row?.original.id !== liveMode?.row?.id) return null- return <LiveRow colSpan={UNIFIED_LOGS_COLUMNS.length - 1} />- }}- setColumnOrder={setColumnOrder}- setColumnVisibility={setColumnVisibility}- searchParamsParser={SEARCH_PARAMS_PARSER}- />- </ResizablePanel>- {selectedRow?.original?.logs && selectedRow?.original?.logs?.length > 0 && (- <>- <ResizableHandle withHandle />- <ResizablePanel defaultSize={20} minSize={20}>- <div className="h-full flex flex-col overflow-hidden">- <div className="px-5 py-3 border-b border-border flex justify-between items-center">- <h3 className="text-sm font-medium">- Function Logs (- {selectedRow?.original?.logs &&- Array.isArray(selectedRow?.original?.logs)- ? selectedRow?.original?.logs?.length- : 0}- )- </h3>- </div>- <div className="flex-grow overflow-auto">- <FunctionLogsTab logs={selectedRow?.original?.logs} />- </div>- </div>- </ResizablePanel>- </>- )}- </ResizablePanelGroup>- </ResizablePanel>-- {selectedRowKey && (- <>- <ResizableHandle withHandle />- <ResizablePanel defaultSize={45} minSize={45}>- <div className="h-full overflow-auto">- <DataTableSheetDetails- title={selectedRow?.original?.pathname}- titleClassName="font-mono text-sm"- >- <Tabs- defaultValue="details"- value={activeTab}- onValueChange={setActiveTab}- className="w-full h-full flex flex-col pt-2"- >- <TabsList className="flex gap-3 px-5">- <TabsTrigger value="details">Log Details</TabsTrigger>- </TabsList>-- <TabsContent- value="details"- className="flex-grow overflow-auto data-[state=active]:flex-grow px-5"- >- <MemoizedDataTableSheetContent- table={table}- data={selectedRow?.original}- filterFields={filterFields}- fields={sheetFields}- metadata={{- totalRows: totalDBRowCount ?? 0,- filterRows: filterDBRowCount ?? 0,- totalRowsFetched: totalFetched ?? 0,- currentPercentiles: {} as any,- }}- />- </TabsContent>- </Tabs>- </DataTableSheetDetails>- </div>- </ResizablePanel>- </>- )}- </ResizablePanelGroup>- </div>+ <ResizablePanelGroup direction="horizontal" autoSaveId="logs-layout">+ <FilterSideBar />+ <ResizableHandle+ withHandle+ // disabled={resizableSidebar ? false : true}+ className="group-data-[expanded=false]/controls:hidden hidden md:flex"+ />+ <ResizablePanel+ order={2}+ id="panel-right"+ className="flex max-w-full flex-1 flex-col overflow-hidden"+ >+ <DataTableHeaderLayout setTopBarHeight={setTopBarHeight}>+ <DataTableFilterCommand+ placeholder="Search logs..."+ searchParamsParser={SEARCH_PARAMS_PARSER}+ />+ <DataTableToolbar+ renderActions={() => [+ <RefreshButton isLoading={isRefetchingData} onRefresh={refetchAllData} />,+ fetchPreviousPage ? (+ <LiveButton+ key="live"+ fetchPreviousPage={fetchPreviousPage}+ searchParamsParser={SEARCH_PARAMS_PARSER}+ />+ ) : null,+ ]}+ />+ <TimelineChart+ data={unifiedLogsChart}+ className="-mb-2"+ columnId="timestamp"+ chartConfig={filteredChartConfig}+ />+ </DataTableHeaderLayout>++ <Separator />++ <ResizablePanelGroup direction="horizontal" className="w-full h-full">+ <ResizablePanel+ defaultSize={selectedRowKey ? 60 : 100}+ minSize={30}+ className="h-full"+ >+ <ResizablePanelGroup key="main-logs" direction="vertical" className="h-full">+ <ResizablePanel defaultSize={100} minSize={30} className="bg">+ <DataTableInfinite+ columns={UNIFIED_LOGS_COLUMNS}+ totalRows={totalDBRowCount}+ filterRows={filterDBRowCount}+ totalRowsFetched={totalFetched}+ fetchNextPage={fetchNextPage}+ hasNextPage={hasNextPage}+ renderLiveRow={(props) => {+ if (!liveMode.timestamp) return null+ if (props?.row?.original.id !== liveMode?.row?.id) return null+ return <LiveRow colSpan={UNIFIED_LOGS_COLUMNS.length - 1} />+ }}+ setColumnOrder={setColumnOrder}+ setColumnVisibility={setColumnVisibility}+ searchParamsParser={SEARCH_PARAMS_PARSER}+ />+ </ResizablePanel>+ <LogsListPanel selectedRow={selectedRow} />+ </ResizablePanelGroup>+ </ResizablePanel>++ {selectedRowKey && (+ <ServiceFlowPanel+ selectedRow={selectedRow?.original}+ selectedRowKey={selectedRowKey}+ searchParameters={searchParameters}+ />+ )}+ </ResizablePanelGroup>+ </ResizablePanel>+ </ResizablePanelGroup></DataTableSideBarLayout></DataTableProvider>)diff --git a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.tsindex a32831a39a8..8d6f7577932 100644--- a/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts+++ b/apps/studio/components/interfaces/UnifiedLogs/UnifiedLogs.utils.ts@@ -50,6 +50,18 @@ export const getLevelLabel = (value: (typeof LEVELS)[number]): string => {}}+// 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':@@ -73,3 +85,23 @@ export function getLevelRowClassName(value: (typeof LEVELS)[number]): string {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',+ }++ return specialCases[serviceType.toLowerCase()] || serviceType+}diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsxindex 49334f1b61b..6a24ec86799 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/Columns.tsx@@ -20,6 +20,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [},enableHiding: false,enableResizing: false,+ enableSorting: false,filterFn: (row, columnId, filterValue) => true,size: 48,minSize: 48,@@ -39,6 +40,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [},filterFn: (row, columnId, filterValue) => true,enableResizing: false,+ enableSorting: false,size: 130,minSize: 130,maxSize: 130,@@ -66,6 +68,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [minSize: 40,maxSize: 40,enableResizing: false,+ enableSorting: false,meta: {headerClassName:'w-[--header-log_type-size] max-w-[--header-log_type-size] min-w-[--header-log_type-size]',@@ -83,6 +86,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [return <span className="text-foreground-lighter">{value}</span>},enableResizing: false,+ enableSorting: false,size: 70,minSize: 70,meta: {@@ -113,8 +117,9 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [},filterFn: (row, columnId, filterValue) => true,enableResizing: false,- size: 50,- minSize: 50,+ enableSorting: false,+ size: 55,+ minSize: 55,meta: {headerClassName:'w-[--header-status-size] max-w-[--header-status-size] min-w-[--header-status-size]',@@ -130,6 +135,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [const value = row.getValue<ColumnSchema['host']>('host')return <TextWithTooltip text={value} />},+ enableSorting: false,size: 220,minSize: 220,meta: {@@ -144,6 +150,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [const value = row.getValue<ColumnFilterSchema['pathname']>('pathname') ?? ''return <TextWithTooltip text={value} />},+ enableSorting: false,size: 320,minSize: 320,meta: {@@ -181,6 +188,7 @@ export const UNIFIED_LOGS_COLUMNS: ColumnDef<ColumnSchema>[] = [)},enableResizing: true,+ enableSorting: false,size: 200,minSize: 200,meta: {diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/HoverCardTimestamp.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/HoverCardTimestamp.tsxindex 337fe574ed6..57f7c28af71 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/HoverCardTimestamp.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/HoverCardTimestamp.tsx@@ -1,3 +1,4 @@+import { cn } from 'ui'import { TimestampInfo } from 'ui-patterns'interface HoverCardTimestampProps {@@ -7,7 +8,7 @@ interface HoverCardTimestampProps {export function HoverCardTimestamp({ date, className }: HoverCardTimestampProps) {return (- <div className="relative w-fit">+ <div className={cn('relative w-fit', className)}><TimestampInfo utcTimestamp={date.getTime()} /></div>)diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsxindex 5f9d067407a..2198117c364 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogTypeIcon.tsx@@ -17,19 +17,20 @@ export const LogTypeIcon = ({strokeWidth = 1.5,className,}: LogTypeIconProps) => {- const iconMap = {- edge: () => <Globe size={size} strokeWidth={strokeWidth} className={className} />,+ // [Alaister]: commented out types coming in the future+ const iconMap: Record<(typeof LOG_TYPES)[number], () => React.ReactNode> = {+ // edge: () => <Globe size={size} strokeWidth={strokeWidth} className={className} />,postgrest: () => <BookHeart size={size} strokeWidth={strokeWidth} className={className} />,auth: () => <Auth size={size} strokeWidth={strokeWidth} className={className} />,- edge_function: () => (+ 'edge function': () => (<EdgeFunctions size={size} strokeWidth={strokeWidth} className={className} />),postgres: () => <Database size={size} strokeWidth={strokeWidth} className={className} />,- function_events: () => (- <EdgeFunctions size={size} strokeWidth={strokeWidth} className={className} />- ),- supavisor: () => <Cpu size={size} strokeWidth={strokeWidth} className={className} />,- postgres_upgrade: () => <Cpu size={size} strokeWidth={strokeWidth} className={className} />,+ // function_events: () => (+ // <EdgeFunctions size={size} strokeWidth={strokeWidth} className={className} />+ // ),+ // supavisor: () => <Cpu size={size} strokeWidth={strokeWidth} className={className} />,+ // postgres_upgrade: () => <Cpu size={size} strokeWidth={strokeWidth} className={className} />,storage: () => <Storage size={size} strokeWidth={strokeWidth} className={className} />,// cron: () => <Clock size={size} strokeWidth={strokeWidth} className={className} />,diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsxsimilarity index 74%rename from apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsxrename to apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsxindex a9998ffe56b..cadfcf0ccbb 100644--- a/apps/studio/components/interfaces/UnifiedLogs/components/FunctionLogsTab.tsx+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsList.tsx@@ -1,7 +1,7 @@import { DataTableColumnStatusCode } from 'components/ui/DataTable/DataTableColumn/DataTableColumnStatusCode'import { HoverCardTimestamp } from './HoverCardTimestamp'-interface FunctionLogEntry {+interface LogEntry {id: stringtimestamp: stringevent_message: string@@ -9,11 +9,11 @@ interface FunctionLogEntry {event_type: string}-interface FunctionLogsTabProps {- logs?: FunctionLogEntry[]+interface LogsListProps {+ logs?: LogEntry[]}-export const FunctionLogsTab = ({ logs = [] }: FunctionLogsTabProps) => {+export const LogsList = ({ logs = [] }: LogsListProps) => {if (!logs || logs.length === 0) {return (<div className="flex flex-col items-center justify-center h-full p-6">@@ -29,18 +29,17 @@ export const FunctionLogsTab = ({ logs = [] }: FunctionLogsTabProps) => {const date = new Date(Number(log.timestamp) / 1000)return (- <div key={log.id} className="py-1 border-b border-border last:border-0">+ <div key={log.id} className="py-1.5 px-4 border-b border-border last:border-0"><div className="flex items-start gap-5">- <div className="flex flex-row items-center gap-5">- <HoverCardTimestamp date={date} className="min-w-20 ml-14" />-+ <div className="flex flex-row items-center gap-5 flex-shrink-0">+ <HoverCardTimestamp date={date} className="flex-shrink-0" /><DataTableColumnStatusCodevalue={log.level}level={log.level}- className="min-w-20"+ className="min-w-20 flex-shrink-0"/></div>- <div className="mt-1 whitespace-pre-wrap break-all pl-2 text-[0.8rem]">+ <div className="mt-1 whitespace-pre-wrap break-all pl-2 text-[0.8rem] flex-shrink-0 overflow-x-auto">{log.event_message}</div></div>diff --git a/apps/studio/components/interfaces/UnifiedLogs/components/LogsListPanel.tsx b/apps/studio/components/interfaces/UnifiedLogs/components/LogsListPanel.tsxnew file mode 100644index 00000000000..1da4ea93035--- /dev/null+++ b/apps/studio/components/interfaces/UnifiedLogs/components/LogsListPanel.tsx@@ -0,0 +1,51 @@+import type { Row } from '@tanstack/react-table'+import { ChevronDown } from 'lucide-react'+import { useState } from 'react'++import { Button, cn, ResizableHandle, ResizablePanel } from 'ui'+import { LogsList } from './LogsList'++export const LogsListPanel = ({ selectedRow }: { selectedRow?: Row<any> }) => {+ const [open, setOpenState] = useState(true)++ return (+ selectedRow?.original?.logs &&+ selectedRow.original.logs.length > 0 && (+ <>+ <ResizableHandle withHandle disabled={!open} />+ <ResizablePanel+ order={2}+ defaultSize={1}+ maxSize={50}+ minSize={open ? 16 : 12}+ className={cn(!open ? '!h-12 max-h-12' : 'h-min-16 h-max-32')}+ >+ <div className="h-full flex flex-col overflow-hidden">+ <div className="min-h-12 flex justify-between items-center px-5">+ <div className="flex flex-row items-center gap-2">+ <h3 className="text-sm font-medium">Event logs</h3>+ <span className="text-muted-foreground text-xs bg-muted rounded-md px-1.5 py-0.5">+ {selectedRow?.original?.logs && Array.isArray(selectedRow?.original?.logs)+ ? selectedRow?.original?.logs?.length+ : 0}+ </span>+ </div>+ <Button+ type="default"+ onClick={() => setOpenState(!open)}+ icon={<ChevronDown className={cn('w-4 h-4', !open ? 'rotate-180' : 'rotate-0')} />}+ >+ {open ? 'Close' : 'Open'}+ </Button>+ </div>+ {open && (+ <div className="flex-grow overflow-auto border-t">+ <LogsList logs={selectedRow?.original?.logs} />+ </div>+ )}+ </div>+ </ResizablePanel>+ </>+ )+ )+}diff --git a/apps/studio/components/ui/DataTable/DataTableColumn/DataTableColumnLevelIndicator.tsx b/apps/studio/components/ui/DataTable/DataTableColumn/DataTableColumnLevelIndicator.tsxindex c0038b7c3dd..8b6f0482d1b 100644--- a/apps/studio/components/ui/DataTable/DataTableColumn/DataTableColumnLevelIndicator.tsx+++ b/apps/studio/components/ui/DataTable/DataTableColumn/DataTableColumnLevelIndicator.tsx@@ -5,13 +5,22 @@ import { getLevelColor } from '../DataTable.utils'export const DataTableColumnLevelIndicator = ({value,className,+ dotClassName,}: {value: (typeof LEVELS)[number]className?: string+ dotClassName?: string}) => {return (<div className={cn('flex items-center justify-center', className)}>- <div className={cn('h-2.5 w-2.5 rounded-[2px]', getLevelColor(value).bg)} />+ <div+ className={cn(+ 'h-2.5 w-2.5 rounded-[2px]',+ getLevelColor(value).bg,+ getLevelColor(value).border,+ dotClassName+ )}+ /></div>)}diff --git a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsxindex c5030af0153..97c16ecd89a 100644--- a/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx+++ b/apps/studio/components/ui/DataTable/DataTableFilters/DataTableFilterControls.tsx@@ -34,12 +34,7 @@ export function DataTableFilterControls() {<AccordionTrigger className="w-full px-2 py-0 hover:no-underline data-[state=closed]:text-muted-foreground data-[state=open]:text-foreground focus-within:data-[state=closed]:text-foreground hover:data-[state=closed]:text-foreground"><div className="flex w-full items-center justify-between gap-2 truncate py-2 pr-2"><div className="flex items-center gap-2 truncate">- <p className="text-sm font-medium">{field.label}</p>- {value !== field.label.toLowerCase() && !field.commandDisabled ? (- <p className="mt-px truncate font-mono text-[10px] text-muted-foreground">- {value}- </p>- ) : null}+ <p className="text-sm">{field.label}</p></div><DataTableFilterResetButton {...field} /></div>diff --git a/apps/studio/components/ui/DataTable/DataTableInfinite.tsx b/apps/studio/components/ui/DataTable/DataTableInfinite.tsxindex 8dec475c052..c36c7199242 100644--- a/apps/studio/components/ui/DataTable/DataTableInfinite.tsx+++ b/apps/studio/components/ui/DataTable/DataTableInfinite.tsx@@ -127,44 +127,59 @@ export function DataTableInfinite<TData, TValue, TMeta>({<Fragment>{renderLiveRow?.()}<TableRow>- <TableCell colSpan={columns.length} className="h-24 text-center">- {isLoading ? 'Retrieving logs...' : 'No results'}+ <TableCell colSpan={columns.length} className="h-[32vh] text-center">+ <div className="flex flex-col items-center justify-center h-full gap-3">+ {isLoading ? (+ <>+ <LoaderCircle className="h-6 w-6 animate-spin text-foreground-muted" />+ <p className="text-foreground-light text-sm">Retrieving logs...</p>+ </>+ ) : (+ <p className="text-foreground-light text-sm">No results found</p>+ )}+ </div></TableCell></TableRow></Fragment>)}- <TableRow className="hover:bg-transparent data-[state=selected]:bg-transparent">- <TableCell colSpan={columns.length} className="text-center !py-2">- {hasNextPage || isFetching || isLoading ? (- <div className="flex flex-col items-center gap-2">- <Button- disabled={isFetching || isLoading}- onClick={() => fetchNextPage()}- size="small"- type="outline"- icon={isFetching ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : null}- >- Load more- </Button>+ {/* Only show load more section if we have rows OR if we're not in initial loading state */}+ {(rows.length > 0 || (!isLoading && !rows.length)) && (+ <TableRow className="hover:bg-transparent data-[state=selected]:bg-transparent">+ <TableCell colSpan={columns.length} className="text-center !py-2">+ {hasNextPage || isFetching ? (+ <div className="flex flex-col items-center gap-2">+ <Button+ disabled={isFetching}+ onClick={() => fetchNextPage()}+ size="small"+ type="outline"+ icon={+ isFetching ? <LoaderCircle className="mr-2 h-4 w-4 animate-spin" /> : null+ }+ >+ Load more+ </Button>+ <p className="text-xs text-foreground-lighter">+ Showing{' '}+ <span className="font-mono font-medium">+ {formatCompactNumber(totalRowsFetched)}+ </span>{' '}+ of{' '}+ <span className="font-mono font-medium">{formatCompactNumber(totalRows)}</span>{' '}+ rows+ </p>+ </div>+ ) : (<p className="text-xs text-foreground-lighter">- Showing{' '}- <span className="font-mono font-medium">- {formatCompactNumber(totalRowsFetched)}- </span>{' '}+ No more data to load (+ <span className="font-mono font-medium">{formatCompactNumber(filterRows)}</span>{' '}of <span className="font-mono font-medium">{formatCompactNumber(totalRows)}</span>{' '}- rows+ rows)</p>- </div>- ) : (- <p className="text-xs text-foreground-lighter">- No more data to load (- <span className="font-mono font-medium">{formatCompactNumber(filterRows)}</span> of{' '}- <span className="font-mono font-medium">{formatCompactNumber(totalRows)}</span>{' '}- rows)- </p>- )}- </TableCell>- </TableRow>+ )}+ </TableCell>+ </TableRow>+ )}</TableBody></Table>)diff --git a/apps/studio/components/ui/DataTable/DataTableResetButton.tsx b/apps/studio/components/ui/DataTable/DataTableResetButton.tsxindex 06a80799f08..0e9c18c8911 100644--- a/apps/studio/components/ui/DataTable/DataTableResetButton.tsx+++ b/apps/studio/components/ui/DataTable/DataTableResetButton.tsx@@ -14,10 +14,10 @@ export function DataTableResetButton() {<Tooltip><TooltipTrigger asChild><Button- type="text"- size="small"+ type="default"+ size="tiny"onClick={() => table.resetColumnFilters()}- icon={<X className="h-4 w-4" />}+ icon={<X />}>Reset</Button>diff --git a/apps/studio/components/ui/DataTable/DataTableSheetDetails.tsx b/apps/studio/components/ui/DataTable/DataTableSheetDetails.tsxindex 922d38bc3ee..4a5ed2200fe 100644--- a/apps/studio/components/ui/DataTable/DataTableSheetDetails.tsx+++ b/apps/studio/components/ui/DataTable/DataTableSheetDetails.tsx@@ -31,22 +31,22 @@ export function DataTableSheetDetails({const selectedRow = useMemo(() => {if (isLoading && !selectedRowKey) return- return table.getCoreRowModel().flatRows.find((row) => row.id === selectedRowKey)- }, [selectedRowKey, isLoading])+ return table.getRowModel().rows.find((row) => row.id === selectedRowKey)+ }, [selectedRowKey, isLoading, table])- const index = table.getCoreRowModel().flatRows.findIndex((row) => row.id === selectedRow?.id)+ const index = table.getRowModel().rows.findIndex((row) => row.id === selectedRow?.id)- const nextId = useMemo(() => table.getCoreRowModel().flatRows[index + 1]?.id, [index, isLoading])+ const nextId = useMemo(() => table.getRowModel().rows[index + 1]?.id, [index, table])- const prevId = useMemo(() => table.getCoreRowModel().flatRows[index - 1]?.id, [index, isLoading])+ const prevId = useMemo(() => table.getRowModel().rows[index - 1]?.id, [index, table])const onPrev = useCallback(() => {if (prevId) table.setRowSelection({ [prevId]: true })- }, [prevId, isLoading])+ }, [prevId, table])const onNext = useCallback(() => {if (nextId) table.setRowSelection({ [nextId]: true })- }, [nextId, isLoading])+ }, [nextId, table])useEffect(() => {const down = (e: KeyboardEvent) => {diff --git a/apps/studio/components/ui/DataTable/DataTableToolbar.tsx b/apps/studio/components/ui/DataTable/DataTableToolbar.tsxindex 906e89dee00..bcfe4811d50 100644--- a/apps/studio/components/ui/DataTable/DataTableToolbar.tsx+++ b/apps/studio/components/ui/DataTable/DataTableToolbar.tsx@@ -1,4 +1,4 @@-import { PanelLeftClose } from 'lucide-react'+import { PanelLeftClose, PanelLeftOpen } from 'lucide-react'import { ReactNode, useMemo } from 'react'import { useHotKey } from 'hooks/ui/useHotKey'@@ -39,7 +39,7 @@ export function DataTableToolbar({ renderActions }: DataTableToolbarProps) {<Buttonsize="tiny"type="outline"- icon={<PanelLeftClose />}+ icon={open ? <PanelLeftClose /> : <PanelLeftOpen />}onClick={() => setOpen((prev) => !prev)}className="hidden sm:flex">diff --git a/apps/studio/components/ui/DataTable/FilterSideBar.tsx b/apps/studio/components/ui/DataTable/FilterSideBar.tsxindex d5be1d62a3d..18216c9bf8b 100644--- a/apps/studio/components/ui/DataTable/FilterSideBar.tsx+++ b/apps/studio/components/ui/DataTable/FilterSideBar.tsx@@ -1,4 +1,4 @@-import { cn } from 'ui'+import { cn, ResizablePanel } from 'ui'import { DataTableFilterControls } from './DataTableFilters/DataTableFilterControls'import { DataTableResetButton } from './DataTableResetButton'import { useDataTable } from './providers/DataTableProvider'@@ -7,22 +7,27 @@ export function FilterSideBar() {const { table } = useDataTable()return (- <div+ <ResizablePanel+ order={1}+ maxSize={33}+ defaultSize={1}+ id="panel-left"className={cn(- 'flex flex-col w-72',+ 'flex flex-col w-full',+ 'min-w-64 max-w-[32rem]','group-data-[expanded=false]/controls:hidden','hidden sm:flex')}>- <div className="border-b border-border bg-background px-2 md:top-0">+ <div className="border-b border-border px-2 md:top-0"><div className="flex h-[48px] items-center justify-between gap-3">- <p className="px-2 font-medium text-foreground">Filters</p>+ <p className="px-2 text-foreground text-lg">Logs</p><div>{table.getState().columnFilters.length ? <DataTableResetButton /> : null}</div></div></div><div className="flex-1 p-2 sm:overflow-y-scroll"><DataTableFilterControls /></div>- </div>+ </ResizablePanel>)}diff --git a/apps/studio/components/ui/DataTable/LiveRow.tsx b/apps/studio/components/ui/DataTable/LiveRow.tsxindex 76c63acd8be..3ee25ff6823 100644--- a/apps/studio/components/ui/DataTable/LiveRow.tsx+++ b/apps/studio/components/ui/DataTable/LiveRow.tsx@@ -1,16 +1,15 @@import { TableCell, TableRow } from 'ui'-import { DataTableColumnLevelIndicator } from './DataTableColumn/DataTableColumnLevelIndicator'export function LiveRow({ colSpan }: { colSpan: number }) {return (<TableRow>- <TableCell className="w-[--header-level-size] min-w-[--header-level-size] max-w-[--header-level-size] border-b border-l border-r border-t border-info border-r-info/50">- <DataTableColumnLevelIndicator value="info" />+ <TableCell className="relative w-[--header-level-size] min-w-[--header-level-size] max-w-[--header-level-size] border-b border-r border-t border-info">+ <div className="flex items-center justify-center">+ <span className="absolute inline-flex h-2.5 w-2.5 animate-ping rounded-full bg-brand opacity-75"></span>+ <span className="relative inline-flex h-2.5 w-2.5 rounded-full bg-brand"></span>+ </div></TableCell>- <TableCell- colSpan={colSpan}- className="border-b border-r border-t border-info font-medium text-info"- >+ <TableCell colSpan={colSpan} className="border-b border-r border-t text-foreground">Live Mode</TableCell></TableRow>diff --git a/apps/studio/data/logs/index.ts b/apps/studio/data/logs/index.tsnew file mode 100644index 00000000000..4410f1e3b84--- /dev/null+++ b/apps/studio/data/logs/index.ts@@ -0,0 +1,12 @@+export { logsKeys } from './keys'+export {+ useUnifiedLogInspectionQuery,+ getUnifiedLogInspection,+ SERVICE_FLOW_TYPES,+ type ServiceFlowType,+ type UnifiedLogInspectionVariables,+ type UnifiedLogInspectionResponse,+ type UnifiedLogInspectionEntry,+ type UnifiedLogInspectionData,+ type UnifiedLogInspectionError,+} from './unified-log-inspection-query'diff --git a/apps/studio/data/logs/keys.ts b/apps/studio/data/logs/keys.tsindex 2a02591a244..a079740b2c8 100644--- a/apps/studio/data/logs/keys.ts+++ b/apps/studio/data/logs/keys.ts@@ -34,4 +34,17 @@ export const logsKeys = {'chart-data',...(searchParams ? [searchParams].filter(Boolean) : []),] as const,+ serviceFlow: (+ projectRef: string | undefined,+ searchParams: QuerySearchParamsType | undefined,+ logId: string | undefined+ ) =>+ [+ 'projects',+ projectRef,+ 'unified-logs',+ 'service-flow',+ logId,+ ...(searchParams ? [searchParams].filter(Boolean) : []),+ ] as const,}diff --git a/apps/studio/data/logs/unified-log-inspection-query.ts b/apps/studio/data/logs/unified-log-inspection-query.tsnew file mode 100644index 00000000000..9b1c2777523--- /dev/null+++ b/apps/studio/data/logs/unified-log-inspection-query.ts@@ -0,0 +1,187 @@+import { useQuery, UseQueryOptions } from '@tanstack/react-query'++import {+ getAuthServiceFlowQuery,+ getEdgeFunctionServiceFlowQuery,+ getPostgresServiceFlowQuery,+ getPostgrestServiceFlowQuery,+ getStorageServiceFlowQuery,+} from 'components/interfaces/UnifiedLogs/Queries/ServiceFlowQueries/ServiceFlow.sql'+import { QuerySearchParamsType } from 'components/interfaces/UnifiedLogs/UnifiedLogs.types'+import { handleError, post } from 'data/fetchers'+import { ResponseError } from 'types'+import { logsKeys } from './keys'+import { getUnifiedLogsISOStartEnd } from './unified-logs-infinite-query'++// Service flow types - subset of LOG_TYPES that support service flows+export const SERVICE_FLOW_TYPES = [+ 'postgrest',+ 'auth',+ 'edge-function',+ 'storage',+ 'postgres',+] as const++export type ServiceFlowType = (typeof SERVICE_FLOW_TYPES)[number]++export type UnifiedLogInspectionVariables = {+ projectRef?: string+ logId?: string+ type?: ServiceFlowType+ search: QuerySearchParamsType+}++export type UnifiedLogInspectionResponse = {+ result: UnifiedLogInspectionEntry[]+}++export interface UnifiedLogInspectionEntry {+ id: string+ timestamp: string+ service_name: string+ method: string+ path: string+ host: string+ status_code: string+ level: string+ response_time_ms?: number+ auth_user?: string | null+ api_role?: string | null+ service_specific_data: Record<string, any>++ // Request data+ 'request.path'?: string+ 'request.host'?: string+ 'request.method'?: string+ 'request.url'?: string++ // Response data+ 'response.origin_time'?: number+ 'response.content_type'?: string+ 'response.cache_status'?: string++ // API Key Authentication+ 'apikey.role'?: 'anon' | 'service_role' | '<invalid>' | '<unrecognized>' | null+ 'apikey.prefix'?: string+ 'apikey.error'?: string++ // User Authorization+ 'authorization.role'?: 'authenticated' | 'anon' | null+ user_id?: string+ user_email?: string++ // Cloudflare Network Info+ cf_ray?: string+ cf_country?: string+ cf_datacenter?: string+ client_ip?: string++ // Client location data+ 'client.continent'?: string+ 'client.country'?: string+ 'client.city'?: string+ 'client.region'?: string+ 'client.region_code'?: string+ 'client.latitude'?: number+ 'client.longitude'?: number+ 'client.timezone'?: string++ // Network data+ 'network.protocol'?: string+ 'network.datacenter'?: string++ // Request headers+ 'headers.user_agent'?: string+ 'headers.x_client_info'?: string+ 'headers.x_forwarded_proto'?: string+ 'headers.x_real_ip'?: string++ // JWT data+ 'jwt.apikey_role'?: string+ 'jwt.apikey_algorithm'?: string+ 'jwt.apikey_expires_at'?: string+ 'jwt.apikey_issuer'?: string+ 'jwt.apikey_signature_prefix'?: string+ 'jwt.auth_role'?: string+ 'jwt.auth_algorithm'?: string+ 'jwt.auth_expires_at'?: string+ 'jwt.auth_issuer'?: string+ 'jwt.auth_signature_prefix'?: string++ // Raw data+ raw_log_data?: any+}++export async function getUnifiedLogInspection(+ { projectRef, logId, type, search }: UnifiedLogInspectionVariables,+ signal?: AbortSignal+) {+ if (!projectRef) {+ throw new Error('projectRef is required')+ }+ if (!logId) {+ throw new Error('logId is required')+ }+ if (!type) {+ throw new Error('type is required')+ }++ let sql = ''+ switch (type) {+ case 'postgrest':+ sql = getPostgrestServiceFlowQuery(logId)+ break+ case 'auth':+ sql = getAuthServiceFlowQuery(logId)+ break+ case 'edge-function':+ sql = getEdgeFunctionServiceFlowQuery(logId)+ break+ case 'storage':+ sql = getStorageServiceFlowQuery(logId)+ break+ case 'postgres':+ sql = getPostgresServiceFlowQuery(logId)+ break+ default:+ throw new Error('Invalid type')+ }++ // Use the same timestamp logic as the main unified logs query+ const { isoTimestampStart, isoTimestampEnd } = getUnifiedLogsISOStartEnd(search)++ const { data, error } = await post('/platform/projects/{ref}/analytics/endpoints/logs.all', {+ params: { path: { ref: projectRef } },+ body: {+ iso_timestamp_start: isoTimestampStart,+ iso_timestamp_end: isoTimestampEnd,+ sql: sql,+ },+ signal,+ })++ if (error) {+ handleError(error)+ }++ return data as unknown as UnifiedLogInspectionResponse+}++export type UnifiedLogInspectionData = Awaited<ReturnType<typeof getUnifiedLogInspection>>+export type UnifiedLogInspectionError = ResponseError++export const useUnifiedLogInspectionQuery = <TData = UnifiedLogInspectionData>(+ { projectRef, logId, type, search }: UnifiedLogInspectionVariables,+ {+ enabled = true,+ ...options+ }: UseQueryOptions<UnifiedLogInspectionData, UnifiedLogInspectionError, TData> = {}+) =>+ useQuery<UnifiedLogInspectionData, UnifiedLogInspectionError, TData>(+ logsKeys.serviceFlow(projectRef, search, logId),+ ({ signal }) => getUnifiedLogInspection({ projectRef, logId, type, search }, signal),+ {+ enabled: enabled && typeof projectRef !== 'undefined',+ ...options,+ }+ )