Use sandboxes and edge functions

更新时间:
复制 MD 格式

RDS Supabase sandboxes provide secure, isolated code execution through the e2b SDK. Edge functions run server-side TypeScript on the Deno runtime within your Supabase instance.

Prerequisites

  • An RDS Supabase instance in the Running state.

  • The instance is in the China (Beijing), China (Shanghai), China (Hangzhou), China (Shenzhen), or China (Chengdu) region.

  • The AliyunServiceRoleForRDSAISupabase service-linked role is authorized.

Billing

Sandboxes and edge functions are in public preview at no charge.

Enable sandboxes and edge functions

  1. Log on to the RDS console. In the navigation pane on the left, click AI Application Development Supabase.

  2. In the top navigation bar, select a region. Click the target instance ID.

  3. In the navigation pane on the left, click Sandboxes and Edge Functions.

  4. Turn on the Enable Sandboxes and Edge Functions switch.

    Available sandbox templates appear.

Use sandboxes

Sandboxes provide secure, isolated code execution through the e2b SDK, supporting file operations, command execution, and code running. Before using sandboxes, bind a domain name and configure the SDK environment.

Step 1: Bind a domain name

Bind a domain name to your Supabase instance IP address. For development and testing, add this to your local /etc/hosts file.

  1. On the instance details page, find the public endpoint IP address.

  2. Add a mapping to your local /etc/hosts file. Example using <instance-id>.sb.rds.com as the domain name:

    <instance-ip-address> <instance-id>.sb.rds.com

Step 2: Download the e2b SDK patch code

Download the e2b SDK patch code from GitHub. This patch adapts the SDK to RDS Supabase routing.

Step 3: (Optional) Configure SSL for HTTPS access

To access the sandbox over HTTPS, configure an SSL certificate for your Supabase instance. Configure SSL for HTTPS access for RDS Supabase.

After configuring SSL, set the following environment variables:

# rootCA.pem is the CA certificate of the SSL certificate generated for the Supabase instance.
export SSL_CERT_FILE="/xxx/rootCA.pem"
export REQUESTS_CA_BUNDLE="/xxx/rootCA.pem"

Step 4: Configure e2b SDK environment variables

Set the following environment variables for the e2b SDK to connect to your Supabase instance.

# E2B_DOMAIN: The domain name that you bound in Step 1.
export E2B_DOMAIN=<instance-id>.sb.rds.com

# E2B_API_KEY: The Service Key of your Supabase instance.
export E2B_API_KEY=<your_service_key>
Note

To get the Service Key: On the instance details page, click Get API Key in the upper-right corner. In the dialog box that appears, copy the value of Service Key.

Step 5: Get template ID and create sandbox

  1. On the Sandboxes and Edge Functions page of your instance, find the Sandbox Templates table and copy the template ID of the target template.

  2. In your project code, import the patch file from Step 2, then use the template ID to create a sandbox.

Examples in Python and TypeScript:

Python

Use the e2b SDK for Python to create a sandbox and perform operations.

import time
from e2b_code_interpreter import Sandbox
from patch_e2b import patch_e2b

# Enable HTTPS. Set to False if an SSL certificate is not configured.
patch_e2b(True)

# Create a sandbox by using the template ID from the console.
sbx: Sandbox = Sandbox.create(
    template="<template-id>",
    timeout=600,
    request_timeout=300
)
print("sandbox_id: " + sbx.sandbox_id)

try:
    # Write to a file.
    sbx.files.write("/home/user/test.txt", "Hello from sandbox!")

    # Read from the file.
    content = sbx.files.read("/home/user/test.txt")
    print(f"File content: {content}")

    # Run a shell command.
    result = sbx.commands.run("ls -la /home/user")
    print(f"Exit code: {result.exit_code}")
    print(f"Stdout: {result.stdout}")

    # Run Python code.
    time.sleep(1)
    execution = sbx.run_code("print('hello world')")
    print(f"Results: {execution.results}")
    print(f"Logs: {execution.logs}")
finally:
    sbx.kill()
    print("Sandbox closed.")

TypeScript

Use the e2b SDK for TypeScript to create a sandbox and perform operations.

import { patchE2b } from './patchE2b'
import { Sandbox } from '@e2b/code-interpreter'

// Enable HTTPS. Set to false if an SSL certificate is not configured.
await patchE2b(true)

// Create a sandbox by using the template ID from the console.
const sandbox = await Sandbox.create('<template-id>', {
  timeoutMs: 600_000,
  requestTimeoutMs: 300_000,
})
console.log(`sandbox_id: ${sandbox.sandboxId}`)

try {
  // Write to a file.
  await sandbox.files.write('/home/user/test.txt', 'Hello from sandbox!')

  // Read from the file.
  const content = await sandbox.files.read('/home/user/test.txt')
  console.log(`File content: ${content}`)

  // Run a shell command.
  const result = await sandbox.commands.run('ls -la /home/user')
  console.log(`Exit code: ${result.exitCode}`)
  console.log(`Stdout: ${result.stdout}`)

  // Run Python code.
  await new Promise(r => setTimeout(r, 1000))
  const execution = await sandbox.runCode("print('hello world')")
  console.log(`Results: ${JSON.stringify(execution.results)}`)
  console.log(`Logs: ${JSON.stringify(execution.logs)}`)
} finally {
  await sandbox.kill()
  console.log('Sandbox closed.')
}

Use edge functions

Edge functions run server-side TypeScript on the Deno runtime. Use the Agent Runtime console to create, deploy, and manage edge functions and configure secrets.

Access Agent Runtime console

Open the Agent Runtime console at:

http://<supabase-instance-public-endpoint>/agent-runtime
Note

The public endpoint is in the Network Information section of the instance details page.

Deploy an edge function

Note

You can create up to 5 edge functions for each Supabase instance.

  1. In the navigation pane on the left of the Agent Runtime console, click Functions.

  2. In the upper-right corner, click Deploy a new function.

  3. On the Create new edge function page, write your function code.

    The following is a simple example of an edge function:

    import "jsr:@supabase/functions-js/edge-runtime.d.ts";
    
    interface reqPayload {
      name: string;
    }
    
    Deno.serve(async (req: Request) => {
      const { name }: reqPayload = await req.json();
      const data = {
        message: `Hello ${name}!`,
      };
      return new Response(
        JSON.stringify(data),
        { headers: { 'Content-Type': 'application/json' } }
      );
    });
  4. At the bottom of the page, enter a name in the Function name field, and then click Deploy Function.

Manage edge functions

Click a function name to open its details page. Available actions:

  • View and edit code: Edit code on the Code tab and click Deploy updates.

  • Configure function settings: On the Settings tab, change the function name or toggle VERIFY JWT.

  • Delete a function: On the Settings tab, go to Danger Zone and click Delete Function.

    Warning

    This action cannot be undone. Proceed with caution.

Manage Secrets

Secrets store sensitive data such as API keys and database connection strings for use in edge functions.

  1. In the navigation pane on the left of the Agent Runtime console, click Secrets.

  2. In the upper-right corner, click Add new secret.

  3. Enter a name and value for the secret.

Note

The system creates these default secrets: SUPABASE_URL, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY, SUPABASE_DB_URL, and SUPABASE_PUBLIC_URL. Retrieve them in your code with Deno.env.get('SECRET_NAME').