サンドボックスコンテナを作成し、管理します。サンドボックスインスタンスの取得、オプションの設定、リソースのクリーンアップができます。
ID でサンドボックスインスタンスを取得または作成します。
const sandbox = getSandbox(
binding: DurableObjectNamespace<Sandbox>,
sandboxId: string,
options?: SandboxOptions
): Sandboxパラメーター:
binding- Worker 環境の Durable Object 名前空間バインディングsandboxId- このサンドボックスの一意な識別子。同じ ID は常に同じサンドボックスインスタンスを返します。ユーザー向けアプリでは、ID を 1 人のユーザーにスコープしてください。options(任意) - 利用できるすべてのオプションは SandboxOptions を参照してください:enableDefaultSession- 明示的なsessionIdなしの操作でデフォルトセッションを使います。各呼び出しを分離して評価するにはfalseにします(デフォルト:true)sleepAfter- 自動スリープまでの非アクティブ期間(デフォルト:"10m")keepAlive- 自動スリープを完全に防ぎます。ハイバネーションをまたいで保持されます(デフォルト:false)containerTimeouts- コンテナ起動タイムアウトを設定しますnormalizeId- プレビュー URL 互換のため、サンドボックス ID を小文字にします(デフォルト: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);
}
};サンドボックス作成後に、keepAlive モードを動的に有効または無効にします。
await sandbox.setKeepAlive(keepAlive: boolean): Promise<void>パラメーター:
keepAlive- 自動スリープを防ぐ場合はtrue、通常のスリープ動作にする場合はfalse
有効にすると、サンドボックスはコンテナの退避を防ぐため、30 秒ごとにハートビート ping を自動送信します。無効にすると、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);サンドボックスコンテナを破棄し、リソースを解放します。
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();
}
}- Sandbox ライフサイクルの概念 - コンテナのライフサイクルと状態
- Sandbox オプションの設定 -
keepAliveとその他のオプション - Sessions API - サンドボックス内の実行コンテキストを作成する