Skip to content

Cloudflare D1 and KV

@arona/store-cloudflare provides two MessageSessionStore implementations for Workers:

  • D1.layer(env.DB, { migrate: false }) — the authoritative store. D1’s single primary and SQL CAS keep concurrent interactions correct.
  • KV.layer(env.KV) — eventually consistent and not atomic. It checks the version before writing, so it is fine for one writer or a low-concurrency bot, but two isolates can race. Use it as a cache or for small deployments, not as the only store behind concurrent traffic.

Both accept the native bindings, so they work with Wrangler (env.DB) and with Alchemy’s async Workers. They do not depend on Node or Alchemy.

The D1 schema lives in packages/store-cloudflare/migrations/0001_message_sessions.sql. Apply it with Wrangler’s migration flow, or let Alchemy apply it on deploy.

If you prefer runtime setup, D1.open(env.DB) yields a scoped Effect SQL client and D1.migrate(client) applies the same statements. Prefer deploy-time migrations in production.

Alchemy v2 is Effect-based and currently in beta. @arona/platform-discord-alchemy exposes Worker, which binds D1/KV from the stack config and constructs a DiscordWorkerClient at Worker start:

src/resources.ts
import * as Cloudflare from "@alchemy.run/cloudflare";
import { migrationsDir } from "@arona/store-cloudflare/migrations";
export const Database = Cloudflare.D1.Database("Sessions", {
migrations: migrationsDir,
});
export const Cache = Cloudflare.KV.Namespace("SessionCache");
src/worker.ts
import { Worker } from "@arona/platform-discord-alchemy";
import { Config, Effect } from "effect";
import { counter } from "./counter";
import { Cache, Database } from "./resources";
const config = Effect.runSync(
Config.all({
token: Config.Redacted("DISCORD_APP_TOKEN"),
publicKey: Config.NonEmptyString("DISCORD_PUBLIC_KEY"),
build: Config.String("BUILD_ID").pipe(Config.withDefault("dev")),
}),
);
export default Worker("Api", {
main: import.meta.url,
database: Database,
cache: Cache,
commands: [counter],
env: {
DISCORD_APP_TOKEN: config.token,
DISCORD_PUBLIC_KEY: config.publicKey,
BUILD_ID: config.build,
},
compatibility: { flags: ["nodejs_compat"], date: "2026-08-31" },
});
alchemy.run.ts
import * as Alchemy from "alchemy";
import * as Cloudflare from "@alchemy.run/cloudflare";
import * as Effect from "effect/Effect";
import Api from "./src/worker.ts";
export default Alchemy.Stack(
"AronaDiscord",
{ providers: Cloudflare.providers(), state: Cloudflare.state() },
Effect.gen(function* () {
const api = yield* Api;
return { url: api.url };
}),
);

The helper reads DB, KV, and the Discord env at Worker start. If you need a custom store or a preconfigured client, pass a clientLayer that reads CloudflareBindings instead of commands.

@arona/platform-discord/worker is the Worker-safe renderer and runtime:

  • DiscordWorkerClient — the shared command/component/session core with an HTTP interaction transport.
  • SlashCommand — the same contract/implementation API as the gateway entry, producing dfx-compatible registration JSON.
  • mountJsonMessage / mountJsonSessionMessage — render through jsonWire.
  • jsonWire — plain Components V2 JSON, no Node-only rendering.

The Node/gateway entry (@arona/platform-discord) uses the same JSON wire plus Resvg for local file and Canvas uploads. Choose the entry per runtime; do not import the Node barrel from a Worker.

Register commands from typed JSON with registerWorkerCommands (dfx’s bulk-set endpoint):

yield *
registerWorkerCommands({
applicationId,
guildId: Option.none(), // or Option.some(guildId)
commands: [counter.json],
}).pipe(Effect.provide(DiscordRest.layerFetch({ token })));

Worker limitations:

  • Canvas needs a pre-rendered url in the Worker profile; SVG rendering requires Resvg and stays on the Node profile.
  • File needs a url in the Worker profile. Uploaded buffers and buffer-backed Media/Thumbnail are still unsupported because the HTTP path has no multipart upload yet.
  • User/role/channel select default values use plain { id, type } JSON, which matches Discord’s API.
src/fetch.ts
import {
createInteractionsHandler,
DiscordRest,
DiscordWorkerClient,
SlashCommand,
} from "@arona/platform-discord/worker";
import { D1 } from "@arona/store-cloudflare";
import { Effect, Layer, ManagedRuntime, Option } from "effect";
import type { ApiEnv } from "../alchemy.run.ts";
import { Counter } from "./counter";
export default {
async fetch(request: Request, env: ApiEnv, ctx: ExecutionContext) {
const clientLayer = DiscordWorkerClient.layer({
build: Option.fromNullishOr(env.BUILD_ID),
commands: [
SlashCommand.make("counter", {
description: "A resumable counter",
component: Counter,
}),
],
}).pipe(Layer.provide(D1.layer(env.DB, { migrate: false })));
const runtime = ManagedRuntime.make(
Layer.merge(DiscordRest.layerFetch({ token: env.DISCORD_APP_TOKEN }), clientLayer),
);
try {
return await runtime.runPromise(
Effect.gen(function* () {
const client = yield* DiscordWorkerClient;
return yield* createInteractionsHandler({
client,
publicKey: env.DISCORD_PUBLIC_KEY,
// Inline mode supports modals; a slow first frame auto-defers
// after firstFrameTimeout (2s default) and finishes through REST.
// For slower work: defer: true, background: (work) => ctx.waitUntil(work).
// autocomplete: (interaction) => Effect.succeed([{ name: "...", value: "..." }]),
})(request);
}),
);
} finally {
await runtime.dispose();
}
},
};

dfx is an Effect-native Discord SDK generated from Discord’s OpenAPI model. Arona uses it for both transports:

  • the generated REST client handles auth, rate-limit buckets, retries and Discord’s error envelope, and includes Components V2 request types;
  • withFiles adds the multipart upload path;
  • DiscordGateway owns sharding, identify/resume, heartbeat and reconnect, with a raw dispatch stream;
  • the Worker profile uses the REST client over FetchHttpClient and keeps Arona’s Fetch interactions handler and Ed25519 verification.

Arona’s remaining interaction classes (RestInteraction, RestOptions, RestModalFields) translate raw payloads into the method-shaped surface the renderer uses. They are transport adapters, not a second REST client.

A runnable Worker example lives in examples/alchemy.

D1 updates use UPDATE ... WHERE id = ? AND version = ? and inspect the changed-row count, so a losing interaction gets SessionConflict rather than overwriting state.

Every interaction also takes an exclusive session lease before dispatch and releases it after the state write. The lease is renewed while the handler runs, so a slow render does not outlive its TTL. MessageSessionStore.acquire uses a TTL (leaseTtlMs, 10 seconds by default), so a crashed writer does not block the message forever. Memory and file stores use their own locks; D1 stores the lease in lease_owner / lease_until columns. Apply 0002_session_leases.sql to an existing database.

When a press arrives while another isolate holds the lease, it waits for up to interactionWindowMs (1 second by default) instead of failing immediately, so a short commit does not lose the click. Only a press that stays blocked past that window is dropped, with a warning. The wait stays well inside Discord’s three-second callback budget; the handler still auto-defers at firstFrameTimeout if the rest of the work is slow.

KV has no compare-and-set and no atomic lease; treat KV.layer as best-effort.