diff --git a/packages/effect/src/cluster/Entity.ts b/packages/effect/src/cluster/Entity.ts index 23704305d7..447c740262 100644 --- a/packages/effect/src/cluster/Entity.ts +++ b/packages/effect/src/cluster/Entity.ts @@ -739,6 +739,11 @@ export const keepAlive: ( never, Sharding | CurrentAddress > = Effect.fnUntraced(function*(enabled: boolean) { + const ohandler = yield* Effect.serviceOption(KeepAliveHandler) + if (ohandler._tag === "Some") { + yield* ohandler.value(enabled) + return + } const olatch = yield* Effect.serviceOption(KeepAliveLatch) if (olatch._tag === "None") return if (!enabled) { @@ -808,3 +813,9 @@ export const KeepAliveRpc = Rpc.make("Cluster/Entity/keepAlive") export class KeepAliveLatch extends Context.Service()( "effect/cluster/Entity/KeepAliveLatch" ) {} + +/** @internal */ +export class KeepAliveHandler extends Context.Service< + KeepAliveHandler, + (enabled: boolean) => Effect.Effect +>()("effect/cluster/Entity/KeepAliveHandler") {} diff --git a/packages/platform/cloudflare/src/CloudflareDurableObjects.ts b/packages/platform/cloudflare/src/CloudflareDurableObjects.ts index 4ef2f40513..6689e9f882 100644 --- a/packages/platform/cloudflare/src/CloudflareDurableObjects.ts +++ b/packages/platform/cloudflare/src/CloudflareDurableObjects.ts @@ -25,6 +25,7 @@ import * as Reply from "effect/unstable/cluster/Reply" import * as ShardId from "effect/unstable/cluster/ShardId" import type * as Rpc from "effect/unstable/rpc/Rpc" import { decodeName } from "./internal/clusterName.ts" +import { makeEntityKeepAlive } from "./internal/entityKeepAlive.ts" import { ackChunk, clearReplies, @@ -121,6 +122,7 @@ export class ClusterEntity extends DurableObject { #serial: Promise = Promise.resolve() readonly #sessions = new Map() readonly #workerWaiters = new Map>() + readonly #keepAlive constructor(ctx: DurableObjectState, env: unknown) { super(ctx, env) @@ -133,6 +135,17 @@ export class ClusterEntity extends DurableObject { entityType: EntityType.make(name.type), entityId: EntityId.make(name.id) }) + this.#keepAlive = makeEntityKeepAlive(() => { + const namespace = (this.#state.exports as Record).ClusterEntity as + | { readonly getByName: (name: string) => { readonly hold: () => Promise } } + | undefined + if (namespace === undefined) { + return Promise.reject( + new Error("CloudflareCluster: ClusterEntity export is unavailable for keep-alive") + ) + } + return namespace.getByName(this.#name).hold() + }) const sql = ctx.storage.sql ensureEntityStorage(sql) const deliverAt = earliestDeliverAt(sql) @@ -147,6 +160,11 @@ export class ClusterEntity extends DurableObject { return operation } + /** @internal Keeps this object non-hibernateable while entity resources have holders. */ + hold(): Promise { + return Effect.runPromise(this.#keepAlive.await) + } + /** @internal Same-Worker RPC transport used by `CloudflareCluster.layer`. */ invoke(envelopeText: string, discard: boolean, delivery?: DeliveryOptions): Promise { const operation = this.#serial.then(() => Effect.runPromise(this.#invoke(envelopeText, discard, delivery))) @@ -338,7 +356,13 @@ export class ClusterEntity extends DurableObject { #getRuntime(registration: EntityRegistration) { if (this.#runtime !== undefined) return Effect.succeed(this.#runtime) return Effect.map( - makeEntityRuntime(registration, this.#address, () => crypto.randomUUID(), this.#name), + makeEntityRuntime( + registration, + this.#address, + () => crypto.randomUUID(), + this.#name, + this.#keepAlive.update + ), (runtime) => { this.#runtime = runtime return runtime diff --git a/packages/platform/cloudflare/src/internal/entityKeepAlive.ts b/packages/platform/cloudflare/src/internal/entityKeepAlive.ts new file mode 100644 index 0000000000..02dbf9b0ee --- /dev/null +++ b/packages/platform/cloudflare/src/internal/entityKeepAlive.ts @@ -0,0 +1,43 @@ +/** @internal */ +import * as Effect from "effect/Effect" +import * as Latch from "effect/Latch" + +export interface EntityKeepAlive { + readonly update: (enabled: boolean) => Effect.Effect + readonly await: Effect.Effect + readonly holderCount: () => number +} + +/** @internal */ +export const makeEntityKeepAlive = (startHold: () => Promise): EntityKeepAlive => { + const latch = Latch.makeUnsafe(true) + let holders = 0 + let generation = 0 + + 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() + }) + return + } + if (holders === 0) return + holders-- + if (holders !== 0) return + generation++ + latch.openUnsafe() + }) + + return { + update, + await: latch.await, + holderCount: () => holders + } +} diff --git a/packages/platform/cloudflare/src/internal/entityRuntime.ts b/packages/platform/cloudflare/src/internal/entityRuntime.ts index b66d29f312..13aa5aa4dd 100644 --- a/packages/platform/cloudflare/src/internal/entityRuntime.ts +++ b/packages/platform/cloudflare/src/internal/entityRuntime.ts @@ -7,7 +7,7 @@ import * as Option from "effect/Option" import type * as Schedule from "effect/Schedule" import * as Scope from "effect/Scope" import * as Stream from "effect/Stream" -import { CurrentAddress, CurrentRunnerAddress, Request } from "effect/unstable/cluster/Entity" +import { CurrentAddress, CurrentRunnerAddress, KeepAliveHandler, Request } from "effect/unstable/cluster/Entity" import type * as EntityAddress from "effect/unstable/cluster/EntityAddress" import type * as Envelope from "effect/unstable/cluster/Envelope" import * as Reply from "effect/unstable/cluster/Reply" @@ -28,7 +28,8 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( registration: EntityRegistration, address: EntityAddress.EntityAddress, nextId: () => string, - entityName = `${String(address.entityType).length}:${address.entityType}${address.entityId}` + entityName = `${String(address.entityType).length}:${address.entityType}${address.entityId}`, + keepAlive?: (enabled: boolean) => Effect.Effect ) { let cached: CachedHandlers | undefined @@ -42,12 +43,15 @@ export const makeEntityRuntime = Effect.fnUntraced(function*( const getHandlers = Effect.fnUntraced(function*() { if (cached !== undefined) return cached const scope = yield* Scope.make() - const context = registration.context.pipe( + let context = registration.context.pipe( Context.add(CurrentAddress, address), Context.add(CurrentRunnerAddress, RunnerAddress.make(`${address.entityType}/${address.entityId}`, 0)), Context.add(CurrentEntityName, entityName), Context.add(Scope.Scope, scope) ) + if (keepAlive !== undefined) { + context = Context.add(context, KeepAliveHandler, keepAlive) + } const handlers = yield* Effect.provideContext(registration.build, context) return cached = { handlers, context, scope } }) diff --git a/packages/platform/cloudflare/test/EntityKeepAlive.test.ts b/packages/platform/cloudflare/test/EntityKeepAlive.test.ts new file mode 100644 index 0000000000..3c7d2996a3 --- /dev/null +++ b/packages/platform/cloudflare/test/EntityKeepAlive.test.ts @@ -0,0 +1,76 @@ +import { makeEntityKeepAlive } from "@effect/platform-cloudflare/internal/entityKeepAlive" +import { assert, describe, it } from "@effect/vitest" +import { Deferred, Effect, Fiber } from "effect" +import { TestClock } from "effect/testing" +import { Entity, EntityResource } from "effect/unstable/cluster" + +const makeFixture = Effect.gen(function*() { + const started = yield* Deferred.make() + let keepAlive!: ReturnType + keepAlive = makeEntityKeepAlive(() => { + Deferred.doneUnsafe(started, Effect.void) + return Effect.runPromise(keepAlive.await) + }) + return { keepAlive, started } +}) + +const provideKeepAlive = ( + effect: Effect.Effect, + keepAlive: ReturnType +) => Effect.provideService(effect, Entity.KeepAliveHandler, keepAlive.update) as Effect.Effect + +describe("EntityKeepAlive", () => { + it.effect("keeps the pin until the last holder releases", () => + Effect.gen(function*() { + const { keepAlive, started } = yield* makeFixture + yield* keepAlive.update(true) + yield* Deferred.await(started) + yield* keepAlive.update(true) + + assert.strictEqual(keepAlive.holderCount(), 2) + const waiter = yield* Effect.forkChild(keepAlive.await) + yield* keepAlive.update(false) + assert.strictEqual(keepAlive.holderCount(), 1) + + yield* keepAlive.update(false) + yield* Fiber.join(waiter) + assert.strictEqual(keepAlive.holderCount(), 0) + })) + + it.effect("releases an EntityResource pin after its idle TTL", () => + Effect.gen(function*() { + const { keepAlive, started } = yield* makeFixture + const resource = yield* provideKeepAlive( + EntityResource.make({ + acquire: Effect.succeed("resource"), + idleTimeToLive: "1 second" + }), + keepAlive + ) + + yield* Effect.scoped(resource.get) + yield* Deferred.await(started) + assert.strictEqual(keepAlive.holderCount(), 1) + + yield* TestClock.adjust("999 millis") + assert.strictEqual(keepAlive.holderCount(), 1) + yield* TestClock.adjust("1 millis") + assert.strictEqual(keepAlive.holderCount(), 0) + }).pipe(Effect.scoped)) + + it.effect("releases an EntityResource pin when it is closed", () => + Effect.gen(function*() { + const { keepAlive, started } = yield* makeFixture + const resource = yield* provideKeepAlive( + EntityResource.make({ acquire: Effect.succeed("resource") }), + keepAlive + ) + + yield* Effect.scoped(resource.get) + yield* Deferred.await(started) + assert.strictEqual(keepAlive.holderCount(), 1) + + yield* resource.close + assert.strictEqual(keepAlive.holderCount(), 0) + }).pipe(Effect.scoped)) +})