mirror of
https://github.com/supabase/supabase.git
synced 2026-12-03 23:18:57 +00:00
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.
187 lines
5.6 KiB
TypeScript
187 lines
5.6 KiB
TypeScript
import { getCreateMigrationsTableSQL, getInsertMigrationSQL } from '@supabase/pg-meta'
|
|
|
|
import { isResponseOk } from './api/apiWrapper'
|
|
import { classifyError, classifyResponseError } from '@/data/error-classification'
|
|
import { fetchHandler } from '@/data/fetchers'
|
|
import type { Integration } from '@/data/integrations/integrations.types'
|
|
import { BASE_PATH } from '@/lib/constants'
|
|
import { type SupaResponse } from '@/types'
|
|
|
|
async function fetchGitHub<T = any>(url: string, responseJson = true): Promise<SupaResponse<T>> {
|
|
const response = await fetchHandler(url)
|
|
if (!response.ok) {
|
|
return {
|
|
error: classifyResponseError({ message: response.statusText, code: response.status }),
|
|
}
|
|
}
|
|
try {
|
|
return (responseJson ? await response.json() : await response.text()) as T
|
|
} catch (error: any) {
|
|
return {
|
|
error: classifyError(error),
|
|
}
|
|
}
|
|
}
|
|
|
|
export type File = {
|
|
name: string
|
|
download_url: string
|
|
}
|
|
|
|
/**
|
|
* Returns the initial migration SQL from a GitHub repo.
|
|
* @param externalId An external GitHub URL for example: https://github.com/vercel/next.js/tree/canary/examples/with-supabase
|
|
*/
|
|
export async function getInitialMigrationSQLFromGitHubRepo(
|
|
externalId?: string
|
|
): Promise<string | null> {
|
|
if (!externalId) return null
|
|
|
|
const [, , , owner, repo, , branch, ...pathSegments] = externalId?.split('/') ?? []
|
|
const path = pathSegments.join('/')
|
|
|
|
const baseGitHubUrl = `https://api.github.com/repos/${owner}/${repo}/contents/${path}`
|
|
const supabaseFolderUrl = `${baseGitHubUrl}/supabase?ref=${branch}`
|
|
const supabaseMigrationsPath = `supabase/migrations` // TODO: read this from the `supabase/config.toml` file
|
|
const migrationsFolderUrl = `${baseGitHubUrl}/${supabaseMigrationsPath}${
|
|
branch ? `?ref=${branch}` : ``
|
|
}`
|
|
|
|
const [supabaseFilesResponse, migrationFilesResponse] = await Promise.all([
|
|
fetchGitHub<File[]>(supabaseFolderUrl),
|
|
fetchGitHub<File[]>(migrationsFolderUrl),
|
|
])
|
|
|
|
if (!isResponseOk(supabaseFilesResponse)) {
|
|
console.warn(`Failed to fetch supabase files from GitHub: ${supabaseFilesResponse.error}`)
|
|
return null
|
|
}
|
|
if (!isResponseOk(migrationFilesResponse)) {
|
|
console.warn(`Failed to fetch migration files from GitHub: ${migrationFilesResponse.error}`)
|
|
return null
|
|
}
|
|
|
|
const seedFileUrl = supabaseFilesResponse.find((file) => file.name === 'seed.sql')?.download_url
|
|
const sortedFiles = migrationFilesResponse.sort((a, b) => {
|
|
// sort by name ascending
|
|
if (a.name < b.name) return -1
|
|
if (a.name > b.name) return 1
|
|
return 0
|
|
})
|
|
const migrationFileDownloadUrlPromises = sortedFiles.map((file) =>
|
|
fetchGitHub<string>(file.download_url, false)
|
|
)
|
|
|
|
const [seedFileResponse, ...migrationFileResponses] = await Promise.all([
|
|
seedFileUrl ? fetchGitHub<string>(seedFileUrl, false) : Promise.resolve<string>(''),
|
|
...migrationFileDownloadUrlPromises,
|
|
])
|
|
|
|
const migrations = migrationFileResponses.filter((response) => isResponseOk(response)).join(';')
|
|
const seed = isResponseOk(seedFileResponse) ? seedFileResponse : ''
|
|
|
|
const createMigrationsTableSql = getCreateMigrationsTableSQL()
|
|
|
|
const migrationsTableSql = `
|
|
${createMigrationsTableSql}
|
|
${sortedFiles
|
|
.map((file, i) => {
|
|
const migration = migrationFileResponses[i]
|
|
if (!isResponseOk(migration)) return ''
|
|
|
|
const version = file.name.split('_')[0]
|
|
const statements = JSON.stringify(
|
|
migration
|
|
.split(';')
|
|
.map((statement) => statement.trim())
|
|
.filter(Boolean)
|
|
)
|
|
return getInsertMigrationSQL({ name: file.name, version, statements })
|
|
})
|
|
.join('')}
|
|
`
|
|
|
|
return `${migrations};${migrationsTableSql};${seed}`
|
|
}
|
|
|
|
type VercelIntegration = Extract<Integration, { integration: { name: 'Vercel' } }>
|
|
type GitHubIntegration = Extract<Integration, { integration: { name: 'GitHub' } }>
|
|
|
|
export function getIntegrationConfigurationUrl(integration: Integration) {
|
|
if (integration.integration.name === 'Vercel') {
|
|
return getVercelConfigurationUrl(integration as VercelIntegration)
|
|
}
|
|
|
|
if (integration.integration.name === 'GitHub') {
|
|
return getGitHubConfigurationUrl(integration as GitHubIntegration)
|
|
}
|
|
|
|
return ''
|
|
}
|
|
|
|
function getVercelConfigurationUrl(integration: VercelIntegration) {
|
|
return `https://vercel.com/dashboard/${
|
|
integration.metadata?.account.type === 'Team'
|
|
? `${integration.metadata?.account.team_slug}/`
|
|
: ''
|
|
}integrations/${integration.metadata?.configuration_id}`
|
|
}
|
|
|
|
function getGitHubConfigurationUrl(integration: GitHubIntegration) {
|
|
return `https://github.com/${
|
|
integration.metadata?.account.type === 'Organization'
|
|
? `organizations/${integration.metadata?.account.name}/`
|
|
: ''
|
|
}settings/installations/${integration.metadata?.installation_id}`
|
|
}
|
|
|
|
export const FRAMEWORK_ICON_SLUGS: ReadonlySet<string> = new Set([
|
|
'angular',
|
|
'astro',
|
|
'blitzjs',
|
|
'brunch',
|
|
'create-react-app',
|
|
'docusaurus',
|
|
'docusaurus-2',
|
|
'dojo',
|
|
'eleventy',
|
|
'ember',
|
|
'gatsby',
|
|
'gridsome',
|
|
'hexo',
|
|
'hugo',
|
|
'hydrogen',
|
|
'ionic-angular',
|
|
'ionic-react',
|
|
'jekyll',
|
|
'middleman',
|
|
'nextjs',
|
|
'nuxtjs',
|
|
'parcel',
|
|
'polymer',
|
|
'preact',
|
|
'redwoodjs',
|
|
'remix',
|
|
'saber',
|
|
'sanity',
|
|
'sapper',
|
|
'scully',
|
|
'solidstart',
|
|
'stencil',
|
|
'storybook',
|
|
'svelte',
|
|
'sveltekit',
|
|
'sveltekit-1',
|
|
'umijs',
|
|
'vite',
|
|
'vitepress',
|
|
'vue',
|
|
'vuepress',
|
|
'zola',
|
|
])
|
|
|
|
export function getFrameworkIconUrl(framework?: string | null): string | undefined {
|
|
if (!framework || !FRAMEWORK_ICON_SLUGS.has(framework)) return undefined
|
|
return `${BASE_PATH}/img/icons/frameworks/${framework}.svg`
|
|
}
|