mirror of
https://github.com/Effect-TS/effect.git
synced 2026-12-06 03:59:09 +08:00
feat(platform-cloudflare): pin entity resource holders
This commit is contained in:
@@ -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<KeepAliveLatch, Latch.Latch>()(
|
||||
"effect/cluster/Entity/KeepAliveLatch"
|
||||
) {}
|
||||
|
||||
/** @internal */
|
||||
export class KeepAliveHandler extends Context.Service<
|
||||
KeepAliveHandler,
|
||||
(enabled: boolean) => Effect.Effect<void>
|
||||
>()("effect/cluster/Entity/KeepAliveHandler") {}
|
||||
|
||||
@@ -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<unknown> {
|
||||
#serial: Promise<void> = Promise.resolve()
|
||||
readonly #sessions = new Map<string, ReplySession>()
|
||||
readonly #workerWaiters = new Map<string, Array<WorkerWaiter>>()
|
||||
readonly #keepAlive
|
||||
|
||||
constructor(ctx: DurableObjectState, env: unknown) {
|
||||
super(ctx, env)
|
||||
@@ -133,6 +135,17 @@ export class ClusterEntity extends DurableObject<unknown> {
|
||||
entityType: EntityType.make(name.type),
|
||||
entityId: EntityId.make(name.id)
|
||||
})
|
||||
this.#keepAlive = makeEntityKeepAlive(() => {
|
||||
const namespace = (this.#state.exports as Record<string, unknown>).ClusterEntity as
|
||||
| { readonly getByName: (name: string) => { readonly hold: () => Promise<void> } }
|
||||
| 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<unknown> {
|
||||
return operation
|
||||
}
|
||||
|
||||
/** @internal Keeps this object non-hibernateable while entity resources have holders. */
|
||||
hold(): Promise<void> {
|
||||
return Effect.runPromise(this.#keepAlive.await)
|
||||
}
|
||||
|
||||
/** @internal Same-Worker RPC transport used by `CloudflareCluster.layer`. */
|
||||
invoke(envelopeText: string, discard: boolean, delivery?: DeliveryOptions): Promise<InvokeResult> {
|
||||
const operation = this.#serial.then(() => Effect.runPromise(this.#invoke(envelopeText, discard, delivery)))
|
||||
@@ -338,7 +356,13 @@ export class ClusterEntity extends DurableObject<unknown> {
|
||||
#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
|
||||
|
||||
@@ -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<void>
|
||||
readonly await: Effect.Effect<void>
|
||||
readonly holderCount: () => number
|
||||
}
|
||||
|
||||
/** @internal */
|
||||
export const makeEntityKeepAlive = (startHold: () => Promise<void>): EntityKeepAlive => {
|
||||
const latch = Latch.makeUnsafe(true)
|
||||
let holders = 0
|
||||
let generation = 0
|
||||
|
||||
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()
|
||||
})
|
||||
return
|
||||
}
|
||||
if (holders === 0) return
|
||||
holders--
|
||||
if (holders !== 0) return
|
||||
generation++
|
||||
latch.openUnsafe()
|
||||
})
|
||||
|
||||
return {
|
||||
update,
|
||||
await: latch.await,
|
||||
holderCount: () => holders
|
||||
}
|
||||
}
|
||||
@@ -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<void>
|
||||
) {
|
||||
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 }
|
||||
})
|
||||
|
||||
@@ -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<void>()
|
||||
let keepAlive!: ReturnType<typeof makeEntityKeepAlive>
|
||||
keepAlive = makeEntityKeepAlive(() => {
|
||||
Deferred.doneUnsafe(started, Effect.void)
|
||||
return Effect.runPromise(keepAlive.await)
|
||||
})
|
||||
return { keepAlive, started }
|
||||
})
|
||||
|
||||
const provideKeepAlive = <A, E, R>(
|
||||
effect: Effect.Effect<A, E, R>,
|
||||
keepAlive: ReturnType<typeof makeEntityKeepAlive>
|
||||
) => Effect.provideService(effect, Entity.KeepAliveHandler, keepAlive.update) as Effect.Effect<A, E, never>
|
||||
|
||||
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))
|
||||
})
|
||||
Reference in New Issue
Block a user