The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(studio): deploy worker form (#49613)
Francesco Sansalvadorea8240e3da8f1
diff --git a/apps/studio/components/interfaces/Workers/DeployWorkerDialog.tsx b/apps/studio/components/interfaces/Workers/DeployWorkerDialog.tsxindex 5c90e6a8f28..66e91a9e00b 100644--- a/apps/studio/components/interfaces/Workers/DeployWorkerDialog.tsx+++ b/apps/studio/components/interfaces/Workers/DeployWorkerDialog.tsx@@ -1,67 +1,238 @@+import { zodResolver } from '@hookform/resolvers/zod'+import { useForm, useWatch } from 'react-hook-form'import {+ Button,Dialog,DialogContent,+ DialogFooter,DialogHeader,DialogSection,DialogSectionSeparator,DialogTitle,+ Form,+ FormControl,+ FormField,+ Input,+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,} from 'ui'+import { Admonition } from 'ui-patterns/Admonition'+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'+import * as z from 'zod'-import { EXAMPLE_WORKER } from './workerSnippets'+import { RuntimeBadge } from './RuntimeBadge'+import { WORKER_DEPLOYABLE_RUNTIMES, WORKER_SIZES, WORKERS_REGION } from './Workers.constants'+import type { WorkerAccess } from './Workers.types'+import { formatSize, generateWorkerName } from './Workers.utils'import { WorkerSnippetTabs } from './WorkerSnippetTabs'+const FORM_ID = 'deploy-worker-form'++const DeployWorkerFormSchema = z.object({+ name: z+ .string()+ .trim()+ .min(1, 'Name is required')+ .regex(/^[a-z0-9-]+$/, 'Lowercase letters, numbers, and hyphens only'),+ runtime: z.enum(WORKER_DEPLOYABLE_RUNTIMES),+ size: z.enum(WORKER_SIZES),+ access: z.enum(['private', 'public']),+ instances: z+ .union([z.literal(''), z.coerce.number().int().gte(1).lte(10)])+ .refine((value) => value !== '', 'Instances is required'),+})++type DeployWorkerFormValues = z.infer<typeof DeployWorkerFormSchema>++const DEFAULT_VALUES: DeployWorkerFormValues = {+ name: '',+ runtime: 'deno',+ size: WORKER_SIZES[0],+ access: 'private',+ instances: 1,+}++const ACCESS_OPTIONS: { value: WorkerAccess; label: string }[] = [+ { value: 'private', label: 'Private' },+ { value: 'public', label: 'Public' },+]+interface DeployWorkerDialogProps {open: booleanonOpenChange: (open: boolean) => void}-const STEPS = [- {- title: 'Scaffold the worker',- description: 'Creates supabase/workers/<name>/ with an entrypoint for the runtime you pick.',- },- {- title: 'Configure it',- description: 'Runtime, size, access, and instance count live in supabase/config.toml.',- },- {- title: 'Push it',- description: 'Builds the image and schedules it on a microVM in US West.',- },-]+export const DeployWorkerDialog = ({ open, onOpenChange }: DeployWorkerDialogProps) => {+ const form = useForm<DeployWorkerFormValues>({+ mode: 'onBlur',+ resolver: zodResolver(DeployWorkerFormSchema),+ defaultValues: { ...DEFAULT_VALUES, name: generateWorkerName() },+ })++ const [name, runtime, size, access, instances] = useWatch({+ control: form.control,+ name: ['name', 'runtime', 'size', 'access', 'instances'],+ })++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent size="large">+ <DialogHeader>+ <DialogTitle>Deploy a worker</DialogTitle>+ </DialogHeader>++ <DialogSectionSeparator />-export const DeployWorkerDialog = ({ open, onOpenChange }: DeployWorkerDialogProps) => (- <Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent size="large">- <DialogHeader>- <DialogTitle>Deploy a worker</DialogTitle>- </DialogHeader>-- <DialogSection className="space-y-4">- <p className="text-sm text-foreground-light">- Workers are deployed with the Supabase CLI. This dashboard is read-only during the private- alpha.- </p>- <ol className="space-y-4">- {STEPS.map((step, index) => (- <li key={step.title} className="flex gap-3">- <span className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-strong text-xs text-foreground-light">- {index + 1}- </span>- <div className="space-y-0.5">- <p className="text-sm text-foreground">{step.title}</p>- <p className="text-sm text-foreground-lighter">{step.description}</p>- </div>- </li>- ))}- </ol>- </DialogSection>-- <DialogSectionSeparator />-- <DialogSection>- <WorkerSnippetTabs input={EXAMPLE_WORKER} tabs={['cli', 'config']} />- </DialogSection>- </DialogContent>- </Dialog>-)+ <Admonition+ type="note"+ title="This dashboard is read-only during the Private Alpha"+ description={`Configure a worker below, then deploy it locally. Workers only deploy to ${WORKERS_REGION} during alpha.`}+ className="border-x-0 border-y-0 rounded-none"+ />++ <DialogSectionSeparator />++ <DialogSection>+ <Form {...form}>+ <form id={FORM_ID} className="flex flex-col gap-y-4">+ <FormField+ control={form.control}+ name="name"+ render={({ field }) => (+ <FormItemLayout name="name" label="Name">+ <FormControl>+ <Input {...field} placeholder="my-worker" />+ </FormControl>+ </FormItemLayout>+ )}+ />++ <FormField+ control={form.control}+ name="runtime"+ render={({ field }) => (+ <FormItemLayout name="runtime" label="Runtime">+ <Select value={field.value} onValueChange={field.onChange}>+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {WORKER_DEPLOYABLE_RUNTIMES.map((value) => (+ <SelectItem key={value} value={value}>+ <RuntimeBadge runtime={value} />+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormItemLayout>+ )}+ />++ <FormField+ control={form.control}+ name="size"+ render={({ field }) => (+ <FormItemLayout+ name="size"+ label="Size"+ description="Fixed at deploy time and cannot be changed later"+ >+ <Select value={field.value} onValueChange={field.onChange}>+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {WORKER_SIZES.map((value) => (+ <SelectItem key={value} value={value}>+ {formatSize(value)}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormItemLayout>+ )}+ />++ <FormField+ control={form.control}+ name="access"+ render={({ field }) => (+ <FormItemLayout+ name="access"+ label="Access"+ description="Public workers accept requests with a publishable key"+ >+ <Select value={field.value} onValueChange={field.onChange}>+ <FormControl>+ <SelectTrigger>+ <SelectValue />+ </SelectTrigger>+ </FormControl>+ <SelectContent>+ {ACCESS_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </FormItemLayout>+ )}+ />++ <FormField+ control={form.control}+ name="instances"+ render={({ field }) => (+ <FormItemLayout name="instances" label="Instances" description="1 to 10">+ <FormControl>+ <Input+ {...field}+ type="number"+ min={1}+ max={10}+ onChange={(e) =>+ field.onChange(+ Number.isNaN(e.target.valueAsNumber) ? '' : e.target.valueAsNumber+ )+ }+ />+ </FormControl>+ </FormItemLayout>+ )}+ />+ </form>+ </Form>+ </DialogSection>++ <DialogSectionSeparator />++ <DialogSection>+ <WorkerSnippetTabs+ input={{+ name: name ?? '',+ runtime: runtime ?? DEFAULT_VALUES.runtime,+ size: size ?? DEFAULT_VALUES.size,+ access: access ?? DEFAULT_VALUES.access,+ instances: typeof instances === 'number' ? instances : DEFAULT_VALUES.instances,+ }}+ tabs={['ai', 'cli', 'config']}+ />+ </DialogSection>++ <DialogFooter>+ <Button variant="default" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/studio/components/interfaces/Workers/WorkerSnippetTabs.tsx b/apps/studio/components/interfaces/Workers/WorkerSnippetTabs.tsxindex 151050e8fd4..08f181338de 100644--- a/apps/studio/components/interfaces/Workers/WorkerSnippetTabs.tsx+++ b/apps/studio/components/interfaces/Workers/WorkerSnippetTabs.tsx@@ -1,4 +1,5 @@import { useParams } from 'common'+import { FileCode, Sparkles, Terminal, type LucideIcon } from 'lucide-react'import { useState } from 'react'import { cn } from 'ui'@@ -6,27 +7,31 @@ import { buildWorkerSnippets, type WorkerSnippetInput } from './workerSnippets'import CopyButton from '@/components/ui/CopyButton'import { useProjectSettingsV2Query } from '@/data/config/project-settings-v2-query'-export type WorkerSnippetTab = 'config' | 'cli' | 'curl' | 'js' | 'python'+export type WorkerSnippetTab = 'ai' | 'config' | 'cli' | 'js' | 'python'const TAB_LABEL: Record<WorkerSnippetTab, string> = {+ ai: 'AI Prompt',config: 'config.toml',cli: 'CLI',- curl: 'cURL',js: 'JavaScript',python: 'Python',}+const TAB_ICON: Record<WorkerSnippetTab, LucideIcon> = {+ ai: Sparkles,+ config: FileCode,+ cli: Terminal,+ js: FileCode,+ python: FileCode,+}+interface WorkerSnippetTabsProps {input: Omit<WorkerSnippetInput, 'endpoint' | 'protocol'>tabs?: [WorkerSnippetTab, ...WorkerSnippetTab[]]className?: string}-export const WorkerSnippetTabs = ({- input,- tabs = ['cli', 'curl'],- className,-}: WorkerSnippetTabsProps) => {+export const WorkerSnippetTabs = ({ input, tabs = ['cli'], className }: WorkerSnippetTabsProps) => {const { ref } = useParams()const [active, setActive] = useState<WorkerSnippetTab>(tabs[0])@@ -37,9 +42,9 @@ export const WorkerSnippetTabs = ({protocol: settings?.app_config?.protocol,})const snippetByTab: Record<WorkerSnippetTab, string> = {+ ai: snippets.aiPrompt,config: snippets.configToml,cli: snippets.cli,- curl: snippets.curl,js: snippets.javascript,python: snippets.python,}@@ -49,22 +54,26 @@ export const WorkerSnippetTabs = ({return (<div className={cn('flex flex-col gap-y-2', className)}><div className="flex items-center gap-x-4 border-b border-default">- {tabs.map((tab) => (- <button- key={tab}- type="button"- tabIndex={0}- onClick={() => setActive(tab)}- className={cn(- '-mb-px border-b px-0.5 py-1.5 text-sm transition-colors',- tab === activeTab- ? 'border-foreground text-foreground'- : 'border-transparent text-foreground-lighter hover:text-foreground-light'- )}- >- {TAB_LABEL[tab]}- </button>- ))}+ {tabs.map((tab) => {+ const Icon = TAB_ICON[tab]+ return (+ <button+ key={tab}+ type="button"+ tabIndex={0}+ onClick={() => setActive(tab)}+ className={cn(+ '-mb-px flex items-center gap-1.5 border-b px-0.5 py-1.5 text-sm transition-colors',+ tab === activeTab+ ? 'border-foreground text-foreground'+ : 'border-transparent text-foreground-lighter hover:text-foreground-light'+ )}+ >+ <Icon size={14} strokeWidth={1.5} />+ {TAB_LABEL[tab]}+ </button>+ )+ })}</div><div className="relative rounded-md border border-default bg-surface-100">@@ -75,9 +84,15 @@ export const WorkerSnippetTabs = ({aria-label="Copy snippet"className="absolute right-2 top-2 text-foreground-lighter hover:text-foreground"/>- <pre className="overflow-x-auto p-3 pr-10 font-mono text-xs leading-relaxed text-foreground-light">- {value}- </pre>+ {activeTab === 'ai' ? (+ <p className="overflow-x-auto whitespace-pre-wrap p-3 pr-10 text-sm leading-relaxed text-foreground-light">+ {value}+ </p>+ ) : (+ <pre className="overflow-x-auto p-3 pr-10 font-mono text-xs leading-relaxed text-foreground-light">+ {value}+ </pre>+ )}</div></div>)diff --git a/apps/studio/components/interfaces/Workers/Workers.constants.ts b/apps/studio/components/interfaces/Workers/Workers.constants.tsindex 7c3b911d0f1..f61b6e3e5a3 100644--- a/apps/studio/components/interfaces/Workers/Workers.constants.ts+++ b/apps/studio/components/interfaces/Workers/Workers.constants.ts@@ -5,7 +5,62 @@ export const WORKERS_REGION = 'us-west-2'export const WORKERS_REGION_LABEL = 'US West (Oregon)'export const WORKERS_REGION_SHORT = 'US West'-// Workers answer on the project's own domain, alongside /functions/v1.+// Sizes are fixed at deploy time — matches the `size` values the API accepts.+export const WORKER_SIZES = ['2gb-1vcpu', '4gb-2vcpu'] as const++export const WORKER_NAME_WORDS = [+ 'swift',+ 'nimble',+ 'brisk',+ 'bold',+ 'sleek',+ 'vivid',+ 'lucid',+ 'crisp',+ 'keen',+ 'agile',+ 'fierce',+ 'bright',+ 'orchid',+ 'lotus',+ 'iris',+ 'dahlia',+ 'tulip',+ 'jasmine',+ 'magnolia',+ 'azalea',+ 'poppy',+ 'marigold',+ 'hibiscus',+ 'camellia',+ 'synergy',+ 'bloom',+ 'scalable',+ 'pivot',+ 'paradigm',+ 'holistic',+ 'leverage',+ 'stream',+ 'viral',+ 'turnkey',+ 'quantum',+ 'photon',+ 'nebula',+ 'comet',+ 'orbit',+ 'cosmos',+ 'meteor',+ 'pulsar',+ 'quasar',+ 'vector',+ 'cipher',+ 'nova',+ 'zenith',+ 'warp',+ 'rocket',+ 'stellar',+] as const+export const workerUrl = ({endpoint,protocol = 'https',@@ -59,6 +114,8 @@ export const RUNTIMES: Record<string, RuntimeMeta> = {},}+export const WORKER_DEPLOYABLE_RUNTIMES = ['node', 'deno', 'dockerfile'] as const+interface WorkerStateMeta {label: stringdotClassName: stringdiff --git a/apps/studio/components/interfaces/Workers/Workers.utils.test.ts b/apps/studio/components/interfaces/Workers/Workers.utils.test.tsindex 275f0763f5c..da791ba0349 100644--- a/apps/studio/components/interfaces/Workers/Workers.utils.test.ts+++ b/apps/studio/components/interfaces/Workers/Workers.utils.test.ts@@ -1,12 +1,13 @@import { describe, expect, it } from 'vitest'-import { getWorkerStateMeta, workerUrl } from './Workers.constants'+import { getWorkerStateMeta, WORKER_NAME_WORDS, workerUrl } from './Workers.constants'import type { Worker } from './Workers.types'import {filterWorkers,formatResources,formatRuntime,formatSize,+ generateWorkerName,getPage,isWorkersForbidden,isWorkersUnavailable,@@ -163,6 +164,19 @@ describe('workerUrl', () => {})})+describe('generateWorkerName', () => {+ it('produces a name that already passes the CLI naming rules', () => {+ const name = generateWorkerName()+ expect(name).toMatch(/^worker-[a-z]+-\d{6}$/)+ expect(WORKER_NAME_WORDS).toContain(name.split('-')[1])+ })++ it('varies across calls', () => {+ const names = new Set(Array.from({ length: 20 }, () => generateWorkerName()))+ expect(names.size).toBeGreaterThan(1)+ })+})+describe('getWorkerStateMeta', () => {it('labels every build state', () => {expect(getWorkerStateMeta(worker({ name: 'a', buildState: 'building' })).label).toBe('Building')diff --git a/apps/studio/components/interfaces/Workers/Workers.utils.ts b/apps/studio/components/interfaces/Workers/Workers.utils.tsindex d0f32d15edf..ddbcae1ee20 100644--- a/apps/studio/components/interfaces/Workers/Workers.utils.ts+++ b/apps/studio/components/interfaces/Workers/Workers.utils.ts@@ -1,4 +1,4 @@-import { RUNTIMES, type RuntimeMeta } from './Workers.constants'+import { RUNTIMES, WORKER_NAME_WORDS, type RuntimeMeta } from './Workers.constants'import type { Worker, WorkerAccess, WorkerBuildState } from './Workers.types'import { ResponseError } from '@/types'@@ -54,6 +54,13 @@ export const formatSize = (size: string): string => {export const formatResources = (worker: Worker): string =>`${formatSize(worker.size)} · ${worker.declaredInstances} inst`+// Suggests a friendly, already-valid starting name so the deploy dialog isn't blank.+export const generateWorkerName = (): string => {+ const word = WORKER_NAME_WORDS[Math.floor(Math.random() * WORKER_NAME_WORDS.length)]+ const number = Math.floor(Math.random() * 900000) + 100000+ return `worker-${word}-${number}`+}+// A project outside the alpha allow-list gets a 404, not a 403.export const isWorkersUnavailable = (error: Error | null): boolean =>error instanceof ResponseError && error.code === 404diff --git a/apps/studio/components/interfaces/Workers/workerSnippets.test.ts b/apps/studio/components/interfaces/Workers/workerSnippets.test.tsindex 283d93e8bd7..7070d5f014d 100644--- a/apps/studio/components/interfaces/Workers/workerSnippets.test.ts+++ b/apps/studio/components/interfaces/Workers/workerSnippets.test.ts@@ -10,25 +10,21 @@ const input = (overrides: Partial<Parameters<typeof buildWorkerSnippets>[0]> = {})describe('buildWorkerSnippets', () => {- it('points every call snippet at the worker URL', () => {- const { curl, javascript, python } = buildWorkerSnippets(input({ name: 'embed' }))+ it('points the invoke examples at the worker URL', () => {+ const { javascript, python } = buildWorkerSnippets(input({ name: 'embed' }))const url = 'https://abcdefgh.supabase.co/workers/v1/embed'- expect(curl).toContain(`'${url}'`)expect(javascript).toContain(`'${url}'`)expect(python).toContain(`"${url}"`)})- it('leaves a placeholder URL until the project settings resolve', () => {- const { curl } = buildWorkerSnippets(input({ endpoint: undefined }))- expect(curl).toContain('[YOUR WORKER URL]')+ it('leaves a placeholder invoke URL until the project settings resolve', () => {+ const { javascript } = buildWorkerSnippets(input({ endpoint: undefined }))+ expect(javascript).toContain('[YOUR WORKER URL]')})- it('asks for the anon key on a public worker and the service role key on a private one', () => {- expect(buildWorkerSnippets(input({ access: 'public' })).curl).toContain('[YOUR ANON KEY]')- expect(buildWorkerSnippets(input({ access: 'private' })).curl).toContain(- '[YOUR SERVICE ROLE KEY]'- )+ it('asks for the anon key to invoke a public worker and the service role key for a private one', () => {+ expect(buildWorkerSnippets(input({ access: 'public' })).javascript).toContain('[YOUR ANON KEY]')expect(buildWorkerSnippets(input({ access: 'private' })).javascript).toContain('[YOUR SERVICE ROLE KEY]')diff --git a/apps/studio/components/interfaces/Workers/workerSnippets.ts b/apps/studio/components/interfaces/Workers/workerSnippets.tsindex cbcc6e2beb7..02499a1fcb0 100644--- a/apps/studio/components/interfaces/Workers/workerSnippets.ts+++ b/apps/studio/components/interfaces/Workers/workerSnippets.ts@@ -1,4 +1,4 @@-import { WORKERS_REGION, workerUrl } from './Workers.constants'+import { RUNTIMES, WORKERS_REGION, workerUrl } from './Workers.constants'import type { WorkerAccess } from './Workers.types'import { formatSize } from './Workers.utils'import { CLI_NAME } from '@/lib/constants/workers'@@ -14,9 +14,9 @@ export interface WorkerSnippetInput {}export interface WorkerSnippets {+ aiPrompt: stringconfigToml: stringcli: string- curl: stringjavascript: stringpython: string}@@ -40,12 +40,13 @@ export function buildWorkerSnippets(input: WorkerSnippetInput): WorkerSnippets {const cli = [`supabase ${CLI_NAME} new ${name} --runtime ${runtime}`,- `supabase ${CLI_NAME} push ${name}`,+ // size comes from config.toml — push has no flag for it. Same for access: the CLI+ // doesn't have a route to a private worker yet, so this always deploys as public.+ `supabase ${CLI_NAME} push ${name} --instances ${input.instances}`,+ ...(input.access === 'private' ? [`# note: the CLI can only deploy public workers today`] : []),].join('\n')- const configToml = [- `# supabase/config.toml`,- ``,+ const configBlock = [`[${CLI_NAME}.${name}]`,`runtime = "${runtime}"`,`size = "${input.size}" # ${formatSize(input.size)}`,@@ -54,16 +55,26 @@ export function buildWorkerSnippets(input: WorkerSnippetInput): WorkerSnippets {`# region is locked to ${WORKERS_REGION} at alpha`,].join('\n')- const authHeader =- input.access === 'public'- ? ` -H 'Authorization: Bearer [YOUR ANON KEY]' \\`- : ` -H 'Authorization: Bearer [YOUR SERVICE ROLE KEY]' \\`+ const configToml = [`# supabase/config.toml`, ``, configBlock].join('\n')++ const runtimeMeta = RUNTIMES[runtime] ?? RUNTIMES.node+ // The entrypoint metadata is "<run command> <filename>" — the filename is the last token.+ const entrypointFile = runtimeMeta.entrypoint.split(' ').pop()- const curl = [- `curl -L -X POST '${url}' \\`,- authHeader,- ` -H 'Content-Type: application/json' \\`,- ` --data '{"name":"world"}'`,+ const aiPrompt = [+ `Scaffold and deploy a Supabase Workers worker named "${name}" using the ${runtimeMeta.label} runtime:`,+ ``,+ `1. Create a supabase/${CLI_NAME}/${name}/ directory with a ${runtimeMeta.label} entrypoint (${entrypointFile}) that responds with "Hello, world!".`,+ ``,+ `2. Add this block to supabase/config.toml:`,+ '```toml',+ configBlock,+ '```',+ ``,+ `3. Run \`supabase ${CLI_NAME} push ${name}\` to deploy it.`,+ ...(input.access === 'private'+ ? [``, `Note: the CLI can only deploy public workers today.`]+ : []),].join('\n')const keyPlaceholder = input.access === 'public' ? '[YOUR ANON KEY]' : '[YOUR SERVICE ROLE KEY]'@@ -91,7 +102,7 @@ export function buildWorkerSnippets(input: WorkerSnippetInput): WorkerSnippets {`print(res.json())`,].join('\n')- return { configToml, cli, curl, javascript, python }+ return { aiPrompt, configToml, cli, javascript, python }}export interface WorkerCliCommand {diff --git a/apps/studio/pages/project/[ref]/workers/index.tsx b/apps/studio/pages/project/[ref]/workers/index.tsxindex af939bb9209..73debf88890 100644--- a/apps/studio/pages/project/[ref]/workers/index.tsx+++ b/apps/studio/pages/project/[ref]/workers/index.tsx@@ -70,7 +70,7 @@ const WorkersPage: NextPageWithLayout = () => {<Admonitiontype="default"title={`${PRODUCT_NAME} is not enabled for this project`}- description={`${PRODUCT_NAME} is in private alpha. Contact support to have this project added to the alpha.`}+ description={`${PRODUCT_NAME} is in Private Alpha. Contact support to have this project added to the alpha.`}/>)}{isMissingPermission && <NoPermission resourceText="view this project's workers" />}