Token导航 LogoToken导航TokenDH.com
前端设计需要联网github未标认证来源可访问许可证需确认审计通过

cloudflare-durable-objectscloudflare 耐用对象

Agent Skill

cloudflare-durable-objects 用于处理 GitHub 仓库、Issue、Pull Request 和代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中需要围绕仓库状态、代码变更或协作事项进行整理时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

494

周安装

20

GitHub Stars

14

下载量

155
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:cloudflare-durable-objects(cloudflare 耐用对象)
来源仓库:https://github.com/itechmeat/llm-code
仓库路径:skills/cloudflare-durable-objects
安装命令:
npx skills add https://github.com/itechmeat/llm-code --skill cloudflare-durable-objects
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/itechmeat/llm-code --skill cloudflare-durable-objects

简介

cloudflare-durable-objects 用于处理 GitHub 仓库、Issue、Pull Request 等代码协作信息,适合在 Codex、Claude、Cursor、Gemini CLI 中进行项目状态跟踪。

  • 适用于 Cloudflare Durable Objects 相关的开发和维护工作。
  • 通过 GitHub API 调用、代码审查和协作流程管理来处理开发任务。
  • 安装命令:npx skills add https://github.com/itechmeat/llm-code --skill cloudflare-durable-objects
  • 建议确认 GitHub 访问权限和仓库读写权限,注意 API 调用限制

SKILL.md

Cloudflare Durable Objects

Durable Objects combine compute with strongly consistent, transactional storage. Each object has a globally-unique name, enabling coordination across clients worldwide.


Quick Start

Durable Object Class

// src/counter.ts
import { DurableObject } from "cloudflare:workers";

export class Counter extends DurableObject<Env> {
  async increment(): Promise<number> {
    let count = (await this.ctx.storage.get<number>("count")) ?? 0;
    count++;
    await this.ctx.storage.put("count", count);
    return count;
  }

  async getCount(): Promise<number> {
    return (await this.ctx.storage.get<number>("count")) ?? 0;
  }
}

Worker Entry Point

// src/index.ts
export { Counter } from "./counter";

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const id = env.COUNTER.idFromName("global");
    const stub = env.COUNTER.get(id);
    const count = await stub.increment();
    return new Response(`Count: ${count}`);
  },
};

wrangler.jsonc

{
  "name": "counter-worker",
  "main": "src/index.ts",
  "durable_objects": {
    "bindings": [
      {
        "name": "COUNTER",
        "class_name": "Counter"
      }
    ]
  },
  "migrations": [
    {
      "tag": "v1",
      "new_sqlite_classes": ["Counter"]
    }
  ]
}

Deploy

npx wrangler deploy

Core Concepts

DurableObjectState

Available as this.ctx in Durable Object class:

interface DurableObjectState {
  readonly id: DurableObjectId;
  readonly storage: DurableObjectStorage;

  blockConcurrencyWhile<T>(callback: () => Promise<T>): Promise<T>;
  waitUntil(promise: Promise<any>): void; // No effect in DO

  // WebSocket Hibernation
  acceptWebSocket(ws: WebSocket, tags?: string[]): void;
  getWebSockets(tag?: string): WebSocket[];
  getTags(ws: WebSocket): string[];
  setWebSocketAutoResponse(pair?: WebSocketRequestResponsePair): void;
  getWebSocketAutoResponse(): WebSocketRequestResponsePair | null;

  abort(message?: string): void; // Force reset DO
}

DurableObjectId

const id = env.MY_DO.idFromName("user-123"); // Deterministic ID
const id = env.MY_DO.newUniqueId(); // Random unique ID
const stub = env.MY_DO.get(id); // Get stub for DO instance

See api.md for full type definitions.


Storage API (SQLite-backed)

SQLite is the recommended storage backend for new Durable Objects.

SQL API

const cursor = this.ctx.storage.sql.exec("SELECT * FROM users WHERE id = ?", userId);

// Get single row (throws if not exactly one)
const user = cursor.one();

