← 返回 Skills 市场
creativerezz

Durable Objects

作者 Reza · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
22
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install durable-objects
功能描述
Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC meth...
使用说明 (SKILL.md)

Durable Objects

Build stateful, coordinated applications on Cloudflare's edge using Durable Objects.

Retrieval Sources

Your knowledge of Durable Objects APIs and configuration may be outdated. Prefer retrieval over pre-training for any Durable Objects task.

Resource URL
Docs https://developers.cloudflare.com/durable-objects/
API Reference https://developers.cloudflare.com/durable-objects/api/
Best Practices https://developers.cloudflare.com/durable-objects/best-practices/
Examples https://developers.cloudflare.com/durable-objects/examples/

Fetch the relevant doc page when implementing features.

When to Use

  • Creating new Durable Object classes for stateful coordination
  • Implementing RPC methods, alarms, or WebSocket handlers
  • Reviewing existing DO code for best practices
  • Configuring wrangler.jsonc/toml for DO bindings and migrations
  • Writing tests with @cloudflare/vitest-pool-workers
  • Designing sharding strategies and parent-child relationships

Reference Documentation

  • ./references/rules.md - Core rules, storage, concurrency, RPC, alarms
  • ./references/testing.md - Vitest setup, unit/integration tests, alarm testing
  • ./references/workers.md - Workers handlers, types, wrangler config, observability

Search: blockConcurrencyWhile, idFromName, getByName, setAlarm, sql.exec

Core Principles

Use Durable Objects For

Need Example
Coordination Chat rooms, multiplayer games, collaborative docs
Strong consistency Inventory, booking systems, turn-based games
Per-entity storage Multi-tenant SaaS, per-user data
Persistent connections WebSockets, real-time notifications
Scheduled work per entity Subscription renewals, game timeouts

Do NOT Use For

  • Stateless request handling (use plain Workers)
  • Maximum global distribution needs
  • High fan-out independent requests

Quick Reference

Wrangler Configuration

// wrangler.jsonc
{
  "durable_objects": {
    "bindings": [{ "name": "MY_DO", "class_name": "MyDurableObject" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDurableObject"] }]
}

Basic Durable Object Pattern

import { DurableObject } from "cloudflare:workers";

export interface Env {
  MY_DO: DurableObjectNamespace\x3CMyDurableObject>;
}

export class MyDurableObject extends DurableObject\x3CEnv> {
  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\x3Cnumber> {
    const result = this.ctx.storage.sql.exec\x3C{ id: number }>(
      "INSERT INTO items (data) VALUES (?) RETURNING id",
      data
    );
    return result.one().id;
  }
}

export default {
  async fetch(request: Request, env: Env): Promise\x3CResponse> {
    const stub = env.MY_DO.getByName("my-instance");
    const id = await stub.addItem("hello");
    return Response.json({ id });
  },
};

Critical Rules

  1. Model around coordination atoms - One DO per chat room/game/user, not one global DO
  2. Use getByName() for deterministic routing - Same input = same DO instance
  3. Use SQLite storage - Configure new_sqlite_classes in migrations
  4. Initialize in constructor - Use blockConcurrencyWhile() for schema setup only
  5. Use RPC methods - Not fetch() handler (compatibility date >= 2024-04-03)
  6. Persist first, cache second - Always write to storage before updating in-memory state
  7. One alarm per DO - setAlarm() replaces any existing alarm

Anti-Patterns (NEVER)

  • Single global DO handling all requests (bottleneck)
  • Using blockConcurrencyWhile() on every request (kills throughput)
  • Storing critical state only in memory (lost on eviction/crash)
  • Using await between related storage writes (breaks atomicity)
  • Holding blockConcurrencyWhile() across fetch() or external I/O

Stub Creation

// 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);

Storage Operations

// SQL (synchronous, recommended)
this.ctx.storage.sql.exec("INSERT INTO t (c) VALUES (?)", value);
const rows = this.ctx.storage.sql.exec\x3CRow>("SELECT * FROM t").toArray();

// KV (async)
await this.ctx.storage.put("key", value);
const val = await this.ctx.storage.get\x3CType>("key");

Alarms

// Schedule (replaces existing)
await this.ctx.storage.setAlarm(Date.now() + 60_000);

// Handler
async alarm(): Promise\x3Cvoid> {
  // Process scheduled work
  // Optionally reschedule: await this.ctx.storage.setAlarm(...)
}

// Cancel
await this.ctx.storage.deleteAlarm();

Testing Quick Start

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);
  });
});
安全使用建议
Before using the production logging examples, avoid forwarding secrets, auth headers, tokens, raw request bodies, or unnecessary user identifiers. Treat Wrangler deploy and secret commands as real Cloudflare account operations and review configuration changes before applying them.
能力标签
cryptorequires-sensitive-credentials
能力评估
Purpose & Capability
The skill teaches how to create, configure, test, and review Cloudflare Durable Objects, Workers handlers, storage, alarms, WebSockets, and Wrangler configuration; these capabilities match the declared purpose.
Instruction Scope
The instructions are broad technical guidance and encourage consulting Cloudflare documentation, but they do not contain role overrides, hidden behavior, unrelated data access, or prompt-injection style instructions.
Install Mechanism
The artifact contains only Markdown files and no executable scripts, install hooks, binaries, or package code.
Credentials
Examples include Wrangler deploy, secrets setup, production logging, and Tail Workers, which are expected for Cloudflare Workers development but may affect real infrastructure if the user applies them.
Persistence & Privilege
Persistent storage, alarms, and log forwarding are part of the Durable Objects/Workers domain and are disclosed in the guidance; the skill itself does not create persistence or request elevated local privileges.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install durable-objects
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /durable-objects 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release of the durable-objects skill. - Create and review Cloudflare Durable Objects for stateful apps, RPC, WebSockets, alarms, and SQLite storage. - Strong bias toward retrieving latest documentation from Cloudflare resources rather than relying on pre-trained knowledge. - Covers Workers integration, wrangler configuration, code review, and best practices for Durable Objects. - Quick references and patterns for configuration, storage, alarms, sharding, and stub usage. - Guidance and anti-patterns included for building robust, scalable stateful systems.
元数据
Slug durable-objects
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Durable Objects 是什么?

Create and review Cloudflare Durable Objects. Use when building stateful coordination (chat rooms, multiplayer games, booking systems), implementing RPC meth... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 22 次。

如何安装 Durable Objects?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install durable-objects」即可一键安装,无需额外配置。

Durable Objects 是免费的吗?

是的,Durable Objects 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Durable Objects 支持哪些平台?

Durable Objects 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Durable Objects?

由 Reza(@creativerezz)开发并维护,当前版本 v1.0.0。

💬 留言讨论