Files
supabase/apps/studio/data/edge-functions/edge-function-body-query.ts
Joshen Lim 4a73166675 Add support for downloading edge functions when file size exceeds max cap (#53709)
## Context

Just creating a separate PR cause I messed up the [previous
one](https://github.com/supabase/supabase/pull/53453) with a bad merge 🫠
Also changed the implementation to no longer use `@deno/eszip`.

For edge functions, functions which exceed 5MB cannot be fetched and
displayed in the dashboard editor (API will return a 507). The CTA we
give to users is to download the function via the CLI, but this PR
explores allowing users to download their edge functions via the browser
still, by calling `/v1/functions/slug/body` without the
`multi-part/data` header. This returns the function in a raw eszip
stream which we're then parsing using a custom reader

We'll do this via the "Download as ZIP" CTA here - but this way of
downloading only kicks in if the GET Edge Function body endpoint returns
a 507. Otherwise it'll just be status quo where we bundle the files that
were already fetched to render in the browser into a ZIP file.
<img width="343" height="186" alt="image"
src="https://github.com/user-attachments/assets/4ffc9fee-7e6d-46a6-bdbe-294610abc802"
/>

Also updated the warning for 507s:
- To use a normal admonition instead of `AlertError` since its
technically not an issue
- To avoid rendering the API error message in this case specifically as
the API message contains "Use multipart instead" which isn't relevant to
the dashboard from a user's POV
<img width="500" alt="image"
src="https://github.com/user-attachments/assets/8242a875-f142-419d-81f0-0dbc30807f87"
/>

## To test

- [ ] Upload an edge function of size larger than 5MB to a staging
project via the CLI
- [ ] Verify that there's an Admonition for the large function instead
of an error
- [ ] Verify that you can still download the edge function via the
Download button (Which triggers a POST /body request without multipart)
2026-11-23 10:59:57 +07:00

113 lines
3.6 KiB
TypeScript

import { getMultipartBoundary, parseMultipartStream } from '@mjackson/multipart-parser'
import * as Sentry from '@sentry/react'
import { useQuery } from '@tanstack/react-query'
import { edgeFunctionsKeys } from './keys'
import { FileData } from '@/components/ui/FileExplorerAndEditor/FileExplorerAndEditor.types'
import { get, handleError, unguarded } from '@/data/fetchers'
import type { StudioError } from '@/lib/errors/studio-errors'
import type { UseCustomQueryOptions } from '@/types'
type EdgeFunctionBodyVariables = {
projectRef?: string
slug?: string
}
export function isFunctionBodyMaxSizeError(error?: { code?: number } | null) {
return error?.code === 507
}
async function fetchFunctionBody(
{ projectRef, slug }: EdgeFunctionBodyVariables,
{
multipart = true,
signal,
reportImmediately = false,
}: { multipart: boolean; signal?: AbortSignal; reportImmediately?: boolean }
) {
if (!projectRef) throw new Error('projectRef is required')
if (!slug) throw new Error('slug is required')
const { data, response, error } = await get('/v1/projects/{ref}/functions/{function_slug}/body', {
params: { path: { ref: projectRef, function_slug: slug } },
// Without the multipart Accept header the API returns the raw eszip bundle,
// which isn't subject to the max size limit that the multipart response has
headers: multipart ? { Accept: 'multipart/form-data' } : undefined,
parseAs: 'stream',
signal,
grant: unguarded.migrating,
})
if (error) handleError(error, { reportImmediately })
return { data, response }
}
export async function getEdgeFunctionBodyEszip(variables: EdgeFunctionBodyVariables) {
const { data } = await fetchFunctionBody(variables, { multipart: false, reportImmediately: true })
if (!data) throw new Error('Failed to retrieve edge function bundle')
return new Uint8Array(await new Response(data).arrayBuffer())
}
export async function getEdgeFunctionBody(
variables: EdgeFunctionBodyVariables,
signal?: AbortSignal
) {
const { data, response } = await fetchFunctionBody(variables, { multipart: true, signal })
const contentTypeHeader = response.headers.get('content-type') ?? ''
const boundary = getMultipartBoundary(contentTypeHeader)
const files = []
if (!data || !boundary) return { files: [] }
let metadata: {
deno2_entrypoint_path?: string | null
} = {}
try {
for await (let part of parseMultipartStream(data, {
boundary,
maxFileSize: 20 * 1024 * 1024,
})) {
if (part.isFile) {
files.push({
name: part.filename,
content: part.text,
})
} else {
// treat it as metadata
metadata = JSON.parse(part.text)
}
}
return {
metadata,
files: files as Omit<FileData, 'id' | 'selected' | 'state'>[],
}
} catch (error) {
if (error instanceof Error) {
Sentry.captureException(error, {
extra: { error, data, response, boundary },
})
}
throw error
}
}
export type EdgeFunctionBodyData = Awaited<ReturnType<typeof getEdgeFunctionBody>>
type EdgeFunctionBodyError = StudioError
export const useEdgeFunctionBodyQuery = <TData = EdgeFunctionBodyData>(
{ projectRef, slug }: EdgeFunctionBodyVariables,
{
enabled = true,
...options
}: UseCustomQueryOptions<EdgeFunctionBodyData, EdgeFunctionBodyError, TData> = {}
) =>
useQuery<EdgeFunctionBodyData, EdgeFunctionBodyError, TData>({
queryKey: edgeFunctionsKeys.body(projectRef, slug),
queryFn: ({ signal }) => getEdgeFunctionBody({ projectRef, slug }, signal),
enabled: enabled && typeof projectRef !== 'undefined' && typeof slug !== 'undefined',
...options,
})