跳转到内容
搜索文档

备份

最后更新 查看 MarkdownAgent 设置

创建沙箱目录的时间点快照,并使用写时复制叠加层恢复它们。

方法

createBackup()

创建目录的时间点快照,并将其上传到 R2 存储。

await sandbox.createBackup(options: BackupOptions): Promise<DirectoryBackup>

参数

  • options — 备份配置(见 BackupOptions):
    • dir(必填)— 要备份的目录的绝对路径(例如 "/workspace"
    • name(可选)— 备份的可读名称。最长 256 个字符,无控制字符。
    • ttl(可选)— 备份过期前的生存时间(秒)。默认:259200(3 天)。必须为正数。
    • useGitignore(可选)— 为 true 时,从备份中排除匹配 .gitignore 规则的文件。默认:false。如果目录不在 git 仓库内,则不应用排除。要求容器中可用 git
    • localBucket(可选)— 为 true 时,直接使用 BACKUP_BUCKET R2 绑定,而不是预签名 URL。适用于 wrangler dev。默认:false

返回Promise<DirectoryBackup>,包含:

  • id — 唯一备份标识符(UUID)
  • dir — 已备份的目录
import { getSandbox } from "@cloudflare/sandbox";

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Create a backup of /workspace
const backup = await sandbox.createBackup({ dir: "/workspace" });

// Later, restore the backup
await sandbox.restoreBackup(backup);
import { getSandbox } from "@cloudflare/sandbox";

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Create a backup of /workspace
const backup = await sandbox.createBackup({ dir: "/workspace" });

// Later, restore the backup
await sandbox.restoreBackup(backup);

工作原理

在生产环境中:

  1. 容器从目录创建压缩的 squashfs 归档。
  2. 容器使用预签名 URL 将归档直接上传到 R2。
  3. 元数据与归档一并存储在 R2 中。
  4. 清理本地归档。

使用 localBucket: true(本地开发)时:

  1. 容器从目录创建压缩的 squashfs 归档。
  2. 归档直接上传到 BACKUP_BUCKET R2 绑定。
  3. 元数据与归档一并存储在 R2 中。
  4. 清理本地归档。

抛出

  • InvalidBackupConfigError — 如果 dir 不是绝对路径、包含 ..、缺少 BACKUP_BUCKET 绑定,或(在生产中)未配置 R2 预签名 URL 凭据
  • BackupCreateError — 如果容器创建归档失败、上传到 R2 失败,或 useGitignoretrue 但容器中不可用 git

restoreBackup()

将先前创建的备份恢复到目录中。

await sandbox.restoreBackup(backup: DirectoryBackup): Promise<RestoreBackupResult>

参数

  • backup — 由 createBackup() 返回的备份句柄。包含 iddir。(见 DirectoryBackup

返回Promise<RestoreBackupResult>,包含:

  • success — 恢复是否成功
  • dir — 已恢复的目录
  • id — 已恢复的备份 ID
// Create a named backup with 24-hour TTL
const backup = await sandbox.createBackup({
	dir: "/workspace",
	name: "before-refactor",
	ttl: 86400,
});

// Store the handle for later use
await env.KV.put(`backup:${userId}`, JSON.stringify(backup));
// Create a named backup with 24-hour TTL
const backup = await sandbox.createBackup({
	dir: "/workspace",
	name: "before-refactor",
	ttl: 86400,
});

// Store the handle for later use
await env.KV.put(`backup:${userId}`, JSON.stringify(backup));

工作原理

在生产环境中:

  1. 从 R2 下载元数据并检查 TTL。如果已过期,则抛出错误(带有 60 秒缓冲)。
  2. 容器使用预签名 URL 从 R2 直接下载归档。
  3. 容器使用 FUSE overlayfs 挂载 squashfs 归档。

使用 localBucket: true(本地开发)时:

  1. BACKUP_BUCKET R2 绑定下载元数据并检查 TTL。
  2. 从 R2 绑定下载归档。
  3. 使用 unsquashfs 将归档提取到目标目录。

抛出

  • InvalidBackupConfigError — 如果 backup.id 缺失或不是有效 UUID,或 backup.dir 无效
  • BackupNotFoundError — 如果在 R2 中未找到备份元数据或归档
  • BackupExpiredError — 如果备份 TTL 已过期
  • BackupRestoreError — 如果容器恢复失败

用法模式

排除 gitignored 文件

使用 useGitignore 从备份中排除匹配 .gitignore 规则的文件(例如 node_modules/dist/)。这可减小 git 仓库的备份大小。

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Exclude gitignored files from the backup
const backup = await sandbox.createBackup({
	dir: "/workspace",
	useGitignore: true,
});

// Without useGitignore (default), all files are included
const fullBackup = await sandbox.createBackup({
	dir: "/workspace",
});
const sandbox = getSandbox(env.Sandbox, "my-sandbox");

// Exclude gitignored files from the backup
const backup = await sandbox.createBackup({
	dir: "/workspace",
	useGitignore: true,
});

// Without useGitignore (default), all files are included
const fullBackup = await sandbox.createBackup({
	dir: "/workspace",
});

如果目录不在 git 仓库内,useGitignore 无效,所有文件都会被包含。如果 useGitignoretrue 但容器中未安装 git,则抛出 BackupCreateError

检查点与恢复

在高风险操作前将备份用作检查点。

// Save checkpoint before risky operation
const checkpoint = await sandbox.createBackup({ dir: "/workspace" });

try {
	await sandbox.exec("npm install some-experimental-package");
	await sandbox.exec("npm run build");
} catch (error) {
	// Restore to the checkpoint if something goes wrong
	await sandbox.restoreBackup(checkpoint);
}
// Save checkpoint before risky operation
const checkpoint = await sandbox.createBackup({ dir: "/workspace" });

try {
	await sandbox.exec("npm install some-experimental-package");
	await sandbox.exec("npm run build");
} catch (error) {
	// Restore to the checkpoint if something goes wrong
	await sandbox.restoreBackup(checkpoint);
}

错误处理

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

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

try {
	const backup = await sandbox.createBackup({ dir: "/workspace" });
	console.log(`Backup created: ${backup.id}`);
} catch (error) {
	if (error.code === "INVALID_BACKUP_CONFIG") {
		console.error("Configuration error:", error.message);
	} else if (error.code === "BACKUP_CREATE_FAILED") {
		console.error("Backup failed:", error.message);
	}
}
import { getSandbox } from "@cloudflare/sandbox";

const sandbox = getSandbox(env.Sandbox, "my-sandbox");

try {
	const backup = await sandbox.createBackup({ dir: "/workspace" });
	console.log(`Backup created: ${backup.id}`);
} catch (error) {
	if (error.code === "INVALID_BACKUP_CONFIG") {
		console.error("Configuration error:", error.message);
	} else if (error.code === "BACKUP_CREATE_FAILED") {
		console.error("Backup failed:", error.message);
	}
}

行为

  • 同一沙箱上的并发备份与恢复操作会自动串行化。
  • 返回的 DirectoryBackup 句柄可序列化——可将其存储在 KV、D1 或 Durable Object 存储中。
  • 重叠的备份彼此独立。恢复父目录会覆盖子目录挂载。

TTL 强制执行

ttl 值控制备份何时视为过期。SDK 仅在恢复时强制执行此规则——当你调用 restoreBackup() 时,SDK 从 R2 读取备份元数据,并检查 TTL 是否已过期。如果已过期,恢复会以 BACKUP_EXPIRED 错误被拒绝。

TTL 不会自动从 R2 删除对象。过期的备份归档与元数据会保留在你的 R2 存储桶中,直到你删除它们。要自动清理过期对象,请在备份存储桶上配置 R2 对象生命周期规则。没有生命周期规则时,过期备份会继续占用 R2 存储。

类型

BackupOptions

interface BackupOptions {
	dir: string;
	name?: string;
	ttl?: number;
	useGitignore?: boolean;
	localBucket?: boolean;
}

字段

  • dir(必填)— 要备份的目录的绝对路径
  • name(可选)— 可读的备份名称。最长 256 个字符,无控制字符。
  • ttl(可选)— 生存时间(秒)。默认:259200(3 天)。必须为正数。
  • useGitignore(可选)— 为 true 时,如果目录在 git 仓库内,则排除匹配 .gitignore 规则的文件。默认:false。如果目录不在 git 仓库内,则不应用基于 git 的排除。
  • localBucket(可选)— 为 true 时,直接使用 BACKUP_BUCKET R2 绑定,而不是预签名 URL。适用于 wrangler dev。默认:false

DirectoryBackup

interface DirectoryBackup {
	readonly id: string;
	readonly dir: string;
}

字段

  • id — 唯一备份标识符(UUID)
  • dir — 已备份的目录

RestoreBackupResult

interface RestoreBackupResult {
	success: boolean;
	dir: string;
	id: string;
}

字段

  • success — 恢复是否成功
  • dir — 已恢复的目录
  • id — 已恢复的备份 ID

相关资源

这篇文档对您有帮助吗?