cn-durable-objects
Installation
Review the source and dependencies with a prompt. A package is available to download.
Install with an AI assistant
Copy the prompt so your assistant can review the pinned revision and dependencies first.
View promptHide prompt
Check whether SkillPI Skill Finder is installed for your current agent. If it is missing, install and enable it using the official instructions at https://github.com/Findskills/skillpi. Then use Skill Finder to locate and install "cn-durable-objects" from this exact SkillPI detail page: https://skillpi.com/skills/deepskill-52e8ed1a9e800eb04ccf4b3ccde26b04df0993a34642910ad077f0a0864f5bc6. Verify the upstream source and version against https://skillhub.cn/skills/user_55e286a5/cn-durable-objects before installing. If they do not match, stop and report the mismatch. Report the installed path and source version.
Source and setup
skillhub.cn
Setup guidance pending
See the original source for supported tools, dependencies, and permissions.
Installation test pending
Build and review Cloudflare Durable Objects stateful applications: chatrooms, collaboration, multiplayer games, scheduling/appointments, RPC, SQLite storage, alarms, WebSocket, and single-entity consistency.
Introduction source: third_party · user_55e286a5 · 1.0.0 Reference
SkillPi interpretation
- Tasks
- Translation pending; see source documentation.
- Audience
- Translation pending; see source documentation.
- Inputs and outputs
- Not specified in the source documentation.
- Software, accounts and paid services
- Not specified in the source documentation.
- Limits and differences
- Not specified in the source documentation.
- Testing
- Not tested
Browse files
Frontmatter
name: cn-durable-objects
slug: cn-durable-objects
version: 1.0.0
displayName: Cloudflare Durable Objects 开发助手
summary: 构建与审查 Cloudflare Durable Objects 有状态应用:聊天室、协作、多人游戏、预约、RPC、SQLite 存储、Alarm、WebSocket 与单实体一致性。
description: 在构建或审查 Cloudflare Durable Objects 用于有状态协调、聊天室、多人游戏、预约、RPC、SQLite 存储、Alarm、WebSocket 或单实体一致性时使用。
tags: [cloudflare, durable-objects, workers, websocket, sqlite, realtime, distributed-state]
license: MIT
homepage: https://developers.cloudflare.com/durable-objects/Durable Objects
使用 Durable Objects 在 Cloudflare 边缘网络上构建有状态、可协调的应用程序。
检索来源
你关于 Durable Objects API 与配置的知识可能已经过时。对于任何 Durable Objects 任务,应优先使用检索,而非依赖预训练知识。
实现功能时,获取相关的文档页面。
使用场景
- 为状态协调创建新的 Durable Object 类
- 实现 RPC 方法、Alarm(闹钟)或 WebSocket 处理器
- 审查现有 DO 代码是否符合最佳实践
- 为 DO 绑定与迁移配置 wrangler.jsonc/toml
- 使用
@cloudflare/vitest-pool-workers编写测试 - 设计分片策略与父子关系
参考文档
./references/rules.md- 核心规则、存储、并发、RPC、Alarm./references/testing.md- Vitest 配置、单元测试/集成测试、Alarm 测试./references/workers.md- Workers 处理器、类型、wrangler 配置、可观测性
检索关键词:blockConcurrencyWhile、idFromName、getByName、setAlarm、sql.exec
核心原则
适用场景
| 需求 | 示例 |
|---|---|
| 协调 | 聊天室、多人游戏、协作文档 |
| 强一致性 | 库存、预约系统、回合制游戏 |
| 单实体存储 | 多租户 SaaS、按用户数据 |
| 持久连接 | WebSocket、实时通知 |
| 单实体定时任务 | 订阅续费、游戏超时 |
不适用场景
- 无状态请求处理(应使用普通 Workers)
- 需要最大程度的全球分布
- 高扇出、相互独立的请求
快速参考
Wrangler 配置
// wrangler.jsonc
{
"durable_objects": {
"bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }]
},
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }]
}
基础 Durable Object 模式
import { DurableObject } from "cloudflare:workers";
export interface Env {
MY_DO: DurableObjectNamespace<MyDurableObject>;
}
export class MyDurableObject extends DurableObject<Env> {
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
ctx.blockConcurrencyWhile(async () => {
this.ctx.storage.sql.exec(`
CREATE TABLE IF NOT EXISTS items (
id INTEGER PRIMARY KEY AUTOINCREMENT,
data TEXT NOT NULL
)
`);
});
}
async addItem(data: string): Promise<number> {
const result = this.ctx.storage.sql.exec<{ id: number }>(
"INSERT INTO items (data) VALUES (?) RETURNING id",
data
);
return result.one().id;
}
}
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const stub = env.MY_DO.getByName("my-instance");
const id = await stub.addItem("hello");
return Response.json({ id });
},
};
关键规则
- 围绕协调单元建模 - 每个聊天室/游戏/用户对应一个 DO,而非一个全局 DO
- 使用
getByName()实现确定性路由 - 相同输入 = 相同 DO 实例 - 使用 SQLite 存储 - 在 migrations 中配置
new_sqlite_classes - 在构造函数中初始化 - 仅使用
blockConcurrencyWhile()初始化表结构 - 使用 RPC 方法 - 而非 fetch() 处理器(兼容性日期 >= 2024-04-03)
- 先持久化,再缓存 - 始终先写入存储,再更新内存状态
- 每个 DO 仅一个 Alarm -
setAlarm()会替换任何已存在的 Alarm
反模式(绝对禁止)
- 单个全局 DO 处理所有请求(形成瓶颈)
- 在每个请求上都使用
blockConcurrencyWhile()(会严重降低吞吐量) - 仅将关键状态保存在内存中(在驱逐/崩溃时丢失)
- 在相关联的存储写入之间使用
await(破坏原子性) - 在
blockConcurrencyWhile()中跨fetch()或外部 I/O 持有锁
Stub 创建
// Deterministic - preferred for most cases
const stub = env.MY_DO.getByName("room-123");
// From existing ID string
const id = env.MY_DO.idFromString(storedIdString);
const stub = env.MY_DO.get(id);
// New unique ID - store mapping externally
const id = env.MY_DO.newUniqueId();
const stub = env.MY_DO.get(id);
存储操作
// SQL (synchronous, recommended)
this.ctx.storage.sql.exec("INSERT INTO t (c) VALUES (?)", value);
const rows = this.ctx.storage.sql.exec<Row>("SELECT * FROM t").toArray();
// KV (async)
await this.ctx.storage.put("key", value);
const val = await this.ctx.storage.get<Type>("key");
Alarms
// Schedule (replaces existing)
await this.ctx.storage.setAlarm(Date.now() + 60_000);
// Handler
async alarm(): Promise<void> {
// Process scheduled work
// Optionally reschedule: await this.ctx.storage.setAlarm(...)
}
// Cancel
await this.ctx.storage.deleteAlarm();
测试快速入门
import { env } from "cloudflare:test";
import { describe, it, expect } from "vitest";
describe("MyDO", () => {
it("should work", async () => {
const stub = env.MY_DO.getByName("test");
const result = await stub.addItem("test");
expect(result).toBe(1);
});
});Current listing version
1.0.0
Safety and assessment details
Quality assessment
Out of 100 · Assessment report from SkillPi LAB.
Highlights
- 提供 Cloudflare Durable Objects 构建与审查的完整指南,涵盖聊天室、协作、多人游戏、预约、RPC、SQLite 存储、Alarm、WebSocket 等高频刚需场景
- 内容详实,具有明确的实用价值和广泛受众
Highlights
- description 明确指出使用场景(构建或审查 Cloudflare Durable Objects),触发词精准完整,覆盖多种变体,边界清晰
Highlights
- 文档结构清晰,包含 Phase/步骤、核心原则、快速参考、关键规则、反模式、Stub 创建、存储操作、Alarms、测试快速入门等完整章节
- frontmatter 完整,单文件未超过 500 行
Highlights
- 提供了完整的代码示例、配置模板、测试方法,工具来源明确(Cloudflare 官方),参数正确
- 覆盖了主要异常处理(如 blockConcurrencyWhile 的正确使用),不可逆操作有明确说明
The arithmetic mean of the first four original scores, rounded to a whole number.
Static text checks
100 / 100 · skillpi-20261123-no-r3-v1
No current rules matched the text.
This score reflects rule matches in the text and is provided for reference before use. It excludes attachments and runtime behavior.
Permissions and checks before use
Automatically summarized from this main document. Matches may be examples or defensive advice; they are not actual permission declarations. Attachments, external dependencies and runtime behavior are not covered.
These common operations were not identified in the main document. This does not mean no permissions or risks exist.
Domains or addresses referenced in the document
These addresses may be documentation links or examples, not an approved network allowlist. Verify actual destinations and outgoing data before use.
- developers.cloudflare.com
Security rating and access scope
safe · Static evidence review; not a runtime safety guarantee.
Not specified in the source documentation.
Before use, confirm and authorize actual file access, external services and network destinations in your host. This review grants no runtime permissions.
User discussion
No verified reviews yet.