import * as Context from "@effect/data/Context" import * as Duration from "@effect/data/Duration" import * as Equal from "@effect/data/Equal" import { dual, pipe } from "@effect/data/Function" import * as Hash from "@effect/data/Hash" import * as HashSet from "@effect/data/HashSet" import { pipeArguments } from "@effect/data/Pipeable" import type * as Clock from "@effect/io/Clock" import type * as Effect from "@effect/io/Effect" import type * as Exit from "@effect/io/Exit" import * as core from "@effect/io/internal/core" import * as effect from "@effect/io/internal/effect" import * as fiberRuntime from "@effect/io/internal/fiberRuntime" import * as queue from "@effect/io/internal/queue" import * as ref from "@effect/io/internal/ref" import type * as Pool from "@effect/io/Pool" import type * as Queue from "@effect/io/Queue" import type * as Ref from "@effect/io/Ref" import type * as Scope from "@effect/io/Scope" /** @internal */ const PoolSymbolKey = "@effect/io/Pool" /** @internal */ export const PoolTypeId: Pool.PoolTypeId = Symbol.for( PoolSymbolKey ) as Pool.PoolTypeId const poolVariance = { _E: (_: never) => _, _A: (_: never) => _ } interface PoolState { readonly size: number readonly free: number } interface Attempted { readonly result: Exit.Exit readonly finalizer: Effect.Effect } /** * A `Strategy` describes the protocol for how a pool whose excess items are * not being used should shrink down to the minimum pool size. */ interface Strategy { /** * Describes how the initial state of the strategy should be allocated. */ initial(): Effect.Effect /** * Describes how the state of the strategy should be updated when an item is * added to the pool or returned to the pool. */ track(state: S, attempted: Exit.Exit): Effect.Effect /** * Describes how excess items that are not being used should shrink down. */ run( state: S, getExcess: Effect.Effect, shrink: Effect.Effect ): Effect.Effect } /** * A strategy that does nothing to shrink excess items. This is useful when * the minimum size of the pool is equal to its maximum size and so there is * nothing to do. */ class NoneStrategy implements Strategy { initial(): Effect.Effect { return core.unit } track(): Effect.Effect { return core.unit } run(): Effect.Effect { return core.unit } } /** * A strategy that shrinks the pool down to its minimum size if items in the * pool have not been used for the specified duration. */ class TimeToLiveStrategy implements Strategy], never, never, never> { constructor(readonly timeToLive: Duration.Duration) {} initial(): Effect.Effect]> { return core.flatMap(effect.clock, (clock) => core.flatMap(clock.currentTimeMillis, (now) => core.map( ref.make(now), (ref) => [clock, ref] as const ))) } track(state: readonly [Clock.Clock, Ref.Ref]): Effect.Effect { return core.asUnit(core.flatMap( state[0].currentTimeMillis, (now) => ref.set(state[1], now) )) } run( state: readonly [Clock.Clock, Ref.Ref], getExcess: Effect.Effect, shrink: Effect.Effect ): Effect.Effect { return core.flatMap(getExcess, (excess) => excess <= 0 ? core.zipRight( state[0].sleep(this.timeToLive), this.run(state, getExcess, shrink) ) : pipe( core.zipWith( ref.get(state[1]), state[0].currentTimeMillis, (start, end) => end - start ), core.flatMap((duration) => { if (duration >= Duration.toMillis(this.timeToLive)) { return core.zipRight(shrink, this.run(state, getExcess, shrink)) } else { return core.zipRight(state[0].sleep(this.timeToLive), this.run(state, getExcess, shrink)) } }) )) } } class PoolImpl implements Pool.Pool { readonly [PoolTypeId] = poolVariance constructor( readonly creator: Effect.Effect, readonly min: number, readonly max: number, readonly isShuttingDown: Ref.Ref, readonly state: Ref.Ref, readonly items: Queue.Queue>, readonly invalidated: Ref.Ref>, readonly track: (exit: Exit.Exit) => Effect.Effect ) {} [Hash.symbol](): number { return pipe( Hash.hash(this.creator), Hash.combine(Hash.number(this.min)), Hash.combine(Hash.number(this.max)), Hash.combine(Hash.hash(this.isShuttingDown)), Hash.combine(Hash.hash(this.state)), Hash.combine(Hash.hash(this.items)), Hash.combine(Hash.hash(this.invalidated)), Hash.combine(Hash.hash(this.track)) ) } [Equal.symbol](that: unknown): boolean { return isPool(that) && Equal.equals(this.creator, (that as PoolImpl).creator) && this.min === (that as PoolImpl).min && this.max === (that as PoolImpl).max && Equal.equals(this.isShuttingDown, (that as PoolImpl).isShuttingDown) && Equal.equals(this.state, (that as PoolImpl).state) && Equal.equals(this.items, (that as PoolImpl).items) && Equal.equals(this.invalidated, (that as PoolImpl).invalidated) && Equal.equals(this.track, (that as PoolImpl).track) } pipe() { return pipeArguments(this, arguments) } get(): Effect.Effect { const acquire = (): Effect.Effect> => core.flatMap(ref.get(this.isShuttingDown), (down) => down ? core.interrupt : core.flatten(ref.modify(this.state, (state) => { if (state.free > 0 || state.size >= this.max) { return [ core.flatMap( queue.take(this.items), (attempted) => core.exitMatch(attempted.result, { onFailure: () => core.succeed(attempted), onSuccess: (item) => core.flatMap( ref.get(this.invalidated), (set) => { if (pipe(set, HashSet.has(item))) { return core.flatMap(finalizeInvalid(this, attempted), acquire) } return core.succeed(attempted) } ) }) ), { ...state, free: state.free - 1 } ] as const } if (state.size >= 0) { return [ core.flatMap(allocate(this), acquire), { size: state.size + 1, free: state.free + 1 } ] as const } return [core.interrupt, state] as const }))) const release = (attempted: Attempted): Effect.Effect => core.exitMatch(attempted.result, { onFailure: () => core.flatten(ref.modify(this.state, (state) => { if (state.size <= this.min) { return [allocate(this), { ...state, free: state.free + 1 }] as const } return [core.unit, { ...state, size: state.size - 1 }] as const })), onSuccess: (item) => core.flatMap(ref.get(this.invalidated), (set) => { if (pipe(set, HashSet.has(item))) { return finalizeInvalid(this, attempted) } return pipe( ref.update(this.state, (state) => ({ ...state, free: state.free + 1 })), core.zipRight(queue.offer(this.items, attempted)), core.zipRight(this.track(attempted.result)), core.zipRight(core.whenEffect(getAndShutdown(this), ref.get(this.isShuttingDown))) ) }) }) return pipe( fiberRuntime.acquireRelease(acquire(), release), fiberRuntime.withEarlyRelease, fiberRuntime.disconnect, core.flatMap(([release, attempted]) => pipe( effect.when(release, () => isFailure(attempted)), core.zipRight(toEffect(attempted)) ) ) ) } invalidate(item: A): Effect.Effect { return ref.update(this.invalidated, HashSet.add(item)) } } const allocate = (self: PoolImpl): Effect.Effect => core.uninterruptibleMask((restore) => core.flatMap(fiberRuntime.scopeMake(), (scope) => core.flatMap( core.exit(restore(fiberRuntime.scopeExtend(self.creator, scope))), (exit) => core.flatMap( core.succeed>({ result: exit as Exit.Exit, finalizer: core.scopeClose(scope, core.exitSucceed(void 0)) }), (attempted) => pipe( queue.offer(self.items, attempted), core.zipRight(self.track(attempted.result)), core.zipRight(core.whenEffect(getAndShutdown(self), ref.get(self.isShuttingDown))), core.as(attempted) ) ) )) ) /** * Returns the number of items in the pool in excess of the minimum size. */ const excess = (self: PoolImpl): Effect.Effect => core.map(ref.get(self.state), (state) => state.size - Math.min(self.min, state.free)) const finalizeInvalid = ( self: PoolImpl, attempted: Attempted ): Effect.Effect => pipe( forEach(attempted, (a) => ref.update(self.invalidated, HashSet.remove(a))), core.zipRight(attempted.finalizer), core.zipRight( core.flatten(ref.modify(self.state, (state) => { if (state.size <= self.min) { return [allocate(self), { ...state, free: state.free + 1 }] as const } return [core.unit, { ...state, size: state.size - 1 }] as const })) ) ) /** * Gets items from the pool and shuts them down as long as there are items * free, signalling shutdown of the pool if the pool is empty. */ const getAndShutdown = (self: PoolImpl): Effect.Effect => core.flatten(ref.modify(self.state, (state) => { if (state.free > 0) { return [ core.matchCauseEffect(queue.take(self.items), { onFailure: () => core.unit, onSuccess: (attempted) => pipe( forEach(attempted, (a) => ref.update(self.invalidated, HashSet.remove(a))), core.zipRight(attempted.finalizer), core.zipRight(ref.update(self.state, (state) => ({ ...state, size: state.size - 1 }))), core.flatMap(() => getAndShutdown(self)) ) }), { ...state, free: state.free - 1 } ] as const } if (state.size > 0) { return [core.unit, state] as const } return [queue.shutdown(self.items), { ...state, size: state.size - 1 }] as const })) /** * Begins pre-allocating pool entries based on minimum pool size. */ const initialize = (self: PoolImpl): Effect.Effect => fiberRuntime.replicateEffect( core.uninterruptibleMask((restore) => core.flatten(ref.modify(self.state, (state) => { if (state.size < self.min && state.size >= 0) { return [ core.flatMap(fiberRuntime.scopeMake(), (scope) => core.flatMap(core.exit(restore(fiberRuntime.scopeExtend(self.creator, scope))), (exit) => core.flatMap( core.succeed>({ result: exit as Exit.Exit, finalizer: core.scopeClose(scope, core.exitSucceed(void 0)) }), (attempted) => pipe( queue.offer(self.items, attempted), core.zipRight(self.track(attempted.result)), core.zipRight(core.whenEffect(getAndShutdown(self), ref.get(self.isShuttingDown))), core.as(attempted) ) ))), { size: state.size + 1, free: state.free + 1 } ] as const } return [core.unit, state] as const })) ), self.min, { discard: true } ) /** * Shrinks the pool down, but never to less than the minimum size. */ const shrink = (self: PoolImpl): Effect.Effect => core.uninterruptible( core.flatten(ref.modify(self.state, (state) => { if (state.size > self.min && state.free > 0) { return [ pipe( queue.take(self.items), core.flatMap((attempted) => pipe( forEach(attempted, (a) => ref.update(self.invalidated, HashSet.remove(a))), core.zipRight(attempted.finalizer), core.zipRight(ref.update(self.state, (state) => ({ ...state, size: state.size - 1 }))) ) ) ), { ...state, free: state.free - 1 } ] as const } return [core.unit, state] as const })) ) const shutdown = (self: PoolImpl): Effect.Effect => core.flatten(ref.modify(self.isShuttingDown, (down) => down ? [queue.awaitShutdown(self.items), true] as const : [core.zipRight(getAndShutdown(self), queue.awaitShutdown(self.items)), true])) const isFailure = (self: Attempted): boolean => core.exitIsFailure(self.result) const forEach = ( self: Attempted, f: (a: A) => Effect.Effect ): Effect.Effect => core.exitMatch(self.result, { onFailure: () => core.unit, onSuccess: f }) const toEffect = (self: Attempted): Effect.Effect => self.result /** * A more powerful variant of `make` that allows specifying a `Strategy` that * describes how a pool whose excess items are not being used will be shrunk * down to the minimum size. */ const makeWith = ( options: { readonly acquire: Effect.Effect readonly min: number readonly max: number readonly strategy: Strategy } ): Effect.Effect> => core.uninterruptibleMask((restore) => pipe( fiberRuntime.all([ core.context(), ref.make(false), ref.make({ size: 0, free: 0 }), queue.bounded>(options.max), ref.make(HashSet.empty()), options.strategy.initial() ]), core.flatMap(([context, down, state, items, inv, initial]) => { const pool = new PoolImpl( core.mapInputContext(options.acquire, (old) => Context.merge(old)(context)), options.min, options.max, down, state, items, inv, (exit) => options.strategy.track(initial, exit) ) return pipe( fiberRuntime.forkDaemon(restore(initialize(pool))), core.flatMap((fiber) => core.flatMap( fiberRuntime.forkDaemon(restore(options.strategy.run(initial, excess(pool), shrink(pool)))), (shrink) => fiberRuntime.addFinalizer(() => pipe( shutdown(pool), core.zipRight(core.interruptFiber(fiber)), core.zipRight(core.interruptFiber(shrink)) ) ) ) ), core.as>(pool) ) }) ) ) /** @internal */ export const isPool = (u: unknown): u is Pool.Pool => typeof u === "object" && u != null && PoolTypeId in u /** @internal */ export const make = ( options: { readonly acquire: Effect.Effect readonly size: number } ): Effect.Effect> => makeWith({ acquire: options.acquire, min: options.size, max: options.size, strategy: new NoneStrategy() }) /** @internal */ export const makeWithTTL = ( options: { readonly acquire: Effect.Effect readonly min: number readonly max: number readonly timeToLive: Duration.DurationInput } ): Effect.Effect> => makeWith({ acquire: options.acquire, min: options.min, max: options.max, strategy: new TimeToLiveStrategy(Duration.decode(options.timeToLive)) }) /** @internal */ export const get = (self: Pool.Pool): Effect.Effect => self.get() /** @internal */ export const invalidate = dual< (value: A) => (self: Pool.Pool) => Effect.Effect, (self: Pool.Pool, value: A) => Effect.Effect >(2, (self, value) => self.invalidate(value))