diff --git a/.changeset/cloudflare-entity-recovery.md b/.changeset/cloudflare-entity-recovery.md new file mode 100644 index 0000000000..ecf360d225 --- /dev/null +++ b/.changeset/cloudflare-entity-recovery.md @@ -0,0 +1,5 @@ +--- +"@effect/platform-cloudflare": patch +--- + +Recover Cloudflare cluster entities after a Durable Object restart. An entity holding `Entity.keepAlive` keeps a heartbeat alarm armed, so a deploy, runtime update, or eviction rebuilds it and restores the hold until `Entity.keepAlive(false)`. The same alarm replays unprocessed persisted requests without waiting for a new message. The interval is the new `keepAliveHeartbeat` option on `CloudflareCluster.layer` and `AlchemyCloudflareCluster.make`, 30 seconds by default. diff --git a/packages/platform/cloudflare/README.md b/packages/platform/cloudflare/README.md index e5426e68cf..05623e0c0d 100644 --- a/packages/platform/cloudflare/README.md +++ b/packages/platform/cloudflare/README.md @@ -341,6 +341,45 @@ const program = Effect.gen(function*() { ) ``` +## Restarts and recovery + +A deploy, a runtime update, or an eviction kills the entity Durable Object. +Cloudflare does not re-create it by itself: the object stays cold until a +request, an alarm, or a WebSocket event arrives. To recover without outside +contact, the entity keeps an alarm in storage while it has something to come +back for: + +- While it holds `Entity.keepAlive`, the alarm re-arms every + `keepAliveHeartbeat` interval (30 seconds by default, set on + `CloudflareCluster.layer` or `AlchemyCloudflareCluster.make`). After a + restart the alarm rebuilds the entity, which runs its handler build, and + restores the hold. `Entity.keepAlive(false)` ends it. +- While a persisted request runs, the alarm stays armed one interval ahead. + After a restart it replays every unprocessed row, so an interrupted request + runs again without a new message. Replay is alarm-driven; any later request + to the entity replays the rows too. + +The interval is recovery latency, not a liveness check. At 30 seconds a +kept-alive entity costs about 2,880 alarm requests a day, which is small next +to the duration billing of the held object itself. + +Things to plan for: + +- After a deploy, kept-alive entities keep running the old code for about 5 + minutes, then die without warning. Schema changes must tolerate old code + still running against the same storage. +- Recovery after a deploy takes about those 5 minutes plus one interval. The + hold cannot see the deploy; only the heartbeat brings the entity back. +- The keep-alive flag is persisted, the holder count is not. Each handler + build counts its own holders, so two `EntityResource`s need two releases. + Classic cluster drops the hold when the first one releases. +- An `EntityResource` that is not acquired eagerly in the handler build + leaves the object pinned after a restart until a later + `Entity.keepAlive(false)`. Classic cluster behaves the same. +- A deploy that removes an entity type leaves its heartbeat behind. The alarm + fails, Cloudflare retries it 6 times, and the chain stops; the stored + keep-alive flag is never cleaned up. + ## v1 compatibility The status vocabulary is **maps 1:1**, **adapted**, and **out of scope**. @@ -360,7 +399,7 @@ The status vocabulary is **maps 1:1**, **adapted**, and **out of scope**. | `MailboxFull` / 4096 cap / 2 MB row rejection | maps 1:1 | Same limits; the SQLite row is the hard ceiling | | `defectRetryPolicy` then terminal defect | adapted | Rebuilds handlers in the wake; crash or deployment wipes memory and replays unprocessed rows | | `Entity.toLayer` `concurrency` | maps 1:1 | Same per-entity handler interleaving contract; storage entry stays serialized at any setting | -| `Entity.keepAlive` | adapted | Pins while holders exist; hibernation is allowed with no holders | +| `Entity.keepAlive` | maps 1:1 | Survives restarts through a heartbeat alarm; the holder count is per handler build, not persisted | | `CurrentRunnerAddress` | adapted | Synthetic address for identity and telemetry; no peer dialing | | `EntityResource.make` | adapted | External lifetimes such as a browser; close or idle TTL unpins | | `DurableObjectSqlClient` in entity handlers (`CloudflareCluster.toLayer`) | adapted | The entity Durable Object's own SQLite; `cluster_` tables reserved, 2 MB rows, transactions per object | diff --git a/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts b/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts index e69df6fe85..152a72ae80 100644 --- a/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts +++ b/packages/platform/cloudflare/src/AlchemyCloudflareCluster.ts @@ -43,6 +43,7 @@ import * as Cloudflare from "alchemy/Cloudflare" import type * as Entity from "effect/cluster/Entity" import type { Sharding } from "effect/cluster/Sharding" +import type * as Duration from "effect/Duration" import * as Effect from "effect/Effect" import type * as Layer from "effect/Layer" import type { PersistedQueueFactory } from "effect/persistence/PersistedQueue" @@ -104,6 +105,11 @@ export interface MakeOptions { * handlers, and any services they need. */ readonly layer: Layer.Layer + /** + * Interval of the entity keep-alive heartbeat alarm, as in + * `CloudflareCluster.LayerOptions`. Defaults to 30 seconds. + */ + readonly keepAliveHeartbeat?: Duration.Input | undefined } // One alchemy Durable Object class per cluster program. The outer effect @@ -146,7 +152,8 @@ const makeUnsafe = Effect.fnUntraced(function*(options: MakeOptions ClusterName | undefined = Internal.de * handler registration for an entity type outside this set fails at the * Worker, before any Durable Object is contacted. * + * `keepAliveHeartbeat` (default 30 seconds) is the interval of the alarm an + * entity Durable Object keeps armed while it holds `Entity.keepAlive` or runs + * a persisted request. Cloudflare never re-creates an evicted object on its + * own, so this alarm is what rebuilds a kept-alive entity and replays an + * interrupted request after a restart or deploy. It bounds recovery latency; + * it is not a liveness check. + * * @stability unstable * @category layers * @since 4.0.0 @@ -114,6 +121,7 @@ export interface LayerOptions { readonly workflowNamespace: DurableObjectNamespace readonly queueNamespace: DurableObjectNamespace readonly singletonNamespace: DurableObjectNamespace + readonly keepAliveHeartbeat?: Duration.Input | undefined } const notImplemented = (method: string) => @@ -175,6 +183,9 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) { entities.set(entity.type, entity) } const clock = yield* Clock + const keepAliveHeartbeat = options.keepAliveHeartbeat === undefined + ? undefined + : Duration.toMillis(options.keepAliveHeartbeat) const requestTargets = new Map() const unknownEntity = (entity: Entity.Entity) => @@ -437,7 +448,7 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) { return yield* unknownEntity(entity) } const context = yield* Effect.context() - const registration = { entity, build: build as any, options: buildOptions, context } + const registration = { entity, build: build as any, options: buildOptions, context, keepAliveHeartbeat } if (!registerEntityHandler(entity.type, registration)) return if (!declared) entities.set(entity.type, entity) yield* Effect.addFinalizer(() => diff --git a/packages/platform/cloudflare/src/CloudflareDurableObjectPrograms.ts b/packages/platform/cloudflare/src/CloudflareDurableObjectPrograms.ts index 05a995a9d5..cb4a59688e 100644 --- a/packages/platform/cloudflare/src/CloudflareDurableObjectPrograms.ts +++ b/packages/platform/cloudflare/src/CloudflareDurableObjectPrograms.ts @@ -21,8 +21,16 @@ import * as ShardId from "effect/cluster/ShardId" import * as Effect from "effect/Effect" import { decodeName, encodeName } from "./internal/clusterName.ts" import { makeEntityKeepAlive } from "./internal/entityKeepAlive.ts" +import { getEntityRegistration } from "./internal/entityRegistry.ts" import { makeEntityManager } from "./internal/entityRuntime.ts" -import { armAlarm, earliestDeliverAt, ensureEntityStorage } from "./internal/entityStorage.ts" +import { + armAlarm, + defaultKeepAliveHeartbeatMillis, + earliestDeliverAt, + ensureEntityStorage, + loadEntityState, + rememberEntityName +} from "./internal/entityStorage.ts" import { makeQueueRuntime } from "./internal/queueRuntime.ts" import { earliestLeaseExpiry } from "./internal/queueStorage.ts" import { getSingletonRegistration } from "./internal/singletonRegistry.ts" @@ -134,20 +142,30 @@ export type ClusterEntityProgram = { * Run the returned Effect once per Durable Object activation, after the * Worker application (the entity handler registrations) is initialized. It * ensures the mailbox tables and re-arms the single alarm from the earliest - * pending `deliver_at` before returning the handler object. The host class - * must be exported from the Worker entry as `ClusterEntity`; keep-alive and - * reply delivery resolve that export through `state.exports`. + * pending `deliver_at`, or the keep-alive heartbeat when that alarm is + * missing, before returning the handler object. The host class must be + * exported from the Worker entry as `ClusterEntity`; keep-alive and reply + * delivery resolve that export through `state.exports`. * * @stability unstable * @category constructors * @since 4.0.0 */ export const makeClusterEntityProgram = Effect.fnUntraced(function*(state: DurableObjectProgramState) { - const entityName = state.id.name ?? "" + const sql = state.storage.sql + ensureEntityStorage(sql) + const stored = loadEntityState(sql) + if (state.id.name !== undefined && decodeName(state.id.name) !== undefined) { + rememberEntityName(sql, state.id.name, stored) + } + // An alarm wake may carry no `id.name`; fall back to the name stored by an + // earlier activation, so heartbeat and `deliverAt` alarms still run. + const entityName = state.id.name ?? stored.name ?? "" const name = decodeName(entityName) if (name === undefined) { return yield* Effect.die(new Error("ClusterEntity requires a canonical entity Durable Object name")) } + const heartbeatMillis = () => getEntityRegistration(name.type)?.keepAliveHeartbeat ?? defaultKeepAliveHeartbeatMillis const keepAlive = makeEntityKeepAlive(() => { const namespace = exportedNamespace<{ readonly hold: () => Promise }>(state, "ClusterEntity") if (namespace === undefined) { @@ -156,6 +174,10 @@ export const makeClusterEntityProgram = Effect.fnUntraced(function*(state: Durab ) } return namespace.getByName(entityName).hold() + }, { + wanted: stored.keepAlive, + persist: (wanted) => manager.saveKeepAlive(wanted), + retryCapMillis: heartbeatMillis }) const manager = makeEntityManager({ storage: state.storage, @@ -172,12 +194,17 @@ export const makeClusterEntityProgram = Effect.fnUntraced(function*(state: Durab readonly deliverReply: (requestId: string, reply: string) => Promise }>(state, "ClusterEntity") }) - const sql = state.storage.sql - ensureEntityStorage(sql) const deliverAt = earliestDeliverAt(sql) if (deliverAt !== undefined) { yield* armAlarm(state.storage, deliverAt) } + if (stored.keepAlive) { + // Repairs the heartbeat chain after Cloudflare dropped an alarm whose + // retries all failed, or after a crash between the flag write and + // `setAlarm`. Arming at `now` on every activation would fire one wasted + // alarm per wake. + yield* armAlarm(state.storage, Date.now() + heartbeatMillis()) + } const program: ClusterEntityProgram = { alarm: () => manager.alarm, hold: () => keepAlive.await, diff --git a/packages/platform/cloudflare/src/CloudflareDurableObjects.ts b/packages/platform/cloudflare/src/CloudflareDurableObjects.ts index 055e4552f7..f9fca6093b 100644 --- a/packages/platform/cloudflare/src/CloudflareDurableObjects.ts +++ b/packages/platform/cloudflare/src/CloudflareDurableObjects.ts @@ -120,7 +120,8 @@ const blockOnInitialization = ( * **Details** * * The constructor stays cheap: it opens SQLite, ensures the mailbox tables, - * and re-arms the single alarm from the earliest pending `deliver_at`. User + * and re-arms the single alarm from the earliest pending `deliver_at`, or the + * keep-alive heartbeat when the entity holds `Entity.keepAlive`. User * handlers are never built in the constructor; requests and alarms wait for * the registered {@link setInitializer} callback, then handlers are built once * per wake. Each build gets a `DurableObjectSqlClient` on this object's SQLite diff --git a/packages/platform/cloudflare/src/internal/alchemyCluster.ts b/packages/platform/cloudflare/src/internal/alchemyCluster.ts index da9f0ed856..04c7ceecdd 100644 --- a/packages/platform/cloudflare/src/internal/alchemyCluster.ts +++ b/packages/platform/cloudflare/src/internal/alchemyCluster.ts @@ -8,6 +8,7 @@ */ import type * as Entity from "effect/cluster/Entity" import * as Context from "effect/Context" +import type * as Duration from "effect/Duration" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" import * as Scope from "effect/Scope" @@ -19,6 +20,7 @@ export interface ClusterHandleOptions { readonly entities: ReadonlyArray> readonly layer: Layer.Layer readonly env: Record + readonly keepAliveHeartbeat?: Duration.Input | undefined } /** @internal */ @@ -39,7 +41,8 @@ export const makeClusterHandle = Effect.fnUntraced(function*(options: ClusterHan entityNamespace, workflowNamespace, queueNamespace, - singletonNamespace + singletonNamespace, + keepAliveHeartbeat: options.keepAliveHeartbeat })) ), scope diff --git a/packages/platform/cloudflare/src/internal/entityKeepAlive.ts b/packages/platform/cloudflare/src/internal/entityKeepAlive.ts index 0a82f083db..27f3727ed5 100644 --- a/packages/platform/cloudflare/src/internal/entityKeepAlive.ts +++ b/packages/platform/cloudflare/src/internal/entityKeepAlive.ts @@ -1,44 +1,129 @@ -/** @internal */ +/** + * Keep-alive for one entity Durable Object, in three separate pieces of + * state: + * + * - `wanted` mirrors the persisted `keep_alive` flag that a restart restores. + * - `holding` tracks whether the self `hold()` RPC is in flight. + * - The holder count belongs to the current handler build only. Persisting it + * would break on restart: an `EntityResource` re-acquired by the rebuild + * adds a holder on top of the stored count, which then never returns to 0. + * + * @internal + */ import * as Effect from "effect/Effect" import * as Latch from "effect/Latch" /** @internal */ export interface EntityKeepAlive { + /** The `Entity.keepAlive` handler. */ readonly update: (enabled: boolean) => Effect.Effect + /** The body of the self `hold()` RPC; resolves once the hold is released. */ readonly await: Effect.Effect readonly holderCount: () => number + /** Forgets the holders of a closed handler build. The hold stays. */ + readonly resetHolders: () => void + /** Starts the self hold when keep-alive is wanted and none is in flight. */ + readonly restore: () => void } /** @internal */ -export const makeEntityKeepAlive = (startHold: () => Promise): EntityKeepAlive => { +export interface EntityKeepAliveOptions { + /** The persisted flag, read when the Durable Object starts. */ + readonly wanted?: boolean | undefined + /** + * Persists the flag. Runs in a forked fiber with the value current at that + * point, and the hold is released only after a `false` write completes. + */ + readonly persist?: ((wanted: boolean) => Effect.Effect) | undefined + /** Upper bound of the retry delay after a failed hold RPC. */ + readonly retryCapMillis?: (() => number) | undefined +} + +/** @internal */ +export const makeEntityKeepAlive = ( + startHold: () => Promise, + options?: EntityKeepAliveOptions +): EntityKeepAlive => { const latch = Latch.makeUnsafe(true) let holders = 0 + let wanted = options?.wanted ?? false + let holding = false let generation = 0 + const attempt = (current: number, failures: number): void => { + startHold().then( + () => { + if (current === generation) holding = false + }, + (error) => { + if (current !== generation) return + // A safeguard only: production probes never saw a rejected hold. + const cap = options?.retryCapMillis?.() ?? 30_000 + const delay = Math.random() * Math.min(cap, 100 * 2 ** failures) + void Effect.runFork(Effect.logWarning("Entity keep-alive hold failed, retrying", error)) + setTimeout(() => { + if (current === generation) attempt(current, failures + 1) + }, delay) + } + ) + } + + const restore = () => { + if (!wanted || holding) return + holding = true + latch.closeUnsafe() + attempt(++generation, 0) + } + + const release = () => { + if (!holding) return + holding = false + generation++ + latch.openUnsafe() + } + + const setWanted = (next: boolean) => { + if (wanted === next) return + wanted = next + if (next) restore() + const persist = options?.persist + if (persist === undefined) { + if (!next) release() + return + } + // Mailbox writes wait for an open user transaction, so writing inline + // would deadlock `Entity.keepAlive` called inside `withTransaction`. + void Effect.runFork( + Effect.suspend(() => persist(wanted)).pipe( + Effect.ensuring(Effect.sync(() => { + if (!wanted) release() + })) + ) + ) + } + const update = (enabled: boolean): Effect.Effect => Effect.sync(() => { if (enabled) { holders++ - if (holders !== 1) return - latch.closeUnsafe() - const currentGeneration = ++generation - void startHold().catch(() => { - if (currentGeneration !== generation) return - holders = 0 - latch.openUnsafe() - }) + setWanted(true) + // A hold that ended without a release is started again. + restore() return } - if (holders === 0) return - holders-- - if (holders !== 0) return - generation++ - latch.openUnsafe() + // With no holders in memory the flag may still be set: a fresh object + // after a restart has count 0 while its stored row says 1. + if (holders > 0) holders-- + if (holders === 0) setWanted(false) }) return { update, await: latch.await, - holderCount: () => holders + holderCount: () => holders, + resetHolders: () => { + holders = 0 + }, + restore } } diff --git a/packages/platform/cloudflare/src/internal/entityMailbox.ts b/packages/platform/cloudflare/src/internal/entityMailbox.ts index 11bc99953a..73e6b4da81 100644 --- a/packages/platform/cloudflare/src/internal/entityMailbox.ts +++ b/packages/platform/cloudflare/src/internal/entityMailbox.ts @@ -224,6 +224,9 @@ export const loadUnprocessed = (sql: SqlStorage, now?: number): Effect.Effect> => Effect.sync(() => sql.exec( diff --git a/packages/platform/cloudflare/src/internal/entityRegistry.ts b/packages/platform/cloudflare/src/internal/entityRegistry.ts index 1544ca81cc..51aae9930b 100644 --- a/packages/platform/cloudflare/src/internal/entityRegistry.ts +++ b/packages/platform/cloudflare/src/internal/entityRegistry.ts @@ -14,6 +14,8 @@ export interface EntityRegistration { readonly spanAttributes?: Record | undefined } | undefined readonly context: Context.Context + /** Interval of the keep-alive heartbeat alarm, in milliseconds. */ + readonly keepAliveHeartbeat?: number | undefined } const registry = makeRegistry() diff --git a/packages/platform/cloudflare/src/internal/entityRuntime.ts b/packages/platform/cloudflare/src/internal/entityRuntime.ts index 8c57895733..c5e77613b7 100644 --- a/packages/platform/cloudflare/src/internal/entityRuntime.ts +++ b/packages/platform/cloudflare/src/internal/entityRuntime.ts @@ -32,7 +32,6 @@ import { ackChunk, clearReplies, completeTell, - loadDue, loadMessage, loadNextReply, loadUnprocessed, @@ -44,7 +43,15 @@ import { import { type EntityRegistration, getEntityRegistration } from "./entityRegistry.ts" import { CurrentEntityName, CurrentReplyRegistry, type EntityReplyRegistry, makeReplyRegistry } from "./entityReply.ts" import { type EntitySql, makeEntitySql } from "./entitySql.ts" -import { armAlarm, earliestDeliverAt, withTransaction } from "./entityStorage.ts" +import { + armAlarm, + defaultKeepAliveHeartbeatMillis, + earliestDeliverAt, + loadEntityState, + nextAlarmAt, + saveKeepAlive, + withTransaction +} from "./entityStorage.ts" import { decodeReplyFor, decodeRequest, encodeReplyFor, peekEnvelopeTag } from "./entityWire.ts" interface CachedHandlers { @@ -59,7 +66,7 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( address: EntityAddress.EntityAddress, nextId: () => string, entityName = encodeName(address.entityType, address.entityId), - keepAlive?: (enabled: boolean) => Effect.Effect, + keepAlive?: EntityKeepAlive, replyRegistry?: EntityReplyRegistry, entitySql?: EntitySql ) { @@ -78,6 +85,10 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( if (cached === undefined) return const scope = cached.scope cached = undefined + // The closing build's holders are gone with it. `EntityResource` skips + // `keepAlive(false)` while its scope shuts down, so keeping the count + // would leak a holder into the rebuild. + keepAlive?.resetHolders() yield* Scope.close(scope, Exit.void).pipe( Effect.ensuring(Effect.sync(() => { ClusterMetrics.entities.modifyUnsafe(BigInt(-1), metricContext) @@ -94,7 +105,7 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( Context.add(Scope.Scope, scope) ) if (keepAlive !== undefined) { - context = Context.add(context, KeepAliveHandler, keepAlive) + context = Context.add(context, KeepAliveHandler, keepAlive.update) } if (replyRegistry !== undefined) { context = Context.add(context, CurrentReplyRegistry, replyRegistry) @@ -108,6 +119,9 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( Effect.tapCause((cause) => Scope.close(scope, Exit.failCause(cause))) ) ClusterMetrics.entities.modifyUnsafe(BigInt(1), metricContext) + // Any event that builds the entity restores a hold persisted before a + // restart. + keepAlive?.restore() return { handlers, context, scope } }) @@ -215,7 +229,11 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( } }) - return { run, invalidate, handlerSemaphore } as const + // Builds the handlers without running a request, for wakes that only need + // the entity alive. + const warm: Effect.Effect = Effect.asVoid(getHandlers()) + + return { run, invalidate, warm, handlerSemaphore } as const }) type EntityRuntime = Effect.Success> @@ -276,6 +294,8 @@ export interface EntityManager { readonly reset: (requestId: string) => Effect.Effect readonly alarm: Effect.Effect readonly deliverReply: (requestId: string, reply: string) => Effect.Effect + /** Writes the keep-alive flag and moves the alarm to match it. */ + readonly saveKeepAlive: (wanted: boolean) => Effect.Effect } const success = (requestId: string, replies: ReadonlyArray): EntityInvokeResult => ({ @@ -374,7 +394,7 @@ export const makeEntityManager = (options: EntityManagerOptions): EntityManager options.address, () => crypto.randomUUID(), options.entityName, - options.keepAlive.update, + options.keepAlive, replyRegistry, entitySql ), @@ -386,6 +406,27 @@ export const makeEntityManager = (options: EntityManagerOptions): EntityManager return deliverAt === undefined ? Effect.void : armAlarm(storage, deliverAt) }) + const heartbeatMillis = () => + getEntityRegistration(options.address.entityType)?.keepAliveHeartbeat ?? defaultKeepAliveHeartbeatMillis + + const isRunning = (requestId: string) => sessions.has(requestId) || pendingRuns.has(requestId) + + // Hot paths only ever move the alarm earlier. A heartbeat while a persisted + // row runs leaves an alarm behind for the restart that kills its handler. + const armHeartbeat = Effect.suspend(() => armAlarm(storage, Date.now() + heartbeatMillis())) + + // Recomputes the single alarm from the whole entity state. Callers hold the + // entry permit, so a concurrent keep-alive write cannot slip in between the + // read and a `deleteAlarm`. + const rearm = Effect.suspend(() => { + const next = nextAlarmAt(sql, { now: Date.now(), heartbeatMillis: heartbeatMillis(), isRunning }) + if (next !== undefined) return armAlarm(storage, next) + return Effect.flatMap( + Effect.promise(() => storage.getAlarm()), + (current) => current === null ? Effect.void : Effect.promise(() => storage.deleteAlarm()) + ) + }) + const takeReply = (requestId: string, session: Session): Effect.Effect> => Queue.take(session.queue).pipe( Effect.map((reply) => { @@ -493,6 +534,7 @@ export const makeEntityManager = (options: EntityManagerOptions): EntityManager ) ) options.waitUntil(Fiber.await(fiber)) + if (persisted) yield* armHeartbeat return Effect.as(Fiber.join(fiber), []) } @@ -549,6 +591,7 @@ export const makeEntityManager = (options: EntityManagerOptions): EntityManager ) ) options.waitUntil(Fiber.await(session.fiber)) + if (persisted) yield* armHeartbeat return takeReply(requestId, session) }) @@ -846,20 +889,46 @@ export const makeEntityManager = (options: EntityManagerOptions): EntityManager const alarm = Effect.suspend(() => { const registration = getEntityRegistration(options.address.entityType) if (registration === undefined) { + // A deploy that removed this entity type leaves its last alarm behind: + // it fails here, Cloudflare retries it 6 times, and the chain stops. The + // `cluster_entity_state` row is never cleaned up. return Effect.die(`No handlers registered for entity type: ${options.address.entityType}`) } - // The entry permit covers replay setup and alarm arming; awaiting the - // due handlers happens between the two so they can draw handler permits - // while later invokes still enter storage. + // The entry permit covers replay setup and alarm arming. The next alarm is + // armed before awaiting the replayed handlers: a handler that outlives the + // alarm wall-clock limit kills this invocation, and the chain must not + // depend on code after it. return Semaphore.withPermit( semaphore, - Effect.flatMap( - getRuntime(registration), - (entityRuntime) => Effect.flatMap(loadDue(sql), (rows) => replayRows(registration, entityRuntime, rows)) - ) + Effect.gen(function*() { + const rows = (yield* loadUnprocessed(sql)).filter((row) => !isRunning(row.requestId)) + const keepAlive = loadEntityState(sql).keepAlive + // A heartbeat left over after keep-alive was released must not + // rebuild the entity. + if (rows.length === 0 && !keepAlive) { + yield* rearm + return undefined + } + const entityRuntime = yield* getRuntime(registration) + const entries = yield* replayRows(registration, entityRuntime, rows) + yield* rearm + return { entityRuntime, entries, keepAlive } + }) ).pipe( - Effect.flatMap((entries) => Effect.asVoid(Fiber.awaitAll(entries.map((entry) => entry.fiber)))), - Effect.andThen(Semaphore.withPermit(semaphore, armEarliestAlarm)), + Effect.flatMap((woken) => { + if (woken === undefined) return Effect.void + // Building restores the hold; `restore` covers an entity that was + // already built when its hold ended. The hold is never awaited: it + // does not resolve while held. + const warm = woken.keepAlive + ? woken.entityRuntime.warm.pipe( + Effect.andThen(Effect.sync(() => options.keepAlive.restore())), + Effect.catchCause((cause) => Effect.logError("Entity keep-alive rebuild failed", cause)) + ) + : Effect.void + return Effect.andThen(warm, Fiber.awaitAll(woken.entries.map((entry) => entry.fiber))) + }), + Effect.ensuring(Semaphore.withPermit(semaphore, rearm)), Effect.withSpan("CloudflareCluster.alarm", { attributes: { entityType: registration.entity.type, @@ -870,8 +939,17 @@ export const makeEntityManager = (options: EntityManagerOptions): EntityManager ) }) + const saveKeepAliveState = (wanted: boolean): Effect.Effect => + Semaphore.withPermit( + semaphore, + Effect.andThen( + write(saveKeepAlive(sql, wanted)), + wanted ? armHeartbeat : rearm + ) + ) + const deliverReply = (requestId: string, reply: string): Effect.Effect => Effect.sync(() => replyRegistry.deliver(requestId, reply)) - return { invoke, acknowledge, interrupt, reset, alarm, deliverReply } + return { invoke, acknowledge, interrupt, reset, alarm, deliverReply, saveKeepAlive: saveKeepAliveState } } diff --git a/packages/platform/cloudflare/src/internal/entityStorage.ts b/packages/platform/cloudflare/src/internal/entityStorage.ts index 4b4b006d11..a84b269cf5 100644 --- a/packages/platform/cloudflare/src/internal/entityStorage.ts +++ b/packages/platform/cloudflare/src/internal/entityStorage.ts @@ -12,6 +12,13 @@ import * as Result from "effect/Result" /** @internal */ export type EntityAlarm = Pick +/** + * Default interval of the keep-alive heartbeat alarm. + * + * @internal + */ +export const defaultKeepAliveHeartbeatMillis = 30_000 + type DeliverAtRow = { readonly deliver_at: number | null } @@ -56,7 +63,14 @@ const ddl = [ `CREATE INDEX IF NOT EXISTS cluster_messages_deliver_at_idx ON cluster_messages (processed, deliver_at)`, `CREATE INDEX IF NOT EXISTS cluster_replies_unacked_idx - ON cluster_replies (request_id) WHERE kind = 'Chunk' AND acked = 0` + ON cluster_replies (request_id) WHERE kind = 'Chunk' AND acked = 0`, + // One row: whether the entity wants keep-alive across restarts, and the + // encoded name for wakes that arrive without one. + `CREATE TABLE IF NOT EXISTS cluster_entity_state ( + id INTEGER PRIMARY KEY CHECK (id = 0), + keep_alive INTEGER NOT NULL DEFAULT 0, + name TEXT + )` ] /** @internal */ @@ -83,3 +97,87 @@ export const armAlarm = (alarm: EntityAlarm, deliverAt: number): Effect.Effect { + const row = sql.exec("SELECT keep_alive, name FROM cluster_entity_state WHERE id = 0").toArray()[0] + return { keepAlive: row?.keep_alive === 1, name: row?.name ?? undefined } +} + +/** @internal */ +export const saveKeepAlive = (sql: SqlStorage, enabled: boolean): Effect.Effect => + Effect.sync(() => { + sql.exec( + `INSERT INTO cluster_entity_state (id, keep_alive) VALUES (0, ?) + ON CONFLICT (id) DO UPDATE SET keep_alive = excluded.keep_alive`, + enabled ? 1 : 0 + ) + }) + +/** + * Stores the encoded entity name when it differs from the stored one, so an + * activation that already recorded it costs a read and no write. + * + * @internal + */ +export const rememberEntityName = (sql: SqlStorage, name: string, stored: EntityState): void => { + if (stored.name === name) return + sql.exec( + `INSERT INTO cluster_entity_state (id, name) VALUES (0, ?) + ON CONFLICT (id) DO UPDATE SET name = excluded.name`, + name + ) +} + +type UnprocessedRow = { + readonly request_id: string + readonly deliver_at: number | null +} + +/** + * The single alarm time covering every reason to wake this entity: the + * earliest due row, `now` for an unprocessed row nothing is running, and a + * heartbeat while a row is in flight or keep-alive is wanted. An in-flight row + * counts as a heartbeat rather than `now`, so a long handler does not keep + * re-firing the alarm. + * + * @internal + */ +export const nextAlarmAt = ( + sql: SqlStorage, + options: { + readonly now: number + readonly heartbeatMillis: number + readonly isRunning: (requestId: string) => boolean + } +): number | undefined => { + let next: number | undefined + let heartbeat = loadEntityState(sql).keepAlive + const rows = sql.exec( + "SELECT request_id, deliver_at FROM cluster_messages WHERE processed = 0" + ).toArray() + for (const row of rows) { + if (options.isRunning(row.request_id)) { + heartbeat = true + continue + } + const at = row.deliver_at === null ? options.now : Math.max(row.deliver_at, options.now) + if (next === undefined || at < next) next = at + } + if (heartbeat) { + const at = options.now + options.heartbeatMillis + if (next === undefined || at < next) next = at + } + return next +}