mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-04 03:35:36 +08:00
feat(platform-cloudflare): recover entities after a Durable Object restart
An entity holding Entity.keepAlive, or running a persisted request, keeps an alarm armed one heartbeat ahead. Cloudflare never re-creates an evicted object by itself, so that alarm is what brings it back after a deploy, runtime update, or eviction: it rebuilds a kept-alive entity and restores its hold, and replays every unprocessed row instead of only due DeliverAt rows. - cluster_entity_state stores the keep-alive flag and the encoded name, so an alarm wake without id.name still resolves the entity. - The holder count stays in memory, per handler build, and resets when the build is invalidated. The flag is written in a forked fiber (inline would deadlock inside withTransaction), and a release writes 0 before the hold opens. - One nextAlarmAt covers due rows, unrun unprocessed rows, and the heartbeat; the alarm arms it before awaiting replayed handlers. - keepAliveHeartbeat on CloudflareCluster.layer and AlchemyCloudflareCluster.make, 30 seconds by default.
This commit is contained in:
@@ -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.
|
||||
@@ -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 |
|
||||
|
||||
@@ -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<ROut, E, RIn> {
|
||||
* handlers, and any services they need.
|
||||
*/
|
||||
readonly layer: Layer.Layer<ROut, E, RIn>
|
||||
/**
|
||||
* 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<any, any, an
|
||||
return yield* makeClusterHandle({
|
||||
entities: options.entities,
|
||||
layer: options.layer,
|
||||
env
|
||||
env,
|
||||
keepAliveHeartbeat: options.keepAliveHeartbeat
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@ import * as ShardId from "effect/cluster/ShardId"
|
||||
import { Sharding } from "effect/cluster/Sharding"
|
||||
import * as Context from "effect/Context"
|
||||
import * as Deferred from "effect/Deferred"
|
||||
import type * as Duration from "effect/Duration"
|
||||
import * as Duration from "effect/Duration"
|
||||
import * as Effect from "effect/Effect"
|
||||
import * as Layer from "effect/Layer"
|
||||
import * as Option from "effect/Option"
|
||||
@@ -104,6 +104,13 @@ export const decodeName: (name: string) => 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<string, { readonly stub: EntityStub; storageRequestId: string }>()
|
||||
|
||||
const unknownEntity = (entity: Entity.Entity<any, any>) =>
|
||||
@@ -437,7 +448,7 @@ const make = Effect.fnUntraced(function*(options: LayerOptions) {
|
||||
return yield* unknownEntity(entity)
|
||||
}
|
||||
const context = yield* Effect.context<never>()
|
||||
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(() =>
|
||||
|
||||
@@ -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<void> }>(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<boolean>
|
||||
}>(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,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<Entity.Entity<any, any>>
|
||||
readonly layer: Layer.Layer<never, any, any>
|
||||
readonly env: Record<string, unknown>
|
||||
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
|
||||
|
||||
@@ -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<void>
|
||||
/** The body of the self `hold()` RPC; resolves once the hold is released. */
|
||||
readonly await: Effect.Effect<void>
|
||||
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<void>): 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<void>) | undefined
|
||||
/** Upper bound of the retry delay after a failed hold RPC. */
|
||||
readonly retryCapMillis?: (() => number) | undefined
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const makeEntityKeepAlive = (
|
||||
startHold: () => Promise<void>,
|
||||
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<void> =>
|
||||
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
|
||||
}
|
||||
}
|
||||
|
||||
@@ -224,6 +224,9 @@ export const loadUnprocessed = (sql: SqlStorage, now?: number): Effect.Effect<Ar
|
||||
)
|
||||
|
||||
/** @internal */
|
||||
// The alarm replays every unprocessed row through `loadUnprocessed` now; this
|
||||
// stays only for `EntityMailbox.test.ts` until that test moves off it.
|
||||
// oxlint-disable-next-line effect/no-unused-internal
|
||||
export const loadDue = (sql: SqlStorage, now?: number): Effect.Effect<Array<StoredMessage>> =>
|
||||
Effect.sync(() =>
|
||||
sql.exec<StoredMessageRow>(
|
||||
|
||||
@@ -14,6 +14,8 @@ export interface EntityRegistration {
|
||||
readonly spanAttributes?: Record<string, string> | undefined
|
||||
} | undefined
|
||||
readonly context: Context.Context<never>
|
||||
/** Interval of the keep-alive heartbeat alarm, in milliseconds. */
|
||||
readonly keepAliveHeartbeat?: number | undefined
|
||||
}
|
||||
|
||||
const registry = makeRegistry<EntityRegistration>()
|
||||
|
||||
@@ -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<void>,
|
||||
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<void> = Effect.asVoid(getHandlers())
|
||||
|
||||
return { run, invalidate, warm, handlerSemaphore } as const
|
||||
})
|
||||
|
||||
type EntityRuntime = Effect.Success<ReturnType<typeof makeEntityRuntime>>
|
||||
@@ -276,6 +294,8 @@ export interface EntityManager {
|
||||
readonly reset: (requestId: string) => Effect.Effect<void>
|
||||
readonly alarm: Effect.Effect<void>
|
||||
readonly deliverReply: (requestId: string, reply: string) => Effect.Effect<boolean>
|
||||
/** Writes the keep-alive flag and moves the alarm to match it. */
|
||||
readonly saveKeepAlive: (wanted: boolean) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
const success = (requestId: string, replies: ReadonlyArray<string>): 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<ReadonlyArray<string>> =>
|
||||
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<void> =>
|
||||
Semaphore.withPermit(
|
||||
semaphore,
|
||||
Effect.andThen(
|
||||
write(saveKeepAlive(sql, wanted)),
|
||||
wanted ? armHeartbeat : rearm
|
||||
)
|
||||
)
|
||||
|
||||
const deliverReply = (requestId: string, reply: string): Effect.Effect<boolean> =>
|
||||
Effect.sync(() => replyRegistry.deliver(requestId, reply))
|
||||
|
||||
return { invoke, acknowledge, interrupt, reset, alarm, deliverReply }
|
||||
return { invoke, acknowledge, interrupt, reset, alarm, deliverReply, saveKeepAlive: saveKeepAliveState }
|
||||
}
|
||||
|
||||
@@ -12,6 +12,13 @@ import * as Result from "effect/Result"
|
||||
/** @internal */
|
||||
export type EntityAlarm = Pick<DurableObjectStorage, "getAlarm" | "setAlarm">
|
||||
|
||||
/**
|
||||
* 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<v
|
||||
: Effect.void
|
||||
)
|
||||
)
|
||||
|
||||
type EntityStateRow = {
|
||||
readonly keep_alive: number
|
||||
readonly name: string | null
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export interface EntityState {
|
||||
readonly keepAlive: boolean
|
||||
readonly name: string | undefined
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const loadEntityState = (sql: SqlStorage): EntityState => {
|
||||
const row = sql.exec<EntityStateRow>("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<void> =>
|
||||
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<UnprocessedRow>(
|
||||
"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
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user