Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

cloudflare-durable-objects

БесплатноБез исполняемых скриптовНе проверен

Guide to Cloudflare Durable Objects: globally unique, stateful objects for coordination, real- time communication and persistent state. Covers the…

jackspaceот jackspace★ 16 звёзд на GitHub15 установок в других каталогах

Об этом скилле

Cloudflare Durable Objects

Status: Production Ready ✅ Last Updated: 2025-10-22 Dependencies: cloudflare-worker-base (recommended) Latest Versions: [email protected]+, @cloudflare/[email protected]+ Official Docs: https://developers.cloudflare.com/durable-objects/


What are Durable Objects?

Cloudflare Durable Objects are globally unique, stateful objects that provide:

  • Single-point coordination - Each Durable Object instance is globally unique across Cloudflare's network
  • Strong consistency - Transactional, serializable storage (ACID guarantees)
  • Real-time communication - WebSocket Hibernation API for thousands of connections per instance
  • Persistent state - Built-in SQLite database (up to 1GB) or key-value storage
  • Scheduled tasks - Alarms API for future task execution
  • Global distribution - Automatically routed to optimal location
  • Automatic scaling - Millions of independent instances

Use Cases:

  • Chat rooms and real-time collaboration
  • Multiplayer game servers
  • Rate limiting and session management
  • Leader election and coordination
  • WebSocket servers with hibernation
  • Stateful workflows and queues
  • Per-user or per-room logic

Quick Start (10 Minutes)

Option 1: Scaffold New DO Project

npm create cloudflare@latest my-durable-app -- \
  --template=cloudflare/durable-objects-template \
  --ts \
  --git \
  --deploy false

cd my-durable-app
npm install
npm run dev

What this creates:

  • Complete Durable Objects project structure
  • TypeScript configuration
  • wrangler.jsonc with bindings and migrations
  • Example DO class implementation
  • Worker to call the DO

Option 2: Add to Existing Worker

cd my-existing-worker
npm install -D @cloudflare/workers-types

Create a Durable Object class (src/counter.ts):

import { DurableObject } from 'cloudflare:workers';

export class Counter extends DurableObject {
  async increment(): Promise<number> {
    // Get current value from storage (default to 0)
    let value: number = (await this.ctx.storage.get('value')) || 0;

    // Increment
    value += 1;

    // Save back to storage
    await this.ctx.storage.put('value', value);

    return value;
  }

  async get(): Promise<number> {
    return (await this.ctx.storage.get('value')) || 0;
  }
}

// CRITICAL: Export the class
export default Counter;

Configure wrangler.jsonc:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "my-worker",
  "main": "src/index.ts",
  "compatibility_date": "2025-10-22",

  // Durable Objects binding
  "durable_objects": {
    "bindings": [
      {
        "name": "COUNTER",           // How you access it: env.COUNTER
        "class_name": "Counter"      // MUST match exported class name
      }
    ]
  },

  // REQUIRED: Migration for new DO class
  "migrations": [
    {
      "tag": "v1",                   // Unique migration identifier
      "new_sqlite_classes": [        // Use SQLite backend (recommended)
        "Counter"
      ]
    }
  ]
}

Call from Worker (src/index.ts):

import { Counter } from './counter';

interface Env {
  COUNTER: DurableObjectNamespace<Counter>;
}

export { Counter };

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    // Get Durable Object stub by name
    const id = env.COUNTER.idFromName('global-counter');
    const stub = env.COUNTER.get(id);

    // Call RPC method on the DO
    const count = await stub.increment();

    return new Response(`Count: ${count}`);
  },
};

Deploy:

npx wrangler deploy

Durable Object Class Structure

Base Class Pattern

All Durable Objects MUST extend DurableObject from cloudflare:workers:

import { DurableObject } from 'cloudflare:workers';

export class MyDurableObject extends DurableObject {
  constructor(ctx: DurableObjectState, env: Env) {
    super(ctx, env);

    // Optional: Initialize from storage
    ctx.blockConcurrencyWhile(async () => {
      // Load state before handling requests
      this.someValue = await ctx.storage.get('someKey') || defaultValue;
    });
  }

  // RPC methods (recommended)
  async myMethod(): Promise<string> {
    return 'Hello from DO!';
  }

  // Optional: HTTP fetch handler
  async fetch(request: Request): Promise<Response> {
    return new Response('Hello from DO fetch!');
  }
}

// CRITICAL: Export the class
export default MyDurableObject;

Constructor Pattern

constructor(ctx: DurableObjectState, env: Env) {
  super(ctx, env);  // REQUIRED

  // Access to environment bindings
  this.env = env;

  // this.ctx provides:
  // - this.ctx.storage      (storage API)
  // - this.ctx.id           (unique ID)
  // - this.ctx.waitUntil()  (background tasks)
  // - this.ctx.acceptWebSocket() (WebSocket hibernation)
}

CRITICAL Rules:

  • ✅ Always call super(ctx, env) fi
Полный SKILL.md на GitHub

Установить cloudflare-durable-objects в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

README.mdSKILL.json

FAQ

Что делает скилл cloudflare-durable-objects?

Guide to Cloudflare Durable Objects: globally unique, stateful objects for coordination, real- time communication and persistent state. Covers the DurableObject class and bindings, WebSocket Hibernation (ctx.acceptWebSocket, webSocketMessage, serializeAttachment), SQLite storage via ctx.storage.sql, alarms with storage.setAlarm and the alarm() handler, ids from idFromName, newUniqueId and getByName, RPC methods, blockConcurrencyWhile, migrations and location hints. Documents 15+ pitfalls: class not exported, missing or wrong migrations, new_sqlite_classes, constructor work and setTimeout or fetch breaking hibernation, in-memory state lost on hibernation, partial deleteAll on the KV backend, binding mismatches, state size limits and alarm retry failures. Use when building chat rooms, multiplayer games, rate limiters, session stores, queues or per-user state on Workers, or debugging DO migration, hibernation and alarm errors.

Как установить скилл cloudflare-durable-objects?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл cloudflare-durable-objects запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить cloudflare-durable-objects с