// Get all rows
const users = cursor.toArray();

// Iterate
for (const row of cursor) {
  console.log(row);
}

SQL Cursor Properties

cursor.columnNames; // string[]
cursor.rowsRead; // number
cursor.rowsWritten; // number

Create Tables

this.ctx.storage.sql.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id TEXT PRIMARY KEY,
    name TEXT NOT NULL,
    created_at INTEGER DEFAULT (unixepoch())
  )
`);

Insert/Update

this.ctx.storage.sql.exec("INSERT INTO users (id, name) VALUES (?, ?)", id, name);

this.ctx.storage.sql.exec("UPDATE users SET name = ? WHERE id = ?", newName, id);

Transactions

// Synchronous transaction (SQLite only)
this.ctx.storage.transactionSync(() => {
  this.ctx.storage.sql.exec("INSERT INTO logs (msg) VALUES (?)", "start");
  this.ctx.storage.sql.exec("UPDATE counters SET value = value + 1");
});

Database Size

const sizeBytes = this.ctx.storage.sql.databaseSize;

See storage.md for KV API and advanced usage.


Storage API (KV)

Synchronous KV (SQLite-backed)

this.ctx.storage.kv.put("key", value);
const val = this.ctx.storage.kv.get("key");
const deleted = this.ctx.storage.kv.delete("key");

for (const [key, value] of this.ctx.storage.kv.list()) {
  console.log(key, value);
}

Async KV (Both backends)

await this.ctx.storage.put("key", value);
const val = await this.ctx.storage.get<MyType>("key");

// Batch operations (up to 128 keys)
const values = await this.ctx.storage.get(["key1", "key2", "key3"]);
await this.ctx.storage.put({ key1: val1, key2: val2 });
await this.ctx.storage.delete(["key1", "key2"]);

// List with options
const map = await this.ctx.storage.list({ prefix: "user:" });

// Delete all
await this.ctx.storage.deleteAll();

Write Coalescing

Multiple writes without await are coalesced atomically:

// These are batched into single transaction
this.ctx.storage.put("a", 1);
this.ctx.storage.put("b", 2);
this.ctx.storage.put("c", 3);
// All committed together

Alarms

Schedule single alarm per Durable Object for background processing.

Set Alarm

// Schedule 1 hour from now
await this.ctx.storage.setAlarm(Date.now() + 60 * 60 * 1000);

// Schedule at specific time
await this.ctx.storage.setAlarm(new Date("2024-12-31T00:00:00Z"));

Handle Alarm

export class MyDO extends DurableObject<Env> {
  async alarm(info?: AlarmInfo): Promise<void> {
    console.log(`Alarm fired! Retry: ${info?.isRetry}, count: ${info?.retryCount}`);

    // Process scheduled work
    await this.processScheduledTasks();

    // Schedule next alarm if needed
    const nextRun = await this.getNextScheduledTime();
    if (nextRun) {
      await this.ctx.storage.setAlarm(nextRun);
    }
  }
}

Alarm Methods

await this.ctx.storage.setAlarm(timestamp); // Set/overwrite alarm
const time = await this.ctx.storage.getAlarm(); // Get scheduled time (ms) or null
await this.ctx.storage.deleteAlarm(); // Cancel alarm

Retry behavior: Alarms retry with exponential backoff (2s initial, up to 6 retries) on exceptions.

See alarms.md for patterns.


WebSocket Hibernation

Keep WebSocket connections alive while Durable Object hibernates.

Accept WebSocket

export class ChatRoom extends DurableObject<Env> {
  async fetch(request: Request): Promise<Response> {
    const upgradeHeader = request.headers.get("Upgrade");
    if (upgradeHeader === "websocket") {
      const [client, server] = Object.values(new WebSocketPair());

      // Accept with hibernation support
      this.ctx.acceptWebSocket(server, ["user:123"]); // Optional tags

      return new Response(null, { status: 101, webSocket: client });
    }
    return new Response("Expected WebSocket", { status: 400 });
  }

  async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer): Promise<void> {
    // Handle incoming message (DO wakes from hibernation)
    this.broadcast(message);
  }

  async webSocketClose(ws: WebSocket, code: number, reason: string): Promise<void> {
    // Handle disconnect
  }
}

Broadcast to All

broadcast(message: string) {
  for (const ws of this.ctx.getWebSockets()) {
    ws.send(message);
  }
}

Per-Connection State

// Save state that survives hibernation (max 2048 bytes)
ws.serializeAttachment({ userId: "123", role: "admin" });

// Restore in message handler
const state = ws.deserializeAttachment();

Auto-Response (No Wake)

// Respond to pings without waking DO
this.ctx.setWebSocketAutoResponse(new WebSocketRequestResponsePair("ping", "pong"));

See websockets.md for details.


RPC Methods

Call Durable Object methods directly (compatibility date >= 2024-04-03):

const stub = env.USER_SERVICE.get(id);
const user = await stub.getUser("123"); // Direct RPC call
await stub.updateUser("123", { name: "New Name" });

Note: Each RPC method call = one RPC session for billing.


Initialization

Use blockConcurrencyWhile in constructor for migrations:

constructor(ctx: DurableObjectState, env: Env) {
  super(ctx, env);
  ctx.blockConcurrencyWhile(async () => {
    this.ctx.storage.sql.exec(`CREATE TABLE IF NOT EXISTS data (key TEXT PRIMARY KEY, value TEXT)`);
  });
}

Timeout: 30 seconds.


Hibernation

Conditions for Hibernation

All must be true:

  • No pending setTimeout/setInterval
  • No in-progress await fetch()
  • Using Hibernation WebSocket API (not standard WebSocket)
  • No active request processing

Lifecycle

  1. Active: Processing requests
  2. Idle hibernateable: ~10 seconds → may hibernate
  3. Hibernated: Removed from memory, WebSockets stay connected
  4. Wake: On message/event, constructor runs, handler invoked

Important: In-memory state is lost on hibernation. Restore from storage or attachments.


Bindings & Migrations

{
  "durable_objects": {
    "bindings": [{ "name": "MY_DO", "class_name": "MyDO" }]
  },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["MyDO"] }]
}

Note: Cannot enable SQLite on existing deployed classes.


Wrangler Commands

npx wrangler deploy   # Deploy with migrations
wrangler tail         # Tail logs

Limits

FeatureFreePaid
DO classes100500
Storage per DO10 GB10 GB
Storage per account5 GBUnlimited
CPU per request30 sec30 sec (max 5 min)
WebSocket connections32,76832,768
SQL row/value size2 MB2 MB
KV value size128 KiB128 KiB
Batch size128 keys128 keys

Pricing

MetricFreePaid
Requests100K/day1M/mo included, +$0.15/M
Duration13K GB-s/day400K GB-s/mo, +$12.50/M GB-s
SQLite rows read5M/day25B/mo included, +$0.001/M
SQLite rows written100K/day50M/mo included, +$1.00/M
Storage5 GB5 GB/mo included, +$0.20/GB-mo

WebSocket: 20:1 billing ratio (1M messages = 50K requests).

See pricing.md for details.


Prohibitions

  • ❌ Do not store state outside storage (lost on hibernation)
  • ❌ Do not use standard WebSocket API for hibernation
  • ❌ Do not exceed 2 MB per row/value in SQLite
  • ❌ Do not call sql.exec() with transaction control statements
  • ❌ Do not expect waitUntil to work (no effect in DO)

References

Links

Related Skills

  • cloudflare-workers — Worker development
  • cloudflare-d1 — D1 database
  • cloudflare-kv — Global KV
  • cloudflare-workflows — Durable execution

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

34.36%
按下载量换算53

Claude

31.91%
按下载量换算49

Cursor

18%
按下载量换算28

Gemini CLI

9.08%
按下载量换算14

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills