import * as Duration from "@effect/data/Duration" import * as Either from "@effect/data/Either" import * as Equal from "@effect/data/Equal" import type { Equivalence } from "@effect/data/Equivalence" import type { LazyArg } from "@effect/data/Function" import { dual, pipe } from "@effect/data/Function" import * as Hash from "@effect/data/Hash" import * as MutableHashMap from "@effect/data/MutableHashMap" import * as Option from "@effect/data/Option" import { pipeArguments } from "@effect/data/Pipeable" import * as Predicate from "@effect/data/Predicate" import type * as Cause from "@effect/io/Cause" import type * as Deferred from "@effect/io/Deferred" import type * as Effect from "@effect/io/Effect" import * as Exit from "@effect/io/Exit" import type * as Fiber from "@effect/io/Fiber" import * as FiberId from "@effect/io/FiberId" import type * as FiberRefsPatch from "@effect/io/FiberRefsPatch" import * as internalCause from "@effect/io/internal/cause" import * as core from "@effect/io/internal/core" import * as effect from "@effect/io/internal/effect" import * as executionStrategy from "@effect/io/internal/executionStrategy" import * as internalFiber from "@effect/io/internal/fiber" import * as fiberRuntime from "@effect/io/internal/fiberRuntime" import { globalScope } from "@effect/io/internal/fiberScope" import * as internalRef from "@effect/io/internal/ref" import * as _schedule from "@effect/io/internal/schedule" import * as supervisor from "@effect/io/internal/supervisor" import type * as Ref from "@effect/io/Ref" import type * as Schedule from "@effect/io/Schedule" import { currentScheduler } from "@effect/io/Scheduler" import type * as Scope from "@effect/io/Scope" import type * as Supervisor from "@effect/io/Supervisor" import type * as Synchronized from "@effect/io/SynchronizedRef" /** @internal */ class Semaphore { public waiters = new Array<() => void>() public taken = 0 constructor(readonly permits: number) {} get free() { return this.permits - this.taken } readonly take = (n: number): Effect.Effect => core.asyncEither((resume) => { if (this.free < n) { const observer = () => { if (this.free >= n) { const observerIndex = this.waiters.findIndex((cb) => cb === observer) if (observerIndex !== -1) { this.waiters.splice(observerIndex, 1) } this.taken += n resume(core.succeed(n)) } } this.waiters.push(observer) return Either.left(core.sync(() => { const observerIndex = this.waiters.findIndex((cb) => cb === observer) if (observerIndex !== -1) { this.waiters.splice(observerIndex, 1) } })) } this.taken += n return Either.right(core.succeed(n)) }) readonly release = (n: number): Effect.Effect => core.withFiberRuntime((fiber) => { this.taken -= n fiber.getFiberRef(currentScheduler).scheduleTask(() => { this.waiters.forEach((wake) => wake()) }, fiber.getFiberRef(core.currentSchedulingPriority)) return core.unit }) readonly withPermits = (n: number) => (self: Effect.Effect) => core.uninterruptibleMask((restore) => core.flatMap( restore(this.take(n)), (permits) => fiberRuntime.ensuring(restore(self), this.release(permits)) ) ) } /** @internal */ export const unsafeMakeSemaphore = (leases: number) => { return new Semaphore(leases) } /** @internal */ export const makeSemaphore = (permits: number) => core.sync(() => unsafeMakeSemaphore(permits)) /** @internal */ export const awaitAllChildren = (self: Effect.Effect): Effect.Effect => ensuringChildren(self, fiberRuntime.fiberAwaitAll) /** @internal */ export const cached = dual< ( timeToLive: Duration.DurationInput ) => (self: Effect.Effect) => Effect.Effect>, ( self: Effect.Effect, timeToLive: Duration.DurationInput ) => Effect.Effect> >(2, (self, timeToLive) => core.map(cachedInvalidate(self, timeToLive), (tuple) => tuple[0])) /** @internal */ export const cachedInvalidate = dual< ( timeToLive: Duration.DurationInput ) => ( self: Effect.Effect ) => Effect.Effect, Effect.Effect]>, ( self: Effect.Effect, timeToLive: Duration.DurationInput ) => Effect.Effect, Effect.Effect]> >( 2, (self: Effect.Effect, timeToLive: Duration.DurationInput) => { const duration = Duration.decode(timeToLive) return core.flatMap( core.context(), (env) => core.map( makeSynchronized]>>(Option.none()), (cache) => [ core.provideContext(getCachedValue(self, duration, cache), env), invalidateCache(cache) ] as [Effect.Effect, Effect.Effect] ) ) } ) /** @internal */ const computeCachedValue = ( self: Effect.Effect, timeToLive: Duration.DurationInput, start: number ): Effect.Effect]>> => { const timeToLiveMillis = Duration.toMillis(Duration.decode(timeToLive)) return pipe( core.deferredMake(), core.tap((deferred) => core.intoDeferred(self, deferred)), core.map((deferred) => Option.some([start + timeToLiveMillis, deferred] as const)) ) } /** @internal */ const getCachedValue = ( self: Effect.Effect, timeToLive: Duration.DurationInput, cache: Synchronized.SynchronizedRef]>> ): Effect.Effect => core.uninterruptibleMask((restore) => pipe( effect.clockWith((clock) => clock.currentTimeMillis), core.flatMap((time) => updateSomeAndGetEffectSynchronized(cache, (option) => { switch (option._tag) { case "None": { return Option.some(computeCachedValue(self, timeToLive, time)) } case "Some": { const [end] = option.value return end - time <= 0 ? Option.some(computeCachedValue(self, timeToLive, time)) : Option.none() } } }) ), core.flatMap((option) => Option.isNone(option) ? core.dieMessage( "BUG: Effect.cachedInvalidate - please report an issue at https://github.com/Effect-TS/io/issues" ) : restore(core.deferredAwait(option.value[1])) ) ) ) /** @internal */ const invalidateCache = ( cache: Synchronized.SynchronizedRef]>> ): Effect.Effect => internalRef.set(cache, Option.none()) /** @internal */ export const ensuringChild = dual< ( f: (fiber: Fiber.Fiber>) => Effect.Effect ) => ( self: Effect.Effect ) => Effect.Effect, ( self: Effect.Effect, f: (fiber: Fiber.Fiber>) => Effect.Effect ) => Effect.Effect >(2, (self, f) => ensuringChildren(self, (children) => f(fiberRuntime.fiberAll(children)))) /** @internal */ export const ensuringChildren = dual< ( children: (fibers: ReadonlyArray>) => Effect.Effect ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, children: (fibers: ReadonlyArray>) => Effect.Effect ) => Effect.Effect >(2, (self, children) => core.flatMap(supervisor.track, (supervisor) => pipe( supervised(self, supervisor), fiberRuntime.ensuring(core.flatMap(supervisor.value(), children)) ))) /** @internal */ // @ts-expect-error export const forkAll = dual< { (options?: { readonly discard?: false }): ( effects: Iterable> ) => Effect.Effect>> (options: { readonly discard: true }): ( effects: Iterable> ) => Effect.Effect }, { ( effects: Iterable>, options?: { readonly discard?: false } ): Effect.Effect>> ( effects: Iterable>, options: { readonly discard: true } ): Effect.Effect } >((args) => Predicate.isIterable(args[0]), ( effects, options ) => options?.discard ? core.forEachSequentialDiscard(effects, fiberRuntime.fork) : core.map(core.forEachSequential(effects, fiberRuntime.fork), fiberRuntime.fiberAll)) /** @internal */ export const forkIn = dual< (scope: Scope.Scope) => (self: Effect.Effect) => Effect.Effect>, (self: Effect.Effect, scope: Scope.Scope) => Effect.Effect> >( 2, (self, scope) => core.uninterruptibleMask((restore) => core.flatMap(scope.fork(executionStrategy.sequential), (child) => pipe( restore(self), core.onExit((exit) => child.close(exit)), fiberRuntime.forkDaemon, core.tap((fiber) => child.addFinalizer(() => core.fiberIdWith((fiberId) => Equal.equals(fiberId, fiber.id()) ? core.unit : core.asUnit(core.interruptFiber(fiber)) ) ) ) )) ) ) /** @internal */ export const forkScoped = ( self: Effect.Effect ): Effect.Effect> => fiberRuntime.scopeWith((scope) => forkIn(self, scope)) /** @internal */ export const fromFiber = (fiber: Fiber.Fiber): Effect.Effect => internalFiber.join(fiber) /** @internal */ export const fromFiberEffect = (fiber: Effect.Effect>): Effect.Effect => core.suspend(() => core.flatMap(fiber, internalFiber.join)) const memoKeySymbol = Symbol.for("@effect/io/Effect/memoizeFunction.key") class Key implements Equal.Equal { [memoKeySymbol] = memoKeySymbol constructor(readonly a: A, readonly eq?: Equivalence) {} [Equal.symbol](that: Equal.Equal) { if (typeof that === "object" && that !== null && memoKeySymbol in that) { if (this.eq) { return this.eq(this.a, (that as unknown as Key).a) } else { return Equal.equals(this.a, (that as unknown as Key).a) } } return false } [Hash.symbol]() { return this.eq ? 0 : Hash.hash(this.a) } } /** @internal */ export const memoizeFunction = ( f: (a: A) => Effect.Effect, eq?: Equivalence ): Effect.Effect Effect.Effect> => { return pipe( core.sync(() => MutableHashMap.empty, Deferred.Deferred>()), core.flatMap(makeSynchronized), core.map((ref) => (a: A) => pipe( ref.modifyEffect((map) => { const result = pipe(map, MutableHashMap.get(new Key(a, eq))) if (Option.isNone(result)) { return pipe( core.deferredMake(), core.tap((deferred) => pipe( effect.diffFiberRefs(f(a)), core.intoDeferred(deferred), fiberRuntime.fork ) ), core.map((deferred) => [deferred, pipe(map, MutableHashMap.set(new Key(a, eq), deferred))] as const) ) } return core.succeed([result.value, map] as const) }), core.flatMap(core.deferredAwait), core.flatMap(([patch, b]) => pipe(effect.patchFiberRefs(patch), core.as(b))) ) ) ) } /** @internal */ export const raceFirst = dual< ( that: Effect.Effect ) => ( self: Effect.Effect ) => Effect.Effect, ( self: Effect.Effect, that: Effect.Effect ) => Effect.Effect >(2, ( self: Effect.Effect, that: Effect.Effect ) => pipe( core.exit(self), fiberRuntime.race(core.exit(that)), (effect: Effect.Effect>) => core.flatten(effect) )) /** @internal */ export const scheduleForked = dual< ( schedule: Schedule.Schedule ) => ( self: Effect.Effect ) => Effect.Effect>, ( self: Effect.Effect, schedule: Schedule.Schedule ) => Effect.Effect> >(2, (self, schedule) => pipe(self, _schedule.schedule_Effect(schedule), forkScoped)) /** @internal */ export const supervised = dual< (supervisor: Supervisor.Supervisor) => (self: Effect.Effect) => Effect.Effect, (self: Effect.Effect, supervisor: Supervisor.Supervisor) => Effect.Effect >(2, (self, supervisor) => { const supervise = core.fiberRefLocallyWith(fiberRuntime.currentSupervisor, (s) => s.zip(supervisor)) return supervise(self) }) /** @internal */ export const timeout = dual< ( duration: Duration.DurationInput ) => (self: Effect.Effect) => Effect.Effect>, (self: Effect.Effect, duration: Duration.DurationInput) => Effect.Effect> >(2, (self, duration) => timeoutTo(self, { onTimeout: Option.none, onSuccess: Option.some, duration })) /** @internal */ export const timeoutFail = dual< ( options: { readonly onTimeout: LazyArg readonly duration: Duration.DurationInput } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly onTimeout: LazyArg readonly duration: Duration.DurationInput } ) => Effect.Effect >(2, (self, { duration, onTimeout }) => core.flatten(timeoutTo(self, { onTimeout: () => core.failSync(onTimeout), onSuccess: core.succeed, duration }))) /** @internal */ export const timeoutFailCause = dual< ( options: { readonly onTimeout: LazyArg> readonly duration: Duration.DurationInput } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly onTimeout: LazyArg> readonly duration: Duration.DurationInput } ) => Effect.Effect >(2, (self, { duration, onTimeout }) => core.flatten(timeoutTo(self, { onTimeout: () => core.failCauseSync(onTimeout), onSuccess: core.succeed, duration }))) /** @internal */ export const timeoutTo = dual< ( options: { readonly onTimeout: LazyArg readonly onSuccess: (a: A) => B readonly duration: Duration.DurationInput } ) => (self: Effect.Effect) => Effect.Effect, ( self: Effect.Effect, options: { readonly onTimeout: LazyArg readonly onSuccess: (a: A) => B readonly duration: Duration.DurationInput } ) => Effect.Effect >(2, (self, { duration, onSuccess, onTimeout }) => core.fiberIdWith((parentFiberId) => fiberRuntime.raceFibersWith( self, core.interruptible(effect.sleep(duration)), { onSelfWin: (winner, loser) => core.flatMap( winner.await(), (exit) => { if (exit._tag === "Success") { return core.flatMap( winner.inheritAll(), () => core.as( core.interruptAsFiber(loser, parentFiberId), onSuccess(exit.value) ) ) } else { return core.flatMap( core.interruptAsFiber(loser, parentFiberId), () => core.exitFailCause(exit.cause) ) } } ), onOtherWin: (winner, loser) => core.flatMap( winner.await(), (exit) => { if (exit._tag === "Success") { return core.flatMap( winner.inheritAll(), () => core.as( core.interruptAsFiber(loser, parentFiberId), onTimeout() ) ) } else { return core.flatMap( core.interruptAsFiber(loser, parentFiberId), () => core.exitFailCause(exit.cause) ) } } ), otherScope: globalScope } ) )) // circular with Synchronized /** @internal */ const SynchronizedSymbolKey = "@effect/io/Ref/SynchronizedRef" /** @internal */ export const SynchronizedTypeId: Synchronized.SynchronizedRefTypeId = Symbol.for( SynchronizedSymbolKey ) as Synchronized.SynchronizedRefTypeId /** @internal */ export const synchronizedVariance = { _A: (_: never) => _ } /** @internal */ class SynchronizedImpl implements Synchronized.SynchronizedRef { readonly [SynchronizedTypeId] = synchronizedVariance readonly [internalRef.RefTypeId] = internalRef.refVariance constructor( readonly ref: Ref.Ref, readonly withLock: (self: Effect.Effect) => Effect.Effect ) {} modify(f: (a: A) => readonly [B, A]): Effect.Effect { return this.modifyEffect((a) => core.succeed(f(a))) } modifyEffect(f: (a: A) => Effect.Effect): Effect.Effect { return this.withLock( pipe( core.flatMap(internalRef.get(this.ref), f), core.flatMap(([b, a]) => core.as(internalRef.set(this.ref, a), b)) ) ) } pipe() { return pipeArguments(this, arguments) } } /** @internal */ export const makeSynchronized = (value: A): Effect.Effect> => core.sync(() => unsafeMakeSynchronized(value)) /** @internal */ export const unsafeMakeSynchronized = (value: A): Synchronized.SynchronizedRef => { const ref = internalRef.unsafeMake(value) const sem = unsafeMakeSemaphore(1) return new SynchronizedImpl(ref, sem.withPermits(1)) } /** @internal */ export const updateSomeAndGetEffectSynchronized = dual< ( pf: (a: A) => Option.Option> ) => (self: Synchronized.SynchronizedRef) => Effect.Effect, ( self: Synchronized.SynchronizedRef, pf: (a: A) => Option.Option> ) => Effect.Effect >(2, (self, pf) => self.modifyEffect((value) => { const result = pf(value) switch (result._tag) { case "None": { return core.succeed([value, value] as const) } case "Some": { return core.map(result.value, (a) => [a, a] as const) } } })) // circular with Fiber /** @internal */ export const zipFiber = dual< (that: Fiber.Fiber) => (self: Fiber.Fiber) => Fiber.Fiber, (self: Fiber.Fiber, that: Fiber.Fiber) => Fiber.Fiber >(2, (self, that) => zipWithFiber(self, that, (a, b) => [a, b] as const)) /** @internal */ export const zipLeftFiber = dual< (that: Fiber.Fiber) => (self: Fiber.Fiber) => Fiber.Fiber, (self: Fiber.Fiber, that: Fiber.Fiber) => Fiber.Fiber >(2, (self, that) => zipWithFiber(self, that, (a, _) => a)) /** @internal */ export const zipRightFiber = dual< (that: Fiber.Fiber) => (self: Fiber.Fiber) => Fiber.Fiber, (self: Fiber.Fiber, that: Fiber.Fiber) => Fiber.Fiber >(2, (self, that) => zipWithFiber(self, that, (_, b) => b)) /** @internal */ export const zipWithFiber = dual< ( that: Fiber.Fiber, f: (a: A, b: B) => C ) => (self: Fiber.Fiber) => Fiber.Fiber, ( self: Fiber.Fiber, that: Fiber.Fiber, f: (a: A, b: B) => C ) => Fiber.Fiber >(3, (self, that, f) => ({ [internalFiber.FiberTypeId]: internalFiber.fiberVariance, id: () => pipe(self.id(), FiberId.getOrElse(that.id())), await: () => pipe( self.await(), core.flatten, fiberRuntime.zipWithOptions(core.flatten(that.await()), f, { concurrent: true }), core.exit ), children: () => self.children(), inheritAll: () => core.zipRight( that.inheritAll(), self.inheritAll() ), poll: () => core.zipWith( self.poll(), that.poll(), (optionA, optionB) => pipe( optionA, Option.flatMap((exitA) => pipe( optionB, Option.map((exitB) => Exit.zipWith(exitA, exitB, { onSuccess: f, onFailure: internalCause.parallel }) ) ) ) ) ), interruptAsFork: (id) => core.zipRight( self.interruptAsFork(id), that.interruptAsFork(id) ), pipe() { return pipeArguments(this, arguments) } }))