INTEGRITY Dokumentace

Životní cyklus

Vytvářejte a spravujte kontejnery sandboxu. Získávejte instance sandboxu, konfigurujte možnosti a uklízejte prostředky.

Metody

getSandbox()

Získejte nebo vytvořte instanci sandboxu podle ID.

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

Parametry:

Vrací: Sandbox instance

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()

Po vytvoření sandboxu můžete dynamicky povolit nebo zakázat režim keepAlive.

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

Parametry:

Pokud je tato funkce zapnutá, sandbox automaticky odesílá heartbeat pingy každých 30 sekund, aby se zabránilo odstranění kontejneru. Pokud je vypnutá, sandbox se vrátí k běžnému chování usínání podle sleepAfter konfigurace.

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()

Zničte kontejner sandboxu a uvolněte prostředky.

await sandbox.destroy(): Promise<void>

Okamžitě ukončí kontejner a natrvalo smaže veškerý stav:

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();
  }
}