Diffinery

homeflare/celldpublic

46 lines · 1.8 KBRaw History
1import { getSandbox, Sandbox } from "@cloudflare/sandbox";
2
3export { Sandbox };
4
5// One sandbox per `id`: a Linux environment with a shell, a filesystem,
6// and background processes, supervised by the Durable Object.
7export default {
8 async fetch(request, env) {
9 const url = new URL(request.url);
10 const sandbox = getSandbox(env.Sandbox, url.searchParams.get("id") ?? "demo");
11 switch (url.pathname) {
12 case "/exec": {
13 const command = url.searchParams.get("cmd") ?? "uname -a";
14 const result = await sandbox.exec(command);
15 return Response.json({
16 stdout: result.stdout,
17 stderr: result.stderr,
18 exitCode: result.exitCode,
19 });
20 }
21 case "/write": {
22 await sandbox.writeFile("/workspace/note.txt", `written at ${new Date().toISOString()}\n`);
23 const file = await sandbox.readFile("/workspace/note.txt");
24 return Response.json({ content: file.content });
25 }
26 case "/serve": {
27 // A background process that outlives this request: a small HTTP
28 // server. It uses node, which the Sandbox image ships, rather than a
29 // language the image may not carry.
30 const process = await sandbox.startProcess(
31 `node -e "require('http').createServer((_req, res) => res.end('served from the sandbox')).listen(8787, '0.0.0.0')"`,
32 );
33 return Response.json({ id: process.id, status: process.status });
34 }
35 case "/processes": {
36 const list = await sandbox.listProcesses();
37 return Response.json(list.map((process) => ({ id: process.id, status: process.status })));
38 }
39 default:
40 return new Response(
41 "Try /exec?cmd=..., /write, /serve, or /processes, with ?id=<sandbox>\n",
42 { headers: { "content-type": "text/plain" } },
43 );
44 }
45 },
46};