fix(platform-cloudflare): apply review findings

- Exclude the package from deno check (workers-types globals are not
  visible to Deno) and ship @cloudflare/workers-types as a runtime
  dependency since the public types reference it.
- Match core Sharding registerEntity semantics: duplicates are a no-op
  and registrations are removed when the registering scope closes.
- Handle alarm() on ClusterEntity so an armed alarm cannot fire into a
  missing handler, and only block object construction on alarm work
  when a pending deliver_at row exists.
- Replace async/await storage glue with Effect-based helpers typed
  against the official workers-types signatures.
- Reject empty entity types in decodeName, single-source the
  ClusterName type, simplify the stub client to a plain record, align
  reply-table uniqueness with the cluster reply protocol, and fix JSDoc
  categories.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Tim Smart
2026-10-28 08:28:37 +00:00
co-authored by Claude Fable 5
parent 09811255df
commit 4400a89aa4
10 changed files with 116 additions and 97 deletions
+1
View File
@@ -27,6 +27,7 @@
"packages/opentelemetry/",
"packages/platform/browser/",
"packages/platform/bun/",
"packages/platform/cloudflare/",
"packages/platform/node/",
"packages/platform/node-shared/",
"packages/tools/",
+3 -1
View File
@@ -65,8 +65,10 @@
"peerDependencies": {
"effect": "workspace:^"
},
"dependencies": {
"@cloudflare/workers-types": "^5.20260816.1"
},
"devDependencies": {
"@cloudflare/workers-types": "^5.20260816.1",
"effect": "workspace:^",
"esbuild": "^0.25.12",
"miniflare": "^4.20260730.0"
@@ -58,7 +58,7 @@ export const encodeName: (type: string, id: string) => string = Internal.encodeN
* including non-canonical length prefixes. A Durable Object uses this to
* recover its own address from `ctx.id.name`.
*
* @category encoding
* @category decoding
* @since 4.0.0
*/
export const decodeName: (name: string) => ClusterName | undefined = Internal.decodeName
@@ -94,7 +94,7 @@ export interface LayerOptions {
* address only gives logs, metrics, and `Entity.CurrentRunnerAddress` a stable
* identity, with the port fixed to `0`.
*
* @category models
* @category constructors
* @since 4.0.0
*/
export const makeRunnerAddress = (objectName: string): RunnerAddress.RunnerAddress => RunnerAddress.make(objectName, 0)
@@ -117,6 +117,8 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) {
entities.set(entity.type, entity)
}
const registrations = new Map<string, EntityRegistration>()
// Snowflakes are isolate-local here (random machine id, no coordination).
// Persisted request ids on this path use uuidv7, not these snowflakes.
const snowflakeGen = yield* Snowflake.makeGenerator
const unknownEntity = (entity: Entity.Entity<any, any>) =>
@@ -126,22 +128,14 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) {
)
)
const stubMethod = () => notImplemented("entity messaging")
const makeStubClient = (entity: Entity.Entity<any, any>, entityId: string) => {
options.entityNamespace.getByName(Internal.encodeName(entity.type, entityId))
const target: Record<string | symbol, unknown> = {}
return new Proxy(target, {
has: (_, tag) => entity.protocol.requests.has(tag as string),
get(target, tag) {
if (Object.hasOwn(target, tag)) {
return target[tag]
} else if (!entity.protocol.requests.has(tag as string)) {
return undefined
}
const method = () => notImplemented("entity messaging")
target[tag] = method
return method
}
})
const client: Record<string, unknown> = {}
for (const tag of entity.protocol.requests.keys()) {
client[tag] = stubMethod
}
return client
}
const makeClient = (entity: Entity.Entity<any, any>) =>
@@ -149,22 +143,24 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) {
? Effect.sync(() => (entityId: string) => makeStubClient(entity, entityId))
: unknownEntity(entity)
const registerEntity = (
const registerEntity = Effect.fnUntraced(function*(
entity: Entity.Entity<any, any>,
build: Effect.Effect<unknown, never, unknown>,
buildOptions?: Record<string, unknown>
) =>
Effect.contextWith((context: Context.Context<never>) => {
if (!entities.has(entity.type)) {
return unknownEntity(entity)
} else if (registrations.has(entity.type)) {
return Effect.die(
new Error(`CloudflareCluster: handlers for entity type "${entity.type}" are already registered`)
)
}
registrations.set(entity.type, { entity, build, options: buildOptions, context })
return Effect.void
})
) {
if (!entities.has(entity.type)) {
return yield* unknownEntity(entity)
} else if (registrations.has(entity.type)) {
return
}
const context = yield* Effect.context<never>()
registrations.set(entity.type, { entity, build, options: buildOptions, context })
yield* Effect.addFinalizer(() =>
Effect.sync(() => {
registrations.delete(entity.type)
})
)
})
return Sharding.of({
getRegistrationEvents: Stream.never,
@@ -10,7 +10,8 @@
* @since 4.0.0
*/
import { DurableObject } from "cloudflare:workers"
import { ensureEntityStorage, rearmAlarm } from "./internal/entityStorage.ts"
import * as Effect from "effect/Effect"
import { armAlarm, earliestDeliverAt, ensureEntityStorage } from "./internal/entityStorage.ts"
const notExposed = (className: string) => () => {
throw new Error(
@@ -34,10 +35,18 @@ const notExposed = (className: string) => () => {
export class ClusterEntity extends DurableObject<unknown> {
constructor(ctx: DurableObjectState, env: unknown) {
super(ctx, env)
ensureEntityStorage(ctx.storage.sql)
void ctx.blockConcurrencyWhile(() => rearmAlarm(ctx.storage, ctx.storage.sql))
const sql = ctx.storage.sql
ensureEntityStorage(sql)
const deliverAt = earliestDeliverAt(sql)
if (deliverAt !== undefined) {
void ctx.blockConcurrencyWhile(() => Effect.runPromise(armAlarm(ctx.storage, deliverAt)))
}
}
// Scheduled rows cannot exist until the mailbox lands; handling the alarm
// here keeps an armed alarm from firing into a missing handler.
override alarm(): void {}
override fetch: () => never = notExposed("ClusterEntity")
}
@@ -1,13 +1,9 @@
/** @internal */
export interface ClusterName {
readonly type: string
readonly id: string
}
import type { ClusterName } from "../CloudflareCluster.ts"
/** @internal */
export const encodeName = (type: string, id: string): string => `${type.length}:${type}${id}`
const lengthPrefix = /^(0|[1-9]\d*):/
const lengthPrefix = /^([1-9]\d*):/
/** @internal */
export const decodeName = (name: string): ClusterName | undefined => {
@@ -5,19 +5,11 @@
*
* @internal
*/
import type { DurableObjectStorage, SqlStorage } from "@cloudflare/workers-types"
import * as Effect from "effect/Effect"
/** @internal */
export interface EntitySql {
exec(query: string, ...bindings: Array<unknown>): {
toArray(): Array<Record<string, unknown>>
}
}
/** @internal */
export interface EntityAlarm {
getAlarm(): Promise<number | null>
setAlarm(scheduledTime: number): Promise<unknown>
}
export type EntityAlarm = Pick<DurableObjectStorage, "getAlarm" | "setAlarm">
const ddl = [
`CREATE TABLE IF NOT EXISTS cluster_messages (
@@ -39,30 +31,36 @@ const ddl = [
kind INTEGER NOT NULL,
payload TEXT NOT NULL,
sequence INTEGER,
acked INTEGER NOT NULL DEFAULT 0
acked INTEGER NOT NULL DEFAULT 0,
UNIQUE (request_id, kind),
UNIQUE (request_id, sequence)
)`,
`CREATE INDEX IF NOT EXISTS cluster_messages_deliver_at_idx
ON cluster_messages (processed, deliver_at)`,
`CREATE INDEX IF NOT EXISTS cluster_replies_request_id_idx
ON cluster_replies (request_id)`
ON cluster_messages (processed, deliver_at)`
]
/** @internal */
export const ensureEntityStorage = (sql: EntitySql): void => {
export const ensureEntityStorage = (sql: SqlStorage): void => {
for (const statement of ddl) {
sql.exec(statement)
}
}
/** @internal */
export const rearmAlarm = async (alarm: EntityAlarm, sql: EntitySql): Promise<void> => {
export const earliestDeliverAt = (sql: SqlStorage): number | undefined => {
const rows = sql.exec(
"SELECT min(deliver_at) AS deliver_at FROM cluster_messages WHERE processed = 0 AND deliver_at IS NOT NULL"
).toArray()
const deliverAt = rows[0]?.deliver_at
if (typeof deliverAt !== "number") return
const current = await alarm.getAlarm()
if (current === null || current > deliverAt) {
await alarm.setAlarm(deliverAt)
}
return typeof deliverAt === "number" ? deliverAt : undefined
}
/** @internal */
export const armAlarm = (alarm: EntityAlarm, deliverAt: number): Effect.Effect<void> =>
Effect.promise(() => alarm.getAlarm()).pipe(
Effect.flatMap((current) =>
current === null || current > deliverAt
? Effect.promise(() => alarm.setAlarm(deliverAt))
: Effect.void
)
)
@@ -66,16 +66,15 @@ describe("CloudflareCluster", () => {
)
}))
it.effect("fails on duplicate handler registration", () =>
it.effect("ignores duplicate handler registration", () =>
Effect.gen(function*() {
const { options } = makeOptions()
const handlers = User.toLayer({ Ping: () => Effect.succeed("pong") })
const exit = yield* Layer.build(
yield* Layer.build(
Layer.merge(handlers, User.toLayer({ Ping: () => Effect.succeed("pong2") })).pipe(
Layer.provide(CloudflareCluster.layer(options))
)
).pipe(Effect.exit)
assert.isTrue(Exit.isFailure(exit))
)
}))
it.effect("fails when registering an entity type not bound at Worker init", () =>
@@ -44,5 +44,9 @@ describe("ClusterName", () => {
it("rejects non-canonical length prefixes", () => {
assert.isUndefined(CloudflareCluster.decodeName("04:User42"))
})
it("rejects empty entity types", () => {
assert.isUndefined(CloudflareCluster.decodeName("0:whatever"))
})
})
})
@@ -1,5 +1,8 @@
import { ensureEntityStorage, rearmAlarm } from "@effect/platform-cloudflare/internal/entityStorage"
import type { SqlStorage } from "@cloudflare/workers-types"
import type { EntityAlarm } from "@effect/platform-cloudflare/internal/entityStorage"
import { armAlarm, earliestDeliverAt, ensureEntityStorage } from "@effect/platform-cloudflare/internal/entityStorage"
import { assert, describe, it } from "@effect/vitest"
import { Effect } from "effect"
class FakeSql {
readonly statements: Array<string> = []
@@ -12,6 +15,10 @@ class FakeSql {
: []
return { toArray: () => rows }
}
get sql(): SqlStorage {
return this as unknown as SqlStorage
}
}
class FakeAlarm {
@@ -26,13 +33,17 @@ class FakeAlarm {
this.current = scheduledTime
return Promise.resolve()
}
get alarm(): EntityAlarm {
return this as unknown as EntityAlarm
}
}
describe("EntityStorage", () => {
describe("ensureEntityStorage", () => {
it("creates the mailbox tables idempotently", () => {
const sql = new FakeSql()
ensureEntityStorage(sql)
ensureEntityStorage(sql.sql)
const first = [...sql.statements]
assert.isAtLeast(first.length, 1)
for (const statement of first) {
@@ -41,43 +52,45 @@ describe("EntityStorage", () => {
assert.isTrue(first.some((statement) => statement.includes("cluster_messages")))
assert.isTrue(first.some((statement) => statement.includes("cluster_replies")))
ensureEntityStorage(sql)
ensureEntityStorage(sql.sql)
assert.deepStrictEqual(sql.statements, [...first, ...first])
})
})
describe("rearmAlarm", () => {
it("does nothing without pending deliver_at rows", async () => {
const sql = new FakeSql()
const alarm = new FakeAlarm()
await rearmAlarm(alarm, sql)
assert.deepStrictEqual(alarm.setCalls, [])
describe("earliestDeliverAt", () => {
it("returns undefined without pending deliver_at rows", () => {
assert.isUndefined(earliestDeliverAt(new FakeSql().sql))
})
it("arms the alarm at the earliest deliver_at", async () => {
it("returns the earliest pending deliver_at", () => {
const sql = new FakeSql()
sql.earliestDeliverAt = 1000
const alarm = new FakeAlarm()
await rearmAlarm(alarm, sql)
assert.deepStrictEqual(alarm.setCalls, [1000])
})
it("keeps an already earlier alarm", async () => {
const sql = new FakeSql()
sql.earliestDeliverAt = 1000
const alarm = new FakeAlarm()
alarm.current = 500
await rearmAlarm(alarm, sql)
assert.deepStrictEqual(alarm.setCalls, [])
})
it("moves a later alarm forward", async () => {
const sql = new FakeSql()
sql.earliestDeliverAt = 1000
const alarm = new FakeAlarm()
alarm.current = 2000
await rearmAlarm(alarm, sql)
assert.deepStrictEqual(alarm.setCalls, [1000])
assert.strictEqual(earliestDeliverAt(sql.sql), 1000)
})
})
describe("armAlarm", () => {
it.effect("arms an unset alarm", () =>
Effect.gen(function*() {
const alarm = new FakeAlarm()
yield* armAlarm(alarm.alarm, 1000)
assert.deepStrictEqual(alarm.setCalls, [1000])
}))
it.effect("keeps an already earlier alarm", () =>
Effect.gen(function*() {
const alarm = new FakeAlarm()
alarm.current = 500
yield* armAlarm(alarm.alarm, 1000)
assert.deepStrictEqual(alarm.setCalls, [])
}))
it.effect("moves a later alarm forward", () =>
Effect.gen(function*() {
const alarm = new FakeAlarm()
alarm.current = 2000
yield* armAlarm(alarm.alarm, 1000)
assert.deepStrictEqual(alarm.setCalls, [1000])
}))
})
})
+2 -1
View File
@@ -456,10 +456,11 @@ importers:
version: 6.2.2
packages/platform/cloudflare:
devDependencies:
dependencies:
'@cloudflare/workers-types':
specifier: ^5.20260816.1
version: 5.20260816.1
devDependencies:
effect:
specifier: workspace:^
version: link:../../effect