@cloudflare/dynamic-workflows

中文文档
0.1.1发布于 2026/05/01MITTypeScriptES Module零依赖构建来源已验证近 30 天下载 27.7万

Integrate Cloudflare Workflows with Dynamic Workers by routing workflow execution to tenant-specific dynamic workers

原始使用文档
文档目录10 节
  1. Install
  2. Use it
  3. API
  4. wrapWorkflowBinding(metadata, options?): Workflow
  5. createDynamicWorkflowEntrypoint<Env>(loadRunner): typeof Wo…
  6. DynamicWorkflowBinding
  7. dispatchWorkflow(context, event, step, loadRunner)
  8. MissingDispatcherMetadataError
  9. Things to know
  10. License

dynamic-workflows

Run a different Cloudflare Workflow implementation per tenant, from a single dispatcher worker.

A Workflow is normally bound to one static class_name at deploy time. If you're building a platform on top of Dynamic Workers where each customer ships their own code, that's a problem: you only get one WorkflowEntrypoint, but you need it to route into N tenant workers.

This library is the glue. The dispatcher hands each tenant a wrapped Workflow binding that quietly tags every create() with a tenant id; the dispatcher's single WorkflowEntrypoint reads that tag back out at run time and forwards run(event, step) into the right tenant.

┌──────────── Dispatcher Worker ────────────┐          ┌──── Tenant's dynamic worker ────┐
│                                           │          │                                 │
│  env.WORKFLOWS (real Workflow binding)    │          │  env.WORKFLOWS (wrapped!)       │
│                                           │          │                                 │
│                                           │          │  ── env.WORKFLOWS.create({      │
│                                           │          │        params: { ... }          │
│                                           │          │      })                         │
│                                           │          │         │                       │
│  ┌──── wrapWorkflowBinding ──────────┐    │  tags    │         │                       │
│  │ injects { __dispatcherMetadata,   │◀───┼──────────┼─────────┘                       │
│  │   params } into create(...)       │    │          │                                 │
│  └────────────────┬──────────────────┘    │          └─────────────────────────────────┘
│                   │                       │
│                   ▼                       │
│            Workflows engine               │
│                   │                       │
│                   │ run(event, step)      │
│                   ▼                       │
│  ┌── createDynamicWorkflowEntrypoint ──┐  │          ┌──── Tenant's dynamic worker ────┐
│  │ pulls metadata off event.payload    │  │          │                                 │
│  │ loadRunner({metadata, env, ctx})    │──┼─────────▶│  class TenantWorkflow           │
│  │ forwards run(innerEvent, step)      │  │          │    extends WorkflowEntrypoint { │
│  └─────────────────────────────────────┘  │          │      run(event, step) { … }     │
└───────────────────────────────────────────┘          │    }                            │
                                                       └─────────────────────────────────┘

You stay in charge of how tenant code is loaded — Worker Loader, service bindings, whatever — this library only carries the tenant id between the two halves of the dance.

Install

npm install dynamic-workflows

Use it

The dispatcher needs three things: re-export DynamicWorkflowBinding, hand each tenant a wrapped binding, and register a WorkflowEntrypoint that knows how to load tenant code.

// dispatcher/src/index.ts
import {
  createDynamicWorkflowEntrypoint,
  DynamicWorkflowBinding,
  wrapWorkflowBinding,
  type WorkflowRunner,
} from 'dynamic-workflows';

// Required: re-exporting puts the class on `cloudflare:workers` exports,
// which is how `wrapWorkflowBinding` builds per-tenant RPC stubs.
export { DynamicWorkflowBinding };

interface Env {
  WORKFLOWS: Workflow;
  LOADER: WorkerLoader;
}

function loadTenant(env: Env, tenantId: string) {
  return env.LOADER.get(tenantId, async () => ({
    compatibilityDate: '2026-01-01',
    mainModule: 'index.js',
    modules: { 'index.js': await fetchTenantCode(tenantId) },
    env: {
      // The tenant uses this exactly like a real Workflow binding;
      // every create() is tagged with { tenantId } automatically.
      WORKFLOWS: wrapWorkflowBinding({ tenantId }),
    },
    globalOutbound: null,
  }));
}

// Register this as `class_name` in wrangler.jsonc.
export const DynamicWorkflow = createDynamicWorkflowEntrypoint<Env>(
  async ({ env, metadata }) => {
    const stub = loadTenant(env, metadata.tenantId as string);
    return stub.getEntrypoint('TenantWorkflow') as unknown as WorkflowRunner;
  }
);

export default {
  fetch(request: Request, env: Env) {
    const tenantId = request.headers.get('x-tenant-id')!;
    return loadTenant(env, tenantId).getEntrypoint().fetch(request);
  },
};
// dispatcher/wrangler.jsonc
{
  "name": "my-dispatcher",
  "main": "src/index.ts",
  "compatibility_date": "2026-01-01",
  "worker_loaders": [{ "binding": "LOADER" }],
  "workflows": [
    {
      "name": "dynamic-workflow",
      "binding": "WORKFLOWS",
      "class_name": "DynamicWorkflow"
    }
  ]
}

The tenant's code is plain Workflows — they don't know they're being dispatched:

// tenant code, loaded at runtime by the dispatcher
import { WorkflowEntrypoint } from 'cloudflare:workers';

export class TenantWorkflow extends WorkflowEntrypoint {
  async run(event, step) {
    return step.do('greet', async () => `Hello, ${event.payload.name}!`);
  }
}

export default {
  async fetch(request, env) {
    const instance = await env.WORKFLOWS.create({ params: await request.json() });
    // `instance` is an RPC stub — `.id` is an RpcPromise, so await it.
    return Response.json({ id: await instance.id });
  },
};

That's it. Workflow IDs, status, retries, hibernation — everything else works the way it normally does.

API

wrapWorkflowBinding(metadata, options?): Workflow

Returns a Workflow-shaped RPC stub. Every create() / createBatch() call through it tags the instance's params with metadata. Pass it to a Dynamic Worker as a binding.

metadata is any JSON-serialisable object — typically { tenantId }, but routing hints, region, plan tier etc. all work. options.bindingName defaults to 'WORKFLOWS'; override it if your dispatcher's binding has a different name.

Throws if you forgot to re-export DynamicWorkflowBinding.

createDynamicWorkflowEntrypoint<Env>(loadRunner): typeof WorkflowEntrypoint

Returns a WorkflowEntrypoint subclass. Register it as the class_name of your [[workflows]] binding.

loadRunner({ metadata, env, ctx }) runs once per run() call and must return something with a run(event, step) method. In practice you return stub.getEntrypoint('YourWorkflowClass') from a Worker Loader stub.

DynamicWorkflowBinding

The WorkerEntrypoint class behind wrapWorkflowBinding's stubs. Re-export it from your dispatcher's main module — Cloudflare populates cloudflare:workers exports from your top-level exports, and wrapWorkflowBinding looks the class up there.

dispatchWorkflow(context, event, step, loadRunner)

The lower-level primitive that createDynamicWorkflowEntrypoint is built on. Use it directly if you need to subclass WorkflowEntrypoint yourself (e.g. to wrap run in custom logging).

MissingDispatcherMetadataError

Thrown from run() when the event payload isn't a dispatcher envelope — i.e. the workflow was created against the raw binding instead of a wrapped one.

Things to know

  • Bindings cross RPC, so they have to be RPC stubs. That's why DynamicWorkflowBinding is a WorkerEntrypoint: a plain { create, get } object isn't structured-clonable, and the real Workflow binding can't be serialised either.
  • Workflows persists event.payload. That payload is the dispatcher envelope, metadata included. Don't put secrets in metadata, and treat it as routing hints, not authorization — tenant code can read it back via instance.status().
  • WorkflowInstance is an RPC stub on the tenant side. Property reads return RpcPromises, so await instance.id. Method calls (status(), pause(), …) work normally.
  • The envelope shape is internal. wrapWorkflowBinding and createDynamicWorkflowEntrypoint are guaranteed to be compatible with each other; don't parse the persisted payload yourself.

License

MIT

版本与发布记录

@cloudflare/dynamic-workflows 共发布 2 个版本,首次发布于 2026/05/01;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.1latest2026/05/016 个月前
0.1.02026/05/016 个月前

关于 @cloudflare/dynamic-workflows 的常见问题

@cloudflare/dynamic-workflows 是什么?

Integrate Cloudflare Workflows with Dynamic Workers by routing workflow execution to tenant-specific dynamic workers

如何安装 @cloudflare/dynamic-workflows?

在项目目录运行 npm install @cloudflare/dynamic-workflows,或使用 pnpm add / yarn add / bun add。

@cloudflare/dynamic-workflows 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@cloudflare/dynamic-workflows 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@cloudflare/dynamic-workflows 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=22。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@cloudflare/dynamic-workflows 可以商用吗?

@cloudflare/dynamic-workflows 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@cloudflare/dynamic-workflows 的下载量有多少?

根据 npm 官方下载统计,@cloudflare/dynamic-workflows 在 2026/10/10 – 2026/11/08 这 30 天内被下载 276,578 次,日均约 9,219 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@cloudflare/dynamic-workflows 还在维护吗?

最新版本 0.1.1 发布于 2026/05/01(6 个月前);至今共发布 2 个版本,其中过去 12 个月发布了 2 个;首次发布于 2026/05/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。