Files
supabase/apps/studio/data/replication/utils.ts
T
Charis b3dd6612d7 feat(studio): classify errors with fault, reason, and per-tag Sentry sampling (#52730)
Follows #52707 (rename `ResponseError` to `StudioError`).

Resolves FE-4772.

## What

Introduces the error core for Studio error classification.

- **Tagged errors.** `lib/errors/studio-errors.ts` defines
`Data.TaggedError` classes (`RequestAborted`, `NetworkUnreachable`,
`MalformedResponse`, `PlatformError`, `UnclassifiedApiError`,
`DbConnectionTimeout`, `UnexpectedError`). Each carries `fault`,
`reason`, `classifiedBy` (`rule` or `default`), `retryable`, and
`service`. `StudioError` is the union type; use `isStudioError` instead
of `instanceof`.
- **Two classifiers** in `data/error-classification.ts`:
- `classifyResponseError` is only for errors from an API response: known
message patterns first, then defaults by status (5xx `PlatformError`,
4xx `UnclassifiedApiError`, no status `UnexpectedError`).
- `classifyError` is for everything else: aborts, browser fetch failures
(matched by message, so ordinary `TypeError` bugs stay
`UnexpectedError`), and unexpected errors.
- `handleError` picks between them, reports, and rethrows the same
instance so React Query receives the classified error.
- **Routing and sampling.** `lib/errors/error-routing.ts` maps every tag
to a Sentry sample rate (`SAMPLE_NEVER`, `SAMPLE_OTHER`, `SAMPLE_OWNED`,
`SAMPLE_ALWAYS`). `reportStudioError` tags events with `sample_rate`,
and `beforeSend` applies it. `alwaysCapture` reports at rate 1. The
global Sentry error `sampleRate` stays unset so the rates don't
multiply.
- **Network failures.** A fetch failure is a `user` fault with reason
`offline` when the browser reports being offline, and a `platform` fault
otherwise.
- **Hand-built errors.** Call sites that wrapped caught exceptions or
made up status codes now use `classifyError` or a specific class instead
of `classifyResponseError`.

## Behavior changes

- Errors that previously went unreported, including unexpected errors
with a message, are now reported to Sentry at their routed sample rate.
- `handleError` no longer logs the stack with `console.error`.
- `MalformedResponse` is defined but not produced yet; a follow-up adds
the empty-body check.

## Testing

- Unit tests for classification, routing, reporting, and the
`beforeSend` sampling helper.
- `pnpm vitest run data lib components/interfaces/ErrorHandling`,
typecheck, lint ratchet, and knip pass locally.
2026-11-04 13:19:01 -05:00

127 lines
4.0 KiB
TypeScript

import type {
BigQueryPartitionBy,
BigQueryTableOption,
CompleteBigQueryPartitionBy,
CreatePipelineApiConfig,
DucklakeDestinationConfig,
DucklakeSupabaseDestinationConfig,
PipelineConfig,
} from './types'
import { MAX_RETRY_FAILURE_COUNT } from '@/data/query-client'
import type { StudioError } from '@/lib/errors/studio-errors'
import { isStudioError } from '@/lib/errors/studio-errors'
const isLocal =
process.env.NEXT_PUBLIC_ENVIRONMENT !== 'prod' &&
process.env.NEXT_PUBLIC_ENVIRONMENT !== 'staging'
export const checkLocalPipelinesNotSetUp = (error: StudioError | null) => {
if (error === null) return false
const isPipelinesApiNotRunning =
error.code === undefined && error.message.includes('API error happened')
const isPipelinesNotSetUp =
error.code === 503 && error.message.includes('replication API URL is not configured')
return isLocal && (isPipelinesApiNotRunning || isPipelinesNotSetUp)
}
export const checkReplicationFeatureFlagRetry = (
failureCount: number,
error: StudioError
): boolean => {
const isFeatureFlagRequiredError =
isStudioError(error) && error.code === 503 && error.message.includes('feature flag is required')
const isLocalPipelinesNotSetUp = checkLocalPipelinesNotSetUp(error)
if (isFeatureFlagRequiredError || isLocalPipelinesNotSetUp) {
return false
}
if (failureCount < MAX_RETRY_FAILURE_COUNT) {
return true
}
return false
}
export function isDucklakeSupabaseConfig(
config: DucklakeDestinationConfig
): config is DucklakeSupabaseDestinationConfig {
return 'catalogProjectRef' in config
}
export const buildPipelineApiConfig = ({
publicationName,
batch,
maxTableSyncWorkers,
maxCopyConnectionsPerTable,
invalidatedSlotBehavior,
tableSyncCopy,
}: PipelineConfig): CreatePipelineApiConfig => ({
publication_name: publicationName,
max_table_sync_workers: maxTableSyncWorkers,
max_copy_connections_per_table: maxCopyConnectionsPerTable,
invalidated_slot_behavior: invalidatedSlotBehavior,
table_sync_copy: tableSyncCopy,
batch: batch
? {
max_fill_ms: batch.maxFillMs,
max_bytes: batch.maxBytes,
memory_budget_ratio: batch.memoryBudgetRatio,
}
: undefined,
})
const hasClusteringColumns = (clusterBy: string[] | undefined) => (clusterBy?.length ?? 0) > 0
const isCompleteBigQueryPartition = (
partitionBy: BigQueryPartitionBy | undefined
): partitionBy is CompleteBigQueryPartitionBy => {
if (!partitionBy) return false
if (partitionBy.kind === 'ingestion_time') return true
if (!('column' in partitionBy) || partitionBy.column.trim().length === 0) return false
if (partitionBy.kind !== 'integer_range') return true
return (
typeof partitionBy.start === 'number' &&
typeof partitionBy.end === 'number' &&
typeof partitionBy.interval === 'number'
)
}
const buildBigQueryPartitionByApiConfig = (partitionBy: CompleteBigQueryPartitionBy) => {
switch (partitionBy.kind) {
case 'time_column':
return {
kind: partitionBy.kind,
column: partitionBy.column,
granularity: partitionBy.granularity,
}
case 'integer_range':
return {
kind: partitionBy.kind,
column: partitionBy.column,
start: partitionBy.start,
end: partitionBy.end,
interval: partitionBy.interval,
}
case 'ingestion_time':
return { kind: partitionBy.kind, granularity: partitionBy.granularity }
}
}
export const buildBigQueryTableOptionApiConfig = (option: BigQueryTableOption) => ({
table_id: option.tableId,
partition_by: isCompleteBigQueryPartition(option.partitionBy)
? buildBigQueryPartitionByApiConfig(option.partitionBy)
: undefined,
cluster_by: hasClusteringColumns(option.clusterBy) ? option.clusterBy : undefined,
})
const isBigQueryTableOptionConfigured = (option: BigQueryTableOption) =>
isCompleteBigQueryPartition(option.partitionBy) || hasClusteringColumns(option.clusterBy)
export const getConfiguredBigQueryTableOptions = (
tableOptions: BigQueryTableOption[] | undefined
) => (tableOptions ?? []).filter(isBigQueryTableOptionConfigured)