跳转到内容
搜索文档

生命周期

最后更新 查看 MarkdownAgent 设置

创建并管理 sandbox 容器。获取 sandbox 实例、配置选项并清理资源。

方法

getSandbox()

按 ID 获取或创建 sandbox 实例。

const sandbox = getSandbox(
  binding: DurableObjectNamespace<Sandbox>,
  sandboxId: string,
  options?: SandboxOptions
): Sandbox

参数

  • binding - 来自 Worker 环境的 Durable Object 命名空间绑定(binding)
  • sandboxId - 此 sandbox 的唯一标识符。相同 ID 始终返回同一 sandbox 实例。在面向用户的应用中,请将 ID 限定到单个用户。
  • options(可选)- 有关所有可用选项,请参阅 SandboxOptions
    • enableDefaultSession - 对未显式指定 sessionId 的操作使用默认会话。设为 false 可让每次调用在隔离环境中评估(默认:true
    • sleepAfter - 不活动后自动休眠的时长(默认:"10m"
    • keepAlive - 完全阻止自动休眠。在休眠期间也会保持(默认:false
    • containerTimeouts - 配置容器启动超时
    • normalizeId - 将 sandbox ID 转为小写,以兼容预览 URL(默认:false

返回Sandbox 实例

import { getSandbox } from "@cloudflare/sandbox";

export default {
	async fetch(request, env) {
		const sandbox = getSandbox(env.Sandbox, "user-123");
		const result = await sandbox.exec("python script.py");
		return Response.json(result);
	},
};
import { getSandbox } from '@cloudflare/sandbox';

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const sandbox = getSandbox(env.Sandbox, 'user-123');
    const result = await sandbox.exec('python script.py');
    return Response.json(result);
  }
};

setKeepAlive()

在创建 sandbox 后动态启用或禁用 keepAlive 模式。

await sandbox.setKeepAlive(keepAlive: boolean): Promise<void>

参数

  • keepAlive - true 阻止自动休眠,false 允许正常休眠行为

启用后,sandbox 会每 30 秒自动发送心跳 ping,以防止容器被驱逐。禁用后,sandbox 会根据 sleepAfter 配置恢复正常休眠行为。

const sandbox = getSandbox(env.Sandbox, "user-123");

// Enable keepAlive for a long-running process
await sandbox.setKeepAlive(true);
await sandbox.startProcess("python long_running_analysis.py");

// Later, disable keepAlive when done
await sandbox.setKeepAlive(false);
const sandbox = getSandbox(env.Sandbox, 'user-123');

// Enable keepAlive for a long-running process
await sandbox.setKeepAlive(true);
await sandbox.startProcess('python long_running_analysis.py');

// Later, disable keepAlive when done
await sandbox.setKeepAlive(false);

destroy()

销毁 sandbox 容器并释放资源。

await sandbox.destroy(): Promise<void>

立即终止容器并永久删除所有状态:

  • /workspace/tmp/home 中的所有文件
  • 所有正在运行的进程
  • 所有会话(包括默认会话)
  • 网络连接与已暴露的端口
async function executeCode(code) {
	const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);

	try {
		await sandbox.writeFile("/tmp/code.py", code);
		const result = await sandbox.exec("python /tmp/code.py");
		return result.stdout;
	} finally {
		await sandbox.destroy();
	}
}
async function executeCode(code: string): Promise<string> {
  const sandbox = getSandbox(env.Sandbox, `temp-${Date.now()}`);

  try {
    await sandbox.writeFile('/tmp/code.py', code);
    const result = await sandbox.exec('python /tmp/code.py');
    return result.stdout;
  } finally {
    await sandbox.destroy();
  }
}

相关资源

这篇文档对您有帮助吗?