Files
supabase/apps/studio/data/storage/bucket-object-sign-mutation.ts
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

90 lines
2.4 KiB
TypeScript

import { useMutation } from '@tanstack/react-query'
import { toast } from 'sonner'
import { components } from '@/data/api'
import { handleError, post } from '@/data/fetchers'
import type { StudioError } from '@/lib/errors/studio-errors'
import type { UseCustomMutationOptions } from '@/types'
type SignBucketObjectParams = {
projectRef: string
bucketId?: string
path: string
expiresIn: number
options?: components['schemas']['GetSignedUrlBody']['options']
}
export const signBucketObject = async (
{ projectRef, bucketId, path, expiresIn, options }: SignBucketObjectParams,
signal?: AbortSignal
) => {
if (!bucketId) throw new Error('bucketId is required')
const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/sign', {
params: {
path: {
ref: projectRef,
id: bucketId,
},
},
body: { path, expiresIn, options },
signal,
})
if (error) handleError(error)
return data
}
type SignBucketObjectData = Awaited<ReturnType<typeof signBucketObject>>
type SignBucketObjectsParams = {
projectRef: string
bucketId?: string
paths: Array<string>
expiresIn: number
}
export const signBucketObjects = async (
{ projectRef, bucketId, paths, expiresIn }: SignBucketObjectsParams,
signal?: AbortSignal
) => {
if (!bucketId) throw new Error('bucketId is required')
const { data, error } = await post('/platform/storage/{ref}/buckets/{id}/objects/sign-multi', {
params: {
path: {
ref: projectRef,
id: bucketId,
},
},
body: { path: paths, expiresIn },
signal,
})
// Called directly by the storage explorer state, not through a mutation
if (error) handleError(error, { reportImmediately: true })
return data ?? []
}
export const useGetSignBucketObjectMutation = ({
onSuccess,
onError,
...options
}: Omit<
UseCustomMutationOptions<SignBucketObjectData, StudioError, SignBucketObjectParams>,
'mutationFn'
> = {}) => {
return useMutation<SignBucketObjectData, StudioError, SignBucketObjectParams>({
mutationFn: (vars) => signBucketObject(vars),
async onSuccess(data, variables, context) {
await onSuccess?.(data, variables, context)
},
async onError(data, variables, context) {
if (onError === undefined) {
toast.error(`Failed to get sign bucket object: ${data.message}`)
} else {
onError(data, variables, context)
}
},
...options,
})
}