編集

Cloudflare Sandbox、`sandbox.watch()`でリアルタイムファイル監視に対応

エージェントやビルドパイプラインがSandbox内でファイルを書き換える場面で、ポーリングなしで差分を追えると応答が速くなる。そこでコンテナ内パスを監視するsandbox.watch()が追加。戻り値はServer-Sent EventsReadableStreamで、ネイティブinotifyに裏打ち。Workerはcreatemodifydeletemoveを発生順に受け取れる。

ディレクトリパスと任意のフィルタを渡す。戻りのストリームは標準ReadableStreamのため、ブラウザへtext/event-streamとしてそのまま返すか、Worker内で@cloudflare/sandboxparseSSEStreamによりfor awaitで消費する。各イベントはtypeと影響を受けたpathを持ち、moveでは元パスを示すfromも付く。

オプションはrecursive(子ディレクトリを監視、既定はfalse)とinclude(globの配列、省略時は全イベント)。最新版へはnpm i @cloudflare/sandbox@latest。APIの詳細はSandbox file watching referenceを参照。当該changelogに破壊的変更の記載はない。

javascript
const stream = await sandbox.watch("/workspace/src", {
  recursive: true,
  include: ["*.ts", "*.js"],
});

return new Response(stream, {
  headers: { "Content-Type": "text/event-stream" },
});
javascript
import { parseSSEStream } from "@cloudflare/sandbox";

const stream = await sandbox.watch("/workspace/src", { recursive: true });

for await (const event of parseSSEStream(stream)) {
  console.log(event.type, event.path);
}

#参考文献

編集