CDKTN app that uses a Durable Object to publish messages to a queue.
- wrangler-cloudflare-durable-objects-queue - Built with Wrangler instead of CDKTN.
- Cloudflare:
- Must have set the
CLOUDFLARE_API_TOKENvariable in your local environment, with theWorkers Scripts:Edit,Queues:EditandAccount Settings:Readpermissions.
- Must have set the
- mise:
- Install mise, which manages Node, pnpm, and OpenTofu.
mise install
pnpm install
pnpm genpnpm gen generates the Cloudflare provider constructs into .gen/. Re-run it whenever the provider constraint in cdktf.json changes.
pnpm run deploy-
Grab the
workers.devURL ofmy-workerfrom the Cloudflare dashboard. -
Navigate to
https://my-worker.<SUBDOMAIN>.workers.dev?userId=test. -
Check that a message is present in
my-queuefrom the Cloudflare dashboard.
pnpm destroyA request carrying a userId is routed to the Durable Object instance derived from that id, and the Durable Object publishes its own id to my-queue.
Wrangler owns the Worker bundle, CDKTN owns the deployment:
pnpm bundlerunswrangler deploy --dry-run --outdir dist, which bundlessrc/worker/index.ts.src/stacks/my-stack.tspicks updist/index.jsas aTerraformAssetand uploads it throughcloudflare_workers_script(content_file+content_sha256), with the Durable Object binding, the queue producer binding, and the class migration declared in Terraform.
pnpm synth, pnpm diff, pnpm run deploy, and pnpm test all run the bundle step first, so the synthesized stack always matches the current source. The stack reads dist/index.js while it is being constructed, so nothing that instantiates it works without a bundle.
Keep the compatibility date, compatibility flags, bindings, and migrations in wrangler.jsonc in sync with src/stacks/my-stack.ts. Wrangler needs them to bundle and to run locally, OpenTofu needs them to deploy.
The MyDurableObject namespace is not a resource of its own: it is created by the migrations block on cloudflare_workers_script, which is why the migration and the binding have to agree on the class name. The class uses the SQLite storage backend (new_sqlite_classes), the default for new Durable Object classes; the key-value backend used by new_classes is legacy and not available to new classes on all plans.
Renaming or deleting the class later needs a new migration tag plus renamed_classes or deleted_classes. Changing new_sqlite_classes in place will not do it.