Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

R2 でデータを永続化する

最終更新 Markdown で表示Agent セットアップ

オブジェクトストレージのバケットをローカルのファイルシステムパスとしてマウントし、サンドボックスのライフサイクルをまたいでデータを永続化します。このチュートリアルでは Cloudflare R2 を使いますが、同じ手順は任意の S3 互換プロバイダーでも使えます。

このチュートリアルでは、/data にマウントした外部データディレクトリを永続化します。/workspace の作業プロジェクトを永続化したい場合は バックアップと復元 を参照してください。

所要時間: 20 分

作るもの

データを処理し、ローカルディレクトリとしてマウントした R2 バケットに結果を保存する Worker です。サンドボックスを破棄して再作成しても、データが残ることを確認します。

学べるポイント:

  • R2 バケットをファイルシステムパスとしてマウントする
  • サンドボックスのライフサイクルをまたいだ自動的なデータ永続化
  • 標準のファイル操作でマウント済みストレージを扱う

前提条件

  1. Cloudflare アカウント に登録します。
  2. Node.js をインストールします。

Node.js のバージョンマネージャー

権限の問題を避け、Node.js のバージョンを切り替えられるよう、Voltanvm などの Node バージョンマネージャーを使います。このガイドの後半で説明する Wrangler には、Node バージョン 16.17.0 以降が必要です。

次も必要です。

1. プロジェクトを作成する

npm create cloudflare@latest -- data-pipeline --template=cloudflare/sandbox-sdk/examples/minimal
cd data-pipeline

2. R2 バインディングを設定する

wrangler.json に R2 バケットのバインディングを追加します。

wrangler.jsonjson
{
  "name": "data-pipeline",
  "compatibility_date": "2025-11-09",
  "durable_objects": {
    "bindings": [
      { "name": "Sandbox", "class_name": "Sandbox" }
    ]
  },
  "r2_buckets": [
    {
      "binding": "DATA_BUCKET",
      "bucket_name": "my-data-bucket"
    }
  ]
}

my-data-bucket を自分の R2 バケット名に置き換えます。先に Cloudflare ダッシュボード でバケットを作成してください。

3. データ処理を実装する

src/index.ts を、R2 をマウントしてデータを処理するコードに置き換えます。

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

export { Sandbox } from "@cloudflare/sandbox";

export default {
	async fetch(request, env) {
		const url = new URL(request.url);
		const sandbox = getSandbox(env.Sandbox, "data-processor");

		// Mount R2 bucket to /data directory
		await sandbox.mountBucket("my-data-bucket", "/data", {
			endpoint: "https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com",
		});

		if (url.pathname === "/process") {
			// Process data and save to mounted R2
			const result = await sandbox.exec("python", {
				args: [
					"-c",
					`
import json
import os
from datetime import datetime

# Read input (or create sample data)
data = [
    {'id': 1, 'value': 42},
    {'id': 2, 'value': 87},
    {'id': 3, 'value': 15}
]

# Process: calculate sum and average
total = sum(item['value'] for item in data)
avg = total / len(data)

# Save results to mounted R2 (/data is the mounted bucket)
result = {
    'timestamp': datetime.now().isoformat(),
    'total': total,
    'average': avg,
    'processed_count': len(data)
}

os.makedirs('/data/results', exist_ok=True)
with open('/data/results/latest.json', 'w') as f:
    json.dump(result, f, indent=2)

print(json.dumps(result))
				`,
				],
			});

			return Response.json({
				message: "Data processed and saved to R2",
				result: JSON.parse(result.stdout),
			});
		}

		if (url.pathname === "/results") {
			// Read results from mounted R2
			const result = await sandbox.exec("cat", {
				args: ["/data/results/latest.json"],
			});

			if (!result.success) {
				return Response.json(
					{ error: "No results found yet" },
					{ status: 404 },
				);
			}

			return Response.json({
				message: "Results retrieved from R2",
				data: JSON.parse(result.stdout),
			});
		}

		if (url.pathname === "/destroy") {
			// Destroy sandbox to demonstrate persistence
			await sandbox.destroy();
			return Response.json({
				message: "Sandbox destroyed. Data persists in R2!",
			});
		}

		return new Response(
			`
Data Pipeline with Persistent Storage

Endpoints:
- POST /process  - Process data and save to R2
- GET /results   - Retrieve results from R2
- POST /destroy  - Destroy sandbox (data survives!)

Try this flow:
1. POST /process  (processes and saves to R2)
2. POST /destroy  (destroys sandbox)
3. GET /results   (data still accessible from R2)
		`,
			{ headers: { "Content-Type": "text/plain" } },
		);
	},
};
import { getSandbox, type Sandbox } from '@cloudflare/sandbox';

export { Sandbox } from '@cloudflare/sandbox';

interface Env {
	Sandbox: DurableObjectNamespace<Sandbox>;
	DATA_BUCKET: R2Bucket;
}

export default {
	async fetch(request: Request, env: Env): Promise<Response> {
		const url = new URL(request.url);
		const sandbox = getSandbox(env.Sandbox, 'data-processor');

		// Mount R2 bucket to /data directory
		await sandbox.mountBucket('my-data-bucket', '/data', {
			endpoint: 'https://YOUR_ACCOUNT_ID.r2.cloudflarestorage.com'
		});

		if (url.pathname === '/process') {
			// Process data and save to mounted R2
			const result = await sandbox.exec('python', {
				args: ['-c', `
import json
import os
from datetime import datetime

# Read input (or create sample data)
data = [
    {'id': 1, 'value': 42},
    {'id': 2, 'value': 87},
    {'id': 3, 'value': 15}
]

# Process: calculate sum and average
total = sum(item['value'] for item in data)
avg = total / len(data)

# Save results to mounted R2 (/data is the mounted bucket)
result = {
    'timestamp': datetime.now().isoformat(),
    'total': total,
    'average': avg,
    'processed_count': len(data)
}

os.makedirs('/data/results', exist_ok=True)
with open('/data/results/latest.json', 'w') as f:
    json.dump(result, f, indent=2)

print(json.dumps(result))
				`]
			});

			return Response.json({
				message: 'Data processed and saved to R2',
				result: JSON.parse(result.stdout)
			});
		}

		if (url.pathname === '/results') {
			// Read results from mounted R2
			const result = await sandbox.exec('cat', {
				args: ['/data/results/latest.json']
			});

			if (!result.success) {
				return Response.json({ error: 'No results found yet' }, { status: 404 });
			}

			return Response.json({
				message: 'Results retrieved from R2',
				data: JSON.parse(result.stdout)
			});
		}

		if (url.pathname === '/destroy') {
			// Destroy sandbox to demonstrate persistence
			await sandbox.destroy();
			return Response.json({ message: 'Sandbox destroyed. Data persists in R2!' });
		}

		return new Response(`
Data Pipeline with Persistent Storage

Endpoints:
- POST /process  - Process data and save to R2
- GET /results   - Retrieve results from R2
- POST /destroy  - Destroy sandbox (data survives!)

Try this flow:
1. POST /process  (processes and saves to R2)
2. POST /destroy  (destroys sandbox)
3. GET /results   (data still accessible from R2)
		`, { headers: { 'Content-Type': 'text/plain' } });
	}
};

4. 本番へデプロイする

R2 API トークンを発行する:

  1. Cloudflare ダッシュボードR2 > Overview を開きます
  2. Manage R2 API Tokens を選択します
  3. Object Read & Write 権限のトークンを作成します
  4. Access Key IDSecret Access Key をコピーします

認証情報を Worker のシークレットとして設定する:

npx wrangler secret put AWS_ACCESS_KEY_ID
# Paste your R2 Access Key ID

npx wrangler secret put AWS_SECRET_ACCESS_KEY
# Paste your R2 Secret Access Key

Worker のシークレットは暗号化され、デプロイした Worker だけがアクセスできます。mountBucket() を呼ぶと、SDK がこれらの認証情報を自動で検出します。

Worker をデプロイする:

npx wrangler deploy

デプロイ後、wrangler が Worker URL(例: https://data-pipeline.yourname.workers.dev)を出力します。

5. 永続化の流れを確認する

デプロイした Worker に対して確認します。YOUR_WORKER_URL を実際の Worker URL に置き換えてください。

# 1. Process data (saves to R2)
curl -X POST https://YOUR_WORKER_URL/process
# Returns: { "message": "Data processed...", "result": { "total": 144, "average": 48, ... } }

# 2. Verify data is accessible
curl https://YOUR_WORKER_URL/results
# Returns the same results from R2

# 3. Destroy the sandbox
curl -X POST https://YOUR_WORKER_URL/destroy
# Returns: { "message": "Sandbox destroyed. Data persists in R2!" }

# 4. Access results again (from new sandbox)
curl https://YOUR_WORKER_URL/results
# Still works! Data persisted across sandbox lifecycle

ポイントは次のとおりです。サンドボックスを破棄したあと、次のリクエストで新しいサンドボックスインスタンスが作られ、同じ R2 バケットがマウントされ、データが残っていることを確認できます。

学んだこと

このチュートリアルでは、R2 バケットのマウントによるファイルシステムの永続化を示すデータパイプラインを作りました。

  • バケットのマウント: mountBucket() で R2 をローカルディレクトリとして使えます
  • 標準のファイル操作: cat や Python の open() など、使い慣れたファイルシステムコマンドでマウント済みバケットにアクセスできます
  • 自動的な永続化: マウントしたディレクトリへ書いたデータは、サンドボックスの破棄後も残ります
  • 適切な永続化モデルを選ぶ: /data のような外部ストレージディレクトリにはバケットマウントを使い、/workspace 配下の作業領域を残したいときはバックアップと復元を検討します
  • 認証情報の管理: 環境変数または明示的な認証情報で R2 アクセスを設定します

次のステップ

関連リソース

役に立ちましたか